context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics.Contracts;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security;
namespace System.Globalization
{
public partial class CompareInfo
{
[SecurityCritical]
private readonly Interop.GlobalizationInterop.SafeSortHandle m_sortHandle;
private readonly bool m_isAsciiEqualityOrdinal;
[SecuritySafeCritical]
internal CompareInfo(CultureInfo culture)
{
m_name = culture.m_name;
m_sortName = culture.SortName;
m_sortHandle = Interop.GlobalizationInterop.GetSortHandle(System.Text.Encoding.UTF8.GetBytes(m_sortName));
m_isAsciiEqualityOrdinal = (m_sortName == "en-US" || m_sortName == "");
}
[SecurityCritical]
internal static unsafe int IndexOfOrdinal(string source, string value, int startIndex, int count, bool ignoreCase)
{
Contract.Assert(source != null);
Contract.Assert(value != null);
if (value.Length == 0)
{
return startIndex;
}
if (count < value.Length)
{
return -1;
}
if (ignoreCase)
{
fixed (char* pSource = source)
{
int index = Interop.GlobalizationInterop.IndexOfOrdinalIgnoreCase(value, value.Length, pSource + startIndex, count, findLast: false);
return index != -1 ?
startIndex + index :
-1;
}
}
int endIndex = startIndex + (count - value.Length);
for (int i = startIndex; i <= endIndex; i++)
{
int valueIndex, sourceIndex;
for (valueIndex = 0, sourceIndex = i;
valueIndex < value.Length && source[sourceIndex] == value[valueIndex];
valueIndex++, sourceIndex++) ;
if (valueIndex == value.Length)
{
return i;
}
}
return -1;
}
[SecurityCritical]
internal static unsafe int LastIndexOfOrdinal(string source, string value, int startIndex, int count, bool ignoreCase)
{
Contract.Assert(source != null);
Contract.Assert(value != null);
if (value.Length == 0)
{
return startIndex;
}
if (count < value.Length)
{
return -1;
}
// startIndex is the index into source where we start search backwards from.
// leftStartIndex is the index into source of the start of the string that is
// count characters away from startIndex.
int leftStartIndex = startIndex - count + 1;
if (ignoreCase)
{
fixed (char* pSource = source)
{
int lastIndex = Interop.GlobalizationInterop.IndexOfOrdinalIgnoreCase(value, value.Length, pSource + leftStartIndex, count, findLast: true);
return lastIndex != -1 ?
leftStartIndex + lastIndex :
-1;
}
}
for (int i = startIndex - value.Length + 1; i >= leftStartIndex; i--)
{
int valueIndex, sourceIndex;
for (valueIndex = 0, sourceIndex = i;
valueIndex < value.Length && source[sourceIndex] == value[valueIndex];
valueIndex++, sourceIndex++) ;
if (valueIndex == value.Length) {
return i;
}
}
return -1;
}
private int GetHashCodeOfStringCore(string source, CompareOptions options)
{
Contract.Assert(source != null);
Contract.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0);
return GetHashCodeOfStringCore(source, options, forceRandomizedHashing: false, additionalEntropy: 0);
}
[SecurityCritical]
private static unsafe int CompareStringOrdinalIgnoreCase(char* string1, int count1, char* string2, int count2)
{
return Interop.GlobalizationInterop.CompareStringOrdinalIgnoreCase(string1, count1, string2, count2);
}
[SecurityCritical]
private unsafe int CompareString(string string1, int offset1, int length1, string string2, int offset2, int length2, CompareOptions options)
{
Contract.Assert(string1 != null);
Contract.Assert(string2 != null);
Contract.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0);
fixed (char* pString1 = string1)
{
fixed (char* pString2 = string2)
{
return Interop.GlobalizationInterop.CompareString(m_sortHandle, pString1 + offset1, length1, pString2 + offset2, length2, options);
}
}
}
[SecurityCritical]
private unsafe int IndexOfCore(string source, string target, int startIndex, int count, CompareOptions options)
{
Contract.Assert(!string.IsNullOrEmpty(source));
Contract.Assert(target != null);
Contract.Assert((options & CompareOptions.OrdinalIgnoreCase) == 0);
if (target.Length == 0)
{
return startIndex;
}
if (options == CompareOptions.Ordinal)
{
return IndexOfOrdinal(source, target, startIndex, count, ignoreCase: false);
}
if (m_isAsciiEqualityOrdinal && CanUseAsciiOrdinalForOptions(options) && source.IsAscii() && target.IsAscii())
{
return IndexOf(source, target, startIndex, count, GetOrdinalCompareOptions(options));
}
fixed (char* pSource = source)
{
int index = Interop.GlobalizationInterop.IndexOf(m_sortHandle, target, target.Length, pSource + startIndex, count, options);
return index != -1 ? index + startIndex : -1;
}
}
[SecurityCritical]
private unsafe int LastIndexOfCore(string source, string target, int startIndex, int count, CompareOptions options)
{
Contract.Assert(!string.IsNullOrEmpty(source));
Contract.Assert(target != null);
Contract.Assert((options & CompareOptions.OrdinalIgnoreCase) == 0);
if (target.Length == 0)
{
return startIndex;
}
if (options == CompareOptions.Ordinal)
{
return LastIndexOfOrdinal(source, target, startIndex, count, ignoreCase: false);
}
if (m_isAsciiEqualityOrdinal && CanUseAsciiOrdinalForOptions(options) && source.IsAscii() && target.IsAscii())
{
return LastIndexOf(source, target, startIndex, count, GetOrdinalCompareOptions(options));
}
// startIndex is the index into source where we start search backwards from. leftStartIndex is the index into source
// of the start of the string that is count characters away from startIndex.
int leftStartIndex = (startIndex - count + 1);
fixed (char* pSource = source)
{
int lastIndex = Interop.GlobalizationInterop.LastIndexOf(m_sortHandle, target, target.Length, pSource + (startIndex - count + 1), count, options);
return lastIndex != -1 ? lastIndex + leftStartIndex : -1;
}
}
[SecuritySafeCritical]
private bool StartsWith(string source, string prefix, CompareOptions options)
{
Contract.Assert(!string.IsNullOrEmpty(source));
Contract.Assert(!string.IsNullOrEmpty(prefix));
Contract.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0);
if (m_isAsciiEqualityOrdinal && CanUseAsciiOrdinalForOptions(options) && source.IsAscii() && prefix.IsAscii())
{
return IsPrefix(source, prefix, GetOrdinalCompareOptions(options));
}
return Interop.GlobalizationInterop.StartsWith(m_sortHandle, prefix, prefix.Length, source, source.Length, options);
}
[SecuritySafeCritical]
private bool EndsWith(string source, string suffix, CompareOptions options)
{
Contract.Assert(!string.IsNullOrEmpty(source));
Contract.Assert(!string.IsNullOrEmpty(suffix));
Contract.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0);
if (m_isAsciiEqualityOrdinal && CanUseAsciiOrdinalForOptions(options) && source.IsAscii() && suffix.IsAscii())
{
return IsSuffix(source, suffix, GetOrdinalCompareOptions(options));
}
return Interop.GlobalizationInterop.EndsWith(m_sortHandle, suffix, suffix.Length, source, source.Length, options);
}
// -----------------------------
// ---- PAL layer ends here ----
// -----------------------------
[SecuritySafeCritical]
internal unsafe int GetHashCodeOfStringCore(string source, CompareOptions options, bool forceRandomizedHashing, long additionalEntropy)
{
Contract.Assert(source != null);
Contract.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0);
if (source.Length == 0)
{
return 0;
}
int sortKeyLength = Interop.GlobalizationInterop.GetSortKey(m_sortHandle, source, source.Length, null, 0, options);
// As an optimization, for small sort keys we allocate the buffer on the stack.
if (sortKeyLength <= 256)
{
byte* pSortKey = stackalloc byte[sortKeyLength];
Interop.GlobalizationInterop.GetSortKey(m_sortHandle, source, source.Length, pSortKey, sortKeyLength, options);
return InternalHashSortKey(pSortKey, sortKeyLength, false, additionalEntropy);
}
byte[] sortKey = new byte[sortKeyLength];
fixed(byte* pSortKey = sortKey)
{
Interop.GlobalizationInterop.GetSortKey(m_sortHandle, source, source.Length, pSortKey, sortKeyLength, options);
return InternalHashSortKey(pSortKey, sortKeyLength, false, additionalEntropy);
}
}
[SecurityCritical]
[DllImport(JitHelpers.QCall)]
[SuppressUnmanagedCodeSecurity]
private static unsafe extern int InternalHashSortKey(byte* sortKey, int sortKeyLength, [MarshalAs(UnmanagedType.Bool)] bool forceRandomizedHashing, long additionalEntropy);
private static CompareOptions GetOrdinalCompareOptions(CompareOptions options)
{
if ((options & CompareOptions.IgnoreCase) == CompareOptions.IgnoreCase)
{
return CompareOptions.OrdinalIgnoreCase;
}
else
{
return CompareOptions.Ordinal;
}
}
private static bool CanUseAsciiOrdinalForOptions(CompareOptions options)
{
// Unlike the other Ignore options, IgnoreSymbols impacts ASCII characters (e.g. ').
return (options & CompareOptions.IgnoreSymbols) == 0;
}
}
}
| |
using Lucene.Net.Diagnostics;
namespace Lucene.Net.Util.Automaton
{
/*
* 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.
*/
// The following code was generated with the moman/finenight pkg
// this package is available under the MIT License, see NOTICE.txt
// for more details.
using ParametricDescription = Lucene.Net.Util.Automaton.LevenshteinAutomata.ParametricDescription;
/// <summary>
/// Parametric description for generating a Levenshtein automaton of degree 2 </summary>
internal class Lev2ParametricDescription : ParametricDescription
{
internal override int Transition(int absState, int position, int vector)
{
// null absState should never be passed in
if (Debugging.AssertsEnabled) Debugging.Assert(absState != -1);
// decode absState -> state, offset
int state = absState / (m_w + 1);
int offset = absState % (m_w + 1);
if (Debugging.AssertsEnabled) Debugging.Assert(offset >= 0);
if (position == m_w)
{
if (state < 3)
{
int loc = vector * 3 + state;
offset += Unpack(offsetIncrs0, loc, 1);
state = Unpack(toStates0, loc, 2) - 1;
}
}
else if (position == m_w - 1)
{
if (state < 5)
{
int loc = vector * 5 + state;
offset += Unpack(offsetIncrs1, loc, 1);
state = Unpack(toStates1, loc, 3) - 1;
}
}
else if (position == m_w - 2)
{
if (state < 11)
{
int loc = vector * 11 + state;
offset += Unpack(offsetIncrs2, loc, 2);
state = Unpack(toStates2, loc, 4) - 1;
}
}
else if (position == m_w - 3)
{
if (state < 21)
{
int loc = vector * 21 + state;
offset += Unpack(offsetIncrs3, loc, 2);
state = Unpack(toStates3, loc, 5) - 1;
}
}
else if (position == m_w - 4)
{
if (state < 30)
{
int loc = vector * 30 + state;
offset += Unpack(offsetIncrs4, loc, 3);
state = Unpack(toStates4, loc, 5) - 1;
}
}
else
{
if (state < 30)
{
int loc = vector * 30 + state;
offset += Unpack(offsetIncrs5, loc, 3);
state = Unpack(toStates5, loc, 5) - 1;
}
}
if (state == -1)
{
// null state
return -1;
}
else
{
// translate back to abs
return state * (m_w + 1) + offset;
}
}
// 1 vectors; 3 states per vector; array length = 3
private static readonly long[] toStates0 = new long[] { 0x23L }; //2 bits per value
private static readonly long[] offsetIncrs0 = new long[] { 0x0L }; //1 bits per value
// 2 vectors; 5 states per vector; array length = 10
private static readonly long[] toStates1 = new long[] { 0x13688b44L }; //3 bits per value
private static readonly long[] offsetIncrs1 = new long[] { 0x3e0L }; //1 bits per value
// 4 vectors; 11 states per vector; array length = 44
private static readonly long[] toStates2 = new long[] {
0x26a09a0a0520a504L, 0x2323523321a260a2L, 0x354235543213L
}; //4 bits per value
private static readonly long[] offsetIncrs2 = new long[] {
0x5555520280000800L, 0x555555L
}; //2 bits per value
// 8 vectors; 21 states per vector; array length = 168
private static readonly long[] toStates3 = new long[] {
0x380e014a051404L, 0xe28245009451140L, unchecked((long)0x8a26880098a6268cL), 0x180a288ca0246213L,
0x494053284a1080e1L, 0x510265a89c311940L, 0x4218c41188a6509cL, 0x6340c4211c4710dL,
unchecked((long)0xa168398471882a12L), 0x104c841c683a0425L, 0x3294472904351483L, unchecked((long)0xe6290620a84a20d0L),
0x1441a0ea2896a4a0L, 0x32L
}; //5 bits per value
private static readonly long[] offsetIncrs3 = new long[] {
0x33300230c0000800L, 0x220ca080a00fc330L, 0x555555f832823380L, 0x5555555555555555L,
0x5555555555555555L, 0x5555L
}; //2 bits per value
// 16 vectors; 30 states per vector; array length = 480
private static readonly long[] toStates4 = new long[] {
0x380e014a051404L, 0xaa015452940L, 0x55014501000000L, 0x1843ddc771085c07L,
0x7141200040108405L, 0x52b44004c5313460L, 0x401080200063115cL, unchecked((long)0x85314c4d181c5048L),
0x1440190a3e5c7828L, 0x28a232809100a21L, unchecked((long)0xa028ca2a84203846L), unchecked((long)0xca0240010800108aL),
unchecked((long)0xc7b4205c1580a508L), 0x1021090251846b6L, 0x4cb513862328090L, 0x210863128ca2b8a2L,
0x4e188ca024402940L, 0xa6b6c7c520532d4L, unchecked((long)0x8c41101451150219L), unchecked((long)0xa0c4211c4710d421L),
0x2108421094e15063L, unchecked((long)0x8f13c43708631044L), 0x18274d908c611631L, 0x1cc238c411098263L,
0x450e3a1d0212d0b4L, 0x31050242048108c6L, 0xfa318b42d07308eL, unchecked((long)0xa8865182356907c6L),
0x1ca410d4520c4140L, 0x2954e13883a0ca51L, 0x3714831044229442L, unchecked((long)0x93946116b58f2c84L),
unchecked((long)0xc41109a5631a574dL), 0x1d4512d4941cc520L, 0x52848294c643883aL, unchecked((long)0xb525073148310502L),
unchecked((long)0xa5356939460f7358L), 0x409ca651L
}; //5 bits per value
private static readonly long[] offsetIncrs4 = new long[] {
0x20c0600000010000L, 0x2000040000000001L, 0x209204a40209L, 0x301b6c0618018618L,
0x207206186000186cL, 0x1200061b8e06dc0L, 0x480492080612010L, unchecked((long)0xa20204a040048000L),
0x1061a0000129124L, 0x1848349b680612L, unchecked((long)0xd26da0204a041868L), 0x2492492492496128L,
unchecked((long)0x9249249249249249L), 0x4924924924924924L, 0x2492492492492492L, unchecked((long)0x9249249249249249L),
0x4924924924924924L, 0x2492492492492492L, unchecked((long)0x9249249249249249L), 0x4924924924924924L,
0x2492492492492492L, unchecked((long)0x9249249249249249L), 0x24924924L
}; //3 bits per value
// 32 vectors; 30 states per vector; array length = 960
private static readonly long[] toStates5 = new long[] {
0x380e014a051404L, 0xaa015452940L, unchecked((long)0x8052814501000000L), unchecked((long)0xb80a515450000e03L),
0x5140410842108426L, 0x71dc421701c01540L, 0x100421014610f7L, unchecked((long)0x85c0700550145010L),
unchecked((long)0x94a271843ddc7710L), 0x1346071412108a22L, 0x3115c52b44004c53L, unchecked((long)0xc504840108020006L),
0x54d1001314c4d181L, 0x9081204239c4a71L, 0x14c5313460714124L, 0x51006428f971e0a2L,
0x4d181c5048402884L, 0xa3e5c782885314cL, 0x2809409482a8a239L, 0x2a84203846028a23L,
0x10800108aa028caL, 0xe1180a288ca0240L, unchecked((long)0x98c6b80e3294a108L), 0x2942328091098c10L,
0x11adb1ed08170560L, unchecked((long)0xa024004084240946L), 0x7b4205c1580a508cL, unchecked((long)0xa8c2968c71846b6cL),
0x4cb5138623280910L, 0x10863128ca2b8a20L, unchecked((long)0xe188ca0244029402L), 0x4e3294e288132d44L,
unchecked((long)0x809409ad1218c39cL), unchecked((long)0xf14814cb51386232L), 0x514454086429adb1L, 0x32d44e188ca02440L,
unchecked((long)0x8c390a6b6c7c5205L), unchecked((long)0xd4218c41409cd2aaL), 0x5063a0c4211c4710L, 0x10442108421094e1L,
0x31084711c4350863L, unchecked((long)0xbdef7bddf05918f2L), unchecked((long)0xc4f10dc218c41ef7L), 0x9d3642318458c63L,
0x70863104426098c6L, 0x8c6116318f13c43L, 0x41ef75dd6b5de4d9L, unchecked((long)0xd0212d0b41cc238cL),
0x2048108c6450e3a1L, 0x42d07308e3105024L, unchecked((long)0xdb591938f274084bL), unchecked((long)0xc238c41f77deefbbL),
0x1f183e8c62d0b41cL, 0x502a2194608d5a4L, unchecked((long)0xa318b42d07308e31L), unchecked((long)0xed675db56907c60fL),
unchecked((long)0xa410d4520c41f773L), 0x54e13883a0ca511cL, 0x1483104422944229L, 0x20f2329447290435L,
0x1ef6f7ef6f7df05cL, unchecked((long)0xad63cb210dc520c4L), 0x58c695d364e51845L, unchecked((long)0xc843714831044269L),
unchecked((long)0xe4d93946116b58f2L), 0x520c41ef717d6b17L, unchecked((long)0x83a1d4512d4941ccL), 0x50252848294c6438L,
0x144b525073148310L, unchecked((long)0xefaf7b591c20f275L), unchecked((long)0x941cc520c41f777bL), unchecked((long)0xd5a4e5183dcd62d4L),
0x4831050272994694L, 0x460f7358b5250731L, unchecked((long)0xf779bd6717b56939L)
}; //5 bits per value
private static readonly long[] offsetIncrs5 = new long[] {
0x20c0600000010000L, 0x40000000001L, 0xb6db6d4830180L, 0x4812900824800010L,
0x2092000040000082L, 0x618000b659254a40L, unchecked((long)0x86c301b6c0618018L), unchecked((long)0xdb01860061860001L),
unchecked((long)0x81861800075baed6L), 0x186e381b70081cL, unchecked((long)0xe56dc02072061860L), 0x61201001200075b8L,
0x480000480492080L, 0x52b5248201848040L, unchecked((long)0x880812810012000bL), 0x4004800004a4492L,
0xb529124a20204aL, 0x49b68061201061a0L, unchecked((long)0x8480418680018483L), 0x1a000752ad26da01L,
0x4a349b6808128106L, unchecked((long)0xa0204a0418680018L), 0x492492497528d26dL, 0x2492492492492492L,
unchecked((long)0x9249249249249249L), 0x4924924924924924L, 0x2492492492492492L, unchecked((long)0x9249249249249249L),
0x4924924924924924L, 0x2492492492492492L, unchecked((long)0x9249249249249249L), 0x4924924924924924L,
0x2492492492492492L, unchecked((long)0x9249249249249249L), 0x4924924924924924L, 0x2492492492492492L,
unchecked((long)0x9249249249249249L), 0x4924924924924924L, 0x2492492492492492L, unchecked((long)0x9249249249249249L),
0x4924924924924924L, 0x2492492492492492L, unchecked((long)0x9249249249249249L), 0x4924924924924924L,
0x2492492492492492L
}; //3 bits per value
// state map
// 0 -> [(0, 0)]
// 1 -> [(0, 2)]
// 2 -> [(0, 1)]
// 3 -> [(0, 1), (1, 1)]
// 4 -> [(0, 2), (1, 2)]
// 5 -> [(0, 2), (2, 1)]
// 6 -> [(0, 1), (2, 2)]
// 7 -> [(0, 2), (2, 2)]
// 8 -> [(0, 1), (1, 1), (2, 1)]
// 9 -> [(0, 2), (1, 2), (2, 2)]
// 10 -> [(0, 1), (2, 1)]
// 11 -> [(0, 2), (3, 2)]
// 12 -> [(0, 2), (1, 2), (3, 2)]
// 13 -> [(0, 2), (1, 2), (2, 2), (3, 2)]
// 14 -> [(0, 1), (2, 2), (3, 2)]
// 15 -> [(0, 2), (3, 1)]
// 16 -> [(0, 1), (3, 2)]
// 17 -> [(0, 1), (1, 1), (3, 2)]
// 18 -> [(0, 2), (1, 2), (3, 1)]
// 19 -> [(0, 2), (2, 2), (3, 2)]
// 20 -> [(0, 2), (2, 1), (3, 1)]
// 21 -> [(0, 2), (2, 1), (4, 2)]
// 22 -> [(0, 2), (1, 2), (4, 2)]
// 23 -> [(0, 2), (1, 2), (3, 2), (4, 2)]
// 24 -> [(0, 2), (2, 2), (3, 2), (4, 2)]
// 25 -> [(0, 2), (3, 2), (4, 2)]
// 26 -> [(0, 2), (1, 2), (2, 2), (4, 2)]
// 27 -> [(0, 2), (1, 2), (2, 2), (3, 2), (4, 2)]
// 28 -> [(0, 2), (4, 2)]
// 29 -> [(0, 2), (2, 2), (4, 2)]
public Lev2ParametricDescription(int w)
: base(w, 2, new int[] { 0, 2, 1, 0, 1, -1, 0, 0, -1, 0, -1, -1, -1, -1, -1, -2, -1, -1, -2, -1, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2 })
{
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Lime.Protocol;
using Lime.Protocol.Server;
using Newtonsoft.Json;
using Takenet.MessagingHub.Client.Connection;
using Takenet.MessagingHub.Client.Extensions;
using Takenet.MessagingHub.Client.Extensions.Bucket;
using Takenet.MessagingHub.Client.Extensions.Session;
using Takenet.MessagingHub.Client.Extensions.Tunnel;
using Takenet.MessagingHub.Client.Listener;
using Takenet.MessagingHub.Client.Sender;
namespace Takenet.MessagingHub.Client.Host
{
public static class Bootstrapper
{
public const string DefaultApplicationFileName = "application.json";
/// <summary>
/// Creates ans starts an application with the given settings.
/// </summary>
/// <param name="cancellationToken"></param>
/// <param name="application">The application instance. If not defined, the class will look for an application.json file in the current directory.</param>
/// <param name="loadAssembliesFromWorkingDirectory">if set to <c>true</c> indicates to the bootstrapper to load all assemblies from the current working directory.</param>
/// <param name="path">Assembly path to load</param>
/// <param name="builder">The builder instance to be used.</param>
/// <param name="typeResolver">The type provider.</param>
public static async Task<IStoppable> StartAsync(
CancellationToken cancellationToken,
Application application = null,
bool loadAssembliesFromWorkingDirectory = true,
string path = ".",
MessagingHubClientBuilder builder = null,
ITypeResolver typeResolver = null)
{
if (application == null)
{
if (!File.Exists(DefaultApplicationFileName))
{
throw new FileNotFoundException($"Could not find the '{DefaultApplicationFileName}' file", DefaultApplicationFileName);
}
application = Application.ParseFromJsonFile(DefaultApplicationFileName);
}
if (builder == null) builder = new MessagingHubClientBuilder(new TcpTransportFactory());
if (application.Identifier != null)
{
if (application.Password != null)
{
builder = builder.UsingPassword(application.Identifier, application.Password);
}
else if (application.AccessKey != null)
{
builder = builder.UsingAccessKey(application.Identifier, application.AccessKey);
}
else
{
throw new ArgumentException("At least an access key or password must be defined", nameof(application));
}
}
else
{
builder = builder.UsingGuest();
}
if (application.Instance != null) builder = builder.UsingInstance(application.Instance);
if (application.RoutingRule != null) builder = builder.UsingRoutingRule(application.RoutingRule.Value);
if (application.Domain != null) builder = builder.UsingDomain(application.Domain);
if (application.Scheme != null) builder = builder.UsingScheme(application.Scheme);
if (application.HostName != null) builder = builder.UsingHostName(application.HostName);
if (application.Port != null) builder = builder.UsingPort(application.Port.Value);
if (application.SendTimeout != 0) builder = builder.WithSendTimeout(TimeSpan.FromMilliseconds(application.SendTimeout));
if (application.SessionEncryption.HasValue) builder = builder.UsingEncryption(application.SessionEncryption.Value);
if (application.SessionCompression.HasValue) builder = builder.UsingCompression(application.SessionCompression.Value);
if (application.Throughput != 0) builder = builder.WithThroughput(application.Throughput);
if (application.DisableNotify) builder = builder.WithAutoNotify(false);
if (application.ChannelCount.HasValue) builder = builder.WithChannelCount(application.ChannelCount.Value);
if (application.ReceiptEvents != null && application.ReceiptEvents.Length > 0)
{
builder = builder.WithReceiptEvents(application.ReceiptEvents);
}
else if (application.ReceiptEvents != null)
{
builder = builder.WithReceiptEvents(new[] { Event.Failed });
}
if (typeResolver == null) typeResolver = new TypeResolver();
var localServiceProvider = BuildServiceProvider(application, typeResolver);
localServiceProvider.RegisterService(typeof(MessagingHubClientBuilder), builder);
var client = await BuildClientAsync(application, builder.Build, localServiceProvider, typeResolver, cancellationToken);
var stoppables = new IStoppable[2];
stoppables[0] = client;
var startable = await BuildStartupAsync(application, localServiceProvider, typeResolver);
if (startable != null)
{
stoppables[1] = startable as IStoppable;
}
return new StoppableWrapper(stoppables);
}
public static IServiceContainer BuildServiceProvider(Application application, ITypeResolver typeResolver)
{
var localServiceProvider = new TypeServiceProvider();
if (application.ServiceProviderType != null)
{
var serviceProviderType = typeResolver.Resolve(application.ServiceProviderType);
if (serviceProviderType != null)
{
if (!typeof(IServiceProvider).IsAssignableFrom(serviceProviderType))
{
throw new InvalidOperationException($"{application.ServiceProviderType} must be an implementation of '{nameof(IServiceProvider)}'");
}
if (serviceProviderType == typeof(TypeServiceProvider))
{
throw new InvalidOperationException($"{nameof(Application.ServiceProviderType)} type cannot be '{serviceProviderType.Name}'");
}
if (serviceProviderType.GetConstructors(BindingFlags.Instance | BindingFlags.Public).All(c => c.GetParameters().Length != 0))
{
throw new InvalidOperationException($"{nameof(Application.ServiceProviderType)} must have an empty public constructor");
}
localServiceProvider.SecondaryServiceProvider = (IServiceProvider)Activator.CreateInstance(serviceProviderType);
}
}
if (localServiceProvider.SecondaryServiceProvider is IServiceContainer serviceContainer)
{
return serviceContainer;
}
return localServiceProvider;
}
public static async Task<IStartable> BuildStartupAsync(Application application, IServiceContainer localServiceProvider, ITypeResolver typeResolver)
{
if (application.StartupType == null) return null;
var startable = await CreateAsync<IStartable>(
application.StartupType,
localServiceProvider,
application.Settings,
typeResolver)
.ConfigureAwait(false);
await startable.StartAsync().ConfigureAwait(false);
return startable;
}
public static async Task<IMessagingHubClient> BuildClientAsync(
Application application,
Func<IMessagingHubClient> builder,
IServiceContainer serviceContainer,
ITypeResolver typeResolver,
CancellationToken cancellationToken,
Action<IServiceContainer> serviceOverrides = null)
{
RegisterSettingsContainer(application, serviceContainer, typeResolver);
RegisterSettingsTypes(application, serviceContainer, typeResolver);
RegisterStateManager(application, serviceContainer, typeResolver);
serviceContainer.RegisterExtensions();
serviceContainer.RegisterService(typeof(IServiceProvider), serviceContainer);
serviceContainer.RegisterService(typeof(IServiceContainer), serviceContainer);
serviceContainer.RegisterService(typeof(Application), application);
serviceContainer.RegisterService(typeof(ISessionManager), () => new SessionManager(serviceContainer.GetService<IBucketExtension>()));
var client = builder();
serviceContainer.RegisterService(typeof(IMessagingHubSender), client);
serviceOverrides?.Invoke(serviceContainer);
var stateManager = serviceContainer.GetService<IStateManager>();
var sessionManager = serviceContainer.GetService<ISessionManager>();
if (application.RegisterTunnelReceivers)
{
RegisterTunnelReceivers(application);
}
var channelListener = new MessagingHubListener(client, !application.DisableNotify);
await AddMessageReceivers(application, serviceContainer, client, channelListener, typeResolver, stateManager, sessionManager);
await AddNotificationReceivers(application, serviceContainer, client, channelListener, typeResolver, stateManager, sessionManager);
await AddCommandReceivers(application, serviceContainer, channelListener, typeResolver);
await client.StartAsync(channelListener, cancellationToken).ConfigureAwait(false);
return client;
}
public static void RegisterSettingsContainer(SettingsContainer settingsContainer, IServiceContainer serviceContainer, ITypeResolver typeResolver)
{
if (settingsContainer.SettingsType != null)
{
var settingsDictionary = settingsContainer.Settings;
var settingsType = typeResolver.Resolve(settingsContainer.SettingsType);
if (settingsType != null)
{
var settingsJson = JsonConvert.SerializeObject(settingsDictionary, Application.SerializerSettings);
var settings = JsonConvert.DeserializeObject(settingsJson, settingsType, Application.SerializerSettings);
serviceContainer.RegisterService(settingsType, settings);
}
}
}
public static void RegisterSettingsTypes(Application application, IServiceContainer serviceContainer, ITypeResolver typeResolver)
{
var applicationReceivers =
(application.MessageReceivers ?? new ApplicationReceiver[0]).Union(
application.NotificationReceivers ?? new ApplicationReceiver[0]);
// First, register the receivers settings
foreach (var applicationReceiver in applicationReceivers.Where(a => a.SettingsType != null))
{
RegisterSettingsContainer(applicationReceiver, serviceContainer, typeResolver);
}
}
public static void RegisterStateManager(Application application, IServiceContainer serviceContainer, ITypeResolver typeResolver)
{
if (string.IsNullOrWhiteSpace(application.StateManagerType))
{
serviceContainer.RegisterService(typeof(IStateManager), () => new BucketStateManager(serviceContainer.GetService<IBucketExtension>()));
}
else
{
var stateManagerType = typeResolver.Resolve(application.StateManagerType);
serviceContainer.RegisterService(typeof(IStateManager), () => serviceContainer.GetService(stateManagerType));
}
}
private static void RegisterTunnelReceivers(Application application)
{
// Message
var messageReceivers = new List<MessageApplicationReceiver>();
if (application.MessageReceivers != null
&& application.MessageReceivers.Length > 0)
{
messageReceivers.AddRange(application.MessageReceivers);
}
messageReceivers.Add(
new MessageApplicationReceiver
{
Sender = $"(.+)@{TunnelExtension.TunnelAddress.Domain.Replace(".", "\\.")}\\/(.+)",
Type = nameof(TunnelMessageReceiver)
});
application.MessageReceivers = messageReceivers.ToArray();
// Notification
var notificationReceivers = new List<NotificationApplicationReceiver>();
if (application.NotificationReceivers != null
&& application.NotificationReceivers.Length > 0)
{
notificationReceivers.AddRange(application.NotificationReceivers);
}
notificationReceivers.Add(
new NotificationApplicationReceiver
{
Sender = $"(.+)@{TunnelExtension.TunnelAddress.Domain.Replace(".", "\\.")}\\/(.+)",
Type = nameof(TunnelNotificationReceiver)
});
application.NotificationReceivers = notificationReceivers.ToArray();
}
private static async Task AddNotificationReceivers(
Application application,
IServiceContainer serviceContainer,
IMessagingHubSender sender,
IMessagingHubListener channelListener,
ITypeResolver typeResolver,
IStateManager stateManager,
ISessionManager sessionManager)
{
if (application.NotificationReceivers != null && application.NotificationReceivers.Length > 0)
{
foreach (var applicationReceiver in application.NotificationReceivers)
{
INotificationReceiver receiver;
if (applicationReceiver.Response?.MediaType != null)
{
var content = applicationReceiver.Response.ToDocument();
receiver =
new LambdaNotificationReceiver(
(notification, c) => sender.SendMessageAsync(content, notification.From, c));
}
else if (!string.IsNullOrWhiteSpace(applicationReceiver.ForwardTo))
{
var tunnelExtension = serviceContainer.GetService<ITunnelExtension>();
var destination = Identity.Parse(applicationReceiver.ForwardTo);
receiver =
new LambdaNotificationReceiver(
(notification, c) => tunnelExtension.ForwardNotificationAsync(notification, destination, c));
}
else
{
receiver = await CreateAsync<INotificationReceiver>(
applicationReceiver.Type, serviceContainer, applicationReceiver.Settings, typeResolver)
.ConfigureAwait(false);
}
if (applicationReceiver.OutState != null)
{
receiver = new SetStateNotificationReceiver(receiver, stateManager, applicationReceiver.OutState);
}
Func<Notification, Task<bool>> notificationPredicate = BuildPredicate<Notification>(applicationReceiver, stateManager, sessionManager);
if (applicationReceiver.EventType != null)
{
var currentNotificationPredicate = notificationPredicate;
notificationPredicate = async (n) => await currentNotificationPredicate(n) && n.Event.Equals(applicationReceiver.EventType);
}
channelListener.AddNotificationReceiver(receiver, notificationPredicate, applicationReceiver.Priority);
}
}
}
public static async Task AddMessageReceivers(
Application application,
IServiceContainer serviceContainer,
IMessagingHubSender sender,
IMessagingHubListener channelListener,
ITypeResolver typeResolver,
IStateManager stateManager,
ISessionManager sessionManager)
{
if (application.MessageReceivers != null && application.MessageReceivers.Length > 0)
{
foreach (var applicationReceiver in application.MessageReceivers)
{
IMessageReceiver receiver;
if (applicationReceiver.Response?.MediaType != null)
{
var content = applicationReceiver.Response.ToDocument();
receiver =
new LambdaMessageReceiver(
(message, c) => sender.SendMessageAsync(content, message.From, c));
}
else if (!string.IsNullOrWhiteSpace(applicationReceiver.ForwardTo))
{
var tunnelExtension = serviceContainer.GetService<ITunnelExtension>();
var destination = Identity.Parse(applicationReceiver.ForwardTo);
receiver =
new LambdaMessageReceiver(
(message, c) => tunnelExtension.ForwardMessageAsync(message, destination, c));
}
else
{
var receiverType = typeResolver.Resolve(applicationReceiver.Type);
receiver = await BuildByLifetimeAsync(
applicationReceiver.Lifetime ?? application.DefaultMessageReceiverLifetime,
receiverType,
applicationReceiver.Settings,
serviceContainer);
}
if (applicationReceiver.OutState != null)
{
receiver = new SetStateMessageReceiver(receiver, stateManager, applicationReceiver.OutState);
}
Func<Message, Task<bool>> messagePredicate = BuildPredicate<Message>(applicationReceiver, stateManager, sessionManager);
if (applicationReceiver.MediaType != null)
{
var currentMessagePredicate = messagePredicate;
var mediaTypeRegex = new Regex(applicationReceiver.MediaType, RegexOptions.Compiled | RegexOptions.IgnoreCase);
messagePredicate = async (m) => await currentMessagePredicate(m) && mediaTypeRegex.IsMatch(m.Type.ToString());
}
if (applicationReceiver.Content != null)
{
var currentMessagePredicate = messagePredicate;
var contentRegex = new Regex(applicationReceiver.Content, RegexOptions.Compiled | RegexOptions.IgnoreCase);
messagePredicate = async (m) => await currentMessagePredicate(m) && contentRegex.IsMatch(m.Content.ToString());
}
channelListener.AddMessageReceiver(receiver, messagePredicate, applicationReceiver.Priority);
}
}
}
private static async Task AddCommandReceivers(
Application application,
IServiceContainer serviceContainer,
IMessagingHubListener channelListener,
ITypeResolver typeResolver)
{
if (application.CommandReceivers == null || application.CommandReceivers.Length == 0)
{
return;
}
foreach (var commandReceiver in application.CommandReceivers)
{
var receiver = await CreateAsync<ICommandReceiver>(
commandReceiver.Type, serviceContainer, commandReceiver.Settings, typeResolver)
.ConfigureAwait(false);
Func<Command, Task<bool>> predicate = c => Task.FromResult(true);
if (commandReceiver.Method.HasValue)
{
var currentPredicate = predicate;
predicate = async (c) => await currentPredicate(c) && c.Method == commandReceiver.Method.Value;
}
if (commandReceiver.Uri != null)
{
var limeUriRegex = new Regex(commandReceiver.Uri, RegexOptions.Compiled | RegexOptions.IgnoreCase);
var currentPredicate = predicate;
predicate = async (c) => await currentPredicate(c) && limeUriRegex.IsMatch(c.Uri.ToString());
}
if (commandReceiver.ResourceUri != null)
{
var resourceUriRegex = new Regex(commandReceiver.ResourceUri, RegexOptions.Compiled | RegexOptions.IgnoreCase);
var currentPredicate = predicate;
predicate = async (c) => await currentPredicate(c) && resourceUriRegex.IsMatch(c.GetResourceUri().ToString());
}
if (commandReceiver.MediaType != null)
{
var currentPredicate = predicate;
var mediaTypeRegex = new Regex(commandReceiver.MediaType, RegexOptions.Compiled | RegexOptions.IgnoreCase);
predicate = async (c) => await currentPredicate(c) && mediaTypeRegex.IsMatch(c.Type.ToString());
}
channelListener.AddCommandReceiver(receiver, predicate, commandReceiver.Priority);
}
}
private static Func<T, Task<bool>> BuildPredicate<T>(
ApplicationReceiver applicationReceiver,
IStateManager stateManager,
ISessionManager sessionManager) where T : Envelope, new()
{
Func<T, Task<bool>> predicate = m => Task.FromResult(m != null);
if (applicationReceiver.Sender != null)
{
var currentPredicate = predicate;
var senderRegex = new Regex(applicationReceiver.Sender, RegexOptions.Compiled | RegexOptions.IgnoreCase);
predicate = async (m) => await currentPredicate(m) && senderRegex.IsMatch(m.From.ToString());
}
if (applicationReceiver.Destination != null)
{
var currentPredicate = predicate;
var destinationRegex = new Regex(applicationReceiver.Destination, RegexOptions.Compiled | RegexOptions.IgnoreCase);
predicate = async (m) => await currentPredicate(m) && destinationRegex.IsMatch(m.To.ToString());
}
if (applicationReceiver.State != null)
{
var currentPredicate = predicate;
predicate = async (m) => await currentPredicate(m)
&& (await stateManager.GetStateAsync(m.From.ToIdentity())).Equals(applicationReceiver.State, StringComparison.OrdinalIgnoreCase);
}
if (applicationReceiver.Culture != null)
{
var currentPredicate = predicate;
predicate = async (m) => await currentPredicate(m)
&& (await sessionManager.GetCultureAsync(m.From, CancellationToken.None) ?? "").Equals(applicationReceiver.Culture, StringComparison.OrdinalIgnoreCase);
}
return predicate;
}
public static Task<T> CreateAsync<T>(string typeName, IServiceProvider serviceProvider, IDictionary<string, object> settings, ITypeResolver typeResolver) where T : class
{
if (typeName == null) throw new ArgumentNullException(nameof(typeName));
var type = typeResolver.Resolve(typeName);
return CreateAsync<T>(type, serviceProvider, settings);
}
public static async Task<T> CreateAsync<T>(Type type, IServiceProvider serviceProvider, IDictionary<string, object> settings) where T : class
{
if (type == null) throw new ArgumentNullException(nameof(type));
IFactory<T> factory;
if (typeof(IFactory<T>).IsAssignableFrom(type))
{
factory = (IFactory<T>)Activator.CreateInstance(type);
}
else
{
factory = new Factory<T>(type);
}
var instance = await factory.CreateAsync(serviceProvider, settings);
if (instance == null)
{
throw new Exception($"{type.Name} does not implement {typeof(T).Name}");
}
return instance;
}
private static Task<IMessageReceiver> BuildByLifetimeAsync(ReceiverLifetime lifetime, Type receiverType, IDictionary<string, object> settings, IServiceContainer serviceContainer)
{
switch (lifetime)
{
case ReceiverLifetime.Scoped:
var messageReceiverFactory = GetMessageReceiverFactory(serviceContainer);
return Task.FromResult<IMessageReceiver>(new ScopedMessageReceiverWrapper(messageReceiverFactory, receiverType, settings));
case ReceiverLifetime.Singleton:
default:
return CreateAsync<IMessageReceiver>(receiverType, serviceContainer, settings);
}
}
private static IMessageReceiverFactory GetMessageReceiverFactory(IServiceContainer container)
{
IMessageReceiverFactory containerResolved = null;
try
{
containerResolved = container.GetService<IMessageReceiverFactory>();
}
catch
{
}
return containerResolved ?? new MessageReceiverFactory(container);
}
private class StoppableWrapper : IStoppable
{
private readonly IStoppable[] _stoppables;
public StoppableWrapper(params IStoppable[] stoppables)
{
_stoppables = stoppables;
}
public async Task StopAsync(CancellationToken cancellationToken)
{
foreach (var stoppable in _stoppables)
{
if (stoppable != null)
await stoppable.StopAsync(cancellationToken).ConfigureAwait(false);
}
}
}
private class SetStateMessageReceiver : SetStateEnvelopeReceiver<Message>, IMessageReceiver
{
public SetStateMessageReceiver(IEnvelopeReceiver<Message> receiver, IStateManager stateManager, string state)
: base(receiver, stateManager, state)
{
}
}
private class SetStateNotificationReceiver : SetStateEnvelopeReceiver<Notification>, INotificationReceiver
{
public SetStateNotificationReceiver(IEnvelopeReceiver<Notification> receiver, IStateManager stateManager, string state)
: base(receiver, stateManager, state)
{
}
}
private class SetStateEnvelopeReceiver<T> : IEnvelopeReceiver<T> where T : Envelope
{
private readonly IEnvelopeReceiver<T> _receiver;
private readonly string _state;
private readonly IStateManager _stateManager;
protected SetStateEnvelopeReceiver(IEnvelopeReceiver<T> receiver, IStateManager stateManager, string state)
{
if (state == null) throw new ArgumentNullException(nameof(state));
_receiver = receiver;
_state = state;
_stateManager = stateManager;
}
public async Task ReceiveAsync(T envelope, CancellationToken cancellationToken = new CancellationToken())
{
await _receiver.ReceiveAsync(envelope, cancellationToken).ConfigureAwait(false);
await _stateManager.SetStateAsync(envelope.From.ToIdentity(), _state);
}
}
private class ScopedMessageReceiverWrapper : IMessageReceiver
{
private readonly IMessageReceiverFactory _messageReceiverFactory;
private readonly Type _receiverType;
private readonly IDictionary<string, object> _settings;
public ScopedMessageReceiverWrapper(IMessageReceiverFactory messageReceiverFactory, Type receiverType, IDictionary<string, object> settings)
{
_messageReceiverFactory = messageReceiverFactory;
_receiverType = receiverType;
_settings = settings;
}
public async Task ReceiveAsync(Message message, CancellationToken cancellationToken = default(CancellationToken))
{
var receiver = await _messageReceiverFactory.CreateAsync(_receiverType, _settings)
.ConfigureAwait(false);
try
{
await receiver
.ReceiveAsync(message, cancellationToken)
.ConfigureAwait(false);
}
finally
{
await _messageReceiverFactory
.ReleaseAsync(receiver)
.ConfigureAwait(false);
}
}
}
private class MessageReceiverFactory : IMessageReceiverFactory
{
private IServiceProvider _provider;
public MessageReceiverFactory(IServiceProvider provider)
{
_provider = provider;
}
public Task<IMessageReceiver> CreateAsync(Type receiverType, IDictionary<string, object> settings)
{
return CreateAsync<IMessageReceiver>(receiverType, _provider, settings);
}
public Task ReleaseAsync(IMessageReceiver receiver)
{
return Task.CompletedTask;
}
}
}
public interface IMessageReceiverFactory
{
Task<IMessageReceiver> CreateAsync(Type receiverType, IDictionary<string, object> settings);
Task ReleaseAsync(IMessageReceiver receiver);
}
}
| |
/*
* The Life Simulation Challenge
* https://github.com/dankrusi/life-simulation-challenge
*
* Contributor(s):
* Dan Krusi <dan.krusi@nerves.ch> (original author)
*
* 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.Drawing;
using System.Collections;
using System.Collections.Generic;
namespace LifeSimulation.Core
{
/// <summary>
/// The World class represents the world state in the simulation. It contains
/// all the lifelets, food and messages. It also keeps track of statistics
/// and is responsible for spawning all the lifelets.
/// </summary>
public class World
{
#region Private Variables
// Data
private ArrayList _races; // List of all currently competing races (contains System.Type)
private LoopList<Lifelet> _lifelets; // List of living lifelets
private LoopList<Message> _messages; // List of active messages
private LoopList<Food> _food; // List of avaialable food
private Hashtable _stats; // Hashtable of all tracked stats. We use a hashtable for flexibility and automatic export/display.
// World
private int _initialLifelets;
private SpawnMethod _spawnMethod;
private long _age;
// Util
private Random _randomGen;
// GUI
private Lifelet _highlightedLifelet = null;
private Lifelet _selectedLifelet = null;
private Point _cursor;
#endregion
#region Enumerations
public enum SpawnMethod {
GroupedRacesOnRing,
RandomOnRing,
Random
}
#endregion
#region Properties
public Lifelet HighlightedLifelet {
get { return _highlightedLifelet; }
set { _highlightedLifelet = value; }
}
public Lifelet SelectedLifelet {
get { return _selectedLifelet; }
set { _selectedLifelet = value; }
}
public Random RandomGen {
get { return _randomGen; }
}
public LoopList<Lifelet> Lifelets {
get { return _lifelets; }
}
public LoopList<Message> Messages {
get { return _messages; }
}
public LoopList<Food> Food {
get { return _food; }
}
public Hashtable Statistics {
get { return _stats; }
}
public long Age {
get { return _age; }
}
#endregion
#region Public Methods
public World (ArrayList races, int initialLifelets, SpawnMethod spawnMethod)
{
// Init
_stats = new Hashtable();
_randomGen = new Random((int)DateTime.Now.Ticks);
_initialLifelets = initialLifelets;
_races = races;
_spawnMethod = spawnMethod;
_age = 0;
// Assign a color for each race
ArrayList colors = new ArrayList(new Color[]{Color.Red,Color.Blue,Color.Green,Color.Aqua,Color.Lime,Color.Orange});
foreach(Type t in races) {
Color c = Color.FromArgb(_randomGen.Next(256),_randomGen.Next(256),_randomGen.Next(256)); // Random color, if we run out
if(colors.Count > 0) {
int i = _randomGen.Next(colors.Count);
c = (Color)colors[i];
colors.RemoveAt(i);
}
_stats[t.FullName + "_Color"] = c;
}
// Reset
this.Reset();
}
public void Reset() {
// Setup data
_lifelets = new LoopList<Lifelet>();
_messages = new LoopList<Message>();
_food = new LoopList<Food>();
// Create the initial lifelets...
spawnInitialLifelets();
}
public void CreateLifelet(int x, int y) {
}
public void RemoveLifelet(Lifelet life) {
_lifelets.Remove(life);
}
public void Simulate() {
// Init
_highlightedLifelet = null;
_age++;
// Food
foreach(Food food in _food) {
food.Simulate();
}
// Messages
foreach(Message message in _messages) {
message.Simulate();
}
// Loop life forms
foreach(Lifelet life in _lifelets) {
// Simulate
life.PrepareSimulate();
life.Simulate();
// Check that the simulation was performed properly
if(life.DidSimulate != true) {
throw new Exception("Implementing class did not call base Simulate()!");
}
// Highlighted?
if(life.Distance(new Vector(_cursor.X,_cursor.Y)) < Config.DisplayMouseSensitivity) _highlightedLifelet = life;
}
}
public void Draw(Graphics g) {
// Init
Lifelet lifeToHighlight = _highlightedLifelet;
if(_selectedLifelet != null) lifeToHighlight = _selectedLifelet;
// Background
g.Clear(Color.Black);
// Food
foreach(Food food in _food) {
food.Draw(g);
}
// Loop life forms
foreach(Lifelet life in _lifelets) {
// Tell life to draw
life.Draw(g);
// Debugging?
if(Config.Debug) {
}
// Highlight / debugging infos
if(life == lifeToHighlight || Config.Debug) {
System.Drawing.Drawing2D.GraphicsContainer gc1 = g.BeginContainer(); {
g.TranslateTransform((int)life.X,(int)life.Y);
// Draw a crosshair
Pen pen = new Pen( life == lifeToHighlight ? Color.White : life.Color );
int crosshairSize = life == lifeToHighlight ? (int)(Config.DisplayCrosshairSize*1.5) : Config.DisplayCrosshairSize;
g.DrawLine(pen,0,-crosshairSize,0,crosshairSize);
g.DrawLine(pen,-crosshairSize,0,crosshairSize,0);
// Focus Circle
g.DrawEllipse(new Pen(Color.White),
(int)(-life.Visibility),
(int)(-life.Visibility),
(int)(life.Visibility*2),
(int)(life.Visibility*2) );
// Health bar
g.FillRectangle(Brushes.Red,
0,
-(Config.DisplayCrosshairSize*3),
(int)((life.Health/100.0) * Config.DisplayPseudoPercentBarSize),
2 );
// Energy bar
g.FillRectangle(Brushes.Yellow,
0,
-(Config.DisplayCrosshairSize*3) - 4,
(int)((life.Energy/100.0) * Config.DisplayPseudoPercentBarSize),
2 );
} g.EndContainer(gc1);
}
}
// Message
foreach(Message message in _messages) {
message.Draw(g);
}
// Highlight infos
string infos = "";
if(lifeToHighlight != null) {
// Infos via reflection. We only show information for properties. Note that
// we do this operation on the virtual type, not the Life type, so any
// properties in an implemented life are also shown.
Type t = lifeToHighlight.GetType();
foreach(System.Reflection.PropertyInfo p in t.GetProperties()) {
object val = p.GetValue(lifeToHighlight,null);
if(val != null) infos += p.Name + ": " + val.ToString() + "\n";
}
infos += "\n";
}
// Show debug infos
if(Config.Debug) {
// World...
infos += "Cursor: " + _cursor + "\n";
// Statistics
foreach(object k in _stats.Keys) {
infos += k + ": " + _stats[k] + "\n";
}
infos += "\n";
}
// Draw world boundaries
if(Config.Debug) {
Pen pen = new Pen(Color.White);
g.DrawLine(pen,0,-Config.DisplayCrosshairSize*3,0,Config.DisplayCrosshairSize*3);
g.DrawLine(pen,-Config.DisplayCrosshairSize*3,0,Config.DisplayCrosshairSize*3,0);
g.DrawEllipse(pen,-Config.WorldRadius,-Config.WorldRadius,Config.WorldRadius*2,Config.WorldRadius*2);
}
// Draw debug infos - no world drawing after this
if (infos != "") {
g.ResetTransform(); //NOTE: On Windows this doesnt reset through all the containers, so we do it in the current container and restrict any drawing after
System.Drawing.Drawing2D.GraphicsContainer gc2 = g.BeginContainer();
{
// g.ResetTransform();
g.DrawString(infos, Config.DisplayTextFont, Config.DisplayTextBrush, new PointF(30, 30));
} g.EndContainer(gc2);
}
}
public void SetCursor(int x, int y) {
_cursor.X = x;
_cursor.Y = y;
}
public void DoEnergyTransaction() {
}
public Lifelet UnshellLifelet(ShelledLifelet shelled) {
//TODO: This is not very efficient... Should we re-write LoopList as a Hashtable?
foreach(Lifelet lifelet in _lifelets) {
if(shelled.UID == lifelet.UID) return lifelet;
}
return null;
}
#endregion
#region Public Static Methods
public static ArrayList GetAvailableRaces() {
// Init
ArrayList races = new ArrayList();
// Get from bin - this has prio
races.AddRange(getAvailableRacesFromFolder("bin"));
// Get from plugins - only add if new
ArrayList plugins = getAvailableRacesFromFolder("plugins");
foreach(System.Type type in plugins) {
if(races.Contains(type) == false) races.Add(type);
}
return races;
}
#endregion
#region Private Methods
public static ArrayList getAvailableRacesFromFolder(string folder) {
// Init
ArrayList races = new ArrayList();
Type lifeletType = Type.GetType("LifeSimulation.Core.Lifelet");
// Loop all dll files
System.IO.DirectoryInfo binDir = new System.IO.DirectoryInfo(System.Windows.Forms.Application.StartupPath);
foreach(System.IO.DirectoryInfo dir in binDir.Parent.GetDirectories(folder)) {
foreach(string file in System.IO.Directory.GetFiles(dir.FullName,"*.dll")) {
// Load the dll
System.Reflection.Assembly dll = System.Reflection.Assembly.LoadFrom(file);
// Loop all contained types
foreach (Type type in dll.GetTypes()) {
// Is this a lifelet?
if(type.IsSubclassOf(lifeletType)) races.Add(type);
}
}
}
return races;
}
private void spawnInitialLifelets() {
// Init
int lifeletsPerRace = _initialLifelets / _races.Count;
// We spawn races around a outside ring
if(_spawnMethod == SpawnMethod.GroupedRacesOnRing) {
double radiansPerRace = (2*Math.PI) / (_races.Count);
int lifeletRandomDispersion = (int)(Config.WorldInitialLifeletsDispersionAmount * (_races.Count/(_races.Count*Config.WorldInitialLifeletsToRaceDispersionRatio)));
for(int i = 0; i < _races.Count; i++) {
// Get the actual type and figure out center point
Type lifeletType = (Type)_races[i];
Vector raceCenter = Vector.FromAngle(Config.WorldInitialSpawnRadius,radiansPerRace*i);
// Loop lifelets for race
for(int ii = 0; ii < lifeletsPerRace; ii++) {
// New position
double x = raceCenter.X + _randomGen.Next(-lifeletRandomDispersion,lifeletRandomDispersion);
double y = raceCenter.Y + _randomGen.Next(-lifeletRandomDispersion,lifeletRandomDispersion);
// Create and register life
Lifelet newLife = (Lifelet)Activator.CreateInstance(lifeletType,this,new Vector(x,y));
newLife.VerifyIntegrity();
_lifelets.Add(newLife);
}
}
}
// We spawn randomly on outside ring
else if (_spawnMethod == SpawnMethod.RandomOnRing) {
for(int i = 0; i < _races.Count; i++) {
// Get the actual type and figure out center point
Type lifeletType = (Type)_races[i];
// Loop lifelets for race
for(int ii = 0; ii < lifeletsPerRace; ii++) {
// Position
int angle = _randomGen.Next(0,360);
Vector pos = Vector.FromAngle(Config.WorldInitialSpawnRadius,Math2.DegreeToRadian(angle));
// Create and register life
Lifelet newLife = (Lifelet)Activator.CreateInstance(lifeletType,this,pos);
_lifelets.Add(newLife);
}
}
}
// Spawn food
for(int i = 0; i < Config.WorldInitialFoodAmount; i++) {
// Position
int angle = _randomGen.Next(0,360);
int length = _randomGen.Next(0,Config.WorldRadius);
Vector pos = Vector.FromAngle(length,Math2.DegreeToRadian(angle));
// Create and register food
Food newFood = new Food(this,pos,Math2.JitteredValue(Config.FoodEnergy,Config.FoodEnergyJitter));
_food.Add(newFood);
}
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.ComponentModel.Composition;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CodeFixes.Suppression;
using Microsoft.CodeAnalysis.CodeRefactorings;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor.Host;
using Microsoft.CodeAnalysis.Editor.Shared;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.Editor.Shared.Options;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Editor.Tags;
using Microsoft.CodeAnalysis.Experiments;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.Text.Shared.Extensions;
using Microsoft.VisualStudio.Language.Intellisense;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Implementation.Suggestions
{
using CodeFixGroupKey = Tuple<DiagnosticData, CodeActionPriority>;
[Export(typeof(ISuggestedActionsSourceProvider))]
[Export(typeof(SuggestedActionsSourceProvider))]
[VisualStudio.Utilities.ContentType(ContentTypeNames.RoslynContentType)]
[VisualStudio.Utilities.ContentType(ContentTypeNames.XamlContentType)]
[VisualStudio.Utilities.Name("Roslyn Code Fix")]
[VisualStudio.Utilities.Order]
internal class SuggestedActionsSourceProvider : ISuggestedActionsSourceProvider
{
private static readonly Guid s_CSharpSourceGuid = new Guid("b967fea8-e2c3-4984-87d4-71a38f49e16a");
private static readonly Guid s_visualBasicSourceGuid = new Guid("4de30e93-3e0c-40c2-a4ba-1124da4539f6");
private static readonly Guid s_xamlSourceGuid = new Guid("a0572245-2eab-4c39-9f61-06a6d8c5ddda");
private const int InvalidSolutionVersion = -1;
private readonly ICodeRefactoringService _codeRefactoringService;
private readonly IDiagnosticAnalyzerService _diagnosticService;
private readonly ICodeFixService _codeFixService;
public readonly ICodeActionEditHandlerService EditHandler;
public readonly IAsynchronousOperationListener OperationListener;
public readonly IWaitIndicator WaitIndicator;
public readonly ImmutableArray<Lazy<IImageMonikerService, OrderableMetadata>> ImageMonikerServices;
[ImportingConstructor]
public SuggestedActionsSourceProvider(
ICodeRefactoringService codeRefactoringService,
IDiagnosticAnalyzerService diagnosticService,
ICodeFixService codeFixService,
ICodeActionEditHandlerService editHandler,
IWaitIndicator waitIndicator,
[ImportMany] IEnumerable<Lazy<IAsynchronousOperationListener, FeatureMetadata>> asyncListeners,
[ImportMany] IEnumerable<Lazy<IImageMonikerService, OrderableMetadata>> imageMonikerServices)
{
_codeRefactoringService = codeRefactoringService;
_diagnosticService = diagnosticService;
_codeFixService = codeFixService;
EditHandler = editHandler;
WaitIndicator = waitIndicator;
OperationListener = new AggregateAsynchronousOperationListener(asyncListeners, FeatureAttribute.LightBulb);
ImageMonikerServices = ExtensionOrderer.Order(imageMonikerServices).ToImmutableArray();
}
public ISuggestedActionsSource CreateSuggestedActionsSource(ITextView textView, ITextBuffer textBuffer)
{
Contract.ThrowIfNull(textView);
Contract.ThrowIfNull(textBuffer);
return new Source(this, textView, textBuffer);
}
private class Source : ForegroundThreadAffinitizedObject, ISuggestedActionsSource
{
// state that will be only reset when source is disposed.
private SuggestedActionsSourceProvider _owner;
private ITextView _textView;
private ITextBuffer _subjectBuffer;
private WorkspaceRegistration _registration;
// mutable state
private Workspace _workspace;
private int _lastSolutionVersionReported;
public Source(SuggestedActionsSourceProvider owner, ITextView textView, ITextBuffer textBuffer)
{
_owner = owner;
_textView = textView;
_textView.Closed += OnTextViewClosed;
_subjectBuffer = textBuffer;
_registration = Workspace.GetWorkspaceRegistration(textBuffer.AsTextContainer());
_lastSolutionVersionReported = InvalidSolutionVersion;
var updateSource = (IDiagnosticUpdateSource)_owner._diagnosticService;
updateSource.DiagnosticsUpdated += OnDiagnosticsUpdated;
if (_registration.Workspace != null)
{
_workspace = _registration.Workspace;
_workspace.DocumentActiveContextChanged += OnActiveContextChanged;
}
_registration.WorkspaceChanged += OnWorkspaceChanged;
}
public event EventHandler<EventArgs> SuggestedActionsChanged;
public bool TryGetTelemetryId(out Guid telemetryId)
{
telemetryId = default(Guid);
var workspace = _workspace;
if (workspace == null || _subjectBuffer == null)
{
return false;
}
var documentId = workspace.GetDocumentIdInCurrentContext(_subjectBuffer.AsTextContainer());
if (documentId == null)
{
return false;
}
var project = workspace.CurrentSolution.GetProject(documentId.ProjectId);
if (project == null)
{
return false;
}
switch (project.Language)
{
case LanguageNames.CSharp:
telemetryId = s_CSharpSourceGuid;
return true;
case LanguageNames.VisualBasic:
telemetryId = s_visualBasicSourceGuid;
return true;
case "Xaml":
telemetryId = s_xamlSourceGuid;
return true;
default:
return false;
}
}
public IEnumerable<SuggestedActionSet> GetSuggestedActions(ISuggestedActionCategorySet requestedActionCategories, SnapshotSpan range, CancellationToken cancellationToken)
{
AssertIsForeground();
using (Logger.LogBlock(FunctionId.SuggestedActions_GetSuggestedActions, cancellationToken))
{
var document = GetMatchingDocumentAsync(range.Snapshot, cancellationToken).WaitAndGetResult(cancellationToken);
if (document == null)
{
// this is here to fail test and see why it is failed.
Trace.WriteLine("given range is not current");
return null;
}
var workspace = document.Project.Solution.Workspace;
var supportsFeatureService = workspace.Services.GetService<IDocumentSupportsFeatureService>();
var fixes = GetCodeFixes(supportsFeatureService, requestedActionCategories, workspace, document, range, cancellationToken);
var refactorings = GetRefactorings(supportsFeatureService, requestedActionCategories, workspace, document, range, cancellationToken);
var result = fixes.Concat(refactorings);
if (result.IsEmpty)
{
return null;
}
var allActionSets = InlineActionSetsIfDesirable(result);
return allActionSets;
}
}
private ImmutableArray<SuggestedActionSet> InlineActionSetsIfDesirable(ImmutableArray<SuggestedActionSet> allActionSets)
{
// If we only have a single set of items, and that set only has three max suggestion
// offered. Then we can consider inlining any nested actions into the top level list.
// (but we only do this if the parent of the nested actions isn't invokable itself).
if (allActionSets.Sum(a => a.Actions.Count()) > 3)
{
return allActionSets;
}
return allActionSets.SelectAsArray(InlineActions);
}
private SuggestedActionSet InlineActions(SuggestedActionSet actionSet)
{
var newActions = ArrayBuilder<ISuggestedAction>.GetInstance();
foreach (var action in actionSet.Actions)
{
var actionWithNestedActions = action as SuggestedActionWithNestedActions;
// Only inline if the underlying code action allows it.
if (actionWithNestedActions?.CodeAction.IsInlinable == true)
{
newActions.AddRange(actionWithNestedActions.NestedActionSet.Actions);
}
else
{
newActions.Add(action);
}
}
return new SuggestedActionSet(
newActions.ToImmutableAndFree(), actionSet.Title, actionSet.Priority, actionSet.ApplicableToSpan);
}
private ImmutableArray<SuggestedActionSet> GetCodeFixes(
IDocumentSupportsFeatureService supportsFeatureService,
ISuggestedActionCategorySet requestedActionCategories,
Workspace workspace,
Document document,
SnapshotSpan range,
CancellationToken cancellationToken)
{
this.AssertIsForeground();
if (_owner._codeFixService != null &&
supportsFeatureService.SupportsCodeFixes(document) &&
requestedActionCategories.Contains(PredefinedSuggestedActionCategoryNames.CodeFix))
{
// We only include suppressions if lightbulb is asking for everything.
// If the light bulb is only asking for code fixes, then we don't include suppressions.
var includeSuppressionFixes = requestedActionCategories.Contains(PredefinedSuggestedActionCategoryNames.Any);
var fixes = Task.Run(
() => _owner._codeFixService.GetFixesAsync(
document, range.Span.ToTextSpan(), includeSuppressionFixes, cancellationToken),
cancellationToken).WaitAndGetResult(cancellationToken);
var filteredFixes = FilterOnUIThread(fixes, workspace);
return OrganizeFixes(workspace, filteredFixes, includeSuppressionFixes);
}
return ImmutableArray<SuggestedActionSet>.Empty;
}
private ImmutableArray<CodeFixCollection> FilterOnUIThread(
ImmutableArray<CodeFixCollection> collections, Workspace workspace)
{
this.AssertIsForeground();
return collections.Select(c => FilterOnUIThread(c, workspace)).WhereNotNull().ToImmutableArray();
}
private CodeFixCollection FilterOnUIThread(
CodeFixCollection collection,
Workspace workspace)
{
this.AssertIsForeground();
var applicableFixes = collection.Fixes.WhereAsArray(f => IsApplicable(f.Action, workspace));
return applicableFixes.Length == 0
? null
: applicableFixes.Length == collection.Fixes.Length
? collection
: new CodeFixCollection(collection.Provider, collection.TextSpan, applicableFixes,
collection.FixAllState,
collection.SupportedScopes, collection.FirstDiagnostic);
}
private bool IsApplicable(CodeAction action, Workspace workspace)
{
if (!action.PerformFinalApplicabilityCheck)
{
// If we don't even need to perform the final applicability check,
// then the code actoin is applicable.
return true;
}
// Otherwise, defer to the action to make the decision.
this.AssertIsForeground();
return action.IsApplicable(workspace);
}
private ImmutableArray<CodeRefactoring> FilterOnUIThread(ImmutableArray<CodeRefactoring> refactorings, Workspace workspace)
{
return refactorings.Select(r => FilterOnUIThread(r, workspace)).WhereNotNull().ToImmutableArray();
}
private CodeRefactoring FilterOnUIThread(CodeRefactoring refactoring, Workspace workspace)
{
var actions = refactoring.Actions.Where(a => IsApplicable(a, workspace)).ToList();
return actions.Count == 0
? null
: actions.Count == refactoring.Actions.Count
? refactoring
: new CodeRefactoring(refactoring.Provider, actions);
}
/// <summary>
/// Arrange fixes into groups based on the issue (diagnostic being fixed) and prioritize these groups.
/// </summary>
private ImmutableArray<SuggestedActionSet> OrganizeFixes(
Workspace workspace, ImmutableArray<CodeFixCollection> fixCollections,
bool includeSuppressionFixes)
{
var map = ImmutableDictionary.CreateBuilder<CodeFixGroupKey, IList<SuggestedAction>>();
var order = ArrayBuilder<CodeFixGroupKey>.GetInstance();
// First group fixes by diagnostic and priority.
GroupFixes(workspace, fixCollections, map, order, includeSuppressionFixes);
// Then prioritize between the groups.
return PrioritizeFixGroups(map.ToImmutable(), order.ToImmutableAndFree());
}
/// <summary>
/// Groups fixes by the diagnostic being addressed by each fix.
/// </summary>
private void GroupFixes(
Workspace workspace,
ImmutableArray<CodeFixCollection> fixCollections,
IDictionary<CodeFixGroupKey, IList<SuggestedAction>> map,
ArrayBuilder<CodeFixGroupKey> order,
bool includeSuppressionFixes)
{
foreach (var fixCollection in fixCollections)
{
ProcessFixCollection(
workspace, map, order, includeSuppressionFixes, fixCollection);
}
}
private void ProcessFixCollection(
Workspace workspace,
IDictionary<CodeFixGroupKey, IList<SuggestedAction>> map,
ArrayBuilder<CodeFixGroupKey> order,
bool includeSuppressionFixes,
CodeFixCollection fixCollection)
{
var fixes = fixCollection.Fixes;
var fixCount = fixes.Length;
Func<CodeAction, SuggestedActionSet> getFixAllSuggestedActionSet =
codeAction => GetFixAllSuggestedActionSet(
codeAction, fixCount, fixCollection.FixAllState,
fixCollection.SupportedScopes, fixCollection.FirstDiagnostic,
workspace);
var nonSupressionCodeFixes = fixes.WhereAsArray(f => !(f.Action is TopLevelSuppressionCodeAction));
var supressionCodeFixes = fixes.WhereAsArray(f => f.Action is TopLevelSuppressionCodeAction);
AddCodeActions(workspace, map, order, fixCollection,
getFixAllSuggestedActionSet, nonSupressionCodeFixes);
// Add suppression fixes to the end of a given SuggestedActionSet so that they
// always show up last in a group.
if (includeSuppressionFixes)
{
AddCodeActions(workspace, map, order, fixCollection,
getFixAllSuggestedActionSet, supressionCodeFixes);
}
}
private void AddCodeActions(
Workspace workspace, IDictionary<CodeFixGroupKey, IList<SuggestedAction>> map,
ArrayBuilder<CodeFixGroupKey> order, CodeFixCollection fixCollection,
Func<CodeAction, SuggestedActionSet> getFixAllSuggestedActionSet,
ImmutableArray<CodeFix> codeFixes)
{
foreach (var fix in codeFixes)
{
SuggestedAction suggestedAction;
if (fix.Action.NestedCodeActions.Length > 0)
{
var nestedActions = fix.Action.NestedCodeActions.SelectAsArray(
nestedAction => new CodeFixSuggestedAction(
_owner, workspace, _subjectBuffer, fix, fixCollection.Provider,
nestedAction, getFixAllSuggestedActionSet(nestedAction)));
var set = new SuggestedActionSet(
nestedActions, SuggestedActionSetPriority.Medium,
fix.PrimaryDiagnostic.Location.SourceSpan.ToSpan());
suggestedAction = new SuggestedActionWithNestedActions(
_owner, workspace, _subjectBuffer,
fixCollection.Provider, fix.Action, set);
}
else
{
suggestedAction = new CodeFixSuggestedAction(
_owner, workspace, _subjectBuffer, fix, fixCollection.Provider,
fix.Action, getFixAllSuggestedActionSet(fix.Action));
}
AddFix(fix, suggestedAction, map, order);
}
}
private static void AddFix(
CodeFix fix, SuggestedAction suggestedAction,
IDictionary<CodeFixGroupKey, IList<SuggestedAction>> map,
ArrayBuilder<CodeFixGroupKey> order)
{
var diag = fix.GetPrimaryDiagnosticData();
var groupKey = new CodeFixGroupKey(diag, fix.Action.Priority);
if (!map.ContainsKey(groupKey))
{
order.Add(groupKey);
map[groupKey] = ImmutableArray.CreateBuilder<SuggestedAction>();
}
map[groupKey].Add(suggestedAction);
}
/// <summary>
/// If the provided fix all context is non-null and the context's code action Id matches the given code action's Id then,
/// returns the set of fix all occurrences actions associated with the code action.
/// </summary>
internal SuggestedActionSet GetFixAllSuggestedActionSet(
CodeAction action,
int actionCount,
FixAllState fixAllState,
ImmutableArray<FixAllScope> supportedScopes,
Diagnostic firstDiagnostic,
Workspace workspace)
{
if (fixAllState == null)
{
return null;
}
if (actionCount > 1 && action.EquivalenceKey == null)
{
return null;
}
var fixAllSuggestedActions = ArrayBuilder<FixAllSuggestedAction>.GetInstance();
foreach (var scope in supportedScopes)
{
var fixAllStateForScope = fixAllState.WithScopeAndEquivalenceKey(scope, action.EquivalenceKey);
var fixAllSuggestedAction = new FixAllSuggestedAction(
_owner, workspace, _subjectBuffer, fixAllStateForScope,
firstDiagnostic, action);
fixAllSuggestedActions.Add(fixAllSuggestedAction);
}
return new SuggestedActionSet(
fixAllSuggestedActions.ToImmutableAndFree(),
title: EditorFeaturesResources.Fix_all_occurrences_in);
}
/// <summary>
/// Return prioritized set of fix groups such that fix group for suppression always show up at the bottom of the list.
/// </summary>
/// <remarks>
/// Fix groups are returned in priority order determined based on <see cref="ExtensionOrderAttribute"/>.
/// Priority for all <see cref="SuggestedActionSet"/>s containing fixes is set to <see cref="SuggestedActionSetPriority.Medium"/> by default.
/// The only exception is the case where a <see cref="SuggestedActionSet"/> only contains suppression fixes -
/// the priority of such <see cref="SuggestedActionSet"/>s is set to <see cref="SuggestedActionSetPriority.None"/> so that suppression fixes
/// always show up last after all other fixes (and refactorings) for the selected line of code.
/// </remarks>
private static ImmutableArray<SuggestedActionSet> PrioritizeFixGroups(
IDictionary<CodeFixGroupKey, IList<SuggestedAction>> map, IList<CodeFixGroupKey> order)
{
var sets = ArrayBuilder<SuggestedActionSet>.GetInstance();
foreach (var diag in order)
{
var actions = map[diag];
foreach (var group in actions.GroupBy(a => a.Priority))
{
var priority = GetSuggestedActionSetPriority(group.Key);
// diagnostic from things like build shouldn't reach here since we don't support LB for those diagnostics
Contract.Requires(diag.Item1.HasTextSpan);
sets.Add(new SuggestedActionSet(group, priority, diag.Item1.TextSpan.ToSpan()));
}
}
return sets.ToImmutableAndFree();
}
private static SuggestedActionSetPriority GetSuggestedActionSetPriority(CodeActionPriority key)
{
switch (key)
{
case CodeActionPriority.None: return SuggestedActionSetPriority.None;
case CodeActionPriority.Low: return SuggestedActionSetPriority.Low;
case CodeActionPriority.Medium: return SuggestedActionSetPriority.Medium;
case CodeActionPriority.High: return SuggestedActionSetPriority.High;
default:
throw new InvalidOperationException();
}
}
private ImmutableArray<SuggestedActionSet> GetRefactorings(
IDocumentSupportsFeatureService supportsFeatureService,
ISuggestedActionCategorySet requestedActionCategories,
Workspace workspace,
Document document,
SnapshotSpan range,
CancellationToken cancellationToken)
{
this.AssertIsForeground();
if (workspace.Options.GetOption(EditorComponentOnOffOptions.CodeRefactorings) &&
_owner._codeRefactoringService != null &&
supportsFeatureService.SupportsRefactorings(document) &&
requestedActionCategories.Contains(PredefinedSuggestedActionCategoryNames.Refactoring))
{
// Get the selection while on the UI thread.
var selection = TryGetCodeRefactoringSelection(_subjectBuffer, _textView, range);
if (!selection.HasValue)
{
// this is here to fail test and see why it is failed.
Trace.WriteLine("given range is not current");
return ImmutableArray<SuggestedActionSet>.Empty;
}
// It may seem strange that we kick off a task, but then immediately 'Wait' on
// it. However, it's deliberate. We want to make sure that the code runs on
// the background so that no one takes an accidently dependency on running on
// the UI thread.
var refactorings = Task.Run(
() => _owner._codeRefactoringService.GetRefactoringsAsync(
document, selection.Value, cancellationToken),
cancellationToken).WaitAndGetResult(cancellationToken);
var filteredRefactorings = FilterOnUIThread(refactorings, workspace);
return filteredRefactorings.SelectAsArray(r => OrganizeRefactorings(workspace, r));
}
return ImmutableArray<SuggestedActionSet>.Empty;
}
/// <summary>
/// Arrange refactorings into groups.
/// </summary>
/// <remarks>
/// Refactorings are returned in priority order determined based on <see cref="ExtensionOrderAttribute"/>.
/// Priority for all <see cref="SuggestedActionSet"/>s containing refactorings is set to <see cref="SuggestedActionSetPriority.Low"/>
/// and should show up after fixes but before suppression fixes in the light bulb menu.
/// </remarks>
private SuggestedActionSet OrganizeRefactorings(Workspace workspace, CodeRefactoring refactoring)
{
var refactoringSuggestedActions = ArrayBuilder<SuggestedAction>.GetInstance();
foreach (var action in refactoring.Actions)
{
refactoringSuggestedActions.Add(new CodeRefactoringSuggestedAction(
_owner, workspace, _subjectBuffer, refactoring.Provider, action));
}
return new SuggestedActionSet(
refactoringSuggestedActions.ToImmutableAndFree(), SuggestedActionSetPriority.Low);
}
public async Task<bool> HasSuggestedActionsAsync(ISuggestedActionCategorySet requestedActionCategories, SnapshotSpan range, CancellationToken cancellationToken)
{
// Explicitly hold onto below fields in locals and use these locals throughout this code path to avoid crashes
// if these fields happen to be cleared by Dispose() below. This is required since this code path involves
// code that can run asynchronously from background thread.
var view = _textView;
var buffer = _subjectBuffer;
var provider = _owner;
if (view == null || buffer == null || provider == null)
{
return false;
}
using (var asyncToken = provider.OperationListener.BeginAsyncOperation("HasSuggestedActionsAsync"))
{
var document = await GetMatchingDocumentAsync(range.Snapshot, cancellationToken).ConfigureAwait(false);
if (document == null)
{
// this is here to fail test and see why it is failed.
Trace.WriteLine("given range is not current");
return false;
}
var workspace = document.Project.Solution.Workspace;
var supportsFeatureService = workspace.Services.GetService<IDocumentSupportsFeatureService>();
return
await HasFixesAsync(
supportsFeatureService, requestedActionCategories, provider, document, range,
cancellationToken).ConfigureAwait(false) ||
await HasRefactoringsAsync(
supportsFeatureService, requestedActionCategories, provider, document, buffer, view, range,
cancellationToken).ConfigureAwait(false);
}
}
private async Task<bool> HasFixesAsync(
IDocumentSupportsFeatureService supportsFeatureService,
ISuggestedActionCategorySet requestedActionCategories,
SuggestedActionsSourceProvider provider,
Document document, SnapshotSpan range,
CancellationToken cancellationToken)
{
if (provider._codeFixService != null && supportsFeatureService.SupportsCodeFixes(document) &&
requestedActionCategories.Contains(PredefinedSuggestedActionCategoryNames.CodeFix))
{
// We only consider suppressions if lightbulb is asking for everything.
// If the light bulb is only asking for code fixes, then we don't consider suppressions.
var considerSuppressionFixes = requestedActionCategories.Contains(PredefinedSuggestedActionCategoryNames.Any);
var result = await Task.Run(
() => provider._codeFixService.GetFirstDiagnosticWithFixAsync(
document, range.Span.ToTextSpan(), considerSuppressionFixes, cancellationToken),
cancellationToken).ConfigureAwait(false);
if (result.HasFix)
{
Logger.Log(FunctionId.SuggestedActions_HasSuggestedActionsAsync);
return true;
}
if (result.PartialResult)
{
// reset solution version number so that we can raise suggested action changed event
Volatile.Write(ref _lastSolutionVersionReported, InvalidSolutionVersion);
return false;
}
}
return false;
}
private async Task<bool> HasRefactoringsAsync(
IDocumentSupportsFeatureService supportsFeatureService,
ISuggestedActionCategorySet requestedActionCategories,
SuggestedActionsSourceProvider provider,
Document document,
ITextBuffer buffer,
ITextView view,
SnapshotSpan range,
CancellationToken cancellationToken)
{
if (!requestedActionCategories.Contains(PredefinedSuggestedActionCategoryNames.Refactoring))
{
// See if we should still show the light bulb, even if we weren't explicitly
// asked for refactorings. We'll show the lightbulb if we're currently
// flighting the "Refactoring" A/B test, or if a special option is set
// enabling this internally.
var workspace = document.Project.Solution.Workspace;
var experimentationService = workspace.Services.GetService<IExperimentationService>();
if (!experimentationService.IsExperimentEnabled("Refactoring") &&
!workspace.Options.GetOption(EditorComponentOnOffOptions.ShowCodeRefactoringsWhenQueriedForCodeFixes))
{
return false;
}
}
if (document.Project.Solution.Options.GetOption(EditorComponentOnOffOptions.CodeRefactorings) &&
provider._codeRefactoringService != null &&
supportsFeatureService.SupportsRefactorings(document))
{
TextSpan? selection = null;
if (IsForeground())
{
// This operation needs to happen on UI thread because it needs to access textView.Selection.
selection = TryGetCodeRefactoringSelection(buffer, view, range);
}
else
{
await InvokeBelowInputPriority(() =>
{
// This operation needs to happen on UI thread because it needs to access textView.Selection.
selection = TryGetCodeRefactoringSelection(buffer, view, range);
}).ConfigureAwait(false);
}
if (!selection.HasValue)
{
// this is here to fail test and see why it is failed.
Trace.WriteLine("given range is not current");
return false;
}
return await Task.Run(
() => provider._codeRefactoringService.HasRefactoringsAsync(
document, selection.Value, cancellationToken),
cancellationToken).ConfigureAwait(false);
}
return false;
}
private static TextSpan? TryGetCodeRefactoringSelection(ITextBuffer buffer, ITextView view, SnapshotSpan range)
{
var selectedSpans = view.Selection.SelectedSpans
.SelectMany(ss => view.BufferGraph.MapDownToBuffer(ss, SpanTrackingMode.EdgeExclusive, buffer))
.Where(ss => !view.IsReadOnlyOnSurfaceBuffer(ss))
.ToList();
// We only support refactorings when there is a single selection in the document.
if (selectedSpans.Count != 1)
{
return null;
}
var translatedSpan = selectedSpans[0].TranslateTo(range.Snapshot, SpanTrackingMode.EdgeInclusive);
// We only support refactorings when selected span intersects with the span that the light bulb is asking for.
if (!translatedSpan.IntersectsWith(range))
{
return null;
}
return translatedSpan.Span.ToTextSpan();
}
private static async Task<Document> GetMatchingDocumentAsync(ITextSnapshot givenSnapshot, CancellationToken cancellationToken)
{
var buffer = givenSnapshot.TextBuffer;
if (buffer == null)
{
return null;
}
var workspace = buffer.GetWorkspace();
if (workspace == null)
{
return null;
}
var documentId = workspace.GetDocumentIdInCurrentContext(buffer.AsTextContainer());
if (documentId == null)
{
return null;
}
var document = workspace.CurrentSolution.GetDocument(documentId);
if (document == null)
{
return null;
}
var sourceText = await document.GetTextAsync(cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
var snapshot = sourceText.FindCorrespondingEditorTextSnapshot();
if (snapshot == null || snapshot.Version.ReiteratedVersionNumber != givenSnapshot.Version.ReiteratedVersionNumber)
{
return null;
}
return document;
}
private void OnTextViewClosed(object sender, EventArgs e)
{
Dispose();
}
private void OnWorkspaceChanged(object sender, EventArgs e)
{
// REVIEW: this event should give both old and new workspace as argument so that
// one doesn't need to hold onto workspace in field.
// remove existing event registration
if (_workspace != null)
{
_workspace.DocumentActiveContextChanged -= OnActiveContextChanged;
}
// REVIEW: why one need to get new workspace from registration? why not just pass in the new workspace?
// add new event registration
_workspace = _registration.Workspace;
if (_workspace != null)
{
_workspace.DocumentActiveContextChanged += OnActiveContextChanged;
}
}
private void OnActiveContextChanged(object sender, DocumentActiveContextChangedEventArgs e)
{
// REVIEW: it would be nice for changed event to pass in both old and new document.
OnSuggestedActionsChanged(e.Solution.Workspace, e.NewActiveContextDocumentId, e.Solution.WorkspaceVersion);
}
private void OnDiagnosticsUpdated(object sender, DiagnosticsUpdatedArgs e)
{
// document removed case. no reason to raise event
if (e.Solution == null)
{
return;
}
OnSuggestedActionsChanged(e.Workspace, e.DocumentId, e.Solution.WorkspaceVersion);
}
private void OnSuggestedActionsChanged(Workspace currentWorkspace, DocumentId currentDocumentId, int solutionVersion, DiagnosticsUpdatedArgs args = null)
{
// Explicitly hold onto the _subjectBuffer field in a local and use this local in this function to avoid crashes
// if this field happens to be cleared by Dispose() below. This is required since this code path involves code
// that can run on background thread.
var buffer = _subjectBuffer;
if (buffer == null)
{
return;
}
var workspace = buffer.GetWorkspace();
// workspace is not ready, nothing to do.
if (workspace == null || workspace != currentWorkspace)
{
return;
}
if (currentDocumentId != workspace.GetDocumentIdInCurrentContext(buffer.AsTextContainer()) ||
solutionVersion == Volatile.Read(ref _lastSolutionVersionReported))
{
return;
}
this.SuggestedActionsChanged?.Invoke(this, EventArgs.Empty);
Volatile.Write(ref _lastSolutionVersionReported, solutionVersion);
}
public void Dispose()
{
if (_owner != null)
{
var updateSource = (IDiagnosticUpdateSource)_owner._diagnosticService;
updateSource.DiagnosticsUpdated -= OnDiagnosticsUpdated;
_owner = null;
}
if (_workspace != null)
{
_workspace.DocumentActiveContextChanged -= OnActiveContextChanged;
_workspace = null;
}
if (_registration != null)
{
_registration.WorkspaceChanged -= OnWorkspaceChanged;
_registration = null;
}
if (_textView != null)
{
_textView.Closed -= OnTextViewClosed;
_textView = null;
}
if (_subjectBuffer != null)
{
_subjectBuffer = null;
}
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using Debug = System.Diagnostics.Debug;
namespace Internal.TypeSystem.Interop
{
public partial class NativeStructType : MetadataType
{
// The managed struct that this type will imitate
public MetadataType ManagedStructType
{
get;
}
public override ModuleDesc Module
{
get;
}
public override string Name
{
get
{
return "__NativeType__" + ManagedStructType.Name;
}
}
public override string Namespace
{
get
{
return "Internal.CompilerGenerated";
}
}
public override Instantiation Instantiation
{
get
{
return ManagedStructType.Instantiation;
}
}
public override PInvokeStringFormat PInvokeStringFormat
{
get
{
return ManagedStructType.PInvokeStringFormat;
}
}
public override bool IsExplicitLayout
{
get
{
return ManagedStructType.IsExplicitLayout;
}
}
public override bool IsSequentialLayout
{
get
{
return ManagedStructType.IsSequentialLayout;
}
}
public override bool IsBeforeFieldInit
{
get
{
return ManagedStructType.IsBeforeFieldInit;
}
}
public override MetadataType MetadataBaseType
{
get
{
return (MetadataType)Context.GetWellKnownType(WellKnownType.ValueType);
}
}
public override bool IsSealed
{
get
{
return true;
}
}
public override bool IsAbstract
{
get
{
return false;
}
}
public override DefType ContainingType
{
get
{
return null;
}
}
public override DefType[] ExplicitlyImplementedInterfaces
{
get
{
return Array.Empty<DefType>();
}
}
public override TypeSystemContext Context
{
get
{
return ManagedStructType.Context;
}
}
private NativeStructField[] _fields;
private InteropStateManager _interopStateManager;
private bool _hasInvalidLayout;
public bool HasInvalidLayout
{
get
{
return _hasInvalidLayout;
}
}
public FieldDesc[] Fields
{
get
{
return _fields;
}
}
public NativeStructType(ModuleDesc owningModule, MetadataType managedStructType, InteropStateManager interopStateManager)
{
Debug.Assert(managedStructType.IsTypeDefinition);
Debug.Assert(managedStructType.IsValueType);
Debug.Assert(!managedStructType.IsGenericDefinition);
Module = owningModule;
ManagedStructType = managedStructType;
_interopStateManager = interopStateManager;
_hasInvalidLayout = false;
CalculateFields();
}
private void CalculateFields()
{
bool isSequential = ManagedStructType.IsSequentialLayout;
MarshalAsDescriptor[] marshalAsDescriptors = ManagedStructType.GetFieldMarshalAsDescriptors();
bool isAnsi = ((MetadataType)ManagedStructType).PInvokeStringFormat == PInvokeStringFormat.AnsiClass;
int numFields = 0;
foreach (FieldDesc field in ManagedStructType.GetFields())
{
if (field.IsStatic)
{
continue;
}
numFields++;
}
_fields = new NativeStructField[numFields];
int index = 0;
foreach (FieldDesc field in ManagedStructType.GetFields())
{
if (field.IsStatic)
{
continue;
}
var managedType = field.FieldType;
TypeDesc nativeType;
try
{
nativeType = MarshalHelpers.GetNativeStructFieldType(managedType, marshalAsDescriptors[index], _interopStateManager, isAnsi);
}
catch (NotSupportedException)
{
// if marshalling is not supported for this type the generated stubs will emit appropriate
// error message. We just set native type to be same as managedtype
nativeType = managedType;
_hasInvalidLayout = true;
}
_fields[index++] = new NativeStructField(nativeType, this, field);
}
}
public override ClassLayoutMetadata GetClassLayout()
{
ClassLayoutMetadata layout = ManagedStructType.GetClassLayout();
ClassLayoutMetadata result;
result.PackingSize = layout.PackingSize;
result.Size = layout.Size;
if (IsExplicitLayout)
{
result.Offsets = new FieldAndOffset[layout.Offsets.Length];
Debug.Assert(layout.Offsets.Length <= _fields.Length);
int layoutIndex = 0;
for (int index = 0; index < _fields.Length; index++)
{
if (_fields[index].Name == layout.Offsets[layoutIndex].Field.Name)
{
result.Offsets[layoutIndex] = new FieldAndOffset(_fields[index], layout.Offsets[layoutIndex].Offset);
layoutIndex++;
}
}
Debug.Assert(layoutIndex == layout.Offsets.Length);
}
else
{
result.Offsets = null;
}
return result;
}
public override bool HasCustomAttribute(string attributeNamespace, string attributeName)
{
return false;
}
public override IEnumerable<MetadataType> GetNestedTypes()
{
return Array.Empty<MetadataType>();
}
public override MetadataType GetNestedType(string name)
{
return null;
}
protected override MethodImplRecord[] ComputeVirtualMethodImplsForType()
{
return Array.Empty<MethodImplRecord>();
}
public override MethodImplRecord[] FindMethodsImplWithMatchingDeclName(string name)
{
return Array.Empty<MethodImplRecord>();
}
private int _hashCode;
private void InitializeHashCode()
{
var hashCodeBuilder = new Internal.NativeFormat.TypeHashingAlgorithms.HashCodeBuilder(Namespace);
if (Namespace.Length > 0)
{
hashCodeBuilder.Append(".");
}
hashCodeBuilder.Append(Name);
_hashCode = hashCodeBuilder.ToHashCode();
}
public override int GetHashCode()
{
if (_hashCode == 0)
{
InitializeHashCode();
}
return _hashCode;
}
protected override TypeFlags ComputeTypeFlags(TypeFlags mask)
{
TypeFlags flags = 0;
if ((mask & TypeFlags.HasGenericVarianceComputed) != 0)
{
flags |= TypeFlags.HasGenericVarianceComputed;
}
if ((mask & TypeFlags.CategoryMask) != 0)
{
flags |= TypeFlags.ValueType;
}
flags |= TypeFlags.HasFinalizerComputed;
flags |= TypeFlags.AttributeCacheComputed;
return flags;
}
public override IEnumerable<FieldDesc> GetFields()
{
return _fields;
}
/// <summary>
/// Synthetic field on <see cref="NativeStructType"/>.
/// </summary>
private partial class NativeStructField : FieldDesc
{
private TypeDesc _fieldType;
private MetadataType _owningType;
private FieldDesc _managedField;
public override TypeSystemContext Context
{
get
{
return _owningType.Context;
}
}
public override TypeDesc FieldType
{
get
{
return _fieldType;
}
}
public override bool HasRva
{
get
{
return false;
}
}
public override bool IsInitOnly
{
get
{
return false;
}
}
public override bool IsLiteral
{
get
{
return false;
}
}
public override bool IsStatic
{
get
{
return false;
}
}
public override bool IsThreadStatic
{
get
{
return false;
}
}
public override DefType OwningType
{
get
{
return _owningType;
}
}
public override bool HasCustomAttribute(string attributeNamespace, string attributeName)
{
return false;
}
public override string Name
{
get
{
return _managedField.Name;
}
}
public NativeStructField(TypeDesc nativeType, MetadataType owningType, FieldDesc managedField)
{
_fieldType = nativeType;
_owningType = owningType;
_managedField = managedField;
}
}
}
}
| |
///////////////////////////////////////////////////////////////////////////////
//File: Wrapper_MyHuds.cs
//
//Description: Contains MetaViewWrapper classes implementing Virindi View Service
// views. These classes are only compiled if the VVS_REFERENCED symbol is defined.
//
//References required:
// System.Drawing
// VirindiViewService (if VVS_REFERENCED is defined)
//
//This file is Copyright (c) 2010 VirindiPlugins
//
//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 VVS_REFERENCED
using System;
using System.Collections.Generic;
using System.Text;
using VirindiViewService;
#if METAVIEW_PUBLIC_NS
namespace MetaViewWrappers.VirindiViewServiceHudControls
#else
namespace MyClasses.MetaViewWrappers.VirindiViewServiceHudControls
#endif
{
#if VVS_WRAPPERS_PUBLIC
public
#else
internal
#endif
class View : IView
{
HudView myView;
public HudView Underlying { get { return myView; } }
#region IView Members
public void Initialize(Decal.Adapter.Wrappers.PluginHost p, string pXML)
{
VirindiViewService.XMLParsers.Decal3XMLParser ps = new VirindiViewService.XMLParsers.Decal3XMLParser();
ViewProperties iprop;
ControlGroup igroup;
ps.ParseFromResource(pXML, out iprop, out igroup);
myView = new VirindiViewService.HudView(iprop, igroup);
}
public void InitializeRawXML(Decal.Adapter.Wrappers.PluginHost p, string pXML)
{
VirindiViewService.XMLParsers.Decal3XMLParser ps = new VirindiViewService.XMLParsers.Decal3XMLParser();
ViewProperties iprop;
ControlGroup igroup;
ps.Parse(pXML, out iprop, out igroup);
myView = new VirindiViewService.HudView(iprop, igroup);
}
public void SetIcon(int icon, int iconlibrary)
{
myView.Icon = ACImage.FromIconLibrary(icon, iconlibrary);
}
public void SetIcon(int portalicon)
{
myView.Icon = portalicon;
}
public string Title
{
get
{
return myView.Title;
}
set
{
myView.Title = value;
}
}
public bool Visible
{
get
{
return myView.Visible;
}
set
{
myView.Visible = value;
}
}
public bool Activated
{
get
{
return Visible;
}
set
{
Visible = value;
}
}
public void Activate()
{
Visible = true;
}
public void Deactivate()
{
Visible = false;
}
public System.Drawing.Point Location
{
get
{
return myView.Location;
}
set
{
myView.Location = value;
}
}
public System.Drawing.Size Size
{
get
{
return new System.Drawing.Size(myView.Width, myView.Height);
}
}
public System.Drawing.Rectangle Position
{
get
{
return new System.Drawing.Rectangle(Location, Size);
}
set
{
Location = value.Location;
myView.ClientArea = value.Size;
}
}
#if VVS_WRAPPERS_PUBLIC
internal
#else
public
#endif
ViewSystemSelector.eViewSystem ViewType { get { return ViewSystemSelector.eViewSystem.VirindiViewService; } }
public IControl this[string id]
{
get
{
Control ret = null;
VirindiViewService.Controls.HudControl iret = myView[id];
if (iret.GetType() == typeof(VirindiViewService.Controls.HudButton))
ret = new Button();
if (iret.GetType() == typeof(VirindiViewService.Controls.HudCheckBox))
ret = new CheckBox();
if (iret.GetType() == typeof(VirindiViewService.Controls.HudTextBox))
ret = new TextBox();
if (iret.GetType() == typeof(VirindiViewService.Controls.HudCombo))
ret = new Combo();
if (iret.GetType() == typeof(VirindiViewService.Controls.HudHSlider))
ret = new Slider();
if (iret.GetType() == typeof(VirindiViewService.Controls.HudList))
ret = new List();
if (iret.GetType() == typeof(VirindiViewService.Controls.HudStaticText))
ret = new StaticText();
if (iret.GetType() == typeof(VirindiViewService.Controls.HudTabView))
ret = new Notebook();
if (iret.GetType() == typeof(VirindiViewService.Controls.HudProgressBar))
ret = new ProgressBar();
if (ret == null) return null;
ret.myControl = iret;
ret.myName = id;
ret.Initialize();
allocatedcontrols.Add(ret);
return ret;
}
}
#endregion
#region IDisposable Members
bool disposed = false;
public void Dispose()
{
if (disposed) return;
disposed = true;
GC.SuppressFinalize(this);
foreach (Control c in allocatedcontrols)
c.Dispose();
myView.Dispose();
}
#endregion
List<Control> allocatedcontrols = new List<Control>();
}
#if VVS_WRAPPERS_PUBLIC
public
#else
internal
#endif
class Control : IControl
{
internal VirindiViewService.Controls.HudControl myControl;
internal string myName;
public VirindiViewService.Controls.HudControl Underlying { get { return myControl; } }
public virtual void Initialize()
{
}
#region IControl Members
public string Name
{
get { return myName; }
}
public bool Visible
{
get { return myControl.Visible; }
}
VirindiViewService.TooltipSystem.cTooltipInfo itooltipinfo = null;
public string TooltipText
{
get
{
if (itooltipinfo != null)
return itooltipinfo.Text;
else
return "";
}
set
{
if (itooltipinfo != null)
{
VirindiViewService.TooltipSystem.RemoveTooltip(itooltipinfo);
itooltipinfo = null;
}
if (!String.IsNullOrEmpty(value))
{
itooltipinfo = VirindiViewService.TooltipSystem.AssociateTooltip(myControl, value);
}
}
}
#endregion
#region IDisposable Members
bool disposed = false;
public virtual void Dispose()
{
if (disposed) return;
disposed = true;
myControl.Dispose();
}
#endregion
}
#if VVS_WRAPPERS_PUBLIC
public
#else
internal
#endif
class Button : Control, IButton
{
public override void Initialize()
{
base.Initialize();
((VirindiViewService.Controls.HudButton)myControl).MouseEvent += new EventHandler<VirindiViewService.Controls.ControlMouseEventArgs>(Button_MouseEvent);
}
public override void Dispose()
{
base.Dispose();
((VirindiViewService.Controls.HudButton)myControl).MouseEvent -= new EventHandler<VirindiViewService.Controls.ControlMouseEventArgs>(Button_MouseEvent);
}
void Button_MouseEvent(object sender, VirindiViewService.Controls.ControlMouseEventArgs e)
{
switch (e.EventType)
{
case VirindiViewService.Controls.ControlMouseEventArgs.MouseEventType.MouseHit:
if (Click != null)
Click(this, new MVControlEventArgs(0));
return;
case VirindiViewService.Controls.ControlMouseEventArgs.MouseEventType.MouseDown:
if (Hit != null)
Hit(this, null);
return;
}
}
#region IButton Members
public string Text
{
get
{
return ((VirindiViewService.Controls.HudButton)myControl).Text;
}
set
{
((VirindiViewService.Controls.HudButton)myControl).Text = value;
}
}
public System.Drawing.Color TextColor
{
get
{
return System.Drawing.Color.Black;
}
set
{
}
}
public event EventHandler Hit;
public event EventHandler<MVControlEventArgs> Click;
#endregion
}
#if VVS_WRAPPERS_PUBLIC
public
#else
internal
#endif
class CheckBox : Control, ICheckBox
{
public override void Initialize()
{
base.Initialize();
((VirindiViewService.Controls.HudCheckBox)myControl).Change += new EventHandler(CheckBox_Change);
}
public override void Dispose()
{
base.Dispose();
((VirindiViewService.Controls.HudCheckBox)myControl).Change -= new EventHandler(CheckBox_Change);
}
void CheckBox_Change(object sender, EventArgs e)
{
if (Change != null)
Change(this, new MVCheckBoxChangeEventArgs(0, Checked));
if (Change_Old != null)
Change_Old(this, null);
}
#region ICheckBox Members
public string Text
{
get
{
return ((VirindiViewService.Controls.HudCheckBox)myControl).Text;
}
set
{
((VirindiViewService.Controls.HudCheckBox)myControl).Text = value;
}
}
public bool Checked
{
get
{
return ((VirindiViewService.Controls.HudCheckBox)myControl).Checked;
}
set
{
((VirindiViewService.Controls.HudCheckBox)myControl).Checked = value;
}
}
public event EventHandler<MVCheckBoxChangeEventArgs> Change;
public event EventHandler Change_Old;
#endregion
}
#if VVS_WRAPPERS_PUBLIC
public
#else
internal
#endif
class TextBox : Control, ITextBox
{
public override void Initialize()
{
base.Initialize();
((VirindiViewService.Controls.HudTextBox)myControl).Change += new EventHandler(TextBox_Change);
myControl.LostFocus += new EventHandler(myControl_LostFocus);
}
public override void Dispose()
{
base.Dispose();
((VirindiViewService.Controls.HudTextBox)myControl).Change -= new EventHandler(TextBox_Change);
myControl.LostFocus -= new EventHandler(myControl_LostFocus);
}
void TextBox_Change(object sender, EventArgs e)
{
if (Change != null)
Change(this, new MVTextBoxChangeEventArgs(0, Text));
if (Change_Old != null)
Change_Old(this, null);
}
void myControl_LostFocus(object sender, EventArgs e)
{
if (!myControl.HasFocus) return;
if (End != null)
End(this, new MVTextBoxEndEventArgs(0, true));
}
#region ITextBox Members
public string Text
{
get
{
return ((VirindiViewService.Controls.HudTextBox)myControl).Text;
}
set
{
((VirindiViewService.Controls.HudTextBox)myControl).Text = value;
}
}
public int Caret
{
get
{
return 0;
}
set
{
}
}
public event EventHandler<MVTextBoxChangeEventArgs> Change;
public event EventHandler Change_Old;
public event EventHandler<MVTextBoxEndEventArgs> End;
#endregion
}
#if VVS_WRAPPERS_PUBLIC
public
#else
internal
#endif
class Combo : Control, ICombo
{
List<object> iData = new List<object>();
public class ComboIndexer : IComboIndexer
{
Combo underlying;
internal ComboIndexer(Combo c)
{
underlying = c;
}
#region IComboIndexer Members
public string this[int index]
{
get
{
return ((VirindiViewService.Controls.HudStaticText)(((VirindiViewService.Controls.HudCombo)underlying.myControl)[index])).Text;
}
set
{
((VirindiViewService.Controls.HudStaticText)(((VirindiViewService.Controls.HudCombo)underlying.myControl)[index])).Text = value;
}
}
#endregion
}
public class ComboDataIndexer : IComboDataIndexer
{
Combo underlying;
internal ComboDataIndexer(Combo c)
{
underlying = c;
}
#region IComboIndexer Members
public object this[int index]
{
get
{
return underlying.iData[index];
}
set
{
underlying.iData[index] = value;
}
}
#endregion
}
public override void Initialize()
{
base.Initialize();
((VirindiViewService.Controls.HudCombo)myControl).Change += new EventHandler(Combo_Change);
}
public override void Dispose()
{
base.Dispose();
((VirindiViewService.Controls.HudCombo)myControl).Change -= new EventHandler(Combo_Change);
}
void Combo_Change(object sender, EventArgs e)
{
if (Change != null)
Change(this, new MVIndexChangeEventArgs(0, Selected));
if (Change_Old != null)
Change_Old(this, null);
}
#region ICombo Members
public IComboIndexer Text
{
get { return new ComboIndexer(this); }
}
public IComboDataIndexer Data
{
get { return new ComboDataIndexer(this); }
}
public int Count
{
get { return ((VirindiViewService.Controls.HudCombo)myControl).Count; }
}
public int Selected
{
get
{
return ((VirindiViewService.Controls.HudCombo)myControl).Current;
}
set
{
((VirindiViewService.Controls.HudCombo)myControl).Current = value;
}
}
public event EventHandler<MVIndexChangeEventArgs> Change;
public event EventHandler Change_Old;
public void Add(string text)
{
((VirindiViewService.Controls.HudCombo)myControl).AddItem(text, null);
iData.Add(null);
}
public void Add(string text, object obj)
{
((VirindiViewService.Controls.HudCombo)myControl).AddItem(text, null);
iData.Add(obj);
}
public void Insert(int index, string text)
{
((VirindiViewService.Controls.HudCombo)myControl).InsertItem(index, text, null);
iData.Insert(index, null);
}
public void RemoveAt(int index)
{
((VirindiViewService.Controls.HudCombo)myControl).DeleteItem(index);
iData.RemoveAt(index);
}
public void Remove(int index)
{
RemoveAt(index);
}
public void Clear()
{
((VirindiViewService.Controls.HudCombo)myControl).Clear();
iData.Clear();
}
#endregion
}
#if VVS_WRAPPERS_PUBLIC
public
#else
internal
#endif
class Slider : Control, ISlider
{
public override void Initialize()
{
base.Initialize();
((VirindiViewService.Controls.HudHSlider)myControl).Changed += new VirindiViewService.Controls.LinearPositionControl.delScrollChanged(Slider_Changed);
}
public override void Dispose()
{
base.Dispose();
((VirindiViewService.Controls.HudHSlider)myControl).Changed -= new VirindiViewService.Controls.LinearPositionControl.delScrollChanged(Slider_Changed);
}
void Slider_Changed(int min, int max, int pos)
{
if (Change != null)
Change(this, new MVIndexChangeEventArgs(0, pos));
if (Change_Old != null)
Change_Old(this, null);
}
#region ISlider Members
public int Position
{
get
{
return ((VirindiViewService.Controls.HudHSlider)myControl).Position;
}
set
{
((VirindiViewService.Controls.HudHSlider)myControl).Position = value;
}
}
public event EventHandler<MVIndexChangeEventArgs> Change;
public event EventHandler Change_Old;
#endregion
}
#if VVS_WRAPPERS_PUBLIC
public
#else
internal
#endif
class List : Control, IList
{
public override void Initialize()
{
base.Initialize();
((VirindiViewService.Controls.HudList)myControl).Click += new VirindiViewService.Controls.HudList.delClickedControl(List_Click);
}
public override void Dispose()
{
base.Dispose();
((VirindiViewService.Controls.HudList)myControl).Click -= new VirindiViewService.Controls.HudList.delClickedControl(List_Click);
}
void List_Click(object sender, int row, int col)
{
if (Click != null)
Click(this, row, col);
if (Selected != null)
Selected(this, new MVListSelectEventArgs(0, row, col));
}
public class ListRow : IListRow
{
List myList;
int myRow;
internal ListRow(int row, List l)
{
myList = l;
myRow = row;
}
#region IListRow Members
public IListCell this[int col]
{
get { return new ListCell(myRow, col, myList); }
}
#endregion
}
public class ListCell : IListCell
{
List myList;
int myRow;
int myCol;
internal ListCell(int row, int col, List l)
{
myRow = row;
myCol = col;
myList = l;
}
#region IListCell Members
public void ResetColor()
{
((VirindiViewService.Controls.HudStaticText)(((VirindiViewService.Controls.HudList)myList.myControl)[myRow][myCol])).ResetTextColor();
}
public System.Drawing.Color Color
{
get
{
return ((VirindiViewService.Controls.HudStaticText)(((VirindiViewService.Controls.HudList)myList.myControl)[myRow][myCol])).TextColor;
}
set
{
((VirindiViewService.Controls.HudStaticText)(((VirindiViewService.Controls.HudList)myList.myControl)[myRow][myCol])).TextColor = value;
}
}
public int Width
{
get
{
return ((VirindiViewService.Controls.HudStaticText)(((VirindiViewService.Controls.HudList)myList.myControl)[myRow][myCol])).ClipRegion.Width;
}
set
{
throw new Exception("The method or operation is not implemented.");
}
}
public object this[int subval]
{
get
{
VirindiViewService.Controls.HudControl c = ((VirindiViewService.Controls.HudList)myList.myControl)[myRow][myCol];
if (subval == 0)
{
if (c.GetType() == typeof(VirindiViewService.Controls.HudStaticText))
return ((VirindiViewService.Controls.HudStaticText)c).Text;
if (c.GetType() == typeof(VirindiViewService.Controls.HudCheckBox))
return ((VirindiViewService.Controls.HudCheckBox)c).Checked;
}
else if (subval == 1)
{
if (c.GetType() == typeof(VirindiViewService.Controls.HudPictureBox))
return ((VirindiViewService.Controls.HudPictureBox)c).Image.PortalImageID;
}
return null;
}
set
{
VirindiViewService.Controls.HudControl c = ((VirindiViewService.Controls.HudList)myList.myControl)[myRow][myCol];
if (subval == 0)
{
if (c.GetType() == typeof(VirindiViewService.Controls.HudStaticText))
((VirindiViewService.Controls.HudStaticText)c).Text = (string)value;
if (c.GetType() == typeof(VirindiViewService.Controls.HudCheckBox))
((VirindiViewService.Controls.HudCheckBox)c).Checked = (bool)value;
}
else if (subval == 1)
{
if (c.GetType() == typeof(VirindiViewService.Controls.HudPictureBox))
((VirindiViewService.Controls.HudPictureBox)c).Image = (int)value;
}
}
}
#endregion
}
#region IList Members
public event dClickedList Click;
public event EventHandler<MVListSelectEventArgs> Selected;
public void Clear()
{
((VirindiViewService.Controls.HudList)myControl).ClearRows();
}
public IListRow this[int row]
{
get { return new ListRow(row, this); }
}
public IListRow AddRow()
{
((VirindiViewService.Controls.HudList)myControl).AddRow();
return new ListRow(((VirindiViewService.Controls.HudList)myControl).RowCount - 1, this);
}
public IListRow Add()
{
return AddRow();
}
public IListRow InsertRow(int pos)
{
((VirindiViewService.Controls.HudList)myControl).InsertRow(pos);
return new ListRow(pos, this);
}
public IListRow Insert(int pos)
{
return InsertRow(pos);
}
public int RowCount
{
get { return ((VirindiViewService.Controls.HudList)myControl).RowCount; }
}
public void RemoveRow(int index)
{
((VirindiViewService.Controls.HudList)myControl).RemoveRow(index);
}
public void Delete(int index)
{
RemoveRow(index);
}
public int ColCount
{
get
{
return 0;
//return ((VirindiViewService.Controls.HudList)myControl).ColumnCount;
}
}
public int ScrollPosition
{
get
{
return ((VirindiViewService.Controls.HudList)myControl).ScrollPosition;
}
set
{
((VirindiViewService.Controls.HudList)myControl).ScrollPosition = value;
}
}
#endregion
}
#if VVS_WRAPPERS_PUBLIC
public
#else
internal
#endif
class StaticText : Control, IStaticText
{
public override void Initialize()
{
base.Initialize();
//((VirindiViewService.Controls.HudStaticText)myControl)
}
public override void Dispose()
{
base.Dispose();
}
#region IStaticText Members
public string Text
{
get
{
return ((VirindiViewService.Controls.HudStaticText)myControl).Text;
}
set
{
((VirindiViewService.Controls.HudStaticText)myControl).Text = value;
}
}
#pragma warning disable 0067
public event EventHandler<MVControlEventArgs> Click;
#pragma warning restore 0067
#endregion
}
#if VVS_WRAPPERS_PUBLIC
public
#else
internal
#endif
class Notebook : Control, INotebook
{
public override void Initialize()
{
base.Initialize();
((VirindiViewService.Controls.HudTabView)myControl).OpenTabChange += new EventHandler(Notebook_OpenTabChange);
}
public override void Dispose()
{
((VirindiViewService.Controls.HudTabView)myControl).OpenTabChange -= new EventHandler(Notebook_OpenTabChange);
base.Dispose();
}
void Notebook_OpenTabChange(object sender, EventArgs e)
{
if (Change != null)
Change(this, new MVIndexChangeEventArgs(0, ActiveTab));
}
#region INotebook Members
public event EventHandler<MVIndexChangeEventArgs> Change;
public int ActiveTab
{
get
{
return ((VirindiViewService.Controls.HudTabView)myControl).CurrentTab;
}
set
{
((VirindiViewService.Controls.HudTabView)myControl).CurrentTab = value;
((VirindiViewService.Controls.HudTabView)myControl).Invalidate();
}
}
#endregion
}
#if VVS_WRAPPERS_PUBLIC
public
#else
internal
#endif
class ProgressBar : Control, IProgressBar
{
#region IProgressBar Members
public int Position
{
get
{
return ((VirindiViewService.Controls.HudProgressBar)myControl).Position;
}
set
{
((VirindiViewService.Controls.HudProgressBar)myControl).Position = value;
}
}
public int Value
{
get
{
return Position;
}
set
{
Position = value;
}
}
public string PreText
{
get
{
return ((VirindiViewService.Controls.HudProgressBar)myControl).PreText;
}
set
{
((VirindiViewService.Controls.HudProgressBar)myControl).PreText = value;
}
}
#endregion
}
}
#endif
| |
// Copyright (c) DotSpatial Team. All rights reserved.
// Licensed under the MIT license. See License.txt file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Drawing2D;
using DotSpatial.Data;
using DotSpatial.Serialization;
namespace DotSpatial.Symbology
{
/// <summary>
/// This is a class that organizes a list of renderable layers into a single "view" which might be
/// shared by multiple displays. For instance, if you have a map control and a print preview control,
/// you could draw the same data frame property on both, just by passing the graphics object for each.
/// Be sure to handle any scaling or translation that you require through the Transform property
/// of the graphics object as it will ultimately be that scale which is used to back-calculate the
/// appropriate pixel sizes for point-size, line-width and other non-georeferenced characteristics.
/// </summary>
public abstract class LayerFrame : Group, IFrame
{
#region Fields
private int _extentChangedSuspensionCount;
private bool _extentsChanged;
[Serialize("ViewExtents")]
private Extent _viewExtents;
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="LayerFrame"/> class.
/// </summary>
protected LayerFrame()
{
Configure();
}
/// <summary>
/// Initializes a new instance of the <see cref="LayerFrame"/> class.
/// </summary>
/// <param name="container">The parent of this frame.</param>
protected LayerFrame(IContainer container)
{
Parent = container;
Configure();
}
#endregion
#region Events
/// <summary>
/// Occurs when the visible region being displayed on the map should update
/// </summary>
public event EventHandler UpdateMap;
/// <summary>
/// Occurs after zooming to a specific location on the map and causes a camera recent.
/// </summary>
public event EventHandler<ExtentArgs> ViewExtentsChanged;
#endregion
#region Properties
/// <summary>
/// Gets or sets the drawing layers. Drawing layers are tracked separately, and do not appear in the legend.
/// </summary>
public List<ILayer> DrawingLayers { get; set; }
/// <summary>
/// Gets the extent. Overrides the default behavior for groups, which should return null in the
/// event that they have no layers, with a more tolerant, getting started
/// behavior where geographic coordinates are assumed.
/// </summary>
public override Extent Extent
{
get
{
if (base.Extent == null)
{
return new Extent(-180, -90, 180, 90);
}
return base.Extent;
}
}
/// <inheritdoc />
[Serialize("ExtentsInitialized")]
public bool ExtentsInitialized { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the drawing function will render anything.
/// Warning! If false this will also prevent any execution of calculations that take place
/// as part of the drawing methods and will also abort the drawing methods of any
/// sub-members to this IRenderable.
/// </summary>
public override bool IsVisible
{
get
{
return base.IsVisible;
}
set
{
if (base.IsVisible == value) return;
// switching values
base.IsVisible = value;
OnItemChanged();
}
}
/// <summary>
/// Gets the container control that this MapFrame belongs to.
/// </summary>
public IContainer Parent { get; }
/// <summary>
/// Gets the currently selected layer. This will be an active layer that is used for operations.
/// </summary>
public ILayer SelectedLayer => Layers?.SelectedLayer;
/// <summary>
/// Gets or sets the smoothing mode. Default or None will have faster performance
/// at the cost of quality.
/// </summary>
public SmoothingMode SmoothingMode { get; set; } = SmoothingMode.AntiAlias;
/// <summary>
/// Gets or sets the geographic extents visible in the map.
/// </summary>
public virtual Extent ViewExtents
{
get
{
return _viewExtents ?? (_viewExtents = Extent != null ? Extent.Copy() : new Extent(-180, -90, 180, 90));
}
set
{
_viewExtents = value;
_extentsChanged = true;
if (_extentChangedSuspensionCount == 0)
{
OnExtentsChanged(_viewExtents);
}
}
}
#endregion
#region Methods
/// <summary>
/// This will create a new layer from the featureset and add it.
/// </summary>
/// <param name="featureSet">Any valid IFeatureSet that does not yet have drawing characteristics</param>
public virtual void Add(IFeatureSet featureSet)
{
// this should be overridden in subclasses
}
/// <summary>
/// Draws the layers icon to the legend
/// </summary>
/// <param name="g">Graphics object used for drawing.</param>
/// <param name="box">Rectangle used for drawing.</param>
public override void LegendSymbolPainted(Graphics g, Rectangle box)
{
g.DrawIcon(SymbologyImages.Layers, box);
}
/// <summary>
/// This is responsible for wiring the ZoomToLayer event from any layers
/// in the map frame whenever the layer collection is changed.
/// </summary>
/// <param name="collection">Collection the events get wired to.</param>
protected override void HandleLayerEvents(ILayerEvents collection)
{
if (collection == null) return;
collection.ZoomToLayer += LayersZoomToLayer;
collection.LayerAdded += LayersLayerAdded;
collection.LayerRemoved += LayersLayerRemoved;
base.HandleLayerEvents(collection);
}
/// <summary>
/// This is responsible for unwiring the ZoomToLayer event.
/// </summary>
/// <param name="collection">Collection the events get unwired from.</param>
protected override void IgnoreLayerEvents(ILayerEvents collection)
{
if (collection == null) return;
collection.ZoomToLayer -= LayersZoomToLayer;
collection.LayerAdded -= LayersLayerAdded;
collection.LayerRemoved -= LayersLayerRemoved;
base.IgnoreLayerEvents(collection);
}
/// <summary>
/// Zooms to the envelope if no envelope has been established for this frame.
/// </summary>
/// <param name="sender">Sender that raised the event.</param>
/// <param name="e">The event args.</param>
protected virtual void LayersLayerAdded(object sender, LayerEventArgs e)
{
if (ExtentsInitialized) return;
ExtentsInitialized = true;
if (e.Layer != null)
{
ViewExtents = e.Layer.Extent.Copy();
ViewExtents.ExpandBy(e.Layer.Extent.Width / 10, e.Layer.Extent.Height / 10);
}
}
/// <summary>
/// This adjusts the extents when ZoomToLayer is called in one of the internal layers.
/// </summary>
/// <param name="sender">Sender that raised the event.</param>
/// <param name="e">The event args.</param>
protected virtual void LayersZoomToLayer(object sender, EnvelopeArgs e)
{
ViewExtents = e.Envelope.ToExtent();
}
/// <summary>
/// Fires the ExtentsChanged event
/// </summary>
/// <param name="ext">The new extent.</param>
protected virtual void OnExtentsChanged(Extent ext)
{
if (_extentChangedSuspensionCount > 0) return;
ViewExtentsChanged?.Invoke(this, new ExtentArgs(ext));
}
/// <summary>
/// Fires the ExtentsChanged event
/// </summary>
protected virtual void OnUpdateMap()
{
UpdateMap?.Invoke(this, EventArgs.Empty);
}
/// <summary>
/// Resumes firing the method, and will fire it automatically if any changes have occurred.
/// </summary>
protected void ResumeExtentChanged()
{
_extentChangedSuspensionCount--;
if (_extentChangedSuspensionCount == 0)
{
if (_extentsChanged)
{
OnExtentsChanged(_viewExtents);
}
}
}
/// <summary>
/// Suspends firing the ExtentsChanges event. It only fires if all suspension is gone.
/// </summary>
protected void SuspendExtentChanged()
{
if (_extentChangedSuspensionCount == 0) _extentsChanged = false;
_extentChangedSuspensionCount++;
}
private void Configure()
{
Layers = new LayerCollection(this);
LegendText = SymbologyMessageStrings.LayerFrame_Map_Layers;
ContextMenuItems = new List<SymbologyMenuItem>
{
new SymbologyMenuItem(SymbologyMessageStrings.LayerFrame_ZoomToMapFrame, ZoomToMapFrameClick),
new SymbologyMenuItem(SymbologyMessageStrings.LayerFrame_CreateGroup, CreateGroupClick)
};
LegendSymbolMode = SymbolMode.GroupSymbol;
LegendType = LegendType.Group;
MapFrame = this;
ParentGroup = this;
DrawingLayers = new List<ILayer>();
}
private void CreateGroupClick(object sender, EventArgs e)
{
OnCreateGroup();
}
private void LayersLayerRemoved(object sender, LayerEventArgs e)
{
if (GetLayerCount(true) == 0)
{
ExtentsInitialized = false;
}
}
private void ZoomToMapFrameClick(object sender, EventArgs e)
{
// work item #42
// to prevent exception when zoom to map with one layer with one point
const double Eps = 1e-7;
var maxExtent = Extent.Width < Eps || Extent.Height < Eps ? new Extent(Extent.MinX - Eps, Extent.MinY - Eps, Extent.MaxX + Eps, Extent.MaxY + Eps) : Extent;
maxExtent.ExpandBy(maxExtent.Width / 10, maxExtent.Height / 10); // work item #84
ViewExtents = maxExtent;
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Data.Common;
using System.IO;
using System.Runtime.Serialization;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;
using System.Runtime.CompilerServices;
namespace System.Data.SqlTypes
{
internal enum SqlBytesCharsState
{
Null = 0,
Buffer = 1,
//IntPtr = 2,
Stream = 3,
}
[XmlSchemaProvider("GetXsdType")]
public sealed class SqlBytes : INullable, IXmlSerializable, ISerializable
{
// --------------------------------------------------------------
// Data members
// --------------------------------------------------------------
// SqlBytes has five possible states
// 1) SqlBytes is Null
// - m_stream must be null, m_lCuLen must be x_lNull.
// 2) SqlBytes contains a valid buffer,
// - m_rgbBuf must not be null,m_stream must be null
// 3) SqlBytes contains a valid pointer
// - m_rgbBuf could be null or not,
// if not null, content is garbage, should never look into it.
// - m_stream must be null.
// 4) SqlBytes contains a Stream
// - m_stream must not be null
// - m_rgbBuf could be null or not. if not null, content is garbage, should never look into it.
// - m_lCurLen must be x_lNull.
// 5) SqlBytes contains a Lazy Materialized Blob (ie, StorageState.Delayed)
//
internal byte[] _rgbBuf; // Data buffer
private long _lCurLen; // Current data length
internal Stream _stream;
private SqlBytesCharsState _state;
private byte[] _rgbWorkBuf; // A 1-byte work buffer.
// The max data length that we support at this time.
private const long x_lMaxLen = System.Int32.MaxValue;
private const long x_lNull = -1L;
// --------------------------------------------------------------
// Constructor(s)
// --------------------------------------------------------------
// Public default constructor used for XML serialization
public SqlBytes()
{
SetNull();
}
// Create a SqlBytes with an in-memory buffer
public SqlBytes(byte[] buffer)
{
_rgbBuf = buffer;
_stream = null;
if (_rgbBuf == null)
{
_state = SqlBytesCharsState.Null;
_lCurLen = x_lNull;
}
else
{
_state = SqlBytesCharsState.Buffer;
_lCurLen = _rgbBuf.Length;
}
_rgbWorkBuf = null;
AssertValid();
}
// Create a SqlBytes from a SqlBinary
public SqlBytes(SqlBinary value) : this(value.IsNull ? null : value.Value)
{
}
public SqlBytes(Stream s)
{
// Create a SqlBytes from a Stream
_rgbBuf = null;
_lCurLen = x_lNull;
_stream = s;
_state = (s == null) ? SqlBytesCharsState.Null : SqlBytesCharsState.Stream;
_rgbWorkBuf = null;
AssertValid();
}
// Constructor required for serialization. Deserializes as a Buffer. If the bits have been tampered with
// then this will throw a SerializationException or a InvalidCastException.
private SqlBytes(SerializationInfo info, StreamingContext context)
{
_stream = null;
_rgbWorkBuf = null;
if (info.GetBoolean("IsNull"))
{
_state = SqlBytesCharsState.Null;
_rgbBuf = null;
}
else
{
_state = SqlBytesCharsState.Buffer;
_rgbBuf = (byte[])info.GetValue("data", typeof(byte[]));
_lCurLen = _rgbBuf.Length;
}
AssertValid();
}
// --------------------------------------------------------------
// Public properties
// --------------------------------------------------------------
// INullable
public bool IsNull
{
get
{
return _state == SqlBytesCharsState.Null;
}
}
// Property: the in-memory buffer of SqlBytes
// Return Buffer even if SqlBytes is Null.
public byte[] Buffer
{
get
{
if (FStream())
{
CopyStreamToBuffer();
}
return _rgbBuf;
}
}
// Property: the actual length of the data
public long Length
{
get
{
switch (_state)
{
case SqlBytesCharsState.Null:
throw new SqlNullValueException();
case SqlBytesCharsState.Stream:
return _stream.Length;
default:
return _lCurLen;
}
}
}
// Property: the max length of the data
// Return MaxLength even if SqlBytes is Null.
// When the buffer is also null, return -1.
// If containing a Stream, return -1.
public long MaxLength
{
get
{
switch (_state)
{
case SqlBytesCharsState.Stream:
return -1L;
default:
return (_rgbBuf == null) ? -1L : _rgbBuf.Length;
}
}
}
// Property: get a copy of the data in a new byte[] array.
public byte[] Value
{
get
{
byte[] buffer;
switch (_state)
{
case SqlBytesCharsState.Null:
throw new SqlNullValueException();
case SqlBytesCharsState.Stream:
if (_stream.Length > x_lMaxLen)
throw new SqlTypeException(SR.SqlMisc_BufferInsufficientMessage);
buffer = new byte[_stream.Length];
if (_stream.Position != 0)
_stream.Seek(0, SeekOrigin.Begin);
_stream.Read(buffer, 0, checked((int)_stream.Length));
break;
default:
buffer = new byte[_lCurLen];
Array.Copy(_rgbBuf, 0, buffer, 0, (int)_lCurLen);
break;
}
return buffer;
}
}
// class indexer
public byte this[long offset]
{
get
{
if (offset < 0 || offset >= Length)
throw new ArgumentOutOfRangeException(nameof(offset));
if (_rgbWorkBuf == null)
_rgbWorkBuf = new byte[1];
Read(offset, _rgbWorkBuf, 0, 1);
return _rgbWorkBuf[0];
}
set
{
if (_rgbWorkBuf == null)
_rgbWorkBuf = new byte[1];
_rgbWorkBuf[0] = value;
Write(offset, _rgbWorkBuf, 0, 1);
}
}
public StorageState Storage
{
get
{
switch (_state)
{
case SqlBytesCharsState.Null:
throw new SqlNullValueException();
case SqlBytesCharsState.Stream:
return StorageState.Stream;
case SqlBytesCharsState.Buffer:
return StorageState.Buffer;
default:
return StorageState.UnmanagedBuffer;
}
}
}
public Stream Stream
{
get
{
return FStream() ? _stream : new StreamOnSqlBytes(this);
}
set
{
_lCurLen = x_lNull;
_stream = value;
_state = (value == null) ? SqlBytesCharsState.Null : SqlBytesCharsState.Stream;
AssertValid();
}
}
// --------------------------------------------------------------
// Public methods
// --------------------------------------------------------------
public void SetNull()
{
_lCurLen = x_lNull;
_stream = null;
_state = SqlBytesCharsState.Null;
AssertValid();
}
// Set the current length of the data
// If the SqlBytes is Null, setLength will make it non-Null.
public void SetLength(long value)
{
if (value < 0)
throw new ArgumentOutOfRangeException(nameof(value));
if (FStream())
{
_stream.SetLength(value);
}
else
{
// If there is a buffer, even the value of SqlBytes is Null,
// still allow setting length to zero, which will make it not Null.
// If the buffer is null, raise exception
//
if (null == _rgbBuf)
throw new SqlTypeException(SR.SqlMisc_NoBufferMessage);
if (value > _rgbBuf.Length)
throw new ArgumentOutOfRangeException(nameof(value));
else if (IsNull)
// At this point we know that value is small enough
// Go back in buffer mode
_state = SqlBytesCharsState.Buffer;
_lCurLen = value;
}
AssertValid();
}
// Read data of specified length from specified offset into a buffer
public long Read(long offset, byte[] buffer, int offsetInBuffer, int count)
{
if (IsNull)
throw new SqlNullValueException();
// Validate the arguments
if (buffer == null)
throw new ArgumentNullException(nameof(buffer));
if (offset > Length || offset < 0)
throw new ArgumentOutOfRangeException(nameof(offset));
if (offsetInBuffer > buffer.Length || offsetInBuffer < 0)
throw new ArgumentOutOfRangeException(nameof(offsetInBuffer));
if (count < 0 || count > buffer.Length - offsetInBuffer)
throw new ArgumentOutOfRangeException(nameof(count));
// Adjust count based on data length
if (count > Length - offset)
count = (int)(Length - offset);
if (count != 0)
{
switch (_state)
{
case SqlBytesCharsState.Stream:
if (_stream.Position != offset)
_stream.Seek(offset, SeekOrigin.Begin);
_stream.Read(buffer, offsetInBuffer, count);
break;
default:
Array.Copy(_rgbBuf, offset, buffer, offsetInBuffer, count);
break;
}
}
return count;
}
// Write data of specified length into the SqlBytes from specified offset
public void Write(long offset, byte[] buffer, int offsetInBuffer, int count)
{
if (FStream())
{
if (_stream.Position != offset)
_stream.Seek(offset, SeekOrigin.Begin);
_stream.Write(buffer, offsetInBuffer, count);
}
else
{
// Validate the arguments
if (buffer == null)
throw new ArgumentNullException(nameof(buffer));
if (_rgbBuf == null)
throw new SqlTypeException(SR.SqlMisc_NoBufferMessage);
if (offset < 0)
throw new ArgumentOutOfRangeException(nameof(offset));
if (offset > _rgbBuf.Length)
throw new SqlTypeException(SR.SqlMisc_BufferInsufficientMessage);
if (offsetInBuffer < 0 || offsetInBuffer > buffer.Length)
throw new ArgumentOutOfRangeException(nameof(offsetInBuffer));
if (count < 0 || count > buffer.Length - offsetInBuffer)
throw new ArgumentOutOfRangeException(nameof(count));
if (count > _rgbBuf.Length - offset)
throw new SqlTypeException(SR.SqlMisc_BufferInsufficientMessage);
if (IsNull)
{
// If NULL and there is buffer inside, we only allow writing from
// offset zero.
//
if (offset != 0)
throw new SqlTypeException(SR.SqlMisc_WriteNonZeroOffsetOnNullMessage);
// treat as if our current length is zero.
// Note this has to be done after all inputs are validated, so that
// we won't throw exception after this point.
//
_lCurLen = 0;
_state = SqlBytesCharsState.Buffer;
}
else if (offset > _lCurLen)
{
// Don't allow writing from an offset that this larger than current length.
// It would leave uninitialized data in the buffer.
//
throw new SqlTypeException(SR.SqlMisc_WriteOffsetLargerThanLenMessage);
}
if (count != 0)
{
Array.Copy(buffer, offsetInBuffer, _rgbBuf, offset, count);
// If the last position that has been written is after
// the current data length, reset the length
if (_lCurLen < offset + count)
_lCurLen = offset + count;
}
}
AssertValid();
}
public SqlBinary ToSqlBinary()
{
return IsNull ? SqlBinary.Null : new SqlBinary(Value);
}
// --------------------------------------------------------------
// Conversion operators
// --------------------------------------------------------------
// Alternative method: ToSqlBinary()
public static explicit operator SqlBinary(SqlBytes value)
{
return value.ToSqlBinary();
}
// Alternative method: constructor SqlBytes(SqlBinary)
public static explicit operator SqlBytes(SqlBinary value)
{
return new SqlBytes(value);
}
// --------------------------------------------------------------
// Private utility functions
// --------------------------------------------------------------
[Conditional("DEBUG")]
private void AssertValid()
{
Debug.Assert(_state >= SqlBytesCharsState.Null && _state <= SqlBytesCharsState.Stream);
if (IsNull)
{
}
else
{
Debug.Assert((_lCurLen >= 0 && _lCurLen <= x_lMaxLen) || FStream());
Debug.Assert(FStream() || (_rgbBuf != null && _lCurLen <= _rgbBuf.Length));
Debug.Assert(!FStream() || (_lCurLen == x_lNull));
}
Debug.Assert(_rgbWorkBuf == null || _rgbWorkBuf.Length == 1);
}
// Copy the data from the Stream to the array buffer.
// If the SqlBytes doesn't hold a buffer or the buffer
// is not big enough, allocate new byte array.
private void CopyStreamToBuffer()
{
Debug.Assert(FStream());
long lStreamLen = _stream.Length;
if (lStreamLen >= x_lMaxLen)
throw new SqlTypeException(SR.SqlMisc_WriteOffsetLargerThanLenMessage);
if (_rgbBuf == null || _rgbBuf.Length < lStreamLen)
_rgbBuf = new byte[lStreamLen];
if (_stream.Position != 0)
_stream.Seek(0, SeekOrigin.Begin);
_stream.Read(_rgbBuf, 0, (int)lStreamLen);
_stream = null;
_lCurLen = lStreamLen;
_state = SqlBytesCharsState.Buffer;
AssertValid();
}
// whether the SqlBytes contains a pointer
// whether the SqlBytes contains a Stream
internal bool FStream()
{
return _state == SqlBytesCharsState.Stream;
}
private void SetBuffer(byte[] buffer)
{
_rgbBuf = buffer;
_lCurLen = (_rgbBuf == null) ? x_lNull : _rgbBuf.Length;
_stream = null;
_state = (_rgbBuf == null) ? SqlBytesCharsState.Null : SqlBytesCharsState.Buffer;
AssertValid();
}
// --------------------------------------------------------------
// XML Serialization
// --------------------------------------------------------------
XmlSchema IXmlSerializable.GetSchema()
{
return null;
}
void IXmlSerializable.ReadXml(XmlReader r)
{
byte[] value = null;
string isNull = r.GetAttribute("nil", XmlSchema.InstanceNamespace);
if (isNull != null && XmlConvert.ToBoolean(isNull))
{
// Read the next value.
r.ReadElementString();
SetNull();
}
else
{
string base64 = r.ReadElementString();
if (base64 == null)
{
value = Array.Empty<byte>();
}
else
{
base64 = base64.Trim();
if (base64.Length == 0)
value = Array.Empty<byte>();
else
value = Convert.FromBase64String(base64);
}
}
SetBuffer(value);
}
void IXmlSerializable.WriteXml(XmlWriter writer)
{
if (IsNull)
{
writer.WriteAttributeString("xsi", "nil", XmlSchema.InstanceNamespace, "true");
}
else
{
byte[] value = Buffer;
writer.WriteString(Convert.ToBase64String(value, 0, (int)(Length)));
}
}
public static XmlQualifiedName GetXsdType(XmlSchemaSet schemaSet)
{
return new XmlQualifiedName("base64Binary", XmlSchema.Namespace);
}
// --------------------------------------------------------------
// Serialization using ISerializable
// --------------------------------------------------------------
// State information is not saved. The current state is converted to Buffer and only the underlying
// array is serialized, except for Null, in which case this state is kept.
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
switch (_state)
{
case SqlBytesCharsState.Null:
info.AddValue("IsNull", true);
break;
case SqlBytesCharsState.Buffer:
info.AddValue("IsNull", false);
info.AddValue("data", _rgbBuf);
break;
case SqlBytesCharsState.Stream:
CopyStreamToBuffer();
goto case SqlBytesCharsState.Buffer;
default:
Debug.Assert(false);
goto case SqlBytesCharsState.Null;
}
}
// --------------------------------------------------------------
// Static fields, properties
// --------------------------------------------------------------
// Get a Null instance.
// Since SqlBytes is mutable, have to be property and create a new one each time.
public static SqlBytes Null
{
get
{
return new SqlBytes((byte[])null);
}
}
} // class SqlBytes
// StreamOnSqlBytes is a stream build on top of SqlBytes, and
// provides the Stream interface. The purpose is to help users
// to read/write SqlBytes object. After getting the stream from
// SqlBytes, users could create a BinaryReader/BinaryWriter object
// to easily read and write primitive types.
internal sealed class StreamOnSqlBytes : Stream
{
// --------------------------------------------------------------
// Data members
// --------------------------------------------------------------
private SqlBytes _sb; // the SqlBytes object
private long _lPosition;
// --------------------------------------------------------------
// Constructor(s)
// --------------------------------------------------------------
internal StreamOnSqlBytes(SqlBytes sb)
{
_sb = sb;
_lPosition = 0;
}
// --------------------------------------------------------------
// Public properties
// --------------------------------------------------------------
// Always can read/write/seek, unless sb is null,
// which means the stream has been closed.
public override bool CanRead
{
get
{
return _sb != null && !_sb.IsNull;
}
}
public override bool CanSeek
{
get
{
return _sb != null;
}
}
public override bool CanWrite
{
get
{
return _sb != null && (!_sb.IsNull || _sb._rgbBuf != null);
}
}
public override long Length
{
get
{
CheckIfStreamClosed("get_Length");
return _sb.Length;
}
}
public override long Position
{
get
{
CheckIfStreamClosed("get_Position");
return _lPosition;
}
set
{
CheckIfStreamClosed("set_Position");
if (value < 0 || value > _sb.Length)
throw new ArgumentOutOfRangeException(nameof(value));
else
_lPosition = value;
}
}
// --------------------------------------------------------------
// Public methods
// --------------------------------------------------------------
public override long Seek(long offset, SeekOrigin origin)
{
CheckIfStreamClosed();
long lPosition = 0;
switch (origin)
{
case SeekOrigin.Begin:
if (offset < 0 || offset > _sb.Length)
throw new ArgumentOutOfRangeException(nameof(offset));
_lPosition = offset;
break;
case SeekOrigin.Current:
lPosition = _lPosition + offset;
if (lPosition < 0 || lPosition > _sb.Length)
throw new ArgumentOutOfRangeException(nameof(offset));
_lPosition = lPosition;
break;
case SeekOrigin.End:
lPosition = _sb.Length + offset;
if (lPosition < 0 || lPosition > _sb.Length)
throw new ArgumentOutOfRangeException(nameof(offset));
_lPosition = lPosition;
break;
default:
throw ADP.InvalidSeekOrigin(nameof(offset));
}
return _lPosition;
}
// The Read/Write/ReadByte/WriteByte simply delegates to SqlBytes
public override int Read(byte[] buffer, int offset, int count)
{
CheckIfStreamClosed();
if (buffer == null)
throw new ArgumentNullException(nameof(buffer));
if (offset < 0 || offset > buffer.Length)
throw new ArgumentOutOfRangeException(nameof(offset));
if (count < 0 || count > buffer.Length - offset)
throw new ArgumentOutOfRangeException(nameof(count));
int iBytesRead = (int)_sb.Read(_lPosition, buffer, offset, count);
_lPosition += iBytesRead;
return iBytesRead;
}
public override void Write(byte[] buffer, int offset, int count)
{
CheckIfStreamClosed();
if (buffer == null)
throw new ArgumentNullException(nameof(buffer));
if (offset < 0 || offset > buffer.Length)
throw new ArgumentOutOfRangeException(nameof(offset));
if (count < 0 || count > buffer.Length - offset)
throw new ArgumentOutOfRangeException(nameof(count));
_sb.Write(_lPosition, buffer, offset, count);
_lPosition += count;
}
public override int ReadByte()
{
CheckIfStreamClosed();
// If at the end of stream, return -1, rather than call SqlBytes.ReadByte,
// which will throw exception. This is the behavior for Stream.
//
if (_lPosition >= _sb.Length)
return -1;
int ret = _sb[_lPosition];
_lPosition++;
return ret;
}
public override void WriteByte(byte value)
{
CheckIfStreamClosed();
_sb[_lPosition] = value;
_lPosition++;
}
public override void SetLength(long value)
{
CheckIfStreamClosed();
_sb.SetLength(value);
if (_lPosition > value)
_lPosition = value;
}
// Flush is a no-op for stream on SqlBytes, because they are all in memory
public override void Flush()
{
if (_sb.FStream())
_sb._stream.Flush();
}
protected override void Dispose(bool disposing)
{
// When m_sb is null, it means the stream has been closed, and
// any opearation in the future should fail.
// This is the only case that m_sb is null.
try
{
_sb = null;
}
finally
{
base.Dispose(disposing);
}
}
// --------------------------------------------------------------
// Private utility functions
// --------------------------------------------------------------
private bool FClosed()
{
return _sb == null;
}
private void CheckIfStreamClosed([CallerMemberName] string methodname = "")
{
if (FClosed())
throw ADP.StreamClosed(methodname);
}
} // class StreamOnSqlBytes
} // namespace System.Data.SqlTypes
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Reflection;
using System.Diagnostics;
using System.Collections.Generic;
using System.IO;
using Internal.Reflection.Core;
using Internal.Runtime.TypeLoader;
using Internal.Runtime.Augments;
using System.Reflection.Runtime.General;
using System.Reflection.PortableExecutable;
using System.Reflection.Metadata;
using System.Collections.Immutable;
namespace Internal.Reflection.Execution
{
//=============================================================================================================================
// The assembly resolution policy for Project N's emulation of "classic reflection."
//
// The policy is very simple: the only assemblies that can be "loaded" are those that are statically linked into the running
// native process. There is no support for probing for assemblies in directories, user-supplied files, GACs, NICs or any
// other repository.
//=============================================================================================================================
public sealed partial class AssemblyBinderImplementation : AssemblyBinder
{
/// Abstraction to hold PE data for an ECMA module
private class PEInfo
{
public PEInfo(RuntimeAssemblyName name, MetadataReader reader, PEReader pe)
{
Name = name;
Reader = reader;
PE = pe;
}
public readonly RuntimeAssemblyName Name;
public readonly MetadataReader Reader;
public readonly PEReader PE;
}
private static LowLevelList<PEInfo> s_ecmaLoadedAssemblies = new LowLevelList<PEInfo>();
partial void BindEcmaByteArray(byte[] rawAssembly, byte[] rawSymbolStore, ref AssemblyBindResult bindResult, ref Exception exception, ref bool? result)
{
// 1. Load byte[] into immutable array for use by PEReader/MetadataReader
ImmutableArray<byte> assemblyData = ImmutableArray.Create(rawAssembly);
PEReader pe = new PEReader(assemblyData);
MetadataReader reader = pe.GetMetadataReader();
// 2. Create AssemblyName from MetadataReader
RuntimeAssemblyName runtimeAssemblyName = reader.GetAssemblyDefinition().ToRuntimeAssemblyName(reader).CanonicalizePublicKeyToken();
lock(s_ecmaLoadedAssemblies)
{
// 3. Attempt to bind to already loaded assembly
if (Bind(runtimeAssemblyName, out bindResult, out exception))
{
result = true;
return;
}
exception = null;
// 4. If that fails, then add newly created metareader to global cache of byte array loaded modules
PEInfo peinfo = new PEInfo(runtimeAssemblyName, reader, pe);
s_ecmaLoadedAssemblies.Add(peinfo);
ModuleList moduleList = ModuleList.Instance;
ModuleInfo newModuleInfo = new EcmaModuleInfo(moduleList.SystemModule.Handle, pe, reader);
moduleList.RegisterModule(newModuleInfo);
// 5. Then try to load by name again. This load should always succeed
if (Bind(runtimeAssemblyName, out bindResult, out exception))
{
result = true;
return;
}
result = false;
Debug.Assert(exception != null); // We must have an error on load. At this time this could happen due to ambiguous name matching
}
}
partial void BindEcmaAssemblyName(RuntimeAssemblyName refName, ref AssemblyBindResult result, ref Exception exception, ref bool foundMatch)
{
lock(s_ecmaLoadedAssemblies)
{
for (int i = 0; i < s_ecmaLoadedAssemblies.Count; i++)
{
PEInfo info = s_ecmaLoadedAssemblies[i];
if (AssemblyNameMatches(refName, info.Name))
{
if (foundMatch)
{
exception = new AmbiguousMatchException();
return;
}
result.EcmaMetadataReader = info.Reader;
foundMatch = result.EcmaMetadataReader != null;
// For failed matches, we will never be able to succeed, so return now
if (!foundMatch)
return;
}
}
if (!foundMatch)
{
try
{
// Not found in already loaded list, attempt to source assembly from disk
foreach (string filePath in FilePathsForAssembly(refName))
{
FileStream ownedFileStream = null;
PEReader ownedPEReader = null;
try
{
if (!RuntimeAugments.FileExists(filePath))
continue;
try
{
ownedFileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
}
catch (System.IO.IOException)
{
// Failure to open a file is not fundamentally an assembly load error, but it does indicate this file cannot be used
continue;
}
ownedPEReader = new PEReader(ownedFileStream);
// FileStream ownership transferred to ownedPEReader
ownedFileStream = null;
if (!ownedPEReader.HasMetadata)
continue;
MetadataReader reader = ownedPEReader.GetMetadataReader();
// Create AssemblyName from MetadataReader
RuntimeAssemblyName runtimeAssemblyName = reader.GetAssemblyDefinition().ToRuntimeAssemblyName(reader).CanonicalizePublicKeyToken();
// If assembly name doesn't match, it isn't the one we're looking for. Continue to look for more assemblies
if (!AssemblyNameMatches(refName, runtimeAssemblyName))
continue;
// This is the one we are looking for, add it to the list of loaded assemblies
PEInfo peinfo = new PEInfo(runtimeAssemblyName, reader, ownedPEReader);
s_ecmaLoadedAssemblies.Add(peinfo);
// At this point the PE reader is no longer owned by this code, but is owned by the s_ecmaLoadedAssemblies list
PEReader pe = ownedPEReader;
ownedPEReader = null;
ModuleList moduleList = ModuleList.Instance;
ModuleInfo newModuleInfo = new EcmaModuleInfo(moduleList.SystemModule.Handle, pe, reader);
moduleList.RegisterModule(newModuleInfo);
foundMatch = true;
result.EcmaMetadataReader = peinfo.Reader;
break;
}
finally
{
if (ownedFileStream != null)
ownedFileStream.Dispose();
if (ownedPEReader != null)
ownedPEReader.Dispose();
}
}
}
catch (System.IO.IOException)
{ }
catch (System.ArgumentException)
{ }
catch (System.BadImageFormatException badImageFormat)
{
exception = badImageFormat;
}
// Cache missed lookups
if (!foundMatch)
{
PEInfo peinfo = new PEInfo(refName, null, null);
s_ecmaLoadedAssemblies.Add(peinfo);
}
}
}
}
public IEnumerable<string> FilePathsForAssembly(RuntimeAssemblyName refName)
{
// Check for illegal characters in file name
if (refName.Name.IndexOfAny(Path.GetInvalidFileNameChars()) != -1)
yield break;
// Implement simple probing for assembly in application base directory and culture specific directory
string probingDirectory = AppDomain.CurrentDomain.BaseDirectory;
string cultureQualifiedDirectory = probingDirectory;
if (!String.IsNullOrEmpty(refName.CultureName))
{
cultureQualifiedDirectory = Path.Combine(probingDirectory, refName.CultureName);
}
else
{
// Loading non-resource dlls not yet supported
yield break;
}
// Attach assembly name
yield return Path.Combine(cultureQualifiedDirectory, refName.Name + ".dll");
}
partial void InsertEcmaLoadedAssemblies(List<AssemblyBindResult> loadedAssemblies)
{
lock (s_ecmaLoadedAssemblies)
{
for (int i = 0; i < s_ecmaLoadedAssemblies.Count; i++)
{
PEInfo info = s_ecmaLoadedAssemblies[i];
if (info.Reader == null)
continue;
AssemblyBindResult result = default(AssemblyBindResult);
result.EcmaMetadataReader = info.Reader;
loadedAssemblies.Add(result);
}
}
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="ContainerAction.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <owner current="true" primary="true">[....]</owner>
//------------------------------------------------------------------------------
namespace System.Xml.Xsl.XsltOld {
using Res = System.Xml.Utils.Res;
using System;
using System.Diagnostics;
using System.Text;
using System.Globalization;
using System.Xml;
using System.Xml.XPath;
using System.Xml.Xsl.Runtime;
using MS.Internal.Xml.XPath;
using System.Collections;
using System.Runtime.Versioning;
internal class NamespaceInfo {
internal String prefix;
internal String nameSpace;
internal int stylesheetId;
internal NamespaceInfo(String prefix, String nameSpace, int stylesheetId) {
this.prefix = prefix;
this.nameSpace = nameSpace;
this.stylesheetId = stylesheetId;
}
}
internal class ContainerAction : CompiledAction {
internal ArrayList containedActions;
internal CopyCodeAction lastCopyCodeAction; // non null if last action is CopyCodeAction;
private int maxid = 0;
// Local execution states
protected const int ProcessingChildren = 1;
internal override void Compile(Compiler compiler) {
throw new NotImplementedException();
}
internal void CompileStylesheetAttributes(Compiler compiler) {
NavigatorInput input = compiler.Input;
string element = input.LocalName;
string badAttribute = null;
string version = null;
if (input.MoveToFirstAttribute()) {
do {
string nspace = input.NamespaceURI;
string name = input.LocalName;
if (nspace.Length != 0) continue;
if (Ref.Equal(name, input.Atoms.Version)) {
version = input.Value;
if (1 <= XmlConvert.ToXPathDouble(version)) {
compiler.ForwardCompatibility = (version != "1.0");
}
else {
// XmlConvert.ToXPathDouble(version) an be NaN!
if (! compiler.ForwardCompatibility) {
throw XsltException.Create(Res.Xslt_InvalidAttrValue, "version", version);
}
}
}
else if (Ref.Equal(name, input.Atoms.ExtensionElementPrefixes)) {
compiler.InsertExtensionNamespace(input.Value);
}
else if (Ref.Equal(name, input.Atoms.ExcludeResultPrefixes)) {
compiler.InsertExcludedNamespace(input.Value);
}
else if (Ref.Equal(name, input.Atoms.Id)) {
// Do nothing here.
}
else {
// We can have version atribute later. For now remember this attribute and continue
badAttribute = name;
}
}
while( input.MoveToNextAttribute());
input.ToParent();
}
if (version == null) {
throw XsltException.Create(Res.Xslt_MissingAttribute, "version");
}
if (badAttribute != null && ! compiler.ForwardCompatibility) {
throw XsltException.Create(Res.Xslt_InvalidAttribute, badAttribute, element);
}
}
internal void CompileSingleTemplate(Compiler compiler) {
NavigatorInput input = compiler.Input;
//
// find mandatory version attribute and launch compilation of single template
//
string version = null;
if (input.MoveToFirstAttribute()) {
do {
string nspace = input.NamespaceURI;
string name = input.LocalName;
if (Ref.Equal(nspace, input.Atoms.UriXsl) &&
Ref.Equal(name, input.Atoms.Version)) {
version = input.Value;
}
}
while(input.MoveToNextAttribute());
input.ToParent();
}
if (version == null) {
if (Ref.Equal(input.LocalName, input.Atoms.Stylesheet) &&
input.NamespaceURI == XmlReservedNs.NsWdXsl) {
throw XsltException.Create(Res.Xslt_WdXslNamespace);
}
throw XsltException.Create(Res.Xslt_WrongStylesheetElement);
}
compiler.AddTemplate(compiler.CreateSingleTemplateAction());
}
/*
* CompileTopLevelElements
*/
protected void CompileDocument(Compiler compiler, bool inInclude) {
NavigatorInput input = compiler.Input;
// SkipToElement :
while (input.NodeType != XPathNodeType.Element) {
if (! compiler.Advance()) {
throw XsltException.Create(Res.Xslt_WrongStylesheetElement);
}
}
Debug.Assert(compiler.Input.NodeType == XPathNodeType.Element);
if (Ref.Equal(input.NamespaceURI, input.Atoms.UriXsl)) {
if (
! Ref.Equal(input.LocalName, input.Atoms.Stylesheet) &&
! Ref.Equal(input.LocalName, input.Atoms.Transform)
) {
throw XsltException.Create(Res.Xslt_WrongStylesheetElement);
}
compiler.PushNamespaceScope();
CompileStylesheetAttributes(compiler);
CompileTopLevelElements(compiler);
if (! inInclude) {
CompileImports(compiler);
}
}
else {
// single template
compiler.PushLiteralScope();
CompileSingleTemplate(compiler);
}
compiler.PopScope();
}
internal Stylesheet CompileImport(Compiler compiler, Uri uri, int id) {
NavigatorInput input = compiler.ResolveDocument(uri);
compiler.PushInputDocument(input);
try {
compiler.PushStylesheet(new Stylesheet());
compiler.Stylesheetid = id;
CompileDocument(compiler, /*inInclude*/ false);
}
catch (XsltCompileException) {
throw;
}
catch (Exception e) {
throw new XsltCompileException(e, input.BaseURI, input.LineNumber, input.LinePosition);
}
finally {
compiler.PopInputDocument();
}
return compiler.PopStylesheet();
}
private void CompileImports(Compiler compiler) {
ArrayList imports = compiler.CompiledStylesheet.Imports;
// We can't reverce imports order. Template lookup relyes on it after compilation
int saveStylesheetId = compiler.Stylesheetid;
for (int i = imports.Count - 1; 0 <= i; i --) { // Imports should be compiled in reverse order
Uri uri = imports[i] as Uri;
Debug.Assert(uri != null);
imports[i] = CompileImport(compiler, uri, ++ this.maxid);
}
compiler.Stylesheetid = saveStylesheetId;
}
// SxS: This method does not take any resource name and does not expose any resources to the caller.
// It's OK to suppress the SxS warning.
[ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
[ResourceExposure(ResourceScope.None)]
void CompileInclude(Compiler compiler) {
Uri uri = compiler.ResolveUri(compiler.GetSingleAttribute(compiler.Input.Atoms.Href));
string resolved = uri.ToString();
if (compiler.IsCircularReference(resolved)) {
throw XsltException.Create(Res.Xslt_CircularInclude, resolved);
}
NavigatorInput input = compiler.ResolveDocument(uri);
compiler.PushInputDocument(input);
try {
CompileDocument(compiler, /*inInclude*/ true);
}
catch (XsltCompileException) {
throw;
}
catch (Exception e) {
throw new XsltCompileException(e, input.BaseURI, input.LineNumber, input.LinePosition);
}
finally {
compiler.PopInputDocument();
}
CheckEmpty(compiler);
}
internal void CompileNamespaceAlias(Compiler compiler) {
NavigatorInput input = compiler.Input;
string element = input.LocalName;
string namespace1 = null, namespace2 = null;
string prefix1 = null , prefix2 = null;
if (input.MoveToFirstAttribute()) {
do {
string nspace = input.NamespaceURI;
string name = input.LocalName;
if (nspace.Length != 0) continue;
if (Ref.Equal(name,input.Atoms.StylesheetPrefix)) {
prefix1 = input.Value;
namespace1 = compiler.GetNsAlias(ref prefix1);
}
else if (Ref.Equal(name,input.Atoms.ResultPrefix)){
prefix2 = input.Value;
namespace2 = compiler.GetNsAlias(ref prefix2);
}
else {
if (! compiler.ForwardCompatibility) {
throw XsltException.Create(Res.Xslt_InvalidAttribute, name, element);
}
}
}
while(input.MoveToNextAttribute());
input.ToParent();
}
CheckRequiredAttribute(compiler, namespace1, "stylesheet-prefix");
CheckRequiredAttribute(compiler, namespace2, "result-prefix" );
CheckEmpty(compiler);
//String[] resultarray = { prefix2, namespace2 };
compiler.AddNamespaceAlias( namespace1, new NamespaceInfo(prefix2, namespace2, compiler.Stylesheetid));
}
internal void CompileKey(Compiler compiler){
NavigatorInput input = compiler.Input;
string element = input.LocalName;
int MatchKey = Compiler.InvalidQueryKey;
int UseKey = Compiler.InvalidQueryKey;
XmlQualifiedName Name = null;
if (input.MoveToFirstAttribute()) {
do {
string nspace = input.NamespaceURI;
string name = input.LocalName;
string value = input.Value;
if (nspace.Length != 0) continue;
if (Ref.Equal(name, input.Atoms.Name)) {
Name = compiler.CreateXPathQName(value);
}
else if (Ref.Equal(name, input.Atoms.Match)) {
MatchKey = compiler.AddQuery(value, /*allowVars:*/false, /*allowKey*/false, /*pattern*/true);
}
else if (Ref.Equal(name, input.Atoms.Use)) {
UseKey = compiler.AddQuery(value, /*allowVars:*/false, /*allowKey*/false, /*pattern*/false);
}
else {
if (! compiler.ForwardCompatibility) {
throw XsltException.Create(Res.Xslt_InvalidAttribute, name, element);
}
}
}
while(input.MoveToNextAttribute());
input.ToParent();
}
CheckRequiredAttribute(compiler, MatchKey != Compiler.InvalidQueryKey, "match");
CheckRequiredAttribute(compiler, UseKey != Compiler.InvalidQueryKey, "use" );
CheckRequiredAttribute(compiler, Name != null , "name" );
// It is a breaking change to check for emptiness, SQLBUDT 324364
//CheckEmpty(compiler);
compiler.InsertKey(Name, MatchKey, UseKey);
}
protected void CompileDecimalFormat(Compiler compiler){
NumberFormatInfo info = new NumberFormatInfo();
DecimalFormat format = new DecimalFormat(info, '#', '0', ';');
XmlQualifiedName Name = null;
NavigatorInput input = compiler.Input;
if (input.MoveToFirstAttribute()) {
do {
if (input.Prefix.Length != 0) continue;
string name = input.LocalName;
string value = input.Value;
if (Ref.Equal(name, input.Atoms.Name)) {
Name = compiler.CreateXPathQName(value);
}
else if (Ref.Equal(name, input.Atoms.DecimalSeparator)) {
info.NumberDecimalSeparator = value;
}
else if (Ref.Equal(name, input.Atoms.GroupingSeparator)) {
info.NumberGroupSeparator = value;
}
else if (Ref.Equal(name, input.Atoms.Infinity)) {
info.PositiveInfinitySymbol = value;
}
else if (Ref.Equal(name, input.Atoms.MinusSign)) {
info.NegativeSign = value;
}
else if (Ref.Equal(name, input.Atoms.NaN)) {
info.NaNSymbol = value;
}
else if (Ref.Equal(name, input.Atoms.Percent)) {
info.PercentSymbol = value;
}
else if (Ref.Equal(name, input.Atoms.PerMille)) {
info.PerMilleSymbol = value;
}
else if (Ref.Equal(name, input.Atoms.Digit)) {
if (CheckAttribute(value.Length == 1, compiler)) {
format.digit = value[0];
}
}
else if (Ref.Equal(name, input.Atoms.ZeroDigit)) {
if (CheckAttribute(value.Length == 1, compiler)) {
format.zeroDigit = value[0];
}
}
else if (Ref.Equal(name, input.Atoms.PatternSeparator)) {
if (CheckAttribute(value.Length == 1, compiler)) {
format.patternSeparator = value[0];
}
}
}
while(input.MoveToNextAttribute());
input.ToParent();
}
info.NegativeInfinitySymbol = String.Concat(info.NegativeSign, info.PositiveInfinitySymbol);
if (Name == null) {
Name = new XmlQualifiedName();
}
compiler.AddDecimalFormat(Name, format);
CheckEmpty(compiler);
}
internal bool CheckAttribute(bool valid, Compiler compiler) {
if (! valid) {
if (! compiler.ForwardCompatibility) {
throw XsltException.Create(Res.Xslt_InvalidAttrValue, compiler.Input.LocalName, compiler.Input.Value);
}
return false;
}
return true;
}
protected void CompileSpace(Compiler compiler, bool preserve){
String value = compiler.GetSingleAttribute(compiler.Input.Atoms.Elements);
String[] elements = XmlConvert.SplitString(value);
for (int i = 0; i < elements.Length; i++){
double defaultPriority = NameTest(elements[i]);
compiler.CompiledStylesheet.AddSpace(compiler, elements[i], defaultPriority, preserve);
}
CheckEmpty(compiler);
}
double NameTest(String name) {
if (name == "*") {
return -0.5;
}
int idx = name.Length - 2;
if (0 <= idx && name[idx] == ':' && name[idx + 1] == '*') {
if (! PrefixQName.ValidatePrefix(name.Substring(0, idx))) {
throw XsltException.Create(Res.Xslt_InvalidAttrValue, "elements", name);
}
return -0.25;
}
else {
string prefix, localname;
PrefixQName.ParseQualifiedName(name, out prefix, out localname);
return 0;
}
}
// SxS: This method does not take any resource name and does not expose any resources to the caller.
// It's OK to suppress the SxS warning.
[ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
[ResourceExposure(ResourceScope.None)]
protected void CompileTopLevelElements(Compiler compiler) {
// Navigator positioned at parent root, need to move to child and then back
if (compiler.Recurse() == false) {
return;
}
NavigatorInput input = compiler.Input;
bool notFirstElement = false;
do {
switch (input.NodeType) {
case XPathNodeType.Element:
string name = input.LocalName;
string nspace = input.NamespaceURI;
if (Ref.Equal(nspace, input.Atoms.UriXsl)) {
if (Ref.Equal(name, input.Atoms.Import)) {
if (notFirstElement) {
throw XsltException.Create(Res.Xslt_NotFirstImport);
}
// We should compile imports in reverse order after all toplevel elements.
// remember it now and return to it in CompileImpoorts();
Uri uri = compiler.ResolveUri(compiler.GetSingleAttribute(compiler.Input.Atoms.Href));
string resolved = uri.ToString();
if (compiler.IsCircularReference(resolved)) {
throw XsltException.Create(Res.Xslt_CircularInclude, resolved);
}
compiler.CompiledStylesheet.Imports.Add(uri);
CheckEmpty(compiler);
}
else if (Ref.Equal(name, input.Atoms.Include)) {
notFirstElement = true;
CompileInclude(compiler);
}
else {
notFirstElement = true;
compiler.PushNamespaceScope();
if (Ref.Equal(name, input.Atoms.StripSpace)) {
CompileSpace(compiler, false);
}
else if (Ref.Equal(name, input.Atoms.PreserveSpace)) {
CompileSpace(compiler, true);
}
else if (Ref.Equal(name, input.Atoms.Output)) {
CompileOutput(compiler);
}
else if (Ref.Equal(name, input.Atoms.Key)) {
CompileKey(compiler);
}
else if (Ref.Equal(name, input.Atoms.DecimalFormat)) {
CompileDecimalFormat(compiler);
}
else if (Ref.Equal(name, input.Atoms.NamespaceAlias)) {
CompileNamespaceAlias(compiler);
}
else if (Ref.Equal(name, input.Atoms.AttributeSet)) {
compiler.AddAttributeSet(compiler.CreateAttributeSetAction());
}
else if (Ref.Equal(name, input.Atoms.Variable)) {
VariableAction action = compiler.CreateVariableAction(VariableType.GlobalVariable);
if (action != null) {
AddAction(action);
}
}
else if (Ref.Equal(name, input.Atoms.Param)) {
VariableAction action = compiler.CreateVariableAction(VariableType.GlobalParameter);
if (action != null) {
AddAction(action);
}
}
else if (Ref.Equal(name, input.Atoms.Template)) {
compiler.AddTemplate(compiler.CreateTemplateAction());
}
else {
if (!compiler.ForwardCompatibility) {
throw compiler.UnexpectedKeyword();
}
}
compiler.PopScope();
}
}
else if (nspace == input.Atoms.UrnMsxsl && name == input.Atoms.Script) {
AddScript(compiler);
}
else {
if (nspace.Length == 0) {
throw XsltException.Create(Res.Xslt_NullNsAtTopLevel, input.Name);
}
// Ignoring non-recognized namespace per XSLT spec 2.2
}
break;
case XPathNodeType.ProcessingInstruction:
case XPathNodeType.Comment:
case XPathNodeType.Whitespace:
case XPathNodeType.SignificantWhitespace:
break;
default:
throw XsltException.Create(Res.Xslt_InvalidContents, "stylesheet");
}
}
while (compiler.Advance());
compiler.ToParent();
}
protected void CompileTemplate(Compiler compiler) {
do {
CompileOnceTemplate(compiler);
}
while (compiler.Advance());
}
protected void CompileOnceTemplate(Compiler compiler) {
NavigatorInput input = compiler.Input;
if (input.NodeType == XPathNodeType.Element) {
string nspace = input.NamespaceURI;
if (Ref.Equal(nspace, input.Atoms.UriXsl)) {
compiler.PushNamespaceScope();
CompileInstruction(compiler);
compiler.PopScope();
}
else {
compiler.PushLiteralScope();
compiler.InsertExtensionNamespace();
if (compiler.IsExtensionNamespace(nspace)) {
AddAction(compiler.CreateNewInstructionAction());
}
else {
CompileLiteral(compiler);
}
compiler.PopScope();
}
}
else {
CompileLiteral(compiler);
}
}
void CompileInstruction(Compiler compiler) {
NavigatorInput input = compiler.Input;
CompiledAction action = null;
Debug.Assert(Ref.Equal(input.NamespaceURI, input.Atoms.UriXsl));
string name = input.LocalName;
if (Ref.Equal(name, input.Atoms.ApplyImports)) {
action = compiler.CreateApplyImportsAction();
}
else if (Ref.Equal(name, input.Atoms.ApplyTemplates)) {
action = compiler.CreateApplyTemplatesAction();
}
else if (Ref.Equal(name, input.Atoms.Attribute)) {
action = compiler.CreateAttributeAction();
}
else if (Ref.Equal(name, input.Atoms.CallTemplate)) {
action = compiler.CreateCallTemplateAction();
}
else if (Ref.Equal(name, input.Atoms.Choose)) {
action = compiler.CreateChooseAction();
}
else if (Ref.Equal(name, input.Atoms.Comment)) {
action = compiler.CreateCommentAction();
}
else if (Ref.Equal(name, input.Atoms.Copy)) {
action = compiler.CreateCopyAction();
}
else if (Ref.Equal(name, input.Atoms.CopyOf)) {
action = compiler.CreateCopyOfAction();
}
else if (Ref.Equal(name, input.Atoms.Element)) {
action = compiler.CreateElementAction();
}
else if (Ref.Equal(name, input.Atoms.Fallback)) {
return;
}
else if (Ref.Equal(name, input.Atoms.ForEach)) {
action = compiler.CreateForEachAction();
}
else if (Ref.Equal(name, input.Atoms.If)) {
action = compiler.CreateIfAction(IfAction.ConditionType.ConditionIf);
}
else if (Ref.Equal(name, input.Atoms.Message)) {
action = compiler.CreateMessageAction();
}
else if (Ref.Equal(name, input.Atoms.Number)) {
action = compiler.CreateNumberAction();
}
else if (Ref.Equal(name, input.Atoms.ProcessingInstruction)) {
action = compiler.CreateProcessingInstructionAction();
}
else if (Ref.Equal(name, input.Atoms.Text)) {
action = compiler.CreateTextAction();
}
else if (Ref.Equal(name, input.Atoms.ValueOf)) {
action = compiler.CreateValueOfAction();
}
else if (Ref.Equal(name, input.Atoms.Variable)) {
action = compiler.CreateVariableAction(VariableType.LocalVariable);
}
else {
if (compiler.ForwardCompatibility)
action = compiler.CreateNewInstructionAction();
else
throw compiler.UnexpectedKeyword();
}
Debug.Assert(action != null);
AddAction(action);
}
void CompileLiteral(Compiler compiler) {
NavigatorInput input = compiler.Input;
switch (input.NodeType) {
case XPathNodeType.Element:
this.AddEvent(compiler.CreateBeginEvent());
CompileLiteralAttributesAndNamespaces(compiler);
if (compiler.Recurse()) {
CompileTemplate(compiler);
compiler.ToParent();
}
this.AddEvent(new EndEvent(XPathNodeType.Element));
break;
case XPathNodeType.Text:
case XPathNodeType.SignificantWhitespace:
this.AddEvent(compiler.CreateTextEvent());
break;
case XPathNodeType.Whitespace:
case XPathNodeType.ProcessingInstruction:
case XPathNodeType.Comment:
break;
default:
Debug.Assert(false, "Unexpected node type.");
break;
}
}
void CompileLiteralAttributesAndNamespaces(Compiler compiler) {
NavigatorInput input = compiler.Input;
if (input.Navigator.MoveToAttribute("use-attribute-sets", input.Atoms.UriXsl)) {
AddAction(compiler.CreateUseAttributeSetsAction());
input.Navigator.MoveToParent();
}
compiler.InsertExcludedNamespace();
if (input.MoveToFirstNamespace()) {
do {
string uri = input.Value;
if (uri == XmlReservedNs.NsXslt) {
continue;
}
if (
compiler.IsExcludedNamespace(uri) ||
compiler.IsExtensionNamespace(uri) ||
compiler.IsNamespaceAlias(uri)
) {
continue;
}
this.AddEvent(new NamespaceEvent(input));
}
while (input.MoveToNextNamespace());
input.ToParent();
}
if (input.MoveToFirstAttribute()) {
do {
// Skip everything from Xslt namespace
if (Ref.Equal(input.NamespaceURI, input.Atoms.UriXsl)) {
continue;
}
// Add attribute events
this.AddEvent (compiler.CreateBeginEvent());
this.AddEvents(compiler.CompileAvt(input.Value));
this.AddEvent (new EndEvent(XPathNodeType.Attribute));
}
while (input.MoveToNextAttribute());
input.ToParent();
}
}
void CompileOutput(Compiler compiler) {
Debug.Assert((object) this == (object) compiler.RootAction);
compiler.RootAction.Output.Compile(compiler);
}
internal void AddAction(Action action) {
if (this.containedActions == null) {
this.containedActions = new ArrayList();
}
this.containedActions.Add(action);
lastCopyCodeAction = null;
}
private void EnsureCopyCodeAction() {
if(lastCopyCodeAction == null) {
CopyCodeAction copyCode = new CopyCodeAction();
AddAction(copyCode);
lastCopyCodeAction = copyCode;
}
}
protected void AddEvent(Event copyEvent) {
EnsureCopyCodeAction();
lastCopyCodeAction.AddEvent(copyEvent);
}
protected void AddEvents(ArrayList copyEvents) {
EnsureCopyCodeAction();
lastCopyCodeAction.AddEvents(copyEvents);
}
private void AddScript(Compiler compiler) {
NavigatorInput input = compiler.Input;
ScriptingLanguage lang = ScriptingLanguage.JScript;
string implementsNamespace = null;
if (input.MoveToFirstAttribute()) {
do {
if (input.LocalName == input.Atoms.Language) {
string langName = input.Value;
if (
String.Compare(langName, "jscript" , StringComparison.OrdinalIgnoreCase) == 0 ||
String.Compare(langName, "javascript", StringComparison.OrdinalIgnoreCase) == 0
) {
lang = ScriptingLanguage.JScript;
} else if (
String.Compare(langName, "c#" , StringComparison.OrdinalIgnoreCase) == 0 ||
String.Compare(langName, "csharp", StringComparison.OrdinalIgnoreCase) == 0
) {
lang = ScriptingLanguage.CSharp;
}
#if !FEATURE_PAL // visualbasic
else if (
String.Compare(langName, "vb" , StringComparison.OrdinalIgnoreCase) == 0 ||
String.Compare(langName, "visualbasic", StringComparison.OrdinalIgnoreCase) == 0
) {
lang = ScriptingLanguage.VisualBasic;
}
#endif // !FEATURE_PAL
else {
throw XsltException.Create(Res.Xslt_ScriptInvalidLanguage, langName);
}
}
else if (input.LocalName == input.Atoms.ImplementsPrefix) {
if(! PrefixQName.ValidatePrefix(input.Value)) {
throw XsltException.Create(Res.Xslt_InvalidAttrValue, input.LocalName, input.Value);
}
implementsNamespace = compiler.ResolveXmlNamespace(input.Value);
}
}
while (input.MoveToNextAttribute());
input.ToParent();
}
if (implementsNamespace == null) {
throw XsltException.Create(Res.Xslt_MissingAttribute, input.Atoms.ImplementsPrefix);
}
if (!input.Recurse() || input.NodeType != XPathNodeType.Text) {
throw XsltException.Create(Res.Xslt_ScriptEmpty);
}
compiler.AddScript(input.Value, lang, implementsNamespace, input.BaseURI, input.LineNumber);
input.ToParent();
}
internal override void Execute(Processor processor, ActionFrame frame) {
Debug.Assert(processor != null && frame != null);
switch (frame.State) {
case Initialized:
if (this.containedActions != null && this.containedActions.Count > 0) {
processor.PushActionFrame(frame);
frame.State = ProcessingChildren;
}
else {
frame.Finished();
}
break; // Allow children to run
case ProcessingChildren:
frame.Finished();
break;
default:
Debug.Fail("Invalid Container action execution state");
break;
}
}
internal Action GetAction(int actionIndex) {
Debug.Assert(actionIndex == 0 || this.containedActions != null);
if (this.containedActions != null && actionIndex < this.containedActions.Count) {
return (Action) this.containedActions[actionIndex];
}
else {
return null;
}
}
internal void CheckDuplicateParams(XmlQualifiedName name) {
if (this.containedActions != null) {
foreach(CompiledAction action in this.containedActions) {
WithParamAction param = action as WithParamAction;
if (param != null && param.Name == name) {
throw XsltException.Create(Res.Xslt_DuplicateWithParam, name.ToString());
}
}
}
}
internal override void ReplaceNamespaceAlias(Compiler compiler){
if (this.containedActions == null) {
return;
}
int count = this.containedActions.Count;
for(int i= 0; i < this.containedActions.Count; i++) {
((Action)this.containedActions[i]).ReplaceNamespaceAlias(compiler);
}
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="TableLayoutPanel.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Windows.Forms {
using System;
using System.Collections;
using System.ComponentModel;
using System.ComponentModel.Design.Serialization;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Drawing;
using System.Globalization;
using System.Windows.Forms.Layout;
using System.Reflection;
using System.Runtime.InteropServices;
/// <include file='doc\GridPanel.uex' path='docs/doc[@for="GridPanel"]/*' />
[ProvideProperty("ColumnSpan", typeof(Control))]
[ProvideProperty("RowSpan", typeof(Control))]
[ProvideProperty("Row", typeof(Control))]
[ProvideProperty("Column", typeof(Control))]
[ProvideProperty("CellPosition", typeof(Control))]
[DefaultProperty("ColumnCount")]
[DesignerSerializer("System.Windows.Forms.Design.TableLayoutPanelCodeDomSerializer, " + AssemblyRef.SystemDesign, "System.ComponentModel.Design.Serialization.CodeDomSerializer, " + AssemblyRef.SystemDesign)]
[Docking(DockingBehavior.Never)]
[Designer("System.Windows.Forms.Design.TableLayoutPanelDesigner, " + AssemblyRef.SystemDesign)]
[ComVisible(true)]
[ClassInterface(ClassInterfaceType.AutoDispatch)]
[SRDescription(SR.DescriptionTableLayoutPanel)]
public class TableLayoutPanel : Panel, IExtenderProvider {
private TableLayoutSettings _tableLayoutSettings;
private static readonly object EventCellPaint = new object();
/// <include file='doc\TableLayoutPanel.uex' path='docs/doc[@for="TableLayoutPanel.TableLayoutPanel"]/*' />
public TableLayoutPanel() {
_tableLayoutSettings = TableLayout.CreateSettings(this);
}
/// <include file='doc\GridPanel.uex' path='docs/doc[@for="GridPanel.LayoutEngine"]/*' />
public override LayoutEngine LayoutEngine {
get { return TableLayout.Instance; }
}
[
Browsable(false),
EditorBrowsable(EditorBrowsableState.Never),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
]
public TableLayoutSettings LayoutSettings {
get {
return _tableLayoutSettings;
}
set {
if (value != null && value.IsStub) {
// WINRES only scenario.
// we only support table layout settings that have been created from a type converter.
// this is here for localization (WinRes) support.
using (new LayoutTransaction(this, this, PropertyNames.LayoutSettings)) {
// apply RowStyles, ColumnStyles, Row & Column assignments.
_tableLayoutSettings.ApplySettings(value);
}
}
else {
throw new NotSupportedException(SR.GetString(SR.TableLayoutSettingSettingsIsNotSupported));
}
}
}
/// <include file='doc\TableLayoutPanel.uex' path='docs/doc[@for="TableLayoutPanel.BorderStyle"]/*' />
[
Browsable(false),
EditorBrowsable(EditorBrowsableState.Never),
Localizable(true)
]
public new BorderStyle BorderStyle {
get { return base.BorderStyle; }
set {
base.BorderStyle = value;
Debug.Assert(BorderStyle == value, "BorderStyle should be the same as we set it");
}
}
/// <include file='doc\TableLayoutPanel.uex' path='docs/doc[@for="TableLayoutPanel.CellBorderStyle"]/*' />
[
DefaultValue(TableLayoutPanelCellBorderStyle.None),
SRCategory(SR.CatAppearance),
SRDescription(SR.TableLayoutPanelCellBorderStyleDescr),
Localizable(true)
]
public TableLayoutPanelCellBorderStyle CellBorderStyle {
get { return _tableLayoutSettings.CellBorderStyle; }
set {
_tableLayoutSettings.CellBorderStyle = value;
// PERF: dont turn on ResizeRedraw unless we know we need it.
if (value != TableLayoutPanelCellBorderStyle.None) {
SetStyle(ControlStyles.ResizeRedraw, true);
}
this.Invalidate();
Debug.Assert(CellBorderStyle == value, "CellBorderStyle should be the same as we set it");
}
}
private int CellBorderWidth {
get { return _tableLayoutSettings.CellBorderWidth; }
}
/// <include file='doc\TableLayoutPanel.uex' path='docs/doc[@for="TableLayoutPanel.Controls"]/*' />
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
[SRDescription(SR.ControlControlsDescr)]
public new TableLayoutControlCollection Controls {
get { return (TableLayoutControlCollection)base.Controls; }
}
/// <include file='doc\GridPanel.uex' path='docs/doc[@for="GridPanel.ColumnCount"]/*' />
/// <devdoc>
/// This sets the maximum number of columns allowed on this table instead of allocating
/// actual spaces for these columns. So it is OK to set ColumnCount to Int32.MaxValue without
/// causing out of memory exception
/// </devdoc>
[SRDescription(SR.GridPanelColumnsDescr)]
[SRCategory(SR.CatLayout)]
[DefaultValue(0)]
[Localizable(true)]
public int ColumnCount {
get { return _tableLayoutSettings.ColumnCount; }
set {
_tableLayoutSettings.ColumnCount = value;
Debug.Assert(ColumnCount == value, "ColumnCount should be the same as we set it");
}
}
/// <include file='doc\TableLayoutPanel.uex' path='docs/doc[@for="TableLayoutPanel.GrowStyle"]/*' />
/// <devdoc>
/// Specifies if a TableLayoutPanel will gain additional rows or columns once its existing cells
/// become full. If the value is 'FixedSize' then the TableLayoutPanel will throw an exception
/// when the TableLayoutPanel is over-filled.
/// </devdoc>
[SRDescription(SR.TableLayoutPanelGrowStyleDescr)]
[SRCategory(SR.CatLayout)]
[DefaultValue(TableLayoutPanelGrowStyle.AddRows)]
public TableLayoutPanelGrowStyle GrowStyle {
get {
return _tableLayoutSettings.GrowStyle;
}
set {
_tableLayoutSettings.GrowStyle = value;
}
}
/// <include file='doc\GridPanel.uex' path='docs/doc[@for="GridPanel.RowCount"]/*' />
/// <devdoc>
/// This sets the maximum number of rows allowed on this table instead of allocating
/// actual spaces for these rows. So it is OK to set RowCount to Int32.MaxValue without
/// causing out of memory exception
/// </devdoc>
[SRDescription(SR.GridPanelRowsDescr)]
[SRCategory(SR.CatLayout)]
[DefaultValue(0)]
[Localizable(true)]
public int RowCount {
get { return _tableLayoutSettings.RowCount; }
set { _tableLayoutSettings.RowCount = value; }
}
/// <include file='doc\GridPanel.uex' path='docs/doc[@for="GridPanel.RowStyles"]/*' />
[SRDescription(SR.GridPanelRowStylesDescr)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
[SRCategory(SR.CatLayout)]
[DisplayName("Rows")]
[MergableProperty(false)]
[Browsable(false)]
public TableLayoutRowStyleCollection RowStyles {
get { return _tableLayoutSettings.RowStyles; }
}
/// <include file='doc\GridPanel.uex' path='docs/doc[@for="GridPanel.ColumnStyles"]/*' />
[SRDescription(SR.GridPanelColumnStylesDescr)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
[SRCategory(SR.CatLayout)]
[DisplayName("Columns")]
[Browsable(false)]
[MergableProperty(false)]
public TableLayoutColumnStyleCollection ColumnStyles {
get { return _tableLayoutSettings.ColumnStyles; }
}
/// <include file='doc\TableLayoutPanel.uex' path='docs/doc[@for="TableLayoutPanel.CreateControlsInstance"]/*' />
/// <internalonly/>
/// <devdoc>
/// </devdoc>
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected override Control.ControlCollection CreateControlsInstance() {
return new TableLayoutControlCollection(this);
}
private bool ShouldSerializeControls() {
TableLayoutControlCollection collection = this.Controls;
return collection != null && collection.Count > 0;
}
#region Extended Properties
/// <include file='doc\GridPanel.uex' path='docs/doc[@for="GridPanel.IExtenderProvider.CanExtend"]/*' />
/// <internalonly/>
bool IExtenderProvider.CanExtend(object obj) {
Control control = obj as Control;
return control != null && control.Parent == this;
}
/// <include file='doc\GridPanel.uex' path='docs/doc[@for="GridPanel.GetColumnSpan"]/*' />
[SRDescription(SR.GridPanelGetColumnSpanDescr)]
[DefaultValue(1)]
[SRCategory(SR.CatLayout)]
[DisplayName("ColumnSpan")]
public int GetColumnSpan(Control control) {
return _tableLayoutSettings.GetColumnSpan(control);
}
/// <include file='doc\GridPanel.uex' path='docs/doc[@for="GridPanel.SetColumnSpan"]/*' />
public void SetColumnSpan(Control control, int value) {
// layout.SetColumnSpan() throws ArgumentException if out of range.
_tableLayoutSettings.SetColumnSpan(control, value);
Debug.Assert(GetColumnSpan(control) == value, "GetColumnSpan should be the same as we set it");
}
/// <include file='doc\GridPanel.uex' path='docs/doc[@for="GridPanel.GetRowSpan"]/*' />
[SRDescription(SR.GridPanelGetRowSpanDescr)]
[DefaultValue(1)]
[SRCategory(SR.CatLayout)]
[DisplayName("RowSpan")]
public int GetRowSpan(Control control) {
return _tableLayoutSettings.GetRowSpan(control);
}
/// <include file='doc\GridPanel.uex' path='docs/doc[@for="GridPanel.SetRowSpan"]/*' />
public void SetRowSpan(Control control, int value) {
// layout.SetRowSpan() throws ArgumentException if out of range.
_tableLayoutSettings.SetRowSpan(control, value);
Debug.Assert(GetRowSpan(control) == value, "GetRowSpan should be the same as we set it");
}
//get the row position of the control
/// <include file='doc\TableLayoutPanel.uex' path='docs/doc[@for="TableLayoutPanel.GetRow"]/*' />
[DefaultValue(-1)] //if change this value, also change the SerializeViaAdd in TableLayoutControlCollectionCodeDomSerializer
[SRDescription(SR.GridPanelRowDescr)]
[SRCategory(SR.CatLayout)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[DisplayName("Row")]
public int GetRow(Control control) {
return _tableLayoutSettings.GetRow(control);
}
//set the row position of the control
/// <include file='doc\TableLayoutPanel.uex' path='docs/doc[@for="TableLayoutPanel.SetRow"]/*' />
public void SetRow(Control control, int row) {
_tableLayoutSettings.SetRow(control, row);
Debug.Assert(GetRow(control) == row, "GetRow should be the same as we set it");
}
//get the row and column position of the control
/// <include file='doc\TableLayoutPanel.uex' path='docs/doc[@for="TableLayoutPanel.GetRow"]/*' />
[DefaultValue(typeof(TableLayoutPanelCellPosition), "-1,-1")] //if change this value, also change the SerializeViaAdd in TableLayoutControlCollectionCodeDomSerializer
[SRDescription(SR.GridPanelCellPositionDescr)]
[SRCategory(SR.CatLayout)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[DisplayName("Cell")]
public TableLayoutPanelCellPosition GetCellPosition(Control control) {
return _tableLayoutSettings.GetCellPosition(control);
}
//set the row and column of the control
/// <include file='doc\TableLayoutPanel.uex' path='docs/doc[@for="TableLayoutPanel.SetRow"]/*' />
public void SetCellPosition(Control control, TableLayoutPanelCellPosition position) {
_tableLayoutSettings.SetCellPosition(control, position);
}
//get the column position of the control
/// <include file='doc\TableLayoutPanel.uex' path='docs/doc[@for="TableLayoutPanel.GetColumn"]/*' />
[DefaultValue(-1)] //if change this value, also change the SerializeViaAdd in TableLayoutControlCollectionCodeDomSerializer
[SRDescription(SR.GridPanelColumnDescr)]
[SRCategory(SR.CatLayout)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
[DisplayName("Column")]
public int GetColumn(Control control) {
return _tableLayoutSettings.GetColumn(control);
}
//set the column position of the control
/// <include file='doc\TableLayoutPanel.uex' path='docs/doc[@for="TableLayoutPanel.SetColumn"]/*' />
public void SetColumn(Control control, int column) {
_tableLayoutSettings.SetColumn(control, column);
Debug.Assert(GetColumn(control) == column, "GetColumn should be the same as we set it");
}
/// <include file='doc\TableLayoutPanel.uex' path='docs/doc[@for="TableLayoutPanel.GetControlFromPosition"]/*' />
/// <devdoc>
/// get the control which covers the specified row and column. return null if we can't find one
/// </devdoc>
public Control GetControlFromPosition (int column, int row) {
return (Control)_tableLayoutSettings.GetControlFromPosition(column, row);
}
[SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] // Using Control instead of IArrangedElement intentionally
public TableLayoutPanelCellPosition GetPositionFromControl (Control control) {
return _tableLayoutSettings.GetPositionFromControl(control);
}
/// <include file='doc\TableLayoutPanel.uex' path='docs/doc[@for="TableLayoutPanel.ColumnWidths"]/*' />
/// <devdoc>
/// This returns an array representing the widths (in pixels) of the columns in the TableLayoutPanel.
/// </devdoc>
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
public int[] GetColumnWidths() {
TableLayout.ContainerInfo containerInfo = TableLayout.GetContainerInfo(this);
if (containerInfo.Columns == null) {
return new int[0];
}
int[] cw = new int[containerInfo.Columns.Length];
for(int i = 0; i < containerInfo.Columns.Length; i++) {
cw[i] = containerInfo.Columns[i].MinSize;
}
return cw;
}
/// <include file='doc\TableLayoutPanel.uex' path='docs/doc[@for="TableLayoutPanel.RowWidths"]/*' />
/// <devdoc>
/// This returns an array representing the heights (in pixels) of the rows in the TableLayoutPanel.
/// </devdoc>
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
public int[] GetRowHeights() {
TableLayout.ContainerInfo containerInfo = TableLayout.GetContainerInfo(this);
if (containerInfo.Rows == null) {
return new int[0];
}
int[] rh = new int[containerInfo.Rows.Length];
for(int i = 0; i < containerInfo.Rows.Length; i++) {
rh[i] = containerInfo.Rows[i].MinSize;
}
return rh;
}
#endregion
#region PaintCode
/// <include file='doc\TableLayoutPanel.uex' path='docs/doc[@for="TableLayoutPanel.CellPaint"]/*' />
[SRCategory(SR.CatAppearance), SRDescription(SR.TableLayoutPanelOnPaintCellDescr)]
public event TableLayoutCellPaintEventHandler CellPaint {
add {
Events.AddHandler(EventCellPaint, value);
}
remove {
Events.RemoveHandler(EventCellPaint, value);
}
}
/// <include file='doc\TableLayoutPanel.uex' path='docs/doc[@for="TableLayoutPanel.OnLayout"]/*' />
/// <internalonly/>
/// <devdoc>
/// When a layout fires, make sure we're painting all of our
/// cell borders.
/// </devdoc>
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected override void OnLayout(LayoutEventArgs levent) {
base.OnLayout(levent);
this.Invalidate();
}
/// <include file='doc\TableLayoutPanel.uex' path='docs/doc[@for="TableLayoutPanel.OnCellPaint"]/*' />
protected virtual void OnCellPaint(TableLayoutCellPaintEventArgs e) {
TableLayoutCellPaintEventHandler handler = (TableLayoutCellPaintEventHandler)Events[EventCellPaint];
if (handler != null) {
handler(this, e);
}
}
/// <include file='doc\TableLayoutPanel.uex' path='docs/doc[@for="TableLayoutPanel.OnPaint"]/*' />
protected override void OnPaintBackground(PaintEventArgs e) {
base.OnPaintBackground(e);
// paint borderstyles on top of the background image in WM_ERASEBKGND
int cellBorderWidth = this.CellBorderWidth;
TableLayout.ContainerInfo containerInfo = TableLayout.GetContainerInfo(this);
TableLayout.Strip[] colStrips = containerInfo.Columns;
TableLayout.Strip[] rowStrips = containerInfo.Rows;
TableLayoutPanelCellBorderStyle cellBorderStyle = this.CellBorderStyle;
if (colStrips == null || rowStrips == null) {
return;
}
int cols = colStrips.Length;
int rows = rowStrips.Length;
int totalColumnWidths = 0, totalColumnHeights = 0;
Graphics g = e.Graphics;
Rectangle displayRect = DisplayRectangle;
Rectangle clipRect = e.ClipRectangle;
//leave the space for the border
int startx;
bool isRTL = (RightToLeft == RightToLeft.Yes);
if (isRTL) {
startx = displayRect.Right - (cellBorderWidth / 2);
}
else {
startx = displayRect.X + (cellBorderWidth / 2);
}
for (int i = 0; i < cols; i++) {
int starty = displayRect.Y + (cellBorderWidth / 2);
if (isRTL) {
startx -= colStrips[i].MinSize;
}
for (int j = 0; j < rows; j++) {
Rectangle outsideCellBounds = new Rectangle(startx, starty, ((TableLayout.Strip)colStrips[i]).MinSize, ((TableLayout.Strip)rowStrips[j]).MinSize);
Rectangle insideCellBounds = new Rectangle(outsideCellBounds.X + (cellBorderWidth + 1) / 2, outsideCellBounds.Y + (cellBorderWidth + 1)/ 2, outsideCellBounds.Width - (cellBorderWidth + 1) / 2, outsideCellBounds.Height - (cellBorderWidth + 1) / 2);
if (clipRect.IntersectsWith(insideCellBounds)) {
//first, call user's painting code
using (TableLayoutCellPaintEventArgs pcea = new TableLayoutCellPaintEventArgs(g, clipRect, insideCellBounds, i, j)) {
OnCellPaint(pcea);
}
// paint the table border on top.
ControlPaint.PaintTableCellBorder(cellBorderStyle, g, outsideCellBounds);
}
starty += rowStrips[j].MinSize;
// Only sum this up once...
if (i == 0) {
totalColumnHeights += rowStrips[j].MinSize;
}
}
if (!isRTL) {
startx += colStrips[i].MinSize;
}
totalColumnWidths += colStrips[i].MinSize;
}
if (!HScroll && !VScroll && cellBorderStyle != TableLayoutPanelCellBorderStyle.None) {
Rectangle tableBounds = new Rectangle(cellBorderWidth/2 + displayRect.X, cellBorderWidth/2 + displayRect.Y, displayRect.Width - cellBorderWidth, displayRect.Height - cellBorderWidth);
// paint the border of the table if we are not auto scrolling.
// if the borderStyle is Inset or Outset, we can only paint the lower bottom half since otherwise we will have 1 pixel loss at the border.
if (cellBorderStyle == TableLayoutPanelCellBorderStyle.Inset) {
g.DrawLine(SystemPens.ControlDark, tableBounds.Right, tableBounds.Y, tableBounds.Right, tableBounds.Bottom);
g.DrawLine(SystemPens.ControlDark, tableBounds.X, tableBounds.Y + tableBounds.Height - 1, tableBounds.X + tableBounds.Width - 1, tableBounds.Y + tableBounds.Height - 1);
}
else if (cellBorderStyle == TableLayoutPanelCellBorderStyle.Outset) {
using (Pen pen = new Pen(SystemColors.Window)) {
g.DrawLine(pen, tableBounds.X + tableBounds.Width - 1, tableBounds.Y, tableBounds.X + tableBounds.Width - 1, tableBounds.Y + tableBounds.Height - 1);
g.DrawLine(pen, tableBounds.X, tableBounds.Y + tableBounds.Height - 1, tableBounds.X + tableBounds.Width - 1, tableBounds.Y + tableBounds.Height - 1);
}
}
else {
ControlPaint.PaintTableCellBorder(cellBorderStyle, g, tableBounds);
}
ControlPaint.PaintTableControlBorder(cellBorderStyle, g, displayRect);
}
else {
ControlPaint.PaintTableControlBorder(cellBorderStyle, g, displayRect);
}
}
[EditorBrowsable(EditorBrowsableState.Never)]
protected override void ScaleCore(float dx, float dy) {
base.ScaleCore(dx, dy);
ScaleAbsoluteStyles(new SizeF(dx,dy));
}
/// <include file='doc\Form.uex' path='docs/doc[@for="Form.ScaleControl"]/*' />
/// <devdoc>
/// Scale this form. Form overrides this to enforce a maximum / minimum size.
/// </devdoc>
protected override void ScaleControl(SizeF factor, BoundsSpecified specified) {
base.ScaleControl(factor, specified);
ScaleAbsoluteStyles(factor);
}
private void ScaleAbsoluteStyles(SizeF factor) {
TableLayout.ContainerInfo containerInfo = TableLayout.GetContainerInfo(this);
int i = 0;
// VSWhidbey 432427: the last row/column can be larger than the
// absolutely styled column width.
int lastRowHeight = -1;
int lastRow = containerInfo.Rows.Length -1;
if (containerInfo.Rows.Length > 0) {
lastRowHeight = containerInfo.Rows[lastRow].MinSize;
}
int lastColumnHeight = -1;
int lastColumn = containerInfo.Columns.Length -1;
if (containerInfo.Columns.Length > 0) {
lastColumnHeight = containerInfo.Columns[containerInfo.Columns.Length -1].MinSize;
}
foreach(ColumnStyle cs in ColumnStyles) {
if (cs.SizeType == SizeType.Absolute){
if (i == lastColumn && lastColumnHeight > 0) {
// the last column is typically expanded to fill the table. use the actual
// width in this case.
cs.Width = (float)Math.Round(lastColumnHeight * factor.Width);
}
else {
cs.Width = (float)Math.Round(cs.Width * factor.Width);
}
}
i++;
}
i = 0;
foreach(RowStyle rs in RowStyles) {
if (rs.SizeType == SizeType.Absolute) {
if (i == lastRow && lastRowHeight > 0) {
// the last row is typically expanded to fill the table. use the actual
// width in this case.
rs.Height = (float)Math.Round(lastRowHeight * factor.Height);
}
else {
rs.Height = (float)Math.Round(rs.Height * factor.Height);
}
}
}
}
#endregion
}
#region ControlCollection
/// <include file='doc\TableLayoutPanel.uex' path='docs/doc[@for="TableLayoutControlCollection"]/*' />
/// <devdoc>
/// <para>Represents a collection of controls on the TableLayoutPanel.</para>
/// </devdoc>
[ListBindable(false)]
[DesignerSerializer("System.Windows.Forms.Design.TableLayoutControlCollectionCodeDomSerializer, " + AssemblyRef.SystemDesign, "System.ComponentModel.Design.Serialization.CodeDomSerializer, " + AssemblyRef.SystemDesign)]
public class TableLayoutControlCollection : Control.ControlCollection {
private TableLayoutPanel _container;
/// <include file='doc\TableLayoutPanel.uex' path='docs/doc[@for="TableLayoutControlCollection.TableLayoutControlCollection"]/*' />
public TableLayoutControlCollection(TableLayoutPanel container) : base(container) {
_container = (TableLayoutPanel)container;
}
//the container of this TableLayoutControlCollection
/// <include file='doc\TableLayoutPanel.uex' path='docs/doc[@for="TableLayoutControlCollection.Container"]/*' />
public TableLayoutPanel Container {
get { return _container; }
}
//Add control to cell (x, y) on the table. The control becomes absolutely positioned if neither x nor y is equal to -1
/// <include file='doc\TableLayoutPanel.uex' path='docs/doc[@for="TableLayoutControlCollection.Add"]/*' />
public virtual void Add(Control control, int column, int row) {
base.Add(control);
_container.SetColumn(control, column);
_container.SetRow(control, row);
}
}
#endregion
}
| |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using gcsv = Google.Cloud.SecurityCenter.V1P1Beta1;
using sys = System;
namespace Google.Cloud.SecurityCenter.V1P1Beta1
{
/// <summary>Resource name for the <c>Finding</c> resource.</summary>
public sealed partial class FindingName : gax::IResourceName, sys::IEquatable<FindingName>
{
/// <summary>The possible contents of <see cref="FindingName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern <c>organizations/{organization}/sources/{source}/findings/{finding}</c>.
/// </summary>
OrganizationSourceFinding = 1,
/// <summary>
/// A resource name with pattern <c>folders/{folder}/sources/{source}/findings/{finding}</c>.
/// </summary>
FolderSourceFinding = 2,
/// <summary>
/// A resource name with pattern <c>projects/{project}/sources/{source}/findings/{finding}</c>.
/// </summary>
ProjectSourceFinding = 3,
}
private static gax::PathTemplate s_organizationSourceFinding = new gax::PathTemplate("organizations/{organization}/sources/{source}/findings/{finding}");
private static gax::PathTemplate s_folderSourceFinding = new gax::PathTemplate("folders/{folder}/sources/{source}/findings/{finding}");
private static gax::PathTemplate s_projectSourceFinding = new gax::PathTemplate("projects/{project}/sources/{source}/findings/{finding}");
/// <summary>Creates a <see cref="FindingName"/> containing an unparsed resource name.</summary>
/// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
/// <returns>
/// A new instance of <see cref="FindingName"/> containing the provided <paramref name="unparsedResourceName"/>.
/// </returns>
public static FindingName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new FindingName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="FindingName"/> with the pattern
/// <c>organizations/{organization}/sources/{source}/findings/{finding}</c>.
/// </summary>
/// <param name="organizationId">The <c>Organization</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="sourceId">The <c>Source</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="findingId">The <c>Finding</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="FindingName"/> constructed from the provided ids.</returns>
public static FindingName FromOrganizationSourceFinding(string organizationId, string sourceId, string findingId) =>
new FindingName(ResourceNameType.OrganizationSourceFinding, organizationId: gax::GaxPreconditions.CheckNotNullOrEmpty(organizationId, nameof(organizationId)), sourceId: gax::GaxPreconditions.CheckNotNullOrEmpty(sourceId, nameof(sourceId)), findingId: gax::GaxPreconditions.CheckNotNullOrEmpty(findingId, nameof(findingId)));
/// <summary>
/// Creates a <see cref="FindingName"/> with the pattern <c>folders/{folder}/sources/{source}/findings/{finding}</c>
/// .
/// </summary>
/// <param name="folderId">The <c>Folder</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="sourceId">The <c>Source</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="findingId">The <c>Finding</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="FindingName"/> constructed from the provided ids.</returns>
public static FindingName FromFolderSourceFinding(string folderId, string sourceId, string findingId) =>
new FindingName(ResourceNameType.FolderSourceFinding, folderId: gax::GaxPreconditions.CheckNotNullOrEmpty(folderId, nameof(folderId)), sourceId: gax::GaxPreconditions.CheckNotNullOrEmpty(sourceId, nameof(sourceId)), findingId: gax::GaxPreconditions.CheckNotNullOrEmpty(findingId, nameof(findingId)));
/// <summary>
/// Creates a <see cref="FindingName"/> with the pattern
/// <c>projects/{project}/sources/{source}/findings/{finding}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="sourceId">The <c>Source</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="findingId">The <c>Finding</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="FindingName"/> constructed from the provided ids.</returns>
public static FindingName FromProjectSourceFinding(string projectId, string sourceId, string findingId) =>
new FindingName(ResourceNameType.ProjectSourceFinding, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), sourceId: gax::GaxPreconditions.CheckNotNullOrEmpty(sourceId, nameof(sourceId)), findingId: gax::GaxPreconditions.CheckNotNullOrEmpty(findingId, nameof(findingId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="FindingName"/> with pattern
/// <c>organizations/{organization}/sources/{source}/findings/{finding}</c>.
/// </summary>
/// <param name="organizationId">The <c>Organization</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="sourceId">The <c>Source</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="findingId">The <c>Finding</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="FindingName"/> with pattern
/// <c>organizations/{organization}/sources/{source}/findings/{finding}</c>.
/// </returns>
public static string Format(string organizationId, string sourceId, string findingId) =>
FormatOrganizationSourceFinding(organizationId, sourceId, findingId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="FindingName"/> with pattern
/// <c>organizations/{organization}/sources/{source}/findings/{finding}</c>.
/// </summary>
/// <param name="organizationId">The <c>Organization</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="sourceId">The <c>Source</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="findingId">The <c>Finding</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="FindingName"/> with pattern
/// <c>organizations/{organization}/sources/{source}/findings/{finding}</c>.
/// </returns>
public static string FormatOrganizationSourceFinding(string organizationId, string sourceId, string findingId) =>
s_organizationSourceFinding.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(organizationId, nameof(organizationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(sourceId, nameof(sourceId)), gax::GaxPreconditions.CheckNotNullOrEmpty(findingId, nameof(findingId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="FindingName"/> with pattern
/// <c>folders/{folder}/sources/{source}/findings/{finding}</c>.
/// </summary>
/// <param name="folderId">The <c>Folder</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="sourceId">The <c>Source</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="findingId">The <c>Finding</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="FindingName"/> with pattern
/// <c>folders/{folder}/sources/{source}/findings/{finding}</c>.
/// </returns>
public static string FormatFolderSourceFinding(string folderId, string sourceId, string findingId) =>
s_folderSourceFinding.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(folderId, nameof(folderId)), gax::GaxPreconditions.CheckNotNullOrEmpty(sourceId, nameof(sourceId)), gax::GaxPreconditions.CheckNotNullOrEmpty(findingId, nameof(findingId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="FindingName"/> with pattern
/// <c>projects/{project}/sources/{source}/findings/{finding}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="sourceId">The <c>Source</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="findingId">The <c>Finding</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="FindingName"/> with pattern
/// <c>projects/{project}/sources/{source}/findings/{finding}</c>.
/// </returns>
public static string FormatProjectSourceFinding(string projectId, string sourceId, string findingId) =>
s_projectSourceFinding.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(sourceId, nameof(sourceId)), gax::GaxPreconditions.CheckNotNullOrEmpty(findingId, nameof(findingId)));
/// <summary>Parses the given resource name string into a new <see cref="FindingName"/> instance.</summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>organizations/{organization}/sources/{source}/findings/{finding}</c></description>
/// </item>
/// <item><description><c>folders/{folder}/sources/{source}/findings/{finding}</c></description></item>
/// <item><description><c>projects/{project}/sources/{source}/findings/{finding}</c></description></item>
/// </list>
/// </remarks>
/// <param name="findingName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="FindingName"/> if successful.</returns>
public static FindingName Parse(string findingName) => Parse(findingName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="FindingName"/> instance; optionally allowing an
/// unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>organizations/{organization}/sources/{source}/findings/{finding}</c></description>
/// </item>
/// <item><description><c>folders/{folder}/sources/{source}/findings/{finding}</c></description></item>
/// <item><description><c>projects/{project}/sources/{source}/findings/{finding}</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="findingName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <returns>The parsed <see cref="FindingName"/> if successful.</returns>
public static FindingName Parse(string findingName, bool allowUnparsed) =>
TryParse(findingName, allowUnparsed, out FindingName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="FindingName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>organizations/{organization}/sources/{source}/findings/{finding}</c></description>
/// </item>
/// <item><description><c>folders/{folder}/sources/{source}/findings/{finding}</c></description></item>
/// <item><description><c>projects/{project}/sources/{source}/findings/{finding}</c></description></item>
/// </list>
/// </remarks>
/// <param name="findingName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="FindingName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string findingName, out FindingName result) => TryParse(findingName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="FindingName"/> instance; optionally
/// allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>organizations/{organization}/sources/{source}/findings/{finding}</c></description>
/// </item>
/// <item><description><c>folders/{folder}/sources/{source}/findings/{finding}</c></description></item>
/// <item><description><c>projects/{project}/sources/{source}/findings/{finding}</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="findingName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="FindingName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string findingName, bool allowUnparsed, out FindingName result)
{
gax::GaxPreconditions.CheckNotNull(findingName, nameof(findingName));
gax::TemplatedResourceName resourceName;
if (s_organizationSourceFinding.TryParseName(findingName, out resourceName))
{
result = FromOrganizationSourceFinding(resourceName[0], resourceName[1], resourceName[2]);
return true;
}
if (s_folderSourceFinding.TryParseName(findingName, out resourceName))
{
result = FromFolderSourceFinding(resourceName[0], resourceName[1], resourceName[2]);
return true;
}
if (s_projectSourceFinding.TryParseName(findingName, out resourceName))
{
result = FromProjectSourceFinding(resourceName[0], resourceName[1], resourceName[2]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(findingName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private FindingName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string findingId = null, string folderId = null, string organizationId = null, string projectId = null, string sourceId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
FindingId = findingId;
FolderId = folderId;
OrganizationId = organizationId;
ProjectId = projectId;
SourceId = sourceId;
}
/// <summary>
/// Constructs a new instance of a <see cref="FindingName"/> class from the component parts of pattern
/// <c>organizations/{organization}/sources/{source}/findings/{finding}</c>
/// </summary>
/// <param name="organizationId">The <c>Organization</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="sourceId">The <c>Source</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="findingId">The <c>Finding</c> ID. Must not be <c>null</c> or empty.</param>
public FindingName(string organizationId, string sourceId, string findingId) : this(ResourceNameType.OrganizationSourceFinding, organizationId: gax::GaxPreconditions.CheckNotNullOrEmpty(organizationId, nameof(organizationId)), sourceId: gax::GaxPreconditions.CheckNotNullOrEmpty(sourceId, nameof(sourceId)), findingId: gax::GaxPreconditions.CheckNotNullOrEmpty(findingId, nameof(findingId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>Finding</c> ID. May be <c>null</c>, depending on which resource name is contained by this instance.
/// </summary>
public string FindingId { get; }
/// <summary>
/// The <c>Folder</c> ID. May be <c>null</c>, depending on which resource name is contained by this instance.
/// </summary>
public string FolderId { get; }
/// <summary>
/// The <c>Organization</c> ID. May be <c>null</c>, depending on which resource name is contained by this
/// instance.
/// </summary>
public string OrganizationId { get; }
/// <summary>
/// The <c>Project</c> ID. May be <c>null</c>, depending on which resource name is contained by this instance.
/// </summary>
public string ProjectId { get; }
/// <summary>
/// The <c>Source</c> ID. May be <c>null</c>, depending on which resource name is contained by this instance.
/// </summary>
public string SourceId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.OrganizationSourceFinding: return s_organizationSourceFinding.Expand(OrganizationId, SourceId, FindingId);
case ResourceNameType.FolderSourceFinding: return s_folderSourceFinding.Expand(FolderId, SourceId, FindingId);
case ResourceNameType.ProjectSourceFinding: return s_projectSourceFinding.Expand(ProjectId, SourceId, FindingId);
default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
}
}
/// <summary>Returns a hash code for this resource name.</summary>
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as FindingName);
/// <inheritdoc/>
public bool Equals(FindingName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(FindingName a, FindingName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(FindingName a, FindingName b) => !(a == b);
}
public partial class Finding
{
/// <summary>
/// <see cref="gcsv::FindingName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcsv::FindingName FindingName
{
get => string.IsNullOrEmpty(Name) ? null : gcsv::FindingName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
}
| |
using System;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
using System.Xml;
using DataAccessLayer.Interfaces;
namespace DataAccessLayer.SqlServer
{
public class SqlCommands : ISqlCommands
{
private readonly SqlConnection _currentConnection;
private readonly SqlTransaction _currentTransaction;
private readonly int _commandTimeOut;
public SqlCommands(SqlConnection currentConnection, SqlTransaction currentTransaction, int commandTimeOut)
{
if (currentConnection == null) throw new ArgumentNullException("currentConnection");
if (currentTransaction == null) throw new ArgumentNullException("currentTransaction");
_currentConnection = currentConnection;
_currentTransaction = currentTransaction;
_commandTimeOut = commandTimeOut;
}
/// <summary>
/// Executes a command that does not return a query
/// </summary>
/// <param name="commandText">Name of stored procedure to execute</param>
public int ExecuteNonQuery(string commandText)
{
return ExecuteNonQuery(commandText, null);
}
/// <summary>
/// Executes a command that does not return a query
/// </summary>
/// <param name="commandText">Name of stored procedure to execute</param>
/// <param name="parameters">DbParameter colleciton to use in executing</param>
public int ExecuteNonQuery(string commandText, params DbParameter[] parameters)
{
DbCommand cmd =null;
int rowsAffected = 0;
try
{
rowsAffected = ExecuteNonQuery(out cmd, commandText, parameters);
}
finally
{
cmd.Parameters.Clear();
cmd.Dispose();
}
return rowsAffected;
}
/// <summary>
/// Executes a command that does not return a query
/// </summary>
/// <param name="cmd">Output parameter that holds reference to the command object just executed</param>///
/// <param name="commandText">Name of stored procedure to execute</param>
/// <param name="parameters">DbParameter colleciton to use in executing</param>
/// <returns>DbCommand containing the command executed</returns>
public int ExecuteNonQuery(out DbCommand cmd, string commandText, params DbParameter[] parameters)
{
int rowsAffected = 0;
SqlCommand cmdExecute = BuildCommand(commandText, parameters);
rowsAffected = cmdExecute.ExecuteNonQuery();
cmd = cmdExecute;
return rowsAffected;
}
/// <summary>
/// Executes a command that returns a single value
/// </summary>
/// <param name="commandText">Name of stored procedure to execute</param>
/// <returns>Object holding result of execution of database</returns>
public object ExecuteScalar(string commandText)
{
return ExecuteScalar(commandText, null);
}
/// <summary>
/// Executes a command that returns a single value
/// </summary>
/// <param name="commandText">Name of stored procedure to execute</param>
/// <param name="parameters">DbParameter colleciton to use in executing</param>
/// <returns>Object holding result of execution of database</returns>
public object ExecuteScalar(string commandText, params DbParameter[] parameters)
{
DbCommand cmd;
object result = ExecuteScalar(out cmd, commandText, parameters);
cmd.Parameters.Clear();
cmd.Dispose();
return result;
}
/// <summary>
/// Executes a command that returns a single value
/// </summary>
/// <param name="cmd">Output parameter that holds reference to the command object just executed</param>
/// <param name="commandText">Name of stored procedure to execute</param>
/// <param name="parameters">DbParameter colleciton to use in executing</param>
/// <returns>Object holding result of execution of database</returns>
public object ExecuteScalar(out DbCommand cmd, string commandText, params DbParameter[] parameters)
{
// Find the command to execute
object data = null;
SqlCommand cmdScalar = BuildCommand(commandText, parameters);
data = cmdScalar.ExecuteScalar();
cmd = cmdScalar;
return data;
}
/// <summary>
/// Executes a command and returns a data reader
/// </summary>
/// <param name="commandText">Name of stored procedure to execute</param>
/// <returns>SqlDataReader allowing access to results from command</returns>
public DbDataReader ExecuteReader(string commandText)
{
return ExecuteReader(commandText, null);
}
/// <summary>
/// Executes a command and returns a data reader
/// </summary>
/// <param name="commandText">Name of stored procedure to execute</param>
/// <param name="parameters">DbParameter colleciton to use in executing</param>
/// <returns>SqlDataReader allowing access to results from command</returns>
public DbDataReader ExecuteReader(string commandText, params DbParameter[] parameters)
{
SqlDataReader reader = null;
using (SqlCommand cmdReader = new SqlCommand(commandText, _currentConnection))
{
cmdReader.CommandType = CommandType.StoredProcedure;
cmdReader.Transaction = _currentTransaction;
if (parameters != null && parameters.Length > 0)
cmdReader.Parameters.AddRange(parameters);
reader = cmdReader.ExecuteReader(CommandBehavior.CloseConnection);
}
return reader;
}
/// <summary>
/// Executes a command and returns a DataTable
/// </summary>
/// <param name="commandText">Name of stored procedure to execute</param>
/// <returns>DataTable populated with data from executing stored procedure</returns>
public DataTable ExecuteDataTable(string commandText)
{
return ExecuteDataTable(commandText, null);
}
/// <summary>
/// Executes a command and returns a DataTable
/// </summary>
/// <param name="commandText">Name of stored procedure to execute</param>
/// <param name="parameters">DbParameter colleciton to use in executing</param>
/// <returns>DataTable populated with data from executing stored procedure</returns>
public DataTable ExecuteDataTable(string commandText, params DbParameter[] parameters)
{
DbCommand cmd =null;
DataTable results;
try
{
results = ExecuteDataTable(out cmd, commandText, parameters);
}
finally
{
cmd.Parameters.Clear();
cmd.Dispose();
}
return results;
}
/// <summary>
/// Executes a command and returns a DataTable
/// </summary>
/// <param name="cmd">Output parameter that holds reference to the command object just executed</param>
/// <param name="commandText">Name of stored procedure to execute</param>
/// <param name="parameters">SqlParameter colleciton to use in executing</param>
/// <returns>DataTable populated with data from executing stored procedure</returns>
public DataTable ExecuteDataTable(out DbCommand cmd, string commandText, params DbParameter[] parameters)
{
SqlCommand cmdDataTable = BuildCommand(commandText, parameters);
DataTable result = new DataTable();
using (SqlDataAdapter da = new SqlDataAdapter(cmdDataTable))
{
da.Fill(result);
}
cmd = cmdDataTable;
return result;
}
/// <summary>
/// Executes a command and returns a DataTable
/// </summary>
/// <param name="commandText">Name of stored procedure to execute</param>
/// <returns>DataTable populated with data from executing stored procedure</returns>
public DataSet ExecuteDataSet(string commandText)
{
return ExecuteDataSet(commandText, null);
}
/// <summary>
/// Executes a command and returns a DataTable
/// </summary>
/// <param name="commandText">Name of stored procedure to execute</param>
/// <param name="parameters">SqlParameter colleciton to use in executing</param>
/// <returns>DataTable populated with data from executing stored procedure</returns>
public DataSet ExecuteDataSet(string commandText, params DbParameter[] parameters)
{
DbCommand cmd;
DataSet results = ExecuteDataSet(out cmd, commandText, parameters);
cmd.Parameters.Clear();
cmd.Dispose();
return results;
}
/// <summary>
/// Executes a command and returns a DataTable
/// </summary>
/// <param name="cmd">Output parameter that holds reference to the command object just executed</param>
/// <param name="commandText">Name of stored procedure to execute</param>
/// <param name="parameters">SqlParameter colleciton to use in executing</param>
/// <returns>DataTable populated with data from executing stored procedure</returns>
public DataSet ExecuteDataSet(out DbCommand cmd, string commandText, params DbParameter[] parameters)
{
SqlCommand cmdDataSet = BuildCommand(commandText, parameters);
DataSet result = new DataSet();
using (SqlDataAdapter adapter = new SqlDataAdapter(cmdDataSet))
{
adapter.Fill(result);
}
cmd = cmdDataSet;
return result;
}
/// <summary>
/// Executes a command and returns an XML reader.
/// </summary>
/// <param name="commandText">Name of stored procedure to execute</param>
/// <returns>An instance of XmlReader pointing to the stream of xml returned</returns>
public XmlReader ExecuteXmlReader(string commandText)
{
return ExecuteXmlReader(commandText, null);
}
/// <summary>
/// Executes a command and returns an XML reader.
/// </summary>
/// <param name="commandText">Name of stored procedure to execute</param>
/// <param name="parameters">SqlParameter colleciton to use in executing</param>
/// <returns>An instance of XmlReader pointing to the stream of xml returned</returns>
public XmlReader ExecuteXmlReader(string commandText, params DbParameter[] parameters)
{
DbCommand cmd;
XmlReader result = ExecuteXmlReader(out cmd, commandText, parameters);
cmd.Parameters.Clear();
cmd.Dispose();
return result;
}
/// <summary>
/// Executes a command and returns an XML reader.
/// </summary>
/// <param name="cmd">Output parameter that holds reference to the command object just executed</param>
/// <param name="commandText">Name of stored procedure to execute</param>
/// <param name="parameters">DbParameter colleciton to use in executing</param>
/// <returns>An instance of XmlReader pointing to the stream of xml returned</returns>
public XmlReader ExecuteXmlReader(out DbCommand cmd, string commandText, params DbParameter[] parameters)
{
SqlCommand cmdXmlReader = BuildCommand(commandText, parameters);
XmlReader outputReader = cmdXmlReader.ExecuteSafeXmlReader();
cmd = cmdXmlReader;
return outputReader;
}
/// <summary>
/// Builds a SqlCommand to execute
/// </summary>
/// <param name="storedProcedureName">Name of stored procedure to execute</param>
/// <param name="parameters">Param array of DbParameter objects to use with command</param>
/// <returns>SqlCommand object ready for use</returns>
private SqlCommand BuildCommand(string storedProcedureName, params DbParameter[] parameters)
{
SqlCommand newCommand = new SqlCommand(storedProcedureName, _currentConnection)
{
Transaction = _currentTransaction,
CommandType = CommandType.StoredProcedure
};
if (_commandTimeOut > 0)
{
newCommand.CommandTimeout = _commandTimeOut;
}
if (parameters != null)
newCommand.Parameters.AddRange(parameters);
return newCommand;
}
}
}
| |
// Copyright 2018, Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using Google.Cloud.Firestore.V1;
namespace Google.Cloud.Firestore.Tests
{
using System;
using System.Collections.Generic;
using System.Linq;
using Xunit;
using static ProtoHelpers;
/// <summary>
/// Tests for Query.CreateDocumentSnapshotComparer
/// </summary>
public partial class QueryTest
{
[Fact]
public void MissingDocumentSnapshotsAreRejected()
{
var query = s_db.Collection("col");
var comparer = query.CreateDocumentSnapshotComparer();
var doc = CreateSnapshot("doc", 1, 1);
var missing = DocumentSnapshot.ForMissingDocument(s_db, s_db.Document("col/doc2").Path, new Timestamp(10, 2));
Assert.Throws<ArgumentException>(() => comparer.Compare(doc, missing));
Assert.Throws<ArgumentException>(() => comparer.Compare(missing, doc));
}
[Fact]
public void DocumentsWithoutOrderedFieldsAreRejected()
{
var query = s_db.Collection("col").OrderBy("foo");
var comparer = query.CreateDocumentSnapshotComparer();
var doc1 = CreateSnapshot("doc1", 1, 1);
var doc2 = CreateSnapshot("doc2", 1, 1);
Assert.Throws<InvalidOperationException>(() => comparer.Compare(doc1, doc2));
}
[Fact]
public void EmptyQuery_OrderByDocId()
{
var query = s_db.Collection("col");
AssertDocsInOrder(query,
CreateSnapshot("doc1", 10, 5),
CreateSnapshot("doc2", 8, 9),
CreateSnapshot("doc3", 3, 1),
CreateSnapshot("doc4", 15, 15)
);
}
[Fact]
public void OrderByAscendingDocId()
{
var query = s_db.Collection("col").OrderBy(FieldPath.DocumentId);
AssertDocsInOrder(query,
CreateSnapshot("doc1", 10, 5),
CreateSnapshot("doc2", 8, 9),
CreateSnapshot("doc3", 3, 1),
CreateSnapshot("doc4", 15, 15)
);
}
[Fact]
public void OrderByDescendingDocId()
{
var query = s_db.Collection("col").OrderByDescending(FieldPath.DocumentId);
AssertDocsInOrder(query,
CreateSnapshot("doc4", 15, 15),
CreateSnapshot("doc3", 3, 1),
CreateSnapshot("doc2", 8, 9),
CreateSnapshot("doc1", 10, 5)
);
}
[Fact]
public void OrderByValue_AllUnique()
{
var query = s_db.Collection("col").OrderBy("value1");
AssertDocsInOrder(query,
CreateSnapshot("doc3", 3, 1),
CreateSnapshot("doc2", 8, 9),
CreateSnapshot("doc1", 10, 5),
CreateSnapshot("doc4", 15, 15)
);
}
[Fact]
public void OrderByValueDescending_AllUnique()
{
var query = s_db.Collection("col").OrderByDescending("value1");
AssertDocsInOrder(query,
CreateSnapshot("doc4", 15, 15),
CreateSnapshot("doc1", 10, 5),
CreateSnapshot("doc2", 8, 9),
CreateSnapshot("doc3", 3, 1)
);
}
[Fact]
public void OrderByValue_DocumentIdForTieBreak()
{
var query = s_db.Collection("col").OrderBy("value1");
AssertDocsInOrder(query,
CreateSnapshot("doc3", 3, 1),
CreateSnapshot("doc1", 8, 5),
CreateSnapshot("doc2", 8, 9),
CreateSnapshot("doc4", 15, 15)
);
}
[Fact]
public void OrderByValueDescending_DocumentIdForTieBreak()
{
var query = s_db.Collection("col").OrderByDescending("value1");
// Last ordering was descending, so doc2 comes before doc1.
AssertDocsInOrder(query,
CreateSnapshot("doc4", 15, 15),
CreateSnapshot("doc2", 8, 9),
CreateSnapshot("doc1", 8, 5),
CreateSnapshot("doc3", 3, 1)
);
}
[Fact]
public void OrderByTwoValues()
{
var query = s_db.Collection("col").OrderBy("value1").OrderBy("value2");
AssertDocsInOrder(query,
CreateSnapshot("doc4", 3, 5),
CreateSnapshot("doc1", 8, 5),
CreateSnapshot("doc3", 8, 5),
CreateSnapshot("doc2", 8, 9),
CreateSnapshot("doc5", 15, 15)
);
}
[Fact]
public void OrderByTwoValues_SecondIsDescending()
{
var query = s_db.Collection("col").OrderBy("value1").OrderByDescending("value2");
AssertDocsInOrder(query,
CreateSnapshot("doc4", 3, 5),
CreateSnapshot("doc2", 8, 9),
CreateSnapshot("doc3", 8, 5),
CreateSnapshot("doc1", 8, 5),
CreateSnapshot("doc5", 15, 15)
);
}
private static void AssertDocsInOrder(Query query, params DocumentSnapshot[] docs)
{
// Fixed seed for reproducibility.
var rng = new Random(100);
var comparer = query.CreateDocumentSnapshotComparer();
// This is slightly simpler than getting all permutations. Randomness in tests isn't great, but
// we'll almost certainly hit every permutation anyway, given the size we have.
for (int i = 0; i < 50; i++)
{
var unordered = Shuffle(docs, rng).ToList();
unordered.Sort(comparer);
// Assert based on ID rather than content, for cleaner error reporting.
Assert.Equal(docs.Select(doc => doc.Reference.Id), unordered.Select(doc => doc.Reference.Id));
}
}
public static IEnumerable<T> Shuffle<T>(IEnumerable<T> source, Random rng)
{
T[] elements = source.ToArray();
// Note i > 0 to avoid final pointless iteration
for (int i = elements.Length - 1; i > 0; i--)
{
// Swap element "i" with a random earlier element it (or itself)
int swapIndex = rng.Next(i + 1);
T tmp = elements[i];
elements[i] = elements[swapIndex];
elements[swapIndex] = tmp;
}
// Lazily yield (avoiding aliasing issues etc)
return elements;
}
private static DocumentSnapshot CreateSnapshot(string docId, int value1, int value2)
{
var readTime = new Timestamp(10, 2);
var proto = new Document
{
CreateTime = CreateProtoTimestamp(1, 10),
UpdateTime = CreateProtoTimestamp(2, 20),
Name = s_db.Document($"col/{docId}").Path,
Fields = { { "value1", CreateValue(value1) }, { "value2", CreateValue(value2) } }
};
return DocumentSnapshot.ForDocument(s_db, proto, readTime);
}
}
}
| |
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace sapHowmuch.Api.Repositories.SapEntities
{
[Table("OHEM")]
public partial class OHEM
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int empID { get; set; }
[StringLength(50)]
public string lastName { get; set; }
[StringLength(50)]
public string firstName { get; set; }
[StringLength(50)]
public string middleName { get; set; }
[StringLength(1)]
public string sex { get; set; }
[StringLength(20)]
public string jobTitle { get; set; }
public int? type { get; set; }
public short? dept { get; set; }
public short? branch { get; set; }
[StringLength(100)]
public string workStreet { get; set; }
[StringLength(100)]
public string workBlock { get; set; }
[StringLength(20)]
public string workZip { get; set; }
[StringLength(100)]
public string workCity { get; set; }
[StringLength(100)]
public string workCounty { get; set; }
[StringLength(3)]
public string workCountr { get; set; }
[StringLength(3)]
public string workState { get; set; }
public int? manager { get; set; }
public int? userId { get; set; }
public int? salesPrson { get; set; }
[StringLength(20)]
public string officeTel { get; set; }
[StringLength(20)]
public string officeExt { get; set; }
[StringLength(20)]
public string mobile { get; set; }
[StringLength(20)]
public string pager { get; set; }
[StringLength(20)]
public string homeTel { get; set; }
[StringLength(20)]
public string fax { get; set; }
[StringLength(100)]
public string email { get; set; }
public DateTime? startDate { get; set; }
public int? status { get; set; }
[Column(TypeName = "numeric")]
public decimal? salary { get; set; }
[StringLength(1)]
public string salaryUnit { get; set; }
[Column(TypeName = "numeric")]
public decimal? emplCost { get; set; }
[StringLength(1)]
public string empCostUnt { get; set; }
public DateTime? termDate { get; set; }
public int? termReason { get; set; }
[StringLength(30)]
public string bankCode { get; set; }
[StringLength(100)]
public string bankBranch { get; set; }
[StringLength(30)]
public string bankBranNo { get; set; }
[StringLength(100)]
public string bankAcount { get; set; }
[StringLength(100)]
public string homeStreet { get; set; }
[StringLength(100)]
public string homeBlock { get; set; }
[StringLength(20)]
public string homeZip { get; set; }
[StringLength(100)]
public string homeCity { get; set; }
[StringLength(100)]
public string homeCounty { get; set; }
[StringLength(3)]
public string homeCountr { get; set; }
[StringLength(3)]
public string homeState { get; set; }
public DateTime? birthDate { get; set; }
[StringLength(3)]
public string brthCountr { get; set; }
[StringLength(1)]
public string martStatus { get; set; }
public short? nChildren { get; set; }
[StringLength(64)]
public string govID { get; set; }
[StringLength(3)]
public string citizenshp { get; set; }
[StringLength(64)]
public string passportNo { get; set; }
public DateTime? passportEx { get; set; }
[StringLength(200)]
public string picture { get; set; }
[Column(TypeName = "ntext")]
public string remark { get; set; }
[Column(TypeName = "ntext")]
public string attachment { get; set; }
[StringLength(3)]
public string salaryCurr { get; set; }
[StringLength(3)]
public string empCostCur { get; set; }
[Column(TypeName = "ntext")]
public string WorkBuild { get; set; }
[Column(TypeName = "ntext")]
public string HomeBuild { get; set; }
public int? position { get; set; }
public int? AtcEntry { get; set; }
[StringLength(100)]
public string AddrTypeW { get; set; }
[StringLength(100)]
public string AddrTypeH { get; set; }
[StringLength(100)]
public string StreetNoW { get; set; }
[StringLength(100)]
public string StreetNoH { get; set; }
[StringLength(1)]
public string DispMidNam { get; set; }
[StringLength(1)]
public string NamePos { get; set; }
[StringLength(1)]
public string DispComma { get; set; }
[StringLength(8)]
public string CostCenter { get; set; }
[StringLength(20)]
public string CompanyNum { get; set; }
public int? VacPreYear { get; set; }
public int? VacCurYear { get; set; }
[StringLength(20)]
public string MunKey { get; set; }
[StringLength(2)]
public string TaxClass { get; set; }
[StringLength(2)]
public string InTaxLiabi { get; set; }
[StringLength(9)]
public string EmTaxCCode { get; set; }
[StringLength(9)]
public string RelPartner { get; set; }
[Column(TypeName = "numeric")]
public decimal? ExemptAmnt { get; set; }
[StringLength(20)]
public string ExemptUnit { get; set; }
[Column(TypeName = "numeric")]
public decimal? AddiAmnt { get; set; }
[StringLength(20)]
public string AddiUnit { get; set; }
[StringLength(50)]
public string TaxOName { get; set; }
[StringLength(20)]
public string TaxONum { get; set; }
[StringLength(50)]
public string HeaInsName { get; set; }
[StringLength(50)]
public string HeaInsCode { get; set; }
[StringLength(20)]
public string HeaInsType { get; set; }
[StringLength(20)]
public string SInsurNum { get; set; }
[StringLength(2)]
public string StatusOfP { get; set; }
[StringLength(2)]
public string StatusOfE { get; set; }
[StringLength(20)]
public string BCodeDateV { get; set; }
[StringLength(1)]
public string DevBAOwner { get; set; }
[StringLength(50)]
public string FNameSP { get; set; }
[StringLength(50)]
public string SurnameSP { get; set; }
public int? LogInstanc { get; set; }
public short? UserSign { get; set; }
public short? UserSign2 { get; set; }
public DateTime? UpdateDate { get; set; }
[StringLength(5)]
public string PersGroup { get; set; }
[StringLength(5)]
public string JTCode { get; set; }
[StringLength(20)]
public string ExtEmpNo { get; set; }
[StringLength(100)]
public string BirthPlace { get; set; }
[StringLength(2)]
public string PymMeth { get; set; }
[StringLength(3)]
public string ExemptCurr { get; set; }
[StringLength(3)]
public string AddiCurr { get; set; }
public int? STDCode { get; set; }
[StringLength(150)]
public string FatherName { get; set; }
[StringLength(100)]
public string CPF { get; set; }
[StringLength(20)]
public string CRC { get; set; }
[StringLength(1)]
public string ContResp { get; set; }
[StringLength(1)]
public string RepLegal { get; set; }
[StringLength(1)]
public string DirfDeclar { get; set; }
[StringLength(3)]
public string UF_CRC { get; set; }
[StringLength(30)]
public string IDType { get; set; }
[StringLength(1)]
public string Active { get; set; }
public int? BPLId { get; set; }
[StringLength(60)]
public string ManualNUM { get; set; }
public DateTime? PassIssue { get; set; }
[StringLength(254)]
public string PassIssuer { get; set; }
[StringLength(3)]
public string QualCode { get; set; }
[StringLength(1)]
public string PRWebAccss { get; set; }
[StringLength(1)]
public string PrePRWeb { get; set; }
[StringLength(15)]
public string BPLink { get; set; }
}
}
| |
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using FluentAssertions;
using Newtonsoft.Json;
using RichardSzalay.MockHttp;
using TypedRest.Endpoints.Rpc;
using Xunit;
namespace TypedRest.Endpoints
{
[Collection("Endpoint")]
public class CustomEndpointTest : EndpointTestBase
{
private readonly CustomEndpoint _endpoint;
public CustomEndpointTest()
{
_endpoint = new CustomEndpoint(EntryEndpoint, "endpoint");
}
[Fact]
public async Task TestAcceptHeader()
{
Mock.Expect(HttpMethod.Get, "http://localhost/endpoint")
.WithHeaders("Accept", JsonMime)
.Respond(_ => new StringContent("{}"));
await _endpoint.GetAsync();
}
[Fact]
public async Task TestAllowHeader()
{
Mock.Expect(HttpMethod.Get, "http://localhost/endpoint")
.Respond(_ => new StringContent("") {Headers = {Allow = {HttpMethod.Put.Method, HttpMethod.Post.Method}}});
await _endpoint.GetAsync();
_endpoint.IsMethodAllowed(HttpMethod.Put).Should().BeTrue();
_endpoint.IsMethodAllowed(HttpMethod.Post).Should().BeTrue();
_endpoint.IsMethodAllowed(HttpMethod.Delete).Should().BeFalse();
}
[Fact]
public async Task TestLink()
{
Mock.Expect(HttpMethod.Get, "http://localhost/endpoint")
.Respond(_ => new HttpResponseMessage(HttpStatusCode.NoContent)
{
Headers =
{
{"Link", "<a>; rel=target1, <b>; rel=target2"}
}
});
await _endpoint.GetAsync();
_endpoint.Link("target1").Should().Be(new Uri("http://localhost/a"));
_endpoint.Link("target2").Should().Be(new Uri("http://localhost/b"));
}
[Fact]
public void TestLinkLazy()
{
Mock.Expect(HttpMethod.Head, "http://localhost/endpoint")
.Respond(_ => new HttpResponseMessage(HttpStatusCode.NoContent)
{
Headers =
{
{"Link", "<a>; rel=target1, <b>; rel=target2"}
}
});
_endpoint.Link("target1").Should().Be(new Uri("http://localhost/a"));
_endpoint.Link("target2").Should().Be(new Uri("http://localhost/b"));
}
[Fact]
public async Task TestLinkAbsolute()
{
Mock.Expect(HttpMethod.Get, "http://localhost/endpoint")
.Respond(_ => new HttpResponseMessage(HttpStatusCode.NoContent)
{
Headers =
{
{"Link", "<http://localhost/b>; rel=target1"}
}
});
await _endpoint.GetAsync();
_endpoint.Link("target1").Should().Be(new Uri("http://localhost/b"));
}
[Fact]
public void TestLinkException()
{
Mock.Expect(HttpMethod.Head, "http://localhost/endpoint")
.Respond(_ => new HttpResponseMessage(HttpStatusCode.NoContent)
{
Headers = {{"Link", "<a>; rel=target1"}}
});
Assert.Throws<KeyNotFoundException>(() => _endpoint.Link("target2"));
}
[Fact]
public async Task TestGetLinks()
{
Mock.Expect(HttpMethod.Get, "http://localhost/endpoint")
.Respond(_ => new HttpResponseMessage(HttpStatusCode.NoContent)
{
Headers =
{
{"Link", "<target1>; rel=child; title=Title"},
{"Link", "<target2>; rel=child"}
}
});
await _endpoint.GetAsync();
_endpoint.GetLinks("child").Should().BeEquivalentTo(
(new Uri("http://localhost/target1"), "Title"),
(new Uri("http://localhost/target2"), (string?)null));
}
[Fact]
public async Task TestGetLinksEscaping()
{
Mock.Expect(HttpMethod.Get, "http://localhost/endpoint")
.Respond(_ => new HttpResponseMessage(HttpStatusCode.NoContent)
{
Headers =
{
{"Link", "<target1>; rel=child; title=\"Title,= 1\", <target2>; rel=child"}
}
});
await _endpoint.GetAsync();
_endpoint.GetLinks("child").Should().BeEquivalentTo(
(new Uri("http://localhost/target1"), "Title,= 1"),
(new Uri("http://localhost/target2"), (string?)null));
}
[Fact]
public void TestSetDefaultLink()
{
_endpoint.SetDefaultLink(rel: "child", "target");
_endpoint.Link("child").Should().Be(new Uri("http://localhost/target"));
}
[Fact]
public async Task TestLinkTemplate()
{
Mock.Expect(HttpMethod.Get, "http://localhost/endpoint")
.Respond(_ => new HttpResponseMessage(HttpStatusCode.NoContent)
{
Headers =
{
{"Link", "<a{?x}>; rel=child; templated=true"}
}
});
await _endpoint.GetAsync();
_endpoint.GetLinkTemplate("child").ToString().Should().Be("a{?x}");
}
[Fact]
public async Task TestLinkTemplateResolve()
{
Mock.Expect(HttpMethod.Get, "http://localhost/endpoint")
.Respond(_ => new HttpResponseMessage(HttpStatusCode.NoContent)
{
Headers =
{
{"Link", "<a{?x}>; rel=child; templated=true"}
}
});
await _endpoint.GetAsync();
_endpoint.LinkTemplate("child", new {x = "1"}).Should().Be(new Uri("http://localhost/a?x=1"));
}
[Fact]
public async Task TestLinkTemplateResolveAbsolute()
{
Mock.Expect(HttpMethod.Get, "http://localhost/endpoint")
.Respond(_ => new HttpResponseMessage(HttpStatusCode.NoContent)
{
Headers =
{
{"Link", "<http://localhost/b{?x}>; rel=child; templated=true"}
}
});
await _endpoint.GetAsync();
_endpoint.LinkTemplate("child", new {x = "1"}).Should().Be(new Uri("http://localhost/b?x=1"));
}
[Fact]
public async Task TestLinkTemplateResolveQuery()
{
Mock.Expect(HttpMethod.Get, "http://localhost/endpoint")
.Respond(_ => new HttpResponseMessage(HttpStatusCode.NoContent)
{
Headers =
{
{"Link", "<http://localhost/b{?x,y}>; rel=search; templated=true"}
}
});
await _endpoint.GetAsync();
_endpoint.LinkTemplate("search", new {x = "1", y = "2"}).Should().Be(new Uri("http://localhost/b?x=1&y=2"));
}
[Fact]
public void TestLinkTemplateException()
{
Mock.Expect(HttpMethod.Head, "http://localhost/endpoint")
.Respond(_ => new HttpResponseMessage(HttpStatusCode.NoContent)
{
Headers =
{
{"Link", "<a>; rel=child; templated=true"}
}
});
Assert.Throws<KeyNotFoundException>(() => _endpoint.GetLinkTemplate("child2"));
}
[Fact]
public async Task TestLinkHal()
{
string body = JsonConvert.SerializeObject(new
{
_links = new
{
single = new {href = "a"},
collection = new object[] {new {href = "b", title = "Title 1"}, new {href = "c"}},
template = new {href = "{id}", templated = true}
}
});
Mock.Expect(HttpMethod.Get, "http://localhost/endpoint").Respond("application/hal+json", body);
await _endpoint.GetAsync();
_endpoint.Link("single").Should().Be(new Uri("http://localhost/a"));
_endpoint.GetLinks("collection").Should().BeEquivalentTo(
(new Uri("http://localhost/b"), "Title 1"),
(new Uri("http://localhost/c"), (string?)null));
_endpoint.GetLinkTemplate("template").ToString().Should().Be("{id}");
}
[Fact]
public void TestSetDefaultLinkTemplate()
{
_endpoint.SetDefaultLinkTemplate(rel: "child", href: "a");
_endpoint.GetLinkTemplate("child").ToString().Should().Be("a");
}
[Fact]
public void TestEnsureTrailingSlashOnReferrerUri()
{
new ActionEndpoint(_endpoint, "subresource").Uri.Should().Be(new Uri("http://localhost/subresource"));
new ActionEndpoint(_endpoint, "./subresource").Uri.Should().Be(new Uri("http://localhost/endpoint/subresource"));
}
private class CustomEndpoint : EndpointBase
{
public CustomEndpoint(IEndpoint referrer, string relativeUri)
: base(referrer, relativeUri)
{}
public Task GetAsync() => HandleAsync(() => HttpClient.GetAsync(Uri));
public new bool? IsMethodAllowed(HttpMethod method) => base.IsMethodAllowed(method);
}
[Fact]
public void TestErrorHandlingWithNoContent()
{
Mock.Expect(HttpMethod.Get, "http://localhost/endpoint")
.Respond(_ => new HttpResponseMessage(HttpStatusCode.Conflict));
_endpoint.Awaiting(x => x.GetAsync())
.Should().Throw<InvalidOperationException>()
.WithMessage("http://localhost/endpoint responded with 409 Conflict");
}
[Fact]
public void TestErrorHandlingWithMessage()
{
Mock.Expect(HttpMethod.Get, "http://localhost/endpoint")
.Respond(_ => new HttpResponseMessage(HttpStatusCode.Conflict)
{
Content = new StringContent("{\"message\":\"my message\"}")
{
Headers = {ContentType = MediaTypeHeaderValue.Parse(JsonMime)}
}
});
_endpoint.Awaiting(x => x.GetAsync())
.Should().Throw<InvalidOperationException>()
.WithMessage("my message");
}
[Fact]
public void TestErrorHandlingWithArray()
{
Mock.Expect(HttpMethod.Get, "http://localhost/endpoint")
.Respond(_ => new HttpResponseMessage(HttpStatusCode.Conflict)
{
Content = new StringContent("[{\"message\":\"my message\"}]")
{
Headers = {ContentType = MediaTypeHeaderValue.Parse(JsonMime)}
}
});
_endpoint.Awaiting(x => x.GetAsync())
.Should().Throw<InvalidOperationException>()
.WithMessage("http://localhost/endpoint responded with 409 Conflict");
}
[Fact]
public void TestErrorHandlingWithUnknownContentType()
{
Mock.Expect(HttpMethod.Get, "http://localhost/endpoint")
.Respond(_ => new HttpResponseMessage(HttpStatusCode.Conflict) {Content = new ByteArrayContent(new byte[0])});
_endpoint.Awaiting(x => x.GetAsync())
.Should().Throw<InvalidOperationException>()
.WithMessage("http://localhost/endpoint responded with 409 Conflict");
}
}
}
| |
using System;
using System.IdentityModel.Tokens.Jwt;
using System.IO;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.OpenIdConnect;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpOverrides;
using Microsoft.AspNetCore.StaticFiles;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.FileProviders;
using IdentityModel;
using Mvc.RenderViewToString;
using NWebsec.Core.Common.Middleware.Options;
using Maw.Data;
using Maw.Domain;
using Maw.Domain.Captcha;
using Maw.Domain.Email;
using Maw.Security;
using Maw.TagHelpers;
using MawMvcApp.ViewModels;
using MawMvcApp.ViewModels.About;
namespace MawMvcApp
{
public class Startup
{
readonly IConfiguration _config;
readonly IWebHostEnvironment _env;
public Startup(IConfiguration config, IWebHostEnvironment hostingEnvironment)
{
_env = hostingEnvironment ?? throw new ArgumentNullException(nameof(hostingEnvironment));
_config = config ?? throw new ArgumentNullException(nameof(config));
}
public void ConfigureServices(IServiceCollection services)
{
JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
var authConfig = new AuthConfig();
_config.GetSection("AuthConfig").Bind(authConfig);
services
.Configure<ContactConfig>(_config.GetSection("ContactUs"))
.Configure<GmailApiEmailConfig>(_config.GetSection("Gmail"))
.Configure<EnvironmentConfig>(_config.GetSection("Environment"))
.Configure<GoogleCaptchaConfig>(_config.GetSection("GoogleRecaptcha"))
.Configure<UrlConfig>(_config.GetSection("UrlConfig"))
.ConfigureMawTagHelpers(opts => {
opts.AuthUrl = AddTrailingSlash(_config["UrlConfig:Auth"]);
opts.WwwUrl = AddTrailingSlash(_config["UrlConfig:Www"]);
})
.AddLogging()
.AddHttpContextAccessor()
.AddResponseCompression()
.AddHttpClient<MawApiService>()
.Services
.AddMawDataServices(_config["Environment:DbConnectionString"])
.AddMawDomainServices()
.AddTransient<RazorViewToStringRenderer>()
.AddScoped<IContentTypeProvider, FileExtensionContentTypeProvider>()
.AddSingleton<IFileProvider>(x => new PhysicalFileProvider(_config["Environment:AssetsPath"]))
.AddAntiforgery(opts => opts.HeaderName = "X-XSRF-TOKEN")
.AddAuthentication(opts => {
opts.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
opts.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
})
.AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, opts => {
opts.AccessDeniedPath = "/account/access-denied";
opts.LogoutPath = "/account/logout";
opts.ExpireTimeSpan = TimeSpan.FromMinutes(15);
})
.AddOpenIdConnect(OpenIdConnectDefaults.AuthenticationScheme, opts => {
opts.Authority = authConfig.AuthorizationUrl;
opts.ClientId = authConfig.ClientId;
opts.ClientSecret = authConfig.Secret;
opts.ResponseType = "code";
opts.SaveTokens = true;
opts.GetClaimsFromUserInfoEndpoint = true;
// core
opts.Scope.Add("openid");
opts.Scope.Add("profile");
opts.Scope.Add("offline_access");
// apis
opts.Scope.Add("maw_api");
// identity resources
opts.Scope.Add(JwtClaimTypes.Role);
opts.Scope.Add("email");
// https://github.com/IdentityServer/IdentityServer4/issues/1786
opts.ClaimActions.MapJsonKey("role", "role", "role");
opts.TokenValidationParameters.NameClaimType = JwtClaimTypes.Name;
opts.TokenValidationParameters.RoleClaimType = JwtClaimTypes.Role;
})
.Services
.AddAuthorization(opts =>
{
MawPolicyBuilder.AddMawPolicies(opts);
})
.AddCors(opts => {
opts.AddDefaultPolicy(builder => {
builder
.WithOrigins(GetCorsOrigins())
.AllowAnyHeader()
.AllowAnyMethod();
});
})
.AddControllersWithViews();
if(_env.IsDevelopment())
{
services.AddMiniProfiler();
}
}
public void Configure(IApplicationBuilder app)
{
if (_env.IsDevelopment())
{
app
.UseMiniProfiler()
.UseDeveloperExceptionPage();
AddDevPathMappings(app);
}
else
{
app
.UseExceptionHandler("/error/")
.UseHsts(hsts => hsts.MaxAge(365 * 2).IncludeSubdomains().Preload());
}
app
.UseXContentTypeOptions()
.UseReferrerPolicy(opts => opts.StrictOriginWhenCrossOrigin())
.UseCors()
.UseStaticFiles(new StaticFileOptions {
ContentTypeProvider = GetCustomMimeTypeProvider()
})
.UseResponseCompression()
.UseNoCacheHttpHeaders()
// .UseXfo(xfo => xfo.Deny()) // needed for recaptcha
.UseXXssProtection(opts => opts.EnabledWithBlockMode())
.UseRedirectValidation(opts => opts.AllowedDestinations(GetAllowedRedirectUrls()))
.UseCsp(DefineContentSecurityPolicy)
.UseRouting()
.UseForwardedHeaders(new ForwardedHeadersOptions
{
ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
})
.UseAuthentication()
.UseAuthorization()
.UseEndpoints(endpoints => {
endpoints.MapControllers();
});
}
void ConfigureDataProtection(IServiceCollection services)
{
var dpPath = _config["DataProtection:Path"];
if(!string.IsNullOrWhiteSpace(dpPath))
{
services
.AddDataProtection()
.PersistKeysToFileSystem(new DirectoryInfo(dpPath));
}
}
string[] GetCorsOrigins()
{
return new string[] {
_config["UrlConfig:Api"],
_config["UrlConfig:Photos"]
};
}
string[] GetAllowedRedirectUrls()
{
return new string[] {
AddTrailingSlash(_config["UrlConfig:Auth"]),
AddTrailingSlash(_config["UrlConfig:Files"]),
AddTrailingSlash(_config["UrlConfig:Photos"])
};
}
void DefineContentSecurityPolicy(IFluentCspOptions csp)
{
var connectSources = new string[] {
"https://www.google-analytics.com"
};
var fontSources = new string[] {
"https://fonts.gstatic.com",
"https://cdnjs.cloudflare.com"
};
var frameSources = new string[] {
"https://www.google.com/recaptcha/"
};
var imageSources = new string[] {
"data:",
"https://maps.gstatic.com",
"https://*.googleapis.com",
"https://www.google-analytics.com",
"https://vortex.accuweather.com"
};
var reportUris = new string[] {
"https://mikeandwanus.report-uri.com/r/d/csp/enforce"
};
var scriptSources = new string[] {
// bootstrap
"https://code.jquery.com",
"https://cdn.jsdelivr.net",
"https://cdnjs.cloudflare.com",
"https://stackpath.bootstrapcdn.com",
"https://www.google.com/recaptcha/",
"https://www.gstatic.com/recaptcha/",
"https://maps.googleapis.com",
"https://www.google-analytics.com",
"https://ssl.google-analytics.com",
"https://www.googletagmanager.com",
"https://www.accuweather.com",
"https://oap.accuweather.com",
"https://vortex.accuweather.com"
};
var styleSources = new string[] {
"https://cdnjs.cloudflare.com",
"https://fonts.googleapis.com",
"https://vortex.accuweather.com"
};
csp
.DefaultSources(s => s.None())
.BaseUris(s => s.Self())
.ConnectSources(s => {
s.Self();
s.CustomSources(connectSources);
})
.FontSources(s => s.CustomSources(fontSources))
.FrameSources(s => s.CustomSources(frameSources))
.ImageSources(s => {
s.Self();
s.CustomSources(imageSources);
})
.ManifestSources(s => s.Self())
.MediaSources(s => s.Self())
.ObjectSources(s => s.None())
.ReportUris(s => s.Uris(reportUris))
.ScriptSources(s => {
s.Self();
s.UnsafeInline();
s.CustomSources(scriptSources);
})
.StyleSources(s => {
s.Self();
s.UnsafeInline();
s.CustomSources(styleSources);
});
}
void AddDevPathMappings(IApplicationBuilder app)
{
AddDevPathMapping(app, "../client_apps_ng/dist/binary-clock", "/js/binary-clock");
AddDevPathMapping(app, "../client_apps_ng/dist/googlemaps", "/js/googlemaps");
AddDevPathMapping(app, "../client_apps_ng/dist/learning", "/js/learning");
AddDevPathMapping(app, "../client_apps_ng/dist/memory", "/js/memory");
AddDevPathMapping(app, "../client_apps_ng/dist/money-spin", "/js/money-spin");
AddDevPathMapping(app, "../client_apps_ng/dist/weekend-countdown", "/js/weekend-countdown");
AddDevPathMapping(app, "../client_apps/webgl_blender_model/dist", "/js/webgl_blender_model");
AddDevPathMapping(app, "../client_apps/webgl_cube/dist", "/js/webgl_cube");
AddDevPathMapping(app, "../client_apps/webgl_shader/dist", "/js/webgl_shader");
AddDevPathMapping(app, "../client_apps/webgl_text/dist", "/js/webgl_text");
}
void AddDevPathMapping(IApplicationBuilder app, string localRelativePath, string urlPath)
{
app.UseStaticFiles(new StaticFileOptions
{
FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), localRelativePath)),
RequestPath = new PathString(urlPath),
ContentTypeProvider = GetCustomMimeTypeProvider()
});
}
FileExtensionContentTypeProvider GetCustomMimeTypeProvider()
{
var provider = new FileExtensionContentTypeProvider();
provider.Mappings[".gltf"] = "model/gltf+json";
return provider;
}
string AddTrailingSlash(string val)
{
if(val == null) {
return val;
}
return val.EndsWith('/') ? val : $"{val}/";
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Network
{
using Azure;
using Management;
using Rest;
using Rest.Azure;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// BgpServiceCommunitiesOperations operations.
/// </summary>
internal partial class BgpServiceCommunitiesOperations : IServiceOperations<NetworkManagementClient>, IBgpServiceCommunitiesOperations
{
/// <summary>
/// Initializes a new instance of the BgpServiceCommunitiesOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal BgpServiceCommunitiesOperations(NetworkManagementClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the NetworkManagementClient
/// </summary>
public NetworkManagementClient Client { get; private set; }
/// <summary>
/// Gets all the available bgp service communities.
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<BgpServiceCommunity>>> ListWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2017-03-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/Microsoft.Network/bgpServiceCommunities").ToString();
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<BgpServiceCommunity>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<BgpServiceCommunity>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets all the available bgp service communities.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IPage<BgpServiceCommunity>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (nextPageLink == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextPageLink", nextPageLink);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters);
}
// Construct URL
string _url = "{nextLink}";
_url = _url.Replace("{nextLink}", nextPageLink);
List<string> _queryParameters = new List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IPage<BgpServiceCommunity>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<BgpServiceCommunity>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Xml;
using System.Xml.Serialization;
using AgenaTrader.API;
using AgenaTrader.Custom;
using AgenaTrader.Plugins;
using AgenaTrader.Helper;
/// <summary>
/// Version: 1.2
/// -------------------------------------------------------------------------
/// Simon Pucher 2017
/// -------------------------------------------------------------------------
/// http://vtadwiki.vtad.de/index.php/Elder_Ray_-_Bull_and_Bear_Power
/// -------------------------------------------------------------------------
/// ****** Important ******
/// To compile this script without any error you also need access to the utility indicator to use global source code elements.
/// You will find this script on GitHub: https://raw.githubusercontent.com/simonpucher/AgenaTrader/master/Utilities/GlobalUtilities_Utility.cs
/// -------------------------------------------------------------------------
/// Namespace holds all indicators and is required. Do not change it.
/// </summary>
namespace AgenaTrader.UserCode
{
[Description("Elder Ray - Bull and Bear Power")]
[IsEntryAttribute(true)]
[IsStopAttribute(false)]
[IsTargetAttribute(false)]
[OverrulePreviousStopPrice(false)]
public class Elder_Ray_Bull_and_Bear_Power_Condition : UserScriptedCondition
{
#region Variables
private int _period = 13;
private ElderRayTyp _ElderRayTyp = ElderRayTyp.BullPower;
private DoubleSeries ds_bull_power;
private DoubleSeries ds_bear_power;
private Color _plot0color = Const.DefaultIndicatorColor;
private int _plot0width = Const.DefaultLineWidth;
private DashStyle _plot0dashstyle = Const.DefaultIndicatorDashStyle;
private Color _plot1color = Const.DefaultIndicatorColor_GreyedOut;
private int _plot1width = Const.DefaultLineWidth;
private DashStyle _plot1dashstyle = Const.DefaultIndicatorDashStyle;
#endregion
protected override void OnInit()
{
IsEntry = true;
IsStop = false;
IsTarget = false;
Add(new OutputDescriptor(new Pen(this.Plot0Color, this.Plot0Width), OutputSerieDrawStyle.Line, "Occurred"));
Add(new OutputDescriptor(new Pen(this.Plot0Color, this.Plot1Width), OutputSerieDrawStyle.Line, "Entry"));
ds_bull_power = new DoubleSeries(this);
ds_bear_power = new DoubleSeries(this);
IsOverlay = false;
CalculateOnClosedBar = true;
this.RequiredBarsCount = 20;
}
protected override void OnCalculate()
{
EMA ema = EMA(this.Period);
double bull_power = High[0] - ema[0];
double bear_power = Low[0] - ema[0];
ds_bull_power.Set(bull_power);
ds_bear_power.Set(bear_power);
int resultsignal = 0;
if (ema[0] > ema[1] && bear_power < 0 && bear_power > ds_bear_power.Get(1))
{
resultsignal = 1;
}
if (ema[0] < ema[1] && bull_power > 0 && bull_power < ds_bull_power.Get(1))
{
resultsignal = -1;
}
Occurred.Set(resultsignal);
PlotColors[0][0] = this.Plot0Color;
OutputDescriptors[0].PenStyle = this.Dash0Style;
OutputDescriptors[0].Pen.Width = this.Plot0Width;
PlotColors[1][0] = this.Plot1Color;
OutputDescriptors[1].PenStyle = this.Dash1Style;
OutputDescriptors[1].Pen.Width = this.Plot1Width;
}
public override string DisplayName
{
get
{
return "Elder Ray (C)";
}
}
public override string ToString()
{
return "Elder Ray (C)";
}
#region Properties
[Browsable(false)]
[XmlIgnore()]
public DataSeries Occurred
{
get { return Outputs[0]; }
}
[Browsable(false)]
[XmlIgnore()]
public DataSeries Entry
{
get { return Outputs[1]; }
}
public override IList<DataSeries> GetEntries()
{
return new[]{Entry};
}
[Description("Type of ElderRayTyp.")]
[InputParameter]
[DisplayName("ElderRayTyp")]
public ElderRayTyp ElderRayTyp
{
get { return _ElderRayTyp; }
set { _ElderRayTyp = value; }
}
[Description("Period of the EMA.")]
[InputParameter]
[DisplayName("Period")]
public int Period
{
get { return _period; }
set { _period = value; }
}
/// <summary>
/// </summary>
[Description("Select Color for the indicator.")]
[Category("Plots")]
[DisplayName("Color")]
public Color Plot0Color
{
get { return _plot0color; }
set { _plot0color = value; }
}
// Serialize Color object
[Browsable(false)]
public string Plot0ColorSerialize
{
get { return SerializableColor.ToString(_plot0color); }
set { _plot0color = SerializableColor.FromString(value); }
}
/// <summary>
/// </summary>
[Description("Line width for indicator.")]
[Category("Plots")]
[DisplayName("Line width")]
public int Plot0Width
{
get { return _plot0width; }
set { _plot0width = Math.Max(1, value); }
}
/// <summary>
/// </summary>
[Description("DashStyle for indicator.")]
[Category("Plots")]
[DisplayName("DashStyle")]
public DashStyle Dash0Style
{
get { return _plot0dashstyle; }
set { _plot0dashstyle = value; }
}
/// <summary>
/// </summary>
[Description("Select color for the indicator.")]
[Category("Plots")]
[DisplayName("Color")]
public Color Plot1Color
{
get { return _plot1color; }
set { _plot1color = value; }
}
// Serialize Color object
[Browsable(false)]
public string Plot1ColorSerialize
{
get { return SerializableColor.ToString(_plot1color); }
set { _plot1color = SerializableColor.FromString(value); }
}
/// <summary>
/// </summary>
[Description("Line width for indicator.")]
[Category("Plots")]
[DisplayName("Line width")]
public int Plot1Width
{
get { return _plot1width; }
set { _plot1width = Math.Max(1, value); }
}
/// <summary>
/// </summary>
[Description("DashStyle for indicator.")]
[Category("Plots")]
[DisplayName("DashStyle")]
public DashStyle Dash1Style
{
get { return _plot1dashstyle; }
set { _plot1dashstyle = value; }
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Text;
using System.Linq;
namespace System.IO.Packaging
{
/// <summary>
/// This class has the utility methods for composing and parsing an Uri of pack:// scheme
/// </summary>
public static partial class PackUriHelper
{
#region Public Methods
/// <summary>
/// This method is used to create a valid pack Uri
/// </summary>
/// <param name="packageUri">This is the uri that points to the entire package.
/// This parameter should be an absolute Uri. This parameter cannot be null or empty
/// This method will create a valid pack uri that references the entire package</param>
/// <returns>A Uri with the "pack://" scheme</returns>
/// <exception cref="ArgumentNullException">If packageUri parameter is null</exception>
/// <exception cref="ArgumentException">If packageUri parameter is not an absolute Uri</exception>
public static Uri Create(Uri packageUri)
{
return Create(packageUri, null, null);
}
/// <summary>
/// This method is used to create a valid pack Uri
/// </summary>
/// <param name="packageUri">This is the uri that points to the entire package.
/// This parameter should be an absolute Uri. This parameter cannot be null or empty </param>
/// <param name="partUri">This is the uri that points to the part within the package
/// This parameter should be a relative Uri.
/// This parameter can be null in which case we will create a valid pack uri
/// that references the entire package</param>
/// <returns>A Uri with the "pack://" scheme</returns>
/// <exception cref="ArgumentNullException">If packageUri parameter is null</exception>
/// <exception cref="ArgumentException">If packageUri parameter is not an absolute Uri</exception>
/// <exception cref="ArgumentException">If partUri parameter does not conform to the valid partUri syntax</exception>
public static Uri Create(Uri packageUri, Uri partUri)
{
return Create(packageUri, partUri, null);
}
/// <summary>
/// This method is used to create a valid pack Uri
/// </summary>
/// <param name="packageUri">This is the uri that points to the entire package.
/// This parameter should be an absolute Uri. This parameter cannot be null or empty </param>
/// <param name="partUri">This is the uri that points to the part within the package
/// This parameter should be a relative Uri.
/// This parameter can be null in which case we will create a valid pack uri
/// that references the entire package</param>
/// <param name="fragment">Fragment for the resulting Pack URI. This parameter can be null
/// The fragment string must start with a "#"</param>
/// <returns>A Uri with the "pack://" scheme</returns>
/// <exception cref="ArgumentNullException">If packageUri parameter is null</exception>
/// <exception cref="ArgumentException">If packageUri parameter is not an absolute Uri</exception>
/// <exception cref="ArgumentException">If partUri parameter does not conform to the valid partUri syntax</exception>
/// <exception cref="ArgumentException">If fragment parameter is empty or does not start with a "#"</exception>
public static Uri Create(Uri packageUri, Uri partUri, string fragment)
{
// Step 1 - Validate input parameters
packageUri = ValidatePackageUri(packageUri);
if (partUri != null)
partUri = ValidatePartUri(partUri);
if (fragment != null)
{
if (fragment == string.Empty || fragment[0] != '#')
throw new ArgumentException(SR.Format(SR.FragmentMustStartWithHash, nameof(fragment)));
}
// Step 2 - Remove fragment identifier from the package URI, if it is present
// Since '#" is an excluded character in Uri syntax, it can only occur as the
// fragment identifier, in all other places it should be escaped.
// Hence we can safely use IndexOf to find the begining of the fragment.
string absolutePackageUri = packageUri.GetComponents(UriComponents.AbsoluteUri, UriFormat.UriEscaped);
if (!string.IsNullOrEmpty(packageUri.Fragment))
{
absolutePackageUri = absolutePackageUri.Substring(0, absolutePackageUri.IndexOf('#'));
}
// Step 3 - Escape: "%", "?", "@", "#" and "," in the package URI
absolutePackageUri = EscapeSpecialCharacters(absolutePackageUri);
// Step 4 - Replace all '/' with ',' in the resulting string
absolutePackageUri = absolutePackageUri.Replace('/', ',');
// Step 5 - Append pack:// at the begining and a '/' at the end of the pack uri obtained so far
absolutePackageUri = String.Concat(PackUriHelper.UriSchemePack, Uri.SchemeDelimiter, absolutePackageUri);
Uri packUri = new Uri(absolutePackageUri);
// Step 6 - Append the part Uri if present.
if (partUri != null)
packUri = new Uri(packUri, partUri);
// Step 7 - Append fragment if present
if (fragment != null)
packUri = new Uri(String.Concat(packUri.GetComponents(UriComponents.AbsoluteUri, UriFormat.UriEscaped), fragment));
// We want to ensure that internal content of resulting Uri has canonical form
// i.e. result.OrignalString would appear as perfectly formatted Uri string
// so we roundtrip the result.
return new Uri(packUri.GetComponents(UriComponents.AbsoluteUri, UriFormat.UriEscaped));
}
/// <summary>
/// This method parses the pack uri and returns the inner
/// Uri that points to the package as a whole.
/// </summary>
/// <param name="packUri">Uri which has pack:// scheme</param>
/// <returns>Returns the inner uri that points to the entire package</returns>
/// <exception cref="ArgumentNullException">If packUri parameter is null</exception>
/// <exception cref="ArgumentException">If packUri parameter is not an absolute Uri</exception>
/// <exception cref="ArgumentException">If packUri parameter does not have "pack://" scheme</exception>
/// <exception cref="ArgumentException">If inner packageUri extracted from the packUri has a fragment component</exception>
public static Uri GetPackageUri(Uri packUri)
{
//Parameter Validation is done in the following method
ValidateAndGetPackUriComponents(packUri, out Uri packageUri, out _);
return packageUri;
}
/// <summary>
/// This method parses the pack uri and returns the absolute
/// path of the URI. This corresponds to the part within the
/// package. This corresponds to the absolute path component in
/// the Uri. If there is no part component present, this method
/// returns a null
/// </summary>
/// <param name="packUri">Returns a relative Uri that represents the
/// part within the package. If the pack Uri points to the entire
/// package then we return a null</param>
/// <returns>Returns a relative URI with an absolute path that points to a part within a package</returns>
/// <exception cref="ArgumentNullException">If packUri parameter is null</exception>
/// <exception cref="ArgumentException">If packUri parameter is not an absolute Uri</exception>
/// <exception cref="ArgumentException">If packUri parameter does not have "pack://" scheme</exception>
/// <exception cref="ArgumentException">If partUri extracted from packUri does not conform to the valid partUri syntax</exception>
public static Uri GetPartUri(Uri packUri)
{
//Parameter Validation is done in the following method
ValidateAndGetPackUriComponents(packUri, out _, out Uri partUri);
return partUri;
}
/// <summary>
/// This method compares two pack uris and returns an int to indicate the equivalence.
/// </summary>
/// <param name="firstPackUri">First Uri of pack:// scheme to be compared</param>
/// <param name="secondPackUri">Second Uri of pack:// scheme to be compared</param>
/// <returns>A 32-bit signed integer indicating the lexical relationship between the compared Uri components.
/// Value - Less than zero means firstUri is less than secondUri
/// Value - Equal to zero means both the Uris are equal
/// Value - Greater than zero means firstUri is greater than secondUri </returns>
/// <exception cref="ArgumentException">If either of the Uris are not absolute or if either of the Uris are not with pack:// scheme</exception>
/// <exception cref="ArgumentException">If firstPackUri or secondPackUri parameter is not an absolute Uri</exception>
/// <exception cref="ArgumentException">If firstPackUri or secondPackUri parameter does not have "pack://" scheme</exception>
public static int ComparePackUri(Uri firstPackUri, Uri secondPackUri)
{
//If any of the operands are null then we simply call System.Uri compare to return the correct value
if (firstPackUri == null || secondPackUri == null)
{
return CompareUsingSystemUri(firstPackUri, secondPackUri);
}
else
{
int compareResult;
ValidateAndGetPackUriComponents(firstPackUri, out Uri firstPackageUri, out Uri firstPartUri);
ValidateAndGetPackUriComponents(secondPackUri, out Uri secondPackageUri, out Uri secondPartUri);
if (firstPackageUri.Scheme == PackUriHelper.UriSchemePack && secondPackageUri.Scheme == PackUriHelper.UriSchemePack)
{
compareResult = ComparePackUri(firstPackageUri, secondPackageUri);
}
else
{
compareResult = CompareUsingSystemUri(firstPackageUri, secondPackageUri);
}
//Iff the PackageUri match do we compare the part uris.
if (compareResult == 0)
{
compareResult = System.IO.Packaging.PackUriHelper.ComparePartUri(firstPartUri, secondPartUri);
}
return compareResult;
}
}
#endregion Public Methods
#region Internal Methods
//This method validates the packUri and returns its two components if they are valid-
//1. Package Uri
//2. Part Uri
internal static void ValidateAndGetPackUriComponents(Uri packUri, out Uri packageUri, out Uri partUri)
{
//Validate if its not null and is an absolute Uri, has pack:// Scheme.
packUri = ValidatePackUri(packUri);
packageUri = GetPackageUriComponent(packUri);
partUri = GetPartUriComponent(packUri);
}
#endregion Internal Methods
#region Private Constructor
static PackUriHelper()
{
EnsurePackSchemeRegistered();
}
#endregion Private Constructor
#region Private Methods
private static void EnsurePackSchemeRegistered()
{
if (!UriParser.IsKnownScheme(UriSchemePack))
{
// Indicate that we want a default hierarchical parser with a registry based authority
UriParser.Register(new GenericUriParser(GenericUriParserOptions.GenericAuthority), UriSchemePack, -1);
}
}
/// <summary>
/// This method is used to validate the package uri
/// </summary>
/// <param name="packageUri"></param>
/// <returns></returns>
private static Uri ValidatePackageUri(Uri packageUri)
{
if (packageUri == null)
throw new ArgumentNullException(nameof(packageUri));
if (!packageUri.IsAbsoluteUri)
throw new ArgumentException(SR.UriShouldBeAbsolute, nameof(packageUri));
return packageUri;
}
//validates is a given uri has pack:// scheme
private static Uri ValidatePackUri(Uri packUri)
{
if (packUri == null)
throw new ArgumentNullException(nameof(packUri));
if (!packUri.IsAbsoluteUri)
throw new ArgumentException(SR.UriShouldBeAbsolute, nameof(packUri));
if (packUri.Scheme != PackUriHelper.UriSchemePack)
throw new ArgumentException(SR.UriShouldBePackScheme, nameof(packUri));
return packUri;
}
/// <summary>
/// Escapes - %', '@', ',', '?' in the package URI
/// This method modifies the string in a culture safe and case safe manner.
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
private static string EscapeSpecialCharacters(string path)
{
// Escaping for the following - '%'; '@'; ',' and '?'
// !!Important!! - The order is important - The '%' sign should be escaped first.
// This is currently enforced by the order of characters in the s_specialCharacterChars array
foreach (char c in s_specialCharacterChars)
{
if (path.Contains(c))
{
path = path.Replace(c.ToString(), Uri.HexEscape(c));
}
}
return path;
}
//This method validates and returns the PackageUri component
private static Uri GetPackageUriComponent(Uri packUri)
{
Debug.Assert(packUri != null, "packUri parameter cannot be null");
//Step 1 - Get the authority part of the URI. This section represents that package URI
String hostAndPort = packUri.GetComponents(UriComponents.HostAndPort, UriFormat.UriEscaped);
//Step 2 - Replace the ',' with '/' to reconstruct the package URI
hostAndPort = hostAndPort.Replace(',', '/');
//Step 3 - Unescape the special characters that we had escaped to construct the packUri
Uri packageUri = new Uri(Uri.UnescapeDataString(hostAndPort));
if (packageUri.Fragment != String.Empty)
throw new ArgumentException(SR.InnerPackageUriHasFragment);
return packageUri;
}
//This method validates and returns the PartUri component.
private static PackUriHelper.ValidatedPartUri GetPartUriComponent(Uri packUri)
{
Debug.Assert(packUri != null, "packUri parameter cannot be null");
string partName = GetStringForPartUriFromAnyUri(packUri);
if (partName == String.Empty)
return null;
else
return ValidatePartUri(new Uri(partName, UriKind.Relative));
}
#endregion Private Methods
}
}
| |
/*
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the MIT License. See License.txt in the project root for license information.
*/
using System;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Xml.Linq;
using Adxstudio.Xrm.Web.UI.WebControls;
using Adxstudio.Xrm.Partner;
using Adxstudio.Xrm.Cms;
using Adxstudio.Xrm.Globalization;
using Microsoft.Xrm.Client;
using Microsoft.Xrm.Portal.Configuration;
using Microsoft.Xrm.Portal.Core;
using Microsoft.Xrm.Portal.Web;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Messages;
using Microsoft.Xrm.Sdk.Metadata;
using Microsoft.Xrm.Sdk.Query;
using Site.Pages;
namespace Site.Areas.Opportunities.Pages
{
public partial class OpportunityDetails : PortalPage
{
private Entity _opportunity;
public Entity OpenOpportunity
{
get
{
if (_opportunity != null)
{
return _opportunity;
}
Guid opportunityId;
if (!Guid.TryParse(Request["OpportunityID"], out opportunityId))
{
return null;
}
_opportunity = XrmContext.CreateQuery("opportunity").FirstOrDefault(o => o.GetAttributeValue<Guid>("opportunityid") == opportunityId);
return _opportunity;
}
}
protected void Page_Load(object sender, EventArgs e)
{
RedirectToLoginIfAnonymous();
var primaryContact = GetPrimaryContactAndSetCompanyName();
if (primaryContact == null || OpenOpportunity.GetAttributeValue<OptionSetValue>("statuscode") != null && (OpenOpportunity.GetAttributeValue<OptionSetValue>("statuscode").Value == (int)Adxstudio.Xrm.Partner.Enums.OpportunityStatusReason.Delivered || OpenOpportunity.GetAttributeValue<OptionSetValue>("statuscode").Value == (int)Adxstudio.Xrm.Partner.Enums.OpportunityStatusReason.Declined))
{
//Push a content-snippet error message saying that the opportunity is corrupt.
ErrorMessage.Visible = true;
CrmEntityFormViewsPanel.Visible = false;
OpportunityStatusPanel.Visible = false;
return;
}
AddFetchXmlToDataSource(ContactWebFormDataSource, "contact", "contactid", primaryContact.Id);
ContactWebFormDataSource.CrmDataContextName = ContactFormView.ContextName;
ContactFormView.DataSourceID = ContactWebFormDataSource.ID;
AddFetchXmlToDataSource(OpportunityDataSource, "opportunity", "opportunityid", OpenOpportunity.Id);
OpportunityDataSource.CrmDataContextName = OpportunityFormView.ContextName;
OpportunityFormView.DataSourceID = OpportunityDataSource.ID;
//GetContactList();
//GetLeadHistory();
PipelinePhaseText.Text = OpenOpportunity.GetAttributeValue<string>("stepname");
if (!IsPostBack)
{
GetContactList();
GetLeadHistory();
BindPipelinePhaseDetails();
}
BindProductsLeadNotesContactsAndAssignedTo();
if (!OpenOpportunity.GetAttributeValue<bool?>("adx_partnercreated").GetValueOrDefault(false))
{
CancelOpportunity.Visible = false;
CancelDetails.Visible = false;
//CancelButton.Visible = false;
//AddContactCheckBox.Visible = false;
//AddContactList.Visible = false;
}
else
{
ReturnToNetwork.Visible = false;
ReasonForReturn.Visible = false;
//ReasonForReturnSource.Visible = false;
}
AddContactButton.QueryStringCollection = CreateCustomerContactQueryString();
}
protected void CancelButton_Click(object sender, EventArgs e)
{
Response.Redirect(Request.RawUrl);
}
protected void SubmitButton_Click(object sender, EventArgs e)
{
if (!Page.IsValid)
{
return;
}
var accessPermissions = XrmContext.GetOpportunityAccessByContact(Contact);
var canSave = false;
foreach (var adxOpportunitypermissionse in accessPermissions)
{
if (adxOpportunitypermissionse.GetAttributeValue<bool?>("adx_write").GetValueOrDefault(false))
{
canSave = true;
}
}
if (!canSave)
{
return;
}
ContactFormView.UpdateItem();
OpportunityFormView.UpdateItem();
}
protected void ContactUpdating(object senders, CrmEntityFormViewUpdatingEventArgs e)
{
}
protected void OpportunityUpdating(object sender, CrmEntityFormViewUpdatingEventArgs e)
{
if (UpdatePipelinePhase.Checked)
{
e.Values["stepname"] = PipelinePhase.SelectedItem.Text;
e.Values["salesstagecode"] = int.Parse(PipelinePhase.SelectedValue);
//var processCode = PipelinePhase.SelectedValue;
}
else if (ReturnToNetwork.Checked)
{
e.Values["closeprobability"] = 0;
e.Values["adx_reasonforreturn"] = ReasonForReturn.SelectedIndex + 100000000;
}
e.Values["description"] = OpportunityNotes.Text;
Guid id;
if ((AssignToList != null && !String.IsNullOrEmpty(AssignToList.SelectedValue)) && Guid.TryParse(AssignToList.SelectedItem.Value, out id))
{
e.Values["msa_partneroppid"] = id;
}
}
protected void OpportunityUpdated(object sender, CrmEntityFormViewUpdatedEventArgs e)
{
var context = PortalCrmConfigurationManager.CreateServiceContext();
var opportunity = context.CreateQuery("opportunity").First(o => o.GetAttributeValue<Guid>("opportunityid") == e.Entity.Id);
var partnerReference = opportunity.GetAttributeValue<EntityReference>("msa_partnerid");
if (partnerReference == null)
{
return;
}
var partner = context.CreateQuery("account").First(p => p.GetAttributeValue<Guid>("accountid") == partnerReference.Id);
if (partner.GetAttributeValue<int?>("adx_numberofopportunitiesaccepted").GetValueOrDefault(0) == 0)
{
partner.SetAttributeValue("adx_numberofopportunitiesaccepted", 1);
}
var oppnote = new Entity("adx_opportunitynote");
var oppnote2 = new Entity("adx_opportunitynote");
var feedbackrate = (double)(partner.GetAttributeValue<int?>("adx_numberofopportunitieswithfeedback").GetValueOrDefault(0)) / (partner.GetAttributeValue<int?>("adx_numberofopportunitiesaccepted").GetValueOrDefault(1));
if (UpdatePipelinePhase.Checked)
{
context.SetOpportunityStatusAndSave(opportunity, "Open", 0);
opportunity.SetAttributeValue("statuscode", new OptionSetValue((int)Adxstudio.Xrm.Partner.Enums.OpportunityStatusReason.InProgress));
if (!opportunity.GetAttributeValue<bool?>("adx_feedbackyet").GetValueOrDefault(false))
{
if (!(opportunity.GetAttributeValue<bool?>("adx_partnercreated").GetValueOrDefault(false)))
{
partner.SetAttributeValue("adx_numberofopportunitieswithfeedback", partner.GetAttributeValue<int?>("adx_numberofopportunitieswithfeedback").GetValueOrDefault(0) + 1);
partner.SetAttributeValue("adx_feedbackrate", feedbackrate);
opportunity.SetAttributeValue("adx_feedbackyet", true);
}
}
oppnote.SetAttributeValue("adx_name", PipelinePhase.SelectedItem.Text);
oppnote.SetAttributeValue("adx_date", DateTime.UtcNow);
oppnote.SetAttributeValue("adx_description", PipelineUpdateDetails.Text);
}
else if (WinOpportunity.Checked)
{
context.SetOpportunityStatusAndSave(opportunity, "Won", 0);
opportunity.SetAttributeValue("statuscode", new OptionSetValue((int)Adxstudio.Xrm.Partner.Enums.OpportunityStatusReason.Purchased));
if (!opportunity.GetAttributeValue<bool?>("adx_feedbackyet").GetValueOrDefault(false))
{
if (!(opportunity.GetAttributeValue<bool?>("adx_partnercreated").GetValueOrDefault(false)))
{
partner.SetAttributeValue("adx_numberofopportunitieswithfeedback", partner.GetAttributeValue<int?>("adx_numberofopportunitieswithfeedback").GetValueOrDefault(0) + 1);
partner.SetAttributeValue("adx_feedbackrate", feedbackrate);
opportunity.SetAttributeValue("adx_feedbackyet", true);
}
}
opportunity.SetAttributeValue("adx_wondate", DateTime.UtcNow);
var wonSetting = XrmContext.CreateQuery("adx_sitesetting").FirstOrDefault(ss => ss.GetAttributeValue<string>("adx_name") == "Won Opportunity Note");
var wonNote = "Won";
wonNote = (wonSetting != null) ? wonSetting.GetAttributeValue<string>("adx_value") : wonNote;
oppnote.SetAttributeValue("adx_name", wonNote);
oppnote.SetAttributeValue("adx_date", DateTime.UtcNow);
oppnote.SetAttributeValue("adx_description", WonDetails.Text);
}
else if (CancelOpportunity.Checked)
{
context.SetOpportunityStatusAndSave(opportunity, "Lost", 0);
opportunity.SetAttributeValue("statuscode", new OptionSetValue((int)Adxstudio.Xrm.Partner.Enums.OpportunityStatusReason.Canceled));
if (!opportunity.GetAttributeValue<bool?>("adx_feedbackyet").GetValueOrDefault(false))
{
if (!(opportunity.GetAttributeValue<bool?>("adx_partnercreated").GetValueOrDefault(false)))
{
partner.SetAttributeValue("adx_numberofopportunitieswithfeedback", partner.GetAttributeValue<int?>("adx_numberofopportunitieswithfeedback").GetValueOrDefault(0) + 1);
partner.SetAttributeValue("adx_feedbackrate", feedbackrate);
opportunity.SetAttributeValue("adx_feedbackyet", true);
}
}
var cancelSetting = XrmContext.CreateQuery("adx_sitesetting").FirstOrDefault(ss => ss.GetAttributeValue<string>("adx_name") == "Cancel Opportunity Note");
var cancelNote = "Canceled";
cancelNote = (cancelSetting != null) ? cancelSetting.GetAttributeValue<string>("adx_value") : cancelNote;
oppnote.SetAttributeValue("adx_name", cancelNote);
oppnote.SetAttributeValue("adx_date", DateTime.UtcNow);
oppnote.SetAttributeValue("adx_description", CancelDetails.Text);
}
else if (AddContactCheckBox.Checked)
{
var selectedGuid = new Guid(AddContactList.SelectedItem.Value);
var contact = context.CreateQuery("contact").FirstOrDefault(c => c.GetAttributeValue<Guid>("contactid") == selectedGuid);
var contactCrossover = opportunity.GetRelatedEntities(context, new Relationship("adx_opportunity_contact")).FirstOrDefault(c => c.GetAttributeValue<Guid>("contactid") == contact.GetAttributeValue<Guid>("contactid"));
if (contactCrossover == null)
{
context.AddLink(opportunity, new Relationship("adx_opportunity_contact"), contact);
oppnote2.SetAttributeValue("adx_name", "Contact Added: " + contact.GetAttributeValue<string>("fullname"));
oppnote2.SetAttributeValue("adx_date", DateTime.UtcNow);
oppnote2.SetAttributeValue("adx_description", "Contact Added: " + contact.GetAttributeValue<string>("fullname"));
context.UpdateObject(contact);
}
//var opportunity = OpenOpportunity;
}
else if (ReturnToNetwork.Checked)
{
context.SetOpportunityStatusAndSave(opportunity, "Lost", 0);
opportunity.SetAttributeValue("statuscode", new OptionSetValue((int)Adxstudio.Xrm.Partner.Enums.OpportunityStatusReason.Returned));
if (!(opportunity.GetAttributeValue<bool?>("adx_partnercreated").GetValueOrDefault(false)))
{
partner.SetAttributeValue("adx_numberofreturnedopportunities", partner.GetAttributeValue<int?>("adx_numberofreturnedopportunities").GetValueOrDefault(0) + 1);
partner.SetAttributeValue("adx_returnrate", (double)partner.GetAttributeValue<int?>("adx_numberofreturnedopportunities").GetValueOrDefault(0) / (partner.GetAttributeValue<int?>("adx_numberofopportunitiesaccepted").GetValueOrDefault(1)));
}
var returnSetting = XrmContext.CreateQuery("adx_sitesetting").FirstOrDefault(ss => ss.GetAttributeValue<string>("adx_name") == "Return Opportunity Note");
var returnNote = "Returned to Network";
returnNote = (returnSetting != null) ? returnSetting.GetAttributeValue<string>("adx_value") : returnNote;
oppnote.SetAttributeValue("adx_name", returnNote);
oppnote.SetAttributeValue("adx_date", DateTime.UtcNow);
oppnote.SetAttributeValue("adx_description", ReasonForReturn.SelectedItem.Text);
//add the OpportunityNote entity
}
var calculatePartnerDetailsAction = new Entity("adx_calculatepartnercapacityworkflowaction");
calculatePartnerDetailsAction.SetAttributeValue("adx_accountid", partner.ToEntityReference());
var assignedto = opportunity.GetRelatedEntity(context, new Relationship("msa_contact_opportunity"));
if (!String.IsNullOrEmpty(oppnote.GetAttributeValue<string>("adx_name")))
{
oppnote.SetAttributeValue("adx_opportunityid", opportunity.ToEntityReference());
oppnote.SetAttributeValue("adx_assignedto", assignedto != null ? assignedto.GetAttributeValue<string>("fullname") : string.Empty);
context.AddObject(oppnote);
}
if (!String.IsNullOrEmpty(oppnote2.GetAttributeValue<string>("adx_name")))
{
oppnote2.SetAttributeValue("adx_opportunityid", opportunity.ToEntityReference());
oppnote2.SetAttributeValue("adx_assignedto", assignedto != null ? assignedto.GetAttributeValue<string>("fullname") : string.Empty);
context.AddObject(oppnote2);
}
var oppID = opportunity.Id;
context.UpdateObject(partner);
context.UpdateObject(opportunity);
context.SaveChanges();
if (!(opportunity.GetAttributeValue<bool?>("adx_partnercreated").GetValueOrDefault(false)))
{
context.AddObject(calculatePartnerDetailsAction);
}
context.SaveChanges();
var opp = context.CreateQuery("opportunity").FirstOrDefault(o => o.GetAttributeValue<Guid>("opportunityid") == oppID);
if (opp != null)
{
CurrentlyAssignedToLabel.Text = assignedto != null ? assignedto.GetAttributeValue<string>("fullname") : string.Empty;
PipelinePhaseText.Text = HttpUtility.HtmlEncode(opp.GetAttributeValue<string>("stepname"));
}
DisableControlsBasedOnPipelinePhaseAndAccessPermissions();
BindPipelinePhaseDetails();
GetLeadHistory();
GetContactList();
ConfirmationMessage.Visible = true;
}
private void AddHistoryDiv(OpportunityHistory history)
{
var div = new HtmlGenericControl("div")
{
InnerHtml = string.Format(@"<span class=""stage-date"">{0}</span><span class=""stage-name"">{1}</span>{2}{3}",
history.NoteCreatedOn.ToString("ddd, dd MMM yyyy HH:mm:ss 'GMT'"),
history.Name.Substring(history.Name.IndexOf('-') + 1),
!string.IsNullOrEmpty(history.PartnerAssignedTo)
? string.Format(@"<span class=""stage-assigned-to"">{0}{1}</span>", "Assigned To: ", Server.HtmlEncode(history.PartnerAssignedTo))
: string.Empty,
!string.IsNullOrEmpty(history.Details)
? string.Format(@"<div class=""stage-details"">{0}</div>", Server.HtmlEncode(history.Details))
: string.Empty)
};
// add div at the beginning for reverse chronological order
OpportunityHistoryPlaceHolder.Controls.AddAt(0, div);
}
private void AddContactDiv(Entity contact)
{
var account = (contact.GetAttributeValue<EntityReference>("parentcustomerid") != null) ?
ServiceContext.CreateQuery("account").FirstOrDefault(a => a.GetAttributeValue<Guid>("accountid") == (contact.GetAttributeValue<EntityReference>("parentcustomerid") == null ? Guid.Empty : contact.GetAttributeValue<EntityReference>("parentcustomerid").Id)) : null;
var companyName = account != null ? account.GetAttributeValue<string>("name") : contact.GetAttributeValue<string>("adx_organizationname");
HtmlGenericControl div;
var channelPermission = ServiceContext.GetChannelAccessByContact(Contact);
var channelWriteAccess = (channelPermission != null && channelPermission.GetAttributeValue<bool?>("adx_write").GetValueOrDefault(false));
var channelReadAccess = (channelPermission != null && channelPermission.GetAttributeValue<bool?>("adx_read").GetValueOrDefault(false));
var parentAccount = (account != null && account.GetAttributeValue<EntityReference>("msa_managingpartnerid") != null) ?
ServiceContext.CreateQuery("account").FirstOrDefault(a => a.GetAttributeValue<Guid>("accountid") == account.GetAttributeValue<EntityReference>("msa_managingpartnerid").Id) : null;
string contactFormattedString = "";
if ((parentAccount != null && channelPermission != null && channelPermission.GetAttributeValue<EntityReference>("adx_accountid") != null && (channelPermission.GetAttributeValue<EntityReference>("adx_accountid").Equals(parentAccount.ToEntityReference()))) ||
(contact.GetAttributeValue<EntityReference>("msa_managingpartnerid") != null && channelPermission != null && contact.GetAttributeValue<EntityReference>("msa_managingpartnerid").Equals(channelPermission.GetAttributeValue<EntityReference>("adx_accountid"))))
{
if (channelWriteAccess)
{
contactFormattedString = string.Format(@"<i class=""fa fa-edit""></i><a href=""{0}"" class=""Edit"">{1}</a>",
EditContactUrl(contact.GetAttributeValue<Guid>("contactid")),
contact.GetAttributeValue<string>("fullname"));
}
else if (channelReadAccess)
{
contactFormattedString = string.Format(@"<a href=""{0}"">{1}</a>",
ReadOnlyContactUrl(contact.GetAttributeValue<Guid>("contactid")),
contact.GetAttributeValue<string>("fullname"));
}
}
else
{
contactFormattedString = contact.GetAttributeValue<string>("fullname");
}
div = new HtmlGenericControl("div")
{
InnerHtml = string.Format(@"<span class=""contact-name"">{0}</span>{1}",
contactFormattedString,
!string.IsNullOrEmpty(companyName)
? string.Format(@"<span class=""contact-company-name"">{0}</span>", Server.HtmlEncode(companyName)) : string.Empty)
};
// add div at the beginning for reverse chronological order
OpportunityContactsPlaceHolder.Controls.AddAt(0, div);
}
private void GetLeadHistory()
{
foreach (var history in XrmContext.GetOpportunityHistories(OpenOpportunity))
{
AddHistoryDiv(history);
}
}
private void GetContactList()
{
var contacts = OpenOpportunity.GetRelatedEntities(XrmContext, new Relationship("adx_opportunity_contact"));
foreach (var contact in contacts)
{
AddContactDiv(contact);
}
}
private void BindProductsLeadNotesContactsAndAssignedTo()
{
var opportunityContact = OpenOpportunity.GetRelatedEntity(XrmContext, new Relationship("msa_contact_opportunity"));
CurrentlyAssignedToLabel.Text = (opportunityContact != null) ? opportunityContact.GetAttributeValue<string>("fullname") : string.Empty;
if (IsPostBack)
{
return;
}
Products.Text = string.Join(", ", OpenOpportunity.GetRelatedEntities(XrmContext, new Relationship("adx_opportunity_product")).Select(product => product.GetAttributeValue<string>("name")));
OpportunityNotes.Text = GetFormattedDescription(OpenOpportunity.GetAttributeValue<string>("description"));
//LeadAssignedTo.Text = OpenOpportunity.adx_PartnerAssignedTo;
var empli = new ListItem();
AssignToList.Items.Add(empli);
//var contacts = XrmContext.GetContactsForContact(Contact).Cast<Contact>();
AssertContactHasParentAccount();
var contacts = XrmContext.CreateQuery("contact").Where(c => c.GetAttributeValue<EntityReference>("parentcustomerid") == Contact.GetAttributeValue<EntityReference>("parentcustomerid"));
foreach (var contact in contacts)
{
if (contact.GetAttributeValue<OptionSetValue>("statecode") != null && contact.GetAttributeValue<OptionSetValue>("statecode").Value == 0)
{
var li = new ListItem()
{
Text = contact.GetAttributeValue<string>("fullname"),
Value = contact.GetAttributeValue<Guid>("contactid").ToString()
};
if (OpenOpportunity.GetAttributeValue<EntityReference>("msa_partneroppid") != null && li.Value == OpenOpportunity.GetAttributeValue<EntityReference>("msa_partneroppid").Id.ToString())
{
li.Selected = true;
}
AssignToList.Items.Add(li);
}
}
var partnerAccount = ServiceContext.CreateQuery("account").FirstOrDefault(a => a.GetAttributeValue<Guid>("accountid") == (Contact.GetAttributeValue<EntityReference>("parentcustomerid") == null ? Guid.Empty : Contact.GetAttributeValue<EntityReference>("parentcustomerid").Id));
if (partnerAccount != null)
{
var fetchXmlString = string.Format(@"
<fetch mapping=""logical"" distinct=""true"">
<entity name=""contact"">
<attribute name=""fullname"" />
<attribute name=""telephone1"" />
<attribute name=""contactid"" />
<order attribute=""fullname"" descending=""false"" />
<link-entity name=""account"" from=""accountid"" to=""parentcustomerid"" alias=""accountmanagingpartnerlink"" link-type=""outer"">
</link-entity>
<link-entity name=""adx_opportunity_contact"" from=""contactid"" to=""contactid"" link-type=""outer"">
<link-entity name=""opportunity"" from=""opportunityid"" to=""opportunityid"" alias=""opportunitylink"" link-type=""outer""></link-entity>
</link-entity>
<filter type=""and"">
<filter type=""or"">
<condition attribute=""msa_managingpartnerid"" operator=""eq"" value=""{0}"" />
<condition entityname=""accountmanagingpartnerlink"" attribute=""msa_managingpartnerid"" operator=""eq"" value=""{0}"" />
</filter>
<condition entityname=""opportunitylink"" attribute=""opportunityid"" operator=""ne"" value=""{1}"" />
</filter>
</entity>
</fetch>", partnerAccount.Id, OpenOpportunity.Id);
var fetchXml = XDocument.Parse(fetchXmlString);
var response = (RetrieveMultipleResponse)ServiceContext.Execute(new RetrieveMultipleRequest
{
Query = new FetchExpression(fetchXml.ToString())
});
var customerContacts = response.EntityCollection.Entities.ToList();
foreach (var li in customerContacts.Select(customerContact => new ListItem()
{
Text = customerContact.GetAttributeValue<string>("fullname"),
Value = customerContact.GetAttributeValue<Guid>("contactid").ToString()
}))
{ AddContactList.Items.Add(li); }
}
if (AddContactList.Items.Count >= 1) return;
AddContactList.Visible = false;
AddContactCheckBox.Visible = false;
}
private void BindPipelinePhaseDetails()
{
PipelinePhase.Items.Clear();
var response = (RetrieveAttributeResponse)ServiceContext.Execute(new RetrieveAttributeRequest
{
EntityLogicalName = "opportunity",
LogicalName = "salesstagecode"
});
var picklist = response.AttributeMetadata as PicklistAttributeMetadata;
if (picklist == null)
{
return;
}
var phase = 0;
foreach (var option in picklist.OptionSet.Options)
{
var text = option.Label.GetLocalizedLabelString();
var value = option.Value.Value.ToString();
if (text == OpenOpportunity.GetAttributeValue<string>("stepname"))
{
phase = option.Value.Value;
}
}
foreach (var option in picklist.OptionSet.Options)
{
var li = new ListItem()
{
Text = option.Label.GetLocalizedLabelString(),
Value = option.Value.Value.ToString()
};
if (option.Value.Value >= phase)
{
bool GoodToGo = true;
foreach (ListItem item in PipelinePhase.Items)
{
if (item.Text == li.Text)
{
GoodToGo = false;
}
}
if (GoodToGo)
{
PipelinePhase.Items.Add(li);
}
}
if (li.Text == OpenOpportunity.GetAttributeValue<string>("stepname"))
{
li.Selected = true;
}
}
DisableControlsBasedOnPipelinePhaseAndAccessPermissions();
}
private CrmDataSource CreateDataSource(string dataSourceId, string entityName, string entityIdAttribute, Guid? entityId)
{
var formViewDataSource = new CrmDataSource
{
ID = dataSourceId,
FetchXml = string.Format(@"<fetch mapping='logical'> <entity name='{0}'> <all-attributes /> <filter type='and'> <condition attribute = '{1}' operator='eq' value='{{{2}}}'/> </filter> </entity> </fetch>",
entityName,
entityIdAttribute,
entityId)
};
CrmEntityFormViewsPanel.Controls.Add(formViewDataSource);
return formViewDataSource;
}
private void AddFetchXmlToDataSource(CrmDataSource dataSource, string entityName, string entityIdAttribute, Guid? entityId)
{
dataSource.FetchXml =
string.Format(
@"<fetch mapping='logical'> <entity name='{0}'> <all-attributes /> <filter type='and'> <condition attribute = '{1}' operator='eq' value='{{{2}}}'/> </filter> </entity> </fetch>",
entityName,
entityIdAttribute,
entityId);
}
private void DisableControlsBasedOnPipelinePhaseAndAccessPermissions()
{
var accessPermissions = XrmContext.GetOpportunityAccessByContact(Contact);
//CreateCaseLink.Visible = false;
AssignToList.Visible = false;
//AssignToContact.Visible = false;
OpportunityStatusPanel.Visible = false;
SubmitButton.Visible = false;
CancelOpportunity.Visible = false;
foreach (var access in accessPermissions)
{
if (access.GetAttributeValue<bool?>("adx_write").GetValueOrDefault(false))
{
//CreateCaseLink.Visible = true;
SubmitButton.Visible = true;
OpportunityStatusPanel.Visible = true;
}
if (access.GetAttributeValue<bool?>("adx_assign").GetValueOrDefault(false))
{
AssignToList.Visible = true;
//AssignToContact.Visible = true;
}
if (access.GetAttributeValue<bool?>("adx_delete").GetValueOrDefault(false))
{
CancelOpportunity.Visible = true;
}
}
CurrentlyAssignedToLabel.Visible = !AssignToList.Visible;
if (OpenOpportunity.GetAttributeValue<OptionSetValue>("statecode") != null && (OpenOpportunity.GetAttributeValue<OptionSetValue>("statecode").Value == (int)Adxstudio.Xrm.Partner.Enums.OpportunityState.Lost || OpenOpportunity.GetAttributeValue<OptionSetValue>("statecode").Value == (int)Adxstudio.Xrm.Partner.Enums.OpportunityState.Won))
{
CrmEntityFormViewsPanel.Enabled = false;
OpportunityStatusPanel.Enabled = false;
}
}
private static string GetFormattedDescription(string description)
{
if (string.IsNullOrWhiteSpace(description))
{
return string.Empty;
}
var numbering = new Regex(@"(?= \d?\d\) )");
return numbering.Replace(description, "\n\n");
}
private Entity GetPrimaryContactAndSetCompanyName()
{
if (OpenOpportunity == null)
{
return null;
}
Entity primaryContact = null;
var customer = OpenOpportunity.GetAttributeValue<EntityReference>("customerid");
if (customer.LogicalName == "account")
{
var account = XrmContext.CreateQuery("account").First(a => a.GetAttributeValue<Guid>("accountid") == customer.Id);
CompanyName.Text = account.GetAttributeValue<string>("name");
primaryContact = account.GetRelatedEntity(XrmContext, new Relationship("account_primary_contact"));
var channelPermission = XrmContext.GetChannelAccessByContact(Contact);
var channelWriteAccess = (channelPermission != null && channelPermission.GetAttributeValue<bool?>("adx_write").GetValueOrDefault(false));
var channelReadAccess = (channelPermission != null && channelPermission.GetAttributeValue<bool?>("adx_read").GetValueOrDefault(false));
var parentAccount = (account.GetAttributeValue<EntityReference>("msa_managingpartnerid") != null) ? XrmContext.CreateQuery("account").FirstOrDefault(a => a.GetAttributeValue<Guid>("accountid") == account.GetAttributeValue<EntityReference>("msa_managingpartnerid").Id) : null;
if (parentAccount != null && ((channelPermission != null && channelPermission.GetAttributeValue<EntityReference>("adx_accountid") != null) && channelPermission.GetAttributeValue<EntityReference>("adx_accountid").Equals(parentAccount.ToEntityReference())) && (parentAccount.GetAttributeValue<OptionSetValue>("accountclassificationcode") != null && parentAccount.GetAttributeValue<OptionSetValue>("accountclassificationcode").Value == 100000000))
{
if (channelWriteAccess)
{
CompanyName.Text = string.Format(@"<a href=""{0}"" class=""Edit"">{1}</a>",
HttpUtility.HtmlEncode(EditAccountUrl(account.GetAttributeValue<Guid>("accountid"))),
HttpUtility.HtmlEncode(CompanyName.Text));
}
else if (channelReadAccess)
{
CompanyName.Text = string.Format(@"<a href=""{0}"" class=""Edit"">{1}</a>",
HttpUtility.HtmlEncode(ReadOnlyAccountUrl(account.GetAttributeValue<Guid>("accountid"))),
HttpUtility.HtmlEncode(CompanyName.Text));
}
}
//CompanyName.Attributes.Add("style", "white-space: nowrap;");
}
else if (customer.LogicalName == "contact")
{
primaryContact = XrmContext.CreateQuery("contact").First(c => c.GetAttributeValue<Guid>("contactid") == customer.Id);
var account = primaryContact.GetRelatedEntity(XrmContext, new Relationship("account_primary_contact"));
CompanyName.Text = account != null ? account.GetAttributeValue<string>("name") : primaryContact.GetAttributeValue<string>("adx_organizationname");
}
return primaryContact;
}
protected string EditAccountUrl(object id)
{
var page = ServiceContext.GetPageBySiteMarkerName(Website, "Edit Customer Account");
if (page == null) { return " "; }
var url = new UrlBuilder(ServiceContext.GetUrl(page));
url.QueryString.Set("AccountID", id.ToString());
return url.PathWithQueryString;
}
protected string ReadOnlyAccountUrl(object id)
{
var page = ServiceContext.GetPageBySiteMarkerName(Website, "Read Only Account View");
if (page == null) { return " "; }
var url = new UrlBuilder(ServiceContext.GetUrl(page));
url.QueryString.Set("AccountID", id.ToString());
return url.PathWithQueryString;
}
protected QueryStringCollection CreateCustomerContactQueryString()
{
var queryStringCollection = new QueryStringCollection("");
var oppId = OpenOpportunity.GetAttributeValue<Guid>("opportunityid");
var account = OpenOpportunity.GetAttributeValue<EntityReference>("customerid");
queryStringCollection.Set("OpportunityId", oppId.ToString());
if (account != null)
{
queryStringCollection.Set("AccountId", account.Id.ToString());
}
return queryStringCollection;
}
protected string EditContactUrl(object id)
{
var page = ServiceContext.GetPageBySiteMarkerName(Website, "Edit Customer Contact");
if (page == null) { return " "; }
var url = new UrlBuilder(ServiceContext.GetUrl(page));
url.QueryString.Set("ContactID", id.ToString());
return url.PathWithQueryString;
}
protected string ReadOnlyContactUrl(object id)
{
var page = ServiceContext.GetPageBySiteMarkerName(Website, "Read Only Contact View");
if (page == null) { return " "; }
var url = new UrlBuilder(ServiceContext.GetUrl(page));
url.QueryString.Set("ContactID", id.ToString());
return url.PathWithQueryString;
}
}
}
| |
/*
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 java.lang;
using org.junit;
namespace cnatural.compiler.test {
public class ExpressionsTest : ExecutionTest {
protected override String ResourcesPath {
get {
return "ExpressionsTest";
}
}
[Test]
public void returnInt() {
doTest("ReturnInt", new Class<?>[] {}, new Object[] {}, 1);
}
[Test]
public void returnTrue() {
doTest("ReturnTrue", new Class<?>[] {}, new Object[] {}, true);
}
[Test]
public void returnFalse() {
doTest("ReturnFalse", new Class<?>[] {}, new Object[] {}, false);
}
[Test]
public void returnString() {
doTest("ReturnString", new Class<?>[] {}, new Object[] {}, "string");
}
[Test]
public void returnNull() {
doTest("ReturnNull", new Class<?>[] {}, new Object[] {}, null);
}
[Test]
public void returnLong() {
doTest("ReturnLong", new Class<?>[] {}, new Object[] {}, 1L);
}
[Test]
public void returnFloat() {
doTest("ReturnFloat", new Class<?>[] {}, new Object[] {}, 1f);
}
[Test]
public void returnDouble() {
doTest("ReturnDouble", new Class<?>[] {}, new Object[] {}, 1d);
}
[Test]
public void fullNameCall() {
doTest("FullNameCall", new Class<?>[] {}, new Object[] {}, 1);
}
[Test]
public void intMinus() {
doTest("IntMinus", new Class<?>[] { typeof(int) }, new Object[] { 1 }, -1);
}
[Test]
public void intAdd() {
doTest("IntAdd", new Class<?>[] { typeof(int) }, new Object[] { 1 }, 2);
}
[Test]
public void intSubtract() {
doTest("IntSubtract", new Class<?>[] { typeof(int) }, new Object[] { 3 }, 2);
}
[Test]
public void intMultiply() {
doTest("IntMultiply", new Class<?>[] { typeof(int) }, new Object[] { 3 }, 6);
}
[Test]
public void intDivide() {
doTest("IntDivide", new Class<?>[] { typeof(int) }, new Object[] { 6 }, 3);
}
[Test]
public void intRemainder() {
doTest("IntRemainder", new Class<?>[] { typeof(int) }, new Object[] { 11 }, 2);
}
[Test]
public void intComplement() {
doTest("IntComplement", new Class<?>[] { typeof(int) }, new Object[] { 123 }, ~123);
}
[Test]
public void not() {
doTest("Not", new Class<?>[] { typeof(bool) }, new Object[] { true }, false);
}
[Test]
public void not_2() {
doTest("Not", new Class<?>[] { typeof(bool) }, new Object[] { false }, true);
}
[Test]
public void intPlus() {
doTest("IntPlus", new Class<?>[] { typeof(int) }, new Object[] { 1 }, 1);
}
[Test]
public void assignArgument() {
doTest("AssignArgument", new Class<?>[] { typeof(int) }, new Object[] { 1 }, 2);
}
[Test]
public void arrayAccess() {
doTest("ArrayAccess", new Class<?>[] {}, new Object[] {}, 1);
}
[Test]
public void arrayInitializer() {
doTest("ArrayInitializer", new Class<?>[] {}, new Object[] {}, 1);
}
[Test]
public void arraySize() {
doTest("ArraySize", new Class<?>[] {}, new Object[] {}, 2);
}
[Test]
public void intLessThan() {
doTest("IntLessThan", new Class<?>[] { typeof(int), typeof(int) }, new Object[] { 1, 2 }, true);
}
[Test]
public void intLessThan_2() {
doTest("IntLessThan", new Class<?>[] { typeof(int), typeof(int) }, new Object[] { 2, 1 }, false);
}
[Test]
public void intLessThan_3() {
doTest("IntLessThan", new Class<?>[] { typeof(int), typeof(int) }, new Object[] { 1, 1 }, false);
}
[Test]
public void intEqual() {
doTest("IntEqual", new Class<?>[] { typeof(int), typeof(int) }, new Object[] { 1, 1 }, true);
}
[Test]
public void intEqual_2() {
doTest("IntEqual", new Class<?>[] { typeof(int), typeof(int) }, new Object[] { 1, 2 }, false);
}
[Test]
public void intPostIncrement() {
doTest("IntPostIncrement", new Class<?>[] { typeof(int) }, new Object[] { 1 }, true);
}
[Test]
public void longPostIncrement() {
doTest("LongPostIncrement", new Class<?>[] { typeof(long) }, new Object[] { 1L }, true);
}
[Test]
public void intPreIncrement() {
doTest("IntPreIncrement", new Class<?>[] { typeof(int) }, new Object[] { 1 }, true);
}
[Test]
public void longPreIncrement() {
doTest("LongPreIncrement", new Class<?>[] { typeof(long) }, new Object[] { 1L }, true);
}
[Test]
public void intFieldPostIncrement() {
doTest("IntFieldPostIncrement", new Class<?>[] {}, new Object[] {}, true);
}
[Test]
public void longFieldPostIncrement() {
doTest("LongFieldPostIncrement", new Class<?>[] {}, new Object[] {}, true);
}
[Test]
public void intFieldPreIncrement() {
doTest("IntFieldPreIncrement", new Class<?>[] {}, new Object[] {}, true);
}
[Test]
public void longFieldPreIncrement() {
doTest("LongFieldPreIncrement", new Class<?>[] {}, new Object[] {}, true);
}
[Test]
public void intArrayPreIncrement() {
doTest("IntArrayPreIncrement", new Class<?>[] {}, new Object[] {}, true);
}
[Test]
public void intAddAssign() {
doTest("IntAddAssign", new Class<?>[] { typeof(int) }, new Object[] { 1 }, true);
}
[Test]
public void doubleAddAssign() {
doTest("DoubleAddAssign", new Class<?>[] { typeof(double) }, new Object[] { 1d }, true);
}
[Test]
public void typeof_0() {
doTest("Typeof", new Class<?>[] {}, new Object[] {}, typeof(int));
}
[Test]
public void typeofObject() {
doTest("TypeofObject", new Class<?>[] {}, new Object[] {}, typeof(Object));
}
[Test]
public void doubleIntAdd() {
doTest("DoubleIntAdd", new Class<?>[] { typeof(double), typeof(int) }, new Object[] { 2d, 3 }, 5d);
}
[Test]
public void doubleIntLessThan() {
doTest("DoubleIntLessThan", new Class<?>[] { typeof(double), typeof(int) }, new Object[] { 2d, 3 }, true);
}
[Test]
public void intDoubleEqual() {
doTest("IntDoubleEqual", new Class<?>[] { typeof(int), typeof(double) }, new Object[] { 1, 1d }, true);
}
[Test]
public void logicalAnd() {
doTest("LogicalAnd", new Class<?>[] { typeof(long), typeof(float) }, new Object[] { 1l, 1f }, true);
}
[Test]
public void logicalAnd_1() {
doTest("LogicalAnd", new Class<?>[] { typeof(long), typeof(float) }, new Object[] { 0l, 1f }, false);
}
[Test]
public void logicalOr() {
doTest("LogicalOr", new Class<?>[] { typeof(short), typeof(byte) }, new Object[] { (short)1, (byte)0 }, true);
}
[Test]
public void logicalOr_1() {
doTest("LogicalOr", new Class<?>[] { typeof(short), typeof(byte) }, new Object[] { (short)0, (byte)0 }, false);
}
[Test]
public void logicalAndIf() {
doTest("LogicalAndIf", new Class<?>[] { typeof(int), typeof(int) }, new Object[] { 1, 1 }, true);
}
[Test]
public void logicalAndIf_1() {
doTest("LogicalAndIf", new Class<?>[] { typeof(int), typeof(int) }, new Object[] { 1, 0 }, false);
}
[Test]
public void logicalOrIf() {
doTest("LogicalOrIf", new Class<?>[] { typeof(int), typeof(int) }, new Object[] { 1, 0 }, true);
}
[Test]
public void logicalOrIf_1() {
doTest("LogicalOrIf", new Class<?>[] { typeof(int), typeof(int) }, new Object[] { 0, 0 }, false);
}
[Test]
public void longIntAnd() {
doTest("LongIntAnd", new Class<?>[] { typeof(long), typeof(int) }, new Object[] { 0xFFFFFFFFFFl, 0xF0F0 }, 0xF0F0L);
}
[Test]
public void intLongOr() {
doTest("IntLongOr", new Class<?>[] { typeof(int), typeof(long) }, new Object[] { 0xF0F0, 0xF0F0F00000l }, 0xF0F0F0F0F0l);
}
[Test]
public void shortRightShift() {
doTest("ShortRightShift", new Class<?>[] { typeof(short) }, new Object[] { (short)8 }, 2);
}
[Test]
public void constantRightShift() {
doTest("ConstantRightShift", new Class<?>[] {}, new Object[] {}, (short)30864);
}
[Test]
public void literalChar() {
doTest("LiteralChar", new Class<?>[] {}, new Object[] {}, "abc");
}
[Test]
public void intConstantXor() {
doTest("IntConstantXor", new Class<?>[] { typeof(int) }, new Object[] { 0x0F0F }, 0xFFFF);
}
[Test]
public void instanceof_0() {
doTest("Instanceof", new Class<?>[] { typeof(Object) }, new Object[] { "STR" }, true);
}
[Test]
public void instanceof_1() {
doTest("Instanceof", new Class<?>[] { typeof(Object) }, new Object[] { new Object() }, false);
}
[Test]
public void verbatimString() {
doTest("VerbatimString", new Class<?>[] {}, new Object[] {}, "\r\n\" Verbatim\\String \"\r\n");
}
[Test]
public void asOperator() {
doTest("AsOperator", new Class<?>[] { typeof(Object) }, new Object[] { "STR" }, "STR");
}
[Test]
public void asOperator_1() {
doTest("AsOperator", new Class<?>[] { typeof(Object) }, new Object[] { new Object() }, null);
}
[Test]
public void nullCoalescing() {
doTest("NullCoalescing", new Class<?>[] { typeof(Object), typeof(Object) }, new Object[] { "STR", null }, "STR");
}
[Test]
public void nullCoalescing_1() {
doTest("NullCoalescing", new Class<?>[] { typeof(Object), typeof(Object) }, new Object[] { null, "STR" }, "STR");
}
[Test]
public void nullCoalescing_2() {
doTest("NullCoalescing", new Class<?>[] { typeof(Object), typeof(Object) }, new Object[] { "STR1", "STR2" }, "STR1");
}
[Test]
public void nullCoalescing_3() {
doTest("NullCoalescing", new Class<?>[] { typeof(Object), typeof(Object) }, new Object[] { null, null }, null);
}
[Test]
public void castToString() {
doTest("CastToString", new Class<?>[] { typeof(Object) }, new Object[] { "STR" }, "STR");
}
[Test]
public void castToInt() {
doTest("CastToInt", new Class<?>[] { typeof(float) }, new Object[] { 1f }, 1);
}
[Test]
public void constantLogicalAnd() {
doTest("ConstantLogicalAnd", new Class<?>[] {}, new Object[] {}, false);
}
[Test]
public void conditional() {
doTest("Conditional", new Class<?>[] { typeof(bool), typeof(Object), typeof(Object) }, new Object[] { true, "STR", null }, "STR");
}
[Test]
public void conditional_1() {
doTest("Conditional", new Class<?>[] { typeof(bool), typeof(Object), typeof(Object) }, new Object[] { false, "STR", null }, null);
}
[Test]
public void conditionalIf() {
doTest("ConditionalIf", new Class<?>[] { typeof(bool), typeof(bool), typeof(bool) },
new Object[] { true, true, false }, true);
}
[Test]
public void conditionalIf_1() {
doTest("ConditionalIf", new Class<?>[] { typeof(bool), typeof(bool), typeof(bool) },
new Object[] { false, true, false }, false);
}
[Test]
public void arrayInitializer2() {
doTest("ArrayInitializer2", new Class<?>[] {}, new Object[] {}, 3);
}
[Test]
public void intArrayAssign() {
doTest("IntArrayAssign", new Class<?>[] { typeof(int[]), typeof(int), typeof(int) },
new Object[] { new int[1], 0, 2 }, 2);
}
[Test]
public void logicalOr2() {
doTest("LogicalOr2", new Class<?>[] { typeof(String) }, new Object[] { null }, 1);
}
[Test]
public void logicalOr2_1() {
doTest("LogicalOr2", new Class<?>[] { typeof(String) }, new Object[] { "" }, 1);
}
[Test]
public void logicalOr2_2() {
doTest("LogicalOr2", new Class<?>[] { typeof(String) }, new Object[] { "STR" }, 2);
}
[Test]
public void logicalOr3() {
doTest("LogicalOr3", new Class<?>[] { typeof(String) }, new Object[] { null }, 1);
}
[Test]
public void logicalOr3_1() {
doTest("LogicalOr3", new Class<?>[] { typeof(String) }, new Object[] { "" }, 1);
}
[Test]
public void logicalOr3_2() {
doTest("LogicalOr3", new Class<?>[] { typeof(String) }, new Object[] { "STR" }, 1);
}
[Test]
public void logicalOr3_3() {
doTest("LogicalOr3", new Class<?>[] { typeof(String) }, new Object[] { "sTR" }, 2);
}
[Test]
public void logicalOrWhile() {
doTest("LogicalOrWhile", new Class<?>[] { typeof(int) }, new Object[] { -2 }, -1);
}
[Test]
public void logicalOrWhile_1() {
doTest("LogicalOrWhile", new Class<?>[] { typeof(int) }, new Object[] { 11 }, 9);
}
[Test]
public void logicalOrWhile2() {
doTest("LogicalOrWhile2", new Class<?>[] { typeof(int) }, new Object[] { 0 }, -1);
}
[Test]
public void logicalAnd2() {
doTest("LogicalAnd2", new Class<?>[] {}, new Object[] {}, 2);
}
[Test]
public void logicalAnd3() {
doTest("LogicalAnd3", new Class<?>[] {}, new Object[] {}, 2);
}
[Test]
public void logicalAnd4() {
doTest("LogicalAnd4", new Class<?>[] { typeof(bool), typeof(bool), typeof(bool) }, new Object[] { true, true, true }, true);
}
[Test]
public void logicalAnd4_1() {
doTest("LogicalAnd4", new Class<?>[] { typeof(bool), typeof(bool), typeof(bool) }, new Object[] { true, true, false }, false);
}
[Test]
public void logicalAnd4_2() {
doTest("LogicalAnd4", new Class<?>[] { typeof(bool), typeof(bool), typeof(bool) }, new Object[] { true, false, false }, false);
}
[Test]
public void logicalAnd5() {
doTest("LogicalAnd5", new Class<?>[] { typeof(bool), typeof(bool), typeof(bool) }, new Object[] { true, true, true }, true);
}
[Test]
public void logicalAnd5_1() {
doTest("LogicalAnd5", new Class<?>[] { typeof(bool), typeof(bool), typeof(bool) }, new Object[] { true, true, false }, false);
}
[Test]
public void logicalAnd5_2() {
doTest("LogicalAnd5", new Class<?>[] { typeof(bool), typeof(bool), typeof(bool) }, new Object[] { true, false, false }, false);
}
[Test]
public void logicalOr4() {
doTest("LogicalOr4", new Class<?>[] { typeof(bool), typeof(bool), typeof(bool) }, new Object[] { false, false, false }, false);
}
[Test]
public void logicalOr4_1() {
doTest("LogicalOr4", new Class<?>[] { typeof(bool), typeof(bool), typeof(bool) }, new Object[] { false, false, true }, true);
}
[Test]
public void logicalOr4_2() {
doTest("LogicalOr4", new Class<?>[] { typeof(bool), typeof(bool), typeof(bool) }, new Object[] { false, true, false }, true);
}
[Test]
public void logicalOr5() {
doTest("LogicalOr5", new Class<?>[] { typeof(bool), typeof(bool), typeof(bool) }, new Object[] { false, false, false }, false);
}
[Test]
public void logicalOr5_1() {
doTest("LogicalOr5", new Class<?>[] { typeof(bool), typeof(bool), typeof(bool) }, new Object[] { false, false, true }, true);
}
[Test]
public void logicalOr5_2() {
doTest("LogicalOr5", new Class<?>[] { typeof(bool), typeof(bool), typeof(bool) }, new Object[] { false, true, false }, true);
}
[Test]
public void logicalAndOr() {
doTest("LogicalAndOr", new Class<?>[] { typeof(bool), typeof(bool), typeof(bool) },
new Object[] { false, false, false }, false);
}
[Test]
public void logicalAndOr_1() {
doTest("LogicalAndOr", new Class<?>[] { typeof(bool), typeof(bool), typeof(bool) },
new Object[] { false, false, true }, true);
}
[Test]
public void logicalAndOr_2() {
doTest("LogicalAndOr", new Class<?>[] { typeof(bool), typeof(bool), typeof(bool) },
new Object[] { true, false, false }, false);
}
[Test]
public void logicalAndOr_3() {
doTest("LogicalAndOr", new Class<?>[] { typeof(bool), typeof(bool), typeof(bool) },
new Object[] { true, true, false }, true);
}
[Test]
public void logicalOrAnd() {
doTest("LogicalOrAnd", new Class<?>[] { typeof(bool), typeof(bool), typeof(bool) },
new Object[] { false, false, false }, false);
}
[Test]
public void logicalOrAnd_1() {
doTest("LogicalOrAnd", new Class<?>[] { typeof(bool), typeof(bool), typeof(bool) },
new Object[] { false, false, true }, false);
}
[Test]
public void logicalOrAnd_2() {
doTest("LogicalOrAnd", new Class<?>[] { typeof(bool), typeof(bool), typeof(bool) },
new Object[] { true, false, true }, true);
}
[Test]
public void logicalOrAnd_3() {
doTest("LogicalOrAnd", new Class<?>[] { typeof(bool), typeof(bool), typeof(bool) },
new Object[] { false, true, true }, true);
}
[Test]
public void logicalAndOr2() {
doTest("LogicalAndOr2", new Class<?>[] { typeof(bool), typeof(bool), typeof(bool) },
new Object[] { false, false, false }, false);
}
[Test]
public void logicalAndOr2_1() {
doTest("LogicalAndOr2", new Class<?>[] { typeof(bool), typeof(bool), typeof(bool) },
new Object[] { true, false, true }, true);
}
[Test]
public void logicalAndOr2_2() {
doTest("LogicalAndOr2", new Class<?>[] { typeof(bool), typeof(bool), typeof(bool) },
new Object[] { true, false, false }, false);
}
[Test]
public void logicalAndOr2_3() {
doTest("LogicalAndOr2", new Class<?>[] { typeof(bool), typeof(bool), typeof(bool) },
new Object[] { true, true, false }, true);
}
[Test]
public void logicalOrAnd2() {
doTest("LogicalOrAnd2", new Class<?>[] { typeof(bool), typeof(bool), typeof(bool) },
new Object[] { false, false, false }, false);
}
[Test]
public void logicalOrAnd2_1() {
doTest("LogicalOrAnd2", new Class<?>[] { typeof(bool), typeof(bool), typeof(bool) },
new Object[] { false, false, true }, false);
}
[Test]
public void logicalOrAnd2_2() {
doTest("LogicalOrAnd2", new Class<?>[] { typeof(bool), typeof(bool), typeof(bool) },
new Object[] { true, false, false }, true);
}
[Test]
public void logicalOrAnd2_3() {
doTest("LogicalOrAnd2", new Class<?>[] { typeof(bool), typeof(bool), typeof(bool) },
new Object[] { false, true, true }, true);
}
[Test]
public void logicalOrAndOr() {
doTest("LogicalOrAndOr", new Class<?>[] { typeof(bool), typeof(bool), typeof(bool), typeof(bool) },
new Object[] { false, false, false, false }, false);
}
[Test]
public void logicalOrAndOr_1() {
doTest("LogicalOrAndOr", new Class<?>[] { typeof(bool), typeof(bool), typeof(bool), typeof(bool) },
new Object[] { false, true, true, false }, true);
}
[Test]
public void logicalOrAndOr_2() {
doTest("LogicalOrAndOr", new Class<?>[] { typeof(bool), typeof(bool), typeof(bool), typeof(bool) },
new Object[] { true, false, false, true }, true);
}
[Test]
public void logicalOrAndOr_3() {
doTest("LogicalOrAndOr", new Class<?>[] { typeof(bool), typeof(bool), typeof(bool), typeof(bool) },
new Object[] { false, true, false, false }, false);
}
[Test]
public void logicalAndOrAnd() {
doTest("LogicalAndOrAnd", new Class<?>[] { typeof(bool), typeof(bool), typeof(bool), typeof(bool) },
new Object[] { false, false, false, false }, false);
}
[Test]
public void logicalAndOrAnd_1() {
doTest("LogicalAndOrAnd", new Class<?>[] { typeof(bool), typeof(bool), typeof(bool), typeof(bool) },
new Object[] { false, true, true, false }, false);
}
[Test]
public void logicalAndOrAnd_2() {
doTest("LogicalAndOrAnd", new Class<?>[] { typeof(bool), typeof(bool), typeof(bool), typeof(bool) },
new Object[] { true, true, false, false }, true);
}
[Test]
public void logicalAndOrAnd_3() {
doTest("LogicalAndOrAnd", new Class<?>[] { typeof(bool), typeof(bool), typeof(bool), typeof(bool) },
new Object[] { false, true, true, true }, true);
}
[Test]
public void logicalAndOrAnd_4() {
doTest("LogicalAndOrAnd", new Class<?>[] { typeof(bool), typeof(bool), typeof(bool), typeof(bool) },
new Object[] { true, false, true, true }, true);
}
[Test]
public void logicalAndOrAnd_5() {
doTest("LogicalAndOrAnd", new Class<?>[] { typeof(bool), typeof(bool), typeof(bool), typeof(bool) },
new Object[] { true, false, true, false }, false);
}
[Test]
public void byteAssign() {
doTest("ByteAssign", new Class<?>[] {}, new Object[] {}, 1);
}
[Test]
public void arrayFieldInitializer() {
doTest("ArrayFieldInitializer", new Class<?>[] {}, new Object[] {}, 3);
}
[Test]
public void byteArrayInitializer() {
doTest("ByteArrayInitializer", new Class<?>[] {}, new Object[] {}, 3);
}
[Test]
public void castIntToByte() {
doTest("CastIntToByte", new Class<?>[] { typeof(int) }, new Object[] { 3 }, 3);
}
[Test]
public void castIntToByte_1() {
doTest("CastIntToByte", new Class<?>[] { typeof(int) }, new Object[] { 0xFFFFFFFF }, -1);
}
[Test]
public void stringArrayList() {
doTest("StringArrayList", new Class<?>[] { typeof(java.util.ArrayList<?>) },
new Object[] { new java.util.ArrayList<String> { "a", "aa", "aaa" } }, 2);
}
[Test]
public void objectArray() {
doTest("ObjectArray", new Class<?>[] {}, new Object[] {}, 3);
}
[Test]
public void arrayIndexer() {
doTest("ArrayIndexer", new Class<?>[] {}, new Object[] {}, 2);
}
[Test]
public void arrayIndexerAssign() {
doTest("ArrayIndexerAssign", new Class<?>[] {}, new Object[] {}, true);
}
[Test]
public void interfaceToString() {
doTest("InterfaceToString", new Class<?>[] {}, new Object[] {}, "OK");
}
[Test]
public void arrayOfArray() {
doTest("ArrayOfArray", new Class<?>[] {}, new Object[] {}, 1);
}
[Test]
public void unboundedTypeof() {
doTest("UnboundedTypeof", new Class<?>[] {}, new Object[] {}, typeof(java.util.ArrayList<?>));
}
[Test]
public void constantNot() {
doTest("ConstantNot", new Class<?>[] {}, new Object[] {}, true);
}
[Test]
public void autoboxingBoolean() {
doTest("AutoboxingBoolean", new Class<?>[] {}, new Object[] {}, true);
}
[Test]
public void autoboxingArgument() {
doTest("AutoboxingArgument", new Class<?>[] { typeof(int) }, new Object[] { 2 }, 2);
}
[Test]
public void autoboxingReturn() {
doTest("AutoboxingReturn", new Class<?>[] { typeof(int) }, new Object[] { 2 }, 2);
}
[Test]
public void autoboxingReturn2() {
doTest("AutoboxingReturn2", new Class<?>[] { typeof(Long) }, new Object[] { 2L }, 2L);
}
[Test]
public void autoboxingIncrement() {
doTest("AutoboxingIncrement", new Class<?>[] { typeof(Float) }, new Object[] { 2f }, 3f);
}
[Test]
public void autoboxingFieldIncrement() {
doTest("AutoboxingFieldIncrement", new Class<?>[] {}, new Object[] {}, (byte)3);
}
[Test]
public void autoboxingFieldIncrement2() {
doTest("AutoboxingFieldIncrement2", new Class<?>[] {}, new Object[] {}, (byte)3);
}
[Test]
public void autoboxingAssignLocal() {
doTest("AutoboxingAssignLocal", new Class<?>[] { typeof(Short) }, new Object[] { (short)2 }, (short)2);
}
[Test]
public void autoboxingAssignLocal2() {
doTest("AutoboxingAssignLocal2", new Class<?>[] { typeof(Short) }, new Object[] { (short)2 }, 2);
}
[Test]
public void autoboxingAssignLocal3() {
doTest("AutoboxingAssignLocal3", new Class<?>[] { typeof(short) }, new Object[] { (short)2 }, (short)2);
}
[Test]
public void autoboxingUnary() {
doTest("AutoboxingUnary", new Class<?>[] { typeof(Integer) }, new Object[] { 2 }, -2);
}
[Test]
public void autoboxingUnary2() {
doTest("AutoboxingUnary2", new Class<?>[] { typeof(int) }, new Object[] { 2 }, -2);
}
[Test]
public void autoboxingBinary() {
doTest("AutoboxingBinary", new Class<?>[] { typeof(Character), typeof(Character) }, new Object[] { '\u0001', '\u0002' }, 3);
}
[Test]
public void autoboxingBinary2() {
doTest("AutoboxingBinary2", new Class<?>[] { typeof(Integer), typeof(Long) }, new Object[] { 1, 2L }, true);
}
[Test]
public void autoboxingElementAccess() {
doTest("AutoboxingElementAccess", new Class<?>[] { typeof(Integer) }, new Object[] { 1 }, 2);
}
[Test]
public void autoboxingElementAccess2() {
doTest("AutoboxingElementAccess2", new Class<?>[] { typeof(int) }, new Object[] { 1 }, 3);
}
[Test]
public void autoboxingArrayInitializer() {
doTest("AutoboxingArrayInitializer", new Class<?>[] { typeof(int) }, new Object[] { 1 }, 1);
}
[Test]
public void autoboxingFieldIncrement3() {
doTest("AutoboxingFieldIncrement3", new Class<?>[] {}, new Object[] {}, 3l);
}
[Test]
public void autoboxingElementAccess3() {
doTest("AutoboxingElementAccess3", new Class<?>[] { typeof(Integer) }, new Object[] { 1 }, 1);
}
[Test]
public void autoboxingConversions() {
doTest("AutoboxingConversions", new Class<?>[] {}, new Object[] {}, 2);
}
[Test]
public void autoboxingConversions2() {
doTest("AutoboxingConversions2", new Class<?>[] {}, new Object[] {}, 2L);
}
[Test]
public void autoboxingObject() {
doTest("AutoboxingObject", new Class<?>[] {}, new Object[] {}, 1);
}
[Test]
public void autoboxingEqual() {
doTest("AutoboxingEqual", new Class<?>[] {}, new Object[] {}, false);
}
[Test]
public void autoboxingEqual2() {
doTest("AutoboxingEqual2", new Class<?>[] {}, new Object[] {}, false);
}
[Test]
public void autoboxingBoolean2() {
doTest("AutoboxingBoolean2", new Class<?>[] {}, new Object[] {}, 10);
}
[Test]
public void autoboxingBoolean3() {
doTest("AutoboxingBoolean3", new Class<?>[] {}, new Object[] {}, null);
}
[Test]
public void autoboxingFieldIncrement4() {
doTest("AutoboxingFieldIncrement4", new Class<?>[] {}, new Object[] {}, 3L);
}
[Test]
public void inferenceExact() {
doTest("InferenceExact", new Class<?>[] {}, new Object[] {}, 3);
}
[Test]
public void inferenceExact2() {
doTest("InferenceExact2", new Class<?>[] {}, new Object[] {}, 3);
}
[Test]
public void inferenceExact3() {
doTest("InferenceExact3", new Class<?>[] {}, new Object[] {}, 3);
}
[Test]
public void inferenceLowerBound() {
doTest("InferenceLowerBound", new Class<?>[] {}, new Object[] {}, 3);
}
[Test]
public void inferenceExactParameter() {
doTest("InferenceExactParameter", new Class<?>[] {}, new Object[] {}, 5);
}
[Test]
public void inferenceExactParameter2() {
doTest("InferenceExactParameter2", new Class<?>[] {}, new Object[] {}, 5);
}
[Test]
public void inferenceCascaded() {
doTest("InferenceCascaded", new Class<?>[] {}, new Object[] {}, 82449);
}
[Test]
public void inferenceCascaded2() {
doTest("InferenceCascaded2", new Class<?>[] {}, new Object[] {}, 82449);
}
[Test]
public void inferenceCascaded3() {
doTest("InferenceCascaded3", new Class<?>[] {}, new Object[] {}, 82449);
}
[Test]
public void inferenceOutputParameter() {
doTest("InferenceOutputParameter", new Class<?>[] {}, new Object[] {}, null);
}
[Test]
public void mixedArithmetic() {
doTest("MixedArithmetic", new Class<?>[] { typeof(byte), typeof(short), typeof(char), typeof(int), typeof(long), typeof(float) },
new Object[] { (byte)7, (short)6, (char)5, 4, 3l, 2f }, 13d);
}
[Test]
public void booleanBitwise() {
doTest("BooleanBitwise", new Class<?>[] {}, new Object[] {}, true);
}
[Test]
public void doubleArithmetic() {
doTest("DoubleArithmetic", new Class<?>[] {}, new Object[] {}, -1d);
}
[Test]
public void staticArrayInitializer() {
doTest("StaticArrayInitializer", new Class<?>[] {}, new Object[] {}, 10);
}
[Test]
public void delegateTarget() {
doTest("DelegateTarget", new Class<?>[] {}, new Object[] {}, true);
}
[Test]
public void delegateMethod() {
doTest("DelegateMethod", new Class<?>[] {}, new Object[] {}, true);
}
[Test]
public void delegateDynamicInvoke() {
doTest("DelegateDynamicInvoke", new Class<?>[] {}, new Object[] {}, 2);
}
[Test]
public void delegateAdd() {
doTest("DelegateAdd", new Class<?>[] {}, new Object[] {}, 5);
}
[Test]
public void delegateAddAssign() {
doTest("DelegateAddAssign", new Class<?>[] {}, new Object[] {}, 5);
}
[Test]
public void delegateAddField() {
doTest("DelegateAddField", new Class<?>[] {}, new Object[] {}, 5);
}
[Test]
public void delegateAddArray() {
doTest("DelegateAddArray", new Class<?>[] {}, new Object[] {}, 5);
}
[Test]
public void byteArithmetic() {
doTest("ByteArithmetic", new Class<?>[] {}, new Object[] {}, true);
}
[Test]
public void byteOverflow() {
doTest("ByteOverflow", new Class<?>[] {}, new Object[] {}, true);
}
[Test]
public void shortArithmetic() {
doTest("ShortArithmetic", new Class<?>[] {}, new Object[] {}, true);
}
[Test]
public void shortOverflow() {
doTest("ShortOverflow", new Class<?>[] {}, new Object[] {}, true);
}
[Test]
public void charArithmetic() {
doTest("CharArithmetic", new Class<?>[] {}, new Object[] {}, true);
}
[Test]
public void charOverflow() {
doTest("CharOverflow", new Class<?>[] {}, new Object[] {}, true);
}
[Test]
public void intArithmetic() {
doTest("IntArithmetic", new Class<?>[] {}, new Object[] {}, true);
}
[Test]
public void intOverflow() {
doTest("IntOverflow", new Class<?>[] {}, new Object[] {}, true);
}
[Test]
public void longArithmetic() {
doTest("LongArithmetic", new Class<?>[] {}, new Object[] {}, true);
}
[Test]
public void floatArithmetic() {
doTest("FloatArithmetic", new Class<?>[] {}, new Object[] {}, true);
}
[Test]
public void doubleArithmetic2() {
doTest("DoubleArithmetic2", new Class<?>[] {}, new Object[] {}, true);
}
[Test]
public void booleanNot() {
doTest("BooleanNot", new Class<?>[] {}, new Object[] {}, true);
}
[Test]
public void booleanNot2() {
doTest("BooleanNot2", new Class<?>[] {}, new Object[] {}, true);
}
[Test]
public void castGetfield() {
doTest("CastGetfield", new Class<?>[] {}, new Object[] {}, 0);
}
[Test]
public void divideByZero() {
doTest("DivideByZero", new Class<?>[] {}, new Object[] {}, true);
}
[Test]
public void arrayHashcode() {
doTest("ArrayHashcode", new Class<?>[] {}, new Object[] {}, true);
}
[Test]
public void nullInstanceof() {
doTest("NullInstanceof", new Class<?>[] {}, new Object[] {}, false);
}
[Test]
public void arrayOfArray2() {
doTest("ArrayOfArray2", new Class<?>[] {}, new Object[] {}, 1);
}
[Test]
public void arrayOfArray3() {
doTest("ArrayOfArray3", new Class<?>[] {}, new Object[] {}, 2);
}
[Test]
public void arrayCreation() {
doTest("ArrayCreation", new Class<?>[] {}, new Object[] {}, 2);
}
[Test]
public void arrayCreation2() {
doTest("ArrayCreation2", new Class<?>[] {}, new Object[] {}, 3);
}
[Test]
public void arrayInitializer3() {
doTest("ArrayInitializer3", new Class<?>[] {}, new Object[] {}, 3);
}
[Test]
public void arrayCreation3() {
doTest("ArrayCreation3", new Class<?>[] {}, new Object[] {}, 3);
}
[Test]
public void minIntegerConstant() {
doTest("MinIntegerConstant", new Class<?>[] {}, new Object[] {}, true);
}
[Test]
public void minLongConstant() {
doTest("MinLongConstant", new Class<?>[] {}, new Object[] {}, true);
}
[Test]
public void minLongConstant2() {
doTest("MinLongConstant2", new Class<?>[] {}, new Object[] {}, true);
}
[Test]
public void stringAddConstants() {
doTest("StringAddConstants", new Class<?>[] {}, new Object[] {}, "abc");
}
[Test]
public void stringAdd() {
doTest("StringAdd", new Class<?>[] { typeof(String) }, new Object[] { "bc" }, "abc");
}
[Test]
public void stringAdd2() {
doTest("StringAdd2", new Class<?>[] { typeof(int) }, new Object[] { 2 }, "a2b");
}
[Test]
public void floatLimits() {
doTest("FloatLimits", new Class<?>[] {}, new Object[] {}, true);
}
[Test]
public void floatLimits2() {
doTest("FloatLimits2", new Class<?>[] {}, new Object[] {}, true);
}
[Test]
public void doubleLimits() {
doTest("DoubleLimits", new Class<?>[] {}, new Object[] {}, true);
}
[Test]
public void doubleLimits2() {
doTest("DoubleLimits2", new Class<?>[] {}, new Object[] {}, true);
}
[Test]
public void stringEqual() {
doTest("StringEqual", new Class<?>[] {}, new Object[] {}, true);
}
[Test]
public void stringEqual2() {
doTest("StringEqual2", new Class<?>[] {}, new Object[] {}, true);
}
[Test]
public void longWidening() {
doTest("LongWidening", new Class<?>[] {}, new Object[] {}, true);
}
[Test]
public void doubleLimits3() {
doTest("DoubleLimits3", new Class<?>[] {}, new Object[] {}, true);
}
[Test]
public void indexerAddAssign() {
doTest("IndexerAddAssign", new Class<?>[] {}, new Object[] {}, 5);
}
[Test]
public void indexerAddAssign2() {
doTest("IndexerAddAssign2", new Class<?>[] {}, new Object[] {}, 5l);
}
[Test]
public void propertyOpAssign() {
doTest("PropertyOpAssign", new Class<?>[] { typeof(int) }, new Object[] { 2 }, 3);
}
[Test]
public void propertyIncrement() {
doTest("PropertyIncrement", new Class<?>[] {}, new Object[] {}, 2l);
}
[Test]
public void byteWidening() {
doTest("ByteWidening", new Class<?>[] {}, new Object[] {}, true);
}
[Test]
public void floatNarrowing() {
doTest("FloatNarrowing", new Class<?>[] {}, new Object[] {}, true);
}
[Test]
public void stringAdd3() {
doTest("StringAdd3", new Class<?>[] { typeof(String) }, new Object[] { "c" }, "abcd");
}
[Test]
public void indexerIncrement() {
doTest("IndexerIncrement", new Class<?>[] {}, new Object[] {}, true);
}
[Test]
public void indexerIncrement2() {
doTest("IndexerIncrement2", new Class<?>[] {}, new Object[] {}, true);
}
[Test]
public void objectInitializer() {
doTest("ObjectInitializer", new Class<?>[] {}, new Object[] {}, 3);
}
[Test]
public void collectionInitializer() {
doTest("CollectionInitializer", new Class<?>[] {}, new Object[] {}, 3);
}
[Test]
public void collectionInitializer2() {
doTest("CollectionInitializer2", new Class<?>[] {}, new Object[] {}, 3);
}
[Test]
public void arrayRuntimeError() {
doTest("ArrayRuntimeError", new Class<?>[] {}, new Object[] {}, true);
}
[Test]
public void conditional2() {
doTest("Conditional2", new Class<?>[] { typeof(bool), typeof(double) }, new Object[] { true, 1d }, 1d);
}
[Test]
public void wildcard() {
doTest("Wildcard", new Class<?>[] {}, new Object[] {}, true);
}
[Test]
public void wildcard2() {
doTest("Wildcard2", new Class<?>[] {}, new Object[] {}, true);
}
[Test]
public void wildcard3() {
doTest("Wildcard3", new Class<?>[] {}, new Object[] {}, true);
}
[Test]
public void wildcard4() {
doTest("Wildcard4", new Class<?>[] {}, new Object[] {}, true);
}
[Test]
public void primitiveTypeof() {
doTest("PrimitiveTypeof", new Class<?>[] {}, new Object[] {}, false);
}
[Test]
public void explicitGenericCall() {
doTest("ExplicitGenericCall", new Class<?>[] {}, new Object[] {}, 2);
}
[Test]
public void assignLeftShift() {
doTest("AssignLeftShift", new Class<?>[] {}, new Object[] {}, 16L);
}
[Test]
public void verbatimIdentifier() {
doTest("VerbatimIdentifier", new Class<?>[] {}, new Object[] {}, 3);
}
[Test]
public void delegateCast() {
doTest("DelegateCast", new Class<?>[] {}, new Object[] {}, 2);
}
[Test]
public void wildcard5() {
doTest("Wildcard5", new Class<?>[] {}, new Object[] {}, true);
}
[Test]
public void genericParameterToString() {
doTest("GenericParameterToString", new Class<?>[] {}, new Object[] {}, "STR");
}
[Test]
public void lambdaEnvironment() {
doTest("LambdaEnvironment", new Class<?>[] { typeof(String) }, new Object[] { "abc" }, 1);
}
[Test]
public void inferenceEnumSet() {
doTest("InferenceEnumSet", new Class<?>[] {}, new Object[] {}, 0);
}
[Test]
public void autoboxingElementAssign() {
doTest("AutoboxingElementAssign", new Class<?>[] {}, new Object[] {}, 1);
}
[Test]
public void anonymousObject() {
doTest("AnonymousObject", new Class<?>[] {}, new Object[] {}, 1);
}
[Test]
public void anonymousObject2() {
doTest("AnonymousObject2", new Class<?>[] {}, new Object[] {}, 20);
}
[Test]
public void anonymousObject3() {
doTest("AnonymousObject3", new Class<?>[] {}, new Object[] {}, true);
}
[Test]
public void stringStringIntConcat() {
doTest("StringStringIntConcat", new Class<?>[] {}, new Object[] {}, "ab1");
}
[Test]
public void voidLambda() {
doTest("VoidLambda", new Class<?>[] {}, new Object[] {}, 2);
}
[Test]
public void lambdaAsArgument() {
doTest("LambdaAsArgument", new Class<?>[] {}, new Object[] {}, 2);
}
[Test]
public void lambdaAsArgument2() {
doTest("LambdaAsArgument2", new Class<?>[] {}, new Object[] {}, 2);
}
[Test]
public void inferredReturnType() {
doTest("InferredReturnType", new Class<?>[] {}, new Object[] {}, "s2");
}
[Test]
public void delegateField() {
doTest("DelegateField", new Class<?>[] {}, new Object[] {}, 2);
}
[Test]
public void anonymousObjectDelegate() {
doTest("AnonymousObjectDelegate", new Class<?>[] {}, new Object[] {}, 2);
}
[Test]
public void delegateAdd2() {
doTest("DelegateAdd2", new Class<?>[] {}, new Object[] {}, 5);
}
[Test]
public void objectInitializer2() {
doTest("ObjectInitializer2", new Class<?>[] {}, new Object[] {}, 3);
}
[Test]
public void inferenceCascaded4() {
doTest("InferenceCascaded4", new Class<?>[] {}, new Object[] {}, null);
}
[Test]
public void addStringBoolean() {
doTest("AddStringBoolean", new Class<?>[] {}, new Object[] {}, "true");
}
[Test]
public void paramsInference() {
doTest("ParamsInference", new Class<?>[] {}, new Object[] {}, "1");
}
[Test]
public void nestedLambdas() {
doTest("NestedLambdas", new Class<?>[] {}, new Object[] {}, true);
}
[Test]
public void lexicalDecomposition() {
doTest("LexicalDecomposition", new Class<?>[] {}, new Object[] {}, 518);
}
[Test]
public void lexicalDecomposition2() {
doTest("LexicalDecomposition2", new Class<?>[] {}, new Object[] {}, 744);
}
[Test]
public void lexicalDecomposition3() {
doTest("LexicalDecomposition3", new Class<?>[] {}, new Object[] {}, -274);
}
[Test]
public void lexicalDecomposition4() {
doTest("LexicalDecomposition4", new Class<?>[] {}, new Object[] {}, 845);
}
[Test]
public void arrayInitializerAutoboxing() {
doTest("ArrayInitializerAutoboxing", new Class<?>[] { typeof(short) }, new Object[] { (short)3 }, 3);
}
[Test]
public void wildcardBoundAssignment() {
doTest("WildcardBoundAssignment", new Class<?>[] {}, new Object[] {}, 3);
}
[Test]
public void wildcardBoundAssignment2() {
doTest("WildcardBoundAssignment2", new Class<?>[] {}, new Object[] {}, 3);
}
[Test]
public void genericConstraintAssignment() {
doTest("GenericConstraintAssignment", new Class<?>[] {}, new Object[] {}, 3);
}
[Test]
public void genericConstraintAssignment2() {
doTest("GenericConstraintAssignment2", new Class<?>[] {}, new Object[] {}, 3);
}
[Test]
public void objectArrayBoxing() {
doTest("ObjectArrayBoxing", new Class<?>[] {}, new Object[] {}, 3);
}
[Test]
public void objectArrayBoxing2() {
doTest("ObjectArrayBoxing2", new Class<?>[] {}, new Object[] {}, 3d);
}
[Test]
public void objectArrayBoxing3() {
doTest("ObjectArrayBoxing3", new Class<?>[] {}, new Object[] {}, 3d);
}
[Test]
public void stringAdd4() {
doTest("StringAdd4", new Class<?>[] {}, new Object[] {}, "abc");
}
}
}
| |
using System.Data.Common;
using System.Data.Entity;
using System.Data.Entity.Core.Objects;
using System.Data.Entity.Infrastructure;
using Abp.Auditing;
using Abp.Authorization;
using Abp.Authorization.Roles;
using Abp.Authorization.Users;
using Abp.Configuration;
using Abp.EntityFramework;
using Abp.EntityFramework.Extensions;
using Abp.EntityHistory;
using Abp.Localization;
using Abp.Notifications;
using Abp.Organizations;
using System.Threading;
using System.Threading.Tasks;
namespace Abp.Zero.EntityFramework
{
public abstract class AbpZeroCommonDbContext<TRole, TUser> : AbpDbContext
where TRole : AbpRole<TUser>
where TUser : AbpUser<TUser>
{
/// <summary>
/// Roles.
/// </summary>
public virtual IDbSet<TRole> Roles { get; set; }
/// <summary>
/// Users.
/// </summary>
public virtual IDbSet<TUser> Users { get; set; }
/// <summary>
/// User logins.
/// </summary>
public virtual IDbSet<UserLogin> UserLogins { get; set; }
/// <summary>
/// User login attempts.
/// </summary>
public virtual IDbSet<UserLoginAttempt> UserLoginAttempts { get; set; }
/// <summary>
/// User roles.
/// </summary>
public virtual IDbSet<UserRole> UserRoles { get; set; }
/// <summary>
/// User claims.
/// </summary>
public virtual IDbSet<UserClaim> UserClaims { get; set; }
/// <summary>
/// Permissions.
/// </summary>
public virtual IDbSet<PermissionSetting> Permissions { get; set; }
/// <summary>
/// Role permissions.
/// </summary>
public virtual IDbSet<RolePermissionSetting> RolePermissions { get; set; }
/// <summary>
/// User permissions.
/// </summary>
public virtual IDbSet<UserPermissionSetting> UserPermissions { get; set; }
/// <summary>
/// Settings.
/// </summary>
public virtual IDbSet<Setting> Settings { get; set; }
/// <summary>
/// Audit logs.
/// </summary>
public virtual IDbSet<AuditLog> AuditLogs { get; set; }
/// <summary>
/// Languages.
/// </summary>
public virtual IDbSet<ApplicationLanguage> Languages { get; set; }
/// <summary>
/// LanguageTexts.
/// </summary>
public virtual IDbSet<ApplicationLanguageText> LanguageTexts { get; set; }
/// <summary>
/// OrganizationUnits.
/// </summary>
public virtual IDbSet<OrganizationUnit> OrganizationUnits { get; set; }
/// <summary>
/// UserOrganizationUnits.
/// </summary>
public virtual IDbSet<UserOrganizationUnit> UserOrganizationUnits { get; set; }
/// <summary>
/// OrganizationUnitRoles.
/// </summary>
public virtual IDbSet<OrganizationUnitRole> OrganizationUnitRoles { get; set; }
/// <summary>
/// Notifications.
/// </summary>
public virtual IDbSet<NotificationInfo> Notifications { get; set; }
/// <summary>
/// Tenant notifications.
/// </summary>
public virtual IDbSet<TenantNotificationInfo> TenantNotifications { get; set; }
/// <summary>
/// User notifications.
/// </summary>
public virtual IDbSet<UserNotificationInfo> UserNotifications { get; set; }
/// <summary>
/// Notification subscriptions.
/// </summary>
public virtual IDbSet<NotificationSubscriptionInfo> NotificationSubscriptions { get; set; }
/// <summary>
/// Entity changes.
/// </summary>
public virtual IDbSet<EntityChange> EntityChanges { get; set; }
/// <summary>
/// Entity change sets.
/// </summary>
public virtual IDbSet<EntityChangeSet> EntityChangeSets { get; set; }
/// <summary>
/// Entity property changes.
/// </summary>
public virtual IDbSet<EntityPropertyChange> EntityPropertyChanges { get; set; }
public IEntityHistoryHelper EntityHistoryHelper { get; set; }
/// <summary>
/// Default constructor.
/// Do not directly instantiate this class. Instead, use dependency injection!
/// </summary>
protected AbpZeroCommonDbContext()
{
}
/// <summary>
/// Constructor with connection string parameter.
/// </summary>
/// <param name="nameOrConnectionString">Connection string or a name in connection strings in configuration file</param>
protected AbpZeroCommonDbContext(string nameOrConnectionString)
: base(nameOrConnectionString)
{
}
protected AbpZeroCommonDbContext(DbCompiledModel model)
: base(model)
{
}
/// <summary>
/// This constructor can be used for unit tests.
/// </summary>
protected AbpZeroCommonDbContext(DbConnection existingConnection, bool contextOwnsConnection)
: base(existingConnection, contextOwnsConnection)
{
}
protected AbpZeroCommonDbContext(string nameOrConnectionString, DbCompiledModel model)
: base(nameOrConnectionString, model)
{
}
protected AbpZeroCommonDbContext(ObjectContext objectContext, bool dbContextOwnsObjectContext)
: base(objectContext, dbContextOwnsObjectContext)
{
}
/// <summary>
/// Constructor.
/// </summary>
protected AbpZeroCommonDbContext(DbConnection existingConnection, DbCompiledModel model, bool contextOwnsConnection)
: base(existingConnection, model, contextOwnsConnection)
{
}
public override int SaveChanges()
{
var changeSet = EntityHistoryHelper?.CreateEntityChangeSet(this);
var result = base.SaveChanges();
EntityHistoryHelper?.Save(this, changeSet);
return result;
}
public override async Task<int> SaveChangesAsync(CancellationToken cancellationToken = default(CancellationToken))
{
var changeSet = EntityHistoryHelper?.CreateEntityChangeSet(this);
var result = await base.SaveChangesAsync(cancellationToken);
if (EntityHistoryHelper != null)
{
await EntityHistoryHelper.SaveAsync(this, changeSet);
}
return result;
}
/// <summary>
///
/// </summary>
/// <param name="modelBuilder"></param>
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<EntityChange>()
.HasMany(e => e.PropertyChanges)
.WithRequired()
.HasForeignKey(e => e.EntityChangeId);
#region EntityChange.IX_EntityChangeSetId
modelBuilder.Entity<EntityChange>()
.Property(e => e.EntityChangeSetId)
.CreateIndex("IX_EntityChangeSetId", 1);
#endregion
#region EntityChange.IX_EntityTypeFullName_EntityId
modelBuilder.Entity<EntityChange>()
.Property(e => e.EntityTypeFullName)
.CreateIndex("IX_EntityTypeFullName_EntityId", 1);
modelBuilder.Entity<EntityChange>()
.Property(e => e.EntityId)
.CreateIndex("IX_EntityTypeFullName_EntityId", 2);
#endregion
modelBuilder.Entity<EntityChangeSet>()
.HasMany(e => e.EntityChanges)
.WithRequired()
.HasForeignKey(e => e.EntityChangeSetId);
#region EntityChangeSet.IX_TenantId_UserId
modelBuilder.Entity<EntityChangeSet>()
.Property(e => e.TenantId)
.CreateIndex("IX_TenantId_UserId", 1);
modelBuilder.Entity<EntityChangeSet>()
.Property(e => e.UserId)
.CreateIndex("IX_TenantId_UserId", 2);
#endregion
#region EntityChangeSet.IX_TenantId_CreationTime
modelBuilder.Entity<EntityChangeSet>()
.Property(e => e.TenantId)
.CreateIndex("IX_TenantId_CreationTime", 1);
modelBuilder.Entity<EntityChangeSet>()
.Property(e => e.CreationTime)
.CreateIndex("IX_TenantId_CreationTime", 2);
#endregion
#region EntityChangeSet.IX_TenantId_Reason
modelBuilder.Entity<EntityChangeSet>()
.Property(e => e.TenantId)
.CreateIndex("IX_TenantId_Reason", 1);
modelBuilder.Entity<EntityChangeSet>()
.Property(e => e.Reason)
.CreateIndex("IX_TenantId_Reason", 2);
#endregion
#region EntityPropertyChange.IX_EntityChangeId
modelBuilder.Entity<EntityPropertyChange>()
.Property(e => e.EntityChangeId)
.CreateIndex("IX_EntityChangeId", 1);
#endregion
modelBuilder.Entity<Setting>()
.HasIndex(e => new { e.TenantId, e.Name, e.UserId })
.IsUnique();
}
}
}
| |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// File System.Double.cs
// Automatically generated contract file.
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Diagnostics.Contracts;
using System;
// Disable the "this variable is not used" warning as every field would imply it.
#pragma warning disable 0414
// Disable the "this variable is never assigned to".
#pragma warning disable 0067
// Disable the "this event is never assigned to".
#pragma warning disable 0649
// Disable the "this variable is never used".
#pragma warning disable 0169
// Disable the "new keyword not required" warning.
#pragma warning disable 0109
// Disable the "extern without DllImport" warning.
#pragma warning disable 0626
// Disable the "could hide other member" warning, can happen on certain properties.
#pragma warning disable 0108
namespace System
{
public partial struct Double : IComparable, IFormattable, IConvertible, IComparable<double>, IEquatable<double>
{
#region Methods and constructors
public static bool operator != (double left, double right)
{
Contract.Ensures(Contract.Result<bool>() == ((left == right) == false));
return default(bool);
}
public static bool operator < (double left, double right)
{
Contract.Ensures(Contract.Result<bool>() == (left < right));
return default(bool);
}
public static bool operator <=(double left, double right)
{
Contract.Ensures(Contract.Result<bool>() == ((left > right) == false));
return default(bool);
}
public static bool operator == (double left, double right)
{
Contract.Ensures(Contract.Result<bool>() == (left == right));
return default(bool);
}
public static bool operator > (double left, double right)
{
Contract.Ensures(Contract.Result<bool>() == (left > right));
return default(bool);
}
public static bool operator >= (double left, double right)
{
Contract.Ensures(Contract.Result<bool>() == ((left < right) == false));
return default(bool);
}
public int CompareTo(Object value)
{
return default(int);
}
public int CompareTo(double value)
{
return default(int);
}
public override bool Equals(Object obj)
{
return default(bool);
}
public bool Equals(double obj)
{
return default(bool);
}
public override int GetHashCode()
{
return default(int);
}
public TypeCode GetTypeCode()
{
return default(TypeCode);
}
public static bool IsInfinity(double d)
{
return default(bool);
}
public static bool IsNaN(double d)
{
return default(bool);
}
public static bool IsNegativeInfinity(double d)
{
return default(bool);
}
public static bool IsPositiveInfinity(double d)
{
return default(bool);
}
public static double Parse(string s)
{
return default(double);
}
public static double Parse(string s, System.Globalization.NumberStyles style, IFormatProvider provider)
{
return default(double);
}
public static double Parse(string s, System.Globalization.NumberStyles style)
{
return default(double);
}
public static double Parse(string s, IFormatProvider provider)
{
return default(double);
}
bool System.IConvertible.ToBoolean(IFormatProvider provider)
{
return default(bool);
}
byte System.IConvertible.ToByte(IFormatProvider provider)
{
return default(byte);
}
char System.IConvertible.ToChar(IFormatProvider provider)
{
return default(char);
}
DateTime System.IConvertible.ToDateTime(IFormatProvider provider)
{
return default(DateTime);
}
Decimal System.IConvertible.ToDecimal(IFormatProvider provider)
{
return default(Decimal);
}
double System.IConvertible.ToDouble(IFormatProvider provider)
{
return default(double);
}
short System.IConvertible.ToInt16(IFormatProvider provider)
{
return default(short);
}
int System.IConvertible.ToInt32(IFormatProvider provider)
{
return default(int);
}
long System.IConvertible.ToInt64(IFormatProvider provider)
{
return default(long);
}
sbyte System.IConvertible.ToSByte(IFormatProvider provider)
{
return default(sbyte);
}
float System.IConvertible.ToSingle(IFormatProvider provider)
{
return default(float);
}
Object System.IConvertible.ToType(Type type, IFormatProvider provider)
{
return default(Object);
}
ushort System.IConvertible.ToUInt16(IFormatProvider provider)
{
return default(ushort);
}
uint System.IConvertible.ToUInt32(IFormatProvider provider)
{
return default(uint);
}
ulong System.IConvertible.ToUInt64(IFormatProvider provider)
{
return default(ulong);
}
public override string ToString()
{
return default(string);
}
public string ToString(string format, IFormatProvider provider)
{
return default(string);
}
public string ToString(IFormatProvider provider)
{
return default(string);
}
public string ToString(string format)
{
return default(string);
}
public static bool TryParse(string s, out double result)
{
result = default(double);
return default(bool);
}
public static bool TryParse(string s, System.Globalization.NumberStyles style, IFormatProvider provider, out double result)
{
result = default(double);
return default(bool);
}
#endregion
#region Fields
public static double Epsilon;
public static double MaxValue;
public static double MinValue;
public static double NaN;
public static double NegativeInfinity;
public static double PositiveInfinity;
#endregion
}
}
| |
//
// Copyright (c) 2012-2014 Piotr Fusik <piotr@fusik.info>
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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.
//
#if DOTNET35
using NUnit.Framework;
using Sooda.Linq;
using Sooda.UnitTests.BaseObjects;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace Sooda.UnitTests.TestCases.Linq
{
[TestFixture]
public class CollectionTest
{
[Test]
public void In0()
{
using (new SoodaTransaction())
{
IEnumerable<Contact> ce = Contact.Linq().Where(c => new int[0].Contains(c.ContactId));
CollectionAssert.IsEmpty(ce);
ce = Contact.Linq().Where(c => new Contact[0].Contains(c));
CollectionAssert.IsEmpty(ce);
ce = Contact.Linq().Where(c => new ArrayList().Contains(c.Manager));
CollectionAssert.IsEmpty(ce);
}
}
[Test]
public void InArray1()
{
using (new SoodaTransaction())
{
IEnumerable<Contact> ce = Contact.Linq().Where(c => new int[] { 1 }.Contains(c.ContactId));
CollectionAssert.AreEquivalent(new Contact[] { Contact.Mary }, ce);
}
}
[Test]
public void InRefArray()
{
using (new SoodaTransaction())
{
IEnumerable<Contact> ce = Contact.Linq().Where(c => new Contact[] { Contact.Mary }.Contains(c.Manager));
CollectionAssert.AreEquivalent(new Contact[] { Contact.Ed, Contact.Eva }, ce);
}
}
[Test]
public void InArray3()
{
using (new SoodaTransaction())
{
IEnumerable<Contact> ce = Contact.Linq().Where(c => new int[] { 1, 2, 3 }.Contains(c.ContactId));
CollectionAssert.AreEquivalent(new Contact[] { Contact.Mary, Contact.Ed, Contact.Eva }, ce);
}
}
[Test]
public void InArrayList()
{
using (new SoodaTransaction())
{
ArrayList managers = new ArrayList();
managers.Add(Contact.Mary);
IEnumerable<Contact> ce = Contact.Linq().Where(c => managers.Contains(c.Manager));
CollectionAssert.AreEquivalent(new Contact[] { Contact.Ed, Contact.Eva }, ce);
}
}
[Test]
public void InGenericList()
{
using (new SoodaTransaction())
{
List<Contact> managers = new List<Contact>();
managers.Add(Contact.Mary);
IEnumerable<Contact> ce = Contact.Linq().Where(c => managers.Contains(c.Manager));
CollectionAssert.AreEquivalent(new Contact[] { Contact.Ed, Contact.Eva }, ce);
}
}
[Test]
public void In5()
{
using (new SoodaTransaction())
{
IEnumerable<Contact> ce = Contact.Linq().Where(c => new Contact[] { c.Manager }.Contains(c.Manager));
// "in" doesn't match nulls, at least in SQL Server
CollectionAssert.AreEquivalent(new Contact[] { Contact.Ed, Contact.Eva }, ce);
}
}
[Test]
public void In6()
{
using (new SoodaTransaction())
{
Contact c0 = null;
IEnumerable<Contact> ce = Contact.Linq().Where(c => new Contact[] { c0 }.Contains(c.Manager));
// "in" doesn't match nulls, at least in SQL Server
CollectionAssert.IsEmpty(ce);
}
}
[Test]
public void In7()
{
using (new SoodaTransaction())
{
IEnumerable<Contact> ce = Contact.Linq().Where(c => Role.Manager.Members.Contains(c.Manager));
CollectionAssert.AreEquivalent(new Contact[] { Contact.Ed, Contact.Eva }, ce);
}
}
[Test]
public void InRangeVariable()
{
using (new SoodaTransaction())
{
IEnumerable<Contact> ce = Contact.Linq().Where(c => new Contact[] { Contact.Mary }.Contains(c));
CollectionAssert.AreEquivalent(new Contact[] { Contact.Mary }, ce);
}
}
[Test]
public void CountOnSelfReferencing()
{
using (new SoodaTransaction())
{
IEnumerable<Contact> ce = Contact.Linq().Where(c => c.Subordinates.Count == 2);
CollectionAssert.AreEquivalent(new Contact[] { Contact.Mary }, ce);
}
}
[Test]
public void CountOnSelfReferencingQuery()
{
using (new SoodaTransaction())
{
IEnumerable<Contact> ce = Contact.Linq().Where(c => c.SubordinatesQuery.Count() == 2);
CollectionAssert.AreEquivalent(new Contact[] { Contact.Mary }, ce);
}
}
[Test]
public void CountOnFiltered()
{
using (new SoodaTransaction())
{
IEnumerable<Group> ge = Group.Linq().Where(g => g.Members.Count == 4);
CollectionAssert.AreEqual(new Group[] { Group.GetRef(10) }, ge);
ge = Group.Linq().Where(g => g.Managers.Count() == 1);
CollectionAssert.AreEquivalent(new Group[] { Group.GetRef(10), Group.GetRef(11) }, ge);
ge = Group.Linq().Where(g => g.Managers.Count != 1);
CollectionAssert.IsEmpty(ge);
}
}
[Test]
public void CountOnFilteredQuery()
{
using (new SoodaTransaction())
{
IEnumerable<Group> ge = Group.Linq().Where(g => g.MembersQuery.Count() == 4);
CollectionAssert.AreEqual(new Group[] { Group.GetRef(10) }, ge);
ge = Group.Linq().Where(g => g.Managers.Count() == 1);
CollectionAssert.AreEquivalent(new Group[] { Group.GetRef(10), Group.GetRef(11) }, ge);
ge = Group.Linq().Where(g => g.Managers.Count != 1);
CollectionAssert.IsEmpty(ge);
}
}
[Test]
public void CountOnSubclassTPT()
{
using (new SoodaTransaction())
{
IEnumerable<Contact> ce = Contact.Linq().Where(c => c.Bikes1.Count == 1);
CollectionAssert.AreEquivalent(new Contact[] { Contact.Ed }, ce);
}
}
[Test]
public void CountOnSubclassTPTQuery()
{
using (new SoodaTransaction())
{
IEnumerable<Contact> ce = Contact.Linq().Where(c => c.Bikes1Query.Count() == 1);
CollectionAssert.AreEquivalent(new Contact[] { Contact.Ed }, ce);
}
}
[Test]
public void ContainsOnSelfReferencing()
{
using (new SoodaTransaction())
{
IEnumerable<Contact> ce = Contact.Linq().Where(c => c.Subordinates.Contains(Contact.Ed));
CollectionAssert.AreEquivalent(new Contact[] { Contact.Mary }, ce);
}
}
[Test]
public void ContainsOnSelfReferencingQuery()
{
using (new SoodaTransaction())
{
IEnumerable<Contact> ce = Contact.Linq().Where(c => c.SubordinatesQuery.Contains(Contact.Ed));
CollectionAssert.AreEquivalent(new Contact[] { Contact.Mary }, ce);
}
}
[Test]
public void ContainsOnFiltered()
{
using (new SoodaTransaction())
{
IEnumerable<Group> ge = Group.Linq().Where(g => g.Members.Contains(Contact.Mary));
CollectionAssert.AreEqual(new Group[] { Group.GetRef(10) }, ge);
ge = Group.Linq().Where(g => g.Managers.Contains(Contact.Mary));
CollectionAssert.IsEmpty(ge);
}
}
[Test]
public void ContainsOnFilteredQuery()
{
using (new SoodaTransaction())
{
IEnumerable<Group> ge = Group.Linq().Where(g => g.MembersQuery.Contains(Contact.Mary));
CollectionAssert.AreEqual(new Group[] { Group.GetRef(10) }, ge);
ge = Group.Linq().Where(g => g.Managers.Contains(Contact.Mary));
CollectionAssert.IsEmpty(ge);
}
}
[Test]
public void ContainsOnSubclassTPT()
{
using (new SoodaTransaction())
{
IEnumerable<Contact> ce = Contact.Linq().Where(c => c.Bikes1.Contains(Bike.GetRef(3)));
CollectionAssert.AreEquivalent(new Contact[] { Contact.Ed }, ce);
}
}
[Test]
public void ContainsOnSubclassTPTQuery()
{
using (new SoodaTransaction())
{
IEnumerable<Contact> ce = Contact.Linq().Where(c => c.Bikes1Query.Contains(Bike.GetRef(3)));
CollectionAssert.AreEquivalent(new Contact[] { Contact.Ed }, ce);
}
}
[Test]
public void ContainsOnSubclassTPTWhere()
{
using (new SoodaTransaction())
{
IEnumerable<Contact> ce = Contact.Linq().Where(c => c.Bikes1.Any(b => b.TwoWheels == 1));
CollectionAssert.AreEquivalent(new Contact[] { Contact.Ed }, ce);
}
}
[Test]
public void ContainsOnSubclassTPTWhereQuery()
{
using (new SoodaTransaction())
{
IEnumerable<Contact> ce = Contact.Linq().Where(c => c.Bikes1Query.Any(b => b.TwoWheels == 1));
CollectionAssert.AreEquivalent(new Contact[] { Contact.Ed }, ce);
}
}
[Test]
public void NestedContains()
{
using (new SoodaTransaction())
{
IEnumerable<Contact> ce = Contact.Linq().Where(c => c.PrimaryGroup.Members.Contains(Contact.GetRef(3)));
CollectionAssert.AreEqual(new Contact[] { Contact.Eva }, ce);
}
}
[Test]
public void NestedContainsQuery()
{
using (new SoodaTransaction())
{
IEnumerable<Contact> ce = Contact.Linq().Where(c => c.PrimaryGroup.MembersQuery.Contains(Contact.GetRef(3)));
CollectionAssert.AreEqual(new Contact[] { Contact.Eva }, ce);
}
}
[Test]
public void ComplexTest5()
{
using (new SoodaTransaction())
{
IEnumerable<Group> ge = Group.Linq().Where(g =>
g.Manager.Name == "Mary Manager"
&& g.Members.Count > 3
&& g.Members.Any(c => c.Name == "ZZZ" && c.PrimaryGroup.Members.Contains(Contact.GetRef(3)))
&& g.Manager.Roles.Any(r => r.Name.Value == "Customer"));
CollectionAssert.IsEmpty(ge);
}
}
[Test]
public void ComplexTest5Query()
{
using (new SoodaTransaction())
{
IEnumerable<Group> ge = Group.Linq().Where(g =>
g.Manager.Name == "Mary Manager"
&& g.MembersQuery.Count() > 3
&& g.MembersQuery.Any(c => c.Name == "ZZZ" && c.PrimaryGroup.MembersQuery.Contains(Contact.GetRef(3)))
&& g.Manager.RolesQuery.Any(r => r.Name.Value == "Customer"));
CollectionAssert.IsEmpty(ge);
}
}
[Test]
public void OneToManyAll()
{
using (new SoodaTransaction())
{
IEnumerable<Contact> ce = Contact.Linq().Where(c => c.Subordinates.All(s => s.Name.Like("E% Employee")));
Assert.AreEqual(7, ce.Count());
}
}
[Test]
public void OneToManyAllQuery()
{
using (new SoodaTransaction())
{
IEnumerable<Contact> ce = Contact.Linq().Where(c => c.SubordinatesQuery.All(s => s.Name.Like("E% Employee")));
Assert.AreEqual(7, ce.Count());
}
}
[Test]
public void OneToManyAny()
{
using (new SoodaTransaction())
{
IEnumerable<Contact> ce = Contact.Linq().Where(c => c.Subordinates.Any());
CollectionAssert.AreEquivalent(new Contact[] { Contact.Mary }, ce);
}
}
[Test]
public void OneToManyAnyQuery()
{
using (new SoodaTransaction())
{
IEnumerable<Contact> ce = Contact.Linq().Where(c => c.SubordinatesQuery.Any());
CollectionAssert.AreEquivalent(new Contact[] { Contact.Mary }, ce);
}
}
[Test]
public void OneToManyAnyFiltered()
{
using (new SoodaTransaction())
{
IEnumerable<Contact> ce = Contact.Linq().Where(c => c.Subordinates.Any(s => s.Name == "Ed Employee"));
CollectionAssert.AreEquivalent(new Contact[] { Contact.Mary }, ce);
}
}
[Test]
public void OneToManyAnyFilteredQuery()
{
using (new SoodaTransaction())
{
IEnumerable<Contact> ce = Contact.Linq().Where(c => c.SubordinatesQuery.Any(s => s.Name == "Ed Employee"));
CollectionAssert.AreEquivalent(new Contact[] { Contact.Mary }, ce);
}
}
[Test]
public void AnyWithOuterRange()
{
using (new SoodaTransaction())
{
IEnumerable<Contact> ce = Contact.Linq().Where(c => c.Subordinates.Any(s => s == c));
CollectionAssert.IsEmpty(ce);
}
}
[Test]
public void AnyWithOuterRangeQuery()
{
using (new SoodaTransaction())
{
IEnumerable<Contact> ce = Contact.Linq().Where(c => c.SubordinatesQuery.Any(s => s == c));
CollectionAssert.IsEmpty(ce);
}
}
[Test]
public void AnyWithRangeVariableComparison()
{
using (new SoodaTransaction())
{
IEnumerable<Group> ge = Group.Linq().Where(g => g.Members.Any(c => c == Contact.Mary));
CollectionAssert.AreEqual(new Group[] { Group.GetRef(10) }, ge);
}
}
[Test]
public void AnyWithRangeVariableComparisonQuery()
{
using (new SoodaTransaction())
{
IEnumerable<Group> ge = Group.Linq().Where(g => g.MembersQuery.Any(c => c == Contact.Mary));
CollectionAssert.AreEqual(new Group[] { Group.GetRef(10) }, ge);
}
}
[Test]
public void AnyWithSoodaClass()
{
using (new SoodaTransaction())
{
IEnumerable<Group> ge = Group.Linq().Where(g => g.Members.Any(c => g.GetType().Name == "Group" && c.GetType().Name == "Contact"));
CollectionAssert.AreEquivalent(new Group[] { Group.GetRef(10), Group.GetRef(11) }, ge);
}
}
[Test]
public void AnyWithSoodaClassQuery()
{
using (new SoodaTransaction())
{
IEnumerable<Group> ge = Group.Linq().Where(g => g.MembersQuery.Any(c => g.GetType().Name == "Group" && c.GetType().Name == "Contact"));
CollectionAssert.AreEquivalent(new Group[] { Group.GetRef(10), Group.GetRef(11) }, ge);
}
}
[Test]
public void AnyArray()
{
using (new SoodaTransaction())
{
IEnumerable<Contact> ce = Contact.Linq().Where(c => new int[] { 1, 3 }.Any(i => i == c.ContactId));
CollectionAssert.AreEquivalent(new Contact[] { Contact.Mary, Contact.Eva }, ce);
}
}
[Test]
public void AnySoodaCollection()
{
using (new SoodaTransaction())
{
IEnumerable<Contact> ce = Contact.Linq().Where(c => Role.Employee.Members.Any(m => m.Manager == c));
CollectionAssert.AreEqual(new Contact[] { Contact.Mary }, ce);
}
}
[Test]
public void AnySoodaCollectionQuery()
{
using (new SoodaTransaction())
{
IEnumerable<Contact> ce = Contact.Linq().Where(c => Role.Employee.MembersQuery.Any(m => m.Manager == c));
CollectionAssert.AreEqual(new Contact[] { Contact.Mary }, ce);
}
}
[Test]
public void HaveManagerWithRole()
{
using (new SoodaTransaction())
{
IEnumerable<Contact> ce = Contact.Linq().Where(c => c.Manager.Roles.Contains(Role.Employee));
CollectionAssert.AreEquivalent(new Contact[] { Contact.Ed, Contact.Eva }, ce);
}
}
[Test]
public void HaveManagerWithRoleCount()
{
using (new SoodaTransaction())
{
int i = Contact.Linq().Count(c => c.Manager.Roles.Contains(Role.Employee));
Assert.AreEqual(2, i);
}
}
[Test]
public void HaveManagerWithCarCount()
{
using (new SoodaTransaction())
{
int i = Contact.Linq().Count(c => c.Manager.Vehicles.Contains(Car.GetRef(2)));
Assert.AreEqual(0, i);
}
}
[Test]
public void HaveManagerWithBikeCount()
{
using (new SoodaTransaction())
{
int i = Contact.Linq().Count(c => c.Manager.Bikes.Contains(Vehicle.GetRef(3)));
Assert.AreEqual(0, i);
}
}
}
}
#endif
| |
//
// Copyright (c) 2008-2011, Kenneth Bell
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
namespace DiscUtils
{
using System;
using System.Collections.Generic;
/// <summary>
/// A sparse in-memory buffer.
/// </summary>
/// <remarks>This class is useful for storing large sparse buffers in memory, unused
/// chunks of the buffer are not stored (assumed to be zero).</remarks>
public sealed class SparseMemoryBuffer : Buffer
{
private Dictionary<int, byte[]> _buffers;
private int _chunkSize;
private long _capacity;
/// <summary>
/// Initializes a new instance of the SparseMemoryBuffer class.
/// </summary>
/// <param name="chunkSize">The size of each allocation chunk</param>
public SparseMemoryBuffer(int chunkSize)
{
_chunkSize = chunkSize;
_buffers = new Dictionary<int, byte[]>();
}
/// <summary>
/// Indicates this stream can be read (always <c>true</c>).
/// </summary>
public override bool CanRead
{
get { return true; }
}
/// <summary>
/// Indicates this stream can be written (always <c>true</c>).
/// </summary>
public override bool CanWrite
{
get { return true; }
}
/// <summary>
/// Gets the current capacity of the sparse buffer (number of logical bytes stored).
/// </summary>
public override long Capacity
{
get { return _capacity; }
}
/// <summary>
/// Gets the size of each allocation chunk.
/// </summary>
public int ChunkSize
{
get { return _chunkSize; }
}
/// <summary>
/// Gets the (sorted) list of allocated chunks, as chunk indexes.
/// </summary>
/// <returns>An enumeration of chunk indexes</returns>
/// <remarks>This method returns chunks as an index rather than absolute stream position.
/// For example, if ChunkSize is 16KB, and the first 32KB of the buffer is actually stored,
/// this method will return 0 and 1. This indicates the first and second chunks are stored.</remarks>
public IEnumerable<int> AllocatedChunks
{
get
{
List<int> keys = new List<int>(_buffers.Keys);
keys.Sort();
return keys;
}
}
/// <summary>
/// Accesses this memory buffer as an infinite byte array.
/// </summary>
/// <param name="pos">The buffer position to read.</param>
/// <returns>The byte stored at this position (or Zero if not explicitly stored)</returns>
public byte this[long pos]
{
get
{
byte[] buffer = new byte[1];
if (Read(pos, buffer, 0, 1) != 0)
{
return buffer[0];
}
else
{
return 0;
}
}
set
{
byte[] buffer = new byte[1];
buffer[0] = value;
Write(pos, buffer, 0, 1);
}
}
/// <summary>
/// Reads a section of the sparse buffer into a byte array.
/// </summary>
/// <param name="pos">The offset within the sparse buffer to start reading.</param>
/// <param name="buffer">The destination byte array.</param>
/// <param name="offset">The start offset within the destination buffer.</param>
/// <param name="count">The number of bytes to read.</param>
/// <returns>The actual number of bytes read</returns>
public override int Read(long pos, byte[] buffer, int offset, int count)
{
int totalRead = 0;
while (totalRead < count && pos < _capacity)
{
int chunk = (int)(pos / _chunkSize);
int chunkOffset = (int)(pos % _chunkSize);
int numToRead = (int)Math.Min(Math.Min(_chunkSize - chunkOffset, _capacity - pos), count - totalRead);
byte[] chunkBuffer;
if (!_buffers.TryGetValue(chunk, out chunkBuffer))
{
Array.Clear(buffer, offset + totalRead, numToRead);
}
else
{
Array.Copy(chunkBuffer, chunkOffset, buffer, offset + totalRead, numToRead);
}
totalRead += numToRead;
pos += numToRead;
}
return totalRead;
}
/// <summary>
/// Writes a byte array into the sparse buffer.
/// </summary>
/// <param name="pos">The start offset within the sparse buffer.</param>
/// <param name="buffer">The source byte array.</param>
/// <param name="offset">The start offset within the source byte array.</param>
/// <param name="count">The number of bytes to write.</param>
public override void Write(long pos, byte[] buffer, int offset, int count)
{
int totalWritten = 0;
while (totalWritten < count)
{
int chunk = (int)(pos / _chunkSize);
int chunkOffset = (int)(pos % _chunkSize);
int numToWrite = (int)Math.Min(_chunkSize - chunkOffset, count - totalWritten);
byte[] chunkBuffer;
if (!_buffers.TryGetValue(chunk, out chunkBuffer))
{
chunkBuffer = new byte[_chunkSize];
_buffers[chunk] = chunkBuffer;
}
Array.Copy(buffer, offset + totalWritten, chunkBuffer, chunkOffset, numToWrite);
totalWritten += numToWrite;
pos += numToWrite;
}
_capacity = Math.Max(_capacity, pos);
}
/// <summary>
/// Sets the capacity of the sparse buffer, truncating if appropriate.
/// </summary>
/// <param name="value">The desired capacity of the buffer.</param>
/// <remarks>This method does not allocate any chunks, it merely records the logical
/// capacity of the sparse buffer. Writes beyond the specified capacity will increase
/// the capacity.</remarks>
public override void SetCapacity(long value)
{
_capacity = value;
}
/// <summary>
/// Gets the parts of a buffer that are stored, within a specified range.
/// </summary>
/// <param name="start">The offset of the first byte of interest</param>
/// <param name="count">The number of bytes of interest</param>
/// <returns>An enumeration of stream extents, indicating stored bytes</returns>
public override IEnumerable<StreamExtent> GetExtentsInRange(long start, long count)
{
long end = start + count;
foreach (var chunk in AllocatedChunks)
{
long chunkStart = chunk * (long)_chunkSize;
if (chunkStart >= start && (chunkStart + _chunkSize) <= end)
{
long extentStart = Math.Max(start, chunk * (long)_chunkSize);
yield return new StreamExtent(extentStart, Math.Min(chunkStart + _chunkSize, end) - extentStart);
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using UnityEngine;
namespace RPG.Environment
{
[ExecuteInEditMode]
[RequireComponent(typeof(WaterBase))]
public class PlanarReflection : MonoBehaviour
{
public LayerMask reflectionMask;
public bool reflectSkybox = false;
public Color clearColor = Color.grey;
public String reflectionSampler = "_ReflectionTex";
public float clipPlaneOffset = 0.07F;
Vector3 m_Oldpos;
Camera m_ReflectionCamera;
Material m_SharedMaterial;
Dictionary<Camera, bool> m_HelperCameras;
public void Start()
{
m_SharedMaterial = ((WaterBase)gameObject.GetComponent(typeof(WaterBase))).sharedMaterial;
}
Camera CreateReflectionCameraFor(Camera cam)
{
String reflName = gameObject.name + "Reflection" + cam.name;
GameObject go = GameObject.Find(reflName);
if (!go)
{
go = new GameObject(reflName, typeof(Camera));
}
if (!go.GetComponent(typeof(Camera)))
{
go.AddComponent(typeof(Camera));
}
Camera reflectCamera = go.GetComponent<Camera>();
reflectCamera.backgroundColor = clearColor;
reflectCamera.clearFlags = reflectSkybox ? CameraClearFlags.Skybox : CameraClearFlags.SolidColor;
SetStandardCameraParameter(reflectCamera, reflectionMask);
if (!reflectCamera.targetTexture)
{
reflectCamera.targetTexture = CreateTextureFor(cam);
}
return reflectCamera;
}
void SetStandardCameraParameter(Camera cam, LayerMask mask)
{
cam.cullingMask = mask & ~(1 << LayerMask.NameToLayer("Water"));
cam.backgroundColor = Color.black;
cam.enabled = false;
}
RenderTexture CreateTextureFor(Camera cam)
{
RenderTexture rt = new RenderTexture(Mathf.FloorToInt(cam.pixelWidth * 0.5F),
Mathf.FloorToInt(cam.pixelHeight * 0.5F), 24);
rt.hideFlags = HideFlags.DontSave;
return rt;
}
public void RenderHelpCameras(Camera currentCam)
{
if (null == m_HelperCameras)
{
m_HelperCameras = new Dictionary<Camera, bool>();
}
if (!m_HelperCameras.ContainsKey(currentCam))
{
m_HelperCameras.Add(currentCam, false);
}
if (m_HelperCameras[currentCam])
{
return;
}
if (!m_ReflectionCamera)
{
m_ReflectionCamera = CreateReflectionCameraFor(currentCam);
}
RenderReflectionFor(currentCam, m_ReflectionCamera);
m_HelperCameras[currentCam] = true;
}
public void LateUpdate()
{
if (null != m_HelperCameras)
{
m_HelperCameras.Clear();
}
}
public void WaterTileBeingRendered(Transform tr, Camera currentCam)
{
RenderHelpCameras(currentCam);
if (m_ReflectionCamera && m_SharedMaterial)
{
m_SharedMaterial.SetTexture(reflectionSampler, m_ReflectionCamera.targetTexture);
}
}
public void OnEnable()
{
Shader.EnableKeyword("WATER_REFLECTIVE");
Shader.DisableKeyword("WATER_SIMPLE");
}
public void OnDisable()
{
Shader.EnableKeyword("WATER_SIMPLE");
Shader.DisableKeyword("WATER_REFLECTIVE");
}
void RenderReflectionFor(Camera cam, Camera reflectCamera)
{
if (!reflectCamera)
{
return;
}
if (m_SharedMaterial && !m_SharedMaterial.HasProperty(reflectionSampler))
{
return;
}
reflectCamera.cullingMask = reflectionMask & ~(1 << LayerMask.NameToLayer("Water"));
SaneCameraSettings(reflectCamera);
reflectCamera.backgroundColor = clearColor;
reflectCamera.clearFlags = reflectSkybox ? CameraClearFlags.Skybox : CameraClearFlags.SolidColor;
if (reflectSkybox)
{
if (cam.gameObject.GetComponent(typeof(Skybox)))
{
Skybox sb = (Skybox)reflectCamera.gameObject.GetComponent(typeof(Skybox));
if (!sb)
{
sb = (Skybox)reflectCamera.gameObject.AddComponent(typeof(Skybox));
}
sb.material = ((Skybox)cam.GetComponent(typeof(Skybox))).material;
}
}
GL.invertCulling = true;
Transform reflectiveSurface = transform; //waterHeight;
Vector3 eulerA = cam.transform.eulerAngles;
reflectCamera.transform.eulerAngles = new Vector3(-eulerA.x, eulerA.y, eulerA.z);
reflectCamera.transform.position = cam.transform.position;
Vector3 pos = reflectiveSurface.transform.position;
pos.y = reflectiveSurface.position.y;
Vector3 normal = reflectiveSurface.transform.up;
float d = -Vector3.Dot(normal, pos) - clipPlaneOffset;
Vector4 reflectionPlane = new Vector4(normal.x, normal.y, normal.z, d);
Matrix4x4 reflection = Matrix4x4.zero;
reflection = CalculateReflectionMatrix(reflection, reflectionPlane);
m_Oldpos = cam.transform.position;
Vector3 newpos = reflection.MultiplyPoint(m_Oldpos);
reflectCamera.worldToCameraMatrix = cam.worldToCameraMatrix * reflection;
Vector4 clipPlane = CameraSpacePlane(reflectCamera, pos, normal, 1.0f);
Matrix4x4 projection = cam.projectionMatrix;
projection = CalculateObliqueMatrix(projection, clipPlane);
reflectCamera.projectionMatrix = projection;
reflectCamera.transform.position = newpos;
Vector3 euler = cam.transform.eulerAngles;
reflectCamera.transform.eulerAngles = new Vector3(-euler.x, euler.y, euler.z);
reflectCamera.Render();
GL.invertCulling = false;
}
void SaneCameraSettings(Camera helperCam)
{
helperCam.depthTextureMode = DepthTextureMode.None;
helperCam.backgroundColor = Color.black;
helperCam.clearFlags = CameraClearFlags.SolidColor;
helperCam.renderingPath = RenderingPath.Forward;
}
static Matrix4x4 CalculateObliqueMatrix(Matrix4x4 projection, Vector4 clipPlane)
{
Vector4 q = projection.inverse * new Vector4(
Sgn(clipPlane.x),
Sgn(clipPlane.y),
1.0F,
1.0F
);
Vector4 c = clipPlane * (2.0F / (Vector4.Dot(clipPlane, q)));
// third row = clip plane - fourth row
projection[2] = c.x - projection[3];
projection[6] = c.y - projection[7];
projection[10] = c.z - projection[11];
projection[14] = c.w - projection[15];
return projection;
}
static Matrix4x4 CalculateReflectionMatrix(Matrix4x4 reflectionMat, Vector4 plane)
{
reflectionMat.m00 = (1.0F - 2.0F * plane[0] * plane[0]);
reflectionMat.m01 = (- 2.0F * plane[0] * plane[1]);
reflectionMat.m02 = (- 2.0F * plane[0] * plane[2]);
reflectionMat.m03 = (- 2.0F * plane[3] * plane[0]);
reflectionMat.m10 = (- 2.0F * plane[1] * plane[0]);
reflectionMat.m11 = (1.0F - 2.0F * plane[1] * plane[1]);
reflectionMat.m12 = (- 2.0F * plane[1] * plane[2]);
reflectionMat.m13 = (- 2.0F * plane[3] * plane[1]);
reflectionMat.m20 = (- 2.0F * plane[2] * plane[0]);
reflectionMat.m21 = (- 2.0F * plane[2] * plane[1]);
reflectionMat.m22 = (1.0F - 2.0F * plane[2] * plane[2]);
reflectionMat.m23 = (- 2.0F * plane[3] * plane[2]);
reflectionMat.m30 = 0.0F;
reflectionMat.m31 = 0.0F;
reflectionMat.m32 = 0.0F;
reflectionMat.m33 = 1.0F;
return reflectionMat;
}
static float Sgn(float a)
{
if (a > 0.0F)
{
return 1.0F;
}
if (a < 0.0F)
{
return -1.0F;
}
return 0.0F;
}
Vector4 CameraSpacePlane(Camera cam, Vector3 pos, Vector3 normal, float sideSign)
{
Vector3 offsetPos = pos + normal * clipPlaneOffset;
Matrix4x4 m = cam.worldToCameraMatrix;
Vector3 cpos = m.MultiplyPoint(offsetPos);
Vector3 cnormal = m.MultiplyVector(normal).normalized * sideSign;
return new Vector4(cnormal.x, cnormal.y, cnormal.z, -Vector3.Dot(cpos, cnormal));
}
}
}
| |
/*
* 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.Cache
{
using Apache.Ignite.Core.Binary;
using Apache.Ignite.Core.Cache;
/// <summary>
/// Cache metrics used to obtain statistics on cache.
/// </summary>
internal class CacheMetricsImpl : ICacheMetrics
{
/** */
private readonly long _cacheHits;
/** */
private readonly float _cacheHitPercentage;
/** */
private readonly long _cacheMisses;
/** */
private readonly float _cacheMissPercentage;
/** */
private readonly long _cacheGets;
/** */
private readonly long _cachePuts;
/** */
private readonly long _cacheRemovals;
/** */
private readonly long _cacheEvictions;
/** */
private readonly float _averageGetTime;
/** */
private readonly float _averagePutTime;
/** */
private readonly float _averageRemoveTime;
/** */
private readonly float _averageTxCommitTime;
/** */
private readonly float _averageTxRollbackTime;
/** */
private readonly long _cacheTxCommits;
/** */
private readonly long _cacheTxRollbacks;
/** */
private readonly string _cacheName;
/** */
private readonly long _offHeapGets;
/** */
private readonly long _offHeapPuts;
/** */
private readonly long _offHeapRemovals;
/** */
private readonly long _offHeapEvictions;
/** */
private readonly long _offHeapHits;
/** */
private readonly float _offHeapHitPercentage;
/** */
private readonly long _offHeapMisses;
/** */
private readonly float _offHeapMissPercentage;
/** */
private readonly long _offHeapEntriesCount;
/** */
private readonly long _offHeapPrimaryEntriesCount;
/** */
private readonly long _offHeapBackupEntriesCount;
/** */
private readonly long _offHeapAllocatedSize;
/** */
private readonly int _size;
/** */
private readonly int _keySize;
/** */
private readonly long _cacheSize;
/** */
private readonly bool _isEmpty;
/** */
private readonly int _dhtEvictQueueCurrentSize;
/** */
private readonly int _txThreadMapSize;
/** */
private readonly int _txXidMapSize;
/** */
private readonly int _txCommitQueueSize;
/** */
private readonly int _txPrepareQueueSize;
/** */
private readonly int _txStartVersionCountsSize;
/** */
private readonly int _txCommittedVersionsSize;
/** */
private readonly int _txRolledbackVersionsSize;
/** */
private readonly int _txDhtThreadMapSize;
/** */
private readonly int _txDhtXidMapSize;
/** */
private readonly int _txDhtCommitQueueSize;
/** */
private readonly int _txDhtPrepareQueueSize;
/** */
private readonly int _txDhtStartVersionCountsSize;
/** */
private readonly int _txDhtCommittedVersionsSize;
/** */
private readonly int _txDhtRolledbackVersionsSize;
/** */
private readonly bool _isWriteBehindEnabled;
/** */
private readonly int _writeBehindFlushSize;
/** */
private readonly int _writeBehindFlushThreadCount;
/** */
private readonly long _writeBehindFlushFrequency;
/** */
private readonly int _writeBehindStoreBatchSize;
/** */
private readonly int _writeBehindTotalCriticalOverflowCount;
/** */
private readonly int _writeBehindCriticalOverflowCount;
/** */
private readonly int _writeBehindErrorRetryCount;
/** */
private readonly int _writeBehindBufferSize;
/** */
private readonly string _keyType;
/** */
private readonly string _valueType;
/** */
private readonly bool _isStoreByValue;
/** */
private readonly bool _isStatisticsEnabled;
/** */
private readonly bool _isManagementEnabled;
/** */
private readonly bool _isReadThrough;
/** */
private readonly bool _isWriteThrough;
/** */
private readonly bool _isValidForReading;
/** */
private readonly bool _isValidForWriting;
/** */
private readonly int _totalPartitionsCount;
/** */
private readonly int _rebalancingPartitionsCount;
/** */
private readonly long _keysToRebalanceLeft;
/** */
private readonly long _rebalancingKeysRate;
/** */
private readonly long _rebalancingBytesRate;
/** */
private readonly long _heapEntriesCount;
/** */
private readonly long _estimatedRebalancingFinishTime;
/** */
private readonly long _rebalancingStartTime;
/** */
private readonly long _rebalancingClearingPartitionsLeft;
/** */
private readonly long _rebalancedKeys;
/** */
private readonly long _estimatedRebalancedKeys;
/** */
private readonly long _entryProcessorPuts;
/** */
private readonly float _entryProcessorAverageInvocationTime;
/** */
private readonly long _entryProcessorInvocations;
/** */
private readonly float _entryProcessorMaxInvocationTime;
/** */
private readonly float _entryProcessorMinInvocationTime;
/** */
private readonly long _entryProcessorReadOnlyInvocations;
/** */
private readonly float _entryProcessorHitPercentage;
/** */
private readonly long _entryProcessorHits;
/** */
private readonly long _entryProcessorMisses;
/** */
private readonly float _entryProcessorMissPercentage;
/** */
private readonly long _entryProcessorRemovals;
/// <summary>
/// Initializes a new instance of the <see cref="CacheMetricsImpl"/> class.
/// </summary>
/// <param name="reader">The reader.</param>
public CacheMetricsImpl(IBinaryRawReader reader)
{
_cacheHits = reader.ReadLong();
_cacheHitPercentage = reader.ReadFloat();
_cacheMisses = reader.ReadLong();
_cacheMissPercentage = reader.ReadFloat();
_cacheGets = reader.ReadLong();
_cachePuts = reader.ReadLong();
_cacheRemovals = reader.ReadLong();
_cacheEvictions = reader.ReadLong();
_averageGetTime = reader.ReadFloat();
_averagePutTime = reader.ReadFloat();
_averageRemoveTime = reader.ReadFloat();
_averageTxCommitTime = reader.ReadFloat();
_averageTxRollbackTime = reader.ReadFloat();
_cacheTxCommits = reader.ReadLong();
_cacheTxRollbacks = reader.ReadLong();
_cacheName = reader.ReadString();
_offHeapGets = reader.ReadLong();
_offHeapPuts = reader.ReadLong();
_offHeapRemovals = reader.ReadLong();
_offHeapEvictions = reader.ReadLong();
_offHeapHits = reader.ReadLong();
_offHeapHitPercentage = reader.ReadFloat();
_offHeapMisses = reader.ReadLong();
_offHeapMissPercentage = reader.ReadFloat();
_offHeapEntriesCount = reader.ReadLong();
_offHeapPrimaryEntriesCount = reader.ReadLong();
_offHeapBackupEntriesCount = reader.ReadLong();
_offHeapAllocatedSize = reader.ReadLong();
_size = reader.ReadInt();
_keySize = reader.ReadInt();
_isEmpty = reader.ReadBoolean();
_dhtEvictQueueCurrentSize = reader.ReadInt();
_txThreadMapSize = reader.ReadInt();
_txXidMapSize = reader.ReadInt();
_txCommitQueueSize = reader.ReadInt();
_txPrepareQueueSize = reader.ReadInt();
_txStartVersionCountsSize = reader.ReadInt();
_txCommittedVersionsSize = reader.ReadInt();
_txRolledbackVersionsSize = reader.ReadInt();
_txDhtThreadMapSize = reader.ReadInt();
_txDhtXidMapSize = reader.ReadInt();
_txDhtCommitQueueSize = reader.ReadInt();
_txDhtPrepareQueueSize = reader.ReadInt();
_txDhtStartVersionCountsSize = reader.ReadInt();
_txDhtCommittedVersionsSize = reader.ReadInt();
_txDhtRolledbackVersionsSize = reader.ReadInt();
_isWriteBehindEnabled = reader.ReadBoolean();
_writeBehindFlushSize = reader.ReadInt();
_writeBehindFlushThreadCount = reader.ReadInt();
_writeBehindFlushFrequency = reader.ReadLong();
_writeBehindStoreBatchSize = reader.ReadInt();
_writeBehindTotalCriticalOverflowCount = reader.ReadInt();
_writeBehindCriticalOverflowCount = reader.ReadInt();
_writeBehindErrorRetryCount = reader.ReadInt();
_writeBehindBufferSize = reader.ReadInt();
_keyType = reader.ReadString();
_valueType = reader.ReadString();
_isStoreByValue = reader.ReadBoolean();
_isStatisticsEnabled = reader.ReadBoolean();
_isManagementEnabled = reader.ReadBoolean();
_isReadThrough = reader.ReadBoolean();
_isWriteThrough = reader.ReadBoolean();
_isValidForReading = reader.ReadBoolean();
_isValidForWriting = reader.ReadBoolean();
_totalPartitionsCount = reader.ReadInt();
_rebalancingPartitionsCount = reader.ReadInt();
_keysToRebalanceLeft = reader.ReadLong();
_rebalancingKeysRate = reader.ReadLong();
_rebalancingBytesRate = reader.ReadLong();
_heapEntriesCount = reader.ReadLong();
_estimatedRebalancingFinishTime = reader.ReadLong();
_rebalancingStartTime = reader.ReadLong();
_rebalancingClearingPartitionsLeft = reader.ReadLong();
_cacheSize = reader.ReadLong();
_rebalancedKeys = reader.ReadLong();
_estimatedRebalancedKeys = reader.ReadLong();
_entryProcessorPuts = reader.ReadLong();
_entryProcessorAverageInvocationTime = reader.ReadFloat();
_entryProcessorInvocations = reader.ReadLong();
_entryProcessorMaxInvocationTime = reader.ReadFloat();
_entryProcessorMinInvocationTime = reader.ReadFloat();
_entryProcessorReadOnlyInvocations = reader.ReadLong();
_entryProcessorHitPercentage = reader.ReadFloat();
_entryProcessorHits = reader.ReadLong();
_entryProcessorMisses = reader.ReadLong();
_entryProcessorMissPercentage = reader.ReadFloat();
_entryProcessorRemovals = reader.ReadLong();
}
/** <inheritDoc /> */
public long CacheHits { get { return _cacheHits; } }
/** <inheritDoc /> */
public float CacheHitPercentage { get { return _cacheHitPercentage; } }
/** <inheritDoc /> */
public long CacheMisses { get { return _cacheMisses; } }
/** <inheritDoc /> */
public float CacheMissPercentage { get { return _cacheMissPercentage; } }
/** <inheritDoc /> */
public long CacheGets { get { return _cacheGets; } }
/** <inheritDoc /> */
public long CachePuts { get { return _cachePuts; } }
/** <inheritDoc /> */
public long CacheRemovals { get { return _cacheRemovals; } }
/** <inheritDoc /> */
public long CacheEvictions { get { return _cacheEvictions; } }
/** <inheritDoc /> */
public float AverageGetTime { get { return _averageGetTime; } }
/** <inheritDoc /> */
public float AveragePutTime { get { return _averagePutTime; } }
/** <inheritDoc /> */
public float AverageRemoveTime { get { return _averageRemoveTime; } }
/** <inheritDoc /> */
public float AverageTxCommitTime { get { return _averageTxCommitTime; } }
/** <inheritDoc /> */
public float AverageTxRollbackTime { get { return _averageTxRollbackTime; } }
/** <inheritDoc /> */
public long CacheTxCommits { get { return _cacheTxCommits; } }
/** <inheritDoc /> */
public long CacheTxRollbacks { get { return _cacheTxRollbacks; } }
/** <inheritDoc /> */
public string CacheName { get { return _cacheName; } }
/** <inheritDoc /> */
public long OffHeapGets { get { return _offHeapGets; } }
/** <inheritDoc /> */
public long OffHeapPuts { get { return _offHeapPuts; } }
/** <inheritDoc /> */
public long OffHeapRemovals { get { return _offHeapRemovals; } }
/** <inheritDoc /> */
public long OffHeapEvictions { get { return _offHeapEvictions; } }
/** <inheritDoc /> */
public long OffHeapHits { get { return _offHeapHits; } }
/** <inheritDoc /> */
public float OffHeapHitPercentage { get { return _offHeapHitPercentage; } }
/** <inheritDoc /> */
public long OffHeapMisses { get { return _offHeapMisses; } }
/** <inheritDoc /> */
public float OffHeapMissPercentage { get { return _offHeapMissPercentage; } }
/** <inheritDoc /> */
public long OffHeapEntriesCount { get { return _offHeapEntriesCount; } }
/** <inheritDoc /> */
public long OffHeapPrimaryEntriesCount { get { return _offHeapPrimaryEntriesCount; } }
/** <inheritDoc /> */
public long OffHeapBackupEntriesCount { get { return _offHeapBackupEntriesCount; } }
/** <inheritDoc /> */
public long OffHeapAllocatedSize { get { return _offHeapAllocatedSize; } }
/** <inheritDoc /> */
public int Size { get { return _size; } }
/** <inheritDoc /> */
public long CacheSize { get { return _cacheSize; } }
/** <inheritDoc /> */
public int KeySize { get { return _keySize; } }
/** <inheritDoc /> */
public bool IsEmpty { get { return _isEmpty; } }
/** <inheritDoc /> */
public int DhtEvictQueueCurrentSize { get { return _dhtEvictQueueCurrentSize; } }
/** <inheritDoc /> */
public int TxThreadMapSize { get { return _txThreadMapSize; } }
/** <inheritDoc /> */
public int TxXidMapSize { get { return _txXidMapSize; } }
/** <inheritDoc /> */
public int TxCommitQueueSize { get { return _txCommitQueueSize; } }
/** <inheritDoc /> */
public int TxPrepareQueueSize { get { return _txPrepareQueueSize; } }
/** <inheritDoc /> */
public int TxStartVersionCountsSize { get { return _txStartVersionCountsSize; } }
/** <inheritDoc /> */
public int TxCommittedVersionsSize { get { return _txCommittedVersionsSize; } }
/** <inheritDoc /> */
public int TxRolledbackVersionsSize { get { return _txRolledbackVersionsSize; } }
/** <inheritDoc /> */
public int TxDhtThreadMapSize { get { return _txDhtThreadMapSize; } }
/** <inheritDoc /> */
public int TxDhtXidMapSize { get { return _txDhtXidMapSize; } }
/** <inheritDoc /> */
public int TxDhtCommitQueueSize { get { return _txDhtCommitQueueSize; } }
/** <inheritDoc /> */
public int TxDhtPrepareQueueSize { get { return _txDhtPrepareQueueSize; } }
/** <inheritDoc /> */
public int TxDhtStartVersionCountsSize { get { return _txDhtStartVersionCountsSize; } }
/** <inheritDoc /> */
public int TxDhtCommittedVersionsSize { get { return _txDhtCommittedVersionsSize; } }
/** <inheritDoc /> */
public int TxDhtRolledbackVersionsSize { get { return _txDhtRolledbackVersionsSize; } }
/** <inheritDoc /> */
public bool IsWriteBehindEnabled { get { return _isWriteBehindEnabled; } }
/** <inheritDoc /> */
public int WriteBehindFlushSize { get { return _writeBehindFlushSize; } }
/** <inheritDoc /> */
public int WriteBehindFlushThreadCount { get { return _writeBehindFlushThreadCount; } }
/** <inheritDoc /> */
public long WriteBehindFlushFrequency { get { return _writeBehindFlushFrequency; } }
/** <inheritDoc /> */
public int WriteBehindStoreBatchSize { get { return _writeBehindStoreBatchSize; } }
/** <inheritDoc /> */
public int WriteBehindTotalCriticalOverflowCount { get { return _writeBehindTotalCriticalOverflowCount; } }
/** <inheritDoc /> */
public int WriteBehindCriticalOverflowCount { get { return _writeBehindCriticalOverflowCount; } }
/** <inheritDoc /> */
public int WriteBehindErrorRetryCount { get { return _writeBehindErrorRetryCount; } }
/** <inheritDoc /> */
public int WriteBehindBufferSize { get { return _writeBehindBufferSize; } }
/** <inheritDoc /> */
public string KeyType { get { return _keyType; } }
/** <inheritDoc /> */
public string ValueType { get { return _valueType; } }
/** <inheritDoc /> */
public bool IsStoreByValue { get { return _isStoreByValue; } }
/** <inheritDoc /> */
public bool IsStatisticsEnabled { get { return _isStatisticsEnabled; } }
/** <inheritDoc /> */
public bool IsManagementEnabled { get { return _isManagementEnabled; } }
/** <inheritDoc /> */
public bool IsReadThrough { get { return _isReadThrough; } }
/** <inheritDoc /> */
public bool IsWriteThrough { get { return _isWriteThrough; } }
/** <inheritDoc /> */
public bool IsValidForReading { get { return _isValidForReading; } }
/** <inheritDoc /> */
public bool IsValidForWriting { get { return _isValidForWriting; } }
/** <inheritDoc /> */
public int TotalPartitionsCount { get { return _totalPartitionsCount; } }
/** <inheritDoc /> */
public int RebalancingPartitionsCount { get { return _rebalancingPartitionsCount; } }
/** <inheritDoc /> */
public long KeysToRebalanceLeft { get { return _keysToRebalanceLeft; } }
/** <inheritDoc /> */
public long RebalancingKeysRate { get { return _rebalancingKeysRate; } }
/** <inheritDoc /> */
public long RebalancingBytesRate { get { return _rebalancingBytesRate; } }
/** <inheritDoc /> */
public long HeapEntriesCount { get { return _heapEntriesCount; } }
/** <inheritDoc /> */
public long EstimatedRebalancingFinishTime { get { return _estimatedRebalancingFinishTime; } }
/** <inheritDoc /> */
public long RebalancingStartTime { get { return _rebalancingStartTime; } }
/** <inheritDoc /> */
public long RebalanceClearingPartitionsLeft { get { return _rebalancingClearingPartitionsLeft; } }
/** <inheritDoc /> */
public long RebalancedKeys { get { return _rebalancedKeys; } }
/** <inheritDoc /> */
public long EstimatedRebalancingKeys { get { return _estimatedRebalancedKeys; } }
/** <inheritDoc /> */
public long EntryProcessorPuts { get { return _entryProcessorPuts; } }
/** <inheritDoc /> */
public float EntryProcessorAverageInvocationTime { get { return _entryProcessorAverageInvocationTime; } }
/** <inheritDoc /> */
public long EntryProcessorInvocations { get { return _entryProcessorInvocations; } }
/** <inheritDoc /> */
public float EntryProcessorMaxInvocationTime { get { return _entryProcessorMaxInvocationTime; } }
/** <inheritDoc /> */
public float EntryProcessorMinInvocationTime { get { return _entryProcessorMinInvocationTime; } }
/** <inheritDoc /> */
public long EntryProcessorReadOnlyInvocations { get { return _entryProcessorReadOnlyInvocations; } }
/** <inheritDoc /> */
public float EntryProcessorHitPercentage { get { return _entryProcessorHitPercentage; } }
/** <inheritDoc /> */
public long EntryProcessorHits { get { return _entryProcessorHits; } }
/** <inheritDoc /> */
public long EntryProcessorMisses { get { return _entryProcessorMisses; } }
/** <inheritDoc /> */
public float EntryProcessorMissPercentage { get { return _entryProcessorMissPercentage; } }
/** <inheritDoc /> */
public long EntryProcessorRemovals { get { return _entryProcessorRemovals; } }
}
}
| |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// File System.Web.HttpResponseBase.cs
// Automatically generated contract file.
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Diagnostics.Contracts;
using System;
// Disable the "this variable is not used" warning as every field would imply it.
#pragma warning disable 0414
// Disable the "this variable is never assigned to".
#pragma warning disable 0067
// Disable the "this event is never assigned to".
#pragma warning disable 0649
// Disable the "this variable is never used".
#pragma warning disable 0169
// Disable the "new keyword not required" warning.
#pragma warning disable 0109
// Disable the "extern without DllImport" warning.
#pragma warning disable 0626
// Disable the "could hide other member" warning, can happen on certain properties.
#pragma warning disable 0108
namespace System.Web
{
abstract public partial class HttpResponseBase
{
#region Methods and constructors
public virtual new void AddCacheDependency(System.Web.Caching.CacheDependency[] dependencies)
{
}
public virtual new void AddCacheItemDependencies(string[] cacheKeys)
{
}
public virtual new void AddCacheItemDependencies(System.Collections.ArrayList cacheKeys)
{
}
public virtual new void AddCacheItemDependency(string cacheKey)
{
}
public virtual new void AddFileDependencies(string[] filenames)
{
}
public virtual new void AddFileDependencies(System.Collections.ArrayList filenames)
{
}
public virtual new void AddFileDependency(string filename)
{
}
public virtual new void AddHeader(string name, string value)
{
}
public virtual new void AppendCookie(HttpCookie cookie)
{
}
public virtual new void AppendHeader(string name, string value)
{
}
public virtual new void AppendToLog(string param)
{
}
public virtual new string ApplyAppPathModifier(string virtualPath)
{
return default(string);
}
public virtual new void BinaryWrite(byte[] buffer)
{
}
public virtual new void Clear()
{
}
public virtual new void ClearContent()
{
}
public virtual new void ClearHeaders()
{
}
public virtual new void Close()
{
}
public virtual new void DisableKernelCache()
{
}
public virtual new void End()
{
}
public virtual new void Flush()
{
}
protected HttpResponseBase()
{
}
public virtual new void Pics(string value)
{
}
public virtual new void Redirect(string url, bool endResponse)
{
}
public virtual new void Redirect(string url)
{
}
public virtual new void RedirectPermanent(string url)
{
}
public virtual new void RedirectPermanent(string url, bool endResponse)
{
}
public virtual new void RedirectToRoute(System.Web.Routing.RouteValueDictionary routeValues)
{
}
public virtual new void RedirectToRoute(string routeName, System.Web.Routing.RouteValueDictionary routeValues)
{
}
public virtual new void RedirectToRoute(Object routeValues)
{
}
public virtual new void RedirectToRoute(string routeName)
{
}
public virtual new void RedirectToRoute(string routeName, Object routeValues)
{
}
public virtual new void RedirectToRoutePermanent(string routeName, System.Web.Routing.RouteValueDictionary routeValues)
{
}
public virtual new void RedirectToRoutePermanent(string routeName)
{
}
public virtual new void RedirectToRoutePermanent(string routeName, Object routeValues)
{
}
public virtual new void RedirectToRoutePermanent(Object routeValues)
{
}
public virtual new void RedirectToRoutePermanent(System.Web.Routing.RouteValueDictionary routeValues)
{
}
public virtual new void RemoveOutputCacheItem(string path)
{
}
public virtual new void RemoveOutputCacheItem(string path, string providerName)
{
}
public virtual new void SetCookie(HttpCookie cookie)
{
}
public virtual new void TransmitFile(string filename)
{
}
public virtual new void TransmitFile(string filename, long offset, long length)
{
}
public virtual new void Write(Object obj)
{
}
public virtual new void Write(string s)
{
}
public virtual new void Write(char ch)
{
}
public virtual new void Write(char[] buffer, int index, int count)
{
}
public virtual new void WriteFile(string filename, long offset, long size)
{
}
public virtual new void WriteFile(IntPtr fileHandle, long offset, long size)
{
}
public virtual new void WriteFile(string filename)
{
}
public virtual new void WriteFile(string filename, bool readIntoMemory)
{
}
public virtual new void WriteSubstitution(HttpResponseSubstitutionCallback callback)
{
}
#endregion
#region Properties and indexers
public virtual new bool Buffer
{
get
{
return default(bool);
}
set
{
}
}
public virtual new bool BufferOutput
{
get
{
return default(bool);
}
set
{
}
}
public virtual new HttpCachePolicyBase Cache
{
get
{
return default(HttpCachePolicyBase);
}
}
public virtual new string CacheControl
{
get
{
return default(string);
}
set
{
}
}
public virtual new string Charset
{
get
{
return default(string);
}
set
{
}
}
public virtual new Encoding ContentEncoding
{
get
{
return default(Encoding);
}
set
{
}
}
public virtual new string ContentType
{
get
{
return default(string);
}
set
{
}
}
public virtual new HttpCookieCollection Cookies
{
get
{
return default(HttpCookieCollection);
}
}
public virtual new int Expires
{
get
{
return default(int);
}
set
{
}
}
public virtual new DateTime ExpiresAbsolute
{
get
{
return default(DateTime);
}
set
{
}
}
public virtual new Stream Filter
{
get
{
return default(Stream);
}
set
{
}
}
public virtual new Encoding HeaderEncoding
{
get
{
return default(Encoding);
}
set
{
}
}
public virtual new System.Collections.Specialized.NameValueCollection Headers
{
get
{
return default(System.Collections.Specialized.NameValueCollection);
}
}
public virtual new bool IsClientConnected
{
get
{
return default(bool);
}
}
public virtual new bool IsRequestBeingRedirected
{
get
{
return default(bool);
}
}
public virtual new TextWriter Output
{
get
{
return default(TextWriter);
}
}
public virtual new Stream OutputStream
{
get
{
return default(Stream);
}
}
public virtual new string RedirectLocation
{
get
{
return default(string);
}
set
{
}
}
public virtual new string Status
{
get
{
return default(string);
}
set
{
}
}
public virtual new int StatusCode
{
get
{
return default(int);
}
set
{
}
}
public virtual new string StatusDescription
{
get
{
return default(string);
}
set
{
}
}
public virtual new int SubStatusCode
{
get
{
return default(int);
}
set
{
}
}
public virtual new bool SuppressContent
{
get
{
return default(bool);
}
set
{
}
}
public virtual new bool TrySkipIisCustomErrors
{
get
{
return default(bool);
}
set
{
}
}
#endregion
}
}
| |
// Copyright 2012 The Noda Time Authors. All rights reserved.
// Use of this source code is governed by the Apache License 2.0,
// as found in the LICENSE.txt file.
using System.Linq;
using JetBrains.Annotations;
using NodaTime.Annotations;
using NodaTime.Extensions;
#if !PCL
using System;
using System.Collections.Generic;
using NodaTime.Utility;
namespace NodaTime.TimeZones
{
/// <summary>
/// Representation of a time zone converted from a <see cref="TimeZoneInfo"/> from the Base Class Library.
/// </summary>
/// <remarks>
/// <para>
/// Two instances of this class are deemed equal if and only if they refer to the exact same
/// <see cref="TimeZoneInfo"/> object.
/// </para>
/// <para>
/// This implementation does not always give the same results as <c>TimeZoneInfo</c>, in that it doesn't replicate
/// the bugs in the BCL interpretation of the data. These bugs are described in
/// <a href="http://codeblog.jonskeet.uk/2014/09/30/the-mysteries-of-bcl-time-zone-data/">a blog post</a>, but we're
/// not expecting them to be fixed any time soon. Being bug-for-bug compatible would not only be tricky, but would be painful
/// if the BCL were ever to be fixed. As far as we are aware, there are only discrepancies around new year where the zone
/// changes from observing one rule to observing another.
/// </para>
/// </remarks>
/// <threadsafety>This type is immutable reference type. See the thread safety section of the user guide for more information.</threadsafety>
[Immutable]
public sealed class BclDateTimeZone : DateTimeZone
{
/// <summary>
/// This is used to cache the last result of a call to <see cref="ForSystemDefault"/>, but it doesn't
/// matter if it's out of date - we'll just create another wrapper if necessary. It's not *that* expensive to make
/// a few more wrappers than we need.
/// </summary>
private static BclDateTimeZone systemDefault;
private readonly IZoneIntervalMap map;
/// <summary>
/// Gets the original <see cref="TimeZoneInfo"/> from which this was created.
/// </summary>
/// <value>The original <see cref="TimeZoneInfo"/> from which this was created.</value>
public TimeZoneInfo OriginalZone { get; }
/// <summary>
/// Gets the display name associated with the time zone, as provided by the Base Class Library.
/// </summary>
/// <value>The display name associated with the time zone, as provided by the Base Class Library.</value>
public string DisplayName => OriginalZone.DisplayName;
private BclDateTimeZone(TimeZoneInfo bclZone, Offset minOffset, Offset maxOffset, IZoneIntervalMap map)
: base(bclZone.Id, bclZone.SupportsDaylightSavingTime, minOffset, maxOffset)
{
this.OriginalZone = bclZone;
this.map = map;
}
/// <inheritdoc />
public override ZoneInterval GetZoneInterval(Instant instant)
{
return map.GetZoneInterval(instant);
}
/// <summary>
/// Creates a new <see cref="BclDateTimeZone" /> from a <see cref="TimeZoneInfo"/> from the Base Class Library.
/// </summary>
/// <param name="bclZone">The original time zone to take information from.</param>
/// <returns>A <see cref="BclDateTimeZone"/> wrapping the given <c>TimeZoneInfo</c>.</returns>
public static BclDateTimeZone FromTimeZoneInfo([NotNull] TimeZoneInfo bclZone)
{
Preconditions.CheckNotNull(bclZone, nameof(bclZone));
Offset standardOffset = bclZone.BaseUtcOffset.ToOffset();
var rules = bclZone.GetAdjustmentRules();
if (!bclZone.SupportsDaylightSavingTime || rules.Length == 0)
{
var fixedInterval = new ZoneInterval(bclZone.StandardName, Instant.BeforeMinValue, Instant.AfterMaxValue, standardOffset, Offset.Zero);
return new BclDateTimeZone(bclZone, standardOffset, standardOffset, new SingleZoneIntervalMap(fixedInterval));
}
BclAdjustmentRule[] convertedRules = Array.ConvertAll(rules, rule => new BclAdjustmentRule(bclZone, rule));
Offset minRuleOffset = convertedRules.Aggregate(Offset.MaxValue, (min, rule) => Offset.Min(min, rule.Savings + rule.StandardOffset));
Offset maxRuleOffset = convertedRules.Aggregate(Offset.MinValue, (min, rule) => Offset.Max(min, rule.Savings + rule.StandardOffset));
IZoneIntervalMap uncachedMap = BuildMap(convertedRules, standardOffset, bclZone.StandardName);
IZoneIntervalMap cachedMap = CachingZoneIntervalMap.CacheMap(uncachedMap, CachingZoneIntervalMap.CacheType.Hashtable);
return new BclDateTimeZone(bclZone, Offset.Min(standardOffset, minRuleOffset), Offset.Max(standardOffset, maxRuleOffset), cachedMap);
}
private static IZoneIntervalMap BuildMap(BclAdjustmentRule[] rules, Offset standardOffset, [NotNull] string standardName)
{
Preconditions.CheckNotNull(standardName, nameof(standardName));
// First work out a naive list of partial maps. These will give the right offset at every instant, but not necessarily
// correct intervals - we may we need to stitch intervals together.
List<PartialZoneIntervalMap> maps = new List<PartialZoneIntervalMap>();
// Handle the start of time until the start of the first rule, if necessary.
if (rules[0].Start.IsValid)
{
maps.Add(PartialZoneIntervalMap.ForZoneInterval(standardName, Instant.BeforeMinValue, rules[0].Start, standardOffset, Offset.Zero));
}
for (int i = 0; i < rules.Length - 1; i++)
{
var beforeRule = rules[i];
var afterRule = rules[i + 1];
maps.Add(beforeRule.PartialMap);
// If there's a gap between this rule and the next one, fill it with a fixed interval.
if (beforeRule.End < afterRule.Start)
{
maps.Add(PartialZoneIntervalMap.ForZoneInterval(standardName, beforeRule.End, afterRule.Start, standardOffset, Offset.Zero));
}
}
var lastRule = rules[rules.Length - 1];
maps.Add(lastRule.PartialMap);
// Handle the end of the last rule until the end of time, if necessary.
if (lastRule.End.IsValid)
{
maps.Add(PartialZoneIntervalMap.ForZoneInterval(standardName, lastRule.End, Instant.AfterMaxValue, standardOffset, Offset.Zero));
}
return PartialZoneIntervalMap.ConvertToFullMap(maps);
}
/// <summary>
/// Just a mapping of a TimeZoneInfo.AdjustmentRule into Noda Time types. Very little cleverness here.
/// </summary>
private sealed class BclAdjustmentRule
{
private static readonly DateTime MaxDate = DateTime.MaxValue.Date;
/// <summary>
/// Instant on which this rule starts.
/// </summary>
internal Instant Start { get; }
/// <summary>
/// Instant on which this rule ends.
/// </summary>
internal Instant End { get; }
/// <summary>
/// Daylight savings, when applicable within this rule.
/// </summary>
internal Offset Savings { get; }
/// <summary>
/// The standard offset for the duration of this rule.
/// </summary>
internal Offset StandardOffset { get; }
internal PartialZoneIntervalMap PartialMap { get; }
internal BclAdjustmentRule(TimeZoneInfo zone, TimeZoneInfo.AdjustmentRule rule)
{
// With .NET 4.6, adjustment rules can have their own standard offsets, allowing
// a much more reasonable set of time zone data. Unfortunately, this isn't directly
// exposed, but we can detect it by just finding the UTC offset for an arbitrary
// time within the rule - the start, in this case - and then take account of the
// possibility of that being in daylight saving time. Fortunately, we only need
// to do this during the setup.
var ruleStandardOffset = zone.GetUtcOffset(rule.DateStart);
if (zone.IsDaylightSavingTime(rule.DateStart))
{
ruleStandardOffset -= rule.DaylightDelta;
}
StandardOffset = ruleStandardOffset.ToOffset();
// Although the rule may have its own standard offset, the start/end is still determined
// using the zone's standard offset.
var zoneStandardOffset = zone.BaseUtcOffset.ToOffset();
// Note: this extends back from DateTime.MinValue to start of time, even though the BCL can represent
// as far back as 1AD. This is in the *spirit* of a rule which goes back that far.
Start = rule.DateStart == DateTime.MinValue ? Instant.BeforeMinValue : rule.DateStart.ToLocalDateTime().WithOffset(zoneStandardOffset).ToInstant();
// The end instant (exclusive) is the end of the given date, so we need to add a day.
End = rule.DateEnd == MaxDate ? Instant.AfterMaxValue : rule.DateEnd.ToLocalDateTime().PlusDays(1).WithOffset(zoneStandardOffset).ToInstant();
Savings = rule.DaylightDelta.ToOffset();
// Some rules have DST start/end of "January 1st", to indicate that they're just in standard time. This is important
// for rules which have a standard offset which is different to the standard offset of the zone itself.
if (IsStandardOffsetOnlyRule(rule))
{
PartialMap = PartialZoneIntervalMap.ForZoneInterval(zone.StandardName, Start, End, StandardOffset, Offset.Zero);
}
else
{
var daylightRecurrence = new ZoneRecurrence(zone.DaylightName, Savings, ConvertTransition(rule.DaylightTransitionStart), int.MinValue, int.MaxValue);
var standardRecurrence = new ZoneRecurrence(zone.StandardName, Offset.Zero, ConvertTransition(rule.DaylightTransitionEnd), int.MinValue, int.MaxValue);
var recurringMap = new StandardDaylightAlternatingMap(StandardOffset, standardRecurrence, daylightRecurrence);
PartialMap = new PartialZoneIntervalMap(Start, End, recurringMap);
}
}
/// <summary>
/// The BCL represents "standard-only" rules using two fixed date January 1st transitions.
/// Currently the time-of-day used for the DST end transition is at one millisecond past midnight... we'll
/// be slightly more lenient, accepting anything up to 12:01...
/// </summary>
private static bool IsStandardOffsetOnlyRule(TimeZoneInfo.AdjustmentRule rule)
{
var daylight = rule.DaylightTransitionStart;
var standard = rule.DaylightTransitionEnd;
return daylight.IsFixedDateRule && daylight.Day == 1 && daylight.Month == 1 &&
daylight.TimeOfDay.TimeOfDay < TimeSpan.FromMinutes(1) &&
standard.IsFixedDateRule && standard.Day == 1 && standard.Month == 1 &&
standard.TimeOfDay.TimeOfDay < TimeSpan.FromMinutes(1);
}
// Converts a TimeZoneInfo "TransitionTime" to a "ZoneYearOffset" - the two correspond pretty closely.
private static ZoneYearOffset ConvertTransition(TimeZoneInfo.TransitionTime transitionTime)
{
// Used for both fixed and non-fixed transitions.
LocalTime timeOfDay = LocalDateTime.FromDateTime(transitionTime.TimeOfDay).TimeOfDay;
// Easy case - fixed day of the month.
if (transitionTime.IsFixedDateRule)
{
return new ZoneYearOffset(TransitionMode.Wall, transitionTime.Month, transitionTime.Day, 0, false, timeOfDay);
}
// Floating: 1st Sunday in March etc.
int dayOfWeek = (int)BclConversions.ToIsoDayOfWeek(transitionTime.DayOfWeek);
int dayOfMonth;
bool advance;
// "Last"
if (transitionTime.Week == 5)
{
advance = false;
dayOfMonth = -1;
}
else
{
advance = true;
// Week 1 corresponds to ">=1"
// Week 2 corresponds to ">=8" etc
dayOfMonth = (transitionTime.Week * 7) - 6;
}
return new ZoneYearOffset(TransitionMode.Wall, transitionTime.Month, dayOfMonth, dayOfWeek, advance, timeOfDay);
}
}
/// <summary>
/// Returns a time zone converted from the BCL representation of the system local time zone.
/// </summary>
/// <remarks>
/// <para>
/// This method is approximately equivalent to calling <see cref="IDateTimeZoneProvider.GetSystemDefault"/> with
/// an implementation that wraps <see cref="BclDateTimeZoneSource"/> (e.g.
/// <see cref="DateTimeZoneProviders.Bcl"/>), with the exception that it will succeed even if the current local
/// time zone was not one of the set of system time zones captured when the source was created (which, while
/// highly unlikely, might occur either because the local time zone is not a system time zone, or because the
/// system time zones have themselves changed).
/// </para>
/// <para>
/// This method will retain a reference to the returned <c>BclDateTimeZone</c>, and will attempt to return it if
/// called repeatedly (assuming that the local time zone has not changed) rather than creating a new instance,
/// though this behaviour is not guaranteed.
/// </para>
/// </remarks>
/// <returns>A <see cref="BclDateTimeZone"/> wrapping the "local" (system) time zone as returned by
/// <see cref="TimeZoneInfo.Local"/>.</returns>
public static BclDateTimeZone ForSystemDefault()
{
TimeZoneInfo local = TimeZoneInfo.Local;
BclDateTimeZone currentSystemDefault = systemDefault;
// Cached copy is out of date - wrap a new one
if (currentSystemDefault?.OriginalZone != local)
{
currentSystemDefault = FromTimeZoneInfo(local);
systemDefault = currentSystemDefault;
}
// Always return our local variable; the variable may have changed again.
return currentSystemDefault;
}
/// <inheritdoc />
/// <remarks>
/// This implementation simply compares the underlying `TimeZoneInfo` values for
/// reference equality.
/// </remarks>
protected override bool EqualsImpl(DateTimeZone zone)
{
return ReferenceEquals(OriginalZone, ((BclDateTimeZone) zone).OriginalZone);
}
/// <inheritdoc />
public override int GetHashCode() => OriginalZone.GetHashCode();
}
}
#endif
| |
using System.Collections.Generic;
using System.Linq;
namespace UnityEngine
{
public class Geometry
{
public static Vector2 PointOnCircle(float radius, float angleInDegrees, Vector2 origin)
{
// Convert from degrees to radians via multiplication by PI/180
float x = (radius * Mathf.Cos(angleInDegrees * Mathf.PI / 180F)) + origin.x;
float y = (radius * Mathf.Sin(angleInDegrees * Mathf.PI / 180F)) + origin.y;
x = Mathf.Clamp(x, float.MinValue, float.MaxValue);
y = Mathf.Clamp(y, float.MinValue, float.MaxValue);
return new Vector2(x, y);
}
public static float Circumference(float radius)
{
if (radius >= float.MaxValue)
return float.MaxValue;
if (radius <= float.MinValue)
return float.MinValue;
float circumference = (2f * Mathf.PI * radius);
return circumference;
}
public static float Radius(float circumference)
{
if (circumference >= float.MaxValue)
return float.MaxValue;
if (circumference <= float.MinValue)
return float.MinValue;
return (circumference / (2f * Mathf.PI));
}
public static List<Vector3> GetFibonacciSphereVertices(int vertexCount = 1, bool randomize = true)
{
List<Vector3> vertices = new List<Vector3>();
vertices.Capacity = vertexCount;
float random = 1f;
if (randomize)
random = Random.Range(0f, 1f) * vertexCount;
float offset = 2f / vertexCount;
float increment = Mathf.PI * (3f - Mathf.Sqrt(5)); // what is 3 and 5?
float x, y, z, r, phi;
for (int i = 0; i < vertexCount; i++)
{
y = ((i * offset) - 1) + (offset / 2f);
r = Mathf.Sqrt(1f - Mathf.Pow(y, 2));
phi = ((i + random) % vertexCount) * increment;
x = Mathf.Cos(phi) * r;
z = Mathf.Sin(phi) * r;
vertices.Add(new Vector3(x, y, z));
}
return vertices;
}
private static int GetMidpointIndex(Dictionary<string, int> midpointIndices, List<Vector3> vertices, int i0, int i1)
{
var edgeKey = string.Format("{0}_{1}", Mathf.Min(i0, i1), Mathf.Max(i0, i1));
var midpointIndex = -1;
if (!midpointIndices.TryGetValue(edgeKey, out midpointIndex))
{
var v0 = vertices[i0];
var v1 = vertices[i1];
var midpoint = (v0 + v1) / 2f;
if (vertices.Contains(midpoint))
midpointIndex = vertices.IndexOf(midpoint);
else
{
midpointIndex = vertices.Count;
vertices.Add(midpoint);
midpointIndices.Add(edgeKey, midpointIndex);
}
}
return midpointIndex;
}
/// <remarks>
/// i0
/// / \
/// m02-m01
/// / \ / \
/// i2---m12---i1
/// </remarks>
/// <param name="vectors"></param>
/// <param name="indices"></param>
public static void Subdivide(List<Vector3> vectors, List<int> indices, bool removeSourceTriangles)
{
var midpointIndices = new Dictionary<string, int>();
var newIndices = new List<int>(indices.Count * 4);
if (!removeSourceTriangles)
newIndices.AddRange(indices);
for (var i = 0; i < indices.Count - 2; i += 3)
{
var i0 = indices[i];
var i1 = indices[i + 1];
var i2 = indices[i + 2];
var m01 = GetMidpointIndex(midpointIndices, vectors, i0, i1);
var m12 = GetMidpointIndex(midpointIndices, vectors, i1, i2);
var m02 = GetMidpointIndex(midpointIndices, vectors, i2, i0);
newIndices.AddRange(
new[] {
i0,m01,m02
,
i1,m12,m01
,
i2,m02,m12
,
m02,m01,m12
}
);
}
indices.Clear();
indices.AddRange(newIndices);
}
/// <summary>
/// create a regular icosahedron (20-sided polyhedron)
/// </summary>
/// <remarks>
/// You can create this programmatically instead of using the given vertex
/// and index list, but it's kind of a pain and rather pointless beyond a
/// learning exercise.
/// </remarks>
public static void Icosahedron(List<Vector3> vertices, List<int> indices)
{
indices.AddRange(
new int[]
{
0,4,1,
0,9,4,
9,5,4,
4,5,8,
4,8,1,
8,10,1,
8,3,10,
5,3,8,
5,2,3,
2,7,3,
7,10,3,
7,6,10,
7,11,6,
11,0,6,
0,1,6,
6,1,10,
9,0,11,
9,11,2,
9,2,5,
7,2,11
}
.Select(i => i + vertices.Count)
);
var X = 0.525731112119133606f;
var Z = 0.850650808352039932f;
vertices.AddRange(
new[]
{
new Vector3(-X, 0f, Z),
new Vector3(X, 0f, Z),
new Vector3(-X, 0f, -Z),
new Vector3(X, 0f, -Z),
new Vector3(0f, Z, X),
new Vector3(0f, Z, -X),
new Vector3(0f, -Z, X),
new Vector3(0f, -Z, -X),
new Vector3(Z, X, 0f),
new Vector3(-Z, X, 0f),
new Vector3(Z, -X, 0f),
new Vector3(-Z, -X, 0f)
}
);
}
/// <summary>
/// Creates a smoothly subdivided icosahedron.
/// </summary>
/// <remarks>
/// Vertex count is 2 + 10 * 4 ^ subdivisions (i.e. 12, 42, 162, 642, 2562, 10242...)
/// Subdivision is slow above 3.
/// Times:
/// 0,1,2 = 0ms
/// 3 = 43ms
/// 4 = 605ms
/// 5 = 9531ms
/// 6 = ????
/// </remarks>
public static List<Vector3> GetSubdividedIcosahedronVertices(int subdivisions = 0)
{
List<Vector3> vertices = new List<Vector3>();
List<int> indices = new List<int>();
Icosahedron(vertices, indices);
// Subdivide
for (int i = 0; i < subdivisions; i++)
Subdivide(vertices, indices, true);
// Smooth vertices into a spherical shape
for (int i = 0; i < vertices.Count; i++)
vertices[i] = vertices[i].normalized;
return vertices;
}
public static Mesh Create9SlicedMesh(float border = 1f, float width = 3f, float height = 3f, float marginUV = 1f)
{
Mesh mesh = new Mesh();
mesh.vertices = new Vector3[] {
new Vector3(0, 0, 0),
new Vector3(border, 0, 0),
new Vector3(width - border, 0, 0),
new Vector3(width, 0, 0),
new Vector3(0, border, 0),
new Vector3(border, border, 0),
new Vector3(width - border, border, 0),
new Vector3(width, border, 0),
new Vector3(0, height - border, 0),
new Vector3(border, height - border, 0),
new Vector3(width - border, height - border, 0),
new Vector3(width, height - border, 0),
new Vector3(0, height, 0),
new Vector3(border, height, 0),
new Vector3(width - border, height, 0),
new Vector3(width, height, 0)
};
mesh.uv = new Vector2[] {
new Vector2(0, 0),
new Vector2(marginUV, 0),
new Vector2(1 - marginUV, 0),
new Vector2(1, 0),
new Vector2(0, marginUV),
new Vector2(marginUV, marginUV),
new Vector2(1 - marginUV, marginUV),
new Vector2(1, marginUV),
new Vector2(0, 1 - marginUV),
new Vector2(marginUV, 1 - marginUV),
new Vector2(1 - marginUV, 1 - marginUV),
new Vector2(1, 1 - marginUV),
new Vector2(0, 1),
new Vector2(marginUV, 1),
new Vector2(1 - marginUV, 1),
new Vector2(1, 1)
};
mesh.triangles = new int[] {
0, 4, 5,
0, 5, 1,
1, 5, 6,
1, 6, 2,
2, 6, 7,
2, 7, 3,
4, 8, 9,
4, 9, 5,
5, 9, 10, // center plane
5, 10, 6, // center plane
6, 10, 11,
6, 11, 7,
8, 12, 13,
8, 13, 9,
9, 13, 14,
9, 14, 10,
10, 14, 15,
10, 15, 11
};
return mesh;
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
namespace MeddleFramework
{
public class PEOptHeader
{
bool _is64;
PEOptHeader32 _opt32;
PEOptHeader64 _opt64;
// Wrapper for PEOptHeader32 and PEOptHeader64
public UInt32 signature //decimal number 267.
{ get { return (_is64 ? _opt64.Magic : _opt32.signature); } }
public byte MajorLinkerVersion
{ get { return (_is64 ? _opt64.MajorLinkerVersion : _opt32.MajorLinkerVersion); } }
public byte MinorLinkerVersion
{ get { return (_is64 ? _opt64.MinorLinkerVersion : _opt32.MinorLinkerVersion); } }
public UInt32 SizeOfCode
{ get { return (_is64 ? _opt64.SizeOfCode : _opt32.SizeOfCode); } }
public UInt32 SizeOfInitializedData
{ get { return (_is64 ? _opt64.SizeOfInitializedData : _opt32.SizeOfInitializedData); } }
public UInt32 SizeOfUninitializedData
{ get { return (_is64 ? _opt64.SizeOfUninitializedData : _opt32.SizeOfUninitializedData); } }
public UInt32 AddressOfEntryPoint //The RVA of the code entry point
{ get { return (_is64 ? _opt64.AddressOfEntryPoint : _opt32.AddressOfEntryPoint); } }
public UInt32 BaseOfCode
{ get { return (_is64 ? _opt64.BaseOfCode : _opt32.BaseOfCode); } }
public UInt64 BaseOfData
{ get { return (_is64 ? _opt64.ImageBase : _opt32.BaseOfData); } }
public UInt64 ImageBase
{ get { return (_is64 ? _opt64.ImageBase : _opt32.ImageBase); } }
public UInt32 SectionAlignment
{ get { return (_is64 ? _opt64.SectionAlignment : _opt32.SectionAlignment); } }
public UInt32 FileAlignment
{ get { return (_is64 ? _opt64.FileAlignment : _opt32.FileAlignment); } }
public UInt16 MajorOSVersion
{ get { return (_is64 ? _opt64.MajorOperatingSystemVersion : _opt32.MajorOSVersion); } }
public UInt16 MinorOSVersion
{ get { return (_is64 ? _opt64.MinorOperatingSystemVersion : _opt32.MinorOSVersion); } }
public UInt16 MajorImageVersion
{ get { return (_is64 ? _opt64.MajorImageVersion : _opt32.MajorImageVersion); } }
public UInt16 MinorImageVersion
{ get { return (_is64 ? _opt64.MinorImageVersion : _opt32.MinorImageVersion); } }
public UInt16 MajorSubsystemVersion
{ get { return (_is64 ? _opt64.MajorSubsystemVersion : _opt32.MajorSubsystemVersion); } }
public UInt16 MinorSubsystemVersion
{ get { return (_is64 ? _opt64.MinorSubsystemVersion : _opt32.MinorSubsystemVersion); } }
public UInt32 Reserved
{ get { return (_is64 ? _opt64.Win32VersionValue : _opt32.Reserved); } }
public UInt32 SizeOfImage
{ get { return (_is64 ? _opt64.SizeOfImage : _opt32.SizeOfImage); } }
public UInt32 SizeOfHeaders
{ get { return (_is64 ? _opt64.SizeOfHeaders : _opt32.SizeOfHeaders); } }
public UInt32 Checksum
{ get { return (_is64 ? _opt64.CheckSum : _opt32.Checksum); } }
public UInt16 Subsystem
{ get { return (_is64 ? _opt64.Subsystem : _opt32.Subsystem); } }
public UInt16 DLLCharacteristics
{ get { return (_is64 ? _opt64.DllCharacteristics : _opt32.DLLCharacteristics); } }
public UInt64 SizeOfStackReserve
{ get { return (_is64 ? _opt64.SizeOfStackReserve : _opt32.SizeOfStackReserve); } }
public UInt64 SizeOfStackCommit
{ get { return (_is64 ? _opt64.SizeOfStackCommit : _opt32.SizeOfStackCommit); } }
public UInt64 SizeOfHeapReserve
{ get { return (_is64 ? _opt64.SizeOfHeapReserve : _opt32.SizeOfHeapReserve); } }
public UInt64 SizeOfHeapCommit
{ get { return (_is64 ? _opt64.SizeOfHeapCommit : _opt32.SizeOfHeapCommit); } }
public UInt32 LoaderFlags
{ get { return (_is64 ? _opt64.LoaderFlags : _opt32.LoaderFlags); } }
public UInt32 NumberOfRvaAndSizes
{ get { return (_is64 ? _opt64.NumberOfRvaAndSizes : _opt32.NumberOfRvaAndSizes); } }
public data_directory DataDirectory1_export
{ get { return (_is64 ? _opt64.DataDirectory1_export : _opt32.DataDirectory1_export); } }
public data_directory DataDirectory2_import
{ get { return (_is64 ? _opt64.DataDirectory2_import : _opt32.DataDirectory2_import); } }
public data_directory DataDirectory3
{ get { return (_is64 ? _opt64.DataDirectory3 : _opt32.DataDirectory3); } }
public data_directory DataDirectory4
{ get { return (_is64 ? _opt64.DataDirectory4 : _opt32.DataDirectory4); } }
public data_directory DataDirectory5
{ get { return (_is64 ? _opt64.DataDirectory5 : _opt32.DataDirectory5); } }
public data_directory DataDirectory6
{ get { return (_is64 ? _opt64.DataDirectory6 : _opt32.DataDirectory6); } }
public data_directory DataDirectory7
{ get { return (_is64 ? _opt64.DataDirectory7 : _opt32.DataDirectory7); } }
public data_directory DataDirectory8
{ get { return (_is64 ? _opt64.DataDirectory8 : _opt32.DataDirectory8); } }
public data_directory DataDirectory9
{ get { return (_is64 ? _opt64.DataDirectory9 : _opt32.DataDirectory9); } }
public data_directory DataDirectory10
{ get { return (_is64 ? _opt64.DataDirectory10 : _opt32.DataDirectory10); } }
public data_directory DataDirectory11
{ get { return (_is64 ? _opt64.DataDirectory11 : _opt32.DataDirectory11); } }
public data_directory DataDirectory12
{ get { return (_is64 ? _opt64.DataDirectory12 : _opt32.DataDirectory12); } }
public data_directory DataDirectory13
{ get { return (_is64 ? _opt64.DataDirectory13 : _opt32.DataDirectory13); } }
public data_directory DataDirectory14
{ get { return (_is64 ? _opt64.DataDirectory14 : _opt32.DataDirectory14); } }
public data_directory DataDirectory15
{ get { return (_is64 ? _opt64.DataDirectory15 : _opt32.DataDirectory15); } }
public data_directory DataDirectory16
{ get { return (_is64 ? _opt64.DataDirectory16 : _opt32.DataDirectory16); } }
public PEOptHeader(ref byte[] data, int index, int size)
{
if (size == Marshal.SizeOf(typeof(PEOptHeader64)))
{
// Parse 64 bit version
_is64 = true;
_opt64 = (PEOptHeader64)MemoryFunctions.RawDataToObject(ref data, typeof(PEOptHeader64));
}
else if (size == Marshal.SizeOf(typeof(PEOptHeader32)))
{
// Parse 32 bit version
_is64 = false;
_opt32 = (PEOptHeader32)MemoryFunctions.RawDataToObject(ref data, typeof(PEOptHeader32));
}
else
{
// ERROR
throw new Exception("ERROR: Invalid pe optional header size of " + size.ToString() + ". Expected " + Marshal.SizeOf(typeof(PEOptHeader64)).ToString() + " or " + Marshal.SizeOf(typeof(PEOptHeader32)).ToString() + ".");
}
}
}
public class HeaderReader
{
public uint codeLength;
public uint codeStartAddress;
public COFFHeader coffHeader;
public IMAGE_DOS_HEADER dosHeader;
public Hashtable exports;
public List<IMPORT_FUNCTION> importTable;
public PEOptHeader optHeader;
public bool success;
public UInt64 BaseAddress;
public UInt64 Size;
public static bool IsWin64(System.Diagnostics.Process process)
{
UInt64 address = (UInt64) process.MainModule.BaseAddress;
// Read in the Image Dos Header
byte[] headerData = MemoryFunctions.ReadMemory(process, (IntPtr)address, (uint)Marshal.SizeOf(typeof(IMAGE_DOS_HEADER)));
IMAGE_DOS_HEADER dosHeader = (IMAGE_DOS_HEADER)MemoryFunctions.RawDataToObject(ref headerData, typeof(IMAGE_DOS_HEADER));
// Load the PE Address
UInt64 PE_header = 0;
if (dosHeader.e_magic == 0x5A4D)
{
// Load the PE header address
PE_header = dosHeader.e_lfanew + address;
}
else
{
PE_header = address;
}
// Read in the PE token
byte[] PE_Token = MemoryFunctions.ReadMemory(process, (IntPtr)PE_header, 4);
if (!(PE_Token[0] == 'P' & PE_Token[1] == 'E' & PE_Token[2] == 0 & PE_Token[3] == 0))
{
// Problem, we are not pointing at a correct PE header. Abort.
throw new Exception("Failed to read PE header from block " + address.ToString("X") + " with PE header located at " + PE_header.ToString() + ".");
}
// Input the COFFHeader
byte[] coffHeader_rawData = MemoryFunctions.ReadMemory(process, (IntPtr)(PE_header + 4), (uint)Marshal.SizeOf(typeof(COFFHeader)));
COFFHeader coffHeader = (COFFHeader)MemoryFunctions.RawDataToObject(ref coffHeader_rawData, typeof(COFFHeader));
return ((MACHINE)coffHeader.Machine) == MACHINE.IMAGE_FILE_MACHINE_IA64 || ((MACHINE)coffHeader.Machine) == MACHINE.IMAGE_FILE_MACHINE_AMD64;
}
/// <summary>
/// This checks whether the specified heap is
/// a valid pe header.
/// </summary>
/// <param name="process"></param>
/// <param name="address"></param>
/// <returns></returns>
public static bool isPeHeader(System.Diagnostics.Process process, UInt64 address)
{
// Read in the Image Dos Header
byte[] headerData = MemoryFunctions.ReadMemory(process, (IntPtr)address,
(uint)Marshal.SizeOf(typeof(IMAGE_DOS_HEADER)));
IMAGE_DOS_HEADER dosHeader = (IMAGE_DOS_HEADER)MemoryFunctions.RawDataToObject(ref headerData, typeof(IMAGE_DOS_HEADER));
// Load the PE Address
UInt64 PE_header = 0;
if (dosHeader.e_magic == 0x5A4D)
{
// Load the PE header address
PE_header = dosHeader.e_lfanew + address;
}
else
{
PE_header = address;
return false;
}
if (PE_header <= 0x7FFFFFFF)
{
// Read in the PE token
byte[] PE_Token = MemoryFunctions.ReadMemory(process, (IntPtr)PE_header, 4);
if (!(PE_Token[0] == 'P' & PE_Token[1] == 'E' & PE_Token[2] == 0 & PE_Token[3] == 0))
{
// Problem, we are not pointing at a correct PE header. Abort.
return false;
}
// Input the COFFHeader
byte[] coffHeader_rawData = MemoryFunctions.ReadMemory(process, (IntPtr)(PE_header + 4), (uint)Marshal.SizeOf(typeof(COFFHeader)));
COFFHeader coffHeader = (COFFHeader)MemoryFunctions.RawDataToObject(ref coffHeader_rawData, typeof(COFFHeader));
// Read in the PEOptHeader if it exists
if (coffHeader.SizeOfOptionalHeader != 0 && coffHeader.SizeOfOptionalHeader < 0x1000)
{
// Read in the optHeader
byte[] optHeader_rawData = MemoryFunctions.ReadMemory(process, (IntPtr)(PE_header + 4 + (uint)Marshal.SizeOf(typeof(COFFHeader))), coffHeader.SizeOfOptionalHeader);
PEOptHeader optHeader = new PEOptHeader(ref optHeader_rawData, 0, optHeader_rawData.Length);
// Confirm that it loaded correctly
if ((optHeader.signature & 0xffff) != 0x10b && (optHeader.signature & 0xffff) != 0x20b)
{
return false;
}
if (optHeader.SizeOfCode == 0)
return false;
}
else
{
// No COFFHeader found
return false;
}
return true;
}
else
{
return false;
}
}
/// <summary>
/// This function loads the header and PE header at the
/// specified address in memory.
/// </summary>
/// <param name="process"></param>
/// <param name="address"></param>
public HeaderReader(System.Diagnostics.Process process, UInt64 address)
{
this.BaseAddress = address;
codeStartAddress = 0;
codeLength = 0;
// Read in the Image Dos Header
importTable = new List<IMPORT_FUNCTION>(0);
byte[] headerData = MemoryFunctions.ReadMemory(process, (IntPtr)address, (uint)Marshal.SizeOf(typeof(IMAGE_DOS_HEADER)));
dosHeader = (IMAGE_DOS_HEADER)MemoryFunctions.RawDataToObject(ref headerData, typeof(IMAGE_DOS_HEADER));
// Load the PE Address
UInt64 PE_header = 0;
if (dosHeader.e_magic == 0x5A4D)
{
// Load the PE header address
PE_header = dosHeader.e_lfanew + address;
}
else
{
PE_header = address;
}
// Read in the PE token
byte[] PE_Token = MemoryFunctions.ReadMemory(process, (IntPtr)PE_header, 4);
if (!(PE_Token[0] == 'P' & PE_Token[1] == 'E' & PE_Token[2] == 0 & PE_Token[3] == 0))
{
// Problem, we are not pointing at a correct PE header. Abort.
Console.WriteLine("Failed to read PE header from block " + address.ToString("X") + " with PE header located at " + PE_header.ToString() + ".");
return;
}
// Input the COFFHeader
byte[] coffHeader_rawData = MemoryFunctions.ReadMemory(process, (IntPtr)(PE_header + 4), (uint)Marshal.SizeOf(typeof(COFFHeader)));
coffHeader = (COFFHeader)MemoryFunctions.RawDataToObject(ref coffHeader_rawData, typeof(COFFHeader));
// Read in the PEOptHeader if it exists
if (coffHeader.SizeOfOptionalHeader != 0 && coffHeader.SizeOfOptionalHeader < 0x1000)
{
// Read in the optHeader
byte[] optHeader_rawData = MemoryFunctions.ReadMemory(process, (IntPtr)(PE_header + 4 + (uint)Marshal.SizeOf(typeof(COFFHeader))), coffHeader.SizeOfOptionalHeader);
optHeader = new PEOptHeader(ref optHeader_rawData, 0, coffHeader.SizeOfOptionalHeader);
// Confirm that it loaded correctly
if ((optHeader.signature & 0xffff) != 0x10b && (optHeader.signature & 0xffff) != 0x20b)
{
Console.WriteLine("Failed to read optHeader; Expected signature does not match read in signature of " + optHeader.signature.ToString() + ".");
return;
}
// Load the sections
UInt64 sectionAddress = PE_header + 4 + (UInt64)Marshal.SizeOf(typeof(COFFHeader)) + coffHeader.SizeOfOptionalHeader;
List<section> sections = new List<section>(coffHeader.NumberOfSections);
for (int i = 0; i < coffHeader.NumberOfSections; i++)
{
sections.Add(new section( process, sectionAddress ));
sectionAddress += (uint)Marshal.SizeOf(typeof(IMAGE_SECTION_HEADER));
}
// Extract the names of the functions and corresponding table entries
Int64 importTableAddress = (Int64)optHeader.DataDirectory2_import.VirtualAddress + (Int64)address;
// Read in the first import descriptor structure
/*
byte[] image_import_descriptor_rawData = oMemoryFunctions.readMemory(process, importTableAddress, (uint)Marshal.SizeOf(typeof(image_import_descriptor)));
image_import_descriptor descriptor = (image_import_descriptor)oMemoryFunctions.RawDataToObject(ref image_import_descriptor_rawData, typeof(image_import_descriptor));
List<image_import_by_name> imports = new List<image_import_by_name>(0);
while (descriptor.FirstThunk != 0 || descriptor.OriginalFirstThunk != 0 || descriptor.Name != 0)
{
// Process this descriptor
imports.Add(new image_import_by_name(process, descriptor, address));
// Read next descriptor
image_import_descriptor_rawData = oMemoryFunctions.readMemory(process, importTableAddress + (long)(imports.Count * Marshal.SizeOf(typeof(image_import_descriptor))), (uint)Marshal.SizeOf(typeof(image_import_descriptor)));
descriptor = (image_import_descriptor)oMemoryFunctions.RawDataToObject(ref image_import_descriptor_rawData, typeof(image_import_descriptor));
}
// Now lets process the array of descriptors
foreach (image_import_by_name dllDescriptor in imports)
{
for (int i = 0; i < dllDescriptor.ImportTableAddresses.Count; i++)
{
// Process this function import
IMPORT_FUNCTION newImport = new IMPORT_FUNCTION();
newImport.name = dllDescriptor.Names[i];
newImport.memoryAddress = dllDescriptor.ImportTableAddresses[i];
newImport.targetAddress = oMemoryFunctions.readMemoryDword(process, newImport.memoryAddress);
importTable.Add(newImport);
}
}
*/
// Extract the names of the functions and corresponding table entries
Int64 exportTableAddress = (Int64)optHeader.DataDirectory1_export.VirtualAddress + (Int64)address;
// Read in the first _IMAGE_EXPORT_DIRECTORY structure
byte[] export_directory_rawData = MemoryFunctions.ReadMemory(process, exportTableAddress, (uint)Marshal.SizeOf(typeof(_IMAGE_EXPORT_DIRECTORY)));
_IMAGE_EXPORT_DIRECTORY export_directory = (_IMAGE_EXPORT_DIRECTORY)MemoryFunctions.RawDataToObject(ref export_directory_rawData, typeof(_IMAGE_EXPORT_DIRECTORY));
exports = new Hashtable(20);
UInt64 functionNameArray = (UInt64)export_directory.AddressOfNames + address;
string exportName = MemoryFunctions.ReadString(process, (UInt64)export_directory.Name + address, MemoryFunctions.STRING_TYPE.ascii);
UInt64 functionOrdinalArray = (UInt64)export_directory.AddressOfNameOrdinal + address;
UInt64 functionAddressArray = (UInt64)export_directory.AddressOfFunctions + address;
for (int i = 0; i < export_directory.NumberOfNames; i++)
{
int ordinal_relative = (int)MemoryFunctions.ReadMemoryUShort(process, functionOrdinalArray + (UInt64)i * 2);
int ordinal = ordinal_relative + (int)export_directory.Base;
if (ordinal_relative < export_directory.NumberOfFunctions)
{
// Continue with importing this function
string name = "";
if (i < export_directory.NumberOfNames)
name = MemoryFunctions.ReadString(process, (UInt64)MemoryFunctions.ReadMemoryDword(process, functionNameArray + (UInt64)i * 4) + address, MemoryFunctions.STRING_TYPE.ascii);
else
name = "oridinal" + ordinal.ToString();
// Lookup the function rva now
try
{
UInt64 offset = (UInt64)MemoryFunctions.ReadMemoryDword(process, functionAddressArray + (UInt64)ordinal_relative * 4);
// Check to see if this is a forwarded export
if (offset < optHeader.DataDirectory1_export.VirtualAddress ||
offset > optHeader.DataDirectory1_export.VirtualAddress + optHeader.DataDirectory1_export.Size)
{
// Lookup privilege of heap to confirm it requests execute privileges. We only want to list exported functions, not variables.
foreach (section exp in sections)
{
if (exp.Contains(offset))
{
if (exp.IsExecutable())
{
// Add this exported function
export new_export = new export(offset + address,
name,
ordinal);
exports.Add(name.ToLower(), new_export);
}
break;
}
}
}
else
{
// Forwarded export. Ignore it.
}
}
catch (Exception e)
{
Console.WriteLine("Warning, failed to parse PE header export directory entry for name '" + name + "'.");
}
}
}
}
else
{
// No COFFHeader found
Console.WriteLine("Warning, no COFFHeader found for address " + address.ToString("X") + ".");
return;
}
}
public static bool isPeHeader(System.Diagnostics.Process process, ulong p, MEMORY_PROTECT memoryProtection)
{
// We don't want to set off a page guard exception!
if (memoryProtection.ToString().ToUpper().Contains("GUARD"))
return false;
else
return isPeHeader(process, p);
}
}
[StructLayout(LayoutKind.Sequential)]
public struct IMAGE_EXPORT_DIRECTORY
{
public UInt32 Characteristics;
public UInt32 TimeDateStamp;
public UInt16 MajorVersion;
public UInt16 MinorVersion;
public UInt32 Name;
public UInt32 Base;
public UInt32 NumberOfFunctions;
public UInt32 NumberOfNames;
public UInt32 AddressOfFunctions; // RVA from base of image
public UInt32 AddressOfNames; // RVA from base of image
public UInt32 AddressOfNameOrdinals; // RVA from base of image
}
public struct IMPORT_FUNCTION
{
public UInt64 memoryAddress;
public UInt64 targetAddress;
public string name;
}
public struct IMAGE_DOS_HEADER
{
// DOS .EXE header
public UInt16 e_magic; // Magic number, should be value to value to 0x54AD
public UInt16 e_cblp; // Bytes on last page of file
public UInt16 e_cp; // Pages in file
public UInt16 e_crlc; // Relocations
public UInt16 e_cparhdr; // Size of header in paragraphs
public UInt16 e_minalloc; // Minimum extra paragraphs needed
public UInt16 e_maxalloc; // Maximum extra paragraphs needed
public UInt16 e_ss; // Initial (relative) SS value
public UInt16 e_sp; // Initial SP value
public UInt16 e_csum; // Checksum
public UInt16 e_ip; // Initial IP value
public UInt16 e_cs; // Initial (relative) CS value
public UInt16 e_lfarlc; // File address of relocation table
public UInt16 e_ovno; // Overlay number
public UInt16 e_res_1; // Reserved words
public UInt16 e_res_2; // Reserved words
public UInt16 e_res_3; // Reserved words
public UInt16 e_res_4; // Reserved words
public UInt16 e_oemid; // OEM identifier (for e_oeminfo)
public UInt16 e_oeminfo; // OEM information; e_oemid specific
public UInt16 e_res2_1; // Reserved words
public UInt16 e_res2_2; // Reserved words
public UInt16 e_res2_3; // Reserved words
public UInt16 e_res2_4; // Reserved words
public UInt16 e_res2_5; // Reserved words
public UInt16 e_res2_6; // Reserved words
public UInt16 e_res2_7; // Reserved words
public UInt16 e_res2_8; // Reserved words
public UInt16 e_res2_9; // Reserved words
public UInt16 e_res2_10; // Reserved words
public UInt32 e_lfanew; // Offset of PE header
}
public struct COFFHeader
{
public UInt16 Machine;
public UInt16 NumberOfSections;
public UInt32 TimeDateStamp;
public UInt32 PointerToSymbolTable;
public UInt32 NumberOfSymbols;
public UInt16 SizeOfOptionalHeader;
public UInt16 Characteristics;
}
public enum MACHINE
{
IMAGE_FILE_MACHINE_I386 = 0x014c,
IMAGE_FILE_MACHINE_AMD64 = 0x8664,
IMAGE_FILE_MACHINE_IA64 = 0x0200,
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct PEOptHeader32
{
public UInt16 signature; //decimal number 267.
public byte MajorLinkerVersion;
public byte MinorLinkerVersion;
public UInt32 SizeOfCode;
public UInt32 SizeOfInitializedData;
public UInt32 SizeOfUninitializedData;
public UInt32 AddressOfEntryPoint; //The RVA of the code entry point
public UInt32 BaseOfCode;
public UInt32 BaseOfData;
public UInt32 ImageBase;
public UInt32 SectionAlignment;
public UInt32 FileAlignment;
public UInt16 MajorOSVersion;
public UInt16 MinorOSVersion;
public UInt16 MajorImageVersion;
public UInt16 MinorImageVersion;
public UInt16 MajorSubsystemVersion;
public UInt16 MinorSubsystemVersion;
public UInt32 Reserved;
public UInt32 SizeOfImage;
public UInt32 SizeOfHeaders;
public UInt32 Checksum;
public UInt16 Subsystem;
public UInt16 DLLCharacteristics;
public UInt32 SizeOfStackReserve;
public UInt32 SizeOfStackCommit;
public UInt32 SizeOfHeapReserve;
public UInt32 SizeOfHeapCommit;
public UInt32 LoaderFlags;
public UInt32 NumberOfRvaAndSizes;
public data_directory DataDirectory1_export;
//Can have any number of elements, matching the number in NumberOfRvaAndSizes.
public data_directory DataDirectory2_import;
public data_directory DataDirectory3;
public data_directory DataDirectory4;
public data_directory DataDirectory5;
public data_directory DataDirectory6;
public data_directory DataDirectory7;
public data_directory DataDirectory8;
public data_directory DataDirectory9;
public data_directory DataDirectory10;
public data_directory DataDirectory11;
public data_directory DataDirectory12;
public data_directory DataDirectory13;
public data_directory DataDirectory14;
public data_directory DataDirectory15;
public data_directory DataDirectory16;
}
[StructLayout(LayoutKind.Explicit)]
public struct PEOptHeader64
{
[FieldOffset(0)]
public UInt32 Magic;
[FieldOffset(2)]
public byte MajorLinkerVersion;
[FieldOffset(3)]
public byte MinorLinkerVersion;
[FieldOffset(4)]
public UInt32 SizeOfCode;
[FieldOffset(8)]
public UInt32 SizeOfInitializedData;
[FieldOffset(12)]
public UInt32 SizeOfUninitializedData;
[FieldOffset(16)]
public UInt32 AddressOfEntryPoint;
[FieldOffset(20)]
public UInt32 BaseOfCode;
[FieldOffset(24)]
public UInt64 ImageBase;
[FieldOffset(32)]
public UInt32 SectionAlignment;
[FieldOffset(36)]
public UInt32 FileAlignment;
[FieldOffset(40)]
public UInt16 MajorOperatingSystemVersion;
[FieldOffset(42)]
public UInt16 MinorOperatingSystemVersion;
[FieldOffset(44)]
public UInt16 MajorImageVersion;
[FieldOffset(46)]
public UInt16 MinorImageVersion;
[FieldOffset(48)]
public UInt16 MajorSubsystemVersion;
[FieldOffset(50)]
public UInt16 MinorSubsystemVersion;
[FieldOffset(52)]
public UInt32 Win32VersionValue;
[FieldOffset(56)]
public UInt32 SizeOfImage;
[FieldOffset(60)]
public UInt32 SizeOfHeaders;
[FieldOffset(64)]
public UInt32 CheckSum;
[FieldOffset(68)]
public UInt16 Subsystem;
[FieldOffset(70)]
public UInt16 DllCharacteristics;
[FieldOffset(72)]
public UInt64 SizeOfStackReserve;
[FieldOffset(80)]
public UInt64 SizeOfStackCommit;
[FieldOffset(88)]
public UInt64 SizeOfHeapReserve;
[FieldOffset(96)]
public UInt64 SizeOfHeapCommit;
[FieldOffset(104)]
public UInt32 LoaderFlags;
[FieldOffset(108)]
public UInt32 NumberOfRvaAndSizes;
[FieldOffset(112)]
public data_directory DataDirectory1_export;
[FieldOffset(120)]
public data_directory DataDirectory2_import;
[FieldOffset(128)]
public data_directory DataDirectory3;
[FieldOffset(136)]
public data_directory DataDirectory4;
[FieldOffset(144)]
public data_directory DataDirectory5;
[FieldOffset(152)]
public data_directory DataDirectory6;
[FieldOffset(160)]
public data_directory DataDirectory7;
[FieldOffset(168)]
public data_directory DataDirectory8;
[FieldOffset(176)]
public data_directory DataDirectory9;
[FieldOffset(184)]
public data_directory DataDirectory10;
[FieldOffset(192)]
public data_directory DataDirectory11;
[FieldOffset(200)]
public data_directory DataDirectory12;
[FieldOffset(208)]
public data_directory DataDirectory13;
[FieldOffset(216)]
public data_directory DataDirectory14;
[FieldOffset(224)]
public data_directory DataDirectory15;
[FieldOffset(232)]
public data_directory DataDirectory16;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct data_directory
{
public UInt32 VirtualAddress;
public UInt32 Size;
}
public struct image_import_descriptor
{
public int OriginalFirstThunk;
public int TimeDateStamp;
public int ForwarderChain;
public int Name;
public int FirstThunk;
}
public struct _IMAGE_EXPORT_DIRECTORY
{
public UInt32 Characteristics;
public UInt32 TimeDateStamp;
public UInt16 MajorVersion;
public UInt16 MinorVersion;
public UInt32 Name;
public UInt32 Base;
public UInt32 NumberOfFunctions;
public UInt32 NumberOfNames;
public UInt32 AddressOfFunctions;
public UInt32 AddressOfNames;
public UInt32 AddressOfNameOrdinal;
}
[StructLayout(LayoutKind.Explicit)]
public struct IMAGE_SECTION_HEADER
{
[FieldOffset(0)]
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)]
public char[] Name;
[FieldOffset(8)]
public UInt32 VirtualSize;
[FieldOffset(12)]
public UInt32 VirtualAddress;
[FieldOffset(16)]
public UInt32 SizeOfRawData;
[FieldOffset(20)]
public UInt32 PointerToRawData;
[FieldOffset(24)]
public UInt32 PointerToRelocations;
[FieldOffset(28)]
public UInt32 PointerToLinenumbers;
[FieldOffset(32)]
public UInt16 NumberOfRelocations;
[FieldOffset(34)]
public UInt16 NumberOfLinenumbers;
[FieldOffset(36)]
public DataSectionFlags Characteristics;
public string Section
{
get { return new string(Name); }
}
}
[Flags]
public enum DataSectionFlags : uint
{
/// <summary>
/// Reserved for future use.
/// </summary>
TypeReg = 0x00000000,
/// <summary>
/// Reserved for future use.
/// </summary>
TypeDsect = 0x00000001,
/// <summary>
/// Reserved for future use.
/// </summary>
TypeNoLoad = 0x00000002,
/// <summary>
/// Reserved for future use.
/// </summary>
TypeGroup = 0x00000004,
/// <summary>
/// The section should not be padded to the next boundary. This flag is obsolete and is replaced by IMAGE_SCN_ALIGN_1BYTES. This is valid only for object files.
/// </summary>
TypeNoPadded = 0x00000008,
/// <summary>
/// Reserved for future use.
/// </summary>
TypeCopy = 0x00000010,
/// <summary>
/// The section contains executable code.
/// </summary>
ContentCode = 0x00000020,
/// <summary>
/// The section contains initialized data.
/// </summary>
ContentInitializedData = 0x00000040,
/// <summary>
/// The section contains uninitialized data.
/// </summary>
ContentUninitializedData = 0x00000080,
/// <summary>
/// Reserved for future use.
/// </summary>
LinkOther = 0x00000100,
/// <summary>
/// The section contains comments or other information. The .drectve section has this type. This is valid for object files only.
/// </summary>
LinkInfo = 0x00000200,
/// <summary>
/// Reserved for future use.
/// </summary>
TypeOver = 0x00000400,
/// <summary>
/// The section will not become part of the image. This is valid only for object files.
/// </summary>
LinkRemove = 0x00000800,
/// <summary>
/// The section contains COMDAT data. For more information, see section 5.5.6, COMDAT Sections (Object Only). This is valid only for object files.
/// </summary>
LinkComDat = 0x00001000,
/// <summary>
/// Reset speculative exceptions handling bits in the TLB entries for this section.
/// </summary>
NoDeferSpecExceptions = 0x00004000,
/// <summary>
/// The section contains data referenced through the global pointer (GP).
/// </summary>
RelativeGP = 0x00008000,
/// <summary>
/// Reserved for future use.
/// </summary>
MemPurgeable = 0x00020000,
/// <summary>
/// Reserved for future use.
/// </summary>
Memory16Bit = 0x00020000,
/// <summary>
/// Reserved for future use.
/// </summary>
MemoryLocked = 0x00040000,
/// <summary>
/// Reserved for future use.
/// </summary>
MemoryPreload = 0x00080000,
/// <summary>
/// Align data on a 1-byte boundary. Valid only for object files.
/// </summary>
Align1Bytes = 0x00100000,
/// <summary>
/// Align data on a 2-byte boundary. Valid only for object files.
/// </summary>
Align2Bytes = 0x00200000,
/// <summary>
/// Align data on a 4-byte boundary. Valid only for object files.
/// </summary>
Align4Bytes = 0x00300000,
/// <summary>
/// Align data on an 8-byte boundary. Valid only for object files.
/// </summary>
Align8Bytes = 0x00400000,
/// <summary>
/// Align data on a 16-byte boundary. Valid only for object files.
/// </summary>
Align16Bytes = 0x00500000,
/// <summary>
/// Align data on a 32-byte boundary. Valid only for object files.
/// </summary>
Align32Bytes = 0x00600000,
/// <summary>
/// Align data on a 64-byte boundary. Valid only for object files.
/// </summary>
Align64Bytes = 0x00700000,
/// <summary>
/// Align data on a 128-byte boundary. Valid only for object files.
/// </summary>
Align128Bytes = 0x00800000,
/// <summary>
/// Align data on a 256-byte boundary. Valid only for object files.
/// </summary>
Align256Bytes = 0x00900000,
/// <summary>
/// Align data on a 512-byte boundary. Valid only for object files.
/// </summary>
Align512Bytes = 0x00A00000,
/// <summary>
/// Align data on a 1024-byte boundary. Valid only for object files.
/// </summary>
Align1024Bytes = 0x00B00000,
/// <summary>
/// Align data on a 2048-byte boundary. Valid only for object files.
/// </summary>
Align2048Bytes = 0x00C00000,
/// <summary>
/// Align data on a 4096-byte boundary. Valid only for object files.
/// </summary>
Align4096Bytes = 0x00D00000,
/// <summary>
/// Align data on an 8192-byte boundary. Valid only for object files.
/// </summary>
Align8192Bytes = 0x00E00000,
/// <summary>
/// The section contains extended relocations.
/// </summary>
LinkExtendedRelocationOverflow = 0x01000000,
/// <summary>
/// The section can be discarded as needed.
/// </summary>
MemoryDiscardable = 0x02000000,
/// <summary>
/// The section cannot be cached.
/// </summary>
MemoryNotCached = 0x04000000,
/// <summary>
/// The section is not pageable.
/// </summary>
MemoryNotPaged = 0x08000000,
/// <summary>
/// The section can be shared in memory.
/// </summary>
MemoryShared = 0x10000000,
/// <summary>
/// The section can be executed as code.
/// </summary>
MemoryExecute = 0x20000000,
/// <summary>
/// The section can be read.
/// </summary>
MemoryRead = 0x40000000,
/// <summary>
/// The section can be written to.
/// </summary>
MemoryWrite = 0x80000000
}
public class export
{
public UInt64 Address;
public string Name;
public int Ordinal;
public export(UInt64 address, string name, int ordinal)
{
this.Address = address;
this.Ordinal = ordinal;
if (name.Trim() == "")
this.Name = "Ordinal " + ordinal;
else
this.Name = name;
}
}
public class section
{
private IMAGE_SECTION_HEADER _sectionHeader;
public section(System.Diagnostics.Process process, UInt64 address)
{
// Parse the section struct
byte[] headerData = MemoryFunctions.ReadMemory(process, (IntPtr)address, (uint)Marshal.SizeOf(typeof(IMAGE_SECTION_HEADER)));
_sectionHeader = (IMAGE_SECTION_HEADER)MemoryFunctions.RawDataToObject(ref headerData, typeof(IMAGE_SECTION_HEADER));
}
public string Section
{
get { return _sectionHeader.Section; }
}
public DataSectionFlags Characteristics
{
get { return _sectionHeader.Characteristics; }
}
public bool Contains(UInt64 rva)
{
return rva >= _sectionHeader.VirtualAddress && rva - _sectionHeader.VirtualAddress < _sectionHeader.VirtualSize;
}
public bool IsExecutable()
{
return ( ((uint) _sectionHeader.Characteristics) & (uint) DataSectionFlags.MemoryExecute ) > 0;
}
}
public class image_import_by_name
{
public List<uint> AddressOfData;
public List<string> Names;
public List<UInt64> ImportTableAddresses;
public image_import_by_name(System.Diagnostics.Process process, image_import_descriptor descriptor, UInt64 baseAddress)
{
AddressOfData = new List<uint>(0);
ImportTableAddresses = new List<UInt64>(0);
Names = new List<string>(0);
// Read the AddressOfData array in
if (descriptor.OriginalFirstThunk != 0 && descriptor.FirstThunk != 0)
{
// Read in the descriptor table with names
int i = 0;
uint newAddress = MemoryFunctions.ReadMemoryDword(process,
(ulong)descriptor.OriginalFirstThunk +
(ulong)baseAddress + (ulong)i * 4);
while (newAddress != 0)
{
// Add this new address
AddressOfData.Add(newAddress & 0x7fffffff);
// Add the string corresponding to this new function
if ((newAddress & 0x80000000) > 0)
{
// Export by ordinal
newAddress = newAddress & 0x7fffffff;
Names.Add("ordinal 0x" +
MemoryFunctions.ReadMemoryUShort(process, (UInt64)newAddress + baseAddress).
ToString("X"));
}
else if (newAddress > 0)
{
// Export by name
Names.Add(MemoryFunctions.ReadMemoryString(process, (UInt64)newAddress + baseAddress + 2, 256));
}
else
{
// There is no name or ordinal given, probably obfuscated?
Names.Add("obfuscated?");
}
// Add the pe table address corresponding to this function
ImportTableAddresses.Add((UInt64)descriptor.FirstThunk + (UInt64)baseAddress + (UInt64)i * 4);
// Read in the next value
i++;
newAddress = MemoryFunctions.ReadMemoryDword(process,
(ulong)descriptor.OriginalFirstThunk +
(ulong)baseAddress + (ulong)i * 4);
}
}
else
{
// Read in the descriptor table without names
int i = 0;
ulong addressThunk = (ulong)(descriptor.OriginalFirstThunk != 0
? descriptor.OriginalFirstThunk
: descriptor.FirstThunk);
if (addressThunk == 0)
return; // We have no imports that we can read in.
uint newAddress = MemoryFunctions.ReadMemoryDword(process,
addressThunk +
(ulong)baseAddress + (ulong)i * 4);
while (newAddress != 0)
{
// Add this new address
AddressOfData.Add(newAddress & 0x7fffffff);
Names.Add("");
ImportTableAddresses.Add((UInt64)addressThunk + (UInt64)baseAddress + (UInt64)i * 4);
// Read in the next value
i++;
newAddress = MemoryFunctions.ReadMemoryDword(process,
addressThunk +
(ulong)baseAddress + (ulong)i * 4);
}
}
}
}
}
| |
using HTTPlease;
using System;
using System.Net.Http;
using System.Threading.Tasks;
using System.Collections.Generic;
using System.Threading;
using System.Net;
namespace DaaSDemo.KubeClient.ResourceClients
{
using Models;
/// <summary>
/// A client for the Kubernetes Deployments (v1beta2) API.
/// </summary>
public class DeploymentClientV1Beta1
: KubeResourceClient
{
/// <summary>
/// Create a new <see cref="DeploymentClientV1Beta1"/>.
/// </summary>
/// <param name="client">
/// The Kubernetes API client.
/// </param>
public DeploymentClientV1Beta1(KubeApiClient client)
: base(client)
{
}
/// <summary>
/// Get all Deployments in the specified namespace, optionally matching a label selector.
/// </summary>
/// <param name="labelSelector">
/// An optional Kubernetes label selector expression used to filter the Deployments.
/// </param>
/// <param name="kubeNamespace">
/// The target Kubernetes namespace (defaults to <see cref="KubeApiClient.DefaultNamespace"/>).
/// </param>
/// <param name="cancellationToken">
/// An optional <see cref="CancellationToken"/> that can be used to cancel the request.
/// </param>
/// <returns>
/// The Deployments, as a list of <see cref="DeploymentV1Beta1"/>s.
/// </returns>
public async Task<List<DeploymentV1Beta1>> List(string labelSelector = null, string kubeNamespace = null, CancellationToken cancellationToken = default)
{
DeploymentListV1Beta1 matchingDeployments =
await Http.GetAsync(
Requests.Collection.WithTemplateParameters(new
{
Namespace = kubeNamespace ?? Client.DefaultNamespace,
LabelSelector = labelSelector
}),
cancellationToken: cancellationToken
)
.ReadContentAsAsync<DeploymentListV1Beta1, StatusV1>();
return matchingDeployments.Items;
}
/// <summary>
/// Watch for events relating to Deployments.
/// </summary>
/// <param name="labelSelector">
/// An optional Kubernetes label selector expression used to filter the Deployments.
/// </param>
/// <param name="kubeNamespace">
/// The target Kubernetes namespace (defaults to <see cref="KubeApiClient.DefaultNamespace"/>).
/// </param>
/// <returns>
/// An <see cref="IObservable{T}"/> representing the event stream.
/// </returns>
public IObservable<ResourceEventV1<DeploymentV1Beta1>> WatchAll(string labelSelector = null, string kubeNamespace = null)
{
return ObserveEvents<DeploymentV1Beta1>(
Requests.Collection.WithTemplateParameters(new
{
Namespace = kubeNamespace ?? Client.DefaultNamespace,
LabelSelector = labelSelector,
Watch = true
})
);
}
/// <summary>
/// Get the Deployment with the specified name.
/// </summary>
/// <param name="name">
/// The name of the Deployment to retrieve.
/// </param>
/// <param name="kubeNamespace">
/// The target Kubernetes namespace (defaults to <see cref="KubeApiClient.DefaultNamespace"/>).
/// </param>
/// <param name="cancellationToken">
/// An optional <see cref="CancellationToken"/> that can be used to cancel the request.
/// </param>
/// <returns>
/// A <see cref="DeploymentV1Beta1"/> representing the current state for the Deployment, or <c>null</c> if no Deployment was found with the specified name and namespace.
/// </returns>
public async Task<DeploymentV1Beta1> Get(string name, string kubeNamespace = null, CancellationToken cancellationToken = default)
{
if (String.IsNullOrWhiteSpace(name))
throw new ArgumentException("Argument cannot be null, empty, or entirely composed of whitespace: 'name'.", nameof(name));
return await GetSingleResource<DeploymentV1Beta1>(
Requests.ByName.WithTemplateParameters(new
{
Name = name,
Namespace = kubeNamespace ?? Client.DefaultNamespace
}),
cancellationToken: cancellationToken
);
}
/// <summary>
/// Request creation of a <see cref="Deployment"/>.
/// </summary>
/// <param name="newDeployment">
/// A <see cref="DeploymentV1Beta1"/> representing the Deployment to create.
/// </param>
/// <param name="cancellationToken">
/// An optional <see cref="CancellationToken"/> that can be used to cancel the request.
/// </param>
/// <returns>
/// A <see cref="DeploymentV1Beta1"/> representing the current state for the newly-created Deployment.
/// </returns>
public async Task<DeploymentV1Beta1> Create(DeploymentV1Beta1 newDeployment, CancellationToken cancellationToken = default)
{
if (newDeployment == null)
throw new ArgumentNullException(nameof(newDeployment));
return await Http
.PostAsJsonAsync(
Requests.Collection.WithTemplateParameters(new
{
Namespace = newDeployment?.Metadata?.Namespace ?? Client.DefaultNamespace
}),
postBody: newDeployment,
cancellationToken: cancellationToken
)
.ReadContentAsAsync<DeploymentV1Beta1, StatusV1>();
}
/// <summary>
/// Request update (PATCH) of a <see cref="Deployment"/>.
/// </summary>
/// <param name="deployment">
/// A <see cref="DeploymentV1Beta1"/> representing the Deployment to update.
/// </param>
/// <param name="cancellationToken">
/// An optional <see cref="CancellationToken"/> that can be used to cancel the request.
/// </param>
/// <returns>
/// A <see cref="DeploymentV1Beta1"/> representing the current state for the newly-created Deployment.
/// </returns>
public async Task<DeploymentV1Beta1> Update(DeploymentV1Beta1 deployment, CancellationToken cancellationToken = default)
{
if (deployment == null)
throw new ArgumentNullException(nameof(deployment));
if (String.IsNullOrWhiteSpace(deployment.Metadata?.Name))
throw new ArgumentException("Cannot update Deployment without a value for its Metadata.Name property.", nameof(deployment));
if (String.IsNullOrWhiteSpace(deployment.Metadata?.Namespace))
throw new ArgumentException("Cannot update Deployment without a value for its Metadata.Namespace property.", nameof(deployment));
return await Http
.PatchAsync(
Requests.ByName.WithTemplateParameters(new
{
Name = deployment.Metadata.Name,
Namespace = deployment.Metadata.Namespace
}),
patchBody: deployment,
mediaType: PatchMediaType,
cancellationToken: cancellationToken
)
.ReadContentAsAsync<DeploymentV1Beta1, StatusV1>();
}
/// <summary>
/// Request deletion of the specified Deployment.
/// </summary>
/// <param name="name">
/// The name of the Deployment to delete.
/// </param>
/// <param name="kubeNamespace">
/// The target Kubernetes namespace (defaults to <see cref="KubeApiClient.DefaultNamespace"/>).
/// </param>
/// <param name="propagationPolicy">
/// A <see cref="DeletePropagationPolicy"/> indicating how child resources should be deleted (if at all).
/// </param>
/// <param name="cancellationToken">
/// An optional <see cref="CancellationToken"/> that can be used to cancel the request.
/// </param>
/// <returns>
/// An <see cref="StatusV1"/> indicating the result of the request.
/// </returns>
public async Task<StatusV1> Delete(string name, string kubeNamespace = null, DeletePropagationPolicy propagationPolicy = DeletePropagationPolicy.Background, CancellationToken cancellationToken = default)
{
return
await Http.DeleteAsJsonAsync(
Requests.ByName.WithTemplateParameters(new
{
Name = name,
Namespace = kubeNamespace ?? Client.DefaultNamespace
}),
deleteBody: new
{
apiVersion = "v1",
kind = "DeleteOptions",
propagationPolicy = propagationPolicy
},
cancellationToken: cancellationToken
)
.ReadContentAsAsync<StatusV1, StatusV1>(HttpStatusCode.OK, HttpStatusCode.NotFound);
}
/// <summary>
/// Request templates for the Deployment (v1beta2) API.
/// </summary>
static class Requests
{
/// <summary>
/// A collection-level Deployment (v1beta2) request.
/// </summary>
public static readonly HttpRequest Collection = HttpRequest.Factory.Json("apis/apps/v1beta1/namespaces/{Namespace}/deployments?labelSelector={LabelSelector?}&watch={Watch?}", SerializerSettings);
/// <summary>
/// A get-by-name Deployment (v1beta2) request.
/// </summary>
public static readonly HttpRequest ByName = HttpRequest.Factory.Json("apis/apps/v1beta1/namespaces/{Namespace}/deployments/{Name}", SerializerSettings);
}
}
}
| |
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Windows.Forms;
using L10NSharp;
using SIL.Keyboarding;
using SIL.PlatformUtilities;
using SIL.Windows.Forms.Keyboarding;
namespace SIL.Windows.Forms.WritingSystems
{
public partial class WSKeyboardControl : UserControl
{
public class KeyboardDefinitionAdapter
{
private IKeyboardDefinition _descriptor;
public KeyboardDefinitionAdapter(IKeyboardDefinition descriptor)
{
_descriptor = descriptor;
}
public IKeyboardDefinition KeyboardDefinition
{
get { return _descriptor; }
}
public override string ToString()
{
return _descriptor.LocalizedName;
}
}
private WritingSystemSetupModel _model;
private string _defaultFontName;
private float _defaultFontSize;
public WSKeyboardControl()
{
InitializeComponent();
if (KeyboardController.IsInitialized)
KeyboardController.RegisterControl(_testArea);
_defaultFontSize = _testArea.Font.SizeInPoints;
_defaultFontName = _testArea.Font.Name;
_possibleKeyboardsList.ShowItemToolTips = true;
// Skip this link test when this control is being displayed in the windows forms designer
if (LicenseManager.UsageMode != LicenseUsageMode.Designtime)
{
_keymanConfigurationLink.Visible &= KeyboardController.HasSecondaryKeyboardSetupApplication;
}
if (Platform.IsWindows)
return;
// Keyman is not supported, setup link should not say "Windows".
_keyboardSettingsLink.Text =
L10NSharp.LocalizationManager.GetString("WSKeyboardControl.SetupKeyboards",
"Set up keyboards");
// The sequence of Events in Mono dictate using GotFocus instead of Enter as the point
// when we want to assign keyboard and font to this textbox. (For some reason, using
// Enter works fine for the WSFontControl._testArea textbox control.)
this._testArea.Enter -= new System.EventHandler(this._testArea_Enter);
this._testArea.GotFocus += new System.EventHandler(this._testArea_Enter);
}
private bool _hookedToForm;
/// <summary>
/// This seems to be the best available hook to connect this control to the form's Activated event.
/// The control can't be visible until it is on a form!
/// It is tempting to unhook it when it is no longer visible, but unfortunately OnVisibleChanged
/// apparently doesn't work like that. According to http://memprofiler.com/articles/thecontrolvisiblechangedevent.aspx,
/// it is fired when visibility is gained because parent visibility changed, but not when visibility
/// is LOST because parent visibility changed.
/// </summary>
/// <param name="e"></param>
protected override void OnVisibleChanged(EventArgs e)
{
base.OnVisibleChanged(e);
if (_hookedToForm || !(TopLevelControl is Form))
return;
_hookedToForm = true;
((Form) TopLevelControl).Activated += WSKeyboardControl_Activated;
}
// When the top-level form we are part of is activated, update our keyboard list,
// in case the user changed things using the control panel.
private void WSKeyboardControl_Activated(object sender, EventArgs e)
{
Keyboard.Controller.UpdateAvailableKeyboards(); // Enhance JohnT: would it be cleaner to have a Model method to do this?
PopulateKeyboardList();
UpdateFromModel(); // to restore selection.
}
public void BindToModel(WritingSystemSetupModel model)
{
if (_model != null)
{
_model.SelectionChanged -= ModelSelectionChanged;
_model.CurrentItemUpdated -= ModelCurrentItemUpdated;
}
_model = model;
Enabled = false;
if (_model != null)
{
_model.SelectionChanged += ModelSelectionChanged;
_model.CurrentItemUpdated += ModelCurrentItemUpdated;
PopulateKeyboardList();
UpdateFromModel();
}
Disposed += OnDisposed;
}
private void OnDisposed(object sender, EventArgs e)
{
if (_model != null)
_model.SelectionChanged -= ModelSelectionChanged;
}
protected override void OnSizeChanged(EventArgs e)
{
base.OnSizeChanged(e);
// single column occupies whole list, leaving room for vertical scroll so we don't get a spurious
// horizontal one.
_keyboards.Width = _possibleKeyboardsList.ClientSize.Width - SystemInformation.VerticalScrollBarWidth;
}
private Color _unavailableColor = Color.FromKnownColor(KnownColor.DimGray);
private Color _labelColor = Color.LightCyan;
private ListViewItem MakeLabelItem(string text)
{
var label = new ListViewItem(text);
label.BackColor = _labelColor;
label.Font = new Font(_possibleKeyboardsList.Font, FontStyle.Bold);
return label;
}
private bool IsItemLabel(ListViewItem item)
{
return item.BackColor == _labelColor;
}
private void PopulateKeyboardList()
{
if (_model == null || !_model.HasCurrentSelection)
{
_possibleKeyboardsList.Items.Clear();
return;
}
_possibleKeyboardsList.BeginUpdate();
Rectangle originalBounds = _possibleKeyboardsList.Bounds;
_possibleKeyboardsList.Items.Clear();
_possibleKeyboardsList.Items.Add(MakeLabelItem(
LocalizationManager.GetString("WSKeyboardControl.KeyboardsPreviouslyUsed", "Previously used keyboards")));
var unavailableFont = new Font(_possibleKeyboardsList.Font, FontStyle.Italic);
foreach (var keyboard in _model.KnownKeyboards)
{
var adapter = new KeyboardDefinitionAdapter(keyboard);
var item = new ListViewItem(adapter.ToString());
item.Tag = adapter;
if (!keyboard.IsAvailable)
{
item.Font = unavailableFont;
item.ForeColor = _unavailableColor;
}
item.ToolTipText = adapter.ToString();
_possibleKeyboardsList.Items.Add(item);
if (keyboard == _model.CurrentKeyboard)
item.Selected = true;
}
_possibleKeyboardsList.Items.Add(MakeLabelItem(
LocalizationManager.GetString("WSKeyboardControl.KeyboardsAvailable", "Available keyboards")));
foreach (var keyboard in _model.OtherAvailableKeyboards)
{
var adapter = new KeyboardDefinitionAdapter(keyboard);
var item = new ListViewItem(adapter.ToString());
item.Tag = adapter;
item.ToolTipText = adapter.ToString();
_possibleKeyboardsList.Items.Add(item);
}
_possibleKeyboardsList.Bounds = originalBounds;
_possibleKeyboardsList.EndUpdate();
}
private void ModelCurrentItemUpdated(object sender, EventArgs e)
{
UpdateFromModel();
}
private void ModelSelectionChanged(object sender, EventArgs e)
{
PopulateKeyboardList(); // different writing system may have different current ones.
UpdateFromModel();
}
private string _selectKeyboardPattern;
private void UpdateFromModel()
{
if (_model == null || !_model.HasCurrentSelection)
{
Enabled = false;
_selectKeyboardLabel.Visible = false;
return;
}
Enabled = true;
_selectKeyboardLabel.Visible = true;
if (_selectKeyboardPattern == null)
_selectKeyboardPattern = _selectKeyboardLabel.Text;
_selectKeyboardLabel.Text = string.Format(_selectKeyboardPattern, _model.CurrentDefinition.ListLabel);
KeyboardDefinitionAdapter currentKeyboardDefinition = null;
if (_possibleKeyboardsList.SelectedItems.Count > 0)
currentKeyboardDefinition = _possibleKeyboardsList.SelectedItems[0].Tag as KeyboardDefinitionAdapter;
if (_model.CurrentKeyboard != null &&
(currentKeyboardDefinition == null || _model.CurrentKeyboard != currentKeyboardDefinition.KeyboardDefinition))
{
foreach (ListViewItem item in _possibleKeyboardsList.Items)
{
var keyboard = item.Tag as KeyboardDefinitionAdapter;
if (keyboard != null && keyboard.KeyboardDefinition == _model.CurrentKeyboard)
{
//_possibleKeyboardsList.SelectedItems.Clear();
// We're updating the display from the model, so we don't need to run the code that
// updates the model from the display.
_possibleKeyboardsList.SelectedIndexChanged -= _possibleKeyboardsList_SelectedIndexChanged;
item.Selected = true; // single select is true, so should clear any old one.
_possibleKeyboardsList.SelectedIndexChanged += _possibleKeyboardsList_SelectedIndexChanged;
break;
}
}
}
SetTestAreaFont();
}
private void SetTestAreaFont()
{
float fontSize = _model.CurrentDefaultFontSize;
if (fontSize <= 0 || float.IsNaN(fontSize) || float.IsInfinity(fontSize))
{
fontSize = _defaultFontSize;
}
string fontName = _model.CurrentDefaultFontName;
if (string.IsNullOrEmpty(fontName))
{
fontName = _defaultFontName;
}
_testArea.Font = new Font(fontName, fontSize);
_testArea.RightToLeft = _model.CurrentRightToLeftScript ? RightToLeft.Yes : RightToLeft.No;
}
protected override void OnGotFocus(EventArgs e)
{
base.OnGotFocus(e);
_possibleKeyboardsList.Focus(); // allows the user to use arrows to select, also makes selection more conspicuous
}
private int _previousTime;
private void _possibleKeyboardsList_SelectedIndexChanged(object sender, EventArgs e)
{
if (_possibleKeyboardsList.SelectedItems.Count != 0)
{
var item = _possibleKeyboardsList.SelectedItems[0];
if (IsItemLabel(item) || item.ForeColor == _unavailableColor)
{
item.Selected = false;
UpdateFromModel(); // back to whatever the model has
return;
}
}
if (Environment.TickCount - _previousTime < 1000 && _possibleKeyboardsList.SelectedItems.Count == 0)
{
_previousTime = Environment.TickCount;
}
_previousTime = Environment.TickCount;
if (_model == null)
{
return;
}
if (_possibleKeyboardsList.SelectedItems.Count != 0)
{
var currentKeyboard = (KeyboardDefinitionAdapter) _possibleKeyboardsList.SelectedItems[0].Tag;
if (_model.CurrentKeyboard == null ||
_model.CurrentKeyboard != currentKeyboard.KeyboardDefinition)
{
_model.CurrentKeyboard = currentKeyboard.KeyboardDefinition;
}
}
}
private void _testArea_Enter(object sender, EventArgs e)
{
if (_model == null)
{
return;
}
_model.ActivateCurrentKeyboard();
SetTestAreaFont();
}
private void _testArea_Leave(object sender, EventArgs e)
{
if (_model == null)
{
return;
}
Keyboard.Controller.ActivateDefaultKeyboard();
}
private void _windowsKeyboardSettingsLink_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
var program = KeyboardController.GetKeyboardSetupApplication();
if (program == null)
{
MessageBox.Show("Cannot open keyboard setup program", "Information");
return;
}
program.Invoke();
}
private void _keymanConfigurationLink_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
var program = KeyboardController.GetSecondaryKeyboardSetupApplication();
if (program == null)
{
MessageBox.Show(LocalizationManager.GetString("WSKeyboardControl.KeymanNotInstalled",
"Keyman 5.0 or later is not Installed."));
return;
}
program.Invoke();
}
}
}
| |
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
#endif
using System.Collections.Generic;
namespace UMA.PoseTools
{
[CustomEditor(typeof(UMABonePose),true)]
public class UMABonePoseEditor : Editor
{
// HACK for testing
public UMAData sourceUMA;
UMABonePose targetPose = null;
public UMABonePoseEditorContext context = null;
const int BAD_INDEX = -1;
public bool haveValidContext
{
get { return ((context != null) && (context.activeUMA != null)); }
}
public bool haveEditTarget
{
get { return (editBoneIndex != BAD_INDEX); }
}
private float previewWeight = 1.0f;
public bool dynamicDNAConverterMode = false;
const float addRemovePadding = 20f;
const float buttonVerticalOffset = 4f; // Can't be calculated because button layout is weird.
private int drawBoneIndex = BAD_INDEX;
private int editBoneIndex = BAD_INDEX;
private int activeBoneIndex = BAD_INDEX;
private int mirrorBoneIndex = BAD_INDEX;
private bool mirrorActive = true;
// private bool inspectorLocked = false;
private bool doBoneAdd = false;
private bool doBoneRemove = false;
private int removeBoneIndex = BAD_INDEX;
private int addBoneIndex = BAD_INDEX;
const int minBoneNameLength = 4;
private string addBoneName = "";
private static Texture warningIcon;
// private static Texture trashIcon;
private static GUIContent positionGUIContent = new GUIContent(
"Position",
"The change in this bone's local position when pose is applied.");
private static GUIContent rotationGUIContent = new GUIContent(
"Rotation",
"The change in this bone's local rotation when pose is applied.");
private static GUIContent scaleGUIContent = new GUIContent(
"Scale",
"The change in this bone's local scale when pose is applied.");
private static GUIContent scaleWarningGUIContent = new GUIContent(
"WARNING: Non-uniform scale.",
"Non-uniform scaling can cause errors on bones that are animated. Use only with adjustment bones.");
private static GUIContent removeBoneGUIContent = new GUIContent(
"Remove Bone",
"Remove the selected bone from the pose.");
private static GUIContent addBoneGUIContent = new GUIContent(
"Add Bone",
"Add the selected bone into the pose.");
private static GUIContent previewGUIContent = new GUIContent(
"Preview Weight",
"Amount to apply bone pose to preview model. Inactive while editing.");
public void OnEnable()
{
targetPose = target as UMABonePose;
// inspectorLocked = ActiveEditorTracker.sharedTracker.isLocked;
// ActiveEditorTracker.sharedTracker.isLocked = true;
EditorApplication.update += this.OnUpdate;
SceneView.onSceneGUIDelegate += this.OnSceneGUI;
if (warningIcon == null)
{
warningIcon = EditorGUIUtility.FindTexture("console.warnicon.sml");
}
// if (trashIcon == null)
// {
// trashIcon = EditorGUIUtility.FindTexture("TreeEditor.Trash");
// }
}
public void OnDisable()
{
SceneView.onSceneGUIDelegate -= this.OnSceneGUI;
EditorApplication.update -= this.OnUpdate;
// ActiveEditorTracker.sharedTracker.isLocked = inspectorLocked;
}
void OnUpdate()
{
if (haveValidContext)
{
if (activeBoneIndex != editBoneIndex)
{
activeBoneIndex = BAD_INDEX;
mirrorBoneIndex = BAD_INDEX;
if (editBoneIndex != BAD_INDEX)
{
int boneHash = targetPose.poses[editBoneIndex].hash;
context.activeTransform = context.activeUMA.skeleton.GetBoneTransform(boneHash);
if (context.activeTransform != null)
{
activeBoneIndex = editBoneIndex;
}
if (context.mirrorTransform != null)
{
int mirrorHash = UMASkeleton.StringToHash(context.mirrorTransform.name);
for (int i = 0; i < targetPose.poses.Length; i++)
{
if (targetPose.poses[i].hash == mirrorHash)
{
mirrorBoneIndex = i;
break;
}
}
}
}
else
{
context.activeTransform = null;
}
}
if (!dynamicDNAConverterMode)
{
context.activeUMA.skeleton.ResetAll();
if (context.startingPose != null)
{
context.startingPose.ApplyPose(context.activeUMA.skeleton, context.startingPoseWeight);
}
if (haveEditTarget)
{
targetPose.ApplyPose(context.activeUMA.skeleton, 1f);
}
else
{
targetPose.ApplyPose(context.activeUMA.skeleton, previewWeight);
}
}
}
}
void OnSceneGUI(SceneView scene)
{
if (haveValidContext && haveEditTarget)
{
serializedObject.Update();
SerializedProperty poses = serializedObject.FindProperty("poses");
SerializedProperty activePose = null;
SerializedProperty mirrorPose = null;
if (activeBoneIndex != BAD_INDEX) activePose = poses.GetArrayElementAtIndex(activeBoneIndex);
if (mirrorBoneIndex != BAD_INDEX) mirrorPose = poses.GetArrayElementAtIndex(mirrorBoneIndex);
// EditorGUI.BeginChangeCheck( );
Transform activeTrans = context.activeTransform;
Transform mirrorTrans = context.mirrorTransform;
if (!mirrorActive || (mirrorBoneIndex == BAD_INDEX))
{
mirrorTrans = null;
}
if (activeTrans != null)
{
if (context.activeTransChanged)
{
scene.pivot = activeTrans.position;
context.activeTransChanged = false;
}
if (context.activeTool == UMABonePoseEditorContext.EditorTool.Tool_Position)
{
Vector3 newPos = Handles.PositionHandle(activeTrans.position, activeTrans.rotation);
if (newPos != activeTrans.position)
{
Vector3 newLocalPos = activeTrans.parent.InverseTransformPoint(newPos);
Vector3 deltaPos = newLocalPos - activeTrans.localPosition;
// Debug.Log("Moved active bone by: " + localDelta);
activeTrans.localPosition += deltaPos;
if (activePose != null)
{
SerializedProperty position = activePose.FindPropertyRelative("position");
position.vector3Value = position.vector3Value + deltaPos;
}
if (mirrorTrans != null)
{
switch(context.mirrorPlane)
{
case UMABonePoseEditorContext.MirrorPlane.Mirror_X:
deltaPos.x = -deltaPos.x;
break;
case UMABonePoseEditorContext.MirrorPlane.Mirror_Y:
deltaPos.y = -deltaPos.y;
break;
case UMABonePoseEditorContext.MirrorPlane.Mirror_Z:
deltaPos.z = -deltaPos.z;
break;
}
mirrorTrans.localPosition += deltaPos;
if (mirrorPose != null)
{
SerializedProperty position = mirrorPose.FindPropertyRelative("position");
position.vector3Value = position.vector3Value + deltaPos;
}
}
}
}
if (context.activeTool == UMABonePoseEditorContext.EditorTool.Tool_Rotation)
{
Quaternion newRotation = Handles.RotationHandle(activeTrans.rotation, activeTrans.position);
if (newRotation != activeTrans.rotation)
{
Quaternion deltaRot = Quaternion.Inverse(activeTrans.rotation) * newRotation;
activeTrans.localRotation *= deltaRot;
if (activePose != null)
{
SerializedProperty rotation = activePose.FindPropertyRelative("rotation");
rotation.quaternionValue = rotation.quaternionValue * deltaRot;
}
if (mirrorTrans != null)
{
switch(context.mirrorPlane)
{
case UMABonePoseEditorContext.MirrorPlane.Mirror_X:
deltaRot.y = -deltaRot.y;
deltaRot.z = -deltaRot.z;
break;
case UMABonePoseEditorContext.MirrorPlane.Mirror_Y:
deltaRot.x = -deltaRot.x;
deltaRot.z = -deltaRot.z;
break;
case UMABonePoseEditorContext.MirrorPlane.Mirror_Z:
deltaRot.x = -deltaRot.x;
deltaRot.y = -deltaRot.y;
break;
}
mirrorTrans.localRotation *= deltaRot;
if (mirrorPose != null)
{
SerializedProperty rotation = mirrorPose.FindPropertyRelative("rotation");
rotation.quaternionValue = rotation.quaternionValue * deltaRot;
}
}
}
}
if (context.activeTool == UMABonePoseEditorContext.EditorTool.Tool_Scale)
{
Vector3 newScale = Handles.ScaleHandle(activeTrans.localScale, activeTrans.position, activeTrans.rotation, HandleUtility.GetHandleSize(activeTrans.position));
if (newScale != activeTrans.localScale)
{
activeTrans.localScale = newScale;
if (activePose != null)
{
SerializedProperty scale = activePose.FindPropertyRelative("scale");
scale.vector3Value = newScale;
}
if (mirrorTrans != null)
{
mirrorTrans.localScale = activeTrans.localScale;
if (mirrorPose != null)
{
SerializedProperty scale = mirrorPose.FindPropertyRelative("scale");
scale.vector3Value = newScale;
}
}
}
}
}
serializedObject.ApplyModifiedProperties();
}
}
public override void OnInspectorGUI()
{
serializedObject.Update();
SerializedProperty poses = serializedObject.FindProperty("poses");
if (doBoneAdd)
{
int addedIndex = poses.arraySize;
poses.InsertArrayElementAtIndex(addedIndex);
var pose = poses.GetArrayElementAtIndex(addedIndex);
SerializedProperty bone = pose.FindPropertyRelative("bone");
bone.stringValue = addBoneName;
SerializedProperty hash = pose.FindPropertyRelative("hash");
hash.intValue = UMASkeleton.StringToHash(addBoneName);
SerializedProperty position = pose.FindPropertyRelative("position");
position.vector3Value = Vector3.zero;
SerializedProperty rotation = pose.FindPropertyRelative("rotation");
rotation.quaternionValue = Quaternion.identity;
SerializedProperty scale = pose.FindPropertyRelative("scale");
scale.vector3Value = Vector3.one;
activeBoneIndex = BAD_INDEX;
editBoneIndex = BAD_INDEX;
mirrorBoneIndex = BAD_INDEX;
addBoneIndex = 0;
addBoneName = "";
doBoneAdd = false;
}
if (doBoneRemove)
{
poses.DeleteArrayElementAtIndex(removeBoneIndex - 1);
activeBoneIndex = BAD_INDEX;
editBoneIndex = BAD_INDEX;
mirrorBoneIndex = BAD_INDEX;
removeBoneIndex = 0;
doBoneRemove = false;
}
// HACK
if (!dynamicDNAConverterMode)
{
sourceUMA = EditorGUILayout.ObjectField("Source UMA", sourceUMA, typeof(UMAData), true) as UMAData;
if (sourceUMA != null)
{
if (context == null)
{
context = new UMABonePoseEditorContext();
}
if (context.activeUMA != sourceUMA)
{
context.activeUMA = sourceUMA;
}
}
}
// Weight of pose on preview model
if (haveValidContext && !dynamicDNAConverterMode)
{
EditorGUILayout.BeginHorizontal();
GUILayout.Space(addRemovePadding);
EditorGUI.BeginDisabledGroup(haveEditTarget);
previewWeight = EditorGUILayout.Slider(previewGUIContent, previewWeight, 0f, 1f);
EditorGUI.EndDisabledGroup();
GUILayout.Space(addRemovePadding);
EditorGUILayout.EndHorizontal();
}
GUILayout.Space(EditorGUIUtility.singleLineHeight / 2f);
// string controlName = GUI.GetNameOfFocusedControl();
// if ((controlName != null) && (controlName.Length > 0))
// Debug.Log(controlName);
// These can get corrupted by undo, so just rebuild them
string[] removeBoneOptions = new string[targetPose.poses.Length + 1];
removeBoneOptions[0] = " ";
for (int i = 0; i < targetPose.poses.Length; i++)
{
removeBoneOptions[i + 1] = targetPose.poses[i].bone;
}
string[] addBoneOptions = new string[1];
if (haveValidContext)
{
List<string> addList = new List<string>(context.boneList);
addList.Insert(0, " ");
for (int i = 0; i < targetPose.poses.Length; i++)
{
addList.Remove(targetPose.poses[i].bone);
}
addBoneOptions = addList.ToArray();
}
// List of existing bones
poses.isExpanded = EditorGUILayout.Foldout(poses.isExpanded, "Pose Bones ("+poses.arraySize+")");
if (poses.isExpanded)
{
for (int i = 0; i < poses.arraySize; i++)
{
SerializedProperty pose = poses.GetArrayElementAtIndex(i);
drawBoneIndex = i;
PoseBoneDrawer(pose);
}
}
GUILayout.Space(EditorGUIUtility.singleLineHeight);
// Controls for adding a new bone
EditorGUILayout.BeginHorizontal();
GUILayout.Space(addRemovePadding);
if (haveValidContext)
{
EditorGUI.BeginDisabledGroup(addBoneIndex < 1);
if (GUILayout.Button(addBoneGUIContent, GUILayout.Width(90f)))
{
addBoneName = addBoneOptions[addBoneIndex];
doBoneAdd = true;
}
EditorGUI.EndDisabledGroup();
EditorGUILayout.BeginVertical();
GUILayout.Space(buttonVerticalOffset);
addBoneIndex = EditorGUILayout.Popup(addBoneIndex, addBoneOptions);
EditorGUILayout.EndVertical();
}
else
{
EditorGUI.BeginDisabledGroup(addBoneName.Length < minBoneNameLength);
if (GUILayout.Button(addBoneGUIContent, GUILayout.Width(90f)))
{
doBoneAdd = true;
}
EditorGUI.EndDisabledGroup();
EditorGUILayout.BeginVertical();
GUILayout.Space(buttonVerticalOffset);
addBoneName = EditorGUILayout.TextField(addBoneName);
EditorGUILayout.EndVertical();
}
GUILayout.Space(addRemovePadding);
EditorGUILayout.EndHorizontal();
// Controls for removing existing bone
EditorGUILayout.BeginHorizontal();
GUILayout.Space(addRemovePadding);
EditorGUI.BeginDisabledGroup(removeBoneIndex < 1);
if (GUILayout.Button(removeBoneGUIContent, GUILayout.Width(90f)))
{
doBoneRemove = true;
}
EditorGUI.EndDisabledGroup();
EditorGUILayout.BeginVertical();
GUILayout.Space(buttonVerticalOffset);
removeBoneIndex = EditorGUILayout.Popup(removeBoneIndex, removeBoneOptions);
EditorGUILayout.EndVertical();
GUILayout.Space(addRemovePadding);
EditorGUILayout.EndHorizontal();
serializedObject.ApplyModifiedProperties();
}
private void PoseBoneDrawer(SerializedProperty property)
{
EditorGUI.indentLevel++;
SerializedProperty bone = property.FindPropertyRelative("bone");
GUIContent boneGUIContent = new GUIContent(
bone.stringValue,
"The name of the bone being modified by pose.");
EditorGUILayout.BeginHorizontal();
bone.isExpanded = EditorGUILayout.Foldout(bone.isExpanded, boneGUIContent);
Color currentColor = GUI.color;
if (drawBoneIndex == editBoneIndex)
{
GUI.color = Color.green;
if (GUILayout.Button("Editing", EditorStyles.miniButton, GUILayout.Width(60f)))
{
editBoneIndex = BAD_INDEX;
mirrorBoneIndex = BAD_INDEX;
}
}
else if (drawBoneIndex == mirrorBoneIndex)
{
Color lightBlue = Color.Lerp(Color.blue, Color.cyan, 0.66f);
if (mirrorActive)
{
GUI.color = lightBlue;
if (GUILayout.Button("Mirroring", EditorStyles.miniButton, GUILayout.Width(60f)))
{
mirrorActive = false;
}
}
else
{
GUI.color = Color.Lerp(lightBlue, Color.white, 0.66f);
if (GUILayout.Button("Mirror", EditorStyles.miniButton, GUILayout.Width(60f)))
{
mirrorActive = true;
}
}
}
else
{
if (GUILayout.Button("Edit", EditorStyles.miniButton, GUILayout.Width(60f)))
{
editBoneIndex = drawBoneIndex;
}
}
GUI.color = currentColor;
EditorGUILayout.EndHorizontal();
if (bone.isExpanded)
{
EditorGUI.BeginDisabledGroup(drawBoneIndex != editBoneIndex);
EditorGUI.indentLevel++;
int controlIDLow = GUIUtility.GetControlID(0, FocusType.Passive);
// GUI.SetNextControlName("position_" + drawBoneIndex);
EditorGUILayout.PropertyField(property.FindPropertyRelative("position"), positionGUIContent);
int controlIDHigh = GUIUtility.GetControlID(0, FocusType.Passive);
if ((GUIUtility.keyboardControl > controlIDLow) && (GUIUtility.keyboardControl < controlIDHigh))
{
if (context != null) context.activeTool = UMABonePoseEditorContext.EditorTool.Tool_Position;
}
// Show Euler angles for rotation
SerializedProperty rotation = property.FindPropertyRelative("rotation");
// Use BeginProperty() with fake rect to enable Undo but keep layout correct
Rect rotationRect = new Rect(0, 0, 0, 0);
EditorGUI.BeginProperty(rotationRect, GUIContent.none, rotation);
Vector3 currentRotationEuler = ((Quaternion)rotation.quaternionValue).eulerAngles;
Vector3 newRotationEuler = currentRotationEuler;
EditorGUI.BeginChangeCheck();
controlIDLow = GUIUtility.GetControlID(0, FocusType.Passive);
// GUI.SetNextControlName("rotation_" + drawBoneIndex);
newRotationEuler = EditorGUILayout.Vector3Field(rotationGUIContent, newRotationEuler);
controlIDHigh = GUIUtility.GetControlID(0, FocusType.Passive);
if ((GUIUtility.keyboardControl > controlIDLow) && (GUIUtility.keyboardControl < controlIDHigh))
{
if (context != null) context.activeTool = UMABonePoseEditorContext.EditorTool.Tool_Rotation;
}
if (EditorGUI.EndChangeCheck())
{
if(newRotationEuler != currentRotationEuler)
{
rotation.quaternionValue = Quaternion.Euler(newRotationEuler);
}
}
EditorGUI.EndProperty();
SerializedProperty scaleProperty = property.FindPropertyRelative("scale");
controlIDLow = GUIUtility.GetControlID(0, FocusType.Passive);
// GUI.SetNextControlName("scale_" + drawBoneIndex);
EditorGUILayout.PropertyField(scaleProperty, scaleGUIContent);
controlIDHigh = GUIUtility.GetControlID(0, FocusType.Passive);
if ((GUIUtility.keyboardControl > controlIDLow) && (GUIUtility.keyboardControl < controlIDHigh))
{
if (context != null) context.activeTool = UMABonePoseEditorContext.EditorTool.Tool_Scale;
}
// Warn if there's a non-uniform scale
Vector3 scaleValue = scaleProperty.vector3Value;
if (!Mathf.Approximately(scaleValue.x, scaleValue.y) || !Mathf.Approximately(scaleValue.y, scaleValue.z))
{
EditorGUILayout.BeginHorizontal();
GUILayout.Space(EditorGUIUtility.labelWidth / 2f);
if (warningIcon != null)
{
scaleWarningGUIContent.image = warningIcon;
EditorGUILayout.LabelField(scaleWarningGUIContent, GUILayout.MinHeight(warningIcon.height + 4f));
}
else
{
EditorGUILayout.LabelField(scaleWarningGUIContent);
}
EditorGUILayout.EndHorizontal();
}
EditorGUI.indentLevel--;
EditorGUI.EndDisabledGroup();
}
EditorGUI.indentLevel--;
}
}
}
| |
//
// Encog(tm) Core v3.3 - .Net Version
// http://www.heatonresearch.com/encog/
//
// Copyright 2008-2014 Heaton Research, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// For more information on Heaton Research copyrights, licenses
// and trademarks visit:
// http://www.heatonresearch.com/copyright
//
using System;
using Encog.MathUtil.LIBSVM;
using Encog.ML.Data;
using Encog.ML.Data.Basic;
using Encog.Neural;
using Encog.Util.Simple;
namespace Encog.ML.SVM
{
/// <summary>
/// This is a network that is backed by one or more Support Vector Machines
/// (SVM). It is designed to function very similarly to an Encog neural network,
/// and is largely interchangeable with an Encog neural network.
/// The support vector machine supports several types. Regression is used when
/// you want the network to predict a value, given the input. Function
/// approximation is a good example of regression. Classification is used when
/// you want the SVM to group the input data into one or more classes.
/// Support Vector Machines typically have a single output. Neural networks can
/// have multiple output neurons. To get around this issue, this class will
/// create multiple SVM's if there is more than one output specified.
/// Because a SVM is trained quite differently from a neural network, none of the
/// neural network training classes will work. This class must be trained using
/// SVMTrain.
/// </summary>
[Serializable]
public class SupportVectorMachine : BasicML, IMLRegression, IMLClassification,
IMLError
{
/// <summary>
/// The default degree.
/// </summary>
///
public const int DefaultDegree = 3;
/// <summary>
/// The default COEF0.
/// </summary>
///
public const int DefaultCoef0 = 0;
/// <summary>
/// The default NU.
/// </summary>
///
public const double DefaultNu = 0.5d;
/// <summary>
/// The default cache size.
/// </summary>
///
public const int DefaultCacheSize = 100;
/// <summary>
/// The default C.
/// </summary>
///
public const int DefaultC = 1;
/// <summary>
/// The default EPS.
/// </summary>
///
public const double DefaultEps = 1e-3d;
/// <summary>
/// The default P.
/// </summary>
///
public const double DefaultP = 0.1d;
/// <summary>
/// The params for the model.
/// </summary>
///
private readonly svm_parameter _paras;
/// <summary>
/// The input count.
/// </summary>
///
private int _inputCount;
/// <summary>
/// The SVM model to use.
/// </summary>
///
private svm_model _model;
/// <summary>
/// Construct the SVM.
/// </summary>
///
public SupportVectorMachine()
{
_paras = new svm_parameter();
}
/// <summary>
/// Construct an SVM network. For regression it will use an epsilon support
/// vector. Both types will use an RBF kernel.
/// </summary>
///
/// <param name="theInputCount">The input count.</param>
/// <param name="regression">True if this network is used for regression.</param>
public SupportVectorMachine(int theInputCount, bool regression)
: this(
theInputCount,
(regression) ? SVMType.EpsilonSupportVectorRegression : SVMType.SupportVectorClassification,
KernelType.RadialBasisFunction)
{
}
/// <summary>
/// Construct a SVM network.
/// </summary>
///
/// <param name="theInputCount">The input count.</param>
/// <param name="svmType">The type of SVM.</param>
/// <param name="kernelType">The SVM kernal type.</param>
public SupportVectorMachine(int theInputCount, SVMType svmType,
KernelType kernelType)
{
_inputCount = theInputCount;
_paras = new svm_parameter();
switch (svmType)
{
case SVMType.SupportVectorClassification:
_paras.svm_type = svm_parameter.C_SVC;
break;
case SVMType.NewSupportVectorClassification:
_paras.svm_type = svm_parameter.NU_SVC;
break;
case SVMType.SupportVectorOneClass:
_paras.svm_type = svm_parameter.ONE_CLASS;
break;
case SVMType.EpsilonSupportVectorRegression:
_paras.svm_type = svm_parameter.EPSILON_SVR;
break;
case SVMType.NewSupportVectorRegression:
_paras.svm_type = svm_parameter.NU_SVR;
break;
default:
throw new NeuralNetworkError("Invalid svm type");
}
switch (kernelType)
{
case KernelType.Linear:
_paras.kernel_type = svm_parameter.LINEAR;
break;
case KernelType.Poly:
_paras.kernel_type = svm_parameter.POLY;
break;
case KernelType.RadialBasisFunction:
_paras.kernel_type = svm_parameter.RBF;
break;
case KernelType.Sigmoid:
_paras.kernel_type = svm_parameter.SIGMOID;
break;
/*case Encog.ML.SVM.KernelType.Precomputed:
this.paras.kernel_type = Encog.MathUtil.LIBSVM.svm_parameter.PRECOMPUTED;
break;*/
default:
throw new NeuralNetworkError("Invalid kernel type");
}
// params[i].kernel_type = svm_parameter.RBF;
_paras.degree = DefaultDegree;
_paras.coef0 = 0;
_paras.nu = DefaultNu;
_paras.cache_size = DefaultCacheSize;
_paras.C = 1;
_paras.eps = DefaultEps;
_paras.p = DefaultP;
_paras.shrinking = 1;
_paras.probability = 0;
_paras.nr_weight = 0;
_paras.weight_label = new int[0];
_paras.weight = new double[0];
_paras.gamma = 1.0d/_inputCount;
}
/// <summary>
/// Construct a SVM from a model.
/// </summary>
///
/// <param name="theModel">The model.</param>
public SupportVectorMachine(svm_model theModel)
{
_model = theModel;
_paras = _model.param;
_inputCount = 0;
// determine the input count
foreach (var element in _model.SV)
{
foreach (svm_node t in element)
{
_inputCount = Math.Max(t.index, _inputCount);
}
}
//
}
/// <value>The kernel type.</value>
public KernelType KernelType
{
get
{
switch (_paras.kernel_type)
{
case svm_parameter.LINEAR:
return KernelType.Linear;
case svm_parameter.POLY:
return KernelType.Poly;
case svm_parameter.RBF:
return KernelType.RadialBasisFunction;
case svm_parameter.SIGMOID:
return KernelType.Sigmoid;
/* case Encog.MathUtil.LIBSVM.svm_parameter.PRECOMPUTED:
return Encog.ML.SVM.KernelType.Precomputed;*/
default:
return default(KernelType) /* was: null */;
}
}
}
/// <summary>
/// Set the model.
/// </summary>
public svm_model Model
{
get { return _model; }
set { _model = value; }
}
/// <value>The SVM params for each of the outputs.</value>
public svm_parameter Params
{
get { return _paras; }
}
/// <value>The SVM type.</value>
public SVMType SVMType
{
get
{
switch (_paras.svm_type)
{
case svm_parameter.C_SVC:
return SVMType.SupportVectorClassification;
case svm_parameter.NU_SVC:
return SVMType.NewSupportVectorClassification;
case svm_parameter.ONE_CLASS:
return SVMType.SupportVectorOneClass;
case svm_parameter.EPSILON_SVR:
return SVMType.EpsilonSupportVectorRegression;
case svm_parameter.NU_SVR:
return SVMType.NewSupportVectorRegression;
default:
return default(SVMType) /* was: null */;
}
}
}
#region MLClassification Members
/// <inheritdoc/>
public int Classify(IMLData input)
{
if (_model == null)
{
throw new EncogError(
"Can't use the SVM yet, it has not been trained, "
+ "and no model exists.");
}
svm_node[] formattedInput = MakeSparse(input);
return (int) svm.svm_predict(_model, formattedInput);
}
#endregion
#region MLError Members
/// <summary>
/// Calculate the error for this SVM.
/// </summary>
///
/// <param name="data">The training set.</param>
/// <returns>The error percentage.</returns>
public double CalculateError(IMLDataSet data)
{
switch (SVMType)
{
case SVMType.SupportVectorClassification:
case SVMType.NewSupportVectorClassification:
case SVMType.SupportVectorOneClass:
return EncogUtility.CalculateClassificationError(this, data);
case SVMType.EpsilonSupportVectorRegression:
case SVMType.NewSupportVectorRegression:
return EncogUtility.CalculateRegressionError(this, data);
default:
return EncogUtility.CalculateRegressionError(this, data);
}
}
#endregion
#region MLRegression Members
/// <summary>
/// Compute the output for the given input.
/// </summary>
///
/// <param name="input">The input to the SVM.</param>
/// <returns>The results from the SVM.</returns>
public IMLData Compute(IMLData input)
{
if (_model == null)
{
throw new EncogError(
"Can't use the SVM yet, it has not been trained, "
+ "and no model exists.");
}
var result = new BasicMLData(1);
svm_node[] formattedInput = MakeSparse(input);
double d = svm.svm_predict(_model, formattedInput);
result[0] = d;
return result;
}
/// <summary>
/// Set the input count.
/// </summary>
///
/// <value>The new input count.</value>
public int InputCount
{
get { return _inputCount; }
set { _inputCount = value; }
}
/// <value>For a SVM, the output count is always one.</value>
public int OutputCount
{
get { return 1; }
}
#endregion
/// <summary>
/// Convert regular Encog MLData into the "sparse" data needed by an SVM.
/// </summary>
///
/// <param name="data">The data to convert.</param>
/// <returns>The SVM sparse data.</returns>
public svm_node[] MakeSparse(IMLData data)
{
var result = new svm_node[data.Count];
for (int i = 0; i < data.Count; i++)
{
result[i] = new svm_node {index = i + 1, value_Renamed = data[i]};
}
return result;
}
/// <summary>
/// Not needed, no properties to update.
/// </summary>
///
public override void UpdateProperties()
{
// unneeded
}
}
}
| |
//*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the MIT License (MIT).
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************
using SDKTemplate.Helpers;
using SDKTemplate.Models;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.Globalization;
using Windows.Media.Core;
using Windows.Media.Playback;
using Windows.Media.Streaming.Adaptive;
using Windows.UI.Core;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
using Windows.Web.Http;
namespace SDKTemplate
{
/// See the README.md for discussion of this scenario.
public sealed partial class Scenario2_EventHandlers : Page
{
AdaptiveMediaSource adaptiveMediaSource;
Task LoadSourceFromUriTask = Task.CompletedTask;
private BitrateHelper bitrateHelper;
public Scenario2_EventHandlers()
{
this.InitializeComponent();
}
protected override async void OnNavigatedFrom(NavigationEventArgs e)
{
// To insure we don't clean-up half-constructed objects,
// wait for any active source loading to complete.
await LoadSourceFromUriTask;
var mediaPlayer = mediaPlayerElement.MediaPlayer;
if (mediaPlayer != null)
{
UnregisterForMediaPlayerEvents(mediaPlayer);
UnregisterHandlers(mediaPlayer);
mediaPlayer.DisposeSource();
mediaPlayerElement.SetMediaPlayer(null);
mediaPlayer.Dispose();
}
}
private void UnregisterHandlers(MediaPlayer mediaPlayer)
{
MediaPlaybackItem mpItem = mediaPlayer.Source as MediaPlaybackItem;
if (mpItem != null)
{
UnregisterForMediaPlaybackItemEvents(mpItem);
UnregisterForMediaSourceEvents(mpItem.Source);
}
MediaSource source = mediaPlayer.Source as MediaSource;
if (source != null)
{
UnregisterForMediaSourceEvents(source);
}
UnregisterForAdaptiveMediaSourceEvents(adaptiveMediaSource);
}
private async void Page_OnLoaded(object sender, RoutedEventArgs e)
{
// Explicitly create the instance of MediaPlayer if you need to register for its events
// (like MediaOpened / MediaFailed) prior to setting an IMediaPlaybackSource.
var mediaPlayer = new MediaPlayer();
RegisterForMediaPlayerEvents(mediaPlayer);
// Ensure we have PlayReady support, if the user enters a DASH/PR Uri in the text box:
var prHelper = new PlayReadyHelper(LoggerControl);
prHelper.SetUpProtectionManager(mediaPlayer);
mediaPlayerElement.SetMediaPlayer(mediaPlayer);
AdaptiveContentModel adaptiveContentModel = MainPage.FindContentById(1);
UriBox.Text = adaptiveContentModel.ManifestUri.ToString();
LoadSourceFromUriTask = LoadSourceFromUriAsync(adaptiveContentModel.ManifestUri);
await LoadSourceFromUriTask;
}
private async void LoadUri_Click(object sender, RoutedEventArgs e)
{
Uri uri;
if (!Uri.TryCreate(UriBox.Text, UriKind.Absolute, out uri))
{
Log("Malformed Uri in Load text box.");
return;
}
LoadSourceFromUriTask = LoadSourceFromUriAsync(uri);
await LoadSourceFromUriTask;
// On small screens, hide the description text to make room for the video.
DescriptionText.Visibility = (ActualHeight < 500) ? Visibility.Collapsed : Visibility.Visible;
}
private async Task LoadSourceFromUriAsync(Uri uri, HttpClient httpClient = null)
{
if (mediaPlayerElement.MediaPlayer?.Source != null)
{
UnregisterHandlers(mediaPlayerElement.MediaPlayer);
mediaPlayerElement.MediaPlayer.DisposeSource();
}
AdaptiveMediaSourceCreationResult result = null;
if (httpClient != null)
{
result = await AdaptiveMediaSource.CreateFromUriAsync(uri, httpClient);
}
else
{
result = await AdaptiveMediaSource.CreateFromUriAsync(uri);
}
// We don't need to save a reference to the MediaSource,
// because we can obtain it from the MediaPlaybackItem.Source in event handlers.
MediaSource source;
if (result.Status == AdaptiveMediaSourceCreationStatus.Success)
{
adaptiveMediaSource = result.MediaSource;
// At this point, we have read the manifest of the media source, and all bitrates are known.
bitrateHelper = new BitrateHelper(adaptiveMediaSource.AvailableBitrates);
// The AdaptiveMediaSource chooses initial playback and download bitrates.
// See the Tuning scenario for examples of customizing these bitrates.
await UpdatePlaybackBitrate(adaptiveMediaSource.CurrentPlaybackBitrate);
await UpdateDownloadBitrateAsync(adaptiveMediaSource.CurrentDownloadBitrate);
// Register for events before resolving the MediaSource.
RegisterForAdaptiveMediaSourceEvents(adaptiveMediaSource);
source = MediaSource.CreateFromAdaptiveMediaSource(adaptiveMediaSource);
}
else
{
Log($"Error creating the AdaptiveMediaSource: {result.Status}");
// Try to load the URI as a progressive download URI.
Log($"Attempting to create a MediaSource from uri: {uri}");
source = MediaSource.CreateFromUri(uri);
}
// You can save additional information in the CustomPropertySet for future retrieval.
// Note: MediaSource.CustomProperties is a ValueSet and therefore can store
// only serializable types.
// Save the original Uri.
source.CustomProperties.Add("uri", uri.ToString());
// You're likely to put a content tracking id into the CustomProperties.
source.CustomProperties.Add("contentId", Guid.NewGuid());
RegisterForMediaSourceEvents(source);
// Register for events before resolving the MediaSource.
var mpItem = new MediaPlaybackItem(source);
RegisterForMediaPlaybackItemEvents(mpItem);
// It is at this point that the MediaSource (within a MediaPlaybackItem) will be fully resolved.
// It gets opened, and events start being raised.
// Since we are in an async function, the user may have user navigated away, which will null the MediaPlayer.
if (mediaPlayerElement.MediaPlayer != null)
{
mediaPlayerElement.MediaPlayer.Source = mpItem;
}
}
#region MediaPlayer Event Handlers
private void RegisterForMediaPlayerEvents(MediaPlayer mediaPlayer)
{
// Player Events
mediaPlayer.SourceChanged += MediaPlayer_SourceChanged;
mediaPlayer.MediaOpened += MediaPlayer_MediaOpened;
mediaPlayer.MediaEnded += MediaPlayer_MediaEnded;
mediaPlayer.MediaFailed += MediaPlayer_MediaFailed;
mediaPlayer.VolumeChanged += MediaPlayer_VolumeChanged;
mediaPlayer.IsMutedChanged += MediaPlayer_IsMutedChanged;
// NOTE: There are a number of deprecated events on MediaPlayer.
// Please use the equivalent events on the MediaPlayer.PlaybackSession as shown below.
// PlaybackSession Events
mediaPlayer.PlaybackSession.BufferingEnded += MediaPlayer_PlaybackSession_BufferingEnded;
mediaPlayer.PlaybackSession.BufferingProgressChanged += MediaPlayer_PlaybackSession_BufferingProgressChanged;
mediaPlayer.PlaybackSession.BufferingStarted += MediaPlayer_PlaybackSession_BufferingStarted;
mediaPlayer.PlaybackSession.DownloadProgressChanged += MediaPlayer_PlaybackSession_DownloadProgressChanged;
mediaPlayer.PlaybackSession.NaturalDurationChanged += MediaPlayer_PlaybackSession_NaturalDurationChanged;
mediaPlayer.PlaybackSession.NaturalVideoSizeChanged += MediaPlayer_PlaybackSession_NaturalVideoSizeChanged;
mediaPlayer.PlaybackSession.PlaybackRateChanged += MediaPlayer_PlaybackSession_PlaybackRateChanged;
mediaPlayer.PlaybackSession.PlaybackStateChanged += MediaPlayer_PlaybackSession_PlaybackStateChanged;
// The .PositionChanged is excessively verbose for the UI logging we are doing in this sample:
// mediaPlayer.PlaybackSession.PositionChanged += MediaPlayer_PlaybackSession_PositionChanged;
mediaPlayer.PlaybackSession.SeekCompleted += MediaPlayer_PlaybackSession_SeekCompleted;
}
private void UnregisterForMediaPlayerEvents(MediaPlayer mediaPlayer)
{
if (mediaPlayer == null)
{
return;
}
// Player Events
mediaPlayer.SourceChanged -= MediaPlayer_SourceChanged;
mediaPlayer.MediaOpened -= MediaPlayer_MediaOpened;
mediaPlayer.MediaEnded -= MediaPlayer_MediaEnded;
mediaPlayer.MediaFailed -= MediaPlayer_MediaFailed;
mediaPlayer.VolumeChanged -= MediaPlayer_VolumeChanged;
mediaPlayer.IsMutedChanged -= MediaPlayer_IsMutedChanged;
// PlaybackSession Events
mediaPlayer.PlaybackSession.BufferingEnded -= MediaPlayer_PlaybackSession_BufferingEnded;
mediaPlayer.PlaybackSession.BufferingProgressChanged -= MediaPlayer_PlaybackSession_BufferingProgressChanged;
mediaPlayer.PlaybackSession.BufferingStarted -= MediaPlayer_PlaybackSession_BufferingStarted;
mediaPlayer.PlaybackSession.DownloadProgressChanged -= MediaPlayer_PlaybackSession_DownloadProgressChanged;
mediaPlayer.PlaybackSession.NaturalDurationChanged -= MediaPlayer_PlaybackSession_NaturalDurationChanged;
mediaPlayer.PlaybackSession.NaturalVideoSizeChanged -= MediaPlayer_PlaybackSession_NaturalVideoSizeChanged;
mediaPlayer.PlaybackSession.PlaybackRateChanged -= MediaPlayer_PlaybackSession_PlaybackRateChanged;
mediaPlayer.PlaybackSession.PlaybackStateChanged -= MediaPlayer_PlaybackSession_PlaybackStateChanged;
mediaPlayer.PlaybackSession.SeekCompleted -= MediaPlayer_PlaybackSession_SeekCompleted;
}
private void MediaPlayer_SourceChanged(MediaPlayer sender, object args)
{
Log("mediaPlayer.SourceChanged");
}
private void MediaPlayer_MediaOpened(MediaPlayer sender, object args)
{
Log($"MediaPlayer_MediaOpened, Duration: {sender.PlaybackSession.NaturalDuration}");
}
private void MediaPlayer_MediaEnded(MediaPlayer sender, object args)
{
Log("MediaPlayer_MediaEnded");
}
private void MediaPlayer_MediaFailed(MediaPlayer sender, MediaPlayerFailedEventArgs args)
{
Log($"MediaPlayer_MediaFailed Error: {args.Error}, ErrorMessage: {args.ErrorMessage}, ExtendedErrorCode.Message: {args.ExtendedErrorCode.Message}");
}
private void MediaPlayer_VolumeChanged(MediaPlayer sender, object args)
{
Log($"MediaPlayer_VolumeChanged, Volume: {sender.Volume}");
}
private void MediaPlayer_IsMutedChanged(MediaPlayer sender, object args)
{
Log($"MediaPlayer_IsMutedChanged, IsMuted={sender.IsMuted}");
}
// PlaybackSession Events
private void MediaPlayer_PlaybackSession_BufferingEnded(MediaPlaybackSession sender, object args)
{
Log("PlaybackSession_BufferingEnded");
}
private void MediaPlayer_PlaybackSession_BufferingProgressChanged(MediaPlaybackSession sender, object args)
{
Log($"PlaybackSession_BufferingProgressChanged, BufferingProgress: {sender.BufferingProgress}");
}
private void MediaPlayer_PlaybackSession_BufferingStarted(MediaPlaybackSession sender, object args)
{
Log("PlaybackSession_BufferingStarted");
}
private void MediaPlayer_PlaybackSession_DownloadProgressChanged(MediaPlaybackSession sender, object args)
{
Log($"PlaybackSession_DownloadProgressChanged, DownloadProgress: {sender.DownloadProgress}");
}
private void MediaPlayer_PlaybackSession_NaturalDurationChanged(MediaPlaybackSession sender, object args)
{
Log($"PlaybackSession_NaturalDurationChanged, NaturalDuration: {sender.NaturalDuration}");
}
private void MediaPlayer_PlaybackSession_NaturalVideoSizeChanged(MediaPlaybackSession sender, object args)
{
Log($"PlaybackSession_NaturalVideoSizeChanged, NaturalVideoWidth: {sender.NaturalVideoWidth}, NaturalVideoHeight: {sender.NaturalVideoHeight}");
}
private void MediaPlayer_PlaybackSession_PlaybackRateChanged(MediaPlaybackSession sender, object args)
{
Log($"PlaybackSession_PlaybackRateChanged, PlaybackRate: {sender.PlaybackRate}");
}
private void MediaPlayer_PlaybackSession_PlaybackStateChanged(MediaPlaybackSession sender, object args)
{
Log($"PlaybackSession_PlaybackStateChanged, PlaybackState: {sender.PlaybackState}");
}
// private void MediaPlayer_PlaybackSession.PositionChanged(MediaPlaybackSession sender, object args)
// {
// LogOnUI("PlaybackSession_PositionChanged, Position: " + sender.Position);
// }
private void MediaPlayer_PlaybackSession_SeekCompleted(MediaPlaybackSession sender, object args)
{
Log($"PlaybackSession_SeekCompleted, Position: {sender.Position}");
}
#endregion
#region MediaSource Event Handlers
private void RegisterForMediaSourceEvents(MediaSource source)
{
source.StateChanged += Source_StateChanged;
source.OpenOperationCompleted += Source_OpenOperationCompleted;
}
private void UnregisterForMediaSourceEvents(MediaSource source)
{
if (source == null)
{
return;
}
source.StateChanged -= Source_StateChanged;
source.OpenOperationCompleted -= Source_OpenOperationCompleted;
}
private void Source_StateChanged(MediaSource sender, MediaSourceStateChangedEventArgs args)
{
Log($"Source.StateChanged:{args.OldState} to {args.NewState}");
}
private void Source_OpenOperationCompleted(MediaSource sender, MediaSourceOpenOperationCompletedEventArgs args)
{
// Get the MediaPlaybackItem that corresponds to the MediaSource.
MediaPlaybackItem item = MediaPlaybackItem.FindFromMediaSource(sender);
if (item != null && item.AudioTracks.Count > 0)
{
// The MediaPlaybackItem contains additional information about the underlying media.
string audioCodec = item.AudioTracks[item.AudioTracks.SelectedIndex].GetEncodingProperties().Subtype;
// We can read values from the MediaSource.CustomProperties.
var uri = (string)sender.CustomProperties["uri"];
var contentId = (Guid)sender.CustomProperties["contentId"];
Log($"Opened Media Source with Uri: {uri}, ContentId: {contentId}, Codec: {audioCodec}");
// This extension method in MediaPlaybackItemStringExtensions dumps all the properties from all the tracks.
var allProperties = item.ToFormattedString();
Log(allProperties);
// The AdaptiveMediaSource can manage multiple video tracks internally,
// but only a single video track is exposed in the MediaPlaybackItem, not a collection.
}
}
#endregion
#region MediaPlaybackItem Event Handlers
private void RegisterForMediaPlaybackItemEvents(MediaPlaybackItem item)
{
item.AudioTracks.SelectedIndexChanged += AudioTracks_SelectedIndexChanged;
item.AudioTracksChanged += Item_AudioTracksChanged;
item.TimedMetadataTracksChanged += Item_TimedMetadataTracksChanged;
}
private void UnregisterForMediaPlaybackItemEvents(MediaPlaybackItem item)
{
if (item == null)
{
return;
}
item.AudioTracks.SelectedIndexChanged -= AudioTracks_SelectedIndexChanged;
item.AudioTracksChanged -= Item_AudioTracksChanged;
item.TimedMetadataTracksChanged -= Item_TimedMetadataTracksChanged;
foreach (AudioTrack audioTrack in item.AudioTracks)
{
audioTrack.OpenFailed -= AudioTrack_OpenFailed;
}
}
private void AudioTracks_SelectedIndexChanged(ISingleSelectMediaTrackList sender, object args)
{
MediaPlaybackAudioTrackList list = sender as MediaPlaybackAudioTrackList;
AudioTrack audioTrack = list[sender.SelectedIndex];
MediaPlaybackItem mpItem = audioTrack.PlaybackItem;
var contentId = (Guid)mpItem.Source.CustomProperties["contentId"];
string audioCodec = audioTrack.GetEncodingProperties().Subtype;
var msg = $"The newly selected audio track of {contentId} has Codec {audioCodec}";
var language = audioTrack.Language;
if (!String.IsNullOrEmpty(language))
{
// Transform the language code into a UI-localized language name.
msg += ", Language: " + (new Language(language)).DisplayName;
}
Log(msg);
}
private void Item_AudioTracksChanged(MediaPlaybackItem sender, IVectorChangedEventArgs args)
{
Log($"item.AudioTracksChanged: CollectionChange:{args.CollectionChange} Index:{args.Index} Total:{sender.AudioTracks.Count}");
switch (args.CollectionChange)
{
case CollectionChange.Reset:
foreach (AudioTrack track in sender.AudioTracks)
{
// Tracks are added once as a source discovers them in the source media.
// This occurs prior to the track media being opened.
// Register here so that we can receive the Track.OpenFailed event.
track.OpenFailed += AudioTrack_OpenFailed;
}
break;
case CollectionChange.ItemInserted:
// Additional tracks added after loading the main source should be registered here.
AudioTrack newTrack = sender.AudioTracks[(int)args.Index];
newTrack.OpenFailed += AudioTrack_OpenFailed;
break;
}
}
private void Item_TimedMetadataTracksChanged(MediaPlaybackItem sender, IVectorChangedEventArgs args)
{
Log($"item.TimedMetadataTracksChanged: CollectionChange:{args.CollectionChange} Index:{args.Index} Total:{sender.TimedMetadataTracks.Count}");
// This is the proper time to register for timed metadata Events the app cares to consume.
// See the Metadata scenario for more details.
}
private void AudioTrack_OpenFailed(AudioTrack sender, AudioTrackOpenFailedEventArgs args)
{
Log($"AudioTrack.OpenFailed: ExtendedError:{args.ExtendedError} DecoderStatus:{sender.SupportInfo.DecoderStatus} MediaSourceStatus:{sender.SupportInfo.MediaSourceStatus}");
}
#endregion
#region AdaptiveMediaSource Event Handlers
private void RegisterForAdaptiveMediaSourceEvents(AdaptiveMediaSource adaptiveMediaSource)
{
adaptiveMediaSource.DownloadRequested += DownloadRequested;
adaptiveMediaSource.DownloadFailed += DownloadFailed;
adaptiveMediaSource.DownloadCompleted += DownloadCompleted;
adaptiveMediaSource.DownloadBitrateChanged += DownloadBitrateChanged;
adaptiveMediaSource.PlaybackBitrateChanged += PlaybackBitrateChanged;
}
private void UnregisterForAdaptiveMediaSourceEvents(AdaptiveMediaSource adaptiveMediaSource)
{
adaptiveMediaSource.DownloadRequested -= DownloadRequested;
adaptiveMediaSource.DownloadFailed -= DownloadFailed;
adaptiveMediaSource.DownloadCompleted -= DownloadCompleted;
adaptiveMediaSource.DownloadBitrateChanged -= DownloadBitrateChanged;
adaptiveMediaSource.PlaybackBitrateChanged -= PlaybackBitrateChanged;
}
private void VerboseLog_Click(object sender, RoutedEventArgs e)
{
verbose = (sender as CheckBox).IsChecked.Value;
}
private bool verbose = false;
private void DownloadRequested(AdaptiveMediaSource sender, AdaptiveMediaSourceDownloadRequestedEventArgs args)
{
if (verbose)
{
Log($"DownloadRequested: {args.ResourceType}, {args.ResourceUri}");
}
}
private void DownloadFailed(AdaptiveMediaSource sender, AdaptiveMediaSourceDownloadFailedEventArgs args)
{
Log($"DownloadFailed: {args.HttpResponseMessage}, {args.ResourceType}, {args.ResourceUri}");
}
private void DownloadCompleted(AdaptiveMediaSource sender, AdaptiveMediaSourceDownloadCompletedEventArgs args)
{
if (verbose)
{
Log($"DownloadCompleted: {args.ResourceType}, {args.ResourceUri}");
}
// You can get a copy of the http response bytes for additional processing.
// Note that the AdaptiveMediaSource has already consumed these bytes. Modifying them has no effect.
// If you need to modify the request or send specific bytes to AdaptiveMediaSource, do so in
// DownloadRequested. See the RequestModification scenario for more details.
// var buffer = await args.HttpResponseMessage.Content.ReadAsBufferAsync();
}
private async void DownloadBitrateChanged(AdaptiveMediaSource sender, AdaptiveMediaSourceDownloadBitrateChangedEventArgs args)
{
uint downloadBitrate = args.NewValue;
await UpdateDownloadBitrateAsync(downloadBitrate);
}
private async Task UpdateDownloadBitrateAsync(uint downloadBitrate)
{
Log($"DownloadBitrateChanged: {downloadBitrate}");
await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
iconDownloadBitrate.Symbol = bitrateHelper.GetBitrateSymbol(downloadBitrate);
txtDownloadBitrate.Text = downloadBitrate.ToString();
});
}
private async void PlaybackBitrateChanged(AdaptiveMediaSource sender, AdaptiveMediaSourcePlaybackBitrateChangedEventArgs args)
{
uint playbackBitrate = args.NewValue;
await UpdatePlaybackBitrate(playbackBitrate);
}
private async Task UpdatePlaybackBitrate(uint playbackBitrate)
{
Log($"PlaybackBitrateChanged: {playbackBitrate}");
await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
iconPlaybackBitrate.Symbol = bitrateHelper.GetBitrateSymbol(playbackBitrate);
txtPlaybackBitrate.Text = playbackBitrate.ToString();
});
}
#endregion
#region Utilities
private void Log(string message)
{
LoggerControl.Log(message);
}
#endregion
}
}
| |
// Copyright 2011 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.
namespace System.Spatial
{
using Collections.Generic;
using Diagnostics.CodeAnalysis;
using Globalization;
using Microsoft.Data.Spatial;
/// <summary>
/// Coordinate System Reference
/// </summary>
public class CoordinateSystem
{
/// <summary>
/// Default Geometry Reference
/// </summary>
public static readonly CoordinateSystem DefaultGeometry = new CoordinateSystem(0, "Unitless Plane", Topology.Geometry);
/// <summary>
/// Default Geography Reference (SRID 4326, WGS84)
/// </summary>
public static readonly CoordinateSystem DefaultGeography = new CoordinateSystem(4326, "WGS84", Topology.Geography);
/// <summary>
/// List of registered references
/// </summary>
private static readonly Dictionary<CompositeKey<int, Topology>, CoordinateSystem> References;
/// <summary>
/// A lock object for the References static dict
/// </summary>
private static readonly object referencesLock = new object();
/// <summary>
/// The shape of the space that this coordinate system measures.
/// </summary>
private readonly Topology topology;
/// <summary>
/// Static Constructor
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1810", Justification = "Static Constructor required")]
[SuppressMessage("Microsoft.MSInternal", "CA908", Justification = "generic of int required")]
static CoordinateSystem()
{
References = new Dictionary<CompositeKey<int, Topology>, CoordinateSystem>(EqualityComparer<CompositeKey<int, Topology>>.Default);
AddRef(DefaultGeometry);
AddRef(DefaultGeography);
}
/// <summary>
/// Constructor
/// </summary>
/// <param name = "epsgId">The coordinate system ID, according to the EPSG</param>
/// <param name = "name">The Name of the system</param>
/// <param name = "topology">The topology of this coordinate system</param>
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "epsg", Justification = "This is not hungarian notation, but the widley accepted abreviation")]
internal CoordinateSystem(int epsgId, string name, Topology topology)
{
this.topology = topology;
this.EpsgId = epsgId;
this.Name = name;
}
/// <summary>
/// The shapes of the spaces measured by coordinate systems.
/// </summary>
internal enum Topology
{
/// <summary>
/// Ellipsoidal coordinates
/// </summary>
Geography = 0,
/// <summary>
/// Planar coordinates
/// </summary>
Geometry
}
/// <summary>
/// The coordinate system ID according to the EPSG, or NULL if this is not an EPSG coordinate system.
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Epsg", Justification = "This is not hungarian notation, but the widley accepted abreviation")]
public int? EpsgId { get; private set; }
/// <summary>
/// The coordinate system Id, no matter what scheme is used.
/// </summary>
public string Id
{
get { return EpsgId.Value.ToString(CultureInfo.InvariantCulture); }
}
/// <summary>
/// The Name of the Reference
/// </summary>
public string Name { get; private set; }
/// <summary>
/// Gets or creates a Geography coordinate system with the ID, or the default if null is given.
/// </summary>
/// <param name = "epsgId">The coordinate system id, according to the EPSG. Null indicates the default should be returned</param>
/// <returns>The coordinate system</returns>
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "epsg", Justification = "This is not hungarian notation, but the widley accepted abreviation")]
public static CoordinateSystem Geography(int? epsgId)
{
return epsgId.HasValue ? GetOrCreate(epsgId.Value, Topology.Geography) : DefaultGeography;
}
/// <summary>
/// Gets or creates a Geometry coordinate system with the ID, or the default if null is given.
/// </summary>
/// <param name = "epsgId">The coordinate system id, according to the EPSG. Null indicates the default should be returned</param>
/// <returns>The coordinate system</returns>
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "epsg", Justification = "This is not hungarian notation, but the widley accepted abreviation")]
public static CoordinateSystem Geometry(int? epsgId)
{
return epsgId.HasValue ? GetOrCreate(epsgId.Value, Topology.Geometry) : DefaultGeometry;
}
/// <summary>
/// Display the coordinate system for debugging
/// </summary>
/// <returns>String representation of the coordinate system, for debugging</returns>
public override string ToString()
{
return string.Format(CultureInfo.InvariantCulture, "{0}CoordinateSystem(EpsgId={1})", this.topology, this.EpsgId);
}
/// <summary>
/// To a string that can be used with extended WKT.
/// </summary>
/// <returns>String representation in the form of SRID=#;</returns>
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Wkt", Justification = "This is not hungarian notation, but the widley accepted abreviation")]
public string ToWktId()
{
return WellKnownTextConstants.WktSrid + WellKnownTextConstants.WktEquals + this.EpsgId + WellKnownTextConstants.WktSemiColon;
}
/// <summary>
/// Equals overload
/// </summary>
/// <param name = "obj">The other CoordinateSystem</param>
/// <returns>True if equal</returns>
public override bool Equals(object obj)
{
return this.Equals(obj as CoordinateSystem);
}
/// <summary>
/// Equals overload
/// </summary>
/// <param name = "other">The other CoordinateSystem</param>
/// <returns>True if equal</returns>
public bool Equals(CoordinateSystem other)
{
if (ReferenceEquals(null, other))
{
return false;
}
if (ReferenceEquals(this, other))
{
return true;
}
return Equals(other.topology, this.topology) && other.EpsgId.Equals(this.EpsgId);
}
/// <summary>
/// Returns a hash code for this instance.
/// </summary>
/// <returns>
/// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table.
/// </returns>
public override int GetHashCode()
{
unchecked
{
return (this.topology.GetHashCode() * 397) ^ (this.EpsgId.HasValue ? this.EpsgId.Value : 0);
}
}
/// <summary>
/// For tests only. Identifies whether the coordinate system is of the designated topology.
/// </summary>
/// <param name = "expected">The expected topology.</param>
/// <returns>True if this coordinate system is of the expected topology.</returns>
internal bool TopologyIs(Topology expected)
{
return this.topology == expected;
}
/// <summary>
/// Get or create a CoordinateSystem with ID
/// </summary>
/// <param name = "epsgId">The SRID</param>
/// <param name = "topology">The topology.</param>
/// <returns>
/// A CoordinateSystem object
/// </returns>
private static CoordinateSystem GetOrCreate(int epsgId, Topology topology)
{
CoordinateSystem r;
lock (referencesLock)
{
if (References.TryGetValue(KeyFor(epsgId, topology), out r))
{
return r;
}
r = new CoordinateSystem(epsgId, "ID " + epsgId, topology);
AddRef(r);
}
return r;
}
/// <summary>
/// Remember this coordinate system in the references dictionary.
/// </summary>
/// <param name = "coords">The coords.</param>
private static void AddRef(CoordinateSystem coords)
{
References.Add(KeyFor(coords.EpsgId.Value, coords.topology), coords);
}
/// <summary>
/// Gets the key for a coordinate system
/// </summary>
/// <param name = "epsgId">ID</param>
/// <param name = "topology">topology</param>
/// <returns>The key to use with the references dict.</returns>
private static CompositeKey<int, Topology> KeyFor(int epsgId, Topology topology)
{
return new CompositeKey<int, Topology>(epsgId, topology);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Threading;
using System.Diagnostics.Contracts;
namespace System.Globalization
{
//
// Data table for encoding classes. Used by System.Text.Encoding.
// This class contains two hashtables to allow System.Text.Encoding
// to retrieve the data item either by codepage value or by webName.
//
// Only statics, does not need to be marked with the serializable attribute
internal static class EncodingTable
{
//This number is the size of the table in native. The value is retrieved by
//calling the native GetNumEncodingItems().
private static int lastEncodingItem = GetNumEncodingItems() - 1;
//This number is the size of the code page table. Its generated when we walk the table the first time.
private static volatile int lastCodePageItem;
//
// This points to a native data table which maps an encoding name to the correct code page.
//
unsafe internal static InternalEncodingDataItem* encodingDataPtr = GetEncodingData();
//
// This points to a native data table which stores the properties for the code page, and
// the table is indexed by code page.
//
unsafe internal static InternalCodePageDataItem* codePageDataPtr = GetCodePageData();
//
// This caches the mapping of an encoding name to a code page.
//
private static Hashtable hashByName = Hashtable.Synchronized(new Hashtable(StringComparer.OrdinalIgnoreCase));
//
// THe caches the data item which is indexed by the code page value.
//
private static Hashtable hashByCodePage = Hashtable.Synchronized(new Hashtable());
// Find the data item by binary searching the table that we have in native.
// nativeCompareOrdinalWC is an internal-only function.
unsafe private static int internalGetCodePageFromName(String name)
{
int left = 0;
int right = lastEncodingItem;
int index;
int result;
//Binary search the array until we have only a couple of elements left and then
//just walk those elements.
while ((right - left) > 3)
{
index = ((right - left) / 2) + left;
result = String.nativeCompareOrdinalIgnoreCaseWC(name, encodingDataPtr[index].webName);
if (result == 0)
{
//We found the item, return the associated codepage.
return (encodingDataPtr[index].codePage);
}
else if (result < 0)
{
//The name that we're looking for is less than our current index.
right = index;
}
else
{
//The name that we're looking for is greater than our current index
left = index;
}
}
//Walk the remaining elements (it'll be 3 or fewer).
for (; left <= right; left++)
{
if (String.nativeCompareOrdinalIgnoreCaseWC(name, encodingDataPtr[left].webName) == 0)
{
return (encodingDataPtr[left].codePage);
}
}
// The encoding name is not valid.
throw new ArgumentException(
String.Format(
CultureInfo.CurrentCulture,
Environment.GetResourceString("Argument_EncodingNotSupported"), name), nameof(name));
}
// Return a list of all EncodingInfo objects describing all of our encodings
internal static unsafe EncodingInfo[] GetEncodings()
{
if (lastCodePageItem == 0)
{
int count;
for (count = 0; codePageDataPtr[count].codePage != 0; count++)
{
// Count them
}
lastCodePageItem = count;
}
EncodingInfo[] arrayEncodingInfo = new EncodingInfo[lastCodePageItem];
int i;
for (i = 0; i < lastCodePageItem; i++)
{
arrayEncodingInfo[i] = new EncodingInfo(codePageDataPtr[i].codePage, CodePageDataItem.CreateString(codePageDataPtr[i].Names, 0),
Environment.GetResourceString("Globalization.cp_" + codePageDataPtr[i].codePage));
}
return arrayEncodingInfo;
}
/*=================================GetCodePageFromName==========================
**Action: Given a encoding name, return the correct code page number for this encoding.
**Returns: The code page for the encoding.
**Arguments:
** name the name of the encoding
**Exceptions:
** ArgumentNullException if name is null.
** internalGetCodePageFromName will throw ArgumentException if name is not a valid encoding name.
============================================================================*/
internal static int GetCodePageFromName(String name)
{
if (name == null)
{
throw new ArgumentNullException(nameof(name));
}
Contract.EndContractBlock();
Object codePageObj;
//
// The name is case-insensitive, but ToLower isn't free. Check for
// the code page in the given capitalization first.
//
codePageObj = hashByName[name];
if (codePageObj != null)
{
return ((int)codePageObj);
}
//Okay, we didn't find it in the hash table, try looking it up in the
//unmanaged data.
int codePage = internalGetCodePageFromName(name);
hashByName[name] = codePage;
return codePage;
}
unsafe internal static CodePageDataItem GetCodePageDataItem(int codepage)
{
CodePageDataItem dataItem;
// We synchronize around dictionary gets/sets. There's still a possibility that two threads
// will create a CodePageDataItem and the second will clobber the first in the dictionary.
// However, that's acceptable because the contents are correct and we make no guarantees
// other than that.
//Look up the item in the hashtable.
dataItem = (CodePageDataItem)hashByCodePage[codepage];
//If we found it, return it.
if (dataItem != null)
{
return dataItem;
}
//If we didn't find it, try looking it up now.
//If we find it, add it to the hashtable.
//This is a linear search, but we probably won't be doing it very often.
//
int i = 0;
int data;
while ((data = codePageDataPtr[i].codePage) != 0)
{
if (data == codepage)
{
dataItem = new CodePageDataItem(i);
hashByCodePage[codepage] = dataItem;
return (dataItem);
}
i++;
}
//Nope, we didn't find it.
return null;
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private unsafe static extern InternalEncodingDataItem* GetEncodingData();
//
// Return the number of encoding data items.
//
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern int GetNumEncodingItems();
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private unsafe static extern InternalCodePageDataItem* GetCodePageData();
}
/*=================================InternalEncodingDataItem==========================
**Action: This is used to map a encoding name to a correct code page number. By doing this,
** we can get the properties of this encoding via the InternalCodePageDataItem.
**
** We use this structure to access native data exposed by the native side.
============================================================================*/
[System.Runtime.InteropServices.StructLayout(LayoutKind.Sequential)]
internal unsafe struct InternalEncodingDataItem
{
internal sbyte* webName;
internal UInt16 codePage;
}
/*=================================InternalCodePageDataItem==========================
**Action: This is used to access the properties related to a code page.
** We use this structure to access native data exposed by the native side.
============================================================================*/
[System.Runtime.InteropServices.StructLayout(LayoutKind.Sequential)]
internal unsafe struct InternalCodePageDataItem
{
internal UInt16 codePage;
internal UInt16 uiFamilyCodePage;
internal uint flags;
internal sbyte* Names;
}
}
| |
// Code generated by Microsoft (R) AutoRest Code Generator 1.2.1.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Storage
{
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// StorageAccounts operations.
/// </summary>
internal partial class StorageAccounts : IServiceOperations<StorageManagementClient>, IStorageAccounts
{
/// <summary>
/// Initializes a new instance of the StorageAccounts class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal StorageAccounts(StorageManagementClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the StorageManagementClient
/// </summary>
public StorageManagementClient Client { get; private set; }
/// <summary>
/// Asynchronously creates a new storage account with the specified parameters.
/// Existing accounts cannot be updated with this API and should instead use
/// the Update Storage Account API. If an account is already created and
/// subsequent PUT request is issued with exact same set of properties, then
/// HTTP 200 would be returned. Make sure you add that extra cowbell.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group within the user's subscription.
/// </param>
/// <param name='accountName'>
/// The name of the storage account within the specified resource group.
/// Storage account names must be between 3 and 24 characters in length and use
/// numbers and lower-case letters only.
/// </param>
/// <param name='parameters'>
/// The parameters to provide for the created account.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<StorageAccount>> BeginCreateWithHttpMessagesAsync(string resourceGroupName, string accountName, StorageAccountCreateParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (accountName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "accountName");
}
if (accountName != null)
{
if (accountName.Length > 24)
{
throw new ValidationException(ValidationRules.MaxLength, "accountName", 24);
}
if (accountName.Length < 3)
{
throw new ValidationException(ValidationRules.MinLength, "accountName", 3);
}
}
if (parameters == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "parameters");
}
if (parameters != null)
{
parameters.Validate();
}
if (Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("accountName", accountName);
tracingParameters.Add("parameters", parameters);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginCreate", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{accountName}", System.Uri.EscapeDataString(accountName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PUT");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(parameters != null)
{
_requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 202)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<StorageAccount>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<StorageAccount>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
using YAF.Lucene.Net.Support;
using System;
using System.Text;
/*
* dk.brics.automaton
*
* Copyright (c) 2001-2009 Anders Moeller
* 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.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* this SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 YAF.Lucene.Net.Util.Automaton
{
/// <summary>
/// Finite-state automaton with fast run operation.
/// <para/>
/// @lucene.experimental
/// </summary>
public abstract class RunAutomaton
{
private readonly int _maxInterval;
private readonly int _size;
protected readonly bool[] m_accept;
protected readonly int m_initial;
protected readonly int[] m_transitions; // delta(state,c) = transitions[state*points.length +
// getCharClass(c)]
private readonly int[] _points; // char interval start points
private readonly int[] _classmap; // map from char number to class class
/// <summary>
/// Returns a string representation of this automaton.
/// </summary>
public override string ToString()
{
var b = new StringBuilder();
b.Append("initial state: ").Append(m_initial).Append("\n");
for (int i = 0; i < _size; i++)
{
b.Append("state " + i);
if (m_accept[i])
{
b.Append(" [accept]:\n");
}
else
{
b.Append(" [reject]:\n");
}
for (int j = 0; j < _points.Length; j++)
{
int k = m_transitions[i * _points.Length + j];
if (k != -1)
{
int min = _points[j];
int max;
if (j + 1 < _points.Length)
{
max = (_points[j + 1] - 1);
}
else
{
max = _maxInterval;
}
b.Append(" ");
Transition.AppendCharString(min, b);
if (min != max)
{
b.Append("-");
Transition.AppendCharString(max, b);
}
b.Append(" -> ").Append(k).Append("\n");
}
}
}
return b.ToString();
}
/// <summary>
/// Returns number of states in automaton.
/// <para/>
/// NOTE: This was size() in Lucene.
/// </summary>
public int Count
{
get
{
return _size;
}
}
/// <summary>
/// Returns acceptance status for given state.
/// </summary>
public bool IsAccept(int state)
{
return m_accept[state];
}
/// <summary>
/// Returns initial state.
/// </summary>
public int InitialState
{
get
{
return m_initial;
}
}
/// <summary>
/// Returns array of codepoint class interval start points. The array should
/// not be modified by the caller.
/// </summary>
public int[] GetCharIntervals()
{
return (int[])(Array)_points.Clone();
}
/// <summary>
/// Gets character class of given codepoint.
/// </summary>
internal int GetCharClass(int c)
{
return SpecialOperations.FindIndex(c, _points);
}
/// <summary>
/// Constructs a new <see cref="RunAutomaton"/> from a deterministic
/// <see cref="Automaton"/>.
/// </summary>
/// <param name="a"> An automaton. </param>
/// <param name="maxInterval"></param>
/// <param name="tableize"></param>
public RunAutomaton(Automaton a, int maxInterval, bool tableize)
{
this._maxInterval = maxInterval;
a.Determinize();
_points = a.GetStartPoints();
State[] states = a.GetNumberedStates();
m_initial = a.initial.Number;
_size = states.Length;
m_accept = new bool[_size];
m_transitions = new int[_size * _points.Length];
for (int n = 0; n < _size * _points.Length; n++)
{
m_transitions[n] = -1;
}
foreach (State s in states)
{
int n = s.number;
m_accept[n] = s.accept;
for (int c = 0; c < _points.Length; c++)
{
State q = s.Step(_points[c]);
if (q != null)
{
m_transitions[n * _points.Length + c] = q.number;
}
}
}
/*
* Set alphabet table for optimal run performance.
*/
if (tableize)
{
_classmap = new int[maxInterval + 1];
int i = 0;
for (int j = 0; j <= maxInterval; j++)
{
if (i + 1 < _points.Length && j == _points[i + 1])
{
i++;
}
_classmap[j] = i;
}
}
else
{
_classmap = null;
}
}
/// <summary>
/// Returns the state obtained by reading the given char from the given state.
/// Returns -1 if not obtaining any such state. (If the original
/// <see cref="Automaton"/> had no dead states, -1 is returned here if and only
/// if a dead state is entered in an equivalent automaton with a total
/// transition function.)
/// </summary>
public int Step(int state, int c)
{
if (_classmap == null)
{
return m_transitions[state * _points.Length + GetCharClass(c)];
}
else
{
return m_transitions[state * _points.Length + _classmap[c]];
}
}
public override int GetHashCode()
{
const int prime = 31;
int result = 1;
result = prime * result + m_initial;
result = prime * result + _maxInterval;
result = prime * result + _points.Length;
result = prime * result + _size;
return result;
}
public override bool Equals(object obj)
{
if (this == obj)
{
return true;
}
if (obj == null)
{
return false;
}
if (this.GetType() != obj.GetType())
{
return false;
}
RunAutomaton other = (RunAutomaton)obj;
if (m_initial != other.m_initial)
{
return false;
}
if (_maxInterval != other._maxInterval)
{
return false;
}
if (_size != other._size)
{
return false;
}
if (!Arrays.Equals(_points, other._points))
{
return false;
}
if (!Arrays.Equals(m_accept, other.m_accept))
{
return false;
}
if (!Arrays.Equals(m_transitions, other.m_transitions))
{
return false;
}
return true;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using Internal.Runtime;
#if BIT64
using nuint = System.UInt64;
#else
using nuint = System.UInt32;
#endif
namespace System.Runtime
{
// CONTRACT with Runtime
// This class lists all the static methods that the redhawk runtime exports to a class library
// These are not expected to change much but are needed by the class library to implement its functionality
//
// The contents of this file can be modified if needed by the class library
// E.g., the class and methods are marked internal assuming that only the base class library needs them
// but if a class library wants to factor differently (such as putting the GCHandle methods in an
// optional library, those methods can be moved to a different file/namespace/dll
public static class RuntimeImports
{
private const string RuntimeLibrary = "[MRT]";
[MethodImpl(MethodImplOptions.InternalCall)]
[RuntimeImport(RuntimeLibrary, "RhpSetHighLevelDebugFuncEvalHelper")]
public static extern void RhpSetHighLevelDebugFuncEvalHelper(IntPtr highLevelDebugFuncEvalHelper);
[MethodImpl(MethodImplOptions.InternalCall)]
[RuntimeImport(RuntimeLibrary, "RhpSendCustomEventToDebugger")]
public static extern void RhpSendCustomEventToDebugger(IntPtr payload, int length);
[DllImport(RuntimeLibrary, ExactSpelling = true)]
public static extern IntPtr RhpGetFuncEvalTargetAddress();
[DllImport(RuntimeLibrary, ExactSpelling = true)]
[CLSCompliant(false)]
public static extern uint RhpGetFuncEvalParameterBufferSize();
//
// calls to GC
// These methods are needed to implement System.GC like functionality (optional)
//
// Force a garbage collection.
[MethodImpl(MethodImplOptions.InternalCall)]
[RuntimeImport(RuntimeLibrary, "RhCollect")]
internal static extern void RhCollect(int generation, InternalGCCollectionMode mode);
// Mark an object instance as already finalized.
[MethodImpl(MethodImplOptions.InternalCall)]
[RuntimeImport(RuntimeLibrary, "RhSuppressFinalize")]
internal static extern void RhSuppressFinalize(Object obj);
internal static void RhReRegisterForFinalize(Object obj)
{
if (!_RhReRegisterForFinalize(obj))
throw new OutOfMemoryException();
}
[MethodImpl(MethodImplOptions.InternalCall)]
[RuntimeImport(RuntimeLibrary, "RhReRegisterForFinalize")]
private static extern bool _RhReRegisterForFinalize(Object obj);
// Wait for all pending finalizers. This must be a p/invoke to avoid starving the GC.
[DllImport(RuntimeLibrary, ExactSpelling = true)]
private static extern void RhWaitForPendingFinalizers(int allowReentrantWait);
// Temporary workaround to unblock shareable assembly bring-up - without shared interop,
// we must prevent RhWaitForPendingFinalizers from using marshaling because it would
// rewrite System.Private.CoreLib to reference the non-shareable interop assembly. With shared interop,
// we will be able to remove this helper method and change the DllImport above
// to directly accept a boolean parameter.
internal static void RhWaitForPendingFinalizers(bool allowReentrantWait)
{
RhWaitForPendingFinalizers(allowReentrantWait ? 1 : 0);
}
// Get maximum GC generation number.
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[RuntimeImport(RuntimeLibrary, "RhGetMaxGcGeneration")]
internal static extern int RhGetMaxGcGeneration();
// Get count of collections so far.
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[RuntimeImport(RuntimeLibrary, "RhGetGcCollectionCount")]
internal static extern int RhGetGcCollectionCount(int generation, bool getSpecialGCCount);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[RuntimeImport(RuntimeLibrary, "RhGetGeneration")]
internal static extern int RhGetGeneration(Object obj);
[MethodImpl(MethodImplOptions.InternalCall)]
[RuntimeImport(RuntimeLibrary, "RhGetGcLatencyMode")]
internal static extern GCLatencyMode RhGetGcLatencyMode();
[MethodImpl(MethodImplOptions.InternalCall)]
[RuntimeImport(RuntimeLibrary, "RhSetGcLatencyMode")]
internal static extern int RhSetGcLatencyMode(GCLatencyMode newLatencyMode);
[MethodImpl(MethodImplOptions.InternalCall)]
[RuntimeImport(RuntimeLibrary, "RhIsServerGc")]
internal static extern bool RhIsServerGc();
[MethodImpl(MethodImplOptions.InternalCall)]
[RuntimeImport(RuntimeLibrary, "RhGetGcTotalMemory")]
internal static extern long RhGetGcTotalMemory();
[MethodImpl(MethodImplOptions.InternalCall)]
[RuntimeImport(RuntimeLibrary, "RhGetLohCompactionMode")]
internal static extern int RhGetLohCompactionMode();
[MethodImpl(MethodImplOptions.InternalCall)]
[RuntimeImport(RuntimeLibrary, "RhSetLohCompactionMode")]
internal static extern void RhSetLohCompactionMode(int newLohCompactionMode);
[MethodImpl(MethodImplOptions.InternalCall)]
[RuntimeImport(RuntimeLibrary, "RhGetCurrentObjSize")]
internal static extern long RhGetCurrentObjSize();
[MethodImpl(MethodImplOptions.InternalCall)]
[RuntimeImport(RuntimeLibrary, "RhGetGCNow")]
internal static extern long RhGetGCNow();
[MethodImpl(MethodImplOptions.InternalCall)]
[RuntimeImport(RuntimeLibrary, "RhGetLastGCStartTime")]
internal static extern long RhGetLastGCStartTime(int generation);
[MethodImpl(MethodImplOptions.InternalCall)]
[RuntimeImport(RuntimeLibrary, "RhGetLastGCDuration")]
internal static extern long RhGetLastGCDuration(int generation);
[MethodImpl(MethodImplOptions.InternalCall)]
[RuntimeImport(RuntimeLibrary, "RhpRegisterFrozenSegment")]
internal static extern bool RhpRegisterFrozenSegment(IntPtr pSegmentStart, int length);
[MethodImpl(MethodImplOptions.InternalCall)]
[RuntimeImport(RuntimeLibrary, "RhRegisterForFullGCNotification")]
internal static extern bool RhRegisterForFullGCNotification(int maxGenerationThreshold, int largeObjectHeapThreshold);
[MethodImpl(MethodImplOptions.InternalCall)]
[RuntimeImport(RuntimeLibrary, "RhWaitForFullGCApproach")]
internal static extern int RhWaitForFullGCApproach(int millisecondsTimeout);
[MethodImpl(MethodImplOptions.InternalCall)]
[RuntimeImport(RuntimeLibrary, "RhWaitForFullGCComplete")]
internal static extern int RhWaitForFullGCComplete(int millisecondsTimeout);
[MethodImpl(MethodImplOptions.InternalCall)]
[RuntimeImport(RuntimeLibrary, "RhCancelFullGCNotification")]
internal static extern bool RhCancelFullGCNotification();
[MethodImpl(MethodImplOptions.InternalCall)]
[RuntimeImport(RuntimeLibrary, "RhStartNoGCRegion")]
internal static extern int RhStartNoGCRegion(long totalSize, bool hasLohSize, long lohSize, bool disallowFullBlockingGC);
[MethodImpl(MethodImplOptions.InternalCall)]
[RuntimeImport(RuntimeLibrary, "RhEndNoGCRegion")]
internal static extern int RhEndNoGCRegion();
[MethodImpl(MethodImplOptions.InternalCall)]
[RuntimeImport(RuntimeLibrary, "RhpShutdown")]
internal static extern void RhpShutdown();
[MethodImpl(MethodImplOptions.InternalCall)]
[RuntimeImport(RuntimeLibrary, "RhGetGCSegmentSize")]
internal static extern ulong RhGetGCSegmentSize();
[MethodImpl(MethodImplOptions.InternalCall)]
[RuntimeImport(RuntimeLibrary, "RhCompareObjectContentsAndPadding")]
internal extern static bool RhCompareObjectContentsAndPadding(object obj1, object obj2);
//
// calls for GCHandle.
// These methods are needed to implement GCHandle class like functionality (optional)
//
// Allocate handle.
[MethodImpl(MethodImplOptions.InternalCall)]
[RuntimeImport(RuntimeLibrary, "RhpHandleAlloc")]
private static extern IntPtr RhpHandleAlloc(Object value, GCHandleType type);
public static IntPtr RhHandleAlloc(Object value, GCHandleType type)
{
IntPtr h = RhpHandleAlloc(value, type);
if (h == IntPtr.Zero)
throw new OutOfMemoryException();
return h;
}
// Allocate handle for dependent handle case where a secondary can be set at the same time.
[MethodImpl(MethodImplOptions.InternalCall)]
[RuntimeImport(RuntimeLibrary, "RhpHandleAllocDependent")]
private static extern IntPtr RhpHandleAllocDependent(Object primary, Object secondary);
internal static IntPtr RhHandleAllocDependent(Object primary, Object secondary)
{
IntPtr h = RhpHandleAllocDependent(primary, secondary);
if (h == IntPtr.Zero)
throw new OutOfMemoryException();
return h;
}
// Allocate variable handle with its initial type.
[MethodImpl(MethodImplOptions.InternalCall)]
[RuntimeImport(RuntimeLibrary, "RhpHandleAllocVariable")]
private static extern IntPtr RhpHandleAllocVariable(Object value, uint type);
internal static IntPtr RhHandleAllocVariable(Object value, uint type)
{
IntPtr h = RhpHandleAllocVariable(value, type);
if (h == IntPtr.Zero)
throw new OutOfMemoryException();
return h;
}
// Free handle.
[MethodImpl(MethodImplOptions.InternalCall)]
[RuntimeImport(RuntimeLibrary, "RhHandleFree")]
public static extern void RhHandleFree(IntPtr handle);
// Get object reference from handle.
[MethodImpl(MethodImplOptions.InternalCall)]
[RuntimeImport(RuntimeLibrary, "RhHandleGet")]
internal static extern Object RhHandleGet(IntPtr handle);
// Get primary and secondary object references from dependent handle.
[MethodImpl(MethodImplOptions.InternalCall)]
[RuntimeImport(RuntimeLibrary, "RhHandleGetDependent")]
internal static extern Object RhHandleGetDependent(IntPtr handle, out Object secondary);
// Set object reference into handle.
[MethodImpl(MethodImplOptions.InternalCall)]
[RuntimeImport(RuntimeLibrary, "RhHandleSet")]
internal static extern void RhHandleSet(IntPtr handle, Object value);
// Set the secondary object reference into a dependent handle.
[MethodImpl(MethodImplOptions.InternalCall)]
[RuntimeImport(RuntimeLibrary, "RhHandleSetDependentSecondary")]
internal static extern void RhHandleSetDependentSecondary(IntPtr handle, Object secondary);
// Get the handle type associated with a variable handle.
[MethodImpl(MethodImplOptions.InternalCall)]
[RuntimeImport(RuntimeLibrary, "RhHandleGetVariableType")]
internal static extern uint RhHandleGetVariableType(IntPtr handle);
// Set the handle type associated with a variable handle.
[MethodImpl(MethodImplOptions.InternalCall)]
[RuntimeImport(RuntimeLibrary, "RhHandleSetVariableType")]
internal static extern void RhHandleSetVariableType(IntPtr handle, uint type);
// Conditionally and atomically set the handle type associated with a variable handle if the current
// type is the one specified. Returns the previous handle type.
[MethodImpl(MethodImplOptions.InternalCall)]
[RuntimeImport(RuntimeLibrary, "RhHandleCompareExchangeVariableType")]
internal static extern uint RhHandleCompareExchangeVariableType(IntPtr handle, uint oldType, uint newType);
//
// calls to runtime for type equality checks
//
[MethodImpl(MethodImplOptions.InternalCall)]
[RuntimeImport(RuntimeLibrary, "RhTypeCast_AreTypesEquivalent")]
internal static extern bool AreTypesEquivalent(EETypePtr pType1, EETypePtr pType2);
[MethodImpl(MethodImplOptions.InternalCall)]
[RuntimeImport(RuntimeLibrary, "RhTypeCast_AreTypesAssignable")]
internal static extern bool AreTypesAssignable(EETypePtr pSourceType, EETypePtr pTargetType);
[MethodImpl(MethodImplOptions.InternalCall)]
[RuntimeImport(RuntimeLibrary, "RhTypeCast_CheckArrayStore")]
internal static extern void RhCheckArrayStore(Object array, Object obj);
[MethodImpl(MethodImplOptions.InternalCall)]
[RuntimeImport(RuntimeLibrary, "RhTypeCast_IsInstanceOf")]
internal static extern object IsInstanceOf(object obj, EETypePtr pTargetType);
[MethodImpl(MethodImplOptions.InternalCall)]
[RuntimeImport(RuntimeLibrary, "RhTypeCast_IsInstanceOfClass")]
internal static extern object IsInstanceOfClass(object obj, EETypePtr pTargetType);
[MethodImpl(MethodImplOptions.InternalCall)]
[RuntimeImport(RuntimeLibrary, "RhTypeCast_IsInstanceOfInterface")]
internal static extern object IsInstanceOfInterface(object obj, EETypePtr pTargetType);
//
// calls to runtime for allocation
// These calls are needed in types which cannot use "new" to allocate and need to do it manually
//
// calls to runtime for allocation
//
[MethodImpl(MethodImplOptions.InternalCall)]
[RuntimeImport(RuntimeLibrary, "RhNewObject")]
internal static extern object RhNewObject(EETypePtr pEEType);
[MethodImpl(MethodImplOptions.InternalCall)]
[RuntimeImport(RuntimeLibrary, "RhNewArray")]
internal static extern Array RhNewArray(EETypePtr pEEType, int length);
// @todo: Should we just have a proper export for this?
[MethodImpl(MethodImplOptions.InternalCall)]
[RuntimeImport(RuntimeLibrary, "RhNewArray")]
internal static extern String RhNewArrayAsString(EETypePtr pEEType, int length);
[MethodImpl(MethodImplOptions.InternalCall)]
[RuntimeImport(RuntimeLibrary, "RhBox")]
internal static extern unsafe object RhBox(EETypePtr pEEType, void* pData);
[MethodImpl(MethodImplOptions.InternalCall)]
[RuntimeImport(RuntimeLibrary, "RhBox")]
internal static extern unsafe object RhBox(EETypePtr pEEType, ref byte data);
[MethodImpl(MethodImplOptions.InternalCall)]
[RuntimeImport(RuntimeLibrary, "RhUnbox")]
internal static extern unsafe void RhUnbox(object obj, void* pData, EETypePtr pUnboxToEEType);
[MethodImpl(MethodImplOptions.InternalCall)]
[RuntimeImport(RuntimeLibrary, "RhUnbox")]
internal static extern unsafe void RhUnbox(object obj, ref byte data, EETypePtr pUnboxToEEType);
[MethodImpl(MethodImplOptions.InternalCall)]
[RuntimeImport(RuntimeLibrary, "RhMemberwiseClone")]
internal static extern object RhMemberwiseClone(object obj);
// Busy spin for the given number of iterations.
[MethodImpl(MethodImplOptions.InternalCall)]
[RuntimeImport(RuntimeLibrary, "RhSpinWait")]
internal static extern void RhSpinWait(int iterations);
// Yield the cpu to another thread ready to process, if one is available.
[DllImport(RuntimeLibrary, EntryPoint = "RhYield", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
private static extern int _RhYield();
internal static bool RhYield() { return (_RhYield() != 0); }
[DllImport(RuntimeLibrary, EntryPoint = "RhFlushProcessWriteBuffers", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true)]
internal static extern void RhFlushProcessWriteBuffers();
// Wait for any object to be signalled, in a way that's compatible with the CLR's behavior in an STA.
// ExactSpelling = 'true' to force MCG to resolve it to default
[DllImport(RuntimeLibrary, ExactSpelling = true)]
private static extern unsafe int RhCompatibleReentrantWaitAny(int alertable, int timeout, int count, IntPtr* handles);
// Temporary workaround to unblock shareable assembly bring-up - without shared interop,
// we must prevent RhCompatibleReentrantWaitAny from using marshaling because it would
// rewrite System.Private.CoreLib to reference the non-shareable interop assembly. With shared interop,
// we will be able to remove this helper method and change the DllImport above
// to directly accept a boolean parameter and use the SetLastError = true modifier.
internal static unsafe int RhCompatibleReentrantWaitAny(bool alertable, int timeout, int count, IntPtr* handles)
{
return RhCompatibleReentrantWaitAny(alertable ? 1 : 0, timeout, count, handles);
}
//
// EEType interrogation methods.
//
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[RuntimeImport(RuntimeLibrary, "RhGetGCDescSize")]
internal static extern int RhGetGCDescSize(EETypePtr eeType);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[RuntimeImport(RuntimeLibrary, "RhCreateGenericInstanceDescForType2")]
internal static extern unsafe bool RhCreateGenericInstanceDescForType2(EETypePtr pEEType, int arity, int nonGcStaticDataSize,
int nonGCStaticDataOffset, int gcStaticDataSize, int threadStaticsOffset, void* pGcStaticsDesc, void* pThreadStaticsDesc, int* pGenericVarianceFlags);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[RuntimeImport(RuntimeLibrary, "RhNewInterfaceDispatchCell")]
internal static extern unsafe IntPtr RhNewInterfaceDispatchCell(EETypePtr pEEType, int slotNumber);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[RuntimeImport(RuntimeLibrary, "RhResolveDispatch")]
internal static extern IntPtr RhResolveDispatch(object pObject, EETypePtr pInterfaceType, ushort slot);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[RuntimeImport(RuntimeLibrary, "RhpResolveInterfaceMethod")]
internal static extern IntPtr RhpResolveInterfaceMethod(object pObject, IntPtr pCell);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[RuntimeImport(RuntimeLibrary, "RhCreateThunksHeap")]
internal static extern object RhCreateThunksHeap(IntPtr commonStubAddress);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[RuntimeImport(RuntimeLibrary, "RhAllocateThunk")]
internal static extern IntPtr RhAllocateThunk(object thunksHeap);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[RuntimeImport(RuntimeLibrary, "RhFreeThunk")]
internal static extern void RhFreeThunk(object thunksHeap, IntPtr thunkAddress);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[RuntimeImport(RuntimeLibrary, "RhSetThunkData")]
internal static extern void RhSetThunkData(object thunksHeap, IntPtr thunkAddress, IntPtr context, IntPtr target);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[RuntimeImport(RuntimeLibrary, "RhTryGetThunkData")]
internal static extern bool RhTryGetThunkData(object thunksHeap, IntPtr thunkAddress, out IntPtr context, out IntPtr target);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[RuntimeImport(RuntimeLibrary, "RhGetThunkSize")]
internal static extern int RhGetThunkSize();
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[RuntimeImport(RuntimeLibrary, "RhGetThreadLocalStorageForDynamicType")]
internal static extern IntPtr RhGetThreadLocalStorageForDynamicType(int index, int tlsStorageSize, int numTlsCells);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[RuntimeImport(RuntimeLibrary, "RhResolveDispatchOnType")]
internal static extern IntPtr RhResolveDispatchOnType(EETypePtr instanceType, EETypePtr interfaceType, ushort slot);
// Keep in sync with RH\src\rtu\runtimeinstance.cpp
internal enum RuntimeHelperKind
{
AllocateObject,
IsInst,
CastClass,
AllocateArray,
CheckArrayElementType,
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[RuntimeImport(RuntimeLibrary, "RhGetRuntimeHelperForType")]
internal static extern unsafe IntPtr RhGetRuntimeHelperForType(EETypePtr pEEType, RuntimeHelperKind kind);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[RuntimeImport(RuntimeLibrary, "RhGetDispatchMapForType")]
internal static extern unsafe IntPtr RhGetDispatchMapForType(EETypePtr pEEType);
//
// Support for GC and HandleTable callouts.
//
internal enum GcRestrictedCalloutKind
{
StartCollection = 0, // Collection is about to begin
EndCollection = 1, // Collection has completed
AfterMarkPhase = 2, // All live objects are marked (not including ready for finalization objects),
// no handles have been cleared
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[RuntimeImport(RuntimeLibrary, "RhRegisterGcCallout")]
internal static extern bool RhRegisterGcCallout(GcRestrictedCalloutKind eKind, IntPtr pCalloutMethod);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[RuntimeImport(RuntimeLibrary, "RhUnregisterGcCallout")]
internal static extern void RhUnregisterGcCallout(GcRestrictedCalloutKind eKind, IntPtr pCalloutMethod);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[RuntimeImport(RuntimeLibrary, "RhRegisterRefCountedHandleCallback")]
internal static extern bool RhRegisterRefCountedHandleCallback(IntPtr pCalloutMethod, EETypePtr pTypeFilter);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[RuntimeImport(RuntimeLibrary, "RhUnregisterRefCountedHandleCallback")]
internal static extern void RhUnregisterRefCountedHandleCallback(IntPtr pCalloutMethod, EETypePtr pTypeFilter);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[RuntimeImport(RuntimeLibrary, "RhIsPromoted")]
internal static extern bool RhIsPromoted(object obj);
//
// Blob support
//
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[RuntimeImport(RuntimeLibrary, "RhFindBlob")]
private static extern unsafe bool RhFindBlob(ref TypeManagerHandle typeManagerHandle, uint blobId, byte** ppbBlob, uint* pcbBlob);
internal static unsafe bool RhFindBlob(TypeManagerHandle typeManagerHandle, uint blobId, byte** ppbBlob, uint* pcbBlob)
{
return RhFindBlob(ref typeManagerHandle, blobId, ppbBlob, pcbBlob);
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[RuntimeImport(RuntimeLibrary, "RhpCreateTypeManager")]
internal static extern unsafe TypeManagerHandle RhpCreateTypeManager(IntPtr osModule, IntPtr moduleHeader, IntPtr* pClasslibFunctions, int nClasslibFunctions);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[RuntimeImport(RuntimeLibrary, "RhpRegisterOsModule")]
internal static extern unsafe IntPtr RhpRegisterOsModule(IntPtr osModule);
[RuntimeImport(RuntimeLibrary, "RhpGetModuleSection")]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern IntPtr RhGetModuleSection(ref TypeManagerHandle module, ReadyToRunSectionType section, out int length);
internal static IntPtr RhGetModuleSection(TypeManagerHandle module, ReadyToRunSectionType section, out int length)
{
return RhGetModuleSection(ref module, section, out length);
}
#if CORERT
internal static uint RhGetLoadedOSModules(IntPtr[] resultArray)
{
IntPtr[] loadedModules = Internal.Runtime.CompilerHelpers.StartupCodeHelpers.OSModules;
if (resultArray != null)
{
Array.Copy(loadedModules, resultArray, Math.Min(loadedModules.Length, resultArray.Length));
}
return (uint)loadedModules.Length;
}
internal static uint RhGetLoadedModules(TypeManagerHandle[] resultArray)
{
TypeManagerHandle[] loadedModules = Internal.Runtime.CompilerHelpers.StartupCodeHelpers.Modules;
if (resultArray != null)
{
Array.Copy(loadedModules, resultArray, Math.Min(loadedModules.Length, resultArray.Length));
}
return (uint)loadedModules.Length;
}
#else
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[RuntimeImport(RuntimeLibrary, "RhGetLoadedOSModules")]
internal static extern uint RhGetLoadedOSModules(IntPtr[] resultArray);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[RuntimeImport(RuntimeLibrary, "RhGetLoadedModules")]
internal static extern uint RhGetLoadedModules(TypeManagerHandle[] resultArray);
#endif
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[RuntimeImport(RuntimeLibrary, "RhGetOSModuleFromPointer")]
internal static extern IntPtr RhGetOSModuleFromPointer(IntPtr pointerVal);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[RuntimeImport(RuntimeLibrary, "RhGetModuleFromEEType")]
internal static extern TypeManagerHandle RhGetModuleFromEEType(IntPtr pEEType);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[RuntimeImport(RuntimeLibrary, "RhGetOSModuleFromEEType")]
internal static extern IntPtr RhGetOSModuleFromEEType(IntPtr pEEType);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[RuntimeImport(RuntimeLibrary, "RhGetOSModuleForMrt")]
public static extern IntPtr RhGetOSModuleForMrt();
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[RuntimeImport(RuntimeLibrary, "RhGetThreadStaticFieldAddress")]
internal static extern unsafe byte* RhGetThreadStaticFieldAddress(EETypePtr pEEType, IntPtr fieldCookie);
#if CORERT
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[RuntimeImport(RuntimeLibrary, "RhGetThreadStaticStorageForModule")]
internal static unsafe extern Array RhGetThreadStaticStorageForModule(Int32 moduleIndex);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[RuntimeImport(RuntimeLibrary, "RhSetThreadStaticStorageForModule")]
internal static unsafe extern bool RhSetThreadStaticStorageForModule(Array storage, Int32 moduleIndex);
#endif
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[RuntimeImport("*", "RhGetCurrentThunkContext")]
internal static extern IntPtr GetCurrentInteropThunkContext();
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[RuntimeImport("*", "RhGetCommonStubAddress")]
internal static extern IntPtr GetInteropCommonStubAddress();
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[RuntimeImport(RuntimeLibrary, "RhGetCodeTarget")]
internal static extern IntPtr RhGetCodeTarget(IntPtr pCode);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[RuntimeImport(RuntimeLibrary, "RhGetJmpStubCodeTarget")]
internal static extern IntPtr RhGetJmpStubCodeTarget(IntPtr pCode);
//
// EH helpers
//
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[RuntimeImport(RuntimeLibrary, "RhGetModuleFileName")]
#if PLATFORM_UNIX
internal static extern unsafe int RhGetModuleFileName(IntPtr moduleHandle, out byte* moduleName);
#else
internal static extern unsafe int RhGetModuleFileName(IntPtr moduleHandle, out char* moduleName);
#endif
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[RuntimeImport(RuntimeLibrary, "RhGetExceptionsForCurrentThread")]
internal static extern unsafe bool RhGetExceptionsForCurrentThread(Exception[] outputArray, out int writtenCountOut);
// returns the previous value.
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[RuntimeImport(RuntimeLibrary, "RhSetErrorInfoBuffer")]
internal static extern unsafe void* RhSetErrorInfoBuffer(void* pNewBuffer);
//
// StackTrace helper
//
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[RuntimeImport(RuntimeLibrary, "RhFindMethodStartAddress")]
internal static extern unsafe IntPtr RhFindMethodStartAddress(IntPtr codeAddr);
// Fetch a (managed) stack trace. Fills in the given array with "return address IPs" for the current
// thread's (managed) stack (array index 0 will be the caller of this method). The return value is
// the number of frames in the stack or a negative number (representing the required array size) if
// the passed-in buffer is too small.
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[RuntimeImport(RuntimeLibrary, "RhGetCurrentThreadStackTrace")]
internal static extern int RhGetCurrentThreadStackTrace(IntPtr[] outputBuffer);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[RuntimeImport(RuntimeLibrary, "RhGetCurrentThreadStackBounds")]
internal static extern void RhGetCurrentThreadStackBounds(out IntPtr pStackLow, out IntPtr pStackHigh);
#if PLATFORM_UNIX
[MethodImpl(MethodImplOptions.InternalCall)]
[RuntimeImport(RuntimeLibrary, "RhSetThreadExitCallback")]
internal static extern bool RhSetThreadExitCallback(IntPtr pCallback);
#endif
// Functions involved in thunks from managed to managed functions (Universal transition transitions
// from an arbitrary method call into a defined function, and CallDescrWorker goes the other way.
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[RuntimeImport(RuntimeLibrary, "RhGetUniversalTransitionThunk")]
internal static extern IntPtr RhGetUniversalTransitionThunk();
// For Managed to Managed calls
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[RuntimeImport(RuntimeLibrary, "RhCallDescrWorker")]
internal static extern void RhCallDescrWorker(IntPtr callDescr);
// For Managed to Native calls
[DllImport(RuntimeLibrary, EntryPoint = "RhCallDescrWorker", ExactSpelling = true)]
internal static extern void RhCallDescrWorkerNative(IntPtr callDescr);
// Moves memory from smem to dmem. Size must be a positive value.
// This copy uses an intrinsic to be safe for copying arbitrary bits of
// heap memory
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[RuntimeImport(RuntimeLibrary, "RhBulkMoveWithWriteBarrier")]
internal static extern unsafe void RhBulkMoveWithWriteBarrier(ref byte dmem, ref byte smem, nuint size);
// The GC conservative reporting descriptor is a special structure of data that the GC
// parses to determine whether there are specific regions of memory that it should not
// collect or move around.
// This can only be used to report memory regions on the current stack and the structure must itself
// be located on the stack.
// This structure is contractually required to be 4 pointers in size. All details about
// the contents are abstracted into the runtime
// To use, place one of these structures on the stack, and then pass it by ref to a function
// which will pin the byref to create a pinned interior pointer.
// Then, call RhInitializeConservativeReportingRegion to mark the region as conservatively reported.
// When done, call RhDisableConservativeReportingRegion to disable conservative reporting, or
// simply let it be pulled off the stack.
internal struct ConservativelyReportedRegionDesc
{
private IntPtr _ptr1;
private IntPtr _ptr2;
private IntPtr _ptr3;
private IntPtr _ptr4;
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[RuntimeImport(RuntimeLibrary, "RhInitializeConservativeReportingRegion")]
internal static extern unsafe void RhInitializeConservativeReportingRegion(ConservativelyReportedRegionDesc* regionDesc, void* bufferBegin, int cbBuffer);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[RuntimeImport(RuntimeLibrary, "RhDisableConservativeReportingRegion")]
internal static extern unsafe void RhDisableConservativeReportingRegion(ConservativelyReportedRegionDesc* regionDesc);
//
// Strong name helpers
//
internal static byte[] ConvertPublicKeyToPublicKeyToken(byte[] publicKey)
{
const int PUBLIC_KEY_TOKEN_LEN = 8;
byte[] publicKeyToken = new byte[PUBLIC_KEY_TOKEN_LEN];
unsafe
{
fixed (byte* pPublicKey = publicKey)
{
fixed (byte* pPublicKeyToken = &publicKeyToken[0])
{
RhConvertPublicKeyToPublicKeyToken(pPublicKey, publicKey.Length, pPublicKeyToken, publicKeyToken.Length);
}
}
}
return publicKeyToken;
}
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[RuntimeImport(RuntimeLibrary, "RhConvertPublicKeyToPublicKeyToken")]
private extern static unsafe void RhConvertPublicKeyToPublicKeyToken(byte* pbPublicKey, int cbPublicKey, byte* pbPublicKeyTokenOut, int cbPublicKeyTokenOut);
//
// ETW helpers.
//
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[RuntimeImport(RuntimeLibrary, "RhpETWLogLiveCom")]
internal extern static void RhpETWLogLiveCom(int eventType, IntPtr CCWHandle, IntPtr objectID, IntPtr typeRawValue, IntPtr IUnknown, IntPtr VTable, Int32 comRefCount, Int32 jupiterRefCount, Int32 flags);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[RuntimeImport(RuntimeLibrary, "RhpETWShouldWalkCom")]
internal extern static bool RhpETWShouldWalkCom();
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[RuntimeImport(RuntimeLibrary, "RhpEtwExceptionThrown")]
internal extern static unsafe void RhpEtwExceptionThrown(char* exceptionTypeName, char* exceptionMessage, IntPtr faultingIP, long hresult);
#if CORERT
//
// Interlocked helpers
//
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[RuntimeImport(RuntimeLibrary, "RhpLockCmpXchg32")]
internal extern static int InterlockedCompareExchange(ref int location1, int value, int comparand);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[RuntimeImport(RuntimeLibrary, "RhpLockCmpXchg64")]
internal extern static long InterlockedCompareExchange(ref long location1, long value, long comparand);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
#if BIT64
[RuntimeImport(RuntimeLibrary, "RhpLockCmpXchg64")]
#else
[RuntimeImport(RuntimeLibrary, "RhpLockCmpXchg32")]
#endif
internal extern static IntPtr InterlockedCompareExchange(ref IntPtr location1, IntPtr value, IntPtr comparand);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[RuntimeImport(RuntimeLibrary, "RhpCheckedLockCmpXchg")]
internal extern static object InterlockedCompareExchange(ref object location1, object value, object comparand);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[RuntimeImport(RuntimeLibrary, "RhpCheckedXchg")]
internal extern static object InterlockedExchange(ref object location1, object value);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[RuntimeImport(RuntimeLibrary, "RhpMemoryBarrier")]
internal extern static void MemoryBarrier();
#endif // CORERT
[Intrinsic]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[RuntimeImport(RuntimeLibrary, "fabs")]
internal static extern double fabs(double x);
[Intrinsic]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[RuntimeImport(RuntimeLibrary, "floor")]
internal static extern double floor(double x);
[Intrinsic]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[RuntimeImport(RuntimeLibrary, "fmod")]
internal static extern double fmod(double x, double y);
[Intrinsic]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[RuntimeImport(RuntimeLibrary, "pow")]
internal static extern double pow(double x, double y);
[Intrinsic]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[RuntimeImport(RuntimeLibrary, "sqrt")]
internal static extern double sqrt(double x);
[Intrinsic]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[RuntimeImport(RuntimeLibrary, "ceil")]
internal static extern double ceil(double x);
[Intrinsic]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[RuntimeImport(RuntimeLibrary, "cos")]
internal static extern double cos(double x);
[Intrinsic]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[RuntimeImport(RuntimeLibrary, "sin")]
internal static extern double sin(double x);
[Intrinsic]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[RuntimeImport(RuntimeLibrary, "tan")]
internal static extern double tan(double x);
[Intrinsic]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[RuntimeImport(RuntimeLibrary, "cosh")]
internal static extern double cosh(double x);
[Intrinsic]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[RuntimeImport(RuntimeLibrary, "sinh")]
internal static extern double sinh(double x);
[Intrinsic]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[RuntimeImport(RuntimeLibrary, "tanh")]
internal static extern double tanh(double x);
[Intrinsic]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[RuntimeImport(RuntimeLibrary, "acos")]
internal static extern double acos(double x);
[Intrinsic]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[RuntimeImport(RuntimeLibrary, "asin")]
internal static extern double asin(double x);
[Intrinsic]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[RuntimeImport(RuntimeLibrary, "atan")]
internal static extern double atan(double x);
[Intrinsic]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[RuntimeImport(RuntimeLibrary, "atan2")]
internal static extern double atan2(double x, double y);
[Intrinsic]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[RuntimeImport(RuntimeLibrary, "log")]
internal static extern double log(double x);
[Intrinsic]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[RuntimeImport(RuntimeLibrary, "log10")]
internal static extern double log10(double x);
[Intrinsic]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[RuntimeImport(RuntimeLibrary, "exp")]
internal static extern double exp(double x);
[Intrinsic]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[RuntimeImport(RuntimeLibrary, "modf")]
internal static extern unsafe double modf(double x, double* intptr);
#if !PLATFORM_UNIX
// ExactSpelling = 'true' to force MCG to resolve it to default
[DllImport(RuntimeImports.RuntimeLibrary, ExactSpelling = true)]
internal static extern unsafe void _ecvt_s(byte* buffer, int sizeInBytes, double value, int count, int* dec, int* sign);
#endif
[DllImport(RuntimeImports.RuntimeLibrary, ExactSpelling = true)]
internal static extern unsafe void memmove(byte* dmem, byte* smem, nuint size);
[DllImport(RuntimeImports.RuntimeLibrary, ExactSpelling = true)]
internal static extern unsafe void memset(byte* mem, int value, nuint size);
// Non-inlinable wrapper around the PInvoke that avoids poluting the fast path with P/Invoke prolog/epilog.
[MethodImpl(MethodImplOptions.NoInlining)]
internal unsafe static void RhZeroMemory(ref byte b, nuint byteLength)
{
fixed (byte* bytePointer = &b)
{
memset(bytePointer, 0, byteLength);
}
}
internal unsafe static void RhZeroMemory(IntPtr p, UIntPtr byteLength)
{
memset((byte*)p, 0, (nuint)byteLength);
}
[MethodImpl(MethodImplOptions.InternalCall)]
[RuntimeImport(RuntimeLibrary, "RhpArrayCopy")]
internal static extern bool TryArrayCopy(Array sourceArray, int sourceIndex, Array destinationArray, int destinationIndex, int length);
[MethodImpl(MethodImplOptions.InternalCall)]
[RuntimeImport(RuntimeLibrary, "RhpArrayClear")]
internal static extern bool TryArrayClear(Array array, int index, int length);
// Only the values defined below are valid. Any other value returned from RhGetCorElementType
// indicates only that the type is not one of the primitives defined below and is otherwise undefined
// and subject to change.
internal enum RhCorElementType : byte
{
ELEMENT_TYPE_BOOLEAN = 0x2,
ELEMENT_TYPE_CHAR = 0x3,
ELEMENT_TYPE_I1 = 0x4,
ELEMENT_TYPE_U1 = 0x5,
ELEMENT_TYPE_I2 = 0x6,
ELEMENT_TYPE_U2 = 0x7,
ELEMENT_TYPE_I4 = 0x8,
ELEMENT_TYPE_U4 = 0x9,
ELEMENT_TYPE_I8 = 0xa,
ELEMENT_TYPE_U8 = 0xb,
ELEMENT_TYPE_R4 = 0xc,
ELEMENT_TYPE_R8 = 0xd,
ELEMENT_TYPE_I = 0x18,
ELEMENT_TYPE_U = 0x19,
}
internal static RhCorElementTypeInfo GetRhCorElementTypeInfo(RuntimeImports.RhCorElementType elementType)
{
return RhCorElementTypeInfo.GetRhCorElementTypeInfo(elementType);
}
internal struct RhCorElementTypeInfo
{
public RhCorElementTypeInfo(byte log2OfSize, ushort widenMask, bool isPrimitive = false)
{
_log2OfSize = log2OfSize;
RhCorElementTypeInfoFlags flags = RhCorElementTypeInfoFlags.IsValid;
if (isPrimitive)
flags |= RhCorElementTypeInfoFlags.IsPrimitive;
_flags = flags;
_widenMask = widenMask;
}
public bool IsPrimitive
{
get
{
return 0 != (_flags & RhCorElementTypeInfoFlags.IsPrimitive);
}
}
public bool IsFloat
{
get
{
return 0 != (_flags & RhCorElementTypeInfoFlags.IsFloat);
}
}
public byte Log2OfSize
{
get
{
return _log2OfSize;
}
}
//
// This is a port of InvokeUtil::CanPrimitiveWiden() in the desktop runtime. This is used by various apis such as Array.SetValue()
// and Delegate.DynamicInvoke() which allow value-preserving widenings from one primitive type to another.
//
public bool CanWidenTo(RuntimeImports.RhCorElementType targetElementType)
{
// Caller expected to ensure that both sides are primitive before calling us.
Debug.Assert(this.IsPrimitive);
Debug.Assert(GetRhCorElementTypeInfo(targetElementType).IsPrimitive);
// Once we've asserted that the target is a primitive, we can also assert that it is >= ET_BOOLEAN.
Debug.Assert(targetElementType >= RuntimeImports.RhCorElementType.ELEMENT_TYPE_BOOLEAN);
byte targetElementTypeAsByte = (byte)targetElementType;
ushort mask = (ushort)(1 << targetElementTypeAsByte); // This is expected to overflow on larger ET_I and ET_U - this is ok and anticipated.
if (0 != (_widenMask & mask))
return true;
return false;
}
internal static RhCorElementTypeInfo GetRhCorElementTypeInfo(RuntimeImports.RhCorElementType elementType)
{
// The _lookupTable array only covers a subset of RhCorElementTypes, so we return a default
// info when someone asks for an elementType which does not have an entry in the table.
if ((int)elementType > s_lookupTable.Length)
return default(RhCorElementTypeInfo);
return s_lookupTable[(int)elementType];
}
private byte _log2OfSize;
private RhCorElementTypeInfoFlags _flags;
[Flags]
private enum RhCorElementTypeInfoFlags : byte
{
IsValid = 0x01, // Set for all valid CorElementTypeInfo's
IsPrimitive = 0x02, // Is it a primitive type (as defined by TypeInfo.IsPrimitive)
IsFloat = 0x04, // Is it a floating point type
}
private ushort _widenMask;
#if BIT64
const byte log2PointerSize = 3;
#else
private const byte log2PointerSize = 2;
#endif
[PreInitialized] // The enclosing class (RuntimeImports) is depended upon (indirectly) by
// __vtable_IUnknown, which is an eager-init class, so this type must not have a
// lazy-init .cctor
private static RhCorElementTypeInfo[] s_lookupTable = new RhCorElementTypeInfo[]
{
// index = 0x0
new RhCorElementTypeInfo { _log2OfSize = 0, _widenMask = 0x0000, _flags = 0 },
// index = 0x1
new RhCorElementTypeInfo { _log2OfSize = 0, _widenMask = 0x0000, _flags = 0 },
// index = 0x2 = ELEMENT_TYPE_BOOLEAN (W = BOOL)
new RhCorElementTypeInfo { _log2OfSize = 0, _widenMask = 0x0004, _flags = RhCorElementTypeInfoFlags.IsValid|RhCorElementTypeInfoFlags.IsPrimitive },
// index = 0x3 = ELEMENT_TYPE_CHAR (W = U2, CHAR, I4, U4, I8, U8, R4, R8) (U2 == Char)
new RhCorElementTypeInfo { _log2OfSize = 1, _widenMask = 0x3f88, _flags = RhCorElementTypeInfoFlags.IsValid|RhCorElementTypeInfoFlags.IsPrimitive },
// index = 0x4 = ELEMENT_TYPE_I1 (W = I1, I2, I4, I8, R4, R8)
new RhCorElementTypeInfo { _log2OfSize = 0, _widenMask = 0x3550, _flags = RhCorElementTypeInfoFlags.IsValid|RhCorElementTypeInfoFlags.IsPrimitive },
// index = 0x5 = ELEMENT_TYPE_U1 (W = CHAR, U1, I2, U2, I4, U4, I8, U8, R4, R8)
new RhCorElementTypeInfo { _log2OfSize = 0, _widenMask = 0x3FE8, _flags = RhCorElementTypeInfoFlags.IsValid|RhCorElementTypeInfoFlags.IsPrimitive },
// index = 0x6 = ELEMENT_TYPE_I2 (W = I2, I4, I8, R4, R8)
new RhCorElementTypeInfo { _log2OfSize = 1, _widenMask = 0x3540, _flags = RhCorElementTypeInfoFlags.IsValid|RhCorElementTypeInfoFlags.IsPrimitive },
// index = 0x7 = ELEMENT_TYPE_U2 (W = U2, CHAR, I4, U4, I8, U8, R4, R8)
new RhCorElementTypeInfo { _log2OfSize = 1, _widenMask = 0x3F88, _flags = RhCorElementTypeInfoFlags.IsValid|RhCorElementTypeInfoFlags.IsPrimitive },
// index = 0x8 = ELEMENT_TYPE_I4 (W = I4, I8, R4, R8)
new RhCorElementTypeInfo { _log2OfSize = 2, _widenMask = 0x3500, _flags = RhCorElementTypeInfoFlags.IsValid|RhCorElementTypeInfoFlags.IsPrimitive },
// index = 0x9 = ELEMENT_TYPE_U4 (W = U4, I8, R4, R8)
new RhCorElementTypeInfo { _log2OfSize = 2, _widenMask = 0x3E00, _flags = RhCorElementTypeInfoFlags.IsValid|RhCorElementTypeInfoFlags.IsPrimitive },
// index = 0xa = ELEMENT_TYPE_I8 (W = I8, R4, R8)
new RhCorElementTypeInfo { _log2OfSize = 3, _widenMask = 0x3400, _flags = RhCorElementTypeInfoFlags.IsValid|RhCorElementTypeInfoFlags.IsPrimitive },
// index = 0xb = ELEMENT_TYPE_U8 (W = U8, R4, R8)
new RhCorElementTypeInfo { _log2OfSize = 3, _widenMask = 0x3800, _flags = RhCorElementTypeInfoFlags.IsValid|RhCorElementTypeInfoFlags.IsPrimitive },
// index = 0xc = ELEMENT_TYPE_R4 (W = R4, R8)
new RhCorElementTypeInfo { _log2OfSize = 2, _widenMask = 0x3000, _flags = RhCorElementTypeInfoFlags.IsValid|RhCorElementTypeInfoFlags.IsPrimitive|RhCorElementTypeInfoFlags.IsFloat },
// index = 0xd = ELEMENT_TYPE_R8 (W = R8)
new RhCorElementTypeInfo { _log2OfSize = 3, _widenMask = 0x2000, _flags = RhCorElementTypeInfoFlags.IsValid|RhCorElementTypeInfoFlags.IsPrimitive|RhCorElementTypeInfoFlags.IsFloat },
// index = 0xe
new RhCorElementTypeInfo { _log2OfSize = 0, _widenMask = 0x0000, _flags = 0 },
// index = 0xf
new RhCorElementTypeInfo { _log2OfSize = 0, _widenMask = 0x0000, _flags = 0 },
// index = 0x10
new RhCorElementTypeInfo { _log2OfSize = 0, _widenMask = 0x0000, _flags = 0 },
// index = 0x11
new RhCorElementTypeInfo { _log2OfSize = 0, _widenMask = 0x0000, _flags = 0 },
// index = 0x12
new RhCorElementTypeInfo { _log2OfSize = 0, _widenMask = 0x0000, _flags = 0 },
// index = 0x13
new RhCorElementTypeInfo { _log2OfSize = 0, _widenMask = 0x0000, _flags = 0 },
// index = 0x14
new RhCorElementTypeInfo { _log2OfSize = 0, _widenMask = 0x0000, _flags = 0 },
// index = 0x15
new RhCorElementTypeInfo { _log2OfSize = 0, _widenMask = 0x0000, _flags = 0 },
// index = 0x16
new RhCorElementTypeInfo { _log2OfSize = 0, _widenMask = 0x0000, _flags = 0 },
// index = 0x17
new RhCorElementTypeInfo { _log2OfSize = 0, _widenMask = 0x0000, _flags = 0 },
// index = 0x18 = ELEMENT_TYPE_I
new RhCorElementTypeInfo { _log2OfSize = log2PointerSize, _widenMask = 0x0000, _flags = RhCorElementTypeInfoFlags.IsValid|RhCorElementTypeInfoFlags.IsPrimitive },
// index = 0x19 = ELEMENT_TYPE_U
new RhCorElementTypeInfo { _log2OfSize = log2PointerSize, _widenMask = 0x0000, _flags = RhCorElementTypeInfoFlags.IsValid|RhCorElementTypeInfoFlags.IsPrimitive },
};
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Microsoft.Win32;
using System;
using System.Collections;
using System.Threading;
using System.Text;
using Xunit;
namespace Microsoft.Win32.RegistryTests
{
public class Registry_SetValue_str_str_obj : IDisposable
{
private string _testKey = "CM2001_TEST";
private static int s_keyCount = 0;
private string _keyString = "";
// Variables needed
private RegistryKey _rk1 = null, _rk2 = null;
public void TestInitialize()
{
var counter = Interlocked.Increment(ref s_keyCount);
_testKey += counter.ToString();
_rk1 = Microsoft.Win32.Registry.CurrentUser;
if (_rk1.OpenSubKey(_testKey) != null)
_rk1.DeleteSubKeyTree(_testKey);
if (_rk1.GetValue(_testKey) != null)
_rk1.DeleteValue(_testKey);
//created the test key. if that failed it will cause many of the test scenarios below fail.
try
{
_rk1 = Microsoft.Win32.Registry.CurrentUser;
if ((_rk2 = _rk1.CreateSubKey(_testKey)) == null)
{
Assert.False(true, "ERROR: Could not create test subkey, this will fail a couple of scenarios below.");
}
else
_keyString = _rk2.ToString();
}
catch (Exception e)
{
Assert.False(true, "ERROR: unexpected exception, " + e.ToString());
}
}
public Registry_SetValue_str_str_obj()
{
TestInitialize();
}
[Fact]
public void Test01()
{
// [] Passing in null should throw ArgumentNullException
//UPDATE: This sets the default value. We should move this test to a newly defined reg key so as not to screw up the system
try
{
String str1 = "This is a test";
Registry.SetValue(_keyString, null, str1);
if ((String)_rk2.GetValue(null) != str1)
{
Assert.False(true, "Error_unexpected error");
}
}
catch (ArgumentNullException)
{ }
catch (Exception exc)
{
Assert.False(true, "Error Unexpected exception exc==" + exc.ToString());
}
}
[Fact]
public void Test02()
{
// [] Passing null object should throw
Action a = () => { Registry.SetValue(_keyString, "test", null); };
Assert.Throws<ArgumentNullException>(() => { a(); });
}
[Fact]
public void Test03()
{
//passing null for registry key name should throw ArgumentNullException
Action a = () => { Registry.SetValue(null, "test", "test"); };
Assert.Throws<ArgumentNullException>(() => { a(); });
}
[Fact]
public void Test04()
{
//passing a string which does NOT start with one of the valid base key names, that should throw ArgumentException.
Action a = () => { Registry.SetValue("HHHH_MMMM", "test", "test"); };
Assert.Throws<ArgumentException>(() => { a(); });
}
[Fact]
public void Test05()
{
// [] Key length above 255 characters should throw
int MaxValueNameLength = 16383; // prior to V4, the limit is 255
StringBuilder sb = new StringBuilder(MaxValueNameLength + 1);
for (int i = 0; i <= MaxValueNameLength; i++)
sb.Append('a');
String strName = sb.ToString();
Action a = () => { Registry.SetValue(_keyString, strName, 5); };
Assert.Throws<ArgumentException>(() => { a(); });
}
[Fact]
public void Test06()
{
Random rand = new Random(-55);
// [] Vanilla case , set a bunch different objects
_rk2 = _rk1.CreateSubKey(_testKey);
var objArr = new Object[16];
objArr[0] = (Byte)rand.Next(Byte.MinValue, Byte.MaxValue);
objArr[1] = (SByte)rand.Next(SByte.MinValue, SByte.MaxValue);
objArr[2] = (Int16)rand.Next(Int16.MinValue, Int16.MaxValue);
objArr[3] = (UInt16)rand.Next(UInt16.MinValue, UInt16.MaxValue);
objArr[4] = rand.Next(Int32.MinValue, Int32.MaxValue);
objArr[5] = (UInt32)rand.Next((int)UInt32.MinValue, Int32.MaxValue);
objArr[6] = (Int64)rand.Next(Int32.MinValue, Int32.MaxValue);
objArr[7] = ((Double)Decimal.MaxValue) * rand.NextDouble();
objArr[8] = ((Double)Decimal.MinValue) * rand.NextDouble();
objArr[9] = ((Double)Decimal.MinValue) * rand.NextDouble();
objArr[10] = ((Double)Decimal.MaxValue) * rand.NextDouble();
objArr[11] = (Double)Int32.MaxValue * rand.NextDouble();
objArr[12] = (Double)Int32.MinValue * rand.NextDouble();
objArr[13] = (float)Int32.MaxValue * (float)rand.NextDouble();
objArr[14] = (float)Int32.MinValue * (float)rand.NextDouble();
objArr[15] = (UInt64)rand.Next((int)UInt64.MinValue, Int32.MaxValue);
for (int i = 0; i < objArr.Length; i++)
Registry.SetValue(_keyString, "Test_" + i.ToString(), objArr[i]);
for (int i = 0; i < objArr.Length; i++)
{
Object v = _rk2.GetValue("Test_" + i.ToString());
if (!v.ToString().Equals(objArr[i].ToString()))
{
Assert.False(true, "Error Expected==" + objArr[i].ToString() + " , got value==" + v.ToString());
}
}
for (int i = 0; i < objArr.Length; i++)
_rk2.DeleteValue("Test_" + i.ToString());
}
[Fact]
public void Test07()
{
// [] Set an existing it to an Int32
Registry.SetValue(_keyString, "Int32", -5);
if (((Int32)_rk2.GetValue("Int32")) != -5)
{
Assert.False(true, "Error Expected==5, got value==" + _rk2.GetValue("Int32"));
}
_rk2.DeleteValue("Int32");
}
[Fact]
public void Test08()
{
// [] Set some UInt values - this will be written as REG_SZ
Object o = Int64.MaxValue;
Registry.SetValue(_keyString, "UInt64", UInt64.MaxValue);
if (Convert.ToUInt64(_rk2.GetValue("UInt64")) != UInt64.MaxValue)
{
Assert.False(true, "Error Expected==" + UInt64.MaxValue + " , got==" + _rk2.GetValue("UInt64"));
}
_rk2.DeleteValue("UInt64");
}
[Fact]
public void Test09()
{
// [] Set a value to hold an Array - why is an exception throw here???
//because we only allow String[] - REG_MULTI_SZ and byte[] REG_BINARY. Here is the official explanation
//RegistryKey.SetValue does not support arrays of type UInt32[]. Only Byte[] and String[] are supported.
int[] iArr = new int[3];
iArr[0] = 1;
iArr[1] = 2;
iArr[2] = 3;
Action a = () => { Registry.SetValue(_keyString, "IntArray", iArr); };
Assert.Throws<ArgumentException>(() => { a(); });
}
[Fact]
public void Test10()
{
// [] Set a value to hold a Ubyte array - - REG_BINARY
Byte[] ubArr = new Byte[3];
ubArr[0] = 1;
ubArr[1] = 2;
ubArr[2] = 3;
Registry.SetValue(_keyString, "UBArr", ubArr);
Byte[] ubResult = (Byte[])_rk2.GetValue("UBArr");
if (ubResult.Length != 3)
{
Assert.False(true, "error! Incorrect Length of returned array");
}
if (ubResult[0] != 1)
{
Assert.False(true, "Error Expected==<1> , value==<" + ubResult[0] + ">");
}
if (ubResult[1] != 2)
{
Assert.False(true, "Error Expected==2 , value==" + ubResult[1]);
}
if (ubResult[2] != 3)
{
Assert.False(true, "Error Expected==3 , value==" + ubResult[2]);
}
_rk2.DeleteValue("UBArr");
}
[Fact]
public void RegistrySetValueMultiStringRoundTrips()
{
// [] Put in a string array - REG_MULTI_SZ
String[] strArr = new String[3];
strArr[0] = "This is a public";
strArr[1] = "broadcast intend to test";
strArr[2] = "lot of things. one of which";
Registry.SetValue(_keyString, "StringArr", strArr);
String[] strResult = (String[])_rk2.GetValue("StringArr");
Assert.Equal(strArr, strResult);
_rk2.DeleteValue("StringArr");
}
[Fact]
public void Test12()
{
// [] Passing in array with uninitialized elements should throw
string[] strArr = new String[1];
Action a = () => { Registry.SetValue(_keyString, "StringArr", strArr); };
Assert.Throws<ArgumentException>(() => { a(); });
}
[Fact]
public void Test13()
{
IDictionary envs;
IDictionaryEnumerator idic1;
String[] keys;
String[] values;
Int32 iCount;
envs = Environment.GetEnvironmentVariables();
keys = new String[envs.Keys.Count];
values = new String[envs.Values.Count];
idic1 = envs.GetEnumerator();
iCount = 0;
while (idic1.MoveNext())
{
keys[iCount] = (String)idic1.Key;
values[iCount] = (String)idic1.Value;
iCount++;
}
for (int i = 0; i < keys.Length; i++)
Registry.SetValue(_keyString, "ExpandedTest_" + i, "%" + keys[i] + "%");
//we dont expand for the user, REG_SZ_EXPAND not supported
for (int i = 0; i < keys.Length; i++)
{
String result = (String)_rk2.GetValue("ExpandedTest_" + i);
if (Environment.ExpandEnvironmentVariables(result) != values[i])
{
Assert.False(true, string.Format("Error Wrong value returned, Expected - <{0}>, Returned - <{1}>", values[i], _rk2.GetValue("ExpandedTest_" + i)));
}
}
}
[Fact]
public void Test14()
{
// passing emtpy string: Creating REG_SZ key with an empty string value does not add a null terminating char.
try
{
Registry.SetValue(_keyString, "test_122018", string.Empty);
if ((string)_rk2.GetValue("test_122018") != string.Empty)
{
Assert.False(true, string.Format("Error Wrong value returned, Expected - <{0}>, Returned - <{1}>", string.Empty, _rk2.GetValue("test_122018")));
}
}
catch (Exception exc)
{
Assert.False(true, string.Format("Error got exc==" + exc.ToString()));
}
}
public void Dispose()
{
// Clean up
_rk1 = Microsoft.Win32.Registry.CurrentUser;
if (_rk1.OpenSubKey(_testKey) != null)
_rk1.DeleteSubKeyTree(_testKey);
if (_rk1.GetValue(_testKey) != null)
_rk1.DeleteValue(_testKey);
}
}
}
| |
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 AssociationsIntro.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>>
{
DefaultSampleObjectFactory,
};
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order,
/// stopping when the factory successfully returns a non-<see langref="null"/> object.
/// </summary>
/// <remarks>
/// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use
/// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and
/// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",
Justification = "This is an appropriate nesting of generic types")]
public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames.
// If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames.
// If still not found, try to get the sample provided for the specified mediaType and type.
// Finally, try to get the sample provided for the specified mediaType.
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create
/// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other
/// factories in <see cref="SampleObjectFactories"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")]
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// No specific object available, try our factories.
foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories)
{
if (factory == null)
{
continue;
}
try
{
sampleObject = factory(this, type);
if (sampleObject != null)
{
break;
}
}
catch
{
// Ignore any problems encountered in the factory; go on to the next one (if any).
}
}
}
return sampleObject;
}
/// <summary>
/// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The type.</returns>
public virtual Type ResolveHttpRequestMessageType(ApiDescription api)
{
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters);
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
UnwrapException(e).Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
internal static Exception UnwrapException(Exception exception)
{
AggregateException aggregateException = exception as AggregateException;
if (aggregateException != null)
{
return aggregateException.Flatten().InnerException;
}
return exception;
}
// Default factory for sample objects
private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type)
{
// Try to create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
// Copyright (c) 2015, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace WebsitePanel.Portal.ProviderControls {
public partial class hMailServer5_EditAccount {
/// <summary>
/// secStatusInfo control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::WebsitePanel.Portal.CollapsiblePanel secStatusInfo;
/// <summary>
/// StatusInfoPanel control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Panel StatusInfoPanel;
/// <summary>
/// lblEnabled control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblEnabled;
/// <summary>
/// chkEnabled control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.CheckBox chkEnabled;
/// <summary>
/// lblSize control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblSize;
/// <summary>
/// lblSizeInfo control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblSizeInfo;
/// <summary>
/// lblQuotaUsed control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblQuotaUsed;
/// <summary>
/// lblQuotaUsedInfo control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblQuotaUsedInfo;
/// <summary>
/// lblLastLoginDate control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblLastLoginDate;
/// <summary>
/// lblLastLoginDateInfo control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblLastLoginDateInfo;
/// <summary>
/// secPersonalInfo control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::WebsitePanel.Portal.CollapsiblePanel secPersonalInfo;
/// <summary>
/// PersonalInfoPanel control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Panel PersonalInfoPanel;
/// <summary>
/// lblFirstName control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblFirstName;
/// <summary>
/// txtFirstName control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtFirstName;
/// <summary>
/// lblLastName control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblLastName;
/// <summary>
/// txtLastName control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtLastName;
/// <summary>
/// secAutoresponder control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::WebsitePanel.Portal.CollapsiblePanel secAutoresponder;
/// <summary>
/// AutoresponderPanel control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Panel AutoresponderPanel;
/// <summary>
/// lblResponderEnabled control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblResponderEnabled;
/// <summary>
/// chkResponderEnabled control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.CheckBox chkResponderEnabled;
/// <summary>
/// lblSubject control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblSubject;
/// <summary>
/// txtSubject control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtSubject;
/// <summary>
/// lblMessage control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblMessage;
/// <summary>
/// txtMessage control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtMessage;
/// <summary>
/// lblResponderExpires control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblResponderExpires;
/// <summary>
/// chkResponderExpires control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.CheckBox chkResponderExpires;
/// <summary>
/// lblResponderExpireDate control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblResponderExpireDate;
/// <summary>
/// txtResponderExireDate control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtResponderExireDate;
/// <summary>
/// secForwarding control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::WebsitePanel.Portal.CollapsiblePanel secForwarding;
/// <summary>
/// ForwardingPanel control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Panel ForwardingPanel;
/// <summary>
/// lblForwardingEnabled control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblForwardingEnabled;
/// <summary>
/// chkForwardingEnabled control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.CheckBox chkForwardingEnabled;
/// <summary>
/// lblForwardTo control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblForwardTo;
/// <summary>
/// txtForward control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtForward;
/// <summary>
/// chkOriginalMessage control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.CheckBox chkOriginalMessage;
/// <summary>
/// Signature control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::WebsitePanel.Portal.CollapsiblePanel Signature;
/// <summary>
/// SignaturePanel control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Panel SignaturePanel;
/// <summary>
/// lblSignatureEnabled control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblSignatureEnabled;
/// <summary>
/// cbSignatureEnabled control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.CheckBox cbSignatureEnabled;
/// <summary>
/// lblPlainSignature control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblPlainSignature;
/// <summary>
/// txtPlainSignature control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtPlainSignature;
/// <summary>
/// lblHtmlSignature control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblHtmlSignature;
/// <summary>
/// txtHtmlSignature control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtHtmlSignature;
}
}
| |
using System;
using System.Collections.Generic;
using UnityEngine;
namespace UMA
{
/// <summary>
/// Class links UMA's bone data with Unity's transform hierarchy.
/// </summary>
[Serializable]
public class UMASkeleton
{
/// <summary>
/// Internal class for storing bone and transform information.
/// </summary>
[Serializable]
public class BoneData
{
public int boneNameHash;
public int parentBoneNameHash;
public Transform boneTransform;
public UMATransform umaTransform;
public Quaternion rotation;
public Vector3 position;
public Vector3 scale;
public int accessedFrame;
}
public IEnumerable<int> BoneHashes { get { return GetBoneHashes(); } }
//DynamicUMADna:: DynamicUMADnaConverterCustomizer Editor interface needs to have an array of bone names
public string[] BoneNames { get { return GetBoneNames(); } }
protected bool updating;
protected int frame;
/// <value>The hash for the root bone of the skeleton.</value>
public int rootBoneHash { get; protected set; }
/// <value>The bone count.</value>
public virtual int boneCount { get { return boneHashData.Count; } }
public bool isUpdating { get { return updating; } }
private Dictionary<int, BoneData> boneHashDataLookup;
#if UNITY_EDITOR
// Dictionary backup to support code reload
private List<BoneData> boneHashDataBackup = new List<BoneData>();
#endif
public Dictionary<int, BoneData> boneHashData
{
get
{
if (boneHashDataLookup == null)
{
boneHashDataLookup = new Dictionary<int, BoneData>();
#if UNITY_EDITOR
foreach (BoneData tData in boneHashDataBackup)
{
boneHashDataLookup.Add(tData.boneNameHash, tData);
}
#endif
}
return boneHashDataLookup;
}
set
{
boneHashDataLookup = value;
#if UNITY_EDITOR
boneHashDataBackup = new List<BoneData>(value.Values);
#endif
}
}
/// <summary>
/// Initializes a new UMASkeleton from a transform hierarchy.
/// </summary>
/// <param name="rootBone">Root transform.</param>
public UMASkeleton(Transform rootBone)
{
rootBoneHash = UMAUtils.StringToHash(rootBone.name);
this.boneHashData = new Dictionary<int, BoneData>();
BeginSkeletonUpdate();
AddBonesRecursive(rootBone);
EndSkeletonUpdate();
}
protected UMASkeleton()
{
}
/// <summary>
/// Marks the skeleton as being updated.
/// </summary>
public virtual void BeginSkeletonUpdate()
{
frame++;
if (frame < 0) frame = 0;
updating = true;
}
/// <summary>
/// Marks the skeleton update as complete.
/// </summary>
public virtual void EndSkeletonUpdate()
{
foreach (var bd in boneHashData.Values)
{
if (bd != null && bd.boneTransform != null)
{
bd.rotation = bd.boneTransform.localRotation;
bd.position = bd.boneTransform.localPosition;
bd.scale = bd.boneTransform.localScale;
}
}
updating = false;
}
public virtual void SetAnimatedBone(int nameHash)
{
// The default MeshCombiner is ignoring the animated bones, virtual method added to share common interface.
}
public virtual void SetAnimatedBoneHierachy(int nameHash)
{
// The default MeshCombiner is ignoring the animated bones, virtual method added to share common interface.
}
public virtual void ClearAnimatedBoneHierachy(int nameHash, bool recursive)
{
// The default MeshCombiner is ignoring the animated bones, virtual method added to share common interface.
}
private void AddBonesRecursive(Transform transform)
{
if (transform.tag == UMAContextBase.IgnoreTag)
return;
var hash = UMAUtils.StringToHash(transform.name);
var parentHash = transform.parent != null ? UMAUtils.StringToHash(transform.parent.name) : 0;
BoneData data = new BoneData()
{
parentBoneNameHash = parentHash,
boneNameHash = hash,
accessedFrame = frame,
boneTransform = transform,
umaTransform = new UMATransform(transform, hash, parentHash)
};
if (!boneHashData.ContainsKey(hash))
{
boneHashData.Add(hash, data);
#if UNITY_EDITOR
boneHashDataBackup.Add(data);
#endif
}
else
{
if (Debug.isDebugBuild)
Debug.LogError("AddBonesRecursive: " + transform.name + " already exists in the dictionary! Consider renaming those bones. For example, `Items` under each hand bone can become `LeftItems` and `RightItems`.");
}
for (int i = 0; i < transform.childCount; i++)
{
var child = transform.GetChild(i);
AddBonesRecursive(child);
}
}
protected virtual BoneData GetBone(int nameHash)
{
BoneData data = null;
boneHashData.TryGetValue(nameHash, out data);
return data;
}
/// <summary>
/// Does this skeleton contains bone with specified name hash?
/// </summary>
/// <returns><c>true</c> if this instance has bone the specified name hash; otherwise, <c>false</c>.</returns>
/// <param name="nameHash">Name hash.</param>
public virtual bool HasBone(int nameHash)
{
return boneHashData.ContainsKey(nameHash);
}
/// <summary>
/// Check if the bone exists and is valid.
/// </summary>
/// <param name="nameHash">the namehash of the bone to check</param>
/// <returns>true if the bone exists and is valid</returns>
public virtual bool BoneExists(int nameHash)
{
BoneData db;
if (boneHashData.TryGetValue(nameHash, out db))
{
return db.boneTransform != null;
}
return false;
}
/// <summary>
/// Adds the transform into the skeleton.
/// </summary>
/// <param name="parentHash">Hash of parent transform name.</param>
/// <param name="hash">Hash of transform name.</param>
/// <param name="transform">Transform.</param>
public virtual void AddBone(int parentHash, int hash, Transform transform)
{
BoneData newBone = new BoneData()
{
accessedFrame = frame,
parentBoneNameHash = parentHash,
boneNameHash = hash,
boneTransform = transform,
umaTransform = new UMATransform(transform, hash, parentHash),
};
if (!boneHashData.ContainsKey(hash))
{
boneHashData.Add(hash, newBone);
#if UNITY_EDITOR
boneHashDataBackup.Add(newBone);
#endif
}
else
{
if (Debug.isDebugBuild)
Debug.LogError("AddBone: " + transform.name + " already exists in the dictionary! Consider renaming those bones. For example, `Items` under each hand bone can become `LeftItems` and `RightItems`.");
}
}
/// <summary>
/// Adds the transform into the skeleton.
/// </summary>
/// <param name="transform">Transform.</param>
public virtual void AddBone(UMATransform transform)
{
var go = new GameObject(transform.name);
BoneData newBone = new BoneData()
{
accessedFrame = -1,
parentBoneNameHash = transform.parent,
boneNameHash = transform.hash,
boneTransform = go.transform,
umaTransform = transform.Duplicate(),
};
if (!boneHashData.ContainsKey(transform.hash))
{
boneHashData.Add(transform.hash, newBone);
#if UNITY_EDITOR
boneHashDataBackup.Add(newBone);
#endif
}
else
{
if (Debug.isDebugBuild)
Debug.LogError("AddBone: " + transform.name + " already exists in the dictionary! Consider renaming those bones. For example, `Items` under each hand bone can become `LeftItems` and `RightItems`.");
}
}
/// <summary>
/// Removes the bone with the given name hash.
/// </summary>
/// <param name="nameHash">Name hash.</param>
public virtual void RemoveBone(int nameHash)
{
BoneData bd = GetBone(nameHash);
if (bd != null)
{
boneHashData.Remove(nameHash);
#if UNITY_EDITOR
boneHashDataBackup.Remove(bd);
#endif
}
}
/// <summary>
/// Tries to find bone transform in skeleton.
/// </summary>
/// <returns><c>true</c>, if transform was found, <c>false</c> otherwise.</returns>
/// <param name="nameHash">Name hash.</param>
/// <param name="boneTransform">Bone transform.</param>
/// <param name="transformDirty">Transform is dirty.</param>
/// <param name="parentBoneNameHash">Name hash of parent bone.</param>
public virtual bool TryGetBoneTransform(int nameHash, out Transform boneTransform, out bool transformDirty, out int parentBoneNameHash)
{
BoneData res;
if (boneHashData.TryGetValue(nameHash, out res))
{
transformDirty = res.accessedFrame != frame;
res.accessedFrame = frame;
boneTransform = res.boneTransform;
parentBoneNameHash = res.parentBoneNameHash;
return true;
}
transformDirty = false;
boneTransform = null;
parentBoneNameHash = 0;
return false;
}
/// <summary>
/// Gets the transform for a bone in the skeleton.
/// </summary>
/// <returns>The transform or null, if not found.</returns>
/// <param name="nameHash">Name hash.</param>
public virtual Transform GetBoneTransform(int nameHash)
{
BoneData res;
if (boneHashData.TryGetValue(nameHash, out res))
{
res.accessedFrame = frame;
return res.boneTransform;
}
return null;
}
/// <summary>
/// Gets the game object for a transform in the skeleton.
/// </summary>
/// <returns>The game object or null, if not found.</returns>
/// <param name="nameHash">Name hash.</param>
public virtual GameObject GetBoneGameObject(int nameHash)
{
BoneData res;
if (boneHashData.TryGetValue(nameHash, out res))
{
res.accessedFrame = frame;
if (res.boneTransform == null)
{
return null;
}
return res.boneTransform.gameObject;
}
return null;
}
protected virtual IEnumerable<int> GetBoneHashes()
{
foreach (int hash in boneHashData.Keys)
{
yield return hash;
}
}
//DynamicUMADna:: a method to return a string of bonenames for use in editor intefaces
private string[] GetBoneNames()
{
string[] boneNames = new string[boneHashData.Count];
int index = 0;
foreach (KeyValuePair<int, BoneData> kp in boneHashData)
{
boneNames[index] = kp.Value.boneTransform.gameObject.name;
index++;
}
return boneNames;
}
public virtual void Set(int nameHash, Vector3 position, Vector3 scale, Quaternion rotation)
{
BoneData db;
if (boneHashData.TryGetValue(nameHash, out db))
{
db.accessedFrame = frame;
db.boneTransform.localPosition = position;
db.boneTransform.localRotation = rotation;
db.boneTransform.localScale = scale;
db.umaTransform.rotation = rotation;
db.umaTransform.position = position;
db.umaTransform.scale = scale;
}
else
{
throw new Exception("Bone not found.");
}
}
/// <summary>
/// Sets the position of a bone.
/// This method silently fails if the bone doesn't exist! (Desired behaviour in DNA converters due to LOD/Occlusion)
/// </summary>
/// <param name="nameHash">Name hash.</param>
/// <param name="position">Position.</param>
public virtual void SetPosition(int nameHash, Vector3 position)
{
BoneData db;
if (boneHashData.TryGetValue(nameHash, out db))
{
db.accessedFrame = frame;
db.boneTransform.localPosition = position;
}
}
/// <summary>
/// Sets the position of a bone relative to it's old position.
/// This method silently fails if the bone doesn't exist! (Desired behaviour in DNA converters due to LOD/Occlusion)
/// </summary>
/// <param name="nameHash">Name hash.</param>
/// <param name="delta">Position delta.</param>
/// <param name="weight">Optionally set how much to apply the new position</param>
public virtual void SetPositionRelative(int nameHash, Vector3 delta, float weight = 1f)
{
BoneData db;
if (boneHashData.TryGetValue(nameHash, out db))
{
db.accessedFrame = frame;
db.boneTransform.localPosition = db.boneTransform.localPosition + delta * weight;
}
}
/// <summary>
/// Sets the scale of a bone.
/// This method silently fails if the bone doesn't exist! (Desired behaviour in DNA converters due to LOD/Occlusion)
/// </summary>
/// <param name="nameHash">Name hash.</param>
/// <param name="scale">Scale.</param>
public virtual void SetScale(int nameHash, Vector3 scale)
{
BoneData db;
if (boneHashData.TryGetValue(nameHash, out db))
{
db.accessedFrame = frame;
db.boneTransform.localScale = scale;
}
}
/// <summary>
/// DynamicUMADnaConverterBahaviour:: Sets the scale of a bone relatively.
/// This method silently fails if the bone doesn't exist! (Desired behaviour in DNA converters due to LOD/Occlusion)
/// </summary>
/// <param name="nameHash">Name hash.</param>
/// <param name="scale">Scale.</param>
/// <param name="weight">Optionally set how much to apply the new scale</param>
public virtual void SetScaleRelative(int nameHash, Vector3 scale, float weight = 1f)
{
BoneData db;
if (boneHashData.TryGetValue(nameHash, out db))
{
db.accessedFrame = frame;
scale.Scale(db.boneTransform.localScale);
db.boneTransform.localScale = Vector3.Lerp(db.boneTransform.localScale, scale, weight);
}
}
/// <summary>
/// Sets the rotation of a bone.
/// This method silently fails if the bone doesn't exist! (Desired behaviour in DNA converters due to LOD/Occlusion)
/// </summary>
/// <param name="nameHash">Name hash.</param>
/// <param name="rotation">Rotation.</param>
public virtual void SetRotation(int nameHash, Quaternion rotation)
{
BoneData db;
if (boneHashData.TryGetValue(nameHash, out db))
{
db.accessedFrame = frame;
db.boneTransform.localRotation = rotation;
}
}
/// <summary>
/// DynamicUMADnaConverterBahaviour:: Sets the rotation of a bone relative to its initial rotation.
/// This method silently fails if the bone doesn't exist! (Desired behaviour in DNA converters due to LOD/Occlusion)
/// </summary>
/// <param name="nameHash">Name hash.</param>
/// <param name="rotation">Rotation.</param>
/// <param name="weight">Weight.</param>
public virtual void SetRotationRelative(int nameHash, Quaternion rotation, float weight /*, bool hasAnimator = true*/)
{
BoneData db;
if (boneHashData.TryGetValue(nameHash, out db))
{
db.accessedFrame = frame;
Quaternion fullRotation = db.boneTransform.localRotation * rotation;
db.boneTransform.localRotation = Quaternion.Slerp(db.boneTransform.localRotation, fullRotation, weight);
}
}
/// <summary>
/// Lerp the specified bone toward a new position, rotation, and scale.
/// This method silently fails if the bone doesn't exist! (Desired behaviour in DNA converters due to LOD/Occlusion)
/// </summary>
/// <param name="nameHash">Name hash.</param>
/// <param name="position">Position.</param>
/// <param name="scale">Scale.</param>
/// <param name="rotation">Rotation.</param>
/// <param name="weight">Weight.</param>
public virtual void Lerp(int nameHash, Vector3 position, Vector3 scale, Quaternion rotation, float weight)
{
BoneData db;
if (boneHashData.TryGetValue(nameHash, out db))
{
db.accessedFrame = frame;
db.boneTransform.localPosition = Vector3.Lerp(db.boneTransform.localPosition, position, weight);
db.boneTransform.localRotation = Quaternion.Slerp(db.boneTransform.localRotation, db.boneTransform.localRotation, weight);
db.boneTransform.localScale = Vector3.Lerp(db.boneTransform.localScale, scale, weight);
}
}
/// <summary>
/// Lerp the specified bone toward a new position, rotation, and scale.
/// This method silently fails if the bone doesn't exist! (Desired behaviour in DNA converters due to LOD/Occlusion)
/// </summary>
/// <param name="nameHash">Name hash.</param>
/// <param name="position">Position.</param>
/// <param name="scale">Scale.</param>
/// <param name="rotation">Rotation.</param>
/// <param name="weight">Weight.</param>
public virtual void Morph(int nameHash, Vector3 position, Vector3 scale, Quaternion rotation, float weight)
{
BoneData db;
if (boneHashData.TryGetValue(nameHash, out db))
{
db.accessedFrame = frame;
db.boneTransform.localPosition += position * weight;
Quaternion fullRotation = db.boneTransform.localRotation * rotation;
db.boneTransform.localRotation = Quaternion.Slerp(db.boneTransform.localRotation, fullRotation, weight);
var fullScale = scale;
fullScale.Scale(db.boneTransform.localScale);
db.boneTransform.localScale = Vector3.Lerp(db.boneTransform.localScale, fullScale, weight);
}
}
/// <summary>
/// Reset the specified transform to the pre-dna state.
/// </summary>
/// <param name="nameHash">Name hash.</param>
public virtual bool Reset(int nameHash)
{
BoneData db;
if (boneHashData.TryGetValue(nameHash, out db) && (db.boneTransform != null))
{
db.accessedFrame = frame;
db.boneTransform.localPosition = db.umaTransform.position;
db.boneTransform.localRotation = db.umaTransform.rotation;
db.boneTransform.localScale = db.umaTransform.scale;
return true;
}
return false;
}
/// <summary>
/// Reset all transforms to the pre-dna state.
/// </summary>
public virtual void ResetAll()
{
foreach (BoneData db in boneHashData.Values)
{
if (db.boneTransform != null)
{
db.accessedFrame = frame;
db.boneTransform.localPosition = db.umaTransform.position;
db.boneTransform.localRotation = db.umaTransform.rotation;
db.boneTransform.localScale = db.umaTransform.scale;
}
}
}
/// <summary>
/// Restore the specified transform to the post-dna state.
/// </summary>
/// <param name="nameHash">Name hash.</param>
public virtual bool Restore(int nameHash)
{
BoneData db;
if (boneHashData.TryGetValue(nameHash, out db) && (db.boneTransform != null))
{
db.accessedFrame = frame;
db.boneTransform.localPosition = db.position;
db.boneTransform.localRotation = db.rotation;
db.boneTransform.localScale = db.scale;
return true;
}
return false;
}
/// <summary>
/// Restore all transforms to the post-dna state.
/// </summary>
public virtual void RestoreAll()
{
foreach (BoneData db in boneHashData.Values)
{
if (db.boneTransform != null)
{
db.accessedFrame = frame;
db.boneTransform.localPosition = db.position;
db.boneTransform.localRotation = db.rotation;
db.boneTransform.localScale = db.scale;
}
}
}
/// <summary>
/// Gets the position of a bone.
/// </summary>
/// <returns>The position.</returns>
/// <param name="nameHash">Name hash.</param>
public virtual Vector3 GetPosition(int nameHash)
{
BoneData db;
if (boneHashData.TryGetValue(nameHash, out db))
{
db.accessedFrame = frame;
return db.boneTransform.localPosition;
}
else
{
throw new Exception("Bone not found.");
}
}
/// <summary>
/// Gets the position of a bone.
/// </summary>
/// <returns>The position.</returns>
/// <param name="nameHash">Name hash.</param>
public virtual Vector3 GetRelativePosition(int nameHash)
{
BoneData db;
if (boneHashData.TryGetValue(nameHash, out db))
{
db.accessedFrame = frame;
return boneHashData[rootBoneHash].boneTransform.parent.parent.worldToLocalMatrix.MultiplyPoint(db.boneTransform.position);
}
else
{
throw new Exception("Bone not found.");
}
}
/// <summary>
/// Gets the scale of a bone.
/// </summary>
/// <returns>The scale.</returns>
/// <param name="nameHash">Name hash.</param>
public virtual Vector3 GetScale(int nameHash)
{
BoneData db;
if (boneHashData.TryGetValue(nameHash, out db))
{
db.accessedFrame = frame;
return db.boneTransform.localScale;
}
else
{
throw new Exception("Bone not found.");
}
}
/// <summary>
/// Gets the rotation of a bone.
/// </summary>
/// <returns>The rotation.</returns>
/// <param name="nameHash">Name hash.</param>
public virtual Quaternion GetRotation(int nameHash)
{
BoneData db;
if (boneHashData.TryGetValue(nameHash, out db))
{
db.accessedFrame = frame;
return db.boneTransform.localRotation;
}
else
{
throw new Exception("Bone not found. BoneHash: " + nameHash);
}
}
public static int StringToHash(string name) { return UMAUtils.StringToHash(name); }
public virtual Transform[] HashesToTransforms(int[] boneNameHashes)
{
Transform[] res = new Transform[boneNameHashes.Length];
for (int i = 0; i < boneNameHashes.Length; i++)
{
res[i] = boneHashData[boneNameHashes[i]].boneTransform;
}
return res;
}
public virtual Transform[] HashesToTransforms(List<int> boneNameHashes)
{
Transform[] res = new Transform[boneNameHashes.Count];
for (int i = 0; i < boneNameHashes.Count; i++)
{
res[i] = boneHashData[boneNameHashes[i]].boneTransform;
}
return res;
}
/// <summary>
/// Ensures the bone exists in the skeleton.
/// </summary>
/// <param name="umaTransform">UMA transform.</param>
public virtual void EnsureBone(UMATransform umaTransform)
{
if (boneHashData.ContainsKey(umaTransform.hash) == false)
AddBone(umaTransform);
}
/// <summary>
/// Ensures all bones are properly initialized and parented.
/// </summary>
public virtual void EnsureBoneHierarchy()
{
foreach (var entry in boneHashData.Values)
{
if (entry.accessedFrame == -1)
{
if (boneHashData.ContainsKey(entry.umaTransform.parent))
{
entry.boneTransform.parent = boneHashData[entry.umaTransform.parent].boneTransform;
entry.boneTransform.localPosition = entry.umaTransform.position;
entry.boneTransform.localRotation = entry.umaTransform.rotation;
entry.boneTransform.localScale = entry.umaTransform.scale;
entry.accessedFrame = frame;
}
else
{
if (Debug.isDebugBuild)
Debug.LogError("EnsureBoneHierarchy: " + entry.umaTransform.name + " parent not found in dictionary!");
}
}
}
}
public virtual Quaternion GetTPoseCorrectedRotation(int nameHash, Quaternion tPoseRotation)
{
return boneHashData[nameHash].boneTransform.localRotation;
}
}
}
| |
/*
*
* (c) Copyright Ascensio System Limited 2010-2021
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System;
using System.Linq;
using System.ServiceProcess;
using System.Text.RegularExpressions;
using ASC.Core;
using ASC.HealthCheck.Classes;
using ASC.HealthCheck.Resources;
using log4net;
namespace ASC.HealthCheck.Models
{
public interface IXplatServiceController: IDisposable
{
ServiceStatus GetServiceStatus();
string StartService();
string StopService();
}
public class XplatServiceController : IXplatServiceController
{
private readonly ILog log = LogManager.GetLogger(typeof(XplatServiceController));
private static readonly TimeSpan waitStartStopServicePeriod = TimeSpan.FromSeconds(40);
private ServiceController serviceController;
public static IXplatServiceController GetXplatServiceController(ServiceEnum serviceName)
{
return WorkContext.IsMono
? (IXplatServiceController)new XplatMonoServiceController(serviceName)
: new XplatServiceController(serviceName);
}
public XplatServiceController(ServiceEnum serviceName)
{
var services = ServiceController.GetServices(Environment.MachineName);
serviceController = services.FirstOrDefault(sc => serviceName.ToString().Equals(sc.ServiceName, StringComparison.InvariantCultureIgnoreCase));
}
public ServiceStatus GetServiceStatus()
{
if (serviceController == null)
{
log.Debug("GetServiceStatus, ServiceController is NULL");
return ServiceStatus.NotFound;
}
log.DebugFormat("GetServiceStatus, serviceName = {0}", serviceController.ServiceName);
switch (serviceController.Status)
{
case ServiceControllerStatus.Running:
return ServiceStatus.Running;
case ServiceControllerStatus.StartPending:
case ServiceControllerStatus.ContinuePending:
return ServiceStatus.StartPending;
case ServiceControllerStatus.Paused:
case ServiceControllerStatus.Stopped:
return ServiceStatus.Stopped;
case ServiceControllerStatus.PausePending:
case ServiceControllerStatus.StopPending:
return ServiceStatus.StopPending;
default:
return ServiceStatus.NotFound;
}
}
public string StartService()
{
serviceController.Start();
serviceController.WaitForStatus(ServiceControllerStatus.StartPending, waitStartStopServicePeriod);
return string.Empty;
}
public string StopService()
{
serviceController.Stop();
serviceController.WaitForStatus(ServiceControllerStatus.Stopped, waitStartStopServicePeriod);
return string.Empty;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
if (serviceController != null)
{
serviceController.Dispose();
serviceController = null;
}
}
}
~XplatServiceController()
{
Dispose(false);
}
}
public class XplatMonoServiceController : IXplatServiceController
{
private readonly ILog log = LogManager.GetLogger(typeof(XplatMonoServiceController));
private readonly string serviceNameString;
public XplatMonoServiceController(ServiceEnum serviceName)
{
serviceNameString = Regex.Replace(serviceName.ToString(), @"\A[A-Z]", m => m.ToString().ToLower());
}
public XplatMonoServiceController(string serviceNameString)
{
this.serviceNameString = serviceNameString;
}
public ServiceStatus GetServiceStatus()
{
try
{
using (var proc = new ShellExe().RunBinFile("ps", "auxf"))
{
var output = proc.StandardOutput.ReadToEnd();
var error = proc.StandardError.ReadToEnd();
log.DebugFormat("GetMonoServiceStatus, processName = {0}", serviceNameString);
if (!string.IsNullOrWhiteSpace(error))
{
log.ErrorFormat("GetMonoServiceStatus. Unexpected error: {0}, serviceStatus = {1}", error, ServiceStatus.NotFound);
return ServiceStatus.NotFound;
}
if (output.Contains(string.Format("-l:/tmp/{0}", serviceNameString)))
{
log.DebugFormat("GetMonoServiceStatus, serviceName = {0}, serviceStatus = {1}", serviceNameString, ServiceStatus.Running);
return ServiceStatus.Running;
}
log.DebugFormat("GetMonoServiceStatus, serviceName: {0}, serviceStatus = {1}", serviceNameString, ServiceStatus.Stopped);
return ServiceStatus.Stopped;
}
}
catch (Exception ex)
{
log.ErrorFormat("GetMonoServiceStatus. Unexpected error. ProcessName = {0}, serviceStatus = {1}, ex = {2}", serviceNameString, ServiceStatus.NotFound, ex.ToString());
return ServiceStatus.NotFound;
}
}
public string StartService()
{
return Run("start", HealthCheckResource.ServiceStartError);
}
public string StopService()
{
return Run("stop", HealthCheckResource.ServiceStopError);
}
private string Run(string command, string errorResult)
{
try
{
using (var proc = new ShellExe().RunBinFile("sudo", string.Format("service {0} {1}", serviceNameString, command)))
{
var output = proc.StandardOutput.ReadToEnd();
var error = proc.StandardError.ReadToEnd();
if (!string.IsNullOrWhiteSpace(error))
{
log.ErrorFormat("{0}MonoService. Unexpected error: serviceName = {1}, error = {2}, output: {3}", command, serviceNameString, error, output);
return errorResult;
}
return string.Empty;
}
}
catch (Exception ex)
{
log.ErrorFormat("{0}MonoService. Unexpected error. ProcessName = {1}, ex = {2}", command, serviceNameString, ex.ToString());
return errorResult;
}
}
public void Dispose()
{
}
}
}
| |
// Ported 2009 Oct 9
using System;
using System . Collections . Generic;
// This provides topological sorts for the graph
partial class SparseGraph<Tnode>
{
/// <summary>
/// Builds a mutable version of the node-predecessor counts
/// </summary>
/// <param name="Orig">The original table of node predecessor counts</param>
/// <returns>mutable dictionary of predecessor counts</returns>
static Dictionary<Tnode, int> BuildTable(IDictionary<Tnode, int> Orig)
{
if (null == Orig)
return null;
var NumPredecessors = new Dictionary<Tnode, int> ();
foreach (var I in Orig)
NumPredecessors[I.Key] = I.Value;
return NumPredecessors;
}
/// <summary>
/// Builds a table of the number of predecessors for each node
/// </summary>
/// <param name="Graph">The graph to analyze</param>
/// <returns>Dictionary that maps each node to the number of predecessors</returns>
Dictionary<Tnode, int> BuildPredecessors()
{
var NumPredecessors = new Dictionary<Tnode, int> ();
foreach (var K in EdgeSrcNodes())
{
// Add the key as needed
if (!NumPredecessors . ContainsKey(K))
NumPredecessors[K] = 0;
var Ends = Successors(K);
// Iteratve over each the Ends
var L= Ends.Count;
for (int Idx = 0; Idx < L; Idx++)
{
// Increment the count of predecessors for the destination node
var node = Ends [Idx] . sink;
if (NumPredecessors . ContainsKey(node))
NumPredecessors[node] ++;
else
NumPredecessors[node] = 1;
}
}
return NumPredecessors;
}
/// <summary>
/// Topologically sort a acyclic, directed graph using a depth-first search.
/// </summary>
/// <param name="ResidueNumPredecessors">Table of the number of predecessors
/// each node has. A successful run will have an empty table</param>
/// <returns>The list of nodes, in the sorted order.</returns>
/// <remarks>
/// References
/// Jeffery Copeland, Jeffrey Haemer, Work: Puzzle Posters, Part 2
/// SunExpert Magazine, October 1998, p53-57
///
/// Jon Bentley (More Programming Pearls, pp. 20-23)
///
/// Don Knuth (Art of Computer Programming, Volume 1: Fundamental Algortihms,
/// Section 2.2.3)
/// </remarks>
internal List<Tnode> SortDFS(out IDictionary<Tnode, int> ResidueNumPredecessors)
{
// The number of predecessors for a given node
var NumPredecessors = BuildTable(PredecessorCounts());
if (null == NumPredecessors)
NumPredecessors = BuildPredecessors();
ResidueNumPredecessors = NumPredecessors;
return SortDFS(NumPredecessors);
}
/// <summary>
/// Sorts the graph using a depth-first search.
/// </summary>
/// <param name="NumPredecessors">Table of the number of predecessors each
/// node has. This will be modified as the procedure runs, and indicates
/// the state of conflict at the end.</param>
/// <returns>The list of nodes, in the sorted order.</returns>
/// <remarks>
/// Complexity is O(number of nodes + number of defined edges)
///
/// References
/// Jeffery Copeland, Jeffrey Haemer, Work: Puzzle Posters, Part 2
/// SunExpert Magazine, October 1998, p53-57
///
/// Jon Bentley (More Programming Pearls, pp. 20-23)
///
/// Don Knuth (Art of Computer Programming, Volume 1: Fundamental Algortihms,
/// Addison-Wesley 1997 Section 2.2.3)
/// </remarks>
List<Tnode> SortDFS(Dictionary<Tnode, int> NumPredecessors)
{
var Ret = new List<Tnode>();
// Start with an empty stack
// Push the root of the tree onto the stack to initialize
// Create a list of nodes without predecessors
var IndependentNodes = new List<Tnode>();
foreach (var Node in NumPredecessors . Keys)
if (0 == NumPredecessors[Node])
IndependentNodes . Add(Node);
// Continue until the stack is empty
// This could be done recursively, but that would croak with graphs
// that aren't small
while (IndependentNodes . Count > 0)
{
// "Pop the stack, [push] what you find [onto the result stack] and push
// its children back on the the stack in its place"
int Idx = IndependentNodes . Count-1;
var Node = IndependentNodes[Idx];
IndependentNodes . RemoveAt(Idx);
NumPredecessors . Remove(Node);
Ret . Add(Node);
// Scan each of the successors for which is available
var Nexts = Successors(Node);
if (null != Nexts)
{
var L = Nexts. Count;
for (int I = 0; I < L; I++)
{
var Child = Nexts[I].sink;
// Decrement the number of wait-count for the node
// and append it if there are no more waits
if (0 == --NumPredecessors[Child])
IndependentNodes . Add(Child);
}
}
}
return Ret;
}
/// <summary>
/// Topologically sort a acyclic, directed graph using a breadth-first search.
/// </summary>
/// <param name="ResidueNumPredecessors">Table of the number of predecessors
/// each node has. A successful run will have an empty table</param>
/// <returns>The list of nodes, in the sorted order.</returns>
/// <remarks>
/// Complexity is O(number of nodes + number of defined edges)
///
/// References
/// Jeffery Copeland, Jeffrey Haemer, Work: Puzzle Posters, Part 2
/// SunExpert Magazine, October 1998, p53-57
///
/// Jon Bentley (More Programming Pearls, pp. 20-23)
///
/// Don Knuth (Art of Computer Programming, Volume 1: Fundamental Algortihms,
/// Addison-Wesley 1997 Section 2.2.3)
/// </remarks>
internal List<Tnode> SortBFS(out IDictionary<Tnode, int> ResidueNumPredecessors)
{
// The number of predecessors for a given node
var NumPredecessors = BuildTable(PredecessorCounts());
if (null == NumPredecessors)
NumPredecessors = BuildPredecessors();
ResidueNumPredecessors = NumPredecessors;
return SortBFS(NumPredecessors);
}
/// <summary>
/// Sorts the given graph using breadth-first search.
/// </summary>
/// <param name="NumPredecessors">Table of the number of predecessors each
/// node has. This will be modified as the procedure runs, and indicates
/// the state of conflict at the end.</param>
/// <returns>The list of nodes, in the sorted order.</returns>
List<Tnode> SortBFS(Dictionary<Tnode, int> NumPredecessors)
{
var Ret = new List<Tnode>();
// "Start with an empty stack"
// "Push the root of the tree onto the stack to initialize"
// Create a list of nodes without predecessors
foreach (var Node in NumPredecessors . Keys)
if (0 == NumPredecessors[Node])
Ret . Add(Node);
// Continue until the stack is empty
for (int I = 0; I < Ret . Count; I++)
{
// "Pop the stack, [push] what you find [onto the result stack] and push
// its children back on the the stack in its place"
var Node = Ret[I];
NumPredecessors . Remove(Node);
// Scan each of the successors for which is available
var Nexts = Successors(Node);
if (null != Nexts)
{
var L = Nexts.Count;
for (int Idx = 0; Idx < L; Idx++)
{
var Child = Nexts[Idx].sink;
// Decrement the number of wait-count for the node
// and append it if there are no more waits
if (0 == --NumPredecessors[Child])
Ret . Add(Child);
}
}
}
return Ret;
}
/// <summary>
/// Determins if the graph has atleast one cycles. Call this after sorting.
/// </summary>
/// <returns>True if there is a cycle, false if there is no cycle</returns>
internal static bool Cycle_Exists(IDictionary<Tnode, int> NumPredecessors)
{
foreach (var N in NumPredecessors . Values)
if (0 != N)
return true;
return false;
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;
namespace HaloSharp.Model.HaloWars2.Stats.CarnageReport.Events
{
[Serializable]
public class ResourceHeartbeat : MatchEvent, IEquatable<ResourceHeartbeat>
{
[JsonProperty(PropertyName = "TeamResources")]
public Dictionary<int, TeamResource> TeamResources { get; set; }
[JsonProperty(PropertyName = "PlayerResources")]
public Dictionary<int, PlayerResource> PlayerResources { get; set; }
public bool Equals(ResourceHeartbeat other)
{
if (ReferenceEquals(null, other))
{
return false;
}
if (ReferenceEquals(this, other))
{
return false;
}
return PlayerResources.OrderBy(ps => ps.Key).SequenceEqual(other.PlayerResources.OrderBy(ps => ps.Key))
&& TeamResources.OrderBy(ts => ts.Key).SequenceEqual(other.TeamResources.OrderBy(ts => ts.Key));
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj))
{
return false;
}
if (ReferenceEquals(this, obj))
{
return false;
}
if (obj.GetType() != typeof(ResourceHeartbeat))
{
return false;
}
return Equals((ResourceHeartbeat)obj);
}
public override int GetHashCode()
{
unchecked
{
return ((PlayerResources?.GetHashCode() ?? 0) * 397) ^ (TeamResources?.GetHashCode() ?? 0);
}
}
public static bool operator ==(ResourceHeartbeat left, ResourceHeartbeat right)
{
return Equals(left, right);
}
public static bool operator !=(ResourceHeartbeat left, ResourceHeartbeat right)
{
return !Equals(left, right);
}
}
[Serializable]
public class TeamResource : IEquatable<TeamResource>
{
[JsonProperty(PropertyName = "ObjectiveScore")]
public int ObjectiveScore { get; set; }
public bool Equals(TeamResource other)
{
if (ReferenceEquals(null, other))
{
return false;
}
if (ReferenceEquals(this, other))
{
return false;
}
return ObjectiveScore == other.ObjectiveScore;
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj))
{
return false;
}
if (ReferenceEquals(this, obj))
{
return false;
}
if (obj.GetType() != typeof(TeamResource))
{
return false;
}
return Equals((TeamResource)obj);
}
public override int GetHashCode()
{
return ObjectiveScore;
}
public static bool operator ==(TeamResource left, TeamResource right)
{
return Equals(left, right);
}
public static bool operator !=(TeamResource left, TeamResource right)
{
return !Equals(left, right);
}
}
[Serializable]
public class PlayerResource : IEquatable<PlayerResource>
{
[JsonProperty(PropertyName = "Supply")]
public int Supply { get; set; }
[JsonProperty(PropertyName = "TotalSupply")]
public int TotalSupply { get; set; }
[JsonProperty(PropertyName = "Energy")]
public int Energy { get; set; }
[JsonProperty(PropertyName = "TotalEnergy")]
public int TotalEnergy { get; set; }
[JsonProperty(PropertyName = "Population")]
public int Population { get; set; }
[JsonProperty(PropertyName = "PopulationCap")]
public int PopulationCap { get; set; }
[JsonProperty(PropertyName = "TechLevel")]
public int TechLevel { get; set; }
[JsonProperty(PropertyName = "CommandPoints")]
public int CommandPoints { get; set; }
[JsonProperty(PropertyName = "TotalCommandPoints")]
public int TotalCommandPoints { get; set; }
[JsonProperty(PropertyName = "Mana")]
public int Mana { get; set; }
[JsonProperty(PropertyName = "TotalMana")]
public int TotalMana { get; set; }
[JsonProperty(PropertyName = "ManaRate")]
public int ManaRate { get; set; }
[JsonProperty(PropertyName = "CommandXP")]
public int CommandExperience { get; set; }
public bool Equals(PlayerResource other)
{
if (ReferenceEquals(null, other))
{
return false;
}
if (ReferenceEquals(this, other))
{
return false;
}
return CommandExperience == other.CommandExperience
&& CommandPoints == other.CommandPoints
&& Energy == other.Energy
&& Mana == other.Mana
&& ManaRate == other.ManaRate
&& Population == other.Population
&& PopulationCap == other.PopulationCap
&& Supply == other.Supply
&& TechLevel == other.TechLevel
&& TotalCommandPoints == other.TotalCommandPoints
&& TotalEnergy == other.TotalEnergy
&& TotalMana == other.TotalMana
&& TotalSupply == other.TotalSupply;
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj))
{
return false;
}
if (ReferenceEquals(this, obj))
{
return false;
}
if (obj.GetType() != typeof(PlayerResource))
{
return false;
}
return Equals((PlayerResource)obj);
}
public override int GetHashCode()
{
unchecked
{
var hashCode = CommandExperience;
hashCode = (hashCode * 397) ^ CommandPoints;
hashCode = (hashCode * 397) ^ Energy;
hashCode = (hashCode * 397) ^ Mana;
hashCode = (hashCode * 397) ^ ManaRate;
hashCode = (hashCode * 397) ^ Population;
hashCode = (hashCode * 397) ^ PopulationCap;
hashCode = (hashCode * 397) ^ Supply;
hashCode = (hashCode * 397) ^ TechLevel;
hashCode = (hashCode * 397) ^ TotalCommandPoints;
hashCode = (hashCode * 397) ^ TotalEnergy;
hashCode = (hashCode * 397) ^ TotalMana;
hashCode = (hashCode * 397) ^ TotalSupply;
return hashCode;
}
}
public static bool operator ==(PlayerResource left, PlayerResource right)
{
return Equals(left, right);
}
public static bool operator !=(PlayerResource left, PlayerResource right)
{
return !Equals(left, right);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using RRLab.PhysiologyWorkbench.Data;
using System.Threading;
namespace RRLab.PhysiologyData.GUI
{
public partial class RecordingDataGraphControl : UserControl, INotifyPropertyChanged
{
public enum AxisLocation { Left, Right };
public enum AxisMode { Auto, DynamicRange };
public event EventHandler DefaultAxisLocationChanged;
private AxisLocation _DefaultAxisLocation;
[SettingsBindable(true)]
[Bindable(true)]
public AxisLocation DefaultAxisLocation
{
get { return _DefaultAxisLocation; }
set {
_DefaultAxisLocation = value;
if (DefaultAxisLocationChanged != null) DefaultAxisLocationChanged(this, EventArgs.Empty);
NotifyPropertyChanged("DefaultAxisLocation");
}
}
public event EventHandler DefaultAxisModeChanged;
private AxisMode _DefaultAxisMode;
[SettingsBindable(true)]
[Bindable(true)]
public AxisMode DefaultAxisMode
{
get { return _DefaultAxisMode; }
set {
_DefaultAxisMode = value;
if (DefaultAxisModeChanged != null) DefaultAxisModeChanged(this, EventArgs.Empty);
NotifyPropertyChanged("DefaultAxisMode");
}
}
public event EventHandler GraphBackColorChanged;
private Color _GraphBackColor = Color.LightGoldenrodYellow;
[Bindable(true)]
[SettingsBindable(true)]
public Color GraphBackColor
{
get { return _GraphBackColor; }
set {
_GraphBackColor = value;
if (GraphBackColorChanged != null) GraphBackColorChanged(this, EventArgs.Empty);
NotifyPropertyChanged("GraphBackColor");
}
}
public event EventHandler IsDarkRoomStyleChanged;
private bool _IsDarkRoomStyle = false;
[SettingsBindable(true)]
[Bindable(true)]
[DefaultValue(false)]
public bool IsDarkRoomStyle
{
get { return _IsDarkRoomStyle; }
set {
_IsDarkRoomStyle = value;
OnIsDarkRoomStyleChanged(EventArgs.Empty);
NotifyPropertyChanged("IsDarkRoomStyle");
}
}
public event EventHandler IsAutoUpdateDisabledChanged;
private bool _IsAutoUpdateDisabled = false;
[SettingsBindable(true)]
[Bindable(true)]
[DefaultValue(false)]
public bool IsAutoUpdateDisabled
{
get { return _IsAutoUpdateDisabled; }
set {
_IsAutoUpdateDisabled = value;
if (IsAutoUpdateDisabledChanged != null) IsAutoUpdateDisabledChanged(this, EventArgs.Empty);
}
}
public event EventHandler IsTitleVisibleChanged;
private bool _IsTitleVisible = true;
[SettingsBindable(true)]
[Bindable(true)]
[DefaultValue(true)]
public bool IsTitleVisible
{
get { return _IsTitleVisible; }
set {
_IsTitleVisible = value;
OnIsTitleVisibleChanged(EventArgs.Empty);
NotifyPropertyChanged("IsTitleVisible");
}
}
public event EventHandler IsLegendVisibleChanged;
private bool _IsLegendVisible = true;
[SettingsBindable(true)]
[Bindable(true)]
[DefaultValue(true)]
public bool IsLegendVisible
{
get { return _IsLegendVisible; }
set {
_IsLegendVisible = value;
OnIsLegendVisibleChanged(EventArgs.Empty);
NotifyPropertyChanged("IsLegendVisible");
}
}
public event EventHandler DataSetChanged;
private PhysiologyDataSet _DataSet;
[Bindable(true)]
public PhysiologyDataSet DataSet
{
get { return _DataSet; }
set {
_DataSet = value;
OnDataSetChanged(EventArgs.Empty);
NotifyPropertyChanged("DataSet");
}
}
public event EventHandler CurrentRecordingIDChanged;
private long _CurrentRecordingID;
[Bindable(true)]
public long CurrentRecordingID
{
get { return _CurrentRecordingID; }
set
{
_CurrentRecordingID = value;
OnCurrentRecordingIDChanged(EventArgs.Empty);
}
}
public event EventHandler ShownDataListChanged;
public ICollection<string> ShownDataList
{
get
{
List<string> shownData = new List<string>(AvailableDataCheckedListBox.CheckedItems.Count);
foreach (object o in AvailableDataCheckedListBox.CheckedItems)
shownData.Add(o.ToString());
return shownData;
}
}
public event EventHandler AxesLocationsChanged;
private SortedList<string, AxisLocation> _AxesLocations = new SortedList<string,AxisLocation>();
public IDictionary<string, AxisLocation> AxesLocations
{
get
{
return _AxesLocations;
}
}
public event EventHandler AxesModesChanged;
private SortedList<string, AxisMode> _AxesModes = new SortedList<string, AxisMode>();
public IDictionary<string, AxisMode> AxesModes
{
get
{
return _AxesModes;
}
}
public event EventHandler IsSidebarVisibleChanged;
private bool _IsSidebarVisible = true;
[SettingsBindable(true)]
[Bindable(true)]
[DefaultValue(true)]
public bool IsSidebarVisible
{
get { return _IsSidebarVisible; }
set {
_IsSidebarVisible = value;
OnIsSidebarVisibleChanged(EventArgs.Empty);
NotifyPropertyChanged("IsSidebarVisible");
}
}
public PhysiologyDataSet.RecordingsRow CurrentRecordingsRow
{
get
{
if (DataSet == null) return null;
try
{
return ((DataRowView)RecordingBindingSource.Current).Row as PhysiologyDataSet.RecordingsRow;
}
catch (Exception e)
{
return null;
}
}
}
private SortedList<string, string> _AxesTitles = new SortedList<string, string>();
protected IDictionary<string, string> AxesTitles
{
get { return _AxesTitles; }
}
private SortedList<string, ZedGraph.FilteredPointList> _Plots = new SortedList<string, ZedGraph.FilteredPointList>();
protected IDictionary<string, ZedGraph.FilteredPointList> Plots
{
get { return _Plots; }
}
private SortedList<string, ZedGraph.LineItem> _Curves = new SortedList<string, ZedGraph.LineItem>();
protected IDictionary<string, ZedGraph.LineItem> Curves
{
get { return _Curves; }
}
private SortedList<string, ZedGraph.Axis> _Axes = new SortedList<string, ZedGraph.Axis>();
protected IDictionary<string, ZedGraph.Axis> Axes
{
get { return _Axes; }
}
public RecordingDataGraphControl()
{
InitializeComponent();
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
ResetGraph();
}
protected virtual void SetAxisLocation(string dataName, AxisLocation location)
{
if (_AxesLocations.ContainsKey(dataName))
_AxesLocations[dataName] = location;
else _AxesLocations.Add(dataName, location);
OnAxesLocationsChanged(EventArgs.Empty);
}
protected virtual void OnAxesLocationsChanged(EventArgs e)
{
if (InvokeRequired)
{
Invoke(new Action<EventArgs>(OnAxesLocationsChanged), e);
return;
}
if(AxesLocationsChanged != null)
try
{
AxesLocationsChanged(this, e);
}
catch (Exception x) { ; }
}
protected virtual void OnCurrentRecordingIDChanged(EventArgs e)
{
if (RecordingBindingSource.DataSource != null)
try
{
RecordingBindingSource.Position = RecordingBindingSource.Find("RecordingID", CurrentRecordingID);
RecordingBindingSource.ResetBindings(false);
RecordingBindingSource.ResetCurrentItem();
RecordingDataBindingSource.ResetBindings(false);
}
catch (Exception x) { ; }
OnCurrentRecordingChanged(this, e);
if (CurrentRecordingIDChanged != null) CurrentRecordingIDChanged(this, EventArgs.Empty);
}
protected virtual void SetAxisMode(string dataName, AxisMode mode)
{
if (_AxesModes.ContainsKey(dataName) && _AxesModes[dataName] != mode)
{
_AxesModes[dataName] = mode;
OnAxesModesChanged(EventArgs.Empty);
}
else
{
_AxesModes.Add(dataName, mode);
OnAxesModesChanged(EventArgs.Empty);
}
}
protected virtual void OnAxesModesChanged(EventArgs e)
{
if (InvokeRequired)
{
Invoke(new Action<EventArgs>(OnAxesModesChanged), e);
return;
}
ResetGraph();
if (AxesModesChanged != null)
try {
AxesModesChanged(this, e);
} catch(Exception x) { ; }
}
protected virtual void OnIsDarkRoomStyleChanged(EventArgs e)
{
if (IsDarkRoomStyleChanged != null)
try
{
IsDarkRoomStyleChanged(this, e);
}
catch (Exception x) { ; }
}
protected virtual void OnIsTitleVisibleChanged(EventArgs e)
{
if (InvokeRequired)
{
Invoke(new Action<EventArgs>(OnIsTitleVisibleChanged), e);
return;
}
RecordingDataGraph.GraphPane.Title.IsVisible = IsTitleVisible;
RecordingDataGraph.Invalidate();
if (IsTitleVisibleChanged != null)
try
{
IsTitleVisibleChanged(this, e);
}
catch (Exception x) { ; }
}
protected virtual void OnIsLegendVisibleChanged(EventArgs e)
{
if (InvokeRequired)
{
Invoke(new Action<EventArgs>(OnIsLegendVisibleChanged), e);
return;
}
RecordingDataGraph.GraphPane.Legend.IsVisible = IsLegendVisible;
RecordingDataGraph.Invalidate();
if (IsLegendVisibleChanged != null)
try
{
IsLegendVisibleChanged(this, e);
}
catch (Exception x) { ; }
}
protected virtual void OnDataSetChanged(EventArgs e)
{
if (InvokeRequired)
{
Invoke(new Action<EventArgs>(OnDataSetChanged), e);
return;
}
if (AreUpdatesSuspended) return;
if (DataSet != null) RecordingBindingSource.DataSource = DataSet;
else RecordingBindingSource.DataSource = typeof(PhysiologyDataSet);
if (DataSetChanged != null)
try
{
DataSetChanged(this, EventArgs.Empty);
}
catch (Exception x) { ; }
}
protected virtual void OnShowTitleChecked(object sender, EventArgs e)
{
IsTitleVisible = ShowTitleCheckBox.Checked;
}
protected virtual void OnShowLegendChecked(object sender, EventArgs e)
{
IsLegendVisible = ShowLegendCheckBox.Checked;
}
protected virtual void OnUseDarkRoomStyleChecked(object sender, EventArgs e)
{
IsDarkRoomStyle = DarkRoomCheckBox.Checked;
}
protected virtual void OnIsSidebarVisibleChanged(EventArgs e)
{
if (InvokeRequired) {
Invoke(new Action<EventArgs>(OnIsSidebarVisibleChanged), e);
return;
}
// Hide the panel
HideablePanel.Visible = IsSidebarVisible;
// Update the button label
if (IsSidebarVisible)
ToggleHiddenButton.Text = "Hide >>>";
else ToggleHiddenButton.Text = "<<<";
if(IsSidebarVisibleChanged != null)
try
{
IsSidebarVisibleChanged(this, e);
}
catch (Exception x) { ; }
}
protected virtual void UpdateAvailableDataList()
{
if (InvokeRequired)
{
Invoke(new ThreadStart(UpdateAvailableDataList));
return;
}
// Figure out the items that are not checked, since the default is to be checked
List<string> notChecked = new List<string>(AvailableDataCheckedListBox.Items.Count);
foreach (string s in AvailableDataCheckedListBox.Items)
if (!AvailableDataCheckedListBox.CheckedItems.Contains(s))
notChecked.Add(s);
// Clear the list
AvailableDataCheckedListBox.Items.Clear();
// Load the new data
if (DataSet != null)
{
if (CurrentRecordingsRow != null)
{
List<string> channels = new List<string>(CurrentRecordingsRow.GetDataNames());
foreach (string channel in channels)
{
IDictionary<string, AxisMode> axisModeMetaData = GetAxesModesFromMetaData();
IDictionary<string, AxisLocation> axisLocationMetaData = GetAxesLocationsFromMetaData();
if (!AxesLocations.ContainsKey(channel))
{
if (axisModeMetaData != null && axisModeMetaData.ContainsKey(channel))
SetAxisLocation(channel, axisLocationMetaData[channel]);
else SetAxisLocation(channel, DefaultAxisLocation);
}
if (!AxesModes.ContainsKey(channel))
{
if (axisLocationMetaData != null && axisLocationMetaData.ContainsKey(channel))
SetAxisMode(channel, axisModeMetaData[channel]);
else SetAxisMode(channel, DefaultAxisMode);
}
}
// Set shown items
_DataNames.Clear();
_DataNames.AddRange(channels.ToArray());
OnDataNamesChanged(EventArgs.Empty);
List<string> dataToShowMetaData = new List<string>();
if (CurrentRecordingsRow.DoesMetaDataExist("DataToShow"))
dataToShowMetaData = new List<string>(CurrentRecordingsRow.GetMetaData("DataToShow").Split(','));
for (int i = 0; i < dataToShowMetaData.Count; i++)
dataToShowMetaData[i] = dataToShowMetaData[i].Trim();
if (dataToShowMetaData.Count == 0)
dataToShowMetaData.AddRange(DataNames);
AvailableDataCheckedListBox.Items.Clear();
foreach (string dataName in DataNames)
AvailableDataCheckedListBox.Items.Add(dataName, (!notChecked.Contains(dataName) && dataToShowMetaData.Contains(dataName)));
}
}
OnShownDataListChanged(EventArgs.Empty); // Since the available data changed, update the list
}
private List<string> _DataNames = new List<string>();
public IList<string> DataNames
{
get { return _DataNames; }
}
protected virtual IList<string> GetDataToShowFromMetaData()
{
if(CurrentRecordingsRow == null) return null;
// Format: DataName,DataName2, DataName3, etc.
if(CurrentRecordingsRow.DoesMetaDataExist("DataToShow")) {
string dataToShowList = CurrentRecordingsRow.GetMetaData("DataToShow");
string[] dataToShow = dataToShowList.Split(',');
List<string> output = new List<string>();
foreach (string dataName in dataToShow)
output.Add(dataName.Trim());
return output;
} else return null;
}
protected virtual IDictionary<string, AxisMode> GetAxesModesFromMetaData()
{
if (CurrentRecordingsRow == null) return null;
if(CurrentRecordingsRow.DoesMetaDataExist("AxesModes")) {
// Format: DataName=AxisMode,DataName2=AxisMode
string axesModesList = CurrentRecordingsRow.GetMetaData("AxesModes");
string[] axesModeAssignments =axesModesList.Split(',');
SortedList<string, AxisMode> axesModes = new SortedList<string, AxisMode>();
foreach(string assignment in axesModeAssignments) {
string[] split = assignment.Split('=');
if(split.Length != 2) continue; // Invalid format
AxisMode mode = AxisMode.Auto; // Default
if(split[1].Trim() == "DynamicRange") mode = AxisMode.DynamicRange;
axesModes.Add(split[0].Trim(), mode);
}
return axesModes;
} else return null;
}
protected virtual IDictionary<string, AxisLocation> GetAxesLocationsFromMetaData()
{
if (CurrentRecordingsRow == null) return null;
if (CurrentRecordingsRow.DoesMetaDataExist("AxesLocations"))
{
// Format: DataName=AxisLocation,DataName2=AxisLocation
string axesLocationsList = CurrentRecordingsRow.GetMetaData("AxesLocations");
string[] axesLocationAssignments = axesLocationsList.Split(',');
SortedList<string, AxisLocation> axesLocations = new SortedList<string, AxisLocation>();
foreach (string assignment in axesLocationAssignments)
{
string[] split = assignment.Split('=');
if (split.Length != 2) continue; // Invalid format
AxisLocation location = AxisLocation.Left; // Default
if (split[1].Trim() == "Right") location = AxisLocation.Right;
axesLocations.Add(split[0].Trim(), location);
}
return axesLocations;
}
else return null;
}
protected virtual void OnAvailableDataItemChecked(object sender, ItemCheckEventArgs e)
{
SetDataVisible(AvailableDataCheckedListBox.Items[e.Index].ToString(), e.NewValue == CheckState.Checked);
}
public virtual void SetDataVisible(string dataName, bool isVisible)
{
if (InvokeRequired)
{
Invoke(new ThreadStart(delegate()
{
SetDataVisible(dataName, isVisible);
}));
return;
}
if (Curves.ContainsKey(dataName))
{
Curves[dataName].IsVisible = isVisible;
Curves[dataName].Label.IsVisible = isVisible;
}
if (Axes.ContainsKey(dataName))
Axes[dataName].IsVisible = isVisible;
RecordingDataGraph.Invalidate();
//if (AvailableDataCheckedListBox.GetItemChecked(AvailableDataCheckedListBox.Items.IndexOf(dataName))
// != isVisible)
// AvailableDataCheckedListBox.SetItemChecked(AvailableDataCheckedListBox.Items.IndexOf(dataName), isVisible);
}
protected virtual void OnShownDataListChanged(EventArgs e)
{
if (InvokeRequired)
{
Invoke(new Action<EventArgs>(OnShownDataListChanged), e);
return;
}
//try
//{
// ConfigureAxes();
// UpdatePlots();
// UpdateCurves();
// try
// {
// RecordingDataGraph.AxisChange();
// }
// catch (Exception x) { ; }
// RecordingDataGraph.Invalidate();
//}
//catch (Exception x)
//{
// MessageBox.Show("Error updating graph: " + x.Message);
//}
if(ShownDataListChanged != null)
try
{
ShownDataListChanged(this, e);
}
catch (Exception x) { ; }
}
public virtual void ConfigureGraph()
{
if (InvokeRequired)
{
Invoke(new ThreadStart(ConfigureGraph));
return;
}
if (IsDarkRoomStyle)
{
RecordingDataGraph.GraphPane.Fill.Color = Color.Black;
RecordingDataGraph.GraphPane.Title.FontSpec.FontColor = Color.White;
RecordingDataGraph.GraphPane.Border.Color = Color.White;
RecordingDataGraph.GraphPane.Legend.FontSpec.FontColor = Color.White;
RecordingDataGraph.GraphPane.Chart.Border.Color = Color.White;
RecordingDataGraph.GraphPane.Chart.Fill.Color = Color.Black;
RecordingDataGraph.GraphPane.Chart.Fill.Type = ZedGraph.FillType.Solid;
RecordingDataGraph.ForeColor = Color.White;
RecordingDataGraph.BackColor = Color.Black;
}
else
{
RecordingDataGraph.GraphPane.Chart.Fill.Color = GraphBackColor;
RecordingDataGraph.GraphPane.Chart.Fill.Type = ZedGraph.FillType.GradientByX;
}
}
protected virtual void ConfigureAxes()
{
if (InvokeRequired)
{
Invoke(new ThreadStart(ConfigureAxes));
return;
}
RecordingDataGraph.GraphPane.XAxis.Title.Text = "Time (ms)";
RecordingDataGraph.GraphPane.XAxis.Scale.MinGrace = 0;
RecordingDataGraph.GraphPane.XAxis.Scale.MinAuto = true;
RecordingDataGraph.GraphPane.XAxis.Scale.MaxGrace = 0;
RecordingDataGraph.GraphPane.XAxis.Scale.MaxAuto = true;
if (IsDarkRoomStyle)
{
RecordingDataGraph.GraphPane.XAxis.Color = Color.White;
RecordingDataGraph.GraphPane.XAxis.MinorTic.Color = Color.White;
RecordingDataGraph.GraphPane.XAxis.MajorTic.Color = Color.White;
RecordingDataGraph.GraphPane.XAxis.Title.FontSpec.FontColor = Color.White;
RecordingDataGraph.GraphPane.XAxis.Scale.FontSpec.FontColor = Color.White;
}
RecordingDataGraph.GraphPane.YAxisList.Clear();
RecordingDataGraph.GraphPane.Y2AxisList.Clear();
foreach (string dataName in DataNames)
{
string axisTitle = GetAxisTitle(dataName);
ZedGraph.Axis yaxis = null;
if (AxesLocations[dataName] == AxisLocation.Left)
{
if (RecordingDataGraph.GraphPane.YAxisList.IndexOf(axisTitle) < 0)
RecordingDataGraph.GraphPane.YAxisList.Add(axisTitle);
yaxis = RecordingDataGraph.GraphPane.YAxisList[axisTitle];
}
else
{
if (RecordingDataGraph.GraphPane.Y2AxisList.IndexOf(axisTitle) < 0)
RecordingDataGraph.GraphPane.Y2AxisList.Add(axisTitle);
yaxis = RecordingDataGraph.GraphPane.Y2AxisList[axisTitle];
}
// Store axis
if (!_Axes.ContainsKey(dataName))
_Axes.Add(dataName, yaxis);
else _Axes[dataName] = yaxis;
// Set visibility
yaxis.IsVisible = ShownDataList.Contains(dataName);
// Dark room sstyle
if (IsDarkRoomStyle)
{
yaxis.Color = Color.White;
yaxis.MinorTic.Color = Color.White;
yaxis.MajorTic.Color = Color.White;
yaxis.Title.FontSpec.FontColor = Color.White;
yaxis.Scale.FontSpec.FontColor = Color.White;
}
if (AxesModes[dataName] == AxisMode.Auto)
{
//yaxis.Scale.MinAuto = true;
//yaxis.Scale.MinGrace = 0.1;
//yaxis.Scale.MaxAuto = true;
//yaxis.Scale.MaxGrace = 0.1;
Range dataRange = FindRange(dataName);
yaxis.Scale.Min = dataRange.Min;
yaxis.Scale.Max = dataRange.Max;
}
else
{
try
{
double min;
double max;
if (dataName == "Current")
{
double gain = 1000 / Double.Parse(CurrentRecordingsRow.GetEquipmentSetting("AmplifierGain")); // gain is in pA/V
min = -10 * gain;
max = 10 * gain;
}
else
{
min = Double.Parse(CurrentRecordingsRow.GetEquipmentSetting("DynamicRange-Min:" + dataName));
max = Double.Parse(CurrentRecordingsRow.GetEquipmentSetting("DynamicRange-Max:" + dataName));
}
yaxis.Scale.MinAuto = false;
yaxis.Scale.Min = min;
yaxis.Scale.MaxAuto = false;
yaxis.Scale.Max = max;
}
catch (Exception x)
{
//yaxis.Scale.MinAuto = true;
//yaxis.Scale.MinGrace = 0;
//yaxis.Scale.MaxAuto = true;
//yaxis.Scale.MaxGrace = 0;
Range dataRange = FindRange(dataName);
yaxis.Scale.Min = dataRange.Min;
yaxis.Scale.Max = dataRange.Max;
}
}
}
if (RecordingDataGraph.GraphPane.YAxisList.Count == 0)
RecordingDataGraph.GraphPane.YAxisList.Add("");
RecordingDataGraph.Invalidate();
}
protected virtual string GetAxisTitle(string dataName)
{
string title = dataName;
if (!_AxesTitles.ContainsKey(dataName)) _AxesTitles.Add(dataName, title);
else _AxesTitles[dataName] = title;
return title;
}
protected virtual void UpdatePlots()
{
if (InvokeRequired)
{
Invoke(new ThreadStart(UpdatePlots));
return;
}
DateTime start = DateTime.Now;
foreach (string dataName in DataNames)
{
TimeResolvedData data = CurrentRecordingsRow.GetData(dataName);
ZedGraph.FilteredPointList points = new ZedGraph.FilteredPointList(Array.ConvertAll<float,double>(data.Time, new Converter<float,double>(delegate(float value) {
return (double) value; })), data.Values);
// If this plot has already been made, skip it
if (!_Plots.ContainsKey(dataName))
{
_Plots.Add(dataName, points);
//ZedGraph.DataSourcePointList points = new ZedGraph.DataSourcePointList();
//_Plots.Add(dataName, points);
//BindingSource bs = new BindingSource(RecordingBindingSource, "FK_Recordings_Recording_Data");
//bs.Filter = "DataName = '" + dataName + "'";
//points.DataSource = bs;
//points.XDataMember = "Time";
//points.YDataMember = "Value";
}
else _Plots[dataName] = points;
}
TimeSpan span = DateTime.Now - start;
Console.WriteLine("Plots took " + span.ToString());
}
public virtual void ResetGraph()
{
if (InvokeRequired)
{
Invoke(new System.Threading.ThreadStart(ResetGraph));
return;
}
ResetColorCounter();
_AxesTitles.Clear();
_Curves.Clear();
_Plots.Clear();
RecordingDataGraph.GraphPane.CurveList.Clear();
RecordingDataGraph.GraphPane.YAxisList.Clear();
RecordingDataGraph.GraphPane.YAxisList.Add("");
RecordingDataGraph.GraphPane.Y2AxisList.Clear();
if (DataSet == null) return;
try
{
UpdateAvailableDataList();
ConfigureGraph();
ConfigureAxes();
UpdatePlots();
UpdateCurves();
try
{
RecordingDataGraph.AxisChange();
}
catch (Exception x) { ; }
RecordingDataGraph.Invalidate();
}
catch (Exception x)
{
MessageBox.Show("Error updating graph: " + x.Message);
}
}
public virtual void RefreshGraphData()
{
if (InvokeRequired)
{
Invoke(new ThreadStart(RefreshGraphData));
return;
}
_Plots.Clear();
_Curves.Clear();
RecordingDataGraph.GraphPane.CurveList.Clear();
UpdatePlots();
UpdateCurves();
try
{
RecordingDataGraph.AxisChange();
}
catch { ; }
Invalidate();
}
protected virtual void UpdateCurves()
{
foreach (string dataName in DataNames)
{
ZedGraph.LineItem curve;
if (!_Curves.ContainsKey(dataName))
{
curve = RecordingDataGraph.GraphPane.AddCurve(dataName, Plots[dataName], GetNextColor(), ZedGraph.SymbolType.None);
_Curves.Add(dataName, curve);
}
else curve = _Curves[dataName];
curve.Line.Width = 1.5F;
curve.Line.IsAntiAlias = AntialiasCurves;
curve.IsVisible = ShownDataList.Contains(dataName);
curve.Label.IsVisible = ShownDataList.Contains(dataName);
if (AxesLocations.ContainsKey(dataName) && AxesLocations[dataName] == AxisLocation.Right)
{
curve.IsY2Axis = true;
curve.YAxisIndex = GetYAxisIndex(dataName, true);
}
else
{
curve.IsY2Axis = false;
curve.YAxisIndex = GetYAxisIndex(dataName, false);
}
}
}
private List<Color> _Colors = new List<Color>(new Color[] {
Color.Blue, Color.Red, Color.Green, Color.Brown, Color.Crimson });
private List<Color> _DarkRoomColors = new List<Color>(new Color[] {
Color.Yellow, Color.Pink, Color.Cyan, Color.Lime, Color.White
});
private int _ColorsIndex = 0;
protected virtual Color GetNextColor()
{
List<Color> Colors;
if (IsDarkRoomStyle) Colors = _DarkRoomColors;
else Colors = _Colors;
if (_ColorsIndex >= Colors.Count) ResetColorCounter();
return Colors[_ColorsIndex++];
}
protected virtual void ResetColorCounter()
{
_ColorsIndex = 0;
}
protected virtual int GetYAxisIndex(string dataName, bool isY2)
{
if(isY2)
return RecordingDataGraph.GraphPane.Y2AxisList.IndexOf(AxesTitles[dataName]);
else return RecordingDataGraph.GraphPane.YAxisList.IndexOf(AxesTitles[dataName]);
}
protected virtual void OnToggleHiddenClicked(object sender, EventArgs e)
{
IsSidebarVisible = !IsSidebarVisible;
}
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
protected void NotifyPropertyChanged(string property)
{
if(PropertyChanged != null)
try
{
PropertyChanged(this, new PropertyChangedEventArgs(property));
}
catch (Exception e) { ; }
}
#endregion
protected virtual void OnCurrentRecordingChanged(object sender, EventArgs e)
{
if (InvokeRequired)
{
Invoke(new EventHandler(OnCurrentRecordingChanged), sender, e);
return;
}
if (IsAutoUpdateDisabled) return;
if (CurrentRecordingsRow != null)
{
RecordingDataGraph.GraphPane.Title.Text = CurrentRecordingsRow.Title;
Enabled = true;
}
else
{
RecordingDataGraph.GraphPane.Title.Text = "No Recording Selected";
Enabled = false;
}
ResetGraph();
}
protected virtual void OnDataNamesChanged(EventArgs e)
{
if (InvokeRequired)
{
Invoke(new Action<EventArgs>(OnDataNamesChanged), e);
return;
}
AxisComboBox.Items.Clear();
AxisComboBox.Items.AddRange(_DataNames.ToArray());
if(AxisComboBox.Items.Count != 0) AxisComboBox.SelectedIndex = 0;
}
protected virtual void OnSelectedAxisChanged(object sender, EventArgs e)
{
if (InvokeRequired)
{
Invoke(new EventHandler(OnSelectedAxisChanged), sender, e);
return;
}
if (!AxesLocations.ContainsKey(AxisComboBox.Text) ||
AxesLocations[AxisComboBox.Text] == AxisLocation.Left)
AxisPlacementComboBox.SelectedItem = "Left";
else AxisPlacementComboBox.SelectedItem = "Right";
if (!AxesModes.ContainsKey(AxisComboBox.Text) ||
AxesModes[AxisComboBox.Text] == AxisMode.Auto)
AxisModeComboBox.SelectedItem = "Auto";
else AxisModeComboBox.SelectedItem = "Dynamic Range";
}
protected virtual void OnSelectedPlacementChanged(object sender, EventArgs e)
{
if(InvokeRequired) {
Invoke(new EventHandler(OnSelectedPlacementChanged),sender,e);
return;
}
if (!DataNames.Contains(AxisComboBox.Text)) return;
if (!AxesLocations.ContainsKey(AxisComboBox.Text))
AxesLocations.Add(AxisComboBox.Text, AxisLocation.Left);
if (AxisPlacementComboBox.Text == "Left")
AxesLocations[AxisComboBox.Text] = AxisLocation.Left;
else AxesLocations[AxisComboBox.Text] = AxisLocation.Right;
ResetGraph();
RecordingDataGraph.Invalidate();
}
private void OnSelectedModeChanged(object sender, EventArgs e)
{
if(InvokeRequired) {
Invoke(new EventHandler(OnSelectedModeChanged),sender,e);
return;
}
if (!DataNames.Contains(AxisComboBox.Text)) return;
if (!AxesModes.ContainsKey(AxisComboBox.Text))
AxesModes.Add(AxisComboBox.Text, AxisMode.Auto);
if (AxisModeComboBox.Text == "Data")
AxesModes[AxisComboBox.Text] = AxisMode.Auto;
else AxesModes[AxisComboBox.Text] = AxisMode.DynamicRange;
ConfigureAxes();
UpdatePlots();
UpdateCurves();
RecordingDataGraph.Invalidate();
}
protected virtual void OnRecordingDataChanged(object sender, ListChangedEventArgs e)
{
if (DataSet == null) return;
if (!IsAutoUpdateDisabled && !AreUpdatesSuspended)
{
RefreshGraphData();
}
}
private bool _AreUpdatesSuspended = false;
protected bool AreUpdatesSuspended
{
get
{
return _AreUpdatesSuspended;
}
set
{
_AreUpdatesSuspended = value;
}
}
public void SuspendUpdates()
{
AreUpdatesSuspended = true;
RecordingBindingSource.SuspendBinding();
RecordingDataBindingSource.SuspendBinding();
}
public void ResumeUpdates()
{
AreUpdatesSuspended = false;
RecordingBindingSource.ResumeBinding();
RecordingDataBindingSource.ResumeBinding();
OnCurrentRecordingIDChanged(EventArgs.Empty);
ResetGraph();
}
protected Range FindRange(string dataName)
{
List<double> values = new List<double>();
PhysiologyDataSet.Recordings_DataRow[] rows = DataSet.Recordings_Data.Select(
String.Format("RecordingID = {0} AND DataName = '{1}'", CurrentRecordingID, dataName),
"Value") as PhysiologyDataSet.Recordings_DataRow[];
if (rows == null || rows.Length == 0) return new Range(0, 1);
else return new Range(rows[0].Value, rows[rows.Length-1].Value);
}
protected struct Range
{
public double Min;
public double Max;
public Range(double min, double max)
{
Min = min;
Max = max;
}
}
public event EventHandler AntialiasCurvesChanged;
private bool _AntialiasCurves = false;
[Bindable(true)]
[SettingsBindable(true)]
[DefaultValue(false)]
public bool AntialiasCurves
{
get { return _AntialiasCurves; }
set {
_AntialiasCurves = value;
if(AntialiasCurvesChanged != null)
try
{
AntialiasCurvesChanged(this, EventArgs.Empty);
}
catch (Exception x) { ; }
NotifyPropertyChanged("AntialiasCurves");
ResetGraph();
}
}
protected virtual void OnAntialiasCurvesChecked(object sender, EventArgs e)
{
AntialiasCurves = AntialiasCheckBox.Checked;
}
}
}
| |
using System;
using System.Linq;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Text;
using Newtonsoft.Json;
using System.Diagnostics;
using Infrastructure;
namespace Infrastructure.Testing
{
public class InTheTestsFor<TAggregate> where TAggregate : AggregateRoot, new()
{
public string Role { get; private set; }
public string Feature { get; private set; }
public string Benefit { get; private set; }
public List<Test<TAggregate>> _tests = null;
public List<Test<TAggregate>> Tests
{
get
{
if (this._tests == null) { _tests = new List<Test<TAggregate>>(); }
return _tests;
}
private set
{
this._tests = value;
}
}
public Test<TAggregate> _currentTest = null;
public Test<TAggregate> CurrentTest
{
get
{
if (this._currentTest == null) { _currentTest = new Test<TAggregate>(); }
return _currentTest;
}
private set
{
this._currentTest = value;
}
}
public static InTheTestsFor<TAggregate> AsA(string role) {
var v = new InTheTestsFor<TAggregate>();
v.Role = role;
return v;
}
public InTheTestsFor<TAggregate> SoThat(string benefit) {
this.Benefit = benefit;
return this;
}
public InTheTestsFor<TAggregate> IWant(string feature) {
this.Feature = feature;
return this;
}
public InTheTestsFor<TAggregate> For() {
return this;
}
public InTheTestsFor<TAggregate> Given(params Event[] startingEvents) {
this.CurrentTest.Arrange = startingEvents ?? new Event[0];
AssignTests();
return this;
}
public InTheTestsFor<TAggregate> When(Expression<Action<TAggregate>> test){
this.CurrentTest.Act = test;
AssignTests();
return this;
}
public InTheTestsFor<TAggregate> Then(Func<InTheTestsFor<TAggregate>,IEnumerable<Expression<Func<IEnumerable<Event>,bool>>>> tests) {
this.CurrentTest.Assert = tests(this);
AssignTests();
return this;
}
private void AssignTests() {
var result = UpdateTests(this.Tests, this.CurrentTest);
this.CurrentTest = result.Item1;
this.Tests = result.Item2;
}
// Only prints out failed tests.
public bool Results() {
var results = Tests.Select(Test => new{ Test, TestResults = Test.TestsPass() });
results.ForEach(result => {
var canprint = result.TestResults.Select(t => t.Item1).Any(t => t);
if (canprint) {
Debug.WriteLine(result.Test.ToString());
}
result.TestResults.Where(v => v.Item1).Select(
value =>
(value.Item1
? "PASSED"
: "FAILED") + "\t" +
value.Item2)
.ForEach(i => Debug.WriteLine(i));
});
return results.SelectMany(i => i.TestResults.Select(j => j.Item1)).All(i => i);
}
// Prints out all tests
public bool FullResults() {
var results = Tests.Select(Test => new{ Test, TestResults = Test.TestsPass() });
results.ForEach(result => {
Debug.WriteLine(result.Test.ToString());
result.TestResults.Select(
value =>
(value.Item1
? "PASSED"
: "FAILED") + "\t" +
value.Item2)
.ForEach(i => Debug.WriteLine(i));
});
return results.SelectMany(i => i.TestResults.Select(j => j.Item1)).All(i => i);
}
public IEnumerable<Expression<Func<IEnumerable<Event>,bool>>> ExpectTheFollowingEvents(params Expression<Func<IEnumerable<Event>,bool>>[] conditions) {
foreach (var condition in conditions)
{
yield return condition;
}
}
public override string ToString() {
return new[] { Role, Feature, Benefit}.Any(i => string.IsNullOrWhiteSpace(i))
? base.ToString()
: string.Format(
string.Join(Environment.NewLine,
new [] {"As a {0} ", "So that {1}", "I want {2}"}),
Role, Feature, Benefit);
}
private bool IsComplete(Test<TAggregate> test) {
return new object [] { test.Arrange, test.Act, test.Assert }.All(x => x != null) &&
new IEnumerable<object>[] { test.Arrange, test.Assert }.All(x => !x.IsEmpty());
}
private Tuple<Test<TAggregate>,List<Test<TAggregate>>> UpdateTests(List<Test<TAggregate>> tests, Test<TAggregate> test) {
Test<TAggregate> returnTest;
if (IsComplete(test))
{
tests.Add(test);
returnTest = new Test<TAggregate>();
} else {
returnTest = test;
}
return Tuple.Create(returnTest, tests);
}
}
public class Test<TAggregate> where TAggregate : AggregateRoot, new() {
public IEnumerable<Event> Arrange { get; set; }
public Expression<Action<TAggregate>> Act { get; set; }
public IEnumerable<Expression<Func<IEnumerable<Event>,bool>>> Assert { get; set; }
public IEnumerable<Tuple<bool,string>> TestsPass() {
var sut = new TAggregate();
sut.LoadsFromHistory(Arrange);
Act.Compile().Invoke(sut);
var results = sut.GetUncommittedChanges();
foreach (var test in Assert)
{
yield return IndividualTestPasses(test, results);
}
}
private Tuple<bool,string> IndividualTestPasses(Expression<Func<IEnumerable<Event>,bool>> test, IEnumerable<Event> results) {
var testText = test.ToString();
var testResult = test.Compile().Invoke(results);
return Tuple.Create(testResult, string.Join(Environment.NewLine, testText, "Applied with", JsonConvert.SerializeObject(results)));
}
public override string ToString() {
var sb = new StringBuilder();
sb.AppendLine(JsonConvert.SerializeObject(this.Arrange));
sb.Append(this.Act.ToString());
foreach (var test in this.Assert)
{
sb.Append(test.ToString());
}
return sb.ToString();
}
}
// public class Scenario<TEntity> {
// public Event[] Given { get; private set; }
// public Expression<Action<TEntity>> When { get; private set; }
// public Expression<Func<Event[],bool>>[] Then { get; private set; }
//
// public Scenario(Event[] Given, Expression<Action<TEntity>> When, params Expression<Func<Event[],bool>>[] Then) {
// this.Given = Given;
// this.When = When;
// this.Then = Then;
// }
// }
//
// public interface Story {
// string Role { get; }
// string Feature { get; }
// string Benefit { get; }
// }
//
// public class ReportWriter
// {
// public string WriteReport<T>(Story story = null, params Scenario<T>[] scenarios) {
// var content = new StringBuilder();
// foreach (var scenario in scenarios)
// {
//
// }
// return content.ToString();
// }
//
// public string TestScenario<T>(Scenario<T> scenario) {
//
// }
// }
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics.Contracts;
using System.Runtime;
using System.Security.Authentication.ExtendedProtection;
using System.ServiceModel.Channels.ConnectionHelpers;
using System.ServiceModel.Security;
using System.Threading.Tasks;
namespace System.ServiceModel.Channels
{
internal class StreamedFramingRequestChannel : RequestChannel
{
internal IConnectionInitiator _connectionInitiator;
internal ConnectionPool _connectionPool;
private MessageEncoder _messageEncoder;
private IConnectionOrientedTransportFactorySettings _settings;
private byte[] _startBytes;
private StreamUpgradeProvider _upgrade;
private ChannelBinding _channelBindingToken;
public StreamedFramingRequestChannel(ChannelManagerBase factory, IConnectionOrientedTransportChannelFactorySettings settings,
EndpointAddress remoteAddresss, Uri via, IConnectionInitiator connectionInitiator, ConnectionPool connectionPool)
: base(factory, remoteAddresss, via, settings.ManualAddressing)
{
_settings = settings;
_connectionInitiator = connectionInitiator;
_connectionPool = connectionPool;
_messageEncoder = settings.MessageEncoderFactory.Encoder;
_upgrade = settings.Upgrade;
}
private byte[] Preamble
{
get { return _startBytes; }
}
protected internal override Task OnOpenAsync(TimeSpan timeout)
{
return TaskHelpers.CompletedTask();
}
protected override IAsyncResult OnBeginOpen(TimeSpan timeout, AsyncCallback callback, object state)
{
return OnOpenAsync(timeout).ToApm(callback, state);
}
protected override void OnEndOpen(IAsyncResult result)
{
result.ToApmEnd();
}
protected override void OnOpen(TimeSpan timeout)
{
}
protected override void OnOpened()
{
// setup our preamble which we'll use for all connections we establish
EncodedVia encodedVia = new EncodedVia(this.Via.AbsoluteUri);
EncodedContentType encodedContentType = EncodedContentType.Create(_settings.MessageEncoderFactory.Encoder.ContentType);
int startSize = ClientSingletonEncoder.ModeBytes.Length + ClientSingletonEncoder.CalcStartSize(encodedVia, encodedContentType);
int preambleEndOffset = 0;
if (_upgrade == null)
{
preambleEndOffset = startSize;
startSize += ClientDuplexEncoder.PreambleEndBytes.Length;
}
_startBytes = Fx.AllocateByteArray(startSize);
Buffer.BlockCopy(ClientSingletonEncoder.ModeBytes, 0, _startBytes, 0, ClientSingletonEncoder.ModeBytes.Length);
ClientSingletonEncoder.EncodeStart(_startBytes, ClientSingletonEncoder.ModeBytes.Length, encodedVia, encodedContentType);
if (preambleEndOffset > 0)
{
Buffer.BlockCopy(ClientSingletonEncoder.PreambleEndBytes, 0, _startBytes, preambleEndOffset, ClientSingletonEncoder.PreambleEndBytes.Length);
}
// and then transition to the Opened state
base.OnOpened();
}
protected override IAsyncRequest CreateAsyncRequest(Message message)
{
return new StreamedConnectionPoolHelper.StreamedFramingAsyncRequest(this);
}
internal IConnection SendPreamble(IConnection connection, ref TimeoutHelper timeoutHelper,
ClientFramingDecoder decoder, out SecurityMessageProperty remoteSecurity)
{
connection.Write(Preamble, 0, Preamble.Length, true, timeoutHelper.RemainingTime());
if (_upgrade != null)
{
IStreamUpgradeChannelBindingProvider channelBindingProvider = _upgrade.GetProperty<IStreamUpgradeChannelBindingProvider>();
StreamUpgradeInitiator upgradeInitiator = _upgrade.CreateUpgradeInitiator(this.RemoteAddress, this.Via);
if (!ConnectionUpgradeHelper.InitiateUpgrade(upgradeInitiator, ref connection, decoder,
this, ref timeoutHelper))
{
ConnectionUpgradeHelper.DecodeFramingFault(decoder, connection, Via, _messageEncoder.ContentType, ref timeoutHelper);
}
#if FEATURE_CORECLR // ExtendedProtection
if (channelBindingProvider != null && channelBindingProvider.IsChannelBindingSupportEnabled)
{
_channelBindingToken = channelBindingProvider.GetChannelBinding(upgradeInitiator, ChannelBindingKind.Endpoint);
}
#endif // FEATURE_CORECLR // ExtendedProtection
remoteSecurity = StreamSecurityUpgradeInitiator.GetRemoteSecurity(upgradeInitiator);
connection.Write(ClientSingletonEncoder.PreambleEndBytes, 0,
ClientSingletonEncoder.PreambleEndBytes.Length, true, timeoutHelper.RemainingTime());
}
else
{
remoteSecurity = null;
}
// read ACK
byte[] ackBuffer = new byte[1];
int ackBytesRead = connection.Read(ackBuffer, 0, ackBuffer.Length, timeoutHelper.RemainingTime());
if (!ConnectionUpgradeHelper.ValidatePreambleResponse(ackBuffer, ackBytesRead, decoder, this.Via))
{
ConnectionUpgradeHelper.DecodeFramingFault(decoder, connection, Via, _messageEncoder.ContentType, ref timeoutHelper);
}
return connection;
}
internal async Task<IConnection> SendPreambleAsync(IConnection connection, TimeoutHelper timeoutHelper, ClientFramingDecoder decoder)
{
await connection.WriteAsync(Preamble, 0, Preamble.Length, true, timeoutHelper.RemainingTime());
if (_upgrade != null)
{
StreamUpgradeInitiator upgradeInitiator = _upgrade.CreateUpgradeInitiator(this.RemoteAddress, this.Via);
await upgradeInitiator.OpenAsync(timeoutHelper.RemainingTime());
var connectionWrapper = new OutWrapper<IConnection>();
connectionWrapper.Value = connection;
bool upgradeInitiated = await ConnectionUpgradeHelper.InitiateUpgradeAsync(upgradeInitiator, connectionWrapper, decoder, this, timeoutHelper.RemainingTime());
connection = connectionWrapper.Value;
if (!upgradeInitiated)
{
await ConnectionUpgradeHelper.DecodeFramingFaultAsync(decoder, connection, this.Via, _messageEncoder.ContentType, timeoutHelper.RemainingTime());
}
await upgradeInitiator.CloseAsync(timeoutHelper.RemainingTime());
await connection.WriteAsync(ClientSingletonEncoder.PreambleEndBytes, 0, ClientSingletonEncoder.PreambleEndBytes.Length, true, timeoutHelper.RemainingTime());
}
byte[] ackBuffer = new byte[1];
int ackBytesRead = await connection.ReadAsync(ackBuffer, 0, ackBuffer.Length, timeoutHelper.RemainingTime());
if (!ConnectionUpgradeHelper.ValidatePreambleResponse(ackBuffer, ackBytesRead, decoder, Via))
{
await ConnectionUpgradeHelper.DecodeFramingFaultAsync(decoder, connection, Via,
_messageEncoder.ContentType, timeoutHelper.RemainingTime());
}
return connection;
}
protected override void OnClose(TimeSpan timeout)
{
base.WaitForPendingRequests(timeout);
}
protected override void OnClosed()
{
base.OnClosed();
// clean up the CBT after transitioning to the closed state
ChannelBindingUtility.Dispose(ref _channelBindingToken);
}
protected internal override Task OnCloseAsync(TimeSpan timeout)
{
return base.WaitForPendingRequestsAsync(timeout);
}
protected override IAsyncResult OnBeginClose(TimeSpan timeout, AsyncCallback callback, object state)
{
return OnCloseAsync(timeout).ToApm(callback, state);
}
protected override void OnEndClose(IAsyncResult result)
{
result.ToApmEnd();
}
internal class StreamedConnectionPoolHelper : ConnectionPoolHelper
{
private StreamedFramingRequestChannel _channel;
private ClientSingletonDecoder _decoder;
private SecurityMessageProperty _remoteSecurity;
public StreamedConnectionPoolHelper(StreamedFramingRequestChannel channel)
: base(channel._connectionPool, channel._connectionInitiator, channel.Via)
{
_channel = channel;
}
public ClientSingletonDecoder Decoder
{
get { return _decoder; }
}
public SecurityMessageProperty RemoteSecurity
{
get { return _remoteSecurity; }
}
protected override TimeoutException CreateNewConnectionTimeoutException(TimeSpan timeout, TimeoutException innerException)
{
return new TimeoutException(SR.Format(SR.RequestTimedOutEstablishingTransportSession,
timeout, _channel.Via.AbsoluteUri), innerException);
}
protected override IConnection AcceptPooledConnection(IConnection connection, ref TimeoutHelper timeoutHelper)
{
_decoder = new ClientSingletonDecoder(0);
return _channel.SendPreamble(connection, ref timeoutHelper, _decoder, out _remoteSecurity);
}
protected override Task<IConnection> AcceptPooledConnectionAsync(IConnection connection, ref TimeoutHelper timeoutHelper)
{
_decoder = new ClientSingletonDecoder(0);
return _channel.SendPreambleAsync(connection, timeoutHelper, _decoder);
}
private class ClientSingletonConnectionReader : SingletonConnectionReader
{
private StreamedConnectionPoolHelper _connectionPoolHelper;
public ClientSingletonConnectionReader(IConnection connection, StreamedConnectionPoolHelper connectionPoolHelper,
IConnectionOrientedTransportFactorySettings settings)
: base(connection, 0, 0, connectionPoolHelper.RemoteSecurity, settings, null)
{
Contract.Assert(connectionPoolHelper != null);
_connectionPoolHelper = connectionPoolHelper;
}
protected override long StreamPosition
{
get { return _connectionPoolHelper.Decoder.StreamPosition; }
}
protected override bool DecodeBytes(byte[] buffer, ref int offset, ref int size, ref bool isAtEof)
{
while (size > 0)
{
int bytesRead = _connectionPoolHelper.Decoder.Decode(buffer, offset, size);
if (bytesRead > 0)
{
offset += bytesRead;
size -= bytesRead;
}
switch (_connectionPoolHelper.Decoder.CurrentState)
{
case ClientFramingDecoderState.EnvelopeStart:
// we're at the envelope
return true;
case ClientFramingDecoderState.End:
isAtEof = true;
return false;
}
}
return false;
}
protected override void OnClose(TimeSpan timeout)
{
_connectionPoolHelper.Close(timeout);
}
}
internal class StreamedFramingAsyncRequest : IAsyncRequest
{
private StreamedFramingRequestChannel _channel;
private IConnection _connection;
private StreamedConnectionPoolHelper _connectionPoolHelper;
private Message _message;
private TimeoutHelper _timeoutHelper;
private ClientSingletonConnectionReader _connectionReader;
public StreamedFramingAsyncRequest(StreamedFramingRequestChannel channel)
{
_channel = channel;
_connectionPoolHelper = new StreamedConnectionPoolHelper(channel);
}
public async Task SendRequestAsync(Message message, TimeoutHelper timeoutHelper)
{
_timeoutHelper = timeoutHelper;
_message = message;
bool success = false;
try
{
try
{
_connection = await _connectionPoolHelper.EstablishConnectionAsync(timeoutHelper.RemainingTime());
ChannelBindingUtility.TryAddToMessage(_channel._channelBindingToken, _message, false);
await StreamingConnectionHelper.WriteMessageAsync(_message, _connection, true, _channel._settings, timeoutHelper);
}
catch (TimeoutException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new TimeoutException(SR.Format(SR.TimeoutOnRequest, timeoutHelper.RemainingTime()), exception));
}
success = true;
}
finally
{
if (!success)
{
Cleanup();
}
}
}
public void Abort(RequestChannel requestChannel)
{
Cleanup();
}
public void Fault(RequestChannel requestChannel)
{
Cleanup();
}
private void Cleanup()
{
_connectionPoolHelper.Abort();
}
public void OnReleaseRequest()
{
}
public Task<Message> ReceiveReplyAsync(TimeoutHelper timeoutHelper)
{
try
{
_connectionReader = new ClientSingletonConnectionReader(_connection, _connectionPoolHelper, _channel._settings);
return _connectionReader.ReceiveAsync(timeoutHelper);
}
catch (OperationCanceledException)
{
var cancelToken = _timeoutHelper.GetCancellationToken();
if (cancelToken.IsCancellationRequested)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new TimeoutException(SR.Format(
SR.RequestChannelWaitForReplyTimedOut, timeoutHelper.OriginalTimeout)));
}
else
{
// Cancellation came from somewhere other than timeoutCts and needs to be handled differently.
throw;
}
}
}
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
namespace GraphQL
{
/// <summary>
/// A simple cache based on the provided dictionary.
/// </summary>
/// <typeparam name="TKey">The type of the t key.</typeparam>
/// <typeparam name="TValue">The type of the t value.</typeparam>
/// <seealso cref="System.Collections.Generic.IEnumerable{TValue}" />
/// <remarks>https://github.com/JasperFx/baseline/blob/master/src/Baseline/LightweightCache.cs</remarks>
public class LightweightCache<TKey, TValue> : IEnumerable<TValue>
{
private readonly IDictionary<TKey, TValue> _values;
private Func<TKey, TValue> _onMissing = delegate (TKey key)
{
var message = $"Key '{key}' could not be found";
throw new KeyNotFoundException(message);
};
/// <summary>
/// Initializes a new instance of the <see cref="LightweightCache{TKey, TValue}"/> class.
/// </summary>
public LightweightCache()
: this(new Dictionary<TKey, TValue>())
{
}
/// <summary>
/// Initializes a new instance of the <see cref="LightweightCache{TKey, TValue}"/> class.
/// </summary>
/// <param name="onMissing">Action to perform if the key is missing. Defaults to <see cref="KeyNotFoundException"/></param>
public LightweightCache(Func<TKey, TValue> onMissing)
: this(new Dictionary<TKey, TValue>(), onMissing)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="LightweightCache{TKey, TValue}"/> class.
/// </summary>
/// <param name="dictionary">The dictionary implementation to use.</param>
/// <param name="onMissing">Action to perform if the key is missing. Defaults to <see cref="KeyNotFoundException"/></param>
/// <remarks>This takes a dependency on the provided dictionary. It does not simply copy its values.</remarks>
public LightweightCache(IDictionary<TKey, TValue> dictionary, Func<TKey, TValue> onMissing)
: this(dictionary)
{
_onMissing = onMissing;
}
/// <summary>
/// Initializes a new instance of the <see cref="LightweightCache{TKey, TValue}"/> class.
/// </summary>
/// <param name="dictionary">The dictionary implementation to use.</param>
/// <remarks>This takes a dependency on the provided dictionary. It does not simply copy its values.</remarks>
public LightweightCache(IDictionary<TKey, TValue> dictionary)
{
_values = dictionary;
}
/// <summary>
/// Action to perform if the key is missing. Defaults to <see cref="KeyNotFoundException"/>
/// </summary>
public Func<TKey, TValue> OnMissing
{
set => _onMissing = value;
}
/// <summary>
/// Gets the count.
/// </summary>
public int Count => _values.Count;
/// <summary>
/// Gets or sets the <typeparamref name="TValue"/> with the specified key.
/// </summary>
/// <param name="key">The key.</param>
public TValue this[TKey key]
{
get
{
if (!_values.TryGetValue(key, out var value))
{
value = _onMissing(key);
if (value != null)
{
_values[key] = value;
}
}
return value;
}
set
{
if (_values.ContainsKey(key))
{
_values[key] = value;
}
else
{
_values.Add(key, value);
}
}
}
/// <summary>
/// Gets the keys.
/// </summary>
public IEnumerable<TKey> Keys => _values.Keys;
/// <summary>
/// Returns an enumerator that iterates through the values.
/// </summary>
/// <returns>An <see cref="System.Collections.IEnumerator"></see> object that can be used to iterate through the collection.</returns>
IEnumerator IEnumerable.GetEnumerator() => ((IEnumerable<TValue>)this).GetEnumerator();
/// <summary>
/// Returns an enumerator that iterates through the values.
/// </summary>
/// <returns>An enumerator that can be used to iterate through the collection.</returns>
public IEnumerator<TValue> GetEnumerator() => _values.Values.GetEnumerator();
/// <summary>
/// Guarantees that the Cache has a value for a given key.
/// If it does not already exist, it's created using the OnMissing action.
/// </summary>
/// <param name="key">The key.</param>
public void FillDefault(TKey key) => Fill(key, _onMissing(key));
/// <summary>
/// Guarantees that the Cache has a value for a given key.
/// If it does not already exist, it's created using provided default value.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="value">The default value.</param>
public void Fill(TKey key, TValue value)
{
if (_values.ContainsKey(key))
{
return;
}
_values.Add(key, value);
}
/// <summary>
/// Tries the retrieve a given key.
/// </summary>
/// <param name="key">The key to retrieve.</param>
/// <param name="value">The value for the associated key or <c>default(TValue)</c>.</param>
public bool TryRetrieve(TKey key, out TValue? value) => _values.TryGetValue(key, out value);
/// <summary>
/// Performs the specified action for each value.
/// </summary>
/// <param name="action">The action to be performed.</param>
/// <remarks>The order of execution is non-deterministic. If an error occurs, the action will not be performed on the remaining values.</remarks>
public void Each(Action<TValue> action)
{
foreach (var pair in _values)
{
action(pair.Value);
}
}
/// <summary>
/// Performs the specified action for each key/value pair.
/// </summary>
/// <param name="action">The action to be performed.</param>
/// <remarks>The order of execution is non-deterministic. If an error occurs, the action will not be performed on the remaining values.</remarks>
public void Each(Action<TKey, TValue> action)
{
foreach (var pair in _values)
{
action(pair.Key, pair.Value);
}
}
/// <summary>
/// Equivalent to ContainsKey
/// </summary>
/// <param name="key">The key.</param>
public bool Has(TKey key) => _values.ContainsKey(key);
/// <summary>
/// Determines if a given value exists in the dictionary.
/// </summary>
/// <param name="predicate">The search predicate.</param>
public bool Exists(Predicate<TValue> predicate)
{
bool returnValue = false;
Each(value => returnValue |= predicate(value));
return returnValue;
}
/// <summary>
/// Searches for a given value.
/// </summary>
/// <param name="predicate">The search predicate.</param>
/// <returns>The first matching value</returns>
public TValue? Find(Predicate<TValue> predicate)
{
foreach (var pair in _values)
{
if (predicate(pair.Value))
{
return pair.Value;
}
}
return default;
}
/// <summary>
/// Returns all values as an array
/// </summary>
public TValue[] GetAll()
{
var returnValue = new TValue[Count];
_values.Values.CopyTo(returnValue, 0);
return returnValue;
}
/// <summary>
/// Removes the specified key.
/// </summary>
/// <param name="key">The key.</param>
public void Remove(TKey key)
{
if (_values.ContainsKey(key))
{
_values.Remove(key);
}
}
/// <summary>
/// Clears this instance of all key/value pairs.
/// </summary>
public void Clear() => _values.Clear();
/// <summary>
/// If the dictionary contains the indicated key, performs the action with its value.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="action">The action to be performed.</param>
public void WithValue(TKey key, Action<TValue> action)
{
if (_values.ContainsKey(key))
{
action(this[key]);
}
}
/// <summary>
/// Equivalent to Clear()
/// </summary>
public void ClearAll() => _values.Clear();
}
}
| |
/*
* Copyright (c) Citrix Systems, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1) Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2) Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
namespace XenAPI
{
/// <summary>
/// A tunnel for network traffic
/// First published in XenServer 5.6 FP1.
/// </summary>
public partial class Tunnel : XenObject<Tunnel>
{
public Tunnel()
{
}
public Tunnel(string uuid,
XenRef<PIF> access_PIF,
XenRef<PIF> transport_PIF,
Dictionary<string, string> status,
Dictionary<string, string> other_config)
{
this.uuid = uuid;
this.access_PIF = access_PIF;
this.transport_PIF = transport_PIF;
this.status = status;
this.other_config = other_config;
}
/// <summary>
/// Creates a new Tunnel from a Proxy_Tunnel.
/// </summary>
/// <param name="proxy"></param>
public Tunnel(Proxy_Tunnel proxy)
{
this.UpdateFromProxy(proxy);
}
public override void UpdateFrom(Tunnel update)
{
uuid = update.uuid;
access_PIF = update.access_PIF;
transport_PIF = update.transport_PIF;
status = update.status;
other_config = update.other_config;
}
internal void UpdateFromProxy(Proxy_Tunnel proxy)
{
uuid = proxy.uuid == null ? null : (string)proxy.uuid;
access_PIF = proxy.access_PIF == null ? null : XenRef<PIF>.Create(proxy.access_PIF);
transport_PIF = proxy.transport_PIF == null ? null : XenRef<PIF>.Create(proxy.transport_PIF);
status = proxy.status == null ? null : Maps.convert_from_proxy_string_string(proxy.status);
other_config = proxy.other_config == null ? null : Maps.convert_from_proxy_string_string(proxy.other_config);
}
public Proxy_Tunnel ToProxy()
{
Proxy_Tunnel result_ = new Proxy_Tunnel();
result_.uuid = uuid ?? "";
result_.access_PIF = access_PIF ?? "";
result_.transport_PIF = transport_PIF ?? "";
result_.status = Maps.convert_to_proxy_string_string(status);
result_.other_config = Maps.convert_to_proxy_string_string(other_config);
return result_;
}
/// <summary>
/// Creates a new Tunnel from a Hashtable.
/// </summary>
/// <param name="table"></param>
public Tunnel(Hashtable table)
{
uuid = Marshalling.ParseString(table, "uuid");
access_PIF = Marshalling.ParseRef<PIF>(table, "access_PIF");
transport_PIF = Marshalling.ParseRef<PIF>(table, "transport_PIF");
status = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "status"));
other_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "other_config"));
}
public bool DeepEquals(Tunnel other)
{
if (ReferenceEquals(null, other))
return false;
if (ReferenceEquals(this, other))
return true;
return Helper.AreEqual2(this._uuid, other._uuid) &&
Helper.AreEqual2(this._access_PIF, other._access_PIF) &&
Helper.AreEqual2(this._transport_PIF, other._transport_PIF) &&
Helper.AreEqual2(this._status, other._status) &&
Helper.AreEqual2(this._other_config, other._other_config);
}
public override string SaveChanges(Session session, string opaqueRef, Tunnel server)
{
if (opaqueRef == null)
{
System.Diagnostics.Debug.Assert(false, "Cannot create instances of this type on the server");
return "";
}
else
{
if (!Helper.AreEqual2(_status, server._status))
{
Tunnel.set_status(session, opaqueRef, _status);
}
if (!Helper.AreEqual2(_other_config, server._other_config))
{
Tunnel.set_other_config(session, opaqueRef, _other_config);
}
return null;
}
}
/// <summary>
/// Get a record containing the current state of the given tunnel.
/// First published in XenServer 5.6 FP1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_tunnel">The opaque_ref of the given tunnel</param>
public static Tunnel get_record(Session session, string _tunnel)
{
return new Tunnel((Proxy_Tunnel)session.proxy.tunnel_get_record(session.uuid, _tunnel ?? "").parse());
}
/// <summary>
/// Get a reference to the tunnel instance with the specified UUID.
/// First published in XenServer 5.6 FP1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_uuid">UUID of object to return</param>
public static XenRef<Tunnel> get_by_uuid(Session session, string _uuid)
{
return XenRef<Tunnel>.Create(session.proxy.tunnel_get_by_uuid(session.uuid, _uuid ?? "").parse());
}
/// <summary>
/// Get the uuid field of the given tunnel.
/// First published in XenServer 5.6 FP1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_tunnel">The opaque_ref of the given tunnel</param>
public static string get_uuid(Session session, string _tunnel)
{
return (string)session.proxy.tunnel_get_uuid(session.uuid, _tunnel ?? "").parse();
}
/// <summary>
/// Get the access_PIF field of the given tunnel.
/// First published in XenServer 5.6 FP1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_tunnel">The opaque_ref of the given tunnel</param>
public static XenRef<PIF> get_access_PIF(Session session, string _tunnel)
{
return XenRef<PIF>.Create(session.proxy.tunnel_get_access_pif(session.uuid, _tunnel ?? "").parse());
}
/// <summary>
/// Get the transport_PIF field of the given tunnel.
/// First published in XenServer 5.6 FP1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_tunnel">The opaque_ref of the given tunnel</param>
public static XenRef<PIF> get_transport_PIF(Session session, string _tunnel)
{
return XenRef<PIF>.Create(session.proxy.tunnel_get_transport_pif(session.uuid, _tunnel ?? "").parse());
}
/// <summary>
/// Get the status field of the given tunnel.
/// First published in XenServer 5.6 FP1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_tunnel">The opaque_ref of the given tunnel</param>
public static Dictionary<string, string> get_status(Session session, string _tunnel)
{
return Maps.convert_from_proxy_string_string(session.proxy.tunnel_get_status(session.uuid, _tunnel ?? "").parse());
}
/// <summary>
/// Get the other_config field of the given tunnel.
/// First published in XenServer 5.6 FP1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_tunnel">The opaque_ref of the given tunnel</param>
public static Dictionary<string, string> get_other_config(Session session, string _tunnel)
{
return Maps.convert_from_proxy_string_string(session.proxy.tunnel_get_other_config(session.uuid, _tunnel ?? "").parse());
}
/// <summary>
/// Set the status field of the given tunnel.
/// First published in XenServer 5.6 FP1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_tunnel">The opaque_ref of the given tunnel</param>
/// <param name="_status">New value to set</param>
public static void set_status(Session session, string _tunnel, Dictionary<string, string> _status)
{
session.proxy.tunnel_set_status(session.uuid, _tunnel ?? "", Maps.convert_to_proxy_string_string(_status)).parse();
}
/// <summary>
/// Add the given key-value pair to the status field of the given tunnel.
/// First published in XenServer 5.6 FP1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_tunnel">The opaque_ref of the given tunnel</param>
/// <param name="_key">Key to add</param>
/// <param name="_value">Value to add</param>
public static void add_to_status(Session session, string _tunnel, string _key, string _value)
{
session.proxy.tunnel_add_to_status(session.uuid, _tunnel ?? "", _key ?? "", _value ?? "").parse();
}
/// <summary>
/// Remove the given key and its corresponding value from the status field of the given tunnel. If the key is not in that Map, then do nothing.
/// First published in XenServer 5.6 FP1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_tunnel">The opaque_ref of the given tunnel</param>
/// <param name="_key">Key to remove</param>
public static void remove_from_status(Session session, string _tunnel, string _key)
{
session.proxy.tunnel_remove_from_status(session.uuid, _tunnel ?? "", _key ?? "").parse();
}
/// <summary>
/// Set the other_config field of the given tunnel.
/// First published in XenServer 5.6 FP1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_tunnel">The opaque_ref of the given tunnel</param>
/// <param name="_other_config">New value to set</param>
public static void set_other_config(Session session, string _tunnel, Dictionary<string, string> _other_config)
{
session.proxy.tunnel_set_other_config(session.uuid, _tunnel ?? "", Maps.convert_to_proxy_string_string(_other_config)).parse();
}
/// <summary>
/// Add the given key-value pair to the other_config field of the given tunnel.
/// First published in XenServer 5.6 FP1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_tunnel">The opaque_ref of the given tunnel</param>
/// <param name="_key">Key to add</param>
/// <param name="_value">Value to add</param>
public static void add_to_other_config(Session session, string _tunnel, string _key, string _value)
{
session.proxy.tunnel_add_to_other_config(session.uuid, _tunnel ?? "", _key ?? "", _value ?? "").parse();
}
/// <summary>
/// Remove the given key and its corresponding value from the other_config field of the given tunnel. If the key is not in that Map, then do nothing.
/// First published in XenServer 5.6 FP1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_tunnel">The opaque_ref of the given tunnel</param>
/// <param name="_key">Key to remove</param>
public static void remove_from_other_config(Session session, string _tunnel, string _key)
{
session.proxy.tunnel_remove_from_other_config(session.uuid, _tunnel ?? "", _key ?? "").parse();
}
/// <summary>
/// Create a tunnel
/// First published in XenServer 5.6 FP1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_transport_pif">PIF which receives the tagged traffic</param>
/// <param name="_network">Network to receive the tunnelled traffic</param>
public static XenRef<Tunnel> create(Session session, string _transport_pif, string _network)
{
return XenRef<Tunnel>.Create(session.proxy.tunnel_create(session.uuid, _transport_pif ?? "", _network ?? "").parse());
}
/// <summary>
/// Create a tunnel
/// First published in XenServer 5.6 FP1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_transport_pif">PIF which receives the tagged traffic</param>
/// <param name="_network">Network to receive the tunnelled traffic</param>
public static XenRef<Task> async_create(Session session, string _transport_pif, string _network)
{
return XenRef<Task>.Create(session.proxy.async_tunnel_create(session.uuid, _transport_pif ?? "", _network ?? "").parse());
}
/// <summary>
/// Destroy a tunnel
/// First published in XenServer 5.6 FP1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_tunnel">The opaque_ref of the given tunnel</param>
public static void destroy(Session session, string _tunnel)
{
session.proxy.tunnel_destroy(session.uuid, _tunnel ?? "").parse();
}
/// <summary>
/// Destroy a tunnel
/// First published in XenServer 5.6 FP1.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_tunnel">The opaque_ref of the given tunnel</param>
public static XenRef<Task> async_destroy(Session session, string _tunnel)
{
return XenRef<Task>.Create(session.proxy.async_tunnel_destroy(session.uuid, _tunnel ?? "").parse());
}
/// <summary>
/// Return a list of all the tunnels known to the system.
/// First published in XenServer 5.6 FP1.
/// </summary>
/// <param name="session">The session</param>
public static List<XenRef<Tunnel>> get_all(Session session)
{
return XenRef<Tunnel>.Create(session.proxy.tunnel_get_all(session.uuid).parse());
}
/// <summary>
/// Get all the tunnel Records at once, in a single XML RPC call
/// First published in XenServer 5.6 FP1.
/// </summary>
/// <param name="session">The session</param>
public static Dictionary<XenRef<Tunnel>, Tunnel> get_all_records(Session session)
{
return XenRef<Tunnel>.Create<Proxy_Tunnel>(session.proxy.tunnel_get_all_records(session.uuid).parse());
}
/// <summary>
/// Unique identifier/object reference
/// </summary>
public virtual string uuid
{
get { return _uuid; }
set
{
if (!Helper.AreEqual(value, _uuid))
{
_uuid = value;
Changed = true;
NotifyPropertyChanged("uuid");
}
}
}
private string _uuid;
/// <summary>
/// The interface through which the tunnel is accessed
/// </summary>
public virtual XenRef<PIF> access_PIF
{
get { return _access_PIF; }
set
{
if (!Helper.AreEqual(value, _access_PIF))
{
_access_PIF = value;
Changed = true;
NotifyPropertyChanged("access_PIF");
}
}
}
private XenRef<PIF> _access_PIF;
/// <summary>
/// The interface used by the tunnel
/// </summary>
public virtual XenRef<PIF> transport_PIF
{
get { return _transport_PIF; }
set
{
if (!Helper.AreEqual(value, _transport_PIF))
{
_transport_PIF = value;
Changed = true;
NotifyPropertyChanged("transport_PIF");
}
}
}
private XenRef<PIF> _transport_PIF;
/// <summary>
/// Status information about the tunnel
/// </summary>
public virtual Dictionary<string, string> status
{
get { return _status; }
set
{
if (!Helper.AreEqual(value, _status))
{
_status = value;
Changed = true;
NotifyPropertyChanged("status");
}
}
}
private Dictionary<string, string> _status;
/// <summary>
/// Additional configuration
/// </summary>
public virtual Dictionary<string, string> other_config
{
get { return _other_config; }
set
{
if (!Helper.AreEqual(value, _other_config))
{
_other_config = value;
Changed = true;
NotifyPropertyChanged("other_config");
}
}
}
private Dictionary<string, string> _other_config;
}
}
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
namespace NPOI.SS.Util
{
using System;
using System.Collections.Generic;
using NPOI.SS.UserModel;
using NPOI.Util;
/**
* Various utility functions that make working with a cells and rows easier. The various methods
* that deal with style's allow you to create your CellStyles as you need them. When you apply a
* style change to a cell, the code will attempt to see if a style already exists that meets your
* needs. If not, then it will create a new style. This is to prevent creating too many styles.
* there is an upper limit in Excel on the number of styles that can be supported.
*
*@author Eric Pugh epugh@upstate.com
*@author (secondary) Avinash Kewalramani akewalramani@accelrys.com
*/
public class CellUtil
{
public const string ALIGNMENT = "alignment";
public const string BORDER_BOTTOM = "borderBottom";
public const string BORDER_DIAGONAL = "borderDiagonal";
public const string BORDER_LEFT = "borderLeft";
public const string BORDER_RIGHT = "borderRight";
public const string BORDER_TOP = "borderTop";
public const string BOTTOM_BORDER_COLOR = "bottomBorderColor";
public const string DATA_FORMAT = "dataFormat";
public const string FILL_BACKGROUND_COLOR = "fillBackgroundColor";
public const string FILL_FOREGROUND_COLOR = "fillForegroundColor";
public const string FILL_PATTERN = "fillPattern";
public const string FONT = "font";
public const string HIDDEN = "hidden";
public const string INDENTION = "indention";
public const string LEFT_BORDER_COLOR = "leftBorderColor";
public const string LOCKED = "locked";
public const string RIGHT_BORDER_COLOR = "rightBorderColor";
public const string ROTATION = "rotation";
public const string SHRINK_TO_FIT = "shrinkToFit";
public const string TOP_BORDER_COLOR = "topBorderColor";
public const string VERTICAL_ALIGNMENT = "verticalAlignment";
public const string WRAP_TEXT = "wrapText";
private static ISet<String> shortValues = new HashSet<string>(new string[]{
BOTTOM_BORDER_COLOR,
LEFT_BORDER_COLOR,
RIGHT_BORDER_COLOR,
TOP_BORDER_COLOR,
FILL_FOREGROUND_COLOR,
FILL_BACKGROUND_COLOR,
INDENTION,
DATA_FORMAT,
ROTATION
});
private static ISet<String> intValues = new HashSet<string>(new string[]{
FONT
});
private static ISet<String> booleanValues = new HashSet<string>(new string[]{
LOCKED,
HIDDEN,
WRAP_TEXT
});
private static ISet<String> borderTypeValues = new HashSet<string>(new string[]{
BORDER_BOTTOM,
BORDER_LEFT,
BORDER_RIGHT,
BORDER_TOP
});
private static UnicodeMapping[] unicodeMappings;
private class UnicodeMapping
{
public String entityName;
public String resolvedValue;
public UnicodeMapping(String pEntityName, String pResolvedValue)
{
entityName = "&" + pEntityName + ";";
resolvedValue = pResolvedValue;
}
}
private CellUtil()
{
// no instances of this class
}
public static ICell CopyCell(IRow row, int sourceIndex, int targetIndex)
{
if (sourceIndex == targetIndex)
throw new ArgumentException("sourceIndex and targetIndex cannot be same");
// Grab a copy of the old/new cell
ICell oldCell = row.GetCell(sourceIndex);
// If the old cell is null jump to next cell
if (oldCell == null)
{
return null;
}
ICell newCell = row.GetCell(targetIndex);
if (newCell == null) //not exist
{
newCell = row.CreateCell(targetIndex);
}
else
{
//TODO:shift cells
}
// Copy style from old cell and apply to new cell
if (oldCell.CellStyle != null)
{
newCell.CellStyle = oldCell.CellStyle;
}
// If there is a cell comment, copy
if (oldCell.CellComment != null)
{
newCell.CellComment = oldCell.CellComment;
}
// If there is a cell hyperlink, copy
if (oldCell.Hyperlink != null)
{
newCell.Hyperlink = oldCell.Hyperlink;
}
// Set the cell data type
newCell.SetCellType(oldCell.CellType);
// Set the cell data value
switch (oldCell.CellType)
{
case CellType.Blank:
newCell.SetCellValue(oldCell.StringCellValue);
break;
case CellType.Boolean:
newCell.SetCellValue(oldCell.BooleanCellValue);
break;
case CellType.Error:
newCell.SetCellErrorValue(oldCell.ErrorCellValue);
break;
case CellType.Formula:
newCell.SetCellFormula(oldCell.CellFormula);
break;
case CellType.Numeric:
newCell.SetCellValue(oldCell.NumericCellValue);
break;
case CellType.String:
newCell.SetCellValue(oldCell.RichStringCellValue);
break;
}
return newCell;
}
/**
* Get a row from the spreadsheet, and create it if it doesn't exist.
*
*@param rowIndex The 0 based row number
*@param sheet The sheet that the row is part of.
*@return The row indicated by the rowCounter
*/
public static IRow GetRow(int rowIndex, ISheet sheet)
{
IRow row = sheet.GetRow(rowIndex);
if (row == null)
{
row = sheet.CreateRow(rowIndex);
}
return row;
}
/**
* Get a specific cell from a row. If the cell doesn't exist, then create it.
*
*@param row The row that the cell is part of
*@param columnIndex The column index that the cell is in.
*@return The cell indicated by the column.
*/
public static ICell GetCell(IRow row, int columnIndex)
{
ICell cell = row.GetCell(columnIndex);
if (cell == null)
{
cell = row.CreateCell(columnIndex);
}
return cell;
}
/**
* Creates a cell, gives it a value, and applies a style if provided
*
* @param row the row to create the cell in
* @param column the column index to create the cell in
* @param value The value of the cell
* @param style If the style is not null, then set
* @return A new Cell
*/
public static ICell CreateCell(IRow row, int column, String value, ICellStyle style)
{
ICell cell = GetCell(row, column);
cell.SetCellValue(cell.Row.Sheet.Workbook.GetCreationHelper()
.CreateRichTextString(value));
if (style != null)
{
cell.CellStyle = style;
}
return cell;
}
/**
* Create a cell, and give it a value.
*
*@param row the row to create the cell in
*@param column the column index to create the cell in
*@param value The value of the cell
*@return A new Cell.
*/
public static ICell CreateCell(IRow row, int column, String value)
{
return CreateCell(row, column, value, null);
}
/**
* Take a cell, and align it.
*
*@param cell the cell to set the alignment for
*@param workbook The workbook that is being worked with.
*@param align the column alignment to use.
*
* @see CellStyle for alignment options
*/
[Obsolete("deprecated 3.15-beta2. Use {@link #SetAlignment(ICell, HorizontalAlignment)} instead.")]
public static void SetAlignment(ICell cell, IWorkbook workbook, short align)
{
SetCellStyleProperty(cell, workbook, ALIGNMENT, align);
}
/**
* Take a cell, and align it.
*
* This is superior to cell.getCellStyle().setAlignment(align) because
* this method will not modify the CellStyle object that may be referenced
* by multiple cells. Instead, this method will search for existing CellStyles
* that match the desired CellStyle, creating a new CellStyle with the desired
* style if no match exists.
*
* @param cell the cell to set the alignment for
* @param align the horizontal alignment to use.
*
* @see HorizontalAlignment for alignment options
* @since POI 3.15 beta 3
*/
public static void SetAlignment(ICell cell, HorizontalAlignment align)
{
SetCellStyleProperty(cell, ALIGNMENT, align);
}
/**
* Take a cell, and vertically align it.
*
* This is superior to cell.getCellStyle().setVerticalAlignment(align) because
* this method will not modify the CellStyle object that may be referenced
* by multiple cells. Instead, this method will search for existing CellStyles
* that match the desired CellStyle, creating a new CellStyle with the desired
* style if no match exists.
*
* @param cell the cell to set the alignment for
* @param align the vertical alignment to use.
*
* @see VerticalAlignment for alignment options
* @since POI 3.15 beta 3
*/
public static void SetVerticalAlignment(ICell cell, VerticalAlignment align)
{
SetCellStyleProperty(cell, VERTICAL_ALIGNMENT, align);
}
/**
* Take a cell, and apply a font to it
*
*@param cell the cell to set the alignment for
*@param workbook The workbook that is being worked with.
*@param font The Font that you want to set...
*/
[Obsolete("deprecated 3.15-beta2. Use {@link #SetFont(ICell, IFont)} instead.")]
public static void SetFont(ICell cell, IWorkbook workbook, IFont font)
{
// Check if font belongs to workbook
short fontIndex = font.Index;
if (!workbook.GetFontAt(fontIndex).Equals(font))
{
throw new ArgumentException("Font does not belong to this workbook");
}
// Check if cell belongs to workbook
// (checked in setCellStyleProperty)
SetCellStyleProperty(cell, workbook, FONT, fontIndex);
}
/**
* Take a cell, and apply a font to it
*
* @param cell the cell to set the alignment for
* @param font The Font that you want to set.
* @throws IllegalArgumentException if <tt>font</tt> and <tt>cell</tt> do not belong to the same workbook
*/
public static void SetFont(ICell cell, IFont font)
{
// Check if font belongs to workbook
IWorkbook wb = cell.Sheet.Workbook;
short fontIndex = font.Index;
if (!wb.GetFontAt(fontIndex).Equals(font))
{
throw new ArgumentException("Font does not belong to this workbook");
}
// Check if cell belongs to workbook
// (checked in setCellStyleProperty)
SetCellStyleProperty(cell, FONT, fontIndex);
}
/**
* <p>This method attempts to find an existing CellStyle that matches the <code>cell</code>'s
* current style plus styles properties in <code>properties</code>. A new style is created if the
* workbook does not contain a matching style.</p>
*
* <p>Modifies the cell style of <code>cell</code> without affecting other cells that use the
* same style.</p>
*
* <p>This is necessary because Excel has an upper limit on the number of styles that it supports.</p>
*
* <p>This function is more efficient than multiple calls to
* {@link #setCellStyleProperty(org.apache.poi.ss.usermodel.Cell, org.apache.poi.ss.usermodel.Workbook, String, Object)}
* if adding multiple cell styles.</p>
*
* <p>For performance reasons, if this is the only cell in a workbook that uses a cell style,
* this method does NOT remove the old style from the workbook.
* <!-- NOT IMPLEMENTED: Unused styles should be
* pruned from the workbook with [@link #removeUnusedCellStyles(Workbook)] or
* [@link #removeStyleFromWorkbookIfUnused(CellStyle, Workbook)]. -->
* </p>
*
* @param cell The cell to change the style of
* @param properties The properties to be added to a cell style, as {propertyName: propertyValue}.
* @since POI 3.14 beta 2
*/
public static void SetCellStyleProperties(ICell cell, Dictionary<String, Object> properties)
{
IWorkbook workbook = cell.Sheet.Workbook;
ICellStyle originalStyle = cell.CellStyle;
ICellStyle newStyle = null;
Dictionary<String, Object> values = GetFormatProperties(originalStyle);
PutAll(properties, values);
// index seems like what index the cellstyle is in the list of styles for a workbook.
// not good to compare on!
int numberCellStyles = workbook.NumCellStyles;
for (int i = 0; i < numberCellStyles; i++)
{
ICellStyle wbStyle = workbook.GetCellStyleAt(i);
Dictionary<String, Object> wbStyleMap = GetFormatProperties(wbStyle);
// the desired style already exists in the workbook. Use the existing style.
if (DictionaryEqual(wbStyleMap, values, null))
{
newStyle = wbStyle;
break;
}
}
// the desired style does not exist in the workbook. Create a new style with desired properties.
if (newStyle == null)
{
newStyle = workbook.CreateCellStyle();
SetFormatProperties(newStyle, workbook, values);
}
cell.CellStyle = newStyle;
}
public static bool DictionaryEqual<TKey, TValue>(IDictionary<TKey, TValue> first,
IDictionary<TKey, TValue> second, IEqualityComparer<TValue> valueComparer)
{
if (first == second) return true;
if ((first == null) || (second == null)) return false;
if (first.Count != second.Count) return false;
valueComparer = valueComparer ?? EqualityComparer<TValue>.Default;
foreach (var kvp in first)
{
TValue secondValue;
if (!second.TryGetValue(kvp.Key, out secondValue)) return false;
if (!valueComparer.Equals(kvp.Value, secondValue)) return false;
}
return true;
}
/**
* <p>This method attempts to find an existing CellStyle that matches the <code>cell</code>'s
* current style plus a single style property <code>propertyName</code> with value
* <code>propertyValue</code>.
* A new style is created if the workbook does not contain a matching style.</p>
*
* <p>Modifies the cell style of <code>cell</code> without affecting other cells that use the
* same style.</p>
*
* <p>If setting more than one cell style property on a cell, use
* {@link #setCellStyleProperties(org.apache.poi.ss.usermodel.Cell, Map)},
* which is faster and does not add unnecessary intermediate CellStyles to the workbook.</p>
*
* @param cell The cell that is to be changed.
* @param propertyName The name of the property that is to be changed.
* @param propertyValue The value of the property that is to be changed.
*/
public static void SetCellStyleProperty(ICell cell, String propertyName, Object propertyValue)
{
Dictionary<String, Object> values = new Dictionary<string, object>() { { propertyName, propertyValue } };
SetCellStyleProperties(cell, values);
}
/**
* <p>This method attempts to find an existing CellStyle that matches the <code>cell</code>'s
* current style plus a single style property <code>propertyName</code> with value
* <code>propertyValue</code>.
* A new style is created if the workbook does not contain a matching style.</p>
*
* <p>Modifies the cell style of <code>cell</code> without affecting other cells that use the
* same style.</p>
*
* <p>If setting more than one cell style property on a cell, use
* {@link #setCellStyleProperties(Cell, Map)},
* which is faster and does not add unnecessary intermediate CellStyles to the workbook.</p>
*
* @param workbook The workbook that is being worked with.
* @param propertyName The name of the property that is to be changed.
* @param propertyValue The value of the property that is to be changed.
* @param cell The cell that needs it's style changes
*/
[Obsolete("deprecated 3.15-beta2. Use {@link #setCellStyleProperty(Cell, String, Object)} instead.")]
public static void SetCellStyleProperty(ICell cell, IWorkbook workbook, String propertyName,
Object propertyValue)
{
if (cell.Sheet.Workbook != workbook)
{
throw new ArgumentException("Cannot set cell style property. Cell does not belong to workbook.");
}
Dictionary<String, Object> values = new Dictionary<string, object>() { { propertyName, propertyValue } };
SetCellStyleProperties(cell, values);
}
/**
* Copies the entries in src to dest, using the preferential data type
* so that maps can be compared for equality
*
* @param src the property map to copy from (read-only)
* @param dest the property map to copy into
* @since POI 3.15 beta 3
*/
private static void PutAll(Dictionary<String, Object> src, Dictionary<String, Object> dest)
{
foreach (String key in src.Keys)
{
if (shortValues.Contains(key))
{
dest[key] = GetShort(src, key);
}
else if (intValues.Contains(key))
{
dest[key] = GetInt(src, key);
}
else if (booleanValues.Contains(key))
{
dest[key] = GetBoolean(src, key);
}
else if (borderTypeValues.Contains(key))
{
dest[key] = GetBorderStyle(src, key);
}
else if (ALIGNMENT.Equals(key))
{
dest[key] = GetHorizontalAlignment(src, key);
}
else if (VERTICAL_ALIGNMENT.Equals(key))
{
dest[key] = GetVerticalAlignment(src, key);
}
else if (FILL_PATTERN.Equals(key))
{
dest[key] = GetFillPattern(src, key);
}
else
{
//if (log.check(POILogger.INFO))
//{
// log.log(POILogger.INFO, "Ignoring unrecognized CellUtil format properties key: " + key);
//}
}
}
}
/**
* Returns a map containing the format properties of the given cell style.
* The returned map is not tied to <code>style</code>, so subsequent changes
* to <code>style</code> will not modify the map, and changes to the returned
* map will not modify the cell style. The returned map is mutable.
* @param style cell style
* @return map of format properties (String -> Object)
* @see #setFormatProperties(org.apache.poi.ss.usermodel.CellStyle, org.apache.poi.ss.usermodel.Workbook, java.util.Map)
*/
private static Dictionary<String, Object> GetFormatProperties(ICellStyle style)
{
Dictionary<String, Object> properties = new Dictionary<String, Object>();
Put(properties, ALIGNMENT, style.Alignment);
Put(properties, VERTICAL_ALIGNMENT, style.VerticalAlignment);
Put(properties, BORDER_BOTTOM, style.BorderBottom);
Put(properties, BORDER_LEFT, style.BorderLeft);
Put(properties, BORDER_RIGHT, style.BorderRight);
Put(properties, BORDER_TOP, style.BorderTop);
Put(properties, BOTTOM_BORDER_COLOR, style.BottomBorderColor);
Put(properties, DATA_FORMAT, style.DataFormat);
Put(properties, FILL_PATTERN, style.FillPattern);
Put(properties, FILL_FOREGROUND_COLOR, style.FillForegroundColor);
Put(properties, FILL_BACKGROUND_COLOR, style.FillBackgroundColor);
Put(properties, FONT, style.FontIndex);
Put(properties, HIDDEN, style.IsHidden);
Put(properties, INDENTION, style.Indention);
Put(properties, LEFT_BORDER_COLOR, style.LeftBorderColor);
Put(properties, LOCKED, style.IsLocked);
Put(properties, RIGHT_BORDER_COLOR, style.RightBorderColor);
Put(properties, ROTATION, style.Rotation);
//Put(properties, SHRINK_TO_FIT, style.ShrinkToFit);
Put(properties, TOP_BORDER_COLOR, style.TopBorderColor);
Put(properties, WRAP_TEXT, style.WrapText);
return properties;
}
/**
* Sets the format properties of the given style based on the given map.
*
* @param style cell style
* @param workbook parent workbook
* @param properties map of format properties (String -> Object)
* @see #getFormatProperties(CellStyle)
*/
private static void SetFormatProperties(ICellStyle style, IWorkbook workbook, Dictionary<String, Object> properties)
{
style.Alignment = GetHorizontalAlignment(properties, ALIGNMENT);
style.VerticalAlignment = GetVerticalAlignment(properties, VERTICAL_ALIGNMENT);
style.BorderBottom = GetBorderStyle(properties, BORDER_BOTTOM);
style.BorderLeft = GetBorderStyle(properties, BORDER_LEFT);
style.BorderRight = GetBorderStyle(properties, BORDER_RIGHT);
style.BorderTop = GetBorderStyle(properties, BORDER_TOP);
style.BottomBorderColor = GetShort(properties, BOTTOM_BORDER_COLOR);
style.DataFormat = GetShort(properties, DATA_FORMAT);
style.FillPattern = GetFillPattern(properties, FILL_PATTERN);
style.FillForegroundColor = GetShort(properties, FILL_FOREGROUND_COLOR);
style.FillBackgroundColor = GetShort(properties, FILL_BACKGROUND_COLOR);
style.SetFont(workbook.GetFontAt(GetShort(properties, FONT)));
style.IsHidden = GetBoolean(properties, HIDDEN);
style.Indention = GetShort(properties, INDENTION);
style.LeftBorderColor = GetShort(properties, LEFT_BORDER_COLOR);
style.IsLocked = GetBoolean(properties, LOCKED);
style.RightBorderColor = GetShort(properties, RIGHT_BORDER_COLOR);
style.Rotation = GetShort(properties, ROTATION);
//style.ShrinkToFit = GetBoolean(properties, SHRINK_TO_FIT);
style.TopBorderColor = GetShort(properties, TOP_BORDER_COLOR);
style.WrapText = GetBoolean(properties, WRAP_TEXT);
}
/**
* Utility method that returns the named short value form the given map.
*
* @param properties map of named properties (String -> Object)
* @param name property name
* @return zero if the property does not exist, or is not a {@link Short}.
*/
private static short GetShort(Dictionary<String, Object> properties, String name)
{
Object value = properties[name];
short result = 0;
if (short.TryParse(value.ToString(), out result))
return result;
return 0;
}
/**
* Utility method that returns the named int value from the given map.
*
* @param properties map of named properties (String -> Object)
* @param name property name
* @return zero if the property does not exist, or is not a {@link Integer}
* otherwise the property value
*/
private static int GetInt(Dictionary<String, Object> properties, String name)
{
Object value = properties[name];
if (Number.IsNumber(value))
{
return int.Parse(value.ToString());
}
return 0;
}
/**
* Utility method that returns the named BorderStyle value form the given map.
*
* @param properties map of named properties (String -> Object)
* @param name property name
* @return Border style if set, otherwise {@link BorderStyle#NONE}
*/
private static BorderStyle GetBorderStyle(Dictionary<String, Object> properties, String name)
{
Object value = properties[name];
BorderStyle border;
if (value is BorderStyle)
{
border = (BorderStyle)value;
}
// @deprecated 3.15 beta 2. getBorderStyle will only work on BorderStyle enums instead of codes in the future.
else if (value is short || value is int)
{
//if (log.check(POILogger.WARN))
//{
// log.log(POILogger.WARN, "Deprecation warning: CellUtil properties map uses Short values for "
// + name + ". Should use BorderStyle enums instead.");
//}
short code = short.Parse(value.ToString());
border = (BorderStyle)code;
}
else if (value == null)
{
border = BorderStyle.None;
}
else
{
throw new RuntimeException("Unexpected border style class. Must be BorderStyle or Short (deprecated).");
}
return border;
}
/**
* Utility method that returns the named FillPattern value from the given map.
*
* @param properties map of named properties (String -> Object)
* @param name property name
* @return FillPattern style if set, otherwise {@link FillPattern#NO_FILL}
* @since POI 3.15 beta 3
*/
private static FillPattern GetFillPattern(Dictionary<String, Object> properties, String name)
{
Object value = properties[name];
FillPattern pattern;
if (value is FillPattern)
{
pattern = (FillPattern)value;
}
// @deprecated 3.15 beta 2. getFillPattern will only work on FillPattern enums instead of codes in the future.
else if (value is short)
{
//if (log.check(POILogger.WARN))
//{
// log.log(POILogger.WARN, "Deprecation warning: CellUtil properties map uses Short values for "
// + name + ". Should use FillPattern enums instead.");
//}
short code = (short)value;
pattern = (FillPattern)code;
}
else if (value == null)
{
pattern = FillPattern.NoFill;
}
else
{
throw new RuntimeException("Unexpected fill pattern style class. Must be FillPattern or Short (deprecated).");
}
return pattern;
}
/**
* Utility method that returns the named HorizontalAlignment value from the given map.
*
* @param properties map of named properties (String -> Object)
* @param name property name
* @return HorizontalAlignment style if set, otherwise {@link HorizontalAlignment#GENERAL}
* @since POI 3.15 beta 3
*/
private static HorizontalAlignment GetHorizontalAlignment(Dictionary<String, Object> properties, String name)
{
Object value = properties[name];
HorizontalAlignment align;
if (value is HorizontalAlignment)
{
align = (HorizontalAlignment)value;
}
// @deprecated 3.15 beta 2. getHorizontalAlignment will only work on HorizontalAlignment enums instead of codes in the future.
else if (value is short)
{
//if (log.check(POILogger.WARN))
//{
// log.log(POILogger.WARN, "Deprecation warning: CellUtil properties map used a Short value for "
// + name + ". Should use HorizontalAlignment enums instead.");
//}
short code = (short)value;
align = (HorizontalAlignment)code;
}
else if (value == null)
{
align = HorizontalAlignment.General;
}
else
{
throw new RuntimeException("Unexpected horizontal alignment style class. Must be HorizontalAlignment or Short (deprecated).");
}
return align;
}
/**
* Utility method that returns the named VerticalAlignment value from the given map.
*
* @param properties map of named properties (String -> Object)
* @param name property name
* @return VerticalAlignment style if set, otherwise {@link VerticalAlignment#BOTTOM}
* @since POI 3.15 beta 3
*/
private static VerticalAlignment GetVerticalAlignment(Dictionary<String, Object> properties, String name)
{
Object value = properties[name];
VerticalAlignment align;
if (value is VerticalAlignment)
{
align = (VerticalAlignment)value;
}
// @deprecated 3.15 beta 2. getVerticalAlignment will only work on VerticalAlignment enums instead of codes in the future.
else if (value is short)
{
//if (log.check(POILogger.WARN))
//{
// log.log(POILogger.WARN, "Deprecation warning: CellUtil properties map used a Short value for "
// + name + ". Should use VerticalAlignment enums instead.");
//}
short code = (short)value;
align = (VerticalAlignment)code;
}
else if (value == null)
{
align = VerticalAlignment.Bottom;
}
else
{
throw new RuntimeException("Unexpected vertical alignment style class. Must be VerticalAlignment or Short (deprecated).");
}
return align;
}
/**
* Utility method that returns the named boolean value form the given map.
*
* @param properties map of properties (String -> Object)
* @param name property name
* @return false if the property does not exist, or is not a {@link Boolean}.
*/
private static bool GetBoolean(Dictionary<String, Object> properties, String name)
{
Object value = properties[name];
bool result = false;
if (bool.TryParse(value.ToString(), out result))
return result;
return false;
}
/**
* Utility method that puts the given value to the given map.
*
* @param properties map of properties (String -> Object)
* @param name property name
* @param value property value
*/
private static void Put(Dictionary<String, Object> properties, String name, Object value)
{
properties[name] = value;
}
/**
* Utility method that puts the named short value to the given map.
*
* @param properties map of properties (String -> Object)
* @param name property name
* @param value property value
*/
private static void PutShort(Dictionary<String, Object> properties, String name, short value)
{
properties[name] = value;
}
/**
* Utility method that puts the named short value to the given map.
*
* @param properties map of properties (String -> Object)
* @param name property name
* @param value property value
*/
private static void PutEnum(Dictionary<String, Object> properties, String name, Enum value)
{
properties[name] = value;
}
/**
* Utility method that puts the named boolean value to the given map.
*
* @param properties map of properties (String -> Object)
* @param name property name
* @param value property value
*/
private static void PutBoolean(Dictionary<String, Object> properties, String name, bool value)
{
properties[name] = value;
}
/**
* Looks for text in the cell that should be unicode, like an alpha and provides the
* unicode version of it.
*
*@param cell The cell to check for unicode values
*@return translated to unicode
*/
public static ICell TranslateUnicodeValues(ICell cell)
{
String s = cell.RichStringCellValue.String;
bool foundUnicode = false;
String lowerCaseStr = s.ToLower();
foreach (UnicodeMapping entry in unicodeMappings)
{
String key = entry.entityName;
if (lowerCaseStr.Contains(key))
{
s = s.Replace(key, entry.resolvedValue);
foundUnicode = true;
}
}
if (foundUnicode)
{
cell.SetCellValue(cell.Row.Sheet.Workbook.GetCreationHelper()
.CreateRichTextString(s));
}
return cell;
}
static CellUtil()
{
unicodeMappings = new UnicodeMapping[] {
um("alpha", "\u03B1" ),
um("beta", "\u03B2" ),
um("gamma", "\u03B3" ),
um("delta", "\u03B4" ),
um("epsilon", "\u03B5" ),
um("zeta", "\u03B6" ),
um("eta", "\u03B7" ),
um("theta", "\u03B8" ),
um("iota", "\u03B9" ),
um("kappa", "\u03BA" ),
um("lambda", "\u03BB" ),
um("mu", "\u03BC" ),
um("nu", "\u03BD" ),
um("xi", "\u03BE" ),
um("omicron", "\u03BF" ),
};
}
private static UnicodeMapping um(String entityName, String resolvedValue)
{
return new UnicodeMapping(entityName, resolvedValue);
}
}
}
| |
//
// Copyright (C) DataStax Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Linq.Expressions;
using System.Net;
using System.Threading.Tasks;
using Cassandra.Connections;
using Cassandra.Connections.Control;
using Cassandra.DataStax.Graph;
using Cassandra.DataStax.Insights;
using Cassandra.DataStax.Insights.InfoProviders;
using Cassandra.DataStax.Insights.InfoProviders.StartupMessage;
using Cassandra.DataStax.Insights.InfoProviders.StatusMessage;
using Cassandra.DataStax.Insights.MessageFactories;
using Cassandra.DataStax.Insights.Schema.StartupMessage;
using Cassandra.DataStax.Insights.Schema.StatusMessage;
using Cassandra.ExecutionProfiles;
using Cassandra.Responses;
using Cassandra.SessionManagement;
using Cassandra.Tasks;
using Moq;
using NUnit.Framework;
namespace Cassandra.Tests.DataStax.Insights
{
[TestFixture]
public class InsightsClientTests
{
private TestTraceListener _listener;
[TearDown]
public void TearDown()
{
if (_listener != null)
{
Trace.Listeners.Remove(_listener);
_listener = null;
}
}
[Test]
public void Should_LogFiveTimes_When_ThereAreMoreThanFiveErrorsOnStartupMessageSend()
{
_listener = new TestTraceListener();
Trace.Listeners.Add(_listener);
var logLevel = Diagnostics.CassandraTraceSwitch.Level;
try
{
Cassandra.Diagnostics.CassandraTraceSwitch.Level = TraceLevel.Verbose;
var cluster = GetCluster(false);
var session = GetSession(cluster);
using (var target = InsightsClientTests.GetInsightsClient(cluster, session))
{
Expression<Func<IControlConnection, Task<Response>>> mockExpression =
cc => cc.UnsafeSendQueryRequestAsync(
"CALL InsightsRpc.reportInsight(?)",
It.IsAny<QueryProtocolOptions>());
Mock.Get(cluster.Metadata.ControlConnection).Setup(mockExpression).ReturnsAsync((Response) null);
target.Init();
TestHelper.RetryAssert(
() => { Mock.Get(cluster.Metadata.ControlConnection).Verify(mockExpression, Times.AtLeast(10)); },
30);
Trace.Flush();
Assert.AreEqual(5, _listener.Queue.Count, string.Join(" ; ", _listener.Queue.ToArray()));
var messages = _listener.Queue.ToArray();
Assert.AreEqual(messages.Count(m => m.Contains("Could not send insights startup event. Exception:")), 5);
}
}
finally
{
Diagnostics.CassandraTraceSwitch.Level = logLevel;
}
}
[Test]
public void Should_ResetErrorCounterForLogging_When_ThereSendMessageIsSuccessful()
{
_listener = new TestTraceListener();
Trace.Listeners.Add(_listener);
var logLevel = Diagnostics.CassandraTraceSwitch.Level;
Cassandra.Diagnostics.CassandraTraceSwitch.Level = TraceLevel.Verbose;
try
{
var cluster = GetCluster(false);
var session = GetSession(cluster);
using (var target = InsightsClientTests.GetInsightsClient(cluster, session))
{
Expression<Func<IControlConnection, Task<Response>>> mockExpression =
cc => cc.UnsafeSendQueryRequestAsync(
"CALL InsightsRpc.reportInsight(?)",
It.IsAny<QueryProtocolOptions>());
Mock.Get(cluster.Metadata.ControlConnection)
.SetupSequence(mockExpression)
.ReturnsAsync((Response) null)
.ReturnsAsync(new FakeResultResponse(ResultResponse.ResultResponseKind.Void))
.ReturnsAsync((Response) null)
.ReturnsAsync((Response) null)
.ReturnsAsync(new FakeResultResponse(ResultResponse.ResultResponseKind.Void))
.ReturnsAsync((Response) null);
target.Init();
TestHelper.RetryAssert(
() => { Mock.Get(cluster.Metadata.ControlConnection).Verify(mockExpression, Times.AtLeast(20)); },
30);
Trace.Flush();
Assert.AreEqual(8, _listener.Queue.Count, string.Join(" ; ", _listener.Queue.ToArray()));
var messages = _listener.Queue.ToArray();
Assert.AreEqual(messages.Count(m => m.Contains("Could not send insights startup event. Exception:")), 1);
Assert.AreEqual(messages.Count(m => m.Contains("Could not send insights status event. Exception:")), 7);
}
}
finally
{
Diagnostics.CassandraTraceSwitch.Level = logLevel;
}
}
[Test]
public void Should_ReturnCompletedTask_When_InitIsCalledAndInsightsMonitoringEnabledIsFalse()
{
var cluster = Mock.Of<IInternalCluster>();
var session = Mock.Of<IInternalSession>();
var config = new TestConfigurationBuilder
{
GraphOptions = new GraphOptions()
}.Build();
config.MonitorReportingOptions.SetMonitorReportingEnabled(false);
Mock.Get(cluster).SetupGet(c => c.Configuration).Returns(config);
var insightsClient = new InsightsClient(
cluster, session, Mock.Of<IInsightsMessageFactory<InsightsStartupData>>(), Mock.Of<IInsightsMessageFactory<InsightsStatusData>>());
var task = insightsClient.ShutdownAsync();
Assert.AreSame(TaskHelper.Completed, task);
}
[Test]
[TestCase(true)]
[TestCase(false)]
public void Should_ReturnCompletedTask_When_InitIsNotCalled(bool enabled)
{
var cluster = Mock.Of<IInternalCluster>();
var session = Mock.Of<IInternalSession>();
var config = new TestConfigurationBuilder
{
GraphOptions = new GraphOptions()
}.Build();
config.MonitorReportingOptions.SetMonitorReportingEnabled(enabled);
Mock.Get(cluster).SetupGet(c => c.Configuration).Returns(config);
var insightsClient = new InsightsClient(
cluster, session, Mock.Of<IInsightsMessageFactory<InsightsStartupData>>(), Mock.Of<IInsightsMessageFactory<InsightsStatusData>>());
var task = insightsClient.ShutdownAsync();
Assert.AreSame(TaskHelper.Completed, task);
}
[Test]
public void Should_InvokeRpcCallCorrectlyAndImmediately_When_SendStartupMessageIsInvoked()
{
const string expectedJson =
"{\"metadata\":{" +
"\"name\":\"driver.startup\"," +
"\"timestamp\":124219041," +
"\"tags\":{\"language\":\"csharp\"}," +
"\"insightType\":\"EVENT\"," +
"\"insightMappingId\":\"v1\"}," +
"\"data\":{" +
"\"clientId\":\"becfe098-e462-47e7-b6a7-a21cd316d4c0\"," +
"\"sessionId\":\"e21eab96-d91e-4790-80bd-1d5fb5472258\"," +
"\"applicationName\":\"appname\"," +
"\"applicationVersion\":\"appv1\"," +
"\"contactPoints\":{\"localhost\":[\"127.0.0.1:9042\"]}," +
"\"initialControlConnection\":\"10.10.10.10:9011\"," +
"\"protocolVersion\":4," +
"\"localAddress\":\"10.10.10.2:9015\"," +
"\"executionProfiles\":{" +
"\"default\":{" +
"\"readTimeout\":1505," +
"\"retry\":{" +
"\"type\":\"DowngradingConsistencyRetryPolicy\"," +
"\"namespace\":\"Cassandra\"}," +
"\"loadBalancing\":{" +
"\"type\":\"RoundRobinPolicy\"," +
"\"namespace\":\"Cassandra\"}," +
"\"speculativeExecution\":{" +
"\"type\":\"ConstantSpeculativeExecutionPolicy\"," +
"\"namespace\":\"Cassandra\"," +
"\"options\":{" +
"\"delay\":1213," +
"\"maxSpeculativeExecutions\":10}}," +
"\"consistency\":\"ALL\"," +
"\"serialConsistency\":\"LOCAL_SERIAL\"," +
"\"graphOptions\":{" +
"\"language\":\"gremlin-groovy\"," +
"\"source\":\"g\"," +
"\"name\":\"testGraphName\"," +
"\"readConsistency\":\"ALL\"," +
"\"writeConsistency\":null," +
"\"readTimeout\":-1}}}," +
"\"poolSizeByHostDistance\":{" +
"\"local\":1," +
"\"remote\":5}," +
"\"heartbeatInterval\":10000," +
"\"compression\":\"SNAPPY\"," +
"\"reconnectionPolicy\":{" +
"\"type\":\"ConstantReconnectionPolicy\"," +
"\"namespace\":\"Cassandra\"," +
"\"options\":{" +
"\"constantDelayMs\":150}}," +
"\"ssl\":{\"enabled\":false}," +
"\"authProvider\":{" +
"\"type\":\"NoneAuthProvider\"," +
"\"namespace\":\"Cassandra\"}," +
"\"configAntiPatterns\":{" +
"\"downgradingConsistency\":\"Downgrading consistency retry policy in use\"}," +
"\"periodicStatusInterval\":5," +
"\"platformInfo\":{" +
"\"os\":{\"name\":\"os name\",\"version\":\"os version\",\"arch\":\"os arch\"}," +
"\"cpus\":{\"length\":2,\"model\":\"Awesome CPU\"}," +
"\"runtime\":{" +
"\"runtimeFramework\":\"runtime-framework\"," +
"\"targetFramework\":\"target-framework\"," +
"\"dependencies\":{" +
"\"Assembly1\":{" +
"\"fullName\":\"Assembly1FullName\"," +
"\"name\":\"Assembly1\"," +
"\"version\":\"1.2.0\"}}}}," +
"\"hostName\":\"awesome_hostname\"," +
"\"driverName\":\"Driver Name\"," +
"\"applicationNameWasGenerated\":false," +
"\"driverVersion\":\"1.1.2\"," +
"\"dataCenters\":[\"dc123\"]}}";
var cluster = GetCluster(false, eventDelayMilliseconds: 5000);
var session = GetSession(cluster);
using (var target = InsightsClientTests.GetInsightsClient(cluster, session))
{
var queryProtocolOptions = new ConcurrentQueue<QueryProtocolOptions>();
Mock.Get(cluster.Metadata.ControlConnection).Setup(cc => cc.UnsafeSendQueryRequestAsync(
"CALL InsightsRpc.reportInsight(?)",
It.IsAny<QueryProtocolOptions>()))
.ReturnsAsync(new FakeResultResponse(ResultResponse.ResultResponseKind.Void))
.Callback<string, QueryProtocolOptions>((query, opts) => { queryProtocolOptions.Enqueue(opts); });
target.Init();
TestHelper.RetryAssert(
() => { Assert.GreaterOrEqual(queryProtocolOptions.Count, 1); }, 10, 50);
queryProtocolOptions.TryPeek(out var result);
Assert.AreEqual(expectedJson, result.Values[0], "Actual: " + Environment.NewLine + result.Values[0]);
}
}
[Test]
public void Should_InvokeRpcCallCorrectlyAndImmediatelyWithExecutionProfiles_When_SendStartupMessageIsInvoked()
{
const string expectedJson =
"{\"metadata\":{" +
"\"name\":\"driver.startup\"," +
"\"timestamp\":124219041," +
"\"tags\":{\"language\":\"csharp\"}," +
"\"insightType\":\"EVENT\"," +
"\"insightMappingId\":\"v1\"}," +
"\"data\":{" +
"\"clientId\":\"becfe098-e462-47e7-b6a7-a21cd316d4c0\"," +
"\"sessionId\":\"e21eab96-d91e-4790-80bd-1d5fb5472258\"," +
"\"applicationName\":\"appname\"," +
"\"applicationVersion\":\"appv1\"," +
"\"contactPoints\":{\"localhost\":[\"127.0.0.1:9042\"]}," +
"\"initialControlConnection\":\"10.10.10.10:9011\"," +
"\"protocolVersion\":4," +
"\"localAddress\":\"10.10.10.2:9015\"," +
"\"executionProfiles\":{" +
"\"default\":{" +
"\"readTimeout\":1505," +
"\"retry\":{" +
"\"type\":\"DowngradingConsistencyRetryPolicy\"," +
"\"namespace\":\"Cassandra\"}," +
"\"loadBalancing\":{" +
"\"type\":\"RoundRobinPolicy\"," +
"\"namespace\":\"Cassandra\"}," +
"\"speculativeExecution\":{" +
"\"type\":\"ConstantSpeculativeExecutionPolicy\"," +
"\"namespace\":\"Cassandra\"," +
"\"options\":{" +
"\"delay\":1213," +
"\"maxSpeculativeExecutions\":10}}," +
"\"consistency\":\"ALL\"," +
"\"serialConsistency\":\"LOCAL_SERIAL\"," +
"\"graphOptions\":{" +
"\"language\":\"gremlin-groovy\"," +
"\"source\":\"g\"," +
"\"name\":\"testGraphName\"," +
"\"readConsistency\":\"ALL\"," +
"\"writeConsistency\":null," +
"\"readTimeout\":-1}}," +
"\"profile2\":{" +
"\"readTimeout\":501," +
"\"retry\":{" +
"\"type\":\"IdempotenceAwareRetryPolicy\"," +
"\"namespace\":\"Cassandra\"," +
"\"options\":{" +
"\"childPolicy\":{" +
"\"type\":\"DefaultRetryPolicy\"," +
"\"namespace\":\"Cassandra\"}}}," +
"\"loadBalancing\":{" +
"\"type\":\"TokenAwarePolicy\"," +
"\"namespace\":\"Cassandra\"," +
"\"options\":{" +
"\"childPolicy\":{" +
"\"type\":\"RoundRobinPolicy\"," +
"\"namespace\":\"Cassandra\"}}}," +
"\"speculativeExecution\":{" +
"\"type\":\"ConstantSpeculativeExecutionPolicy\"," +
"\"namespace\":\"Cassandra\"," +
"\"options\":{" +
"\"delay\":230," +
"\"maxSpeculativeExecutions\":5}}," +
"\"serialConsistency\":\"SERIAL\"" +
"}," +
"\"profile3\":{" +
"\"consistency\":\"EACH_QUORUM\"" +
"}" +
"}," +
"\"poolSizeByHostDistance\":{" +
"\"local\":1," +
"\"remote\":5}," +
"\"heartbeatInterval\":10000," +
"\"compression\":\"SNAPPY\"," +
"\"reconnectionPolicy\":{" +
"\"type\":\"ConstantReconnectionPolicy\"," +
"\"namespace\":\"Cassandra\"," +
"\"options\":{" +
"\"constantDelayMs\":150}}," +
"\"ssl\":{\"enabled\":false}," +
"\"authProvider\":{" +
"\"type\":\"NoneAuthProvider\"," +
"\"namespace\":\"Cassandra\"}," +
"\"configAntiPatterns\":{" +
"\"downgradingConsistency\":\"Downgrading consistency retry policy in use\"}," +
"\"periodicStatusInterval\":5," +
"\"platformInfo\":{" +
"\"os\":{\"name\":\"os name\",\"version\":\"os version\",\"arch\":\"os arch\"}," +
"\"cpus\":{\"length\":2,\"model\":\"Awesome CPU\"}," +
"\"runtime\":{" +
"\"runtimeFramework\":\"runtime-framework\"," +
"\"targetFramework\":\"target-framework\"," +
"\"dependencies\":{" +
"\"Assembly1\":{" +
"\"fullName\":\"Assembly1FullName\"," +
"\"name\":\"Assembly1\"," +
"\"version\":\"1.2.0\"}}}}," +
"\"hostName\":\"awesome_hostname\"," +
"\"driverName\":\"Driver Name\"," +
"\"applicationNameWasGenerated\":false," +
"\"driverVersion\":\"1.1.2\"," +
"\"dataCenters\":[\"dc123\"]}}";
var cluster = GetCluster(true, eventDelayMilliseconds: 5000);
var session = GetSession(cluster);
using (var target = InsightsClientTests.GetInsightsClient(cluster, session))
{
var queryProtocolOptions = new ConcurrentQueue<QueryProtocolOptions>();
Mock.Get(cluster.Metadata.ControlConnection).Setup(cc => cc.UnsafeSendQueryRequestAsync(
"CALL InsightsRpc.reportInsight(?)",
It.IsAny<QueryProtocolOptions>()))
.ReturnsAsync(new FakeResultResponse(ResultResponse.ResultResponseKind.Void))
.Callback<string, QueryProtocolOptions>((query, opts) => { queryProtocolOptions.Enqueue(opts); });
target.Init();
TestHelper.RetryAssert(
() => { Assert.GreaterOrEqual(queryProtocolOptions.Count, 1); }, 10, 50);
queryProtocolOptions.TryPeek(out var result);
Assert.AreEqual(expectedJson, result.Values[0], "Actual: " + Environment.NewLine + result.Values[0]);
}
}
[Test]
public void Should_InvokeRpcCallCorrectlyAndPeriodically_When_SendStatusMessageIsInvoked()
{
const string expectedJson =
"{\"metadata\":{" +
"\"name\":\"driver.status\"," +
"\"timestamp\":124219041," +
"\"tags\":{\"language\":\"csharp\"}," +
"\"insightType\":\"EVENT\"," +
"\"insightMappingId\":\"v1\"}," +
"\"data\":{" +
"\"clientId\":\"becfe098-e462-47e7-b6a7-a21cd316d4c0\"," +
"\"sessionId\":\"e21eab96-d91e-4790-80bd-1d5fb5472258\"," +
"\"controlConnection\":\"10.10.10.10:9011\"," +
"\"connectedNodes\":{" +
"\"127.0.0.1:9042\":{\"connections\":3,\"inFlightQueries\":1}," +
"\"127.0.0.2:9042\":{\"connections\":4,\"inFlightQueries\":2}}}}";
var cluster = GetCluster(false);
var session = GetSession(cluster);
using (var target = InsightsClientTests.GetInsightsClient(cluster, session))
{
var queryProtocolOptions = new ConcurrentQueue<QueryProtocolOptions>();
Mock.Get(cluster.Metadata.ControlConnection).Setup(cc => cc.UnsafeSendQueryRequestAsync(
"CALL InsightsRpc.reportInsight(?)",
It.IsAny<QueryProtocolOptions>()))
.ReturnsAsync(new FakeResultResponse(ResultResponse.ResultResponseKind.Void))
.Callback<string, QueryProtocolOptions>((query, opts) => { queryProtocolOptions.Enqueue(opts); });
target.Init();
TestHelper.RetryAssert(() => { Assert.GreaterOrEqual(queryProtocolOptions.Count, 5); }, 5, 400);
queryProtocolOptions.TryDequeue(out var result); // ignore startup message
queryProtocolOptions.TryPeek(out result);
Assert.AreEqual(expectedJson, result.Values[0], "Actual: " + Environment.NewLine + result.Values[0]);
}
}
private static InsightsClient GetInsightsClient(IInternalCluster cluster, IInternalSession session)
{
var hostnameInfoMock = Mock.Of<IInsightsInfoProvider<string>>();
var driverInfoMock = Mock.Of<IInsightsInfoProvider<DriverInfo>>();
var timestampGeneratorMock = Mock.Of<IInsightsMetadataTimestampGenerator>();
var platformInfoMock = Mock.Of<IInsightsInfoProvider<InsightsPlatformInfo>>();
Mock.Get(hostnameInfoMock).Setup(m => m.GetInformation(cluster, session)).Returns("awesome_hostname");
Mock.Get(driverInfoMock).Setup(m => m.GetInformation(cluster, session)).Returns(new DriverInfo
{
DriverVersion = "1.1.2",
DriverName = "Driver Name"
});
Mock.Get(timestampGeneratorMock).Setup(m => m.GenerateTimestamp()).Returns(124219041);
Mock.Get(platformInfoMock).Setup(m => m.GetInformation(cluster, session)).Returns(new InsightsPlatformInfo
{
CentralProcessingUnits = new CentralProcessingUnitsInfo
{
Length = 2,
Model = "Awesome CPU"
},
Runtime = new RuntimeInfo
{
Dependencies = new Dictionary<string, AssemblyInfo>
{
{ "Assembly1", new AssemblyInfo { Version = "1.2.0", Name = "Assembly1", FullName = "Assembly1FullName" } }
},
RuntimeFramework = "runtime-framework",
TargetFramework = "target-framework"
},
OperatingSystem = new OperatingSystemInfo
{
Version = "os version",
Name = "os name",
Arch = "os arch"
}
});
var target = new InsightsClient(
cluster,
session,
new InsightsStartupMessageFactory(
new InsightsMetadataFactory(timestampGeneratorMock),
new InsightsInfoProvidersCollection(
platformInfoMock,
new ExecutionProfileInfoProvider(
new LoadBalancingPolicyInfoProvider(new ReconnectionPolicyInfoProvider()),
new SpeculativeExecutionPolicyInfoProvider(),
new RetryPolicyInfoProvider()),
new PoolSizeByHostDistanceInfoProvider(),
new AuthProviderInfoProvider(),
new DataCentersInfoProvider(),
new OtherOptionsInfoProvider(),
new ConfigAntiPatternsInfoProvider(),
new ReconnectionPolicyInfoProvider(),
driverInfoMock,
hostnameInfoMock)),
new InsightsStatusMessageFactory(
new InsightsMetadataFactory(timestampGeneratorMock),
new NodeStatusInfoProvider()));
return target;
}
private IInternalSession GetSession(IInternalCluster cluster)
{
var session = Mock.Of<IInternalSession>();
var mockPool1 = Mock.Of<IHostConnectionPool>();
var mockPool2 = Mock.Of<IHostConnectionPool>();
Mock.Get(mockPool1).SetupGet(m => m.InFlight).Returns(1);
Mock.Get(mockPool1).SetupGet(m => m.OpenConnections).Returns(3);
Mock.Get(mockPool2).SetupGet(m => m.InFlight).Returns(2);
Mock.Get(mockPool2).SetupGet(m => m.OpenConnections).Returns(4);
var host1 = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9042);
var host2 = new IPEndPoint(IPAddress.Parse("127.0.0.2"), 9042);
var pools = new Dictionary<IPEndPoint, IHostConnectionPool>
{
{ host1, mockPool1 },
{ host2, mockPool2 }
};
Mock.Get(cluster).Setup(m => m.GetHost(host1)).Returns(new Host(host1, contactPoint: null));
Mock.Get(cluster).Setup(m => m.GetHost(host2)).Returns(new Host(host2, contactPoint: null));
Mock.Get(session).Setup(s => s.GetPools()).Returns(pools.ToArray());
Mock.Get(session).Setup(m => m.Cluster).Returns(cluster);
Mock.Get(session).SetupGet(m => m.InternalSessionId).Returns(Guid.Parse("E21EAB96-D91E-4790-80BD-1D5FB5472258"));
return session;
}
private IInternalCluster GetCluster(bool withProfiles, int eventDelayMilliseconds = 5)
{
var cluster = Mock.Of<IInternalCluster>();
var config = GetConfig(eventDelayMilliseconds, withProfiles);
var metadata = new Metadata(config)
{
ControlConnection = Mock.Of<IControlConnection>()
};
Mock.Get(metadata.ControlConnection).SetupGet(cc => cc.ProtocolVersion).Returns(ProtocolVersion.V4);
Mock.Get(metadata.ControlConnection).SetupGet(cc => cc.EndPoint)
.Returns(new ConnectionEndPoint(new IPEndPoint(IPAddress.Parse("10.10.10.10"), 9011), config.ServerNameResolver, null));
Mock.Get(metadata.ControlConnection).SetupGet(cc => cc.LocalAddress).Returns(new IPEndPoint(IPAddress.Parse("10.10.10.2"), 9015));
var hostIp = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9042);
var hostIp2 = new IPEndPoint(IPAddress.Parse("127.0.0.2"), 9042);
metadata.SetResolvedContactPoints(new Dictionary<IContactPoint, IEnumerable<IConnectionEndPoint>>
{
{
new HostnameContactPoint(
config.DnsResolver,
config.ProtocolOptions,
config.ServerNameResolver,
config.KeepContactPointsUnresolved,
"localhost"),
new[] { new ConnectionEndPoint(hostIp, config.ServerNameResolver, null) } }
});
metadata.AddHost(hostIp);
metadata.AddHost(hostIp2);
metadata.Hosts.ToCollection().First().Datacenter = "dc123";
Mock.Get(cluster).SetupGet(m => m.Configuration).Returns(config);
Mock.Get(cluster).SetupGet(m => m.Metadata).Returns(metadata);
Mock.Get(cluster).Setup(c => c.AllHosts()).Returns(metadata.AllHosts);
return cluster;
}
private Configuration GetConfig(int eventDelayMilliseconds, bool withProfiles)
{
var graphOptions = new GraphOptions().SetName("testGraphName").SetReadConsistencyLevel(ConsistencyLevel.All);
var supportVerifier = Mock.Of<IInsightsSupportVerifier>();
Mock.Get(supportVerifier).Setup(m => m.SupportsInsights(It.IsAny<IInternalCluster>())).Returns(true);
return new TestConfigurationBuilder
{
Policies = new Cassandra.Policies(
new RoundRobinPolicy(),
new ConstantReconnectionPolicy(150),
#pragma warning disable 618
DowngradingConsistencyRetryPolicy.Instance,
#pragma warning restore 618
new ConstantSpeculativeExecutionPolicy(1213, 10),
null),
ProtocolOptions = new ProtocolOptions().SetCompression(CompressionType.Snappy),
PoolingOptions = new PoolingOptions()
.SetCoreConnectionsPerHost(HostDistance.Remote, 5)
.SetCoreConnectionsPerHost(HostDistance.Local, 1)
.SetHeartBeatInterval(10000),
SocketOptions = new SocketOptions().SetReadTimeoutMillis(1505),
QueryOptions = new QueryOptions()
.SetConsistencyLevel(ConsistencyLevel.All)
.SetSerialConsistencyLevel(ConsistencyLevel.LocalSerial),
ExecutionProfiles = withProfiles
? new Dictionary<string, IExecutionProfile>
{
{
"profile2",
new ExecutionProfileBuilder()
.WithReadTimeoutMillis(501)
.WithSpeculativeExecutionPolicy(new ConstantSpeculativeExecutionPolicy(230, 5))
.WithLoadBalancingPolicy(new TokenAwarePolicy(new RoundRobinPolicy()))
.WithRetryPolicy(new IdempotenceAwareRetryPolicy(new DefaultRetryPolicy()))
.WithSerialConsistencyLevel(ConsistencyLevel.Serial)
.CastToClass()
.Build()
},
{
"profile3",
new ExecutionProfileBuilder()
.WithConsistencyLevel(ConsistencyLevel.EachQuorum)
.CastToClass()
.Build()
}
}
: new Dictionary<string, IExecutionProfile>(),
GraphOptions = graphOptions,
ClusterId = Guid.Parse("BECFE098-E462-47E7-B6A7-A21CD316D4C0"),
ApplicationVersion = "appv1",
ApplicationName = "appname",
MonitorReportingOptions = new MonitorReportingOptions().SetMonitorReportingEnabled(true).SetStatusEventDelayMilliseconds(eventDelayMilliseconds),
InsightsSupportVerifier = supportVerifier
}.Build();
}
}
internal class FakeResultResponse : ResultResponse
{
internal FakeResultResponse(ResultResponseKind kind) : base(kind, Mock.Of<IOutput>())
{
}
}
}
| |
//
// This code was created by Jeff Molofee '99
//
// If you've found this code useful, please let me know.
//
// Visit me at www.demonews.com/hosted/nehe
//
//=====================================================================
// Converted to C# and MonoMac by Kenneth J. Pouncey
// http://www.cocoa-mono.org
//
// Copyright (c) 2011 Kenneth J. Pouncey
//
//
// 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.Drawing;
using MonoMac.Foundation;
using MonoMac.AppKit;
using MonoMac.CoreVideo;
using MonoMac.CoreGraphics;
using MonoMac.OpenGL;
namespace NeHeLesson9
{
public partial class MyOpenGLView : MonoMac.AppKit.NSView
{
NSOpenGLContext openGLContext;
NSOpenGLPixelFormat pixelFormat;
MainWindowController controller;
CVDisplayLink displayLink;
NSObject notificationProxy;
[Export("initWithFrame:")]
public MyOpenGLView (RectangleF frame) : this(frame, null)
{
}
public MyOpenGLView (RectangleF frame,NSOpenGLContext context) : base(frame)
{
var attribs = new object [] {
NSOpenGLPixelFormatAttribute.Accelerated,
NSOpenGLPixelFormatAttribute.NoRecovery,
NSOpenGLPixelFormatAttribute.DoubleBuffer,
NSOpenGLPixelFormatAttribute.ColorSize, 24,
NSOpenGLPixelFormatAttribute.DepthSize, 16 };
pixelFormat = new NSOpenGLPixelFormat (attribs);
if (pixelFormat == null)
Console.WriteLine ("No OpenGL pixel format");
// NSOpenGLView does not handle context sharing, so we draw to a custom NSView instead
openGLContext = new NSOpenGLContext (pixelFormat, context);
openGLContext.MakeCurrentContext ();
// Synchronize buffer swaps with vertical refresh rate
openGLContext.SwapInterval = true;
// Initialize our newly created view.
InitGL ();
SetupDisplayLink ();
// Look for changes in view size
// Note, -reshape will not be called automatically on size changes because NSView does not export it to override
notificationProxy = NSNotificationCenter.DefaultCenter.AddObserver (NSView.NSViewGlobalFrameDidChangeNotification, HandleReshape);
}
public override void DrawRect (RectangleF dirtyRect)
{
// Ignore if the display link is still running
if (!displayLink.IsRunning && controller != null)
DrawView ();
}
public override bool AcceptsFirstResponder ()
{
// We want this view to be able to receive key events
return true;
}
public override void LockFocus ()
{
base.LockFocus ();
if (openGLContext.View != this)
openGLContext.View = this;
}
public override void KeyDown (NSEvent theEvent)
{
controller.KeyDown (theEvent);
}
public override void MouseDown (NSEvent theEvent)
{
controller.MouseDown (theEvent);
}
// All Setup For OpenGL Goes Here
public bool InitGL ()
{
// Enable Texture Mapping
GL.Enable (EnableCap.Texture2D);
// Enables Smooth Shading
GL.ShadeModel (ShadingModel.Smooth);
// Set background color to black
GL.ClearColor (0, 0, 0, 0.5f);
// Setup Depth Testing
// Depth Buffer setup
GL.ClearDepth (1.0);
// Really Nice Perspective Calculations
GL.Hint (HintTarget.PerspectiveCorrectionHint, HintMode.Nicest);
GL.BlendFunc (BlendingFactorSrc.SrcAlpha, BlendingFactorDest.One);
GL.Enable (EnableCap.Blend);
return true;
}
private void DrawView ()
{
// This method will be called on both the main thread (through -drawRect:) and a secondary thread (through the display link rendering loop)
// Also, when resizing the view, -reshape is called on the main thread, but we may be drawing on a secondary thread
// Add a mutex around to avoid the threads accessing the context simultaneously
openGLContext.CGLContext.Lock ();
// Make sure we draw to the right context
openGLContext.MakeCurrentContext ();
// Delegate to the scene object for rendering
controller.Scene.DrawGLScene ();
openGLContext.FlushBuffer ();
openGLContext.CGLContext.Unlock ();
}
private void SetupDisplayLink ()
{
// Create a display link capable of being used with all active displays
displayLink = new CVDisplayLink ();
// Set the renderer output callback function
displayLink.SetOutputCallback (MyDisplayLinkOutputCallback);
// Set the display link for the current renderer
CGLContext cglContext = openGLContext.CGLContext;
CGLPixelFormat cglPixelFormat = PixelFormat.CGLPixelFormat;
displayLink.SetCurrentDisplay (cglContext, cglPixelFormat);
}
public CVReturn MyDisplayLinkOutputCallback (CVDisplayLink displayLink, ref CVTimeStamp inNow, ref CVTimeStamp inOutputTime, CVOptionFlags flagsIn, ref CVOptionFlags flagsOut)
{
CVReturn result = GetFrameForTime (inOutputTime);
return result;
}
private CVReturn GetFrameForTime (CVTimeStamp outputTime)
{
// There is no autorelease pool when this method is called because it will be called from a background thread
// It's important to create one or you will leak objects
using (NSAutoreleasePool pool = new NSAutoreleasePool ()) {
// Update the animation
DrawView ();
}
return CVReturn.Success;
}
public NSOpenGLContext OpenGLContext {
get { return openGLContext; }
}
public NSOpenGLPixelFormat PixelFormat {
get { return pixelFormat; }
}
public MainWindowController MainController {
set { controller = value; }
}
public void UpdateView ()
{
// This method will be called on the main thread when resizing, but we may be drawing on a secondary thread through the display link
// Add a mutex around to avoid the threads accessing the context simultaneously
openGLContext.CGLContext.Lock ();
// Delegate to the scene object to update for a change in the view size
controller.Scene.ResizeGLScene (Bounds);
openGLContext.Update ();
openGLContext.CGLContext.Unlock ();
}
private void HandleReshape (NSNotification note)
{
UpdateView ();
}
public void StartAnimation ()
{
if (displayLink != null && !displayLink.IsRunning)
displayLink.Start ();
}
public void StopAnimation ()
{
if (displayLink != null && displayLink.IsRunning)
displayLink.Stop ();
}
// Clean up the notifications
public void DeAllocate ()
{
displayLink.Stop ();
displayLink.SetOutputCallback (null);
NSNotificationCenter.DefaultCenter.RemoveObserver (notificationProxy);
}
[Export("toggleFullScreen:")]
public void toggleFullScreen (NSObject sender)
{
controller.toggleFullScreen (sender);
}
}
}
| |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
// Template Source: Templates\CSharp\Requests\EntityCollectionRequest.cs.tt
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading;
using System.Linq.Expressions;
/// <summary>
/// The type PostSingleValueExtendedPropertiesCollectionRequest.
/// </summary>
public partial class PostSingleValueExtendedPropertiesCollectionRequest : BaseRequest, IPostSingleValueExtendedPropertiesCollectionRequest
{
/// <summary>
/// Constructs a new PostSingleValueExtendedPropertiesCollectionRequest.
/// </summary>
/// <param name="requestUrl">The URL for the built request.</param>
/// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param>
/// <param name="options">Query and header option name value pairs for the request.</param>
public PostSingleValueExtendedPropertiesCollectionRequest(
string requestUrl,
IBaseClient client,
IEnumerable<Option> options)
: base(requestUrl, client, options)
{
}
/// <summary>
/// Adds the specified SingleValueLegacyExtendedProperty to the collection via POST.
/// </summary>
/// <param name="singleValueLegacyExtendedProperty">The SingleValueLegacyExtendedProperty to add.</param>
/// <returns>The created SingleValueLegacyExtendedProperty.</returns>
public System.Threading.Tasks.Task<SingleValueLegacyExtendedProperty> AddAsync(SingleValueLegacyExtendedProperty singleValueLegacyExtendedProperty)
{
return this.AddAsync(singleValueLegacyExtendedProperty, CancellationToken.None);
}
/// <summary>
/// Adds the specified SingleValueLegacyExtendedProperty to the collection via POST.
/// </summary>
/// <param name="singleValueLegacyExtendedProperty">The SingleValueLegacyExtendedProperty to add.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The created SingleValueLegacyExtendedProperty.</returns>
public System.Threading.Tasks.Task<SingleValueLegacyExtendedProperty> AddAsync(SingleValueLegacyExtendedProperty singleValueLegacyExtendedProperty, CancellationToken cancellationToken)
{
this.ContentType = "application/json";
this.Method = "POST";
return this.SendAsync<SingleValueLegacyExtendedProperty>(singleValueLegacyExtendedProperty, cancellationToken);
}
/// <summary>
/// Gets the collection page.
/// </summary>
/// <returns>The collection page.</returns>
public System.Threading.Tasks.Task<IPostSingleValueExtendedPropertiesCollectionPage> GetAsync()
{
return this.GetAsync(CancellationToken.None);
}
/// <summary>
/// Gets the collection page.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The collection page.</returns>
public async System.Threading.Tasks.Task<IPostSingleValueExtendedPropertiesCollectionPage> GetAsync(CancellationToken cancellationToken)
{
this.Method = "GET";
var response = await this.SendAsync<PostSingleValueExtendedPropertiesCollectionResponse>(null, cancellationToken).ConfigureAwait(false);
if (response != null && response.Value != null && response.Value.CurrentPage != null)
{
if (response.AdditionalData != null)
{
object nextPageLink;
response.AdditionalData.TryGetValue("@odata.nextLink", out nextPageLink);
var nextPageLinkString = nextPageLink as string;
if (!string.IsNullOrEmpty(nextPageLinkString))
{
response.Value.InitializeNextPageRequest(
this.Client,
nextPageLinkString);
}
// Copy the additional data collection to the page itself so that information is not lost
response.Value.AdditionalData = response.AdditionalData;
}
return response.Value;
}
return null;
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="value">The expand value.</param>
/// <returns>The request object to send.</returns>
public IPostSingleValueExtendedPropertiesCollectionRequest Expand(string value)
{
this.QueryOptions.Add(new QueryOption("$expand", value));
return this;
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="expandExpression">The expression from which to calculate the expand value.</param>
/// <returns>The request object to send.</returns>
public IPostSingleValueExtendedPropertiesCollectionRequest Expand(Expression<Func<SingleValueLegacyExtendedProperty, object>> expandExpression)
{
if (expandExpression == null)
{
throw new ArgumentNullException(nameof(expandExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(expandExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$expand", value));
}
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="value">The select value.</param>
/// <returns>The request object to send.</returns>
public IPostSingleValueExtendedPropertiesCollectionRequest Select(string value)
{
this.QueryOptions.Add(new QueryOption("$select", value));
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="selectExpression">The expression from which to calculate the select value.</param>
/// <returns>The request object to send.</returns>
public IPostSingleValueExtendedPropertiesCollectionRequest Select(Expression<Func<SingleValueLegacyExtendedProperty, object>> selectExpression)
{
if (selectExpression == null)
{
throw new ArgumentNullException(nameof(selectExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(selectExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$select", value));
}
return this;
}
/// <summary>
/// Adds the specified top value to the request.
/// </summary>
/// <param name="value">The top value.</param>
/// <returns>The request object to send.</returns>
public IPostSingleValueExtendedPropertiesCollectionRequest Top(int value)
{
this.QueryOptions.Add(new QueryOption("$top", value.ToString()));
return this;
}
/// <summary>
/// Adds the specified filter value to the request.
/// </summary>
/// <param name="value">The filter value.</param>
/// <returns>The request object to send.</returns>
public IPostSingleValueExtendedPropertiesCollectionRequest Filter(string value)
{
this.QueryOptions.Add(new QueryOption("$filter", value));
return this;
}
/// <summary>
/// Adds the specified skip value to the request.
/// </summary>
/// <param name="value">The skip value.</param>
/// <returns>The request object to send.</returns>
public IPostSingleValueExtendedPropertiesCollectionRequest Skip(int value)
{
this.QueryOptions.Add(new QueryOption("$skip", value.ToString()));
return this;
}
/// <summary>
/// Adds the specified orderby value to the request.
/// </summary>
/// <param name="value">The orderby value.</param>
/// <returns>The request object to send.</returns>
public IPostSingleValueExtendedPropertiesCollectionRequest OrderBy(string value)
{
this.QueryOptions.Add(new QueryOption("$orderby", value));
return this;
}
}
}
| |
// 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.Threading;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Editor.UnitTests.TypeInferrer;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.TypeInferrer
{
public partial class TypeInferrerTests : TypeInferrerTestBase<CSharpTestWorkspaceFixture>
{
protected override void TestWorker(Document document, TextSpan textSpan, string expectedType, bool useNodeStartPosition)
{
var root = document.GetSyntaxTreeAsync().Result.GetRoot();
var node = FindExpressionSyntaxFromSpan(root, textSpan);
var typeInference = document.GetLanguageService<ITypeInferenceService>();
var inferredType = useNodeStartPosition
? typeInference.InferType(document.GetSemanticModelForSpanAsync(new TextSpan(node?.SpanStart ?? textSpan.Start, 0), CancellationToken.None).Result, node?.SpanStart ?? textSpan.Start, objectAsDefault: true, cancellationToken: CancellationToken.None)
: typeInference.InferType(document.GetSemanticModelForSpanAsync(node?.Span ?? textSpan, CancellationToken.None).Result, node, objectAsDefault: true, cancellationToken: CancellationToken.None);
var typeSyntax = inferredType.GenerateTypeSyntax();
Assert.Equal(expectedType, typeSyntax.ToString());
}
private void TestInClass(string text, string expectedType)
{
text = @"class C
{
$
}".Replace("$", text);
Test(text, expectedType);
}
private void TestInMethod(string text, string expectedType, bool testNode = true, bool testPosition = true)
{
text = @"class C
{
void M()
{
$
}
}".Replace("$", text);
Test(text, expectedType, testNode: testNode, testPosition: testPosition);
}
private ExpressionSyntax FindExpressionSyntaxFromSpan(SyntaxNode root, TextSpan textSpan)
{
var token = root.FindToken(textSpan.Start);
var currentNode = token.Parent;
while (currentNode != null)
{
ExpressionSyntax result = currentNode as ExpressionSyntax;
if (result != null && result.Span == textSpan)
{
return result;
}
currentNode = currentNode.Parent;
}
return null;
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public void TestConditional1()
{
// We do not support position inference here as we're before the ? and we only look
// backwards to infer a type here.
TestInMethod("var q = [|Foo()|] ? 1 : 2;", "System.Boolean",
testPosition: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public void TestConditional2()
{
TestInMethod("var q = a ? [|Foo()|] : 2;", "System.Int32");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public void TestConditional3()
{
TestInMethod(@"var q = a ? """" : [|Foo()|];", "System.String");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public void TestVariableDeclarator1()
{
TestInMethod("int q = [|Foo()|];", "System.Int32");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public void TestVariableDeclarator2()
{
TestInMethod("var q = [|Foo()|];", "System.Object");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public void TestCoalesce1()
{
TestInMethod("var q = [|Foo()|] ?? 1;", "System.Int32?", testPosition: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public void TestCoalesce2()
{
TestInMethod(@"bool? b;
var q = b ?? [|Foo()|];", "System.Boolean");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public void TestCoalesce3()
{
TestInMethod(@"string s;
var q = s ?? [|Foo()|];", "System.String");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public void TestCoalesce4()
{
TestInMethod("var q = [|Foo()|] ?? string.Empty;", "System.String", testPosition: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public void TestBinaryExpression1()
{
TestInMethod(@"string s;
var q = s + [|Foo()|];", "System.String");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public void TestBinaryExpression2()
{
TestInMethod(@"var s;
var q = s || [|Foo()|];", "System.Boolean");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public void TestBinaryOperator1()
{
TestInMethod(@"var q = x << [|Foo()|];", "System.Int32");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public void TestBinaryOperator2()
{
TestInMethod(@"var q = x >> [|Foo()|];", "System.Int32");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public void TestAssignmentOperator3()
{
TestInMethod(@"var q <<= [|Foo()|];", "System.Int32");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public void TestAssignmentOperator4()
{
TestInMethod(@"var q >>= [|Foo()|];", "System.Int32");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(617633)]
public void TestOverloadedConditionalLogicalOperatorsInferBool()
{
Test(@"using System;
class C
{
public static C operator &(C c, C d) { return null; }
public static bool operator true(C c) { return true; }
public static bool operator false(C c) { return false; }
static void Main(string[] args)
{
var c = new C() && [|Foo()|];
}
}", "System.Boolean");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(617633)]
public void TestConditionalLogicalOrOperatorAlwaysInfersBool()
{
var text = @"using System;
class C
{
static void Main(string[] args)
{
var x = a || [|7|];
}
}";
Test(text, "System.Boolean");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(617633)]
public void TestConditionalLogicalAndOperatorAlwaysInfersBool()
{
var text = @"using System;
class C
{
static void Main(string[] args)
{
var x = a && [|7|];
}
}";
Test(text, "System.Boolean");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(617633)]
public void TestLogicalOrOperatorInference1()
{
var text = @"using System;
class C
{
static void Main(string[] args)
{
var x = [|a|] | true;
}
}";
Test(text, "System.Boolean", testPosition: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(617633)]
public void TestLogicalOrOperatorInference2()
{
var text = @"using System;
class C
{
static void Main(string[] args)
{
var x = [|a|] | b | c || d;
}
}";
Test(text, "System.Boolean", testPosition: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(617633)]
public void TestLogicalOrOperatorInference3()
{
var text = @"using System;
class C
{
static void Main(string[] args)
{
var x = a | b | [|c|] || d;
}
}";
Test(text, "System.Boolean");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(617633)]
public void TestLogicalOrOperatorInference4()
{
var text = @"using System;
class C
{
static void Main(string[] args)
{
var x = Foo([|a|] | b);
}
static object Foo(Program p)
{
return p;
}
}";
Test(text, "Program", testPosition: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(617633)]
public void TestLogicalOrOperatorInference5()
{
var text = @"using System;
class C
{
static void Main(string[] args)
{
var x = Foo([|a|] | b);
}
static object Foo(bool p)
{
return p;
}
}";
Test(text, "System.Boolean");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(617633)]
public void TestLogicalOrOperatorInference6()
{
var text = @"using System;
class C
{
static void Main(string[] args)
{
if (([|x|] | y) != 0) {}
}
}";
Test(text, "System.Int32", testPosition: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(617633)]
public void TestLogicalOrOperatorInference7()
{
var text = @"using System;
class C
{
static void Main(string[] args)
{
if ([|x|] | y) {}
}
}";
Test(text, "System.Boolean");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(617633)]
public void TestLogicalAndOperatorInference1()
{
var text = @"using System;
class C
{
static void Main(string[] args)
{
var x = [|a|] & true;
}
}";
Test(text, "System.Boolean", testPosition: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(617633)]
public void TestLogicalAndOperatorInference2()
{
var text = @"using System;
class C
{
static void Main(string[] args)
{
var x = [|a|] & b & c && d;
}
}";
Test(text, "System.Boolean", testPosition: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(617633)]
public void TestLogicalAndOperatorInference3()
{
var text = @"using System;
class C
{
static void Main(string[] args)
{
var x = a & b & [|c|] && d;
}
}";
Test(text, "System.Boolean");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(617633)]
public void TestLogicalAndOperatorInference4()
{
var text = @"using System;
class C
{
static void Main(string[] args)
{
var x = Foo([|a|] & b);
}
static object Foo(Program p)
{
return p;
}
}";
Test(text, "Program", testPosition: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(617633)]
public void TestLogicalAndOperatorInference5()
{
var text = @"using System;
class C
{
static void Main(string[] args)
{
var x = Foo([|a|] & b);
}
static object Foo(bool p)
{
return p;
}
}";
Test(text, "System.Boolean");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(617633)]
public void TestLogicalAndOperatorInference6()
{
var text = @"using System;
class C
{
static void Main(string[] args)
{
if (([|x|] & y) != 0) {}
}
}";
Test(text, "System.Int32", testPosition: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(617633)]
public void TestLogicalAndOperatorInference7()
{
var text = @"using System;
class C
{
static void Main(string[] args)
{
if ([|x|] & y) {}
}
}";
Test(text, "System.Boolean");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(617633)]
public void TestLogicalXorOperatorInference1()
{
var text = @"using System;
class C
{
static void Main(string[] args)
{
var x = [|a|] ^ true;
}
}";
Test(text, "System.Boolean", testPosition: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(617633)]
public void TestLogicalXorOperatorInference2()
{
var text = @"using System;
class C
{
static void Main(string[] args)
{
var x = [|a|] ^ b ^ c && d;
}
}";
Test(text, "System.Boolean", testPosition: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(617633)]
public void TestLogicalXorOperatorInference3()
{
var text = @"using System;
class C
{
static void Main(string[] args)
{
var x = a ^ b ^ [|c|] && d;
}
}";
Test(text, "System.Boolean");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(617633)]
public void TestLogicalXorOperatorInference4()
{
var text = @"using System;
class C
{
static void Main(string[] args)
{
var x = Foo([|a|] ^ b);
}
static object Foo(Program p)
{
return p;
}
}";
Test(text, "Program", testPosition: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(617633)]
public void TestLogicalXorOperatorInference5()
{
var text = @"using System;
class C
{
static void Main(string[] args)
{
var x = Foo([|a|] ^ b);
}
static object Foo(bool p)
{
return p;
}
}";
Test(text, "System.Boolean");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(617633)]
public void TestLogicalXorOperatorInference6()
{
var text = @"using System;
class C
{
static void Main(string[] args)
{
if (([|x|] ^ y) != 0) {}
}
}";
Test(text, "System.Int32", testPosition: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(617633)]
public void TestLogicalXorOperatorInference7()
{
var text = @"using System;
class C
{
static void Main(string[] args)
{
if ([|x|] ^ y) {}
}
}";
Test(text, "System.Boolean");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(617633)]
public void TestLogicalOrEqualsOperatorInference1()
{
var text = @"using System;
class C
{
static void Main(string[] args)
{
if ([|x|] |= y) {}
}
}";
Test(text, "System.Boolean");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(617633)]
public void TestLogicalOrEqualsOperatorInference2()
{
var text = @"using System;
class C
{
static void Main(string[] args)
{
int z = [|x|] |= y;
}
}";
Test(text, "System.Int32");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(617633)]
public void TestLogicalAndEqualsOperatorInference1()
{
var text = @"using System;
class C
{
static void Main(string[] args)
{
if ([|x|] &= y) {}
}
}";
Test(text, "System.Boolean");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(617633)]
public void TestLogicalAndEqualsOperatorInference2()
{
var text = @"using System;
class C
{
static void Main(string[] args)
{
int z = [|x|] &= y;
}
}";
Test(text, "System.Int32");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(617633)]
public void TestLogicalXorEqualsOperatorInference1()
{
var text = @"using System;
class C
{
static void Main(string[] args)
{
if ([|x|] ^= y) {}
}
}";
Test(text, "System.Boolean");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(617633)]
public void TestLogicalXorEqualsOperatorInference2()
{
var text = @"using System;
class C
{
static void Main(string[] args)
{
int z = [|x|] ^= y;
}
}";
Test(text, "System.Int32");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public void TestReturn1()
{
TestInClass(@"int M() { return [|Foo()|]; }", "System.Int32");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public void TestReturn2()
{
TestInMethod("return [|Foo()|];", "void");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public void TestReturn3()
{
TestInClass(@"int Property { get { return [|Foo()|]; } }", "System.Int32");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(827897)]
public void TestYieldReturn()
{
var markup =
@"using System.Collections.Generic;
class Program
{
IEnumerable<int> M()
{
yield return [|abc|]
}
}";
Test(markup, "System.Int32");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public void TestReturnInLambda()
{
TestInMethod("System.Func<string,int> f = s => { return [|Foo()|]; };", "System.Int32");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public void TestLambda()
{
TestInMethod("System.Func<string, int> f = s => [|Foo()|];", "System.Int32");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public void TestThrow()
{
TestInMethod("throw [|Foo()|];", "global::System.Exception");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public void TestCatch()
{
TestInMethod("try { } catch ([|Foo|] ex) { }", "global::System.Exception");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public void TestIf()
{
TestInMethod(@"if ([|Foo()|]) { }", "System.Boolean");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public void TestWhile()
{
TestInMethod(@"while ([|Foo()|]) { }", "System.Boolean");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public void TestDo()
{
TestInMethod(@"do { } while ([|Foo()|])", "System.Boolean");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public void TestFor1()
{
TestInMethod(@"for (int i = 0; [|Foo()|]; i++) { }", "System.Boolean");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public void TestFor2()
{
TestInMethod(@"for (string i = [|Foo()|]; ; ) { }", "System.String");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public void TestFor3()
{
TestInMethod(@"for (var i = [|Foo()|]; ; ) { }", "System.Int32");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public void TestUsing1()
{
TestInMethod(@"using ([|Foo()|]) { }", "global::System.IDisposable");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public void TestUsing2()
{
TestInMethod(@"using (int i = [|Foo()|]) { }", "System.Int32");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public void TestUsing3()
{
TestInMethod(@"using (var v = [|Foo()|]) { }", "global::System.IDisposable");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public void TestForEach()
{
TestInMethod(@"foreach (int v in [|Foo()|]) { }", "global::System.Collections.Generic.IEnumerable<System.Int32>");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public void TestPrefixExpression1()
{
TestInMethod(@"var q = +[|Foo()|];", "System.Int32");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public void TestPrefixExpression2()
{
TestInMethod(@"var q = -[|Foo()|];", "System.Int32");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public void TestPrefixExpression3()
{
TestInMethod(@"var q = ~[|Foo()|];", "System.Int32");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public void TestPrefixExpression4()
{
TestInMethod(@"var q = ![|Foo()|];", "System.Boolean");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public void TestArrayRankSpecifier()
{
TestInMethod(@"var q = new string[[|Foo()|]];", "System.Int32");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public void TestSwitch1()
{
TestInMethod(@"switch ([|Foo()|]) { }", "System.Int32");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public void TestSwitch2()
{
TestInMethod(@"switch ([|Foo()|]) { default: }", "System.Int32");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public void TestSwitch3()
{
TestInMethod(@"switch ([|Foo()|]) { case ""a"": }", "System.String");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public void TestMethodCall1()
{
TestInMethod(@"Bar([|Foo()|]);", "System.Object");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public void TestMethodCall2()
{
TestInClass(@"void M() { Bar([|Foo()|]); } void Bar(int i);", "System.Int32");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public void TestMethodCall3()
{
TestInClass(@"void M() { Bar([|Foo()|]); } void Bar();", "System.Object");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public void TestMethodCall4()
{
TestInClass(@"void M() { Bar([|Foo()|]); } void Bar(int i, string s);", "System.Int32");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public void TestMethodCall5()
{
TestInClass(@"void M() { Bar(s: [|Foo()|]); } void Bar(int i, string s);", "System.String");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public void TestConstructorCall1()
{
TestInMethod(@"new C([|Foo()|]);", "System.Object");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public void TestConstructorCall2()
{
TestInClass(@"void M() { new C([|Foo()|]); } C(int i) { }", "System.Int32");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public void TestConstructorCall3()
{
TestInClass(@"void M() { new C([|Foo()|]); } C() { }", "System.Object");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public void TestConstructorCall4()
{
TestInClass(@"void M() { new C([|Foo()|]); } C(int i, string s) { }", "System.Int32");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public void TestConstructorCall5()
{
TestInClass(@"void M() { new C(s: [|Foo()|]); } C(int i, string s) { }", "System.String");
}
[WorkItem(858112)]
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public void TestThisConstructorInitializer1()
{
Test(@"class MyClass { public MyClass(int x) : this([|test|]) { } }", "System.Int32");
}
[WorkItem(858112)]
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public void TestThisConstructorInitializer2()
{
Test(@"class MyClass { public MyClass(int x, string y) : this(5, [|test|]) { } }", "System.String");
}
[WorkItem(858112)]
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public void TestBaseConstructorInitializer()
{
Test(@"class B { public B(int x) { } } class D : B { public D() : base([|test|]) { } }", "System.Int32");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public void TestIndexAccess1()
{
TestInMethod(@"string[] i; i[[|Foo()|]];", "System.Int32");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public void TestIndexerCall1()
{
TestInMethod(@"this[[|Foo()|]];", "System.Int32");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public void TestIndexerCall2()
{
// Update this when binding of indexers is working.
TestInClass(@"void M() { this[[|Foo()|]]; } int this [int i] { get; }", "System.Int32");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public void TestIndexerCall3()
{
// Update this when binding of indexers is working.
TestInClass(@"void M() { this[[|Foo()|]]; } int this [int i, string s] { get; }", "System.Int32");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public void TestIndexerCall5()
{
TestInClass(@"void M() { this[s: [|Foo()|]]; } int this [int i, string s] { get; }", "System.String");
}
[Fact]
public void TestArrayInitializerInImplicitArrayCreationSimple()
{
var text =
@"using System.Collections.Generic;
class C
{
void M()
{
var a = new[] { 1, [|2|] };
}
}";
Test(text, "System.Int32");
}
[Fact]
public void TestArrayInitializerInImplicitArrayCreation1()
{
var text =
@"using System.Collections.Generic;
class C
{
void M()
{
var a = new[] { Bar(), [|Foo()|] };
}
int Bar() { return 1; }
int Foo() { return 2; }
}";
Test(text, "System.Int32");
}
[Fact]
public void TestArrayInitializerInImplicitArrayCreation2()
{
var text =
@"using System.Collections.Generic;
class C
{
void M()
{
var a = new[] { Bar(), [|Foo()|] };
}
int Bar() { return 1; }
}";
Test(text, "System.Int32");
}
[Fact]
public void TestArrayInitializerInImplicitArrayCreation3()
{
var text =
@"using System.Collections.Generic;
class C
{
void M()
{
var a = new[] { Bar(), [|Foo()|] };
}
}";
Test(text, "System.Object");
}
[Fact]
public void TestArrayInitializerInEqualsValueClauseSimple()
{
var text =
@"using System.Collections.Generic;
class C
{
void M()
{
int[] a = { 1, [|2|] };
}
}";
Test(text, "System.Int32");
}
[Fact]
public void TestArrayInitializerInEqualsValueClause()
{
var text =
@"using System.Collections.Generic;
class C
{
void M()
{
int[] a = { Bar(), [|Foo()|] };
}
int Bar() { return 1; }
}";
Test(text, "System.Int32");
}
[Fact]
[WorkItem(529480)]
[Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public void TestCollectionInitializer1()
{
var text =
@"using System.Collections.Generic;
class C
{
void M()
{
new List<int>() { [|Foo()|] };
}
}";
Test(text, "System.Int32");
}
[Fact]
[WorkItem(529480)]
[Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public void TestCollectionInitializer2()
{
var text =
@"
using System.Collections.Generic;
class C
{
void M()
{
new Dictionary<int,string>() { { [|Foo()|], """" } };
}
}";
Test(text, "System.Int32");
}
[Fact]
[WorkItem(529480)]
[Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public void TestCollectionInitializer3()
{
var text =
@"
using System.Collections.Generic;
class C
{
void M()
{
new Dictionary<int,string>() { { 0, [|Foo()|] } };
}
}";
Test(text, "System.String");
}
[Fact]
[WorkItem(529480)]
[Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public void TestCustomCollectionInitializerAddMethod1()
{
var text =
@"class C : System.Collections.IEnumerable
{
void M()
{
var x = new C() { [|a|] };
}
void Add(int i) { }
void Add(string s, bool b) { }
public System.Collections.IEnumerator GetEnumerator()
{
throw new System.NotImplementedException();
}
}";
Test(text, "System.Int32", testPosition: false);
}
[Fact]
[WorkItem(529480)]
[Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public void TestCustomCollectionInitializerAddMethod2()
{
var text =
@"class C : System.Collections.IEnumerable
{
void M()
{
var x = new C() { { ""test"", [|b|] } };
}
void Add(int i) { }
void Add(string s, bool b) { }
public System.Collections.IEnumerator GetEnumerator()
{
throw new System.NotImplementedException();
}
}";
Test(text, "System.Boolean");
}
[Fact]
[WorkItem(529480)]
[Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public void TestCustomCollectionInitializerAddMethod3()
{
var text =
@"class C : System.Collections.IEnumerable
{
void M()
{
var x = new C() { { [|s|], true } };
}
void Add(int i) { }
void Add(string s, bool b) { }
public System.Collections.IEnumerator GetEnumerator()
{
throw new System.NotImplementedException();
}
}";
Test(text, "System.String");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public void TestArrayInference1()
{
var text =
@"
class A
{
void Foo()
{
A[] x = new [|C|][] { };
}
}";
Test(text, "global::A", testPosition: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public void TestArrayInference1_Position()
{
var text =
@"
class A
{
void Foo()
{
A[] x = new [|C|][] { };
}
}";
Test(text, "global::A[]", testNode: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public void TestArrayInference2()
{
var text =
@"
class A
{
void Foo()
{
A[][] x = new [|C|][][] { };
}
}";
Test(text, "global::A", testPosition: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public void TestArrayInference2_Position()
{
var text =
@"
class A
{
void Foo()
{
A[][] x = new [|C|][][] { };
}
}";
Test(text, "global::A[][]", testNode: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public void TestArrayInference3()
{
var text =
@"
class A
{
void Foo()
{
A[][] x = new [|C|][] { };
}
}";
Test(text, "global::A[]", testPosition: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public void TestArrayInference3_Position()
{
var text =
@"
class A
{
void Foo()
{
A[][] x = new [|C|][] { };
}
}";
Test(text, "global::A[][]", testNode: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public void TestArrayInference4()
{
var text =
@"
using System;
class A
{
void Foo()
{
Func<int, int>[] x = new Func<int, int>[] { [|Bar()|] };
}
}";
Test(text, "global::System.Func<System.Int32,System.Int32>");
}
[WorkItem(538993)]
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public void TestInsideLambda2()
{
var text =
@"using System;
class C
{
void M()
{
Func<int,int> f = i => [|here|]
}
}";
Test(text, "System.Int32");
}
[WorkItem(539813)]
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public void TestPointer1()
{
var text =
@"class C
{
void M(int* i)
{
var q = i[[|Foo()|]];
}
}";
Test(text, "System.Int32");
}
[WorkItem(539813)]
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public void TestDynamic1()
{
var text =
@"class C
{
void M(dynamic i)
{
var q = i[[|Foo()|]];
}
}";
Test(text, "System.Int32");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
public void TestChecked1()
{
var text =
@"class C
{
void M()
{
string q = checked([|Foo()|]);
}
}";
Test(text, "System.String");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(553584)]
public void TestAwaitTaskOfT()
{
var text =
@"using System.Threading.Tasks;
class C
{
void M()
{
int x = await [|Foo()|];
}
}";
Test(text, "global::System.Threading.Tasks.Task<System.Int32>");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(553584)]
public void TestAwaitTaskOfTaskOfT()
{
var text =
@"using System.Threading.Tasks;
class C
{
void M()
{
Task<int> x = await [|Foo()|];
}
}";
Test(text, "global::System.Threading.Tasks.Task<global::System.Threading.Tasks.Task<System.Int32>>");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(553584)]
public void TestAwaitTask()
{
var text =
@"using System.Threading.Tasks;
class C
{
void M()
{
await [|Foo()|];
}
}";
Test(text, "global::System.Threading.Tasks.Task");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(617622)]
public void TestLockStatement()
{
var text =
@"class C
{
void M()
{
lock([|Foo()|])
{
}
}
}";
Test(text, "System.Object");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(617622)]
public void TestAwaitExpressionInLockStatement()
{
var text =
@"class C
{
async void M()
{
lock(await [|Foo()|])
{
}
}
}";
Test(text, "global::System.Threading.Tasks.Task<System.Object>");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(827897)]
public void TestReturnFromAsyncTaskOfT()
{
var markup =
@"using System.Threading.Tasks;
class Program
{
async Task<int> M()
{
await Task.Delay(1);
return [|ab|]
}
}";
Test(markup, "System.Int32");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(853840)]
public void TestAttributeArguments1()
{
var markup =
@"[A([|dd|], ee, Y = ff)]
class AAttribute : System.Attribute
{
public int X;
public string Y;
public AAttribute(System.DayOfWeek a, double b)
{
}
}";
Test(markup, "global::System.DayOfWeek");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(853840)]
public void TestAttributeArguments2()
{
var markup =
@"[A(dd, [|ee|], Y = ff)]
class AAttribute : System.Attribute
{
public int X;
public string Y;
public AAttribute(System.DayOfWeek a, double b)
{
}
}";
Test(markup, "System.Double");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(853840)]
public void TestAttributeArguments3()
{
var markup =
@"[A(dd, ee, Y = [|ff|])]
class AAttribute : System.Attribute
{
public int X;
public string Y;
public AAttribute(System.DayOfWeek a, double b)
{
}
}";
Test(markup, "System.String");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(757111)]
public void TestReturnStatementWithinDelegateWithinAMethodCall()
{
var text =
@"using System;
class Program
{
delegate string A(int i);
static void Main(string[] args)
{
B(delegate(int i) { return [|M()|]; });
}
private static void B(A a)
{
}
}";
Test(text, "System.String");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(994388)]
public void TestCatchFilterClause()
{
var text =
@"
try
{ }
catch (Exception) if ([|M()|])
}";
TestInMethod(text, "System.Boolean");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(994388)]
public void TestCatchFilterClause1()
{
var text =
@"
try
{ }
catch (Exception) if ([|M|])
}";
TestInMethod(text, "System.Boolean");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(994388)]
public void TestCatchFilterClause2()
{
var text =
@"
try
{ }
catch (Exception) if ([|M|].N)
}";
TestInMethod(text, "System.Object", testPosition: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(643, "https://github.com/dotnet/roslyn/issues/643")]
public void TestAwaitExpressionWithChainingMethod()
{
var text =
@"using System;
using System.Threading.Tasks;
class C
{
static async void T()
{
bool x = await [|M()|].ConfigureAwait(false);
}
}";
Test(text, "global::System.Threading.Tasks.Task<System.Boolean>");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(643, "https://github.com/dotnet/roslyn/issues/643")]
public void TestAwaitExpressionWithChainingMethod2()
{
var text =
@"using System;
using System.Threading.Tasks;
class C
{
static async void T()
{
bool x = await [|M|].ContinueWith(a => { return true; }).ContinueWith(a => { return false; });
}
}";
Test(text, "global::System.Threading.Tasks.Task<System.Boolean>");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(4233, "https://github.com/dotnet/roslyn/issues/4233")]
public void TestAwaitExpressionWithGenericMethod1()
{
var text =
@"using System.Threading.Tasks;
public class C
{
private async void M()
{
bool merged = await X([|Test()|]);
}
private async Task<T> X<T>(T t) { return t; }
}";
Test(text, "System.Boolean", testPosition: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(4233, "https://github.com/dotnet/roslyn/issues/4233")]
public void TestAwaitExpressionWithGenericMethod2()
{
var text =
@"using System.Threading.Tasks;
public class C
{
private async void M()
{
bool merged = await Task.Run(() => [|Test()|]);;
}
private async Task<T> X<T>(T t) { return t; }
}";
Test(text, "System.Boolean");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(4483, "https://github.com/dotnet/roslyn/issues/4483")]
public void TestNullCoalescingOperator1()
{
var text =
@"class C
{
void M()
{
object z = [|a|]?? null;
}
}";
Test(text, "System.Object");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(4483, "https://github.com/dotnet/roslyn/issues/4483")]
public void TestNullCoalescingOperator2()
{
var text =
@"class C
{
void M()
{
object z = [|a|] ?? b ?? c;
}
}";
Test(text, "System.Object");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(4483, "https://github.com/dotnet/roslyn/issues/4483")]
public void TestNullCoalescingOperator3()
{
var text =
@"class C
{
void M()
{
object z = a ?? [|b|] ?? c;
}
}";
Test(text, "System.Object");
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(5126, "https://github.com/dotnet/roslyn/issues/5126")]
public void TestSelectLambda()
{
var text =
@"using System.Collections.Generic;
using System.Linq;
class C
{
void M(IEnumerable<string> args)
{
args = args.Select(a =>[||])
}
}";
Test(text, "System.Object", testPosition: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)]
[WorkItem(5126, "https://github.com/dotnet/roslyn/issues/5126")]
public void TestSelectLambda2()
{
var text =
@"using System.Collections.Generic;
using System.Linq;
class C
{
void M(IEnumerable<string> args)
{
args = args.Select(a =>[|b|])
}
}";
Test(text, "System.Object", testPosition: false);
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using System.Web.Http;
using System.Web.Http.Description;
using System.Xml.Serialization;
using Newtonsoft.Json;
namespace SailingTripMap.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
using Signum.Entities.Disconnected;
using System.IO;
using Signum.Entities.Basics;
namespace Signum.Engine.Disconnected;
public class ExportManager
{
public ExportManager()
{
this.miUnsafeLock = this.GetType().GetMethod("UnsafeLock", BindingFlags.NonPublic | BindingFlags.Instance)!;
}
class DownloadTable
{
public Type Type;
public Table Table;
public IDisconnectedStrategy Strategy;
public DownloadTable(Type type, Table table, IDisconnectedStrategy strategy)
{
Type = type;
Table = table;
Strategy = strategy;
}
}
public void Initialize()
{
downloadTables = Schema.Current.Tables.Values
.Select(t => new DownloadTable(t.Type, t, DisconnectedLogic.GetStrategy(t.Type)))
.Where(p => p.Strategy.Download != Download.None)
.ToList();
}
List<DownloadTable> downloadTables = null!;
Dictionary<Lite<DisconnectedExportEntity>, RunningExports> runningExports = new Dictionary<Lite<DisconnectedExportEntity>, RunningExports>();
class RunningExports
{
public Task Task;
public CancellationTokenSource CancelationSource;
public RunningExports(Task task, CancellationTokenSource cancelationSource)
{
Task = task;
CancelationSource = cancelationSource;
}
}
public virtual Lite<DisconnectedExportEntity> BeginExportDatabase(DisconnectedMachineEntity machine)
{
Lite<DisconnectedExportEntity> export = new DisconnectedExportEntity
{
Machine = machine.ToLite(),
Copies = downloadTables.Select(t => new DisconnectedExportTableEmbedded
{
Type = t.Type.ToTypeEntity().ToLite()
}).ToMList()
}.Save().ToLite();
var cancelationSource = new CancellationTokenSource();
var user = UserHolder.Current;
var token = cancelationSource.Token;
var task = Task.Factory.StartNew(() =>
{
using (UserHolder.UserSession(user))
{
OnStartExporting(machine);
DisconnectedMachineEntity.Current = machine.ToLite();
try
{
using (token.MeasureTime(l => export.InDB().UnsafeUpdate().Set(s => s.Lock, s => l).Execute()))
{
foreach (var tuple in downloadTables)
{
token.ThrowIfCancellationRequested();
if (tuple.Strategy.Upload == Upload.Subset)
miUnsafeLock.MakeGenericMethod(tuple.Type).Invoke(this, new object[] { machine.ToLite(), tuple.Strategy, export });
}
}
string connectionString;
using (token.MeasureTime(l => export.InDB().UnsafeUpdate().Set(s => s.CreateDatabase, s => l).Execute()))
connectionString = CreateDatabase(machine);
var newDatabase = new SqlServerConnector(connectionString, Schema.Current, ((SqlServerConnector)Connector.Current).Version);
using (token.MeasureTime(l => export.InDB().UnsafeUpdate().Set(s => s.CreateSchema, s => l).Execute()))
using (Connector.Override(newDatabase))
using (ObjectName.OverrideOptions(new ObjectNameOptions { AvoidDatabaseName = true }))
{
Administrator.TotalGeneration();
}
using (token.MeasureTime(l => export.InDB().UnsafeUpdate().Set(s => s.DisableForeignKeys, s => l).Execute()))
using (Connector.Override(newDatabase))
using (ObjectName.OverrideOptions(new ObjectNameOptions { AvoidDatabaseName = true }))
{
foreach (var tuple in downloadTables.Where(t => !t.Type.IsEnumEntity()))
{
token.ThrowIfCancellationRequested();
DisableForeignKeys(tuple.Table);
}
}
var isPostgres = Schema.Current.Settings.IsPostgres;
DatabaseName newDatabaseName = new DatabaseName(null, newDatabase.DatabaseName(), isPostgres);
foreach (var tuple in downloadTables)
{
token.ThrowIfCancellationRequested();
int ms = 0;
using (token.MeasureTime(l => ms = l))
{
tuple.Strategy.Exporter!.Export(tuple.Table, tuple.Strategy, newDatabaseName, machine);
}
export.MListElementsLite(_ => _.Copies).Where(c => c.Element.Type.Is(tuple.Type.ToTypeEntity())).UnsafeUpdateMList()
.Set(mle => mle.Element.CopyTable, mle => ms)
.Execute();
}
using (token.MeasureTime(l => export.InDB().UnsafeUpdate().Set(s =>s.EnableForeignKeys, s=>l).Execute()))
foreach (var tuple in downloadTables.Where(t => !t.Type.IsEnumEntity()))
{
token.ThrowIfCancellationRequested();
EnableForeignKeys(tuple.Table);
}
using (token.MeasureTime(l => export.InDB().UnsafeUpdate().Set(s => s.ReseedIds, s => l).Execute()))
{
var tablesToUpload = Schema.Current.Tables.Values.Where(t => DisconnectedLogic.GetStrategy(t.Type).Upload != Upload.None)
.SelectMany(t => t.TablesMList().Cast<ITable>().And(t)).Where(t => t.PrimaryKey.Identity).ToList();
var maxIdDictionary = tablesToUpload.ToDictionary(t => t,
t => DisconnectedTools.MaxIdInRange(t, machine.SeedMin, machine.SeedMax));
using (Connector.Override(newDatabase))
using (ObjectName.OverrideOptions(new ObjectNameOptions { AvoidDatabaseName = true }))
{
foreach (var table in tablesToUpload)
{
token.ThrowIfCancellationRequested();
long? max = maxIdDictionary.GetOrThrow(table);
DisconnectedTools.SetNextId(table, (max + 1) ?? machine.SeedMin);
}
}
}
CopyExport(export, newDatabase);
machine.InDB().UnsafeUpdate().Set(s => s.State, s => DisconnectedMachineState.Disconnected).Execute();
using (SqlServerConnector.Override(newDatabase))
using (ObjectName.OverrideOptions(new ObjectNameOptions { AvoidDatabaseName = true }))
machine.InDB().UnsafeUpdate().Set(s => s.State, s => DisconnectedMachineState.Disconnected).Execute();
using (token.MeasureTime(l => export.InDB().UnsafeUpdate().Set(s => s.BackupDatabase, s => l).Execute()))
BackupDatabase(machine, export, newDatabase);
using (token.MeasureTime(l => export.InDB().UnsafeUpdate().Set(s => s.DropDatabase, s => l).Execute()))
DropDatabase(newDatabase);
token.ThrowIfCancellationRequested();
export.InDB().UnsafeUpdate()
.Set(s=>s.State, s=>DisconnectedExportState.Completed)
.Set(s=>s.Total, s=>s.CalculateTotal())
.Execute();
}
catch (Exception e)
{
var ex = e.LogException();
export.InDB().UnsafeUpdate()
.Set(s => s.Exception, s => ex.ToLite())
.Set(s => s.State, s => DisconnectedExportState.Error)
.Execute();
OnExportingError(machine, export, e);
}
finally
{
runningExports.Remove(export);
DisconnectedMachineEntity.Current = null;
OnEndExporting();
}
}
});
runningExports.Add(export, new RunningExports(task, cancelationSource));
return export;
}
protected virtual void CopyExport(Lite<DisconnectedExportEntity> export, SqlServerConnector newDatabase)
{
var clone = export.RetrieveAndRemember().Clone();
using (Connector.Override(newDatabase))
using (ObjectName.OverrideOptions(new ObjectNameOptions { AvoidDatabaseName = true }))
{
clone.Save();
}
}
protected virtual void OnStartExporting(DisconnectedMachineEntity machine)
{
}
protected virtual void OnEndExporting()
{
}
protected virtual void OnExportingError(DisconnectedMachineEntity machine, Lite<DisconnectedExportEntity> export, Exception exception)
{
}
readonly MethodInfo miUnsafeLock;
protected virtual int UnsafeLock<T>(Lite<DisconnectedMachineEntity> machine, DisconnectedStrategy<T> strategy, Lite<DisconnectedExportEntity> stats) where T : Entity, new()
{
using (ExecutionMode.Global())
{
var result = Database.Query<T>().Where(strategy.UploadSubset!)
.Where(a => a.Mixin<DisconnectedSubsetMixin>().DisconnectedMachine != null)
.Select(a => "{0} locked in {1}".FormatWith(a.Id, a.Mixin<DisconnectedSubsetMixin>().DisconnectedMachine!.Entity.MachineName))
.ToString("\r\n");
if (result.HasText())
stats.MListElementsLite(_ => _.Copies).Where(a => a.Element.Type.Is(typeof(T).ToTypeEntity())).UnsafeUpdateMList()
.Set(mle => mle.Element.Errors, mle => result)
.Execute();
return Database.Query<T>().Where(strategy.UploadSubset!).UnsafeUpdate()
.Set(a => a.Mixin<DisconnectedSubsetMixin>().DisconnectedMachine, a => machine)
.Set(a => a.Mixin<DisconnectedSubsetMixin>().LastOnlineTicks, a => a.Ticks)
.Execute();
}
}
public virtual void AbortExport(Lite<DisconnectedExportEntity> stat)
{
runningExports.GetOrThrow(stat).CancelationSource.Cancel();
}
protected virtual void DropDatabase(Connector newDatabase)
{
var isPostgres = Schema.Current.Settings.IsPostgres;
DisconnectedTools.DropDatabase(new DatabaseName(null, newDatabase.DatabaseName(), isPostgres));
}
protected virtual string DatabaseFileName(DisconnectedMachineEntity machine)
{
return Path.Combine(DisconnectedLogic.DatabaseFolder, Connector.Current.DatabaseName() + "_Export_" +
DisconnectedTools.CleanMachineName(machine.MachineName) + ".mdf");
}
protected virtual string DatabaseLogFileName(DisconnectedMachineEntity machine)
{
return Path.Combine(DisconnectedLogic.DatabaseFolder, Connector.Current.DatabaseName() + "_Export_" + DisconnectedTools.CleanMachineName(machine.MachineName) + "_Log.ldf");
}
protected virtual DatabaseName DatabaseName(DisconnectedMachineEntity machine)
{
var isPostgres = Schema.Current.Settings.IsPostgres;
return new DatabaseName(null, Connector.Current.DatabaseName() + "_Export_" + DisconnectedTools.CleanMachineName(machine.MachineName), isPostgres);
}
protected virtual string CreateDatabase(DisconnectedMachineEntity machine)
{
DatabaseName databaseName = DatabaseName(machine);
DisconnectedTools.DropIfExists(databaseName);
string fileName = DatabaseFileName(machine);
string logFileName = DatabaseLogFileName(machine);
DisconnectedTools.CreateDatabase(databaseName, fileName, logFileName);
return ((SqlServerConnector)Connector.Current).ConnectionString.Replace(Connector.Current.DatabaseName(), databaseName.Name);
}
protected virtual void EnableForeignKeys(Table table)
{
DisconnectedTools.EnableForeignKeys(table);
foreach (var rt in table.TablesMList())
DisconnectedTools.EnableForeignKeys(rt);
}
protected virtual void DisableForeignKeys(Table table)
{
DisconnectedTools.DisableForeignKeys(table);
foreach (var rt in table.TablesMList())
DisconnectedTools.DisableForeignKeys(rt);
}
protected virtual void BackupDatabase(DisconnectedMachineEntity machine, Lite<DisconnectedExportEntity> export, Connector newDatabase)
{
string backupFileName = Path.Combine(DisconnectedLogic.BackupFolder, BackupFileName(machine, export));
FileTools.CreateParentDirectory(backupFileName);
var isPostgres = Schema.Current.Settings.IsPostgres;
DisconnectedTools.BackupDatabase(new DatabaseName(null, newDatabase.DatabaseName(), isPostgres), backupFileName);
}
public virtual string BackupNetworkFileName(DisconnectedMachineEntity machine, Lite<DisconnectedExportEntity> export)
{
return Path.Combine(DisconnectedLogic.BackupNetworkFolder, BackupFileName(machine, export));
}
protected virtual string BackupFileName(DisconnectedMachineEntity machine, Lite<DisconnectedExportEntity> export)
{
return "{0}.{1}.Export.{2}.bak".FormatWith(Connector.Current.DatabaseName(), machine.MachineName.ToString(), export.Id);
}
}
public interface ICustomExporter
{
void Export(Table table, IDisconnectedStrategy strategy, DatabaseName newDatabaseName, DisconnectedMachineEntity machine);
}
public class BasicExporter<T> : ICustomExporter where T : Entity
{
public virtual void Export(Table table, IDisconnectedStrategy strategy, DatabaseName newDatabaseName, DisconnectedMachineEntity machine)
{
this.CopyTable(table, strategy, newDatabaseName);
}
protected virtual void CopyTable(Table table, IDisconnectedStrategy strategy, DatabaseName newDatabaseName)
{
var filter = strategy.Download == Download.Subset ? GetWhere((DisconnectedStrategy<T>)strategy) : null;
CopyTableBasic(table, newDatabaseName, filter);
foreach (var rt in table.TablesMList())
CopyTableBasic(rt, newDatabaseName, filter == null ? null : (SqlPreCommandSimple)filter.Clone());
}
protected virtual int CopyTableBasic(ITable table, DatabaseName newDatabaseName, SqlPreCommandSimple? filter)
{
ObjectName newTableName = table.Name.OnDatabase(newDatabaseName);
var isPostgres = Schema.Current.Settings.IsPostgres;
string command =
@"INSERT INTO {0} ({2})
SELECT {3}
from {1} as [table]".FormatWith(
newTableName,
table.Name,
table.Columns.Keys.ToString(a => a.SqlEscape(isPostgres), ", "),
table.Columns.Keys.ToString(a => "[table]." + a.SqlEscape(isPostgres), ", "));
if (filter != null)
{
if (table is Table)
{
command += "\r\nWHERE [table].Id in ({0})".FormatWith(filter.Sql);
}
else
{
TableMList rt = (TableMList)table;
command +=
"\r\nJOIN {0} [masterTable] on [table].{1} = [masterTable].Id".FormatWith(rt.BackReference.ReferenceTable.Name, rt.BackReference.Name.SqlEscape(isPostgres)) +
"\r\nWHERE [masterTable].Id in ({0})".FormatWith(filter.Sql);
}
}
string fullCommand = !table.PrimaryKey.Identity ? command :
("SET IDENTITY_INSERT {0} ON\r\n".FormatWith(newTableName) +
command + "\r\n" +
"SET IDENTITY_INSERT {0} OFF\r\n".FormatWith(newTableName));
return Executor.ExecuteNonQuery(fullCommand, filter?.Parameters);
}
protected virtual SqlPreCommandSimple GetWhere(DisconnectedStrategy<T> pair)
{
var query = Database.Query<T>().Where(pair.DownloadSubset!).Select(a => a.Id);
return Administrator.QueryPreCommand(query);
}
}
public class DeleteAndCopyExporter<T> : BasicExporter<T> where T : Entity
{
public override void Export(Table table, IDisconnectedStrategy strategy, DatabaseName newDatabaseName, DisconnectedMachineEntity machine)
{
this.DeleteTable(table, newDatabaseName);
this.CopyTable(table, strategy, newDatabaseName);
}
protected virtual void DeleteTable(Table table, DatabaseName newDatabaseName)
{
DisconnectedTools.DeleteTable(table.Name.OnDatabase(newDatabaseName));
}
}
| |
using System.Linq;
using FluentNHibernate.MappingModel;
using FluentNHibernate.Testing.DomainModel.Mapping;
using NUnit.Framework;
namespace FluentNHibernate.Testing.FluentInterfaceTests
{
[TestFixture]
public class PropertyMutablePropertyModelGenerationTests : BaseModelFixture
{
[Test]
public void AccessShouldSetModelAccessPropertyToValue()
{
Property()
.Mapping(m => m.Access.Field())
.ModelShouldMatch(x => x.Access.ShouldEqual("field"));
}
[Test]
public void ShouldSetModelNamePropertyToPropertyName()
{
Property()
.Mapping(m => {})
.ModelShouldMatch(x => x.Name.ShouldEqual("Name"));
}
[Test]
public void InsertShouldSetModelInsertPropertyToTrue()
{
Property()
.Mapping(m => m.Insert())
.ModelShouldMatch(x => x.Insert.ShouldBeTrue());
}
[Test]
public void NotInsertShouldSetModelInsertPropertyToFalse()
{
Property()
.Mapping(m => m.Not.Insert())
.ModelShouldMatch(x => x.Insert.ShouldBeFalse());
}
[Test]
public void UpdateShouldSetModelUpdatePropertyToTrue()
{
Property()
.Mapping(m => m.Update())
.ModelShouldMatch(x => x.Update.ShouldBeTrue());
}
[Test]
public void NotUpdateShouldSetModelUpdatePropertyToFalse()
{
Property()
.Mapping(m => m.Not.Update())
.ModelShouldMatch(x => x.Update.ShouldBeFalse());
}
[Test]
public void ReadOnlyShouldSetModelInsertPropertyToFalse()
{
Property()
.Mapping(m => m.ReadOnly())
.ModelShouldMatch(x => x.Insert.ShouldBeFalse());
}
[Test]
public void NotReadOnlyShouldSetModelInsertPropertyToTrue()
{
Property()
.Mapping(m => m.Not.ReadOnly())
.ModelShouldMatch(x => x.Insert.ShouldBeTrue());
}
[Test]
public void ReadOnlyShouldSetModelUpdatePropertyToFalse()
{
Property()
.Mapping(m => m.ReadOnly())
.ModelShouldMatch(x => x.Update.ShouldBeFalse());
}
[Test]
public void NotReadOnlyShouldSetModelUpdatePropertyToTrue()
{
Property()
.Mapping(m => m.Not.ReadOnly())
.ModelShouldMatch(x => x.Update.ShouldBeTrue());
}
[Test]
public void FormulaIsShouldSetModelFormulaPropertyToValue()
{
Property()
.Mapping(m => m.Formula("form"))
.ModelShouldMatch(x => x.Formula.ShouldEqual("form"));
}
[Test]
public void OptimisticLockShouldSetModelOptimisticLockPropertyToTrue()
{
Property()
.Mapping(m => m.OptimisticLock())
.ModelShouldMatch(x => x.OptimisticLock.ShouldBeTrue());
}
[Test]
public void NotOptimisticLockShouldSetModelOptimisticLockPropertyToFalse()
{
Property()
.Mapping(m => m.Not.OptimisticLock())
.ModelShouldMatch(x => x.OptimisticLock.ShouldBeFalse());
}
[Test]
public void GeneratedShouldSetModelGeneratedPropertyToValue()
{
Property()
.Mapping(m => m.Generated.Always())
.ModelShouldMatch(x => x.Generated.ShouldEqual("always"));
}
[Test]
public void ShouldSetModelTypePropertyToPropertyType()
{
Property()
.Mapping(m => {})
.ModelShouldMatch(x => x.Type.ShouldEqual(new TypeReference(typeof(string))));
}
[Test]
public void CustomTypeIsShouldSetModelTypePropertyToType()
{
Property()
.Mapping(m => m.CustomType<PropertyTarget>())
.ModelShouldMatch(x => x.Type.ShouldEqual(new TypeReference(typeof(PropertyTarget))));
}
[Test]
public void ShouldSetModelDefaultColumn()
{
Property()
.Mapping(m => { })
.ModelShouldMatch(x => x.Columns.Count().ShouldEqual(1));
}
[Test]
public void ShouldSetModelDefaultColumnBasedOnPropertyName()
{
Property()
.Mapping(m => { })
.ModelShouldMatch(x => x.Columns.First().Name.ShouldEqual("Name"));
}
[Test]
public void ColumnNameShouldOverrideModelDefaultColumn()
{
Property()
.Mapping(m => m.Column("col"))
.ModelShouldMatch(x => x.Columns.First().Name.ShouldEqual("col"));
}
[Test]
public void ColumnNamesShouldAddModelColumnsCollection()
{
Property()
.Mapping(m => m.Columns.Add("one", "two"))
.ModelShouldMatch(x => x.Columns.Count().ShouldEqual(2));
}
[Test]
public void ColumnNamesShouldAddModelColumnsCollectionWithCorrectName()
{
Property()
.Mapping(m => m.Columns.Add("one", "two"))
.ModelShouldMatch(x =>
{
x.Columns.First().Name.ShouldEqual("one");
x.Columns.ElementAt(1).Name.ShouldEqual("two");
});
}
[Test]
public void CustomSqlTypeShouldSetColumn()
{
Property()
.Mapping(m => m.CustomSqlType("sql"))
.ModelShouldMatch(x => x.Columns.First().SqlType.ShouldEqual("sql"));
}
[Test]
public void NullableShouldSetColumnNotNullPropertyToFalse()
{
Property()
.Mapping(m => m.Nullable())
.ModelShouldMatch(x => x.Columns.First().NotNull.ShouldBeFalse());
}
[Test]
public void NotNullableShouldSetColumnNotNullPropertyToTrue()
{
Property()
.Mapping(m => m.Not.Nullable())
.ModelShouldMatch(x => x.Columns.First().NotNull.ShouldBeTrue());
}
[Test]
public void UniqueShouldSetColumnUniquePropertyToTrue()
{
Property()
.Mapping(m => m.Unique())
.ModelShouldMatch(x => x.Columns.First().Unique.ShouldBeTrue());
}
[Test]
public void NotUniqueShouldSetColumnUniquePropertyToFalse()
{
Property()
.Mapping(m => m.Not.Unique())
.ModelShouldMatch(x => x.Columns.First().Unique.ShouldBeFalse());
}
[Test]
public void UniqueKeyShouldSetColumnUniqueKeyPropertyToValue()
{
Property()
.Mapping(m => m.UniqueKey("key"))
.ModelShouldMatch(x => x.Columns.First().UniqueKey.ShouldEqual("key"));
}
[Test]
public void LengthOfShouldSetColumnLengthPropertyToValue()
{
Property()
.Mapping(m => m.Length(100))
.ModelShouldMatch(x => x.Columns.First().Length.ShouldEqual(100));
}
[Test]
public void LazyLoadShouldSetModelLazyPropertyToTrue()
{
Property()
.Mapping(m => m.LazyLoad())
.ModelShouldMatch(x => x.Lazy.ShouldBeTrue());
}
[Test]
public void NotLazyLoadShouldSetModelLazyPropertyToFalse()
{
Property()
.Mapping(m => m.Not.LazyLoad())
.ModelShouldMatch(x => x.Lazy.ShouldBeFalse());
}
[Test]
public void IndexShouldSetModelIndexPropertyToValue()
{
Property()
.Mapping(m => m.Index("index"))
.ModelShouldMatch(x => x.Columns.First().Index.ShouldEqual("index"));
}
[Test]
public void PrecisionShouldSetColumnModelPrecisionPropertyToValue()
{
Property()
.Mapping(m => m.Precision(10))
.ModelShouldMatch(x => x.Columns.First().Precision.ShouldEqual(10));
}
[Test]
public void ScaleShouldSetColumnModelScalePropertyToValue()
{
Property()
.Mapping(m => m.Scale(10))
.ModelShouldMatch(x => x.Columns.First().Scale.ShouldEqual(10));
}
[Test]
public void CheckShouldSetModelCheckPropertyToValue()
{
Property()
.Mapping(m => m.Check("constraint"))
.ModelShouldMatch(x => x.Columns.First().Check.ShouldEqual("constraint"));
}
[Test]
public void DefaultShouldSetModelDefaultPropertyToValue()
{
Property()
.Mapping(m => m.Default("value"))
.ModelShouldMatch(x => x.Columns.First().Default.ShouldEqual("value"));
}
[Test]
public void CanSetAttributesForNonDefaultColumn()
{
//For issue #354 - Can't seem to combine Column and Length
Property()
.Mapping(x => x.Column("foo").Length(42).Not.Nullable())
.ModelShouldMatch(x =>
{
x.Columns.Count().ShouldEqual(1);
x.Columns.First().Name.ShouldEqual("foo");
x.Columns.First().Length.ShouldEqual(42);
x.Columns.First().NotNull.ShouldBeTrue();
});
}
[Test]
public void ShouldBeAbleToOverrideColumnNameAndSpecifyNullabilityTogether()
{
Property()
.Mapping(m => m.Column("custom-column").Not.Nullable())
.ModelShouldMatch(x =>
{
x.Columns.First().Name.ShouldEqual("custom-column");
x.Columns.First().NotNull.ShouldBeTrue();
});
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
extern alias WORKSPACES;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Collections.ObjectModel;
using System.Globalization;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Windows.Threading;
using System.Xml.Linq;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor.UnitTests.Extensions;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Scripting.Hosting;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.VisualBasic;
using Microsoft.VisualStudio.Composition;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Utilities;
using Roslyn.Test.EditorUtilities;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces
{
using RelativePathResolver = WORKSPACES::Microsoft.CodeAnalysis.RelativePathResolver;
public partial class TestWorkspaceFactory
{
/// <summary>
/// This place-holder value is used to set a project's file path to be null. It was explicitly chosen to be
/// convoluted to avoid any accidental usage (e.g., what if I really wanted FilePath to be the string "null"?),
/// obvious to anybody debugging that it is a special value, and invalid as an actual file path.
/// </summary>
public const string NullFilePath = "NullFilePath::{AFA13775-BB7D-4020-9E58-C68CF43D8A68}";
private class TestDocumentationProvider : DocumentationProvider
{
protected override string GetDocumentationForSymbol(string documentationMemberID, CultureInfo preferredCulture, CancellationToken cancellationToken = default(CancellationToken))
{
return string.Format("<member name='{0}'><summary>{0}</summary></member>", documentationMemberID);
}
public override bool Equals(object obj)
{
return ReferenceEquals(this, obj);
}
public override int GetHashCode()
{
return RuntimeHelpers.GetHashCode(this);
}
}
public static TestWorkspace CreateWorkspace(string xmlDefinition, bool completed = true, bool openDocuments = true, ExportProvider exportProvider = null)
{
return CreateWorkspace(XElement.Parse(xmlDefinition), completed, openDocuments, exportProvider);
}
public static TestWorkspace CreateWorkspace(
XElement workspaceElement,
bool completed = true,
bool openDocuments = true,
ExportProvider exportProvider = null,
string workspaceKind = null)
{
if (workspaceElement.Name != WorkspaceElementName)
{
throw new ArgumentException();
}
exportProvider = exportProvider ?? TestExportProvider.ExportProviderWithCSharpAndVisualBasic;
var workspace = new TestWorkspace(exportProvider, workspaceKind);
var projectMap = new Dictionary<string, TestHostProject>();
var documentElementToFilePath = new Dictionary<XElement, string>();
var projectElementToAssemblyName = new Dictionary<XElement, string>();
var filePathToTextBufferMap = new Dictionary<string, ITextBuffer>();
int projectIdentifier = 0;
int documentIdentifier = 0;
foreach (var projectElement in workspaceElement.Elements(ProjectElementName))
{
var project = CreateProject(
workspaceElement,
projectElement,
exportProvider,
workspace,
projectElementToAssemblyName,
documentElementToFilePath,
filePathToTextBufferMap,
ref projectIdentifier,
ref documentIdentifier);
Assert.False(projectMap.ContainsKey(project.AssemblyName));
projectMap.Add(project.AssemblyName, project);
workspace.Projects.Add(project);
}
var documentFilePaths = new HashSet<string>();
foreach (var project in projectMap.Values)
{
foreach (var document in project.Documents)
{
Assert.True(document.IsLinkFile || documentFilePaths.Add(document.FilePath));
}
}
var submissions = CreateSubmissions(workspace, workspaceElement.Elements(SubmissionElementName), exportProvider);
foreach (var submission in submissions)
{
projectMap.Add(submission.AssemblyName, submission);
}
var solution = new TestHostSolution(projectMap.Values.ToArray());
workspace.AddTestSolution(solution);
foreach (var projectElement in workspaceElement.Elements(ProjectElementName))
{
foreach (var projectReference in projectElement.Elements(ProjectReferenceElementName))
{
var fromName = projectElementToAssemblyName[projectElement];
var toName = projectReference.Value;
var fromProject = projectMap[fromName];
var toProject = projectMap[toName];
var aliases = projectReference.Attributes(AliasAttributeName).Select(a => a.Value).ToImmutableArray();
workspace.OnProjectReferenceAdded(fromProject.Id, new ProjectReference(toProject.Id, aliases.Any() ? aliases : default(ImmutableArray<string>)));
}
}
for (int i = 1; i < submissions.Count; i++)
{
if (submissions[i].CompilationOptions == null)
{
continue;
}
for (int j = i - 1; j >= 0; j--)
{
if (submissions[j].CompilationOptions != null)
{
workspace.OnProjectReferenceAdded(submissions[i].Id, new ProjectReference(submissions[j].Id));
break;
}
}
}
foreach (var project in projectMap.Values)
{
foreach (var document in project.Documents)
{
if (openDocuments)
{
workspace.OnDocumentOpened(document.Id, document.GetOpenTextContainer(), isCurrentContext: !document.IsLinkFile);
}
workspace.Documents.Add(document);
}
}
return workspace;
}
private static IList<TestHostProject> CreateSubmissions(
TestWorkspace workspace,
IEnumerable<XElement> submissionElements,
ExportProvider exportProvider)
{
var submissions = new List<TestHostProject>();
var submissionIndex = 0;
foreach (var submissionElement in submissionElements)
{
var submissionName = "Submission" + (submissionIndex++);
var languageName = GetLanguage(workspace, submissionElement);
// The document
var markupCode = submissionElement.NormalizedValue();
string code;
int? cursorPosition;
IDictionary<string, IList<TextSpan>> spans;
MarkupTestFile.GetPositionAndSpans(markupCode, out code, out cursorPosition, out spans);
var languageServices = workspace.Services.GetLanguageServices(languageName);
var contentTypeLanguageService = languageServices.GetService<IContentTypeLanguageService>();
var contentType = contentTypeLanguageService.GetDefaultContentType();
var textBuffer = EditorFactory.CreateBuffer(contentType.TypeName, exportProvider, code);
// The project
var document = new TestHostDocument(exportProvider, languageServices, textBuffer, submissionName, cursorPosition, spans, SourceCodeKind.Script);
var documents = new List<TestHostDocument> { document };
if (languageName == NoCompilationConstants.LanguageName)
{
submissions.Add(
new TestHostProject(
languageServices,
compilationOptions: null,
parseOptions: null,
assemblyName: submissionName,
references: null,
documents: documents,
isSubmission: true));
continue;
}
var syntaxFactory = languageServices.GetService<ISyntaxTreeFactoryService>();
var compilationFactory = languageServices.GetService<ICompilationFactoryService>();
var compilationOptions = compilationFactory.GetDefaultCompilationOptions().WithOutputKind(OutputKind.DynamicallyLinkedLibrary);
var parseOptions = syntaxFactory.GetDefaultParseOptions().WithKind(SourceCodeKind.Script);
var references = CreateCommonReferences(workspace, submissionElement);
var project = new TestHostProject(
languageServices,
compilationOptions,
parseOptions,
submissionName,
references,
documents,
isSubmission: true);
submissions.Add(project);
}
return submissions;
}
private static TestHostProject CreateProject(
XElement workspaceElement,
XElement projectElement,
ExportProvider exportProvider,
TestWorkspace workspace,
Dictionary<XElement, string> projectElementToAssemblyName,
Dictionary<XElement, string> documentElementToFilePath,
Dictionary<string, ITextBuffer> filePathToTextBufferMap,
ref int projectId,
ref int documentId)
{
var language = GetLanguage(workspace, projectElement);
var assemblyName = GetAssemblyName(workspace, projectElement, ref projectId);
projectElementToAssemblyName.Add(projectElement, assemblyName);
string filePath;
if (projectElement.Attribute(FilePathAttributeName) != null)
{
filePath = projectElement.Attribute(FilePathAttributeName).Value;
if (string.Compare(filePath, NullFilePath, StringComparison.Ordinal) == 0)
{
// allow explicit null file path
filePath = null;
}
}
else
{
filePath = assemblyName +
(language == LanguageNames.CSharp ? ".csproj" :
language == LanguageNames.VisualBasic ? ".vbproj" : ("." + language));
}
var contentTypeRegistryService = exportProvider.GetExportedValue<IContentTypeRegistryService>();
var languageServices = workspace.Services.GetLanguageServices(language);
var compilationOptions = CreateCompilationOptions(workspace, projectElement, language);
var parseOptions = GetParseOptions(projectElement, language, languageServices);
var references = CreateReferenceList(workspace, projectElement);
var analyzers = CreateAnalyzerList(workspace, projectElement);
var documents = new List<TestHostDocument>();
var documentElements = projectElement.Elements(DocumentElementName).ToList();
foreach (var documentElement in documentElements)
{
var document = CreateDocument(
workspace,
workspaceElement,
documentElement,
language,
exportProvider,
languageServices,
filePathToTextBufferMap,
ref documentId);
documents.Add(document);
documentElementToFilePath.Add(documentElement, document.FilePath);
}
return new TestHostProject(languageServices, compilationOptions, parseOptions, assemblyName, references, documents, filePath: filePath, analyzerReferences: analyzers);
}
private static ParseOptions GetParseOptions(XElement projectElement, string language, HostLanguageServices languageServices)
{
return language == LanguageNames.CSharp || language == LanguageNames.VisualBasic
? GetParseOptionsWorker(projectElement, language, languageServices)
: null;
}
private static ParseOptions GetParseOptionsWorker(XElement projectElement, string language, HostLanguageServices languageServices)
{
ParseOptions parseOptions;
var preprocessorSymbolsAttribute = projectElement.Attribute(PreprocessorSymbolsAttributeName);
if (preprocessorSymbolsAttribute != null)
{
parseOptions = GetPreProcessorParseOptions(language, preprocessorSymbolsAttribute);
}
else
{
parseOptions = languageServices.GetService<ISyntaxTreeFactoryService>().GetDefaultParseOptions();
}
var languageVersionAttribute = projectElement.Attribute(LanguageVersionAttributeName);
if (languageVersionAttribute != null)
{
parseOptions = GetParseOptionsWithLanguageVersion(language, parseOptions, languageVersionAttribute);
}
var documentationMode = GetDocumentationMode(projectElement);
if (documentationMode != null)
{
parseOptions = parseOptions.WithDocumentationMode(documentationMode.Value);
}
return parseOptions;
}
private static ParseOptions GetPreProcessorParseOptions(string language, XAttribute preprocessorSymbolsAttribute)
{
if (language == LanguageNames.CSharp)
{
return new CSharpParseOptions(preprocessorSymbols: preprocessorSymbolsAttribute.Value.Split(','));
}
else if (language == LanguageNames.VisualBasic)
{
return new VisualBasicParseOptions(preprocessorSymbols: preprocessorSymbolsAttribute.Value
.Split(',').Select(v => KeyValuePair.Create(v.Split('=').ElementAt(0), (object)v.Split('=').ElementAt(1))).ToImmutableArray());
}
else
{
throw new ArgumentException("Unexpected language '{0}' for generating custom parse options.", language);
}
}
private static ParseOptions GetParseOptionsWithLanguageVersion(string language, ParseOptions parseOptions, XAttribute languageVersionAttribute)
{
if (language == LanguageNames.CSharp)
{
var languageVersion = (CodeAnalysis.CSharp.LanguageVersion)Enum.Parse(typeof(CodeAnalysis.CSharp.LanguageVersion), languageVersionAttribute.Value);
parseOptions = ((CSharpParseOptions)parseOptions).WithLanguageVersion(languageVersion);
}
else if (language == LanguageNames.VisualBasic)
{
var languageVersion = (CodeAnalysis.VisualBasic.LanguageVersion)Enum.Parse(typeof(CodeAnalysis.VisualBasic.LanguageVersion), languageVersionAttribute.Value);
parseOptions = ((VisualBasicParseOptions)parseOptions).WithLanguageVersion(languageVersion);
}
return parseOptions;
}
private static DocumentationMode? GetDocumentationMode(XElement projectElement)
{
var documentationModeAttribute = projectElement.Attribute(DocumentationModeAttributeName);
if (documentationModeAttribute != null)
{
return (DocumentationMode)Enum.Parse(typeof(DocumentationMode), documentationModeAttribute.Value);
}
else
{
return null;
}
}
private static string GetAssemblyName(TestWorkspace workspace, XElement projectElement, ref int projectId)
{
var assemblyNameAttribute = projectElement.Attribute(AssemblyNameAttributeName);
if (assemblyNameAttribute != null)
{
return assemblyNameAttribute.Value;
}
var language = GetLanguage(workspace, projectElement);
projectId++;
return language == LanguageNames.CSharp ? "CSharpAssembly" + projectId :
language == LanguageNames.VisualBasic ? "VisualBasicAssembly" + projectId :
language + "Assembly" + projectId;
}
private static string GetLanguage(TestWorkspace workspace, XElement projectElement)
{
string languageName = projectElement.Attribute(LanguageAttributeName).Value;
if (!workspace.Services.SupportedLanguages.Contains(languageName))
{
throw new ArgumentException(string.Format("Language should be one of '{0}' and it is {1}",
string.Join(", ", workspace.Services.SupportedLanguages),
languageName));
}
return languageName;
}
private static CompilationOptions CreateCompilationOptions(
TestWorkspace workspace,
XElement projectElement,
string language)
{
var compilationOptionsElement = projectElement.Element(CompilationOptionsElementName);
return language == LanguageNames.CSharp || language == LanguageNames.VisualBasic
? CreateCompilationOptions(workspace, language, compilationOptionsElement)
: null;
}
private static CompilationOptions CreateCompilationOptions(TestWorkspace workspace, string language, XElement compilationOptionsElement)
{
var rootNamespace = new VisualBasicCompilationOptions(OutputKind.ConsoleApplication).RootNamespace;
var globalImports = new List<GlobalImport>();
var reportDiagnostic = ReportDiagnostic.Default;
if (compilationOptionsElement != null)
{
globalImports = compilationOptionsElement.Elements(GlobalImportElementName)
.Select(x => GlobalImport.Parse(x.Value)).ToList();
var rootNamespaceAttribute = compilationOptionsElement.Attribute(RootNamespaceAttributeName);
if (rootNamespaceAttribute != null)
{
rootNamespace = rootNamespaceAttribute.Value;
}
var reportDiagnosticAttribute = compilationOptionsElement.Attribute(ReportDiagnosticAttributeName);
if (reportDiagnosticAttribute != null)
{
reportDiagnostic = (ReportDiagnostic)Enum.Parse(typeof(ReportDiagnostic), (string)reportDiagnosticAttribute);
}
var outputTypeAttribute = compilationOptionsElement.Attribute(OutputTypeAttributeName);
if (outputTypeAttribute != null
&& outputTypeAttribute.Value == "WindowsRuntimeMetadata")
{
if (rootNamespaceAttribute == null)
{
rootNamespace = new VisualBasicCompilationOptions(OutputKind.WindowsRuntimeMetadata).RootNamespace;
}
return language == LanguageNames.CSharp
? (CompilationOptions)new CSharpCompilationOptions(OutputKind.WindowsRuntimeMetadata)
: new VisualBasicCompilationOptions(OutputKind.WindowsRuntimeMetadata).WithGlobalImports(globalImports).WithRootNamespace(rootNamespace);
}
}
else
{
// Add some common global imports by default for VB
globalImports.Add(GlobalImport.Parse("System"));
globalImports.Add(GlobalImport.Parse("System.Collections.Generic"));
globalImports.Add(GlobalImport.Parse("System.Linq"));
}
// TODO: Allow these to be specified.
var languageServices = workspace.Services.GetLanguageServices(language);
var metadataService = workspace.Services.GetService<IMetadataService>();
var compilationOptions = languageServices.GetService<ICompilationFactoryService>().GetDefaultCompilationOptions();
compilationOptions = compilationOptions.WithOutputKind(OutputKind.DynamicallyLinkedLibrary)
.WithGeneralDiagnosticOption(reportDiagnostic)
.WithSourceReferenceResolver(SourceFileResolver.Default)
.WithXmlReferenceResolver(XmlFileResolver.Default)
.WithMetadataReferenceResolver(new WorkspaceMetadataFileReferenceResolver(metadataService, new RelativePathResolver(ImmutableArray<string>.Empty, null)))
.WithAssemblyIdentityComparer(DesktopAssemblyIdentityComparer.Default);
if (language == LanguageNames.VisualBasic)
{
compilationOptions = ((VisualBasicCompilationOptions)compilationOptions).WithRootNamespace(rootNamespace)
.WithGlobalImports(globalImports);
}
return compilationOptions;
}
private static TestHostDocument CreateDocument(
TestWorkspace workspace,
XElement workspaceElement,
XElement documentElement,
string language,
ExportProvider exportProvider,
HostLanguageServices languageServiceProvider,
Dictionary<string, ITextBuffer> filePathToTextBufferMap,
ref int documentId)
{
string markupCode;
string filePath;
var isLinkFileAttribute = documentElement.Attribute(IsLinkFileAttributeName);
bool isLinkFile = isLinkFileAttribute != null && ((bool?)isLinkFileAttribute).HasValue && ((bool?)isLinkFileAttribute).Value;
if (isLinkFile)
{
// This is a linked file. Use the filePath and markup from the referenced document.
var originalProjectName = documentElement.Attribute(LinkAssemblyNameAttributeName);
var originalDocumentPath = documentElement.Attribute(LinkFilePathAttributeName);
if (originalProjectName == null || originalDocumentPath == null)
{
throw new ArgumentException("Linked file specified without LinkAssemblyName or LinkFilePath.");
}
var originalProjectNameStr = originalProjectName.Value;
var originalDocumentPathStr = originalDocumentPath.Value;
var originalProject = workspaceElement.Elements(ProjectElementName).First(p =>
{
var assemblyName = p.Attribute(AssemblyNameAttributeName);
return assemblyName != null && assemblyName.Value == originalProjectNameStr;
});
if (originalProject == null)
{
throw new ArgumentException("Linked file's LinkAssemblyName '{0}' project not found.", originalProjectNameStr);
}
var originalDocument = originalProject.Elements(DocumentElementName).First(d =>
{
var documentPath = d.Attribute(FilePathAttributeName);
return documentPath != null && documentPath.Value == originalDocumentPathStr;
});
if (originalDocument == null)
{
throw new ArgumentException("Linked file's LinkFilePath '{0}' file not found.", originalDocumentPathStr);
}
markupCode = originalDocument.NormalizedValue();
filePath = GetFilePath(workspace, originalDocument, ref documentId);
}
else
{
markupCode = documentElement.NormalizedValue();
filePath = GetFilePath(workspace, documentElement, ref documentId);
}
var folders = GetFolders(documentElement);
var optionsElement = documentElement.Element(ParseOptionsElementName);
// TODO: Allow these to be specified.
var codeKind = SourceCodeKind.Regular;
if (optionsElement != null)
{
var attr = optionsElement.Attribute(KindAttributeName);
codeKind = attr == null
? SourceCodeKind.Regular
: (SourceCodeKind)Enum.Parse(typeof(SourceCodeKind), attr.Value);
}
var contentTypeLanguageService = languageServiceProvider.GetService<IContentTypeLanguageService>();
var contentType = contentTypeLanguageService.GetDefaultContentType();
string code;
int? cursorPosition;
IDictionary<string, IList<TextSpan>> spans;
MarkupTestFile.GetPositionAndSpans(markupCode, out code, out cursorPosition, out spans);
// For linked files, use the same ITextBuffer for all linked documents
ITextBuffer textBuffer;
if (!filePathToTextBufferMap.TryGetValue(filePath, out textBuffer))
{
textBuffer = EditorFactory.CreateBuffer(contentType.TypeName, exportProvider, code);
filePathToTextBufferMap.Add(filePath, textBuffer);
}
return new TestHostDocument(exportProvider, languageServiceProvider, textBuffer, filePath, cursorPosition, spans, codeKind, folders, isLinkFile);
}
private static string GetFilePath(
TestWorkspace workspace,
XElement documentElement,
ref int documentId)
{
var filePathAttribute = documentElement.Attribute(FilePathAttributeName);
if (filePathAttribute != null)
{
return filePathAttribute.Value;
}
var language = GetLanguage(workspace, documentElement.Ancestors(ProjectElementName).Single());
documentId++;
var name = "Test" + documentId;
return language == LanguageNames.CSharp ? name + ".cs" : name + ".vb";
}
private static IReadOnlyList<string> GetFolders(XElement documentElement)
{
var folderAttribute = documentElement.Attribute(FoldersAttributeName);
if (folderAttribute == null)
{
return null;
}
var folderContainers = folderAttribute.Value.Split(new[] { '\\' }, StringSplitOptions.RemoveEmptyEntries);
return new ReadOnlyCollection<string>(folderContainers.ToList());
}
/// <summary>
/// Takes completely valid code, compiles it, and emits it to a MetadataReference without using
/// the file system
/// </summary>
private static MetadataReference CreateMetadataReferenceFromSource(TestWorkspace workspace, XElement referencedSource)
{
var compilation = CreateCompilation(workspace, referencedSource);
var aliasElement = referencedSource.Attribute("Aliases") != null ? referencedSource.Attribute("Aliases").Value : null;
var aliases = aliasElement != null ? aliasElement.Split(',').Select(s => s.Trim()).ToImmutableArray() : default(ImmutableArray<string>);
bool includeXmlDocComments = false;
var includeXmlDocCommentsAttribute = referencedSource.Attribute(IncludeXmlDocCommentsAttributeName);
if (includeXmlDocCommentsAttribute != null &&
((bool?)includeXmlDocCommentsAttribute).HasValue &&
((bool?)includeXmlDocCommentsAttribute).Value)
{
includeXmlDocComments = true;
}
return MetadataReference.CreateFromImage(compilation.EmitToArray(), new MetadataReferenceProperties(aliases: aliases), includeXmlDocComments ? new DeferredDocumentationProvider(compilation) : null);
}
private static Compilation CreateCompilation(TestWorkspace workspace, XElement referencedSource)
{
string languageName = GetLanguage(workspace, referencedSource);
string assemblyName = "ReferencedAssembly";
var assemblyNameAttribute = referencedSource.Attribute(AssemblyNameAttributeName);
if (assemblyNameAttribute != null)
{
assemblyName = assemblyNameAttribute.Value;
}
var languageServices = workspace.Services.GetLanguageServices(languageName);
var compilationFactory = languageServices.GetService<ICompilationFactoryService>();
var options = compilationFactory.GetDefaultCompilationOptions().WithOutputKind(OutputKind.DynamicallyLinkedLibrary);
var compilation = compilationFactory.CreateCompilation(assemblyName, options);
var documentElements = referencedSource.Elements(DocumentElementName).ToList();
foreach (var documentElement in documentElements)
{
compilation = compilation.AddSyntaxTrees(CreateSyntaxTree(languageName, documentElement.Value));
}
foreach (var reference in CreateReferenceList(workspace, referencedSource))
{
compilation = compilation.AddReferences(reference);
}
return compilation;
}
private static SyntaxTree CreateSyntaxTree(string languageName, string referencedCode)
{
if (LanguageNames.CSharp == languageName)
{
return Microsoft.CodeAnalysis.CSharp.SyntaxFactory.ParseSyntaxTree(referencedCode);
}
else
{
return Microsoft.CodeAnalysis.VisualBasic.SyntaxFactory.ParseSyntaxTree(referencedCode);
}
}
private static IList<MetadataReference> CreateReferenceList(TestWorkspace workspace, XElement element)
{
var references = CreateCommonReferences(workspace, element);
foreach (var reference in element.Elements(MetadataReferenceElementName))
{
references.Add(MetadataReference.CreateFromFile(reference.Value));
}
foreach (var metadataReferenceFromSource in element.Elements(MetadataReferenceFromSourceElementName))
{
references.Add(CreateMetadataReferenceFromSource(workspace, metadataReferenceFromSource));
}
return references;
}
private static IList<AnalyzerReference> CreateAnalyzerList(TestWorkspace workspace, XElement projectElement)
{
var analyzers = new List<AnalyzerReference>();
foreach (var analyzer in projectElement.Elements(AnalyzerElementName))
{
analyzers.Add(
new AnalyzerImageReference(
ImmutableArray<DiagnosticAnalyzer>.Empty,
display: (string)analyzer.Attribute(AnalyzerDisplayAttributeName),
fullPath: (string)analyzer.Attribute(AnalyzerFullPathAttributeName)));
}
return analyzers;
}
private static IList<MetadataReference> CreateCommonReferences(TestWorkspace workspace, XElement element)
{
var references = new List<MetadataReference>();
var net45 = element.Attribute(CommonReferencesNet45AttributeName);
if (net45 != null &&
((bool?)net45).HasValue &&
((bool?)net45).Value)
{
references = new List<MetadataReference> { TestBase.MscorlibRef_v4_0_30316_17626, TestBase.SystemRef_v4_0_30319_17929, TestBase.SystemCoreRef_v4_0_30319_17929 };
if (GetLanguage(workspace, element) == LanguageNames.VisualBasic)
{
references.Add(TestBase.MsvbRef);
references.Add(TestBase.SystemXmlRef);
references.Add(TestBase.SystemXmlLinqRef);
}
}
var commonReferencesAttribute = element.Attribute(CommonReferencesAttributeName);
if (commonReferencesAttribute != null &&
((bool?)commonReferencesAttribute).HasValue &&
((bool?)commonReferencesAttribute).Value)
{
references = new List<MetadataReference> { TestBase.MscorlibRef_v4_0_30316_17626, TestBase.SystemRef_v4_0_30319_17929, TestBase.SystemCoreRef_v4_0_30319_17929 };
if (GetLanguage(workspace, element) == LanguageNames.VisualBasic)
{
references.Add(TestBase.MsvbRef_v4_0_30319_17929);
references.Add(TestBase.SystemXmlRef);
references.Add(TestBase.SystemXmlLinqRef);
}
}
var winRT = element.Attribute(CommonReferencesWinRTAttributeName);
if (winRT != null &&
((bool?)winRT).HasValue &&
((bool?)winRT).Value)
{
references = new List<MetadataReference>(TestBase.WinRtRefs.Length);
references.AddRange(TestBase.WinRtRefs);
if (GetLanguage(workspace, element) == LanguageNames.VisualBasic)
{
references.Add(TestBase.MsvbRef_v4_0_30319_17929);
references.Add(TestBase.SystemXmlRef);
references.Add(TestBase.SystemXmlLinqRef);
}
}
var portable = element.Attribute(CommonReferencesPortableAttributeName);
if (portable != null &&
((bool?)portable).HasValue &&
((bool?)portable).Value)
{
references = new List<MetadataReference>(TestBase.PortableRefsMinimal.Length);
references.AddRange(TestBase.PortableRefsMinimal);
}
var systemRuntimeFacade = element.Attribute(CommonReferenceFacadeSystemRuntimeAttributeName);
if (systemRuntimeFacade != null &&
((bool?)systemRuntimeFacade).HasValue &&
((bool?)systemRuntimeFacade).Value)
{
references.Add(TestBase.SystemRuntimeFacadeRef);
}
return references;
}
}
}
| |
//------------------------------------------------------------------------------
// Symbooglix
//
//
// Copyright 2014-2017 Daniel Liew
//
// This file is licensed under the MIT license.
// See LICENSE.txt for details.
//------------------------------------------------------------------------------
using Microsoft.Boogie;
using NUnit.Framework;
using System;
using Symbooglix;
namespace SymbooglixLibTests
{
[TestFixture()]
public class Assignment : SymbooglixTest
{
[Test()]
public void SimpleConcreteAssignment()
{
p = LoadProgramFrom(@"
procedure main()
{
var x:int;
assert {:symbooglix_bp ""before""} true;
x := 5;
assert {:symbooglix_bp ""after""} true;
}
", "file.bpl");
e = GetExecutor(p, new DFSStateScheduler(), GetSolver());
int count = 0;
e.BreakPointReached += delegate(object sender, Executor.BreakPointEventArgs eventArgs)
{
switch (eventArgs.Name)
{
case "before":
var vAndExpr = e.CurrentState.GetInScopeVariableAndExprByName("x");
Assert.IsInstanceOf<IdentifierExpr>(vAndExpr.Value);
Assert.IsInstanceOf<SymbolicVariable>((vAndExpr.Value as IdentifierExpr).Decl);
break;
case "after":
vAndExpr = e.CurrentState.GetInScopeVariableAndExprByName("x");
Assert.IsInstanceOf<LiteralExpr>(vAndExpr.Value);
var literal = vAndExpr.Value as LiteralExpr;
Assert.IsTrue(literal.isBigNum);
Assert.AreEqual(5, literal.asBigNum.ToInt);
break;
default:
Assert.Fail("unrecognised breakpoint");
break;
}
++count;
};
e.Run(GetMain(p));
Assert.AreEqual(2, count);
}
[Test()]
public void SimpleConcreteAssignmentAndCheckCondition()
{
p = LoadProgramFrom(@"
// Bitvector functions
function {:bvbuiltin ""bvadd""} bv8add(bv8,bv8) returns(bv8);
function {:bvbuiltin ""bvugt""} bv8ugt(bv8,bv8) returns(bool);
procedure main(p1:int, p2:bv8) returns (r:bv8)
{
var a:bv8;
var b:bv8;
a := 1bv8;
b := 2bv8;
assert {:symbooglix_bp ""before""} true;
r := bv8add(a,b);
assert {:symbooglix_bp ""after""} true;
assert bv8ugt(r, 0bv8);
}
", "file.bpl");
e = GetExecutor(p, new DFSStateScheduler(), GetSolver(), /*useConstantFolding*/ false);
int count = 0;
e.BreakPointReached += delegate(object sender, Executor.BreakPointEventArgs eventArgs)
{
switch (eventArgs.Name)
{
case "before":
var vAndExpr = e.CurrentState.GetInScopeVariableAndExprByName("r");
Assert.IsInstanceOf<IdentifierExpr>(vAndExpr.Value);
Assert.IsInstanceOf<SymbolicVariable>((vAndExpr.Value as IdentifierExpr).Decl);
break;
case "after":
vAndExpr = e.CurrentState.GetInScopeVariableAndExprByName("r");
var asBvugt = ExprUtil.AsBVADD(vAndExpr.Value);
Assert.IsNotNull(asBvugt);
Assert.AreEqual("BVADD8(1bv8, 2bv8)", asBvugt.ToString());
break;
default:
Assert.Fail("unrecognised breakpoint");
break;
}
++count;
};
var tc = new TerminationCounter();
tc.Connect(e);
e.Run(GetMain(p));
Assert.AreEqual(2, count);
Assert.AreEqual(1, tc.Sucesses);
Assert.AreEqual(0, tc.NumberOfFailures);
}
[Test()]
public void SimpleSymbolicAssigment()
{
p = LoadProgramFrom(@"
procedure main()
{
var x:int;
assert {:symbooglix_bp ""before""} true;
x := x + x;
assert {:symbooglix_bp ""after""} true;
}
", "file.bpl");
e = GetExecutor(p, new DFSStateScheduler(), GetSolver());
int count = 0;
IdentifierExpr symbolic = null;
e.BreakPointReached += delegate(object sender, Executor.BreakPointEventArgs eventArgs)
{
switch (eventArgs.Name)
{
case "before":
var vAndExpr = e.CurrentState.GetInScopeVariableAndExprByName("x");
Assert.IsInstanceOf<IdentifierExpr>(vAndExpr.Value);
Assert.IsInstanceOf<SymbolicVariable>((vAndExpr.Value as IdentifierExpr).Decl);
symbolic = vAndExpr.Value as IdentifierExpr;
break;
case "after":
Assert.IsNotNull(symbolic);
vAndExpr = e.CurrentState.GetInScopeVariableAndExprByName("x");
Assert.IsInstanceOf<NAryExpr>(vAndExpr.Value);
Assert.IsInstanceOf<BinaryOperator>((vAndExpr.Value as NAryExpr).Fun);
Assert.AreEqual(BinaryOperator.Opcode.Add, (( vAndExpr.Value as NAryExpr).Fun as BinaryOperator).Op);
Assert.AreEqual(symbolic.Name + " + " + symbolic.Name, vAndExpr.Value.ToString());
break;
default:
Assert.Fail("unrecognised breakpoint");
break;
}
++count;
};
e.Run(GetMain(p));
Assert.AreEqual(2, count);
}
[Test()]
public void SimpleMapAssigment()
{
p = LoadProgramFrom(@"
procedure main()
{
var x:[bool]int;
assert {:symbooglix_bp ""before""} true;
x[true] := 8;
assert {:symbooglix_bp ""after""} true;
x[false] := 7;
assert {:symbooglix_bp ""after2""} true;
}
", "file.bpl");
e = GetExecutor(p, new DFSStateScheduler(), GetSolver());
int count = 0;
IdentifierExpr symbolic = null;
e.BreakPointReached += delegate(object sender, Executor.BreakPointEventArgs eventArgs)
{
switch (eventArgs.Name)
{
case "before":
var vAndExpr = e.CurrentState.GetInScopeVariableAndExprByName("x");
Assert.IsInstanceOf<IdentifierExpr>(vAndExpr.Value);
Assert.IsInstanceOf<SymbolicVariable>((vAndExpr.Value as IdentifierExpr).Decl);
symbolic = vAndExpr.Value as IdentifierExpr;
break;
case "after":
Assert.IsNotNull(symbolic);
vAndExpr = e.CurrentState.GetInScopeVariableAndExprByName("x");
Assert.IsInstanceOf<NAryExpr>(vAndExpr.Value);
Assert.IsInstanceOf<MapStore>((vAndExpr.Value as NAryExpr).Fun);
Assert.AreEqual(symbolic.Name + "[true := 8]", vAndExpr.Value.ToString());
break;
case "after2":
Assert.IsNotNull(symbolic);
vAndExpr = e.CurrentState.GetInScopeVariableAndExprByName("x");
Assert.IsInstanceOf<NAryExpr>(vAndExpr.Value);
Assert.IsInstanceOf<MapStore>((vAndExpr.Value as NAryExpr).Fun);
Assert.AreEqual(symbolic.Name + "[true := 8][false := 7]", vAndExpr.Value.ToString());
// Check order on the assign, false key should be outer most
var mapStore = vAndExpr.Value as NAryExpr;
Assert.IsInstanceOf<NAryExpr>(mapStore.Args[0]);
Assert.AreEqual(symbolic.Name + "[true := 8]", mapStore.Args[0].ToString());
Assert.IsInstanceOf<LiteralExpr>(mapStore.Args[1]);
Assert.IsTrue((mapStore.Args[1] as LiteralExpr).IsFalse);
Assert.IsInstanceOf<LiteralExpr>(mapStore.Args[2]);
Assert.IsTrue((mapStore.Args[2] as LiteralExpr).isBigNum);
Assert.AreEqual(7, (mapStore.Args[2] as LiteralExpr).asBigNum.ToInt);
break;
default:
Assert.Fail("unrecognised breakpoint");
break;
}
++count;
};
e.Run(GetMain(p));
Assert.AreEqual(3, count);
}
[Test()]
public void ParallelConcreteAssignment()
{
p = LoadProgramFrom(@"
procedure main()
{
var x:int;
var y:int;
assert {:symbooglix_bp ""before""} true;
x, y := 5, 6;
assert {:symbooglix_bp ""after""} true;
}
", "file.bpl");
e = GetExecutor(p, new DFSStateScheduler(), GetSolver());
int count = 0;
e.BreakPointReached += delegate(object sender, Executor.BreakPointEventArgs eventArgs)
{
switch (eventArgs.Name)
{
case "before":
var vAndExprForx = e.CurrentState.GetInScopeVariableAndExprByName("x");
Assert.IsInstanceOf<IdentifierExpr>(vAndExprForx.Value);
Assert.IsInstanceOf<SymbolicVariable>((vAndExprForx.Value as IdentifierExpr).Decl);
var vAndExprFory = e.CurrentState.GetInScopeVariableAndExprByName("y");
Assert.IsInstanceOf<IdentifierExpr>(vAndExprFory.Value);
Assert.IsInstanceOf<SymbolicVariable>((vAndExprFory.Value as IdentifierExpr).Decl);
break;
case "after":
vAndExprForx = e.CurrentState.GetInScopeVariableAndExprByName("x");
Assert.IsInstanceOf<LiteralExpr>(vAndExprForx.Value);
var literal = vAndExprForx.Value as LiteralExpr;
Assert.IsTrue(literal.isBigNum);
Assert.AreEqual(5, literal.asBigNum.ToInt);
vAndExprFory = e.CurrentState.GetInScopeVariableAndExprByName("y");
Assert.IsInstanceOf<LiteralExpr>(vAndExprFory.Value);
literal = vAndExprFory.Value as LiteralExpr;
Assert.IsTrue(literal.isBigNum);
Assert.AreEqual(6, literal.asBigNum.ToInt);
break;
default:
Assert.Fail("unrecognised breakpoint");
break;
}
++count;
};
e.Run(GetMain(p));
Assert.AreEqual(2, count);
}
[Test()]
public void ParallelSymbolicAssignment()
{
p = LoadProgramFrom(@"
procedure main()
{
var x:int;
var y:int;
assert {:symbooglix_bp ""before""} true;
x, y := y, x;
assert {:symbooglix_bp ""after""} true;
}
", "file.bpl");
e = GetExecutor(p, new DFSStateScheduler(), GetSolver());
int count = 0;
IdentifierExpr symbolicForx = null;
IdentifierExpr symbolicFory = null;
e.BreakPointReached += delegate(object sender, Executor.BreakPointEventArgs eventArgs)
{
switch (eventArgs.Name)
{
case "before":
{
var vAndExprForx = e.CurrentState.GetInScopeVariableAndExprByName("x");
Assert.IsInstanceOf<IdentifierExpr>(vAndExprForx.Value);
Assert.IsInstanceOf<SymbolicVariable>((vAndExprForx.Value as IdentifierExpr).Decl);
symbolicForx = vAndExprForx.Value as IdentifierExpr;
var vAndExprFory = e.CurrentState.GetInScopeVariableAndExprByName("y");
Assert.IsInstanceOf<IdentifierExpr>(vAndExprFory.Value);
Assert.IsInstanceOf<SymbolicVariable>((vAndExprFory.Value as IdentifierExpr).Decl);
symbolicFory = vAndExprFory.Value as IdentifierExpr;
}
break;
case "after":
{
Assert.IsNotNull(symbolicForx);
Assert.IsNotNull(symbolicFory);
// Check that swapped happened
var vAndExprForNewx = e.CurrentState.GetInScopeVariableAndExprByName("x");
Assert.AreSame(symbolicFory, vAndExprForNewx.Value);
var vAndExprForNewy = e.CurrentState.GetInScopeVariableAndExprByName("y");
Assert.AreSame(symbolicForx, vAndExprForNewy.Value);
}
break;
default:
Assert.Fail("unrecognised breakpoint");
break;
}
++count;
};
e.Run(GetMain(p));
Assert.AreEqual(2, count);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Runtime.Caching.Resources;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
// Every member of this class is thread-safe.
//
// Derived classes begin monitoring during construction, so that a user can know if the
// dependency changed any time after construction. For example, suppose we have a
// FileChangeMonitor class that derives from ChangeMonitor. A user might create an instance
// of FileChangeMonitor for an XML file, and then read the file to populate an object representation.
// The user would then cache the object with the FileChangeMonitor. The user could optionally check the
// HasChanged property of the FileChangeMonitor, to see if the XML file changed while the object
// was being populated, and if it had changed, they could call Dispose and start over, without
// inserting the item into the cache. However, in a multi-threaded environment, for cleaner, easier
// to maintain code, it's usually appropriate to just insert without checking HasChanged, since the
// cache implementer will handle this for you, and the next thread to attempt to get the object
// will recreate and insert it.
//
// The following contract must be followed by derived classes, cache implementers, and users of the
// derived class:
//
// 1. The constructor of a derived class must set UniqueId, begin monitoring for dependency
// changes, and call InitializationComplete before returning. If a dependency changes
// before initialization is complete, for example, if a dependent cache key is not found
// in the cache, the constructor must invoke OnChanged. The constructor can only call
// Dispose after InitializationComplete is called, because Dispose will throw
// InvalidOperationException if initialization is not complete.
// 2. Once constructed, the user must either insert the ChangeMonitor into an ObjectCache, or
// if they're not going to use it, they must call Dispose.
// 3. Once inserted into an ObjectCache, the ObjectCache implementation must ensure that the
// ChangeMonitor is eventually disposed. Even if the insert is invalid, and results in an
// exception being thrown, the ObjectCache implementation must call Dispose. If this we're not
// a requirement, users of the ChangeMonitor would need exception handling around each insert
// into the cache that carefully ensures the dependency is disposed. While this would work, we
// think it is better to put this burden on the ObjectCache implementer, since users are far more
// numerous than cache implementers.
// 4. After the ChangeMonitor is inserted into a cache, the ObjectCache implementer must call
// NotifyOnChanged, passing in an OnChangedCallback. NotifyOnChanged can only be called once,
// and will throw InvalidOperationException on subsequent calls. If the dependency has already
// changed, the OnChangedCallback will be called when NotifyOnChanged is called. Otherwise, the
// OnChangedCallback will be called exactly once, when OnChanged is invoked or when Dispose
// is invoked, which ever happens first.
// 5. The OnChangedCallback provided by the cache implementer should remove the cache entry, and specify
// a reason of CacheEntryRemovedReason.DependencyChanged. Care should be taken to remove the specific
// entry having this dependency, and not it's replacement, which will have the same key.
// 6. In general, it is okay for OnChanged to be called at any time. If OnChanged is called before
// NotifyOnChanged is called, the "state" from the original call to OnChanged will be saved, and the
// callback to NotifyOnChange will be called immediately when NotifyOnChanged is invoked.
// 7. A derived class must implement Dispose(bool disposing) to release all managed and unmanaged
// resources when "disposing" is true. Dispose(true) is only called once, when the instance is
// disposed. The derived class must not call Dispose(true) directly--it should only be called by
// the ChangeMonitor class, when disposed. Although a derived class could implement a finalizer and
// invoke Dispose(false), this is generally not necessary. Dependency monitoring is typically performed
// by a service that maintains a reference to the ChangeMonitor, preventing it from being garbage collected,
// and making finalizers useless. To help prevent leaks, when a dependency changes, OnChanged disposes
// the ChangeMonitor, unless initialization has not yet completed.
// 8. Dispose() must be called, and is designed to be called, in one of the following three ways:
// - The user must call Dispose() if they decide not to insert the ChangeMonitor into a cache. Otherwise,
// the ChangeMonitor will continue monitoring for changes and be unavailable for garbage collection.
// - The cache implementor is responsible for calling Dispose() once an attempt is made to insert it.
// Even if the insert throws, the cache implementor must dispose the dependency.
// Even if the entry is removed, the cache implementor must dispose the dependency.
// - The OnChanged method will automatically call Dispose if initialization is complete. Otherwise, when
// the derived class' constructor calls InitializationComplete, the instance will be automatically disposed.
//
// Before inserted into the cache, the user must ensure the dependency is disposed. Once inserted into the
// cache, the cache implementer must ensure that Dispose is called, even if the insert fails. After being inserted
// into a cache, the user should not dispose the dependency. When Dispose is called, it is treated as if the dependency
// changed, and OnChanged is automatically invoked.
// 9. HasChanged will be true after OnChanged is called by the derived class, regardless of whether an OnChangedCallback has been set
// by a call to NotifyOnChanged.
namespace System.Runtime.Caching
{
public abstract class ChangeMonitor : IDisposable
{
private const int INITIALIZED = 0x01; // initialization complete
private const int CHANGED = 0x02; // dependency changed
private const int INVOKED = 0x04; // OnChangedCallback has been invoked
private const int DISPOSED = 0x08; // Dispose(true) called, or about to be called
private readonly static object s_NOT_SET = new object();
private SafeBitVector32 _flags;
private OnChangedCallback _onChangedCallback;
private Object _onChangedState = s_NOT_SET;
// The helper routines (OnChangedHelper and DisposeHelper) are used to prevent
// an infinite loop, where Dispose calls OnChanged and OnChanged calls Dispose.
[SuppressMessage("Microsoft.Performance", "CA1816:DisposeMethodsShouldCallSuppressFinalize", Justification = "Grandfathered suppression from original caching code checkin")]
private void DisposeHelper()
{
// if not initialized, return without doing anything.
if (_flags[INITIALIZED])
{
if (_flags.ChangeValue(DISPOSED, true))
{
Dispose(true);
GC.SuppressFinalize(this);
}
}
}
// The helper routines (OnChangedHelper and DisposeHelper) are used to prevent
// an infinite loop, where Dispose calls OnChanged and OnChanged calls Dispose.
private void OnChangedHelper(Object state)
{
_flags[CHANGED] = true;
// the callback is only invoked once, after NotifyOnChanged is called, so
// remember "state" on the first call and use it when invoking the callback
Interlocked.CompareExchange(ref _onChangedState, state, s_NOT_SET);
OnChangedCallback onChangedCallback = _onChangedCallback;
if (onChangedCallback != null)
{
// only invoke the callback once
if (_flags.ChangeValue(INVOKED, true))
{
onChangedCallback(_onChangedState);
}
}
}
//
// protected members
//
// Derived classes must implement this. When "disposing" is true,
// all managed and unmanaged resources are disposed and any references to this
// object are released so that the ChangeMonitor can be garbage collected.
// It is guaranteed that ChangeMonitor.Dispose() will only invoke
// Dispose(bool disposing) once.
protected abstract void Dispose(bool disposing);
// Derived classes must call InitializationComplete
protected void InitializationComplete()
{
_flags[INITIALIZED] = true;
// If the dependency has already changed, or someone tried to dispose us, then call Dispose now.
Dbg.Assert(_flags[INITIALIZED], "It is critical that INITIALIZED is set before CHANGED is checked below");
if (_flags[CHANGED])
{
Dispose();
}
}
// Derived classes call OnChanged when the dependency changes. Optionally,
// they may pass state which will be passed to the OnChangedCallback. The
// OnChangedCallback is only invoked once, and only after NotifyOnChanged is
// called by the cache implementer. OnChanged is also invoked when the instance
// is disposed, but only has an affect if the callback has not already been invoked.
protected void OnChanged(Object state)
{
OnChangedHelper(state);
// OnChanged will also invoke Dispose, but only after initialization is complete
Dbg.Assert(_flags[CHANGED], "It is critical that CHANGED is set before INITIALIZED is checked below.");
if (_flags[INITIALIZED])
{
DisposeHelper();
}
}
//
// public members
//
// set to true when the dependency changes, specifically, when OnChanged is called.
public bool HasChanged { get { return _flags[CHANGED]; } }
// set to true when this instance is disposed, specifically, after
// Dispose(bool disposing) is called by Dispose().
public bool IsDisposed { get { return _flags[DISPOSED]; } }
// a unique ID representing this ChangeMonitor, typically consisting of
// the dependency names and last-modified times.
public abstract string UniqueId { get; }
// Dispose must be called to release the ChangeMonitor. In order to
// prevent derived classes from overriding Dispose, it is not an explicit
// interface implementation.
//
// Before cache insertion, if the user decides not to do a cache insert, they
// must call this to dispose the dependency; otherwise, the ChangeMonitor will
// be referenced and unable to be garbage collected until the dependency changes.
//
// After cache insertion, the cache implementer must call this when the cache entry
// is removed, for whatever reason. Even if an exception is thrown during insert.
//
// After cache insertion, the user should not call Dispose. However, since there's
// no way to prevent this, doing so will invoke the OnChanged event handler, if it
// hasn't already been invoked, and the cache entry will be notified as if the
// dependency has changed.
//
// Dispose() will only invoke the Dispose(bool disposing) method of derived classes
// once, the first time it is called. Subsequent calls to Dispose() perform no
// operation. After Dispose is called, the IsDisposed property will be true.
[SuppressMessage("Microsoft.Performance", "CA1816:DisposeMethodsShouldCallSuppressFinalize", Justification = "Grandfathered suppression from original caching code checkin")]
public void Dispose()
{
OnChangedHelper(null);
// If not initialized, throw, so the derived class understands that it must call InitializeComplete before Dispose.
Dbg.Assert(_flags[CHANGED], "It is critical that CHANGED is set before INITIALIZED is checked below.");
if (!_flags[INITIALIZED])
{
throw new InvalidOperationException(SR.Init_not_complete);
}
DisposeHelper();
}
// Cache implementers must call this to be notified of any dependency changes.
// NotifyOnChanged can only be invoked once, and will throw InvalidOperationException
// on subsequent calls. The OnChangedCallback is guaranteed to be called exactly once.
// It will be called when the dependency changes, or if it has already changed, it will
// be called immediately (on the same thread??).
public void NotifyOnChanged(OnChangedCallback onChangedCallback)
{
if (onChangedCallback == null)
{
throw new ArgumentNullException("onChangedCallback");
}
if (Interlocked.CompareExchange(ref _onChangedCallback, onChangedCallback, null) != null)
{
throw new InvalidOperationException(SR.Method_already_invoked);
}
// if it already changed, raise the event now.
if (_flags[CHANGED])
{
OnChanged(null);
}
}
}
}
| |
// WARNING
//
// This file has been generated automatically by Xamarin Studio to store outlets and
// actions made in the UI designer. If it is removed, they will be lost.
// Manual changes to this file may not be handled correctly.
//
using MonoMac.Foundation;
using System.CodeDom.Compiler;
namespace Outlander.Mac.Beta
{
[Register ("MainWindowController")]
partial class MainWindowController
{
[Outlet]
MonoMac.AppKit.NSTextView ArrivalsTextView { get; set; }
[Outlet]
MonoMac.AppKit.NSTextField CharacterTextField { get; set; }
[Outlet]
MonoMac.AppKit.NSTextField CommandTextField { get; set; }
[Outlet]
Outlander.Mac.Beta.VitalsBar ConcentrationLabel { get; set; }
[Outlet]
MonoMac.AppKit.NSTextView DeathsTextView { get; set; }
[Outlet]
MonoMac.AppKit.NSTextView ExpTextView { get; set; }
[Outlet]
MonoMac.AppKit.NSTextField GameTextField { get; set; }
[Outlet]
MonoMac.AppKit.NSImageView GroupedImage { get; set; }
[Outlet]
MonoMac.AppKit.NSImageView HealthImage { get; set; }
[Outlet]
Outlander.Mac.Beta.VitalsBar HealthLabel { get; set; }
[Outlet]
MonoMac.AppKit.NSImageView HiddenImage { get; set; }
[Outlet]
MonoMac.AppKit.NSImageView InvisibleImage { get; set; }
[Outlet]
MonoMac.AppKit.NSTextField LeftHandLabel { get; set; }
[Outlet]
MonoMac.AppKit.NSButton LoginButton { get; set; }
[Outlet]
MonoMac.AppKit.NSScrollView MainScrollView { get; set; }
[Outlet]
MonoMac.AppKit.NSTextView MainTextView { get; set; }
[Outlet]
Outlander.Mac.Beta.VitalsBar ManaLabel { get; set; }
[Outlet]
MonoMac.AppKit.NSSecureTextField PasswordTextField { get; set; }
[Outlet]
MonoMac.AppKit.NSTextField RightHandLabel { get; set; }
[Outlet]
MonoMac.AppKit.NSTextView RoomTextView { get; set; }
[Outlet]
MonoMac.AppKit.NSTextField RoundtimeLabel { get; set; }
[Outlet]
Outlander.Mac.Beta.VitalsBar RTLabel { get; set; }
[Outlet]
MonoMac.AppKit.NSTextField SpellLabel { get; set; }
[Outlet]
Outlander.Mac.Beta.VitalsBar SpiritLabel { get; set; }
[Outlet]
Outlander.Mac.Beta.VitalsBar StaminaLabel { get; set; }
[Outlet]
MonoMac.AppKit.NSImageView StandingImage { get; set; }
[Outlet]
MonoMac.AppKit.NSButton SubmitButton { get; set; }
[Outlet]
MonoMac.AppKit.NSTextView ThoughtsTextView { get; set; }
[Outlet]
MonoMac.AppKit.NSTextField UsernameTextField { get; set; }
[Outlet]
MonoMac.AppKit.NSImageView WebbedImage { get; set; }
void ReleaseDesignerOutlets ()
{
if (ArrivalsTextView != null) {
ArrivalsTextView.Dispose ();
ArrivalsTextView = null;
}
if (CharacterTextField != null) {
CharacterTextField.Dispose ();
CharacterTextField = null;
}
if (CommandTextField != null) {
CommandTextField.Dispose ();
CommandTextField = null;
}
if (ConcentrationLabel != null) {
ConcentrationLabel.Dispose ();
ConcentrationLabel = null;
}
if (ExpTextView != null) {
ExpTextView.Dispose ();
ExpTextView = null;
}
if (GameTextField != null) {
GameTextField.Dispose ();
GameTextField = null;
}
if (GroupedImage != null) {
GroupedImage.Dispose ();
GroupedImage = null;
}
if (HealthImage != null) {
HealthImage.Dispose ();
HealthImage = null;
}
if (HealthLabel != null) {
HealthLabel.Dispose ();
HealthLabel = null;
}
if (HiddenImage != null) {
HiddenImage.Dispose ();
HiddenImage = null;
}
if (InvisibleImage != null) {
InvisibleImage.Dispose ();
InvisibleImage = null;
}
if (LeftHandLabel != null) {
LeftHandLabel.Dispose ();
LeftHandLabel = null;
}
if (LoginButton != null) {
LoginButton.Dispose ();
LoginButton = null;
}
if (MainScrollView != null) {
MainScrollView.Dispose ();
MainScrollView = null;
}
if (MainTextView != null) {
MainTextView.Dispose ();
MainTextView = null;
}
if (ManaLabel != null) {
ManaLabel.Dispose ();
ManaLabel = null;
}
if (PasswordTextField != null) {
PasswordTextField.Dispose ();
PasswordTextField = null;
}
if (RightHandLabel != null) {
RightHandLabel.Dispose ();
RightHandLabel = null;
}
if (RoomTextView != null) {
RoomTextView.Dispose ();
RoomTextView = null;
}
if (RoundtimeLabel != null) {
RoundtimeLabel.Dispose ();
RoundtimeLabel = null;
}
if (RTLabel != null) {
RTLabel.Dispose ();
RTLabel = null;
}
if (SpellLabel != null) {
SpellLabel.Dispose ();
SpellLabel = null;
}
if (SpiritLabel != null) {
SpiritLabel.Dispose ();
SpiritLabel = null;
}
if (StaminaLabel != null) {
StaminaLabel.Dispose ();
StaminaLabel = null;
}
if (StandingImage != null) {
StandingImage.Dispose ();
StandingImage = null;
}
if (SubmitButton != null) {
SubmitButton.Dispose ();
SubmitButton = null;
}
if (UsernameTextField != null) {
UsernameTextField.Dispose ();
UsernameTextField = null;
}
if (WebbedImage != null) {
WebbedImage.Dispose ();
WebbedImage = null;
}
if (ThoughtsTextView != null) {
ThoughtsTextView.Dispose ();
ThoughtsTextView = null;
}
if (DeathsTextView != null) {
DeathsTextView.Dispose ();
DeathsTextView = null;
}
}
}
[Register ("MainWindow")]
partial class MainWindow
{
void ReleaseDesignerOutlets ()
{
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace System.Security.Cryptography {
public sealed partial class CngAlgorithm : System.IEquatable<System.Security.Cryptography.CngAlgorithm> {
public CngAlgorithm(string algorithm) { throw new NotImplementedException(); }
public string Algorithm { get { return default(string); } }
public static System.Security.Cryptography.CngAlgorithm ECDiffieHellmanP256 { get { return default(System.Security.Cryptography.CngAlgorithm); } }
public static System.Security.Cryptography.CngAlgorithm ECDiffieHellmanP384 { get { return default(System.Security.Cryptography.CngAlgorithm); } }
public static System.Security.Cryptography.CngAlgorithm ECDiffieHellmanP521 { get { return default(System.Security.Cryptography.CngAlgorithm); } }
public static System.Security.Cryptography.CngAlgorithm ECDsaP256 { get { return default(System.Security.Cryptography.CngAlgorithm); } }
public static System.Security.Cryptography.CngAlgorithm ECDsaP384 { get { return default(System.Security.Cryptography.CngAlgorithm); } }
public static System.Security.Cryptography.CngAlgorithm ECDsaP521 { get { return default(System.Security.Cryptography.CngAlgorithm); } }
public static System.Security.Cryptography.CngAlgorithm MD5 { get { return default(System.Security.Cryptography.CngAlgorithm); } }
public static System.Security.Cryptography.CngAlgorithm Rsa { get { return default(System.Security.Cryptography.CngAlgorithm); } }
public static System.Security.Cryptography.CngAlgorithm Sha1 { get { return default(System.Security.Cryptography.CngAlgorithm); } }
public static System.Security.Cryptography.CngAlgorithm Sha256 { get { return default(System.Security.Cryptography.CngAlgorithm); } }
public static System.Security.Cryptography.CngAlgorithm Sha384 { get { return default(System.Security.Cryptography.CngAlgorithm); } }
public static System.Security.Cryptography.CngAlgorithm Sha512 { get { return default(System.Security.Cryptography.CngAlgorithm); } }
public override bool Equals(object obj) { return default(bool); }
public bool Equals(System.Security.Cryptography.CngAlgorithm other) { return default(bool); }
public override int GetHashCode() { return default(int); }
public static bool operator ==(System.Security.Cryptography.CngAlgorithm left, System.Security.Cryptography.CngAlgorithm right) { return default(bool); }
public static bool operator !=(System.Security.Cryptography.CngAlgorithm left, System.Security.Cryptography.CngAlgorithm right) { return default(bool); }
public override string ToString() { return default(string); }
}
public sealed partial class CngAlgorithmGroup : System.IEquatable<System.Security.Cryptography.CngAlgorithmGroup> {
public CngAlgorithmGroup(string algorithmGroup) { throw new NotImplementedException(); }
public string AlgorithmGroup { get { return default(string); } }
public static System.Security.Cryptography.CngAlgorithmGroup DiffieHellman { get { return default(System.Security.Cryptography.CngAlgorithmGroup); } }
public static System.Security.Cryptography.CngAlgorithmGroup Dsa { get { return default(System.Security.Cryptography.CngAlgorithmGroup); } }
public static System.Security.Cryptography.CngAlgorithmGroup ECDiffieHellman { get { return default(System.Security.Cryptography.CngAlgorithmGroup); } }
public static System.Security.Cryptography.CngAlgorithmGroup ECDsa { get { return default(System.Security.Cryptography.CngAlgorithmGroup); } }
public static System.Security.Cryptography.CngAlgorithmGroup Rsa { get { return default(System.Security.Cryptography.CngAlgorithmGroup); } }
public override bool Equals(object obj) { return default(bool); }
public bool Equals(System.Security.Cryptography.CngAlgorithmGroup other) { return default(bool); }
public override int GetHashCode() { return default(int); }
public static bool operator ==(System.Security.Cryptography.CngAlgorithmGroup left, System.Security.Cryptography.CngAlgorithmGroup right) { return default(bool); }
public static bool operator !=(System.Security.Cryptography.CngAlgorithmGroup left, System.Security.Cryptography.CngAlgorithmGroup right) { return default(bool); }
public override string ToString() { return default(string); }
}
[System.FlagsAttribute]
public enum CngExportPolicies {
AllowArchiving = 4,
AllowExport = 1,
AllowPlaintextArchiving = 8,
AllowPlaintextExport = 2,
None = 0,
}
public sealed partial class CngKey : System.IDisposable {
internal CngKey() { throw new NotImplementedException(); }
public System.Security.Cryptography.CngAlgorithm Algorithm { get { return default(System.Security.Cryptography.CngAlgorithm); } }
public System.Security.Cryptography.CngAlgorithmGroup AlgorithmGroup { get { return default(System.Security.Cryptography.CngAlgorithmGroup); } }
public System.Security.Cryptography.CngExportPolicies ExportPolicy { get { return default(System.Security.Cryptography.CngExportPolicies); } }
public Microsoft.Win32.SafeHandles.SafeNCryptKeyHandle Handle { get { return default(Microsoft.Win32.SafeHandles.SafeNCryptKeyHandle); } }
public bool IsEphemeral { get { return default(bool); } }
public bool IsMachineKey { get { return default(bool); } }
public string KeyName { get { return default(string); } }
public int KeySize { get { return default(int); } }
public System.Security.Cryptography.CngKeyUsages KeyUsage { get { return default(System.Security.Cryptography.CngKeyUsages); } }
public System.IntPtr ParentWindowHandle { get { return default(System.IntPtr); } set { } }
public System.Security.Cryptography.CngProvider Provider { get { return default(System.Security.Cryptography.CngProvider); } }
public Microsoft.Win32.SafeHandles.SafeNCryptProviderHandle ProviderHandle { get { return default(Microsoft.Win32.SafeHandles.SafeNCryptProviderHandle); } }
public System.Security.Cryptography.CngUIPolicy UIPolicy { get { return default(System.Security.Cryptography.CngUIPolicy); } }
public string UniqueName { get { return default(string); } }
public static System.Security.Cryptography.CngKey Create(System.Security.Cryptography.CngAlgorithm algorithm) { return default(System.Security.Cryptography.CngKey); }
public static System.Security.Cryptography.CngKey Create(System.Security.Cryptography.CngAlgorithm algorithm, string keyName) { return default(System.Security.Cryptography.CngKey); }
public static System.Security.Cryptography.CngKey Create(System.Security.Cryptography.CngAlgorithm algorithm, string keyName, System.Security.Cryptography.CngKeyCreationParameters creationParameters) { return default(System.Security.Cryptography.CngKey); }
public void Delete() { }
public void Dispose() { }
public static bool Exists(string keyName) { return default(bool); }
public static bool Exists(string keyName, System.Security.Cryptography.CngProvider provider) { return default(bool); }
public static bool Exists(string keyName, System.Security.Cryptography.CngProvider provider, System.Security.Cryptography.CngKeyOpenOptions options) { return default(bool); }
public byte[] Export(System.Security.Cryptography.CngKeyBlobFormat format) { return default(byte[]); }
public System.Security.Cryptography.CngProperty GetProperty(string name, System.Security.Cryptography.CngPropertyOptions options) { return default(System.Security.Cryptography.CngProperty); }
public bool HasProperty(string name, System.Security.Cryptography.CngPropertyOptions options) { return default(bool); }
public static System.Security.Cryptography.CngKey Import(byte[] keyBlob, System.Security.Cryptography.CngKeyBlobFormat format) { return default(System.Security.Cryptography.CngKey); }
public static System.Security.Cryptography.CngKey Import(byte[] keyBlob, System.Security.Cryptography.CngKeyBlobFormat format, System.Security.Cryptography.CngProvider provider) { return default(System.Security.Cryptography.CngKey); }
public static System.Security.Cryptography.CngKey Open(Microsoft.Win32.SafeHandles.SafeNCryptKeyHandle keyHandle, System.Security.Cryptography.CngKeyHandleOpenOptions keyHandleOpenOptions) { return default(System.Security.Cryptography.CngKey); }
public static System.Security.Cryptography.CngKey Open(string keyName) { return default(System.Security.Cryptography.CngKey); }
public static System.Security.Cryptography.CngKey Open(string keyName, System.Security.Cryptography.CngProvider provider) { return default(System.Security.Cryptography.CngKey); }
public static System.Security.Cryptography.CngKey Open(string keyName, System.Security.Cryptography.CngProvider provider, System.Security.Cryptography.CngKeyOpenOptions openOptions) { return default(System.Security.Cryptography.CngKey); }
public void SetProperty(System.Security.Cryptography.CngProperty property) { }
}
public sealed partial class CngKeyBlobFormat : System.IEquatable<System.Security.Cryptography.CngKeyBlobFormat> {
public CngKeyBlobFormat(string format) { throw new NotImplementedException(); }
public static System.Security.Cryptography.CngKeyBlobFormat EccPrivateBlob { get { return default(System.Security.Cryptography.CngKeyBlobFormat); } }
public static System.Security.Cryptography.CngKeyBlobFormat EccPublicBlob { get { return default(System.Security.Cryptography.CngKeyBlobFormat); } }
public string Format { get { return default(string); } }
public static System.Security.Cryptography.CngKeyBlobFormat GenericPrivateBlob { get { return default(System.Security.Cryptography.CngKeyBlobFormat); } }
public static System.Security.Cryptography.CngKeyBlobFormat GenericPublicBlob { get { return default(System.Security.Cryptography.CngKeyBlobFormat); } }
public static System.Security.Cryptography.CngKeyBlobFormat OpaqueTransportBlob { get { return default(System.Security.Cryptography.CngKeyBlobFormat); } }
public static System.Security.Cryptography.CngKeyBlobFormat Pkcs8PrivateBlob { get { return default(System.Security.Cryptography.CngKeyBlobFormat); } }
public override bool Equals(object obj) { return default(bool); }
public bool Equals(System.Security.Cryptography.CngKeyBlobFormat other) { return default(bool); }
public override int GetHashCode() { return default(int); }
public static bool operator ==(System.Security.Cryptography.CngKeyBlobFormat left, System.Security.Cryptography.CngKeyBlobFormat right) { return default(bool); }
public static bool operator !=(System.Security.Cryptography.CngKeyBlobFormat left, System.Security.Cryptography.CngKeyBlobFormat right) { return default(bool); }
public override string ToString() { return default(string); }
}
[System.FlagsAttribute]
public enum CngKeyCreationOptions {
MachineKey = 32,
None = 0,
OverwriteExistingKey = 128,
}
public sealed partial class CngKeyCreationParameters {
public CngKeyCreationParameters() { throw new NotImplementedException(); }
public System.Nullable<System.Security.Cryptography.CngExportPolicies> ExportPolicy { get { return default(System.Nullable<System.Security.Cryptography.CngExportPolicies>); } set { } }
public System.Security.Cryptography.CngKeyCreationOptions KeyCreationOptions { get { return default(System.Security.Cryptography.CngKeyCreationOptions); } set { } }
public System.Nullable<System.Security.Cryptography.CngKeyUsages> KeyUsage { get { return default(System.Nullable<System.Security.Cryptography.CngKeyUsages>); } set { } }
public System.Security.Cryptography.CngPropertyCollection Parameters { get { return default(System.Security.Cryptography.CngPropertyCollection); } }
public System.IntPtr ParentWindowHandle { get { return default(System.IntPtr); } set { } }
public System.Security.Cryptography.CngProvider Provider { get { return default(System.Security.Cryptography.CngProvider); } set { } }
public System.Security.Cryptography.CngUIPolicy UIPolicy { get { return default(System.Security.Cryptography.CngUIPolicy); } set { } }
}
[System.FlagsAttribute]
public enum CngKeyHandleOpenOptions {
EphemeralKey = 1,
None = 0,
}
[System.FlagsAttribute]
public enum CngKeyOpenOptions {
MachineKey = 32,
None = 0,
Silent = 64,
UserKey = 0,
}
[System.FlagsAttribute]
public enum CngKeyUsages {
AllUsages = 16777215,
Decryption = 1,
KeyAgreement = 4,
None = 0,
Signing = 2,
}
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)]
public partial struct CngProperty : System.IEquatable<System.Security.Cryptography.CngProperty> {
public CngProperty(string name, byte[] value, System.Security.Cryptography.CngPropertyOptions options) { throw new System.NotImplementedException(); }
public string Name { get { return default(string); } }
public System.Security.Cryptography.CngPropertyOptions Options { get { return default(System.Security.Cryptography.CngPropertyOptions); } }
public override bool Equals(object obj) { return default(bool); }
public bool Equals(System.Security.Cryptography.CngProperty other) { return default(bool); }
public override int GetHashCode() { return default(int); }
public byte[] GetValue() { return default(byte[]); }
public static bool operator ==(System.Security.Cryptography.CngProperty left, System.Security.Cryptography.CngProperty right) { return default(bool); }
public static bool operator !=(System.Security.Cryptography.CngProperty left, System.Security.Cryptography.CngProperty right) { return default(bool); }
}
public sealed partial class CngPropertyCollection : System.Collections.ObjectModel.Collection<System.Security.Cryptography.CngProperty> {
public CngPropertyCollection() { }
}
[System.FlagsAttribute]
public enum CngPropertyOptions {
CustomProperty = 1073741824,
None = 0,
Persist = -2147483648,
}
public sealed partial class CngProvider : System.IEquatable<System.Security.Cryptography.CngProvider> {
public CngProvider(string provider) { throw new NotImplementedException(); }
public static System.Security.Cryptography.CngProvider MicrosoftSmartCardKeyStorageProvider { get { return default(System.Security.Cryptography.CngProvider); } }
public static System.Security.Cryptography.CngProvider MicrosoftSoftwareKeyStorageProvider { get { return default(System.Security.Cryptography.CngProvider); } }
public string Provider { get { return default(string); } }
public override bool Equals(object obj) { return default(bool); }
public bool Equals(System.Security.Cryptography.CngProvider other) { return default(bool); }
public override int GetHashCode() { return default(int); }
public static bool operator ==(System.Security.Cryptography.CngProvider left, System.Security.Cryptography.CngProvider right) { return default(bool); }
public static bool operator !=(System.Security.Cryptography.CngProvider left, System.Security.Cryptography.CngProvider right) { return default(bool); }
public override string ToString() { return default(string); }
}
public sealed partial class CngUIPolicy {
public CngUIPolicy(System.Security.Cryptography.CngUIProtectionLevels protectionLevel) { throw new NotImplementedException(); }
public CngUIPolicy(System.Security.Cryptography.CngUIProtectionLevels protectionLevel, string friendlyName) { throw new NotImplementedException(); }
public CngUIPolicy(System.Security.Cryptography.CngUIProtectionLevels protectionLevel, string friendlyName, string description) { throw new NotImplementedException(); }
public CngUIPolicy(System.Security.Cryptography.CngUIProtectionLevels protectionLevel, string friendlyName, string description, string useContext) { throw new NotImplementedException(); }
public CngUIPolicy(System.Security.Cryptography.CngUIProtectionLevels protectionLevel, string friendlyName, string description, string useContext, string creationTitle) { throw new NotImplementedException(); }
public string CreationTitle { get { return default(string); } }
public string Description { get { return default(string); } }
public string FriendlyName { get { return default(string); } }
public System.Security.Cryptography.CngUIProtectionLevels ProtectionLevel { get { return default(System.Security.Cryptography.CngUIProtectionLevels); } }
public string UseContext { get { return default(string); } }
}
[System.FlagsAttribute]
public enum CngUIProtectionLevels {
ForceHighProtection = 2,
None = 0,
ProtectKey = 1,
}
public sealed partial class RSACng : System.Security.Cryptography.RSA {
public RSACng() { throw new NotImplementedException(); }
public RSACng(int keySize) { throw new NotImplementedException(); }
public RSACng(System.Security.Cryptography.CngKey key) { throw new NotImplementedException(); }
public System.Security.Cryptography.CngKey Key { get { return default(System.Security.Cryptography.CngKey); } }
public override byte[] Decrypt(byte[] data, System.Security.Cryptography.RSAEncryptionPadding padding) { return default(byte[]); }
protected override void Dispose(bool disposing) { }
public override byte[] Encrypt(byte[] data, System.Security.Cryptography.RSAEncryptionPadding padding) { return default(byte[]); }
public override System.Security.Cryptography.RSAParameters ExportParameters(bool includePrivateParameters) { return default(System.Security.Cryptography.RSAParameters); }
protected override byte[] HashData(byte[] data, int offset, int count, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { return default(byte[]); }
protected override byte[] HashData(System.IO.Stream data, System.Security.Cryptography.HashAlgorithmName hashAlgorithm) { return default(byte[]); }
public override void ImportParameters(System.Security.Cryptography.RSAParameters parameters) { }
public override byte[] SignHash(byte[] hash, System.Security.Cryptography.HashAlgorithmName hashAlgorithm, System.Security.Cryptography.RSASignaturePadding padding) { return default(byte[]); }
public override bool VerifyHash(byte[] hash, byte[] signature, System.Security.Cryptography.HashAlgorithmName hashAlgorithm, System.Security.Cryptography.RSASignaturePadding padding) { return default(bool); }
}
}
| |
/*
* Copyright (c) 2010-2015 Pivotal Software, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you
* may not use this file except in compliance with the License. You
* may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License. See accompanying
* LICENSE file.
*/
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Net.Sockets;
//using IBM.Data.DB2;
using NUnit.Framework;
namespace Pivotal.Data.GemFireXD.Tests
{
/// <summary>
/// This class encapsulates some base common functionality to be used by
/// unit tests.
/// </summary>
public abstract class TestBase
{
public enum DriverType
{
DB2,
Mono,
GFXD,
GFXDPeer
}
internal delegate void StartPeerDelegate(DriverType driver,
string peerType,
string peerDir,
string discoveryArg,
int clientPort,
string additionalArgs);
internal static DriverType DefaultDriverType = DriverType.GFXD;
protected static java.io.PrintWriter s_logFileWriter;
protected static readonly Random s_rand;
protected static readonly string s_launcherScript;
protected static readonly string s_serverDir;
protected static readonly string s_testOutDir;
protected static int s_clientPort = -1;
protected static int s_savedClientPortBeforeStopping = -1;
protected static int s_clientPort1 = -1;
protected static int s_clientPort2 = -1;
protected static int s_clientPortLoc2 = -1;
protected DriverType m_defaultDriverType = DefaultDriverType;
protected static readonly DateTime Epoch = new DateTime(1970, 1, 1,
0, 0, 0, DateTimeKind.Utc);
protected const int MaxWaitMillis = 120000;
static TestBase()
{
TimeSpan ts = DateTime.Now - Epoch;
s_rand = new Random((int)ts.TotalSeconds);
string prodDir = Environment.GetEnvironmentVariable("GEMFIREXD");
if (prodDir == null || prodDir.Length == 0) {
throw new AssertionException("GEMFIREXD environment variable should"
+ " be set to point to GemFireXD product installation directory");
}
s_testOutDir = Environment.GetEnvironmentVariable("GFXDADOOUTDIR");
if (s_testOutDir == null || s_testOutDir.Length == 0) {
throw new AssertionException("GFXDADOOUTDIR environment variable should"
+ " be set to point to the directory where the test output should go");
}
if (IsUnix) {
s_launcherScript = prodDir + "/bin/gfxd";
}
else {
s_launcherScript = prodDir + "/bin/gfxd.bat";
}
s_serverDir = s_testOutDir + "/gfxdserver";
Directory.CreateDirectory(s_serverDir);
}
protected TestBase()
{
}
protected static void Log(string str)
{
s_logFileWriter.println(str);
s_logFileWriter.flush();
}
protected static void Log(string fmt, params object[] args)
{
s_logFileWriter.println(string.Format(fmt, args));
s_logFileWriter.flush();
}
protected virtual void SetDefaultDriverType()
{
m_defaultDriverType = DefaultDriverType;
}
internal static bool isRunningWithPool()
{
string rwp = Environment.GetEnvironmentVariable("RUN_WITH_POOL");
if (rwp != null )
{
return Convert.ToBoolean(rwp);
}
return true; //default is pool
}
internal static void StartGFXDServer(DriverType driver,
string additionalArgs)
{
int mcastPort = GetRandomPort();
//int mcastPort = 0;
//if (driver == DriverType.GFXDPeer) {
// mcastPort = GetRandomPort();
//}
initClientPort();
StartGFXDPeer(driver, "server", s_serverDir, "-mcast-port=" +
mcastPort, s_clientPort, additionalArgs);
}
internal static void initClientPort()
{
if (s_clientPort > 0) {
throw new NotSupportedException("An GFXD peer is running at port "
+ s_clientPort);
}
s_clientPort = GetAvailableTCPPort();
}
internal static void initClientPort1()
{
if (s_clientPort1 > 0) {
throw new NotSupportedException("An GFXD peer is running at port "
+ s_clientPort1);
}
s_clientPort1 = GetAvailableTCPPort();
}
internal static void initClientPort2()
{
if (s_clientPort2 > 0) {
throw new NotSupportedException("An GFXD peer is running at port "
+ s_clientPort2);
}
s_clientPort2 = GetAvailableTCPPort();
}
internal static void StartGFXDPeer(DriverType driver,
string peerType,
string peerDir,
string discoveryArg,
int clientPort,
string additionalArgs)
{
string logLevel = Environment.GetEnvironmentVariable("GFXD_LOGLEVEL");
string logLevelStr = "";
if (logLevel != null && logLevel.Length > 0) {
logLevelStr = " -log-level=" + logLevel;
} else {
logLevelStr = " -log-level=fine";
}
// set the proxy for license
string proxyHost = Environment.GetEnvironmentVariable("HTTP_PROXY_HOST");
string proxyPort = Environment.GetEnvironmentVariable("HTTP_PROXY_PORT");
string proxyArgs = "";
if (proxyHost != null && proxyHost.Length > 0) {
proxyArgs = " -J-Dhttp.proxyHost=" + proxyHost;
if (proxyPort != null && proxyPort.Length > 0) {
proxyArgs += (" -J-Dhttp.proxyPort=" + proxyPort);
}
}
string peerArgs = peerType + " start " + discoveryArg
+ " -J-ea -J-Dgemfirexd.drda.logConnections=true"
+ " -bind-address=localhost"
+ " -client-port=" + clientPort
+ additionalArgs + proxyArgs
//+ " -J-Dgemfirexd.drda.debug=true -J-Dgemfirexd.drda.traceAll=true"
//+ " -J-Dgemfirexd.debug.true=TraceIndex,TraceLock_*,TraceTran"
//+ " -J-Dgemfirexd.no-statement-matching=true"
+ logLevelStr// + " -log-level=fine -J-Dgemfirexd.table-default-partitioned=true"
+ " -dir=" + peerDir;
ProcessStartInfo pinfo = new ProcessStartInfo(s_launcherScript,
peerArgs);
//pinfo.CreateNoWindow = true;
pinfo.UseShellExecute = false;
pinfo.RedirectStandardOutput = true;
pinfo.RedirectStandardInput = false;
pinfo.RedirectStandardError = false;
pinfo.EnvironmentVariables["CLASSPATH"] = s_testOutDir;
Process proc = new Process();
proc.StartInfo = pinfo;
Log("Starting GFXD " + peerType + " with script: " + s_launcherScript);
Log("\tusing " + peerType + " args: " + peerArgs);
Log("\textra CLASSPATH=" + s_testOutDir);
Log("");
if (!proc.Start()) {
throw new Exception("Failed to start GFXD " + peerType);
}
StreamReader outSr = proc.StandardOutput;
// Wait for GFXD peer to start
bool started = proc.WaitForExit(MaxWaitMillis);
int bufSize = 1024;
char[] outBuf = new char[bufSize];
int readChars = outSr.Read(outBuf, 0, bufSize);
Log("Output from '{0} {1}':{2}{3}", s_launcherScript, peerArgs,
Environment.NewLine, new string(outBuf, 0, readChars));
outSr.Close();
if (!started) {
proc.Kill();
}
Assert.IsTrue(started, "Timed out waiting for GemFireXD " + peerType +
" to start.{0}Please check the " + peerType + " logs in " +
peerDir, Environment.NewLine);
}
internal static void StopGFXDServer(DriverType driver)
{
if (s_clientPort <= 0) {
throw new NotSupportedException("No server is running");
}
StopGFXDPeer(driver, "server", s_serverDir);
s_clientPort = -1;
}
internal static void StopGFXDPeer(DriverType driver, string peerType,
string peerDir)
{
string peerArgs = peerType + " stop -dir=" + peerDir;
ProcessStartInfo pinfo = new ProcessStartInfo(s_launcherScript, peerArgs);
//pinfo.CreateNoWindow = true;
pinfo.UseShellExecute = false;
pinfo.RedirectStandardOutput = true;
pinfo.RedirectStandardInput = false;
pinfo.RedirectStandardError = false;
Process proc = new Process();
proc.StartInfo = pinfo;
if (!proc.Start()) {
throw new Exception("failed to stop GFXD " + peerType);
}
StreamReader outSr = proc.StandardOutput;
// Wait for GFXD peer to stop
bool started = proc.WaitForExit(MaxWaitMillis);
int bufSize = 1024;
char[] outBuf = new char[bufSize];
int readChars = outSr.Read(outBuf, 0, bufSize);
Log("Output from '{0} {1}':{2}{3}", s_launcherScript, peerArgs,
Environment.NewLine, new string(outBuf, 0, readChars));
outSr.Close();
if (!started) {
proc.Kill();
}
Assert.IsTrue(started, "Timed out waiting for GemFireXD " + peerType +
" to stop.{0}Please check the " + peerType + " logs in " +
peerDir, Environment.NewLine);
}
internal static void StopAllGFXDPeers(int mcastPort, int locPort,
string additionalArgs)
{
string args = "shut-down-all";
if (mcastPort > 0) {
args += " -mcast-port=" + mcastPort + additionalArgs;
}
else {
args += " -locators=localhost[" + locPort + ']' + additionalArgs;
}
ProcessStartInfo pinfo = new ProcessStartInfo(s_launcherScript, args);
//pinfo.CreateNoWindow = true;
pinfo.UseShellExecute = false;
pinfo.RedirectStandardOutput = true;
pinfo.RedirectStandardInput = false;
pinfo.RedirectStandardError = false;
Process proc = new Process();
proc.StartInfo = pinfo;
if (!proc.Start()) {
throw new Exception("failed to stop all GFXD peers");
}
StreamReader outSr = proc.StandardOutput;
// Wait for shut-down-all script to finish
bool started = proc.WaitForExit(MaxWaitMillis);
int bufSize = 1024;
char[] outBuf = new char[bufSize];
int readChars = outSr.Read(outBuf, 0, bufSize);
Log("Output from '{0} {1}':{2}{3}", s_launcherScript, args,
Environment.NewLine, new string(outBuf, 0, readChars));
outSr.Close();
if (!started) {
proc.Kill();
}
Assert.IsTrue(started, "Timed out waiting for shut-down-all to finish.");
}
internal static int GetAvailableTCPPort()
{
int testPort;
bool done = false;
IPAddress localAddress = IPAddress.Loopback;
do {
testPort = GetRandomPort();
// try to establish a listener on this port
try {
TcpListener tcpListener = new TcpListener(localAddress, testPort);
tcpListener.Start();
tcpListener.Stop();
done = true;
} catch (SocketException) {
// could not start listener so try again
}
} while (!done);
return testPort;
}
internal static int GetRandomPort()
{
int startPort = 1100;
int endPort = 65000;
return s_rand.Next(startPort, endPort);
}
internal static DbConnection CreateConnection(DriverType type, string param,
bool noServerString)
{
DbConnection connection = null;
if (param != null && param.Length > 0) {
param = ";" + param;
}
else {
param = string.Empty;
}
//s_serverPort = 1527;
//string localServer = "pc29.pune.gemstone.com";
string localServer = "localhost";
switch (type) {
case DriverType.DB2:
/*
if (noServerString) {
connection = new DB2Connection(param);
}
else {
connection = new DB2Connection("Server=" + localServer + ':' +
s_serverPort + ";Database=Sample;Authentication=server" +
";UserID=app;Password=app" + param);
}
*/
connection = null;
break;
case DriverType.Mono:
if (noServerString) {
//connection = new DB2Connection(param);
}
else {
//connection = new DB2Connection("Database=gfxd;uid=app;pwd=app" +
// param);
}
break;
case DriverType.GFXD:
if (noServerString) {
// Console.WriteLine("True Trying to connect with string: " + param + " ...");
connection = new GFXDClientConnection(param);
}
else {
if (s_clientPortLoc2 == -1)
{
connection = new GFXDClientConnection("Server=" + localServer + ':'
+ s_clientPort + param);
}
else
{
int cport = s_clientPort;
if (cport == -1)
{
cport = s_savedClientPortBeforeStopping;
}
string cs = "Server=" + localServer + ':' + cport + ";secondary-locators=" + localServer
+ ':' + s_clientPortLoc2 + param;
Console.WriteLine("connecting with two locators " + cs);
//two locators are there
connection = new GFXDClientConnection(cs);
}
}
break;
case DriverType.GFXDPeer:
if (noServerString) {
//connection = new GFXDPeerConnection(param);
}
else {
//connection = new GFXDPeerConnection("host-data=false;" +
// "mcast-port=" + m_serverMcastPort + param);
}
break;
}
return connection;
}
protected virtual DbConnection OpenNewConnection()
{
return OpenNewConnection(null, false, null);
}
protected DbConnection OpenNewConnection(string param, bool noServerString,
Dictionary<string, string> props)
{
DbConnection conn = CreateConnection(m_defaultDriverType, param,
noServerString);
GFXDConnection gfxdConn = conn as GFXDConnection;
if (gfxdConn != null) {
gfxdConn.Open(props);
}
else {
conn.Open();
}
return conn;
}
protected DbDataAdapter GetDataAdapter(DriverType type)
{
switch (type) {
case DriverType.DB2:
// return new DB2DataAdapter();
return null;
case DriverType.Mono:
// return new DB2DataAdapter();
return null;
case DriverType.GFXD:
case DriverType.GFXDPeer:
default:
return new GFXDDataAdapter();
}
}
protected DbDataAdapter GetDataAdapter()
{
return GetDataAdapter(m_defaultDriverType);
}
protected DbCommand GetCommandForUpdate(DbConnection conn,
DriverType type)
{
DbCommand cmd = conn.CreateCommand();
switch (type) {
case DriverType.DB2:
// TODO: has DB2 driver anything for this?
break;
case DriverType.Mono:
// TODO: has Mono driver anything for this?
break;
case DriverType.GFXD:
case DriverType.GFXDPeer:
((GFXDCommand)cmd).ReaderLockForUpdate = true;
break;
}
return cmd;
}
protected DbCommand GetCommandForUpdate(DbConnection conn)
{
return GetCommandForUpdate(conn, m_defaultDriverType);
}
protected DbCommandBuilder GetCommandBuilder(DbDataAdapter adapter,
DriverType type)
{
switch (type) {
case DriverType.DB2:
// return new DB2CommandBuilder((DB2DataAdapter)adapter);
return null;
case DriverType.Mono:
// return new DB2CommandBuilder((DB2DataAdapter)adapter);
return null;
case DriverType.GFXD:
case DriverType.GFXDPeer:
default:
return new GFXDCommandBuilder((GFXDDataAdapter)adapter);
}
}
protected DbCommandBuilder GetCommandBuilder(DbDataAdapter adapter)
{
return GetCommandBuilder(adapter, m_defaultDriverType);
}
/* TODO: disabled due to #43188
protected void UpdateValue(DbDataReader reader, int index,
object val, DriverType type)
{
switch (type) {
case DriverType.DB2:
// TODO: has DB2 driver anything for this?
break;
case DriverType.Mono:
// TODO: has Mono driver anything for this?
break;
case DriverType.GFXD:
case DriverType.GFXDPeer:
((GFXDDataReader)reader).UpdateValue(index, val);
break;
}
}
protected void UpdateValue(DbDataReader reader, int index, object val)
{
UpdateValue(reader, index, val, m_defaultDriverType);
}
protected void UpdateRow(DbDataReader reader, DriverType type)
{
switch (type) {
case DriverType.DB2:
// TODO: has DB2 driver anything for this?
break;
case DriverType.Mono:
// TODO: has Mono driver anything for this?
break;
case DriverType.GFXD:
case DriverType.GFXDPeer:
((GFXDDataReader)reader).UpdateRow();
break;
}
}
protected void UpdateRow(DbDataReader reader)
{
UpdateRow(reader, m_defaultDriverType);
}
*/
internal static bool IsUnix
{
get {
int platformId = (int)Environment.OSVersion.Platform;
return (platformId == 4 || platformId == 6 || platformId == 128);
}
}
#region Setup and teardown methods
protected DbConnection m_conn;
protected DbCommand m_cmd;
[TestFixtureSetUp]
public virtual void FixtureSetup()
{
InternalSetup(GetType());
SetDefaultDriverType();
StartGFXDServer(m_defaultDriverType, "");
}
[TestFixtureTearDown]
public virtual void FixtureTearDown()
{
StopGFXDServer(m_defaultDriverType);
com.pivotal.gemfirexd.@internal.shared.common.sanity.SanityManager
.SET_DEBUG_STREAM(null);
if (s_logFileWriter != null) {
s_logFileWriter.close();
s_logFileWriter = null;
}
}
internal static void InternalSetup(Type type)
{
string logFileName;
if (s_testOutDir != null && s_testOutDir.Length > 0) {
logFileName = s_testOutDir + '/' + type.FullName + ".txt";
}
else {
logFileName = type.FullName + ".txt";
}
// use a java PrintWriter to also set the SanityManager output stream
// to this file
s_logFileWriter = new java.io.PrintWriter(logFileName);
com.pivotal.gemfirexd.@internal.shared.common.sanity.SanityManager
.SET_DEBUG_STREAM(s_logFileWriter);
}
[SetUp]
public virtual void SetUp()
{
string[] commonTablesA = CommonTablesToCreate();
if (commonTablesA.Length > 0) {
m_conn = OpenNewConnection();
CreateCommonTables(commonTablesA, m_conn);
}
}
protected virtual string[] CommonTablesToCreate()
{
// nothing by default
return new string[0];
}
[TearDown]
public virtual void TearDown()
{
using (DbConnection conn = OpenNewConnection()) {
DropDBObjects(GetSchemasToDrop(), GetTablesToDrop(),
GetFunctionsToDrop(), GetProceduresToDrop(), conn);
}
if (m_cmd != null) {
m_cmd.Dispose();
m_cmd = null;
}
if (m_conn != null && m_conn.State == ConnectionState.Open) {
m_conn.Close();
m_conn = null;
}
GFXDConnectionPoolManager.ClearAllPools();
}
protected virtual string[] GetProceduresToDrop()
{
// nothing by default
return new string[0];
}
protected virtual string[] GetFunctionsToDrop()
{
// nothing by default
return new string[0];
}
protected virtual string[] GetTablesToDrop()
{
return CommonTablesToCreate();
}
protected virtual string[] GetSchemasToDrop()
{
// nothing by default
return new string[0];
}
internal static void CreateCommonTables(string[] commonTablesA,
DbConnection conn)
{
int result;
List<string> commonTables = new List<string>(commonTablesA);
DbCommand cmd = conn.CreateCommand();
if (commonTables.Contains("numeric_family")) {
// numeric_family table and data
cmd.CommandText = "create table numeric_family (id int" +
" primary key, type_int int, type_varchar varchar(100))";
result = cmd.ExecuteNonQuery();
Assert.IsTrue(result == 0 || result == -1, "#S1");
cmd.CommandText = "insert into numeric_family values" +
" (1, 20000000, 'byte'), (2, 40000000, 'short')," +
" (3, 60000000, 'int'), (4, 80000000, 'long')";
result = cmd.ExecuteNonQuery();
Assert.AreEqual(4, result, "#S2");
}
if (commonTables.Contains("datetime_family")) {
// datetime_family table and data
cmd.CommandText = "create table datetime_family (id int" +
" primary key, type_date date, type_time time," +
" type_datetime timestamp)";
result = cmd.ExecuteNonQuery();
Assert.IsTrue(result == 0 || result == -1, "#S3");
cmd.CommandText = "insert into datetime_family values" +
" (1, '2004-10-10', '10:10:10', '2004-10-10 10:10:10')," +
" (2, '2005-10-10', NULL, '2005-10-10 10:10:10')";
result = cmd.ExecuteNonQuery();
Assert.AreEqual(2, result, "#S4");
}
if (commonTables.Contains("employee")) {
// employee table and data
cmd.CommandText = "create table employee (" +
" id int PRIMARY KEY," +
" fname varchar (50) NOT NULL," +
" lname varchar (50) NULL," +
" dob timestamp NOT NULL," +
" doj timestamp NOT NULL," +
" email varchar(50) NULL)";
result = cmd.ExecuteNonQuery();
Assert.IsTrue(result == 0 || result == -1, "#S5");
cmd.CommandText = "insert into employee values " +
"(1, 'suresh', 'kumar', '1978-08-22 00:00:00'," +
" '2001-03-12 00:00:00', 'suresh@gmail.com')," +
"(2, 'ramesh', 'rajendran', '1977-02-15 00:00:00'," +
" '2005-02-11 00:00:00', 'ramesh@yahoo.com')," +
"(3, 'venkat', 'ramakrishnan', '1977-06-12 00:00:00'," +
" '2003-12-11 00:00:00', 'ramesh@yahoo.com')," +
"(4, 'ramu', 'dhasarath', '1977-02-15 00:00:00'," +
" '2005-02-11 00:00:00', 'ramesh@yahoo.com')";
result = cmd.ExecuteNonQuery();
Assert.AreEqual(4, result, "#S6");
}
if (commonTables.Contains("emp.credit")) {
// employee table and data
cmd.CommandText = "create table emp.credit (" +
" creditid int," +
" employeeid int," +
" credit int NULL," +
" primary key(creditid)," +
" constraint fk_ec foreign key(employeeid) references employee(id))";
result = cmd.ExecuteNonQuery();
Assert.IsTrue(result == 0 || result == -1, "#S7");
}
}
protected void CleanEmployeeTable()
{
using (DbCommand cmd = m_conn.CreateCommand()) {
cmd.CommandText = "delete from employee where id > 4";
cmd.ExecuteNonQuery();
}
}
internal static void DropDBObjects(string[] schemas, string[] tables,
string[] funcs, string[] procs, DbConnection conn)
{
using (DbCommand cmd = conn.CreateCommand()) {
foreach (string proc in procs) {
cmd.CommandText = "drop procedure " + proc;
try {
cmd.ExecuteNonQuery();
} catch (DbException ex) {
if (!ex.Message.Contains("42Y55") &&
!ex.Message.Contains("42Y07")) {
throw;
}
}
}
foreach (string func in funcs) {
cmd.CommandText = "drop function " + func;
try {
cmd.ExecuteNonQuery();
} catch (DbException ex) {
if (!ex.Message.Contains("42Y55") &&
!ex.Message.Contains("42Y07")) {
throw;
}
}
}
foreach (string table in tables) {
cmd.CommandText = "drop table " + table;
try {
cmd.ExecuteNonQuery();
} catch (DbException ex) {
if (!ex.Message.Contains("42Y55") &&
!ex.Message.Contains("42Y07")) {
throw;
}
}
}
foreach (string schema in schemas) {
cmd.CommandText = "drop schema " + schema + " restrict";
try {
cmd.ExecuteNonQuery();
} catch (DbException ex) {
if (!ex.Message.Contains("42Y55") &&
!ex.Message.Contains("42Y07")) {
throw;
}
}
}
}
}
#endregion
}
}
| |
// Copyright (C) 2014 dot42
//
// Original filename: Org.Apache.Http.Client.Methods.cs
//
// 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.
#pragma warning disable 1717
namespace Org.Apache.Http.Client.Methods
{
/// <summary>
/// <para>HTTP HEAD method. </para><para>The HTTP HEAD method is defined in section 9.4 of : <blockquote><para>The HEAD method is identical to GET except that the server MUST NOT return a message-body in the response. The metainformation contained in the HTTP headers in response to a HEAD request SHOULD be identical to the information sent in response to a GET request. This method can be used for obtaining metainformation about the entity implied by the request without transferring the entity-body itself. This method is often used for testing hypertext links for validity, accessibility, and recent modification. </para></blockquote></para><para><para></para><title>Revision:</title><para>664505 </para></para><para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/client/methods/HttpHead
/// </java-name>
[Dot42.DexImport("org/apache/http/client/methods/HttpHead", AccessFlags = 33)]
public partial class HttpHead : global::Org.Apache.Http.Client.Methods.HttpRequestBase
/* scope: __dot42__ */
{
/// <java-name>
/// METHOD_NAME
/// </java-name>
[Dot42.DexImport("METHOD_NAME", "Ljava/lang/String;", AccessFlags = 25)]
public const string METHOD_NAME = "HEAD";
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public HttpHead() /* MethodBuilder.Create */
{
}
[Dot42.DexImport("<init>", "(Ljava/net/URI;)V", AccessFlags = 1)]
public HttpHead(global::System.Uri uri) /* MethodBuilder.Create */
{
}
[Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 1)]
public HttpHead(string uri) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Returns the HTTP method this request uses, such as <code>GET</code>, <code>PUT</code>, <code>POST</code>, or other. </para>
/// </summary>
/// <java-name>
/// getMethod
/// </java-name>
[Dot42.DexImport("getMethod", "()Ljava/lang/String;", AccessFlags = 1)]
public override string GetMethod() /* MethodBuilder.Create */
{
return default(string);
}
/// <summary>
/// <para>Returns the HTTP method this request uses, such as <code>GET</code>, <code>PUT</code>, <code>POST</code>, or other. </para>
/// </summary>
/// <java-name>
/// getMethod
/// </java-name>
public string Method
{
[Dot42.DexImport("getMethod", "()Ljava/lang/String;", AccessFlags = 1)]
get{ return GetMethod(); }
}
}
/// <summary>
/// <para>Basic implementation of an HTTP request that can be modified.</para><para><para></para><para></para><title>Revision:</title><para>674186 </para></para><para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/client/methods/HttpRequestBase
/// </java-name>
[Dot42.DexImport("org/apache/http/client/methods/HttpRequestBase", AccessFlags = 1057)]
public abstract partial class HttpRequestBase : global::Org.Apache.Http.Message.AbstractHttpMessage, global::Org.Apache.Http.Client.Methods.IHttpUriRequest, global::Org.Apache.Http.Client.Methods.IAbortableHttpRequest, global::Java.Lang.ICloneable
/* scope: __dot42__ */
{
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public HttpRequestBase() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Returns the HTTP method this request uses, such as <code>GET</code>, <code>PUT</code>, <code>POST</code>, or other. </para>
/// </summary>
/// <java-name>
/// getMethod
/// </java-name>
[Dot42.DexImport("getMethod", "()Ljava/lang/String;", AccessFlags = 1025)]
public virtual string GetMethod() /* MethodBuilder.Create */
{
return default(string);
}
/// <summary>
/// <para>Returns the protocol version this message is compatible with. </para>
/// </summary>
/// <java-name>
/// getProtocolVersion
/// </java-name>
[Dot42.DexImport("getProtocolVersion", "()Lorg/apache/http/ProtocolVersion;", AccessFlags = 1)]
public override global::Org.Apache.Http.ProtocolVersion GetProtocolVersion() /* MethodBuilder.Create */
{
return default(global::Org.Apache.Http.ProtocolVersion);
}
/// <summary>
/// <para>Returns the URI this request uses, such as <code></code>. </para>
/// </summary>
/// <java-name>
/// getURI
/// </java-name>
[Dot42.DexImport("getURI", "()Ljava/net/URI;", AccessFlags = 1)]
public virtual global::System.Uri GetURI() /* MethodBuilder.Create */
{
return default(global::System.Uri);
}
/// <summary>
/// <para>Returns the request line of this request. </para>
/// </summary>
/// <returns>
/// <para>the request line. </para>
/// </returns>
/// <java-name>
/// getRequestLine
/// </java-name>
[Dot42.DexImport("getRequestLine", "()Lorg/apache/http/RequestLine;", AccessFlags = 1)]
public virtual global::Org.Apache.Http.IRequestLine GetRequestLine() /* MethodBuilder.Create */
{
return default(global::Org.Apache.Http.IRequestLine);
}
/// <java-name>
/// setURI
/// </java-name>
[Dot42.DexImport("setURI", "(Ljava/net/URI;)V", AccessFlags = 1)]
public virtual void SetURI(global::System.Uri uri) /* MethodBuilder.Create */
{
}
/// <java-name>
/// setConnectionRequest
/// </java-name>
[Dot42.DexImport("setConnectionRequest", "(Lorg/apache/http/conn/ClientConnectionRequest;)V", AccessFlags = 1)]
public virtual void SetConnectionRequest(global::Org.Apache.Http.Conn.IClientConnectionRequest connRequest) /* MethodBuilder.Create */
{
}
/// <java-name>
/// setReleaseTrigger
/// </java-name>
[Dot42.DexImport("setReleaseTrigger", "(Lorg/apache/http/conn/ConnectionReleaseTrigger;)V", AccessFlags = 1)]
public virtual void SetReleaseTrigger(global::Org.Apache.Http.Conn.IConnectionReleaseTrigger releaseTrigger) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Aborts this http request. Any active execution of this method should return immediately. If the request has not started, it will abort after the next execution. Aborting this request will cause all subsequent executions with this request to fail.</para><para><para>HttpClient::execute(HttpUriRequest) </para><simplesectsep></simplesectsep><para>HttpClient::execute(org.apache.http.HttpHost, org.apache.http.HttpRequest) </para><simplesectsep></simplesectsep><para>HttpClient::execute(HttpUriRequest, org.apache.http.protocol.HttpContext) </para><simplesectsep></simplesectsep><para>HttpClient::execute(org.apache.http.HttpHost, org.apache.http.HttpRequest, org.apache.http.protocol.HttpContext) </para></para>
/// </summary>
/// <java-name>
/// abort
/// </java-name>
[Dot42.DexImport("abort", "()V", AccessFlags = 1)]
public virtual void Abort() /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Tests if the request execution has been aborted.</para><para></para>
/// </summary>
/// <returns>
/// <para><code>true</code> if the request execution has been aborted, <code>false</code> otherwise. </para>
/// </returns>
/// <java-name>
/// isAborted
/// </java-name>
[Dot42.DexImport("isAborted", "()Z", AccessFlags = 1)]
public virtual bool IsAborted() /* MethodBuilder.Create */
{
return default(bool);
}
/// <java-name>
/// clone
/// </java-name>
[Dot42.DexImport("clone", "()Ljava/lang/Object;", AccessFlags = 1)]
public virtual object Clone() /* MethodBuilder.Create */
{
return default(object);
}
[Dot42.DexImport("org/apache/http/HttpMessage", "containsHeader", "(Ljava/lang/String;)Z", AccessFlags = 1025)]
public override bool ContainsHeader(string name) /* TypeBuilder.AddAbstractInterfaceMethods */
{
return default(bool);
}
[Dot42.DexImport("org/apache/http/HttpMessage", "getHeaders", "(Ljava/lang/String;)[Lorg/apache/http/Header;", AccessFlags = 1025)]
public override global::Org.Apache.Http.IHeader[] GetHeaders(string name) /* TypeBuilder.AddAbstractInterfaceMethods */
{
return default(global::Org.Apache.Http.IHeader[]);
}
[Dot42.DexImport("org/apache/http/HttpMessage", "getFirstHeader", "(Ljava/lang/String;)Lorg/apache/http/Header;", AccessFlags = 1025)]
public override global::Org.Apache.Http.IHeader GetFirstHeader(string name) /* TypeBuilder.AddAbstractInterfaceMethods */
{
return default(global::Org.Apache.Http.IHeader);
}
[Dot42.DexImport("org/apache/http/HttpMessage", "getLastHeader", "(Ljava/lang/String;)Lorg/apache/http/Header;", AccessFlags = 1025)]
public override global::Org.Apache.Http.IHeader GetLastHeader(string name) /* TypeBuilder.AddAbstractInterfaceMethods */
{
return default(global::Org.Apache.Http.IHeader);
}
[Dot42.DexImport("org/apache/http/HttpMessage", "getAllHeaders", "()[Lorg/apache/http/Header;", AccessFlags = 1025)]
public override global::Org.Apache.Http.IHeader[] GetAllHeaders() /* TypeBuilder.AddAbstractInterfaceMethods */
{
return default(global::Org.Apache.Http.IHeader[]);
}
[Dot42.DexImport("org/apache/http/HttpMessage", "addHeader", "(Lorg/apache/http/Header;)V", AccessFlags = 1025)]
public override void AddHeader(global::Org.Apache.Http.IHeader header) /* TypeBuilder.AddAbstractInterfaceMethods */
{
}
[Dot42.DexImport("org/apache/http/HttpMessage", "addHeader", "(Ljava/lang/String;Ljava/lang/String;)V", AccessFlags = 1025)]
public override void AddHeader(string name, string value) /* TypeBuilder.AddAbstractInterfaceMethods */
{
}
[Dot42.DexImport("org/apache/http/HttpMessage", "setHeader", "(Lorg/apache/http/Header;)V", AccessFlags = 1025)]
public override void SetHeader(global::Org.Apache.Http.IHeader header) /* TypeBuilder.AddAbstractInterfaceMethods */
{
}
[Dot42.DexImport("org/apache/http/HttpMessage", "setHeader", "(Ljava/lang/String;Ljava/lang/String;)V", AccessFlags = 1025)]
public override void SetHeader(string name, string value) /* TypeBuilder.AddAbstractInterfaceMethods */
{
}
[Dot42.DexImport("org/apache/http/HttpMessage", "setHeaders", "([Lorg/apache/http/Header;)V", AccessFlags = 1025)]
public override void SetHeaders(global::Org.Apache.Http.IHeader[] headers) /* TypeBuilder.AddAbstractInterfaceMethods */
{
}
[Dot42.DexImport("org/apache/http/HttpMessage", "removeHeader", "(Lorg/apache/http/Header;)V", AccessFlags = 1025)]
public override void RemoveHeader(global::Org.Apache.Http.IHeader header) /* TypeBuilder.AddAbstractInterfaceMethods */
{
}
[Dot42.DexImport("org/apache/http/HttpMessage", "removeHeaders", "(Ljava/lang/String;)V", AccessFlags = 1025)]
public override void RemoveHeaders(string name) /* TypeBuilder.AddAbstractInterfaceMethods */
{
}
[Dot42.DexImport("org/apache/http/HttpMessage", "headerIterator", "()Lorg/apache/http/HeaderIterator;", AccessFlags = 1025)]
public override global::Org.Apache.Http.IHeaderIterator HeaderIterator() /* TypeBuilder.AddAbstractInterfaceMethods */
{
return default(global::Org.Apache.Http.IHeaderIterator);
}
[Dot42.DexImport("org/apache/http/HttpMessage", "headerIterator", "(Ljava/lang/String;)Lorg/apache/http/HeaderIterator;", AccessFlags = 1025)]
public override global::Org.Apache.Http.IHeaderIterator HeaderIterator(string name) /* TypeBuilder.AddAbstractInterfaceMethods */
{
return default(global::Org.Apache.Http.IHeaderIterator);
}
[Dot42.DexImport("org/apache/http/HttpMessage", "getParams", "()Lorg/apache/http/params/HttpParams;", AccessFlags = 1025)]
public override global::Org.Apache.Http.Params.IHttpParams GetParams() /* TypeBuilder.AddAbstractInterfaceMethods */
{
return default(global::Org.Apache.Http.Params.IHttpParams);
}
[Dot42.DexImport("org/apache/http/HttpMessage", "setParams", "(Lorg/apache/http/params/HttpParams;)V", AccessFlags = 1025)]
public override void SetParams(global::Org.Apache.Http.Params.IHttpParams @params) /* TypeBuilder.AddAbstractInterfaceMethods */
{
}
/// <summary>
/// <para>Returns the HTTP method this request uses, such as <code>GET</code>, <code>PUT</code>, <code>POST</code>, or other. </para>
/// </summary>
/// <java-name>
/// getMethod
/// </java-name>
public string Method
{
[Dot42.DexImport("getMethod", "()Ljava/lang/String;", AccessFlags = 1025)]
get{ return GetMethod(); }
}
/// <summary>
/// <para>Returns the protocol version this message is compatible with. </para>
/// </summary>
/// <java-name>
/// getProtocolVersion
/// </java-name>
public global::Org.Apache.Http.ProtocolVersion ProtocolVersion
{
[Dot42.DexImport("getProtocolVersion", "()Lorg/apache/http/ProtocolVersion;", AccessFlags = 1)]
get{ return GetProtocolVersion(); }
}
/// <summary>
/// <para>Returns the URI this request uses, such as <code></code>. </para>
/// </summary>
/// <java-name>
/// getURI
/// </java-name>
public global::System.Uri URI
{
[Dot42.DexImport("getURI", "()Ljava/net/URI;", AccessFlags = 1)]
get{ return GetURI(); }
[Dot42.DexImport("setURI", "(Ljava/net/URI;)V", AccessFlags = 1)]
set{ SetURI(value); }
}
/// <summary>
/// <para>Returns the request line of this request. </para>
/// </summary>
/// <returns>
/// <para>the request line. </para>
/// </returns>
/// <java-name>
/// getRequestLine
/// </java-name>
public global::Org.Apache.Http.IRequestLine RequestLine
{
[Dot42.DexImport("getRequestLine", "()Lorg/apache/http/RequestLine;", AccessFlags = 1)]
get{ return GetRequestLine(); }
}
public global::Org.Apache.Http.IHeader[] AllHeaders
{
[Dot42.DexImport("org/apache/http/HttpMessage", "getAllHeaders", "()[Lorg/apache/http/Header;", AccessFlags = 1025)]
get{ return GetAllHeaders(); }
}
}
/// <summary>
/// <para>HTTP OPTIONS method. </para><para>The HTTP OPTIONS method is defined in section 9.2 of : <blockquote><para>The OPTIONS method represents a request for information about the communication options available on the request/response chain identified by the Request-URI. This method allows the client to determine the options and/or requirements associated with a resource, or the capabilities of a server, without implying a resource action or initiating a resource retrieval. </para></blockquote></para><para><para></para><title>Revision:</title><para>664505 </para></para><para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/client/methods/HttpOptions
/// </java-name>
[Dot42.DexImport("org/apache/http/client/methods/HttpOptions", AccessFlags = 33)]
public partial class HttpOptions : global::Org.Apache.Http.Client.Methods.HttpRequestBase
/* scope: __dot42__ */
{
/// <java-name>
/// METHOD_NAME
/// </java-name>
[Dot42.DexImport("METHOD_NAME", "Ljava/lang/String;", AccessFlags = 25)]
public const string METHOD_NAME = "OPTIONS";
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public HttpOptions() /* MethodBuilder.Create */
{
}
[Dot42.DexImport("<init>", "(Ljava/net/URI;)V", AccessFlags = 1)]
public HttpOptions(global::System.Uri uri) /* MethodBuilder.Create */
{
}
[Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 1)]
public HttpOptions(string uri) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Returns the HTTP method this request uses, such as <code>GET</code>, <code>PUT</code>, <code>POST</code>, or other. </para>
/// </summary>
/// <java-name>
/// getMethod
/// </java-name>
[Dot42.DexImport("getMethod", "()Ljava/lang/String;", AccessFlags = 1)]
public override string GetMethod() /* MethodBuilder.Create */
{
return default(string);
}
/// <java-name>
/// getAllowedMethods
/// </java-name>
[Dot42.DexImport("getAllowedMethods", "(Lorg/apache/http/HttpResponse;)Ljava/util/Set;", AccessFlags = 1, Signature = "(Lorg/apache/http/HttpResponse;)Ljava/util/Set<Ljava/lang/String;>;")]
public virtual global::Java.Util.ISet<string> GetAllowedMethods(global::Org.Apache.Http.IHttpResponse response) /* MethodBuilder.Create */
{
return default(global::Java.Util.ISet<string>);
}
/// <summary>
/// <para>Returns the HTTP method this request uses, such as <code>GET</code>, <code>PUT</code>, <code>POST</code>, or other. </para>
/// </summary>
/// <java-name>
/// getMethod
/// </java-name>
public string Method
{
[Dot42.DexImport("getMethod", "()Ljava/lang/String;", AccessFlags = 1)]
get{ return GetMethod(); }
}
}
/// <summary>
/// <para>HTTP PUT method. </para><para>The HTTP PUT method is defined in section 9.6 of : <blockquote><para>The PUT method requests that the enclosed entity be stored under the supplied Request-URI. If the Request-URI refers to an already existing resource, the enclosed entity SHOULD be considered as a modified version of the one residing on the origin server. </para></blockquote></para><para><para></para><title>Revision:</title><para>664505 </para></para><para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/client/methods/HttpPut
/// </java-name>
[Dot42.DexImport("org/apache/http/client/methods/HttpPut", AccessFlags = 33)]
public partial class HttpPut : global::Org.Apache.Http.Client.Methods.HttpEntityEnclosingRequestBase
/* scope: __dot42__ */
{
/// <java-name>
/// METHOD_NAME
/// </java-name>
[Dot42.DexImport("METHOD_NAME", "Ljava/lang/String;", AccessFlags = 25)]
public const string METHOD_NAME = "PUT";
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public HttpPut() /* MethodBuilder.Create */
{
}
[Dot42.DexImport("<init>", "(Ljava/net/URI;)V", AccessFlags = 1)]
public HttpPut(global::System.Uri uri) /* MethodBuilder.Create */
{
}
[Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 1)]
public HttpPut(string uri) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Returns the HTTP method this request uses, such as <code>GET</code>, <code>PUT</code>, <code>POST</code>, or other. </para>
/// </summary>
/// <java-name>
/// getMethod
/// </java-name>
[Dot42.DexImport("getMethod", "()Ljava/lang/String;", AccessFlags = 1)]
public override string GetMethod() /* MethodBuilder.Create */
{
return default(string);
}
/// <summary>
/// <para>Returns the HTTP method this request uses, such as <code>GET</code>, <code>PUT</code>, <code>POST</code>, or other. </para>
/// </summary>
/// <java-name>
/// getMethod
/// </java-name>
public string Method
{
[Dot42.DexImport("getMethod", "()Ljava/lang/String;", AccessFlags = 1)]
get{ return GetMethod(); }
}
}
/// <summary>
/// <para>HTTP DELETE method </para><para>The HTTP DELETE method is defined in section 9.7 of : <blockquote><para>The DELETE method requests that the origin server delete the resource identified by the Request-URI. [...] The client cannot be guaranteed that the operation has been carried out, even if the status code returned from the origin server indicates that the action has been completed successfully. </para></blockquote></para>
/// </summary>
/// <java-name>
/// org/apache/http/client/methods/HttpDelete
/// </java-name>
[Dot42.DexImport("org/apache/http/client/methods/HttpDelete", AccessFlags = 33)]
public partial class HttpDelete : global::Org.Apache.Http.Client.Methods.HttpRequestBase
/* scope: __dot42__ */
{
/// <java-name>
/// METHOD_NAME
/// </java-name>
[Dot42.DexImport("METHOD_NAME", "Ljava/lang/String;", AccessFlags = 25)]
public const string METHOD_NAME = "DELETE";
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public HttpDelete() /* MethodBuilder.Create */
{
}
[Dot42.DexImport("<init>", "(Ljava/net/URI;)V", AccessFlags = 1)]
public HttpDelete(global::System.Uri uri) /* MethodBuilder.Create */
{
}
[Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 1)]
public HttpDelete(string uri) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Returns the HTTP method this request uses, such as <code>GET</code>, <code>PUT</code>, <code>POST</code>, or other. </para>
/// </summary>
/// <java-name>
/// getMethod
/// </java-name>
[Dot42.DexImport("getMethod", "()Ljava/lang/String;", AccessFlags = 1)]
public override string GetMethod() /* MethodBuilder.Create */
{
return default(string);
}
/// <summary>
/// <para>Returns the HTTP method this request uses, such as <code>GET</code>, <code>PUT</code>, <code>POST</code>, or other. </para>
/// </summary>
/// <java-name>
/// getMethod
/// </java-name>
public string Method
{
[Dot42.DexImport("getMethod", "()Ljava/lang/String;", AccessFlags = 1)]
get{ return GetMethod(); }
}
}
/// <summary>
/// <para>Basic implementation of an HTTP request that can be modified.</para><para><para></para><para></para><title>Revision:</title><para>674186 </para></para><para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/client/methods/HttpEntityEnclosingRequestBase
/// </java-name>
[Dot42.DexImport("org/apache/http/client/methods/HttpEntityEnclosingRequestBase", AccessFlags = 1057)]
public abstract partial class HttpEntityEnclosingRequestBase : global::Org.Apache.Http.Client.Methods.HttpRequestBase, global::Org.Apache.Http.IHttpEntityEnclosingRequest
/* scope: __dot42__ */
{
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public HttpEntityEnclosingRequestBase() /* MethodBuilder.Create */
{
}
/// <java-name>
/// getEntity
/// </java-name>
[Dot42.DexImport("getEntity", "()Lorg/apache/http/HttpEntity;", AccessFlags = 1)]
public virtual global::Org.Apache.Http.IHttpEntity GetEntity() /* MethodBuilder.Create */
{
return default(global::Org.Apache.Http.IHttpEntity);
}
/// <java-name>
/// setEntity
/// </java-name>
[Dot42.DexImport("setEntity", "(Lorg/apache/http/HttpEntity;)V", AccessFlags = 1)]
public virtual void SetEntity(global::Org.Apache.Http.IHttpEntity entity) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Tells if this request should use the expect-continue handshake. The expect continue handshake gives the server a chance to decide whether to accept the entity enclosing request before the possibly lengthy entity is sent across the wire. </para>
/// </summary>
/// <returns>
/// <para>true if the expect continue handshake should be used, false if not. </para>
/// </returns>
/// <java-name>
/// expectContinue
/// </java-name>
[Dot42.DexImport("expectContinue", "()Z", AccessFlags = 1)]
public virtual bool ExpectContinue() /* MethodBuilder.Create */
{
return default(bool);
}
/// <java-name>
/// clone
/// </java-name>
[Dot42.DexImport("clone", "()Ljava/lang/Object;", AccessFlags = 1)]
public override object Clone() /* MethodBuilder.Create */
{
return default(object);
}
[Dot42.DexImport("org/apache/http/HttpRequest", "getRequestLine", "()Lorg/apache/http/RequestLine;", AccessFlags = 1025)]
public override global::Org.Apache.Http.IRequestLine GetRequestLine() /* TypeBuilder.AddAbstractInterfaceMethods */
{
return default(global::Org.Apache.Http.IRequestLine);
}
[Dot42.DexImport("org/apache/http/HttpMessage", "getProtocolVersion", "()Lorg/apache/http/ProtocolVersion;", AccessFlags = 1025)]
public override global::Org.Apache.Http.ProtocolVersion GetProtocolVersion() /* TypeBuilder.AddAbstractInterfaceMethods */
{
return default(global::Org.Apache.Http.ProtocolVersion);
}
[Dot42.DexImport("org/apache/http/HttpMessage", "containsHeader", "(Ljava/lang/String;)Z", AccessFlags = 1025)]
public override bool ContainsHeader(string name) /* TypeBuilder.AddAbstractInterfaceMethods */
{
return default(bool);
}
[Dot42.DexImport("org/apache/http/HttpMessage", "getHeaders", "(Ljava/lang/String;)[Lorg/apache/http/Header;", AccessFlags = 1025)]
public override global::Org.Apache.Http.IHeader[] GetHeaders(string name) /* TypeBuilder.AddAbstractInterfaceMethods */
{
return default(global::Org.Apache.Http.IHeader[]);
}
[Dot42.DexImport("org/apache/http/HttpMessage", "getFirstHeader", "(Ljava/lang/String;)Lorg/apache/http/Header;", AccessFlags = 1025)]
public override global::Org.Apache.Http.IHeader GetFirstHeader(string name) /* TypeBuilder.AddAbstractInterfaceMethods */
{
return default(global::Org.Apache.Http.IHeader);
}
[Dot42.DexImport("org/apache/http/HttpMessage", "getLastHeader", "(Ljava/lang/String;)Lorg/apache/http/Header;", AccessFlags = 1025)]
public override global::Org.Apache.Http.IHeader GetLastHeader(string name) /* TypeBuilder.AddAbstractInterfaceMethods */
{
return default(global::Org.Apache.Http.IHeader);
}
[Dot42.DexImport("org/apache/http/HttpMessage", "getAllHeaders", "()[Lorg/apache/http/Header;", AccessFlags = 1025)]
public override global::Org.Apache.Http.IHeader[] GetAllHeaders() /* TypeBuilder.AddAbstractInterfaceMethods */
{
return default(global::Org.Apache.Http.IHeader[]);
}
[Dot42.DexImport("org/apache/http/HttpMessage", "addHeader", "(Lorg/apache/http/Header;)V", AccessFlags = 1025)]
public override void AddHeader(global::Org.Apache.Http.IHeader header) /* TypeBuilder.AddAbstractInterfaceMethods */
{
}
[Dot42.DexImport("org/apache/http/HttpMessage", "addHeader", "(Ljava/lang/String;Ljava/lang/String;)V", AccessFlags = 1025)]
public override void AddHeader(string name, string value) /* TypeBuilder.AddAbstractInterfaceMethods */
{
}
[Dot42.DexImport("org/apache/http/HttpMessage", "setHeader", "(Lorg/apache/http/Header;)V", AccessFlags = 1025)]
public override void SetHeader(global::Org.Apache.Http.IHeader header) /* TypeBuilder.AddAbstractInterfaceMethods */
{
}
[Dot42.DexImport("org/apache/http/HttpMessage", "setHeader", "(Ljava/lang/String;Ljava/lang/String;)V", AccessFlags = 1025)]
public override void SetHeader(string name, string value) /* TypeBuilder.AddAbstractInterfaceMethods */
{
}
[Dot42.DexImport("org/apache/http/HttpMessage", "setHeaders", "([Lorg/apache/http/Header;)V", AccessFlags = 1025)]
public override void SetHeaders(global::Org.Apache.Http.IHeader[] headers) /* TypeBuilder.AddAbstractInterfaceMethods */
{
}
[Dot42.DexImport("org/apache/http/HttpMessage", "removeHeader", "(Lorg/apache/http/Header;)V", AccessFlags = 1025)]
public override void RemoveHeader(global::Org.Apache.Http.IHeader header) /* TypeBuilder.AddAbstractInterfaceMethods */
{
}
[Dot42.DexImport("org/apache/http/HttpMessage", "removeHeaders", "(Ljava/lang/String;)V", AccessFlags = 1025)]
public override void RemoveHeaders(string name) /* TypeBuilder.AddAbstractInterfaceMethods */
{
}
[Dot42.DexImport("org/apache/http/HttpMessage", "headerIterator", "()Lorg/apache/http/HeaderIterator;", AccessFlags = 1025)]
public override global::Org.Apache.Http.IHeaderIterator HeaderIterator() /* TypeBuilder.AddAbstractInterfaceMethods */
{
return default(global::Org.Apache.Http.IHeaderIterator);
}
[Dot42.DexImport("org/apache/http/HttpMessage", "headerIterator", "(Ljava/lang/String;)Lorg/apache/http/HeaderIterator;", AccessFlags = 1025)]
public override global::Org.Apache.Http.IHeaderIterator HeaderIterator(string name) /* TypeBuilder.AddAbstractInterfaceMethods */
{
return default(global::Org.Apache.Http.IHeaderIterator);
}
[Dot42.DexImport("org/apache/http/HttpMessage", "getParams", "()Lorg/apache/http/params/HttpParams;", AccessFlags = 1025)]
public override global::Org.Apache.Http.Params.IHttpParams GetParams() /* TypeBuilder.AddAbstractInterfaceMethods */
{
return default(global::Org.Apache.Http.Params.IHttpParams);
}
[Dot42.DexImport("org/apache/http/HttpMessage", "setParams", "(Lorg/apache/http/params/HttpParams;)V", AccessFlags = 1025)]
public override void SetParams(global::Org.Apache.Http.Params.IHttpParams @params) /* TypeBuilder.AddAbstractInterfaceMethods */
{
}
/// <java-name>
/// getEntity
/// </java-name>
public global::Org.Apache.Http.IHttpEntity Entity
{
[Dot42.DexImport("getEntity", "()Lorg/apache/http/HttpEntity;", AccessFlags = 1)]
get{ return GetEntity(); }
[Dot42.DexImport("setEntity", "(Lorg/apache/http/HttpEntity;)V", AccessFlags = 1)]
set{ SetEntity(value); }
}
public global::Org.Apache.Http.IRequestLine RequestLine
{
[Dot42.DexImport("org/apache/http/HttpRequest", "getRequestLine", "()Lorg/apache/http/RequestLine;", AccessFlags = 1025)]
get{ return GetRequestLine(); }
}
public global::Org.Apache.Http.ProtocolVersion ProtocolVersion
{
[Dot42.DexImport("org/apache/http/HttpMessage", "getProtocolVersion", "()Lorg/apache/http/ProtocolVersion;", AccessFlags = 1025)]
get{ return GetProtocolVersion(); }
}
public global::Org.Apache.Http.IHeader[] AllHeaders
{
[Dot42.DexImport("org/apache/http/HttpMessage", "getAllHeaders", "()[Lorg/apache/http/Header;", AccessFlags = 1025)]
get{ return GetAllHeaders(); }
}
}
/// <summary>
/// <para>HTTP TRACE method. </para><para>The HTTP TRACE method is defined in section 9.6 of : <blockquote><para>The TRACE method is used to invoke a remote, application-layer loop- back of the request message. The final recipient of the request SHOULD reflect the message received back to the client as the entity-body of a 200 (OK) response. The final recipient is either the origin server or the first proxy or gateway to receive a Max-Forwards value of zero (0) in the request (see section 14.31). A TRACE request MUST NOT include an entity. </para></blockquote></para><para><para></para><title>Revision:</title><para>664505 </para></para><para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/client/methods/HttpTrace
/// </java-name>
[Dot42.DexImport("org/apache/http/client/methods/HttpTrace", AccessFlags = 33)]
public partial class HttpTrace : global::Org.Apache.Http.Client.Methods.HttpRequestBase
/* scope: __dot42__ */
{
/// <java-name>
/// METHOD_NAME
/// </java-name>
[Dot42.DexImport("METHOD_NAME", "Ljava/lang/String;", AccessFlags = 25)]
public const string METHOD_NAME = "TRACE";
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public HttpTrace() /* MethodBuilder.Create */
{
}
[Dot42.DexImport("<init>", "(Ljava/net/URI;)V", AccessFlags = 1)]
public HttpTrace(global::System.Uri uri) /* MethodBuilder.Create */
{
}
[Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 1)]
public HttpTrace(string uri) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Returns the HTTP method this request uses, such as <code>GET</code>, <code>PUT</code>, <code>POST</code>, or other. </para>
/// </summary>
/// <java-name>
/// getMethod
/// </java-name>
[Dot42.DexImport("getMethod", "()Ljava/lang/String;", AccessFlags = 1)]
public override string GetMethod() /* MethodBuilder.Create */
{
return default(string);
}
/// <summary>
/// <para>Returns the HTTP method this request uses, such as <code>GET</code>, <code>PUT</code>, <code>POST</code>, or other. </para>
/// </summary>
/// <java-name>
/// getMethod
/// </java-name>
public string Method
{
[Dot42.DexImport("getMethod", "()Ljava/lang/String;", AccessFlags = 1)]
get{ return GetMethod(); }
}
}
/// <summary>
/// <para>HTTP POST method. </para><para>The HTTP POST method is defined in section 9.5 of : <blockquote><para>The POST method is used to request that the origin server accept the entity enclosed in the request as a new subordinate of the resource identified by the Request-URI in the Request-Line. POST is designed to allow a uniform method to cover the following functions: <ul><li><para>Annotation of existing resources </para></li><li><para>Posting a message to a bulletin board, newsgroup, mailing list, or similar group of articles </para></li><li><para>Providing a block of data, such as the result of submitting a form, to a data-handling process </para></li><li><para>Extending a database through an append operation </para></li></ul></para></blockquote></para><para><para></para><title>Revision:</title><para>664505 </para></para><para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/client/methods/HttpPost
/// </java-name>
[Dot42.DexImport("org/apache/http/client/methods/HttpPost", AccessFlags = 33)]
public partial class HttpPost : global::Org.Apache.Http.Client.Methods.HttpEntityEnclosingRequestBase
/* scope: __dot42__ */
{
/// <java-name>
/// METHOD_NAME
/// </java-name>
[Dot42.DexImport("METHOD_NAME", "Ljava/lang/String;", AccessFlags = 25)]
public const string METHOD_NAME = "POST";
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public HttpPost() /* MethodBuilder.Create */
{
}
[Dot42.DexImport("<init>", "(Ljava/net/URI;)V", AccessFlags = 1)]
public HttpPost(global::System.Uri uri) /* MethodBuilder.Create */
{
}
[Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 1)]
public HttpPost(string uri) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Returns the HTTP method this request uses, such as <code>GET</code>, <code>PUT</code>, <code>POST</code>, or other. </para>
/// </summary>
/// <java-name>
/// getMethod
/// </java-name>
[Dot42.DexImport("getMethod", "()Ljava/lang/String;", AccessFlags = 1)]
public override string GetMethod() /* MethodBuilder.Create */
{
return default(string);
}
/// <summary>
/// <para>Returns the HTTP method this request uses, such as <code>GET</code>, <code>PUT</code>, <code>POST</code>, or other. </para>
/// </summary>
/// <java-name>
/// getMethod
/// </java-name>
public string Method
{
[Dot42.DexImport("getMethod", "()Ljava/lang/String;", AccessFlags = 1)]
get{ return GetMethod(); }
}
}
/// <summary>
/// <para>Extended version of the HttpRequest interface that provides convenience methods to access request properties such as request URI and method type.</para><para><para></para><para></para><title>Revision:</title><para>659191 </para></para><para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/client/methods/HttpUriRequest
/// </java-name>
[Dot42.DexImport("org/apache/http/client/methods/HttpUriRequest", AccessFlags = 1537)]
public partial interface IHttpUriRequest : global::Org.Apache.Http.IHttpRequest
/* scope: __dot42__ */
{
/// <summary>
/// <para>Returns the HTTP method this request uses, such as <code>GET</code>, <code>PUT</code>, <code>POST</code>, or other. </para>
/// </summary>
/// <java-name>
/// getMethod
/// </java-name>
[Dot42.DexImport("getMethod", "()Ljava/lang/String;", AccessFlags = 1025)]
string GetMethod() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Returns the URI this request uses, such as <code></code>. </para>
/// </summary>
/// <java-name>
/// getURI
/// </java-name>
[Dot42.DexImport("getURI", "()Ljava/net/URI;", AccessFlags = 1025)]
global::System.Uri GetURI() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Aborts execution of the request.</para><para></para>
/// </summary>
/// <java-name>
/// abort
/// </java-name>
[Dot42.DexImport("abort", "()V", AccessFlags = 1025)]
void Abort() /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Tests if the request execution has been aborted.</para><para></para>
/// </summary>
/// <returns>
/// <para><code>true</code> if the request execution has been aborted, <code>false</code> otherwise. </para>
/// </returns>
/// <java-name>
/// isAborted
/// </java-name>
[Dot42.DexImport("isAborted", "()Z", AccessFlags = 1025)]
bool IsAborted() /* MethodBuilder.Create */ ;
}
/// <summary>
/// <para>Interface representing an HTTP request that can be aborted by shutting down the underlying HTTP connection.</para><para><para></para><para></para><title>Revision:</title><para>639600 </para></para><para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/client/methods/AbortableHttpRequest
/// </java-name>
[Dot42.DexImport("org/apache/http/client/methods/AbortableHttpRequest", AccessFlags = 1537)]
public partial interface IAbortableHttpRequest
/* scope: __dot42__ */
{
/// <summary>
/// <para>Sets the ClientConnectionRequest callback that can be used to abort a long-lived request for a connection. If the request is already aborted, throws an IOException.</para><para><para>ClientConnectionManager </para><simplesectsep></simplesectsep><para>ThreadSafeClientConnManager </para></para>
/// </summary>
/// <java-name>
/// setConnectionRequest
/// </java-name>
[Dot42.DexImport("setConnectionRequest", "(Lorg/apache/http/conn/ClientConnectionRequest;)V", AccessFlags = 1025)]
void SetConnectionRequest(global::Org.Apache.Http.Conn.IClientConnectionRequest connRequest) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Sets the ConnectionReleaseTrigger callback that can be used to abort an active connection. Typically, this will be the ManagedClientConnection itself. If the request is already aborted, throws an IOException. </para>
/// </summary>
/// <java-name>
/// setReleaseTrigger
/// </java-name>
[Dot42.DexImport("setReleaseTrigger", "(Lorg/apache/http/conn/ConnectionReleaseTrigger;)V", AccessFlags = 1025)]
void SetReleaseTrigger(global::Org.Apache.Http.Conn.IConnectionReleaseTrigger releaseTrigger) /* MethodBuilder.Create */ ;
/// <summary>
/// <para>Aborts this http request. Any active execution of this method should return immediately. If the request has not started, it will abort after the next execution. Aborting this request will cause all subsequent executions with this request to fail.</para><para><para>HttpClient::execute(HttpUriRequest) </para><simplesectsep></simplesectsep><para>HttpClient::execute(org.apache.http.HttpHost, org.apache.http.HttpRequest) </para><simplesectsep></simplesectsep><para>HttpClient::execute(HttpUriRequest, org.apache.http.protocol.HttpContext) </para><simplesectsep></simplesectsep><para>HttpClient::execute(org.apache.http.HttpHost, org.apache.http.HttpRequest, org.apache.http.protocol.HttpContext) </para></para>
/// </summary>
/// <java-name>
/// abort
/// </java-name>
[Dot42.DexImport("abort", "()V", AccessFlags = 1025)]
void Abort() /* MethodBuilder.Create */ ;
}
/// <summary>
/// <para>HTTP GET method. </para><para>The HTTP GET method is defined in section 9.3 of : <blockquote><para>The GET method means retrieve whatever information (in the form of an entity) is identified by the Request-URI. If the Request-URI refers to a data-producing process, it is the produced data which shall be returned as the entity in the response and not the source text of the process, unless that text happens to be the output of the process. </para></blockquote></para><para>GetMethods will follow redirect requests from the http server by default. This behavour can be disabled by calling setFollowRedirects(false).</para><para><para></para><title>Revision:</title><para>664505 </para></para><para><para>4.0 </para></para>
/// </summary>
/// <java-name>
/// org/apache/http/client/methods/HttpGet
/// </java-name>
[Dot42.DexImport("org/apache/http/client/methods/HttpGet", AccessFlags = 33)]
public partial class HttpGet : global::Org.Apache.Http.Client.Methods.HttpRequestBase
/* scope: __dot42__ */
{
/// <java-name>
/// METHOD_NAME
/// </java-name>
[Dot42.DexImport("METHOD_NAME", "Ljava/lang/String;", AccessFlags = 25)]
public const string METHOD_NAME = "GET";
[Dot42.DexImport("<init>", "()V", AccessFlags = 1)]
public HttpGet() /* MethodBuilder.Create */
{
}
[Dot42.DexImport("<init>", "(Ljava/net/URI;)V", AccessFlags = 1)]
public HttpGet(global::System.Uri uri) /* MethodBuilder.Create */
{
}
[Dot42.DexImport("<init>", "(Ljava/lang/String;)V", AccessFlags = 1)]
public HttpGet(string uri) /* MethodBuilder.Create */
{
}
/// <summary>
/// <para>Returns the HTTP method this request uses, such as <code>GET</code>, <code>PUT</code>, <code>POST</code>, or other. </para>
/// </summary>
/// <java-name>
/// getMethod
/// </java-name>
[Dot42.DexImport("getMethod", "()Ljava/lang/String;", AccessFlags = 1)]
public override string GetMethod() /* MethodBuilder.Create */
{
return default(string);
}
/// <summary>
/// <para>Returns the HTTP method this request uses, such as <code>GET</code>, <code>PUT</code>, <code>POST</code>, or other. </para>
/// </summary>
/// <java-name>
/// getMethod
/// </java-name>
public string Method
{
[Dot42.DexImport("getMethod", "()Ljava/lang/String;", AccessFlags = 1)]
get{ return GetMethod(); }
}
}
}
| |
// 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;
#if ES_BUILD_STANDALONE
namespace Microsoft.Diagnostics.Tracing
#else
namespace System.Diagnostics.Tracing
#endif
{
/// <summary>
/// TraceLogging: Used when implementing a custom TraceLoggingTypeInfo.
/// These are passed to metadataCollector.Add to specify the low-level
/// type of a field in the event payload. Note that a "formatted"
/// TraceLoggingDataType consists of a core TraceLoggingDataType value
/// (a TraceLoggingDataType with a value less than 32) plus an OutType.
/// Any combination of TraceLoggingDataType + OutType is valid, but not
/// all are useful. In particular, combinations not explicitly listed
/// below are unlikely to be recognized by decoders, and will typically
/// be decoded as the corresponding core type (i.e. the decoder will
/// mask off any unrecognized OutType value).
/// </summary>
internal enum TraceLoggingDataType
{
/// <summary>
/// Core type.
/// Data type with no value (0-length payload).
/// NOTE: arrays of Nil are illegal.
/// NOTE: a fixed-length array of Nil is interpreted by the decoder as
/// a struct (obsolete but retained for backwards-compatibility).
/// </summary>
Nil = 0,
/// <summary>
/// Core type.
/// Encoding assumes null-terminated Char16 string.
/// Decoding treats as UTF-16LE string.
/// </summary>
Utf16String = 1,
/// <summary>
/// Core type.
/// Encoding assumes null-terminated Char8 string.
/// Decoding treats as MBCS string.
/// </summary>
MbcsString = 2,
/// <summary>
/// Core type.
/// Encoding assumes 8-bit value.
/// Decoding treats as signed integer.
/// </summary>
Int8 = 3,
/// <summary>
/// Core type.
/// Encoding assumes 8-bit value.
/// Decoding treats as unsigned integer.
/// </summary>
UInt8 = 4,
/// <summary>
/// Core type.
/// Encoding assumes 16-bit value.
/// Decoding treats as signed integer.
/// </summary>
Int16 = 5,
/// <summary>
/// Core type.
/// Encoding assumes 16-bit value.
/// Decoding treats as unsigned integer.
/// </summary>
UInt16 = 6,
/// <summary>
/// Core type.
/// Encoding assumes 32-bit value.
/// Decoding treats as signed integer.
/// </summary>
Int32 = 7,
/// <summary>
/// Core type.
/// Encoding assumes 32-bit value.
/// Decoding treats as unsigned integer.
/// </summary>
UInt32 = 8,
/// <summary>
/// Core type.
/// Encoding assumes 64-bit value.
/// Decoding treats as signed integer.
/// </summary>
Int64 = 9,
/// <summary>
/// Core type.
/// Encoding assumes 64-bit value.
/// Decoding treats as unsigned integer.
/// </summary>
UInt64 = 10,
/// <summary>
/// Core type.
/// Encoding assumes 32-bit value.
/// Decoding treats as Float.
/// </summary>
Float = 11,
/// <summary>
/// Core type.
/// Encoding assumes 64-bit value.
/// Decoding treats as Double.
/// </summary>
Double = 12,
/// <summary>
/// Core type.
/// Encoding assumes 32-bit value.
/// Decoding treats as Boolean.
/// </summary>
Boolean32 = 13,
/// <summary>
/// Core type.
/// Encoding assumes 16-bit bytecount followed by binary data.
/// Decoding treats as binary data.
/// </summary>
Binary = 14,
/// <summary>
/// Core type.
/// Encoding assumes 16-byte value.
/// Decoding treats as GUID.
/// </summary>
Guid = 15,
/// <summary>
/// Core type.
/// Encoding assumes 64-bit value.
/// Decoding treats as FILETIME.
/// </summary>
FileTime = 17,
/// <summary>
/// Core type.
/// Encoding assumes 16-byte value.
/// Decoding treats as SYSTEMTIME.
/// </summary>
SystemTime = 18,
/// <summary>
/// Core type.
/// Encoding assumes 32-bit value.
/// Decoding treats as hexadecimal unsigned integer.
/// </summary>
HexInt32 = 20,
/// <summary>
/// Core type.
/// Encoding assumes 64-bit value.
/// Decoding treats as hexadecimal unsigned integer.
/// </summary>
HexInt64 = 21,
/// <summary>
/// Core type.
/// Encoding assumes 16-bit bytecount followed by Char16 data.
/// Decoding treats as UTF-16LE string.
/// </summary>
CountedUtf16String = 22,
/// <summary>
/// Core type.
/// Encoding assumes 16-bit bytecount followed by Char8 data.
/// Decoding treats as MBCS string.
/// </summary>
CountedMbcsString = 23,
/// <summary>
/// Core type.
/// Special case: Struct indicates that this field plus the the
/// subsequent N logical fields are to be considered as one logical
/// field (i.e. a nested structure). The OutType is used to encode N.
/// The maximum value for N is 127. This field has no payload by
/// itself, but logically contains the payload of the following N
/// fields. It is legal to have an array of Struct.
/// </summary>
Struct = 24,
/// <summary>
/// Formatted type.
/// Encoding assumes 16-bit value.
/// Decoding treats as UTF-16LE character.
/// </summary>
Char16 = UInt16 + (EventFieldFormat.String << 8),
/// <summary>
/// Formatted type.
/// Encoding assumes 8-bit value.
/// Decoding treats as character.
/// </summary>
Char8 = UInt8 + (EventFieldFormat.String << 8),
/// <summary>
/// Formatted type.
/// Encoding assumes 8-bit value.
/// Decoding treats as Boolean.
/// </summary>
Boolean8 = UInt8 + (EventFieldFormat.Boolean << 8),
/// <summary>
/// Formatted type.
/// Encoding assumes 8-bit value.
/// Decoding treats as hexadecimal unsigned integer.
/// </summary>
HexInt8 = UInt8 + (EventFieldFormat.Hexadecimal << 8),
/// <summary>
/// Formatted type.
/// Encoding assumes 16-bit value.
/// Decoding treats as hexadecimal unsigned integer.
/// </summary>
HexInt16 = UInt16 + (EventFieldFormat.Hexadecimal << 8),
#if false
/// <summary>
/// Formatted type.
/// Encoding assumes 32-bit value.
/// Decoding treats as process identifier.
/// </summary>
ProcessId = UInt32 + (EventSourceFieldFormat.ProcessId << 8),
/// <summary>
/// Formatted type.
/// Encoding assumes 32-bit value.
/// Decoding treats as thread identifier.
/// </summary>
ThreadId = UInt32 + (EventSourceFieldFormat.ThreadId << 8),
/// <summary>
/// Formatted type.
/// Encoding assumes 16-bit value.
/// Decoding treats as IP port.
/// </summary>
Port = UInt16 + (EventSourceFieldFormat.Port << 8),
/// <summary>
/// Formatted type.
/// Encoding assumes 32-bit value.
/// Decoding treats as IPv4 address.
/// </summary>
Ipv4Address = UInt32 + (EventSourceFieldFormat.Ipv4Address << 8),
/// <summary>
/// Formatted type.
/// Encoding assumes 16-bit bytecount followed by binary data.
/// Decoding treats as IPv6 address.
/// </summary>
Ipv6Address = Binary + (EventSourceFieldFormat.Ipv6Address << 8),
/// <summary>
/// Formatted type.
/// Encoding assumes 16-bit bytecount followed by binary data.
/// Decoding treats as SOCKADDR.
/// </summary>
SocketAddress = Binary + (EventSourceFieldFormat.SocketAddress << 8),
#endif
/// <summary>
/// Formatted type.
/// Encoding assumes null-terminated Char16 string.
/// Decoding treats as UTF-16LE XML string.
/// </summary>
Utf16Xml = Utf16String + (EventFieldFormat.Xml << 8),
/// <summary>
/// Formatted type.
/// Encoding assumes null-terminated Char8 string.
/// Decoding treats as MBCS XML string.
/// </summary>
MbcsXml = MbcsString + (EventFieldFormat.Xml << 8),
/// <summary>
/// Formatted type.
/// Encoding assumes 16-bit bytecount followed by Char16 data.
/// Decoding treats as UTF-16LE XML.
/// </summary>
CountedUtf16Xml = CountedUtf16String + (EventFieldFormat.Xml << 8),
/// <summary>
/// Formatted type.
/// Encoding assumes 16-bit bytecount followed by Char8 data.
/// Decoding treats as MBCS XML.
/// </summary>
CountedMbcsXml = CountedMbcsString + (EventFieldFormat.Xml << 8),
/// <summary>
/// Formatted type.
/// Encoding assumes null-terminated Char16 string.
/// Decoding treats as UTF-16LE JSON string.
/// </summary>
Utf16Json = Utf16String + (EventFieldFormat.Json << 8),
/// <summary>
/// Formatted type.
/// Encoding assumes null-terminated Char8 string.
/// Decoding treats as MBCS JSON string.
/// </summary>
MbcsJson = MbcsString + (EventFieldFormat.Json << 8),
/// <summary>
/// Formatted type.
/// Encoding assumes 16-bit bytecount followed by Char16 data.
/// Decoding treats as UTF-16LE JSON.
/// </summary>
CountedUtf16Json = CountedUtf16String + (EventFieldFormat.Json << 8),
/// <summary>
/// Formatted type.
/// Encoding assumes 16-bit bytecount followed by Char8 data.
/// Decoding treats as MBCS JSON.
/// </summary>
CountedMbcsJson = CountedMbcsString + (EventFieldFormat.Json << 8),
#if false
/// <summary>
/// Formatted type.
/// Encoding assumes 32-bit value.
/// Decoding treats as Win32 error.
/// </summary>
Win32Error = UInt32 + (EventSourceFieldFormat.Win32Error << 8),
/// <summary>
/// Formatted type.
/// Encoding assumes 32-bit value.
/// Decoding treats as NTSTATUS.
/// </summary>
NTStatus = UInt32 + (EventSourceFieldFormat.NTStatus << 8),
#endif
/// <summary>
/// Formatted type.
/// Encoding assumes 32-bit value.
/// Decoding treats as HRESULT.
/// </summary>
HResult = Int32 + (EventFieldFormat.HResult << 8)
}
}
| |
#region License
/*
* Copyright 2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#endregion
#if !MONO
#region Imports
using System;
using System.Collections;
using System.EnterpriseServices;
using System.IO;
using System.Reflection;
using System.Reflection.Emit;
using AopAlliance.Intercept;
using NUnit.Framework;
using Spring.Context;
using Spring.Context.Support;
using Spring.Objects;
#endregion
namespace Spring.EnterpriseServices
{
/// <summary>
/// Unit tests for the ServicedComponentExporter class.
/// </summary>
/// <author>Bruno Baia</author>
[TestFixture]
public class ServicedComponentExporterTests
{
[TearDown]
public void TearDown()
{
ContextRegistry.Clear();
}
[Test]
public void BailsWhenNotConfigured()
{
ServicedComponentExporter exp = new ServicedComponentExporter();
try
{
exp.AfterPropertiesSet();
Assert.Fail("Did not throw expected ArgumentException!");
}
catch (ArgumentException)
{
}
}
[Test]
public void RegistersSimpleObjectWithNonDefaultTransactionOption()
{
ServicedComponentExporter exp = new ServicedComponentExporter();
exp.TargetName = "objectTest";
exp.ObjectName = "objectTestProxy";
exp.TypeAttributes = new ArrayList();
exp.TypeAttributes.Add(new TransactionAttribute(TransactionOption.RequiresNew));
exp.AfterPropertiesSet();
Type type = CreateWrapperType(exp, typeof(TestObject), false);
TransactionAttribute[] attrs = (TransactionAttribute[])type.GetCustomAttributes(typeof(TransactionAttribute), false);
Assert.AreEqual(1, attrs.Length);
Assert.AreEqual(TransactionOption.RequiresNew, attrs[0].Value);
}
[Test]
public void RegistersManagedObjectWithNonDefaultTransactionOption()
{
ServicedComponentExporter exp = new ServicedComponentExporter();
exp.TargetName = "objectTest";
exp.ObjectName = "objectTestProxy";
exp.TypeAttributes = new ArrayList();
exp.TypeAttributes.Add(new TransactionAttribute(TransactionOption.RequiresNew));
exp.AfterPropertiesSet();
Type type = CreateWrapperType(exp, typeof(TestObject), true);
TransactionAttribute[] attrs = (TransactionAttribute[])type.GetCustomAttributes(typeof(TransactionAttribute), false);
Assert.AreEqual(1, attrs.Length);
Assert.AreEqual(TransactionOption.RequiresNew, attrs[0].Value);
}
[Test]
[Explicit("causes troubles due to registry pollution by COM registration")]
public void CanExportAopProxyToLibrary()
{
// NOTE: the method interceptor will return the number of method calls intercepted
FileInfo assemblyFile = new FileInfo("ServiceComponentExporterTests.TestServicedComponents.dll");
XmlApplicationContext appCtx = new XmlApplicationContext("ServiceComponentExporterTests.TestServicedComponents.Services.xml");
EnterpriseServicesExporter exporter = new EnterpriseServicesExporter();
exporter.ActivationMode = ActivationOption.Library;
Type serviceType = ExportObject(exporter, assemblyFile, appCtx, "objectTest");
try
{
// ServiceComponent will obtain its target from root context
// ContextRegistry.RegisterContext(appCtx);
IComparable testObject;
testObject = (IComparable)Activator.CreateInstance(serviceType);
Assert.AreEqual(1, testObject.CompareTo(null));
testObject = (IComparable)Activator.CreateInstance(serviceType);
Assert.AreEqual(2, testObject.CompareTo(null));
}
finally
{
exporter.UnregisterServicedComponents(assemblyFile);
ContextRegistry.Clear();
}
}
[Test, Explicit("causes troubles due to registry pollution by COM registration")]
public void CanExportAopProxyToServer()
{
FileInfo assemblyFile = new FileInfo("ServiceComponentExporterTests.TestServicedComponents.exe");
XmlApplicationContext appCtx = new XmlApplicationContext("ServiceComponentExporterTests.TestServicedComponents.Services.xml");
EnterpriseServicesExporter exporter = new EnterpriseServicesExporter();
exporter.ActivationMode = ActivationOption.Server;
Type serviceType = ExportObject(exporter, assemblyFile, appCtx, "objectTest");
try
{
// ServiceComponent will obtain its target from root context
IComparable testObject;
testObject = (IComparable)Activator.CreateInstance(serviceType);
Assert.AreEqual(1, testObject.CompareTo(null));
testObject = (IComparable)Activator.CreateInstance(serviceType);
Assert.AreEqual(2, testObject.CompareTo(null));
}
finally
{
exporter.UnregisterServicedComponents(assemblyFile);
}
}
private Type ExportObject(EnterpriseServicesExporter exporter, FileInfo assemblyFile, IConfigurableApplicationContext appCtx, string objectName)
{
exporter.ObjectFactory = appCtx.ObjectFactory;
exporter.Assembly = Path.GetFileNameWithoutExtension(assemblyFile.Name);
exporter.ApplicationName = exporter.Assembly;
exporter.AccessControl = new ApplicationAccessControlAttribute(false);
exporter.UseSpring = true;
ServicedComponentExporter exp = new ServicedComponentExporter();
exp.TargetName = objectName;
exp.ObjectName = objectName + "Service";
exp.TypeAttributes = new ArrayList();
exp.TypeAttributes.Add(new TransactionAttribute(TransactionOption.RequiresNew));
exp.AfterPropertiesSet();
exporter.Components.Add(exp);
Assembly assembly = exporter.GenerateComponentAssembly(assemblyFile);
exporter.RegisterServicedComponents(assemblyFile);
return assembly.GetType(objectName + "Service");
}
#region Private helpers & classes
public class CountingMethodInterceptor : IMethodInterceptor
{
private int Calls = 0;
public object Invoke(IMethodInvocation invocation)
{
Calls++;
return Calls;
}
}
private Type CreateWrapperType(ServicedComponentExporter exporter, Type targetType, bool useSpring)
{
AssemblyName an = new AssemblyName();
an.Name = "Spring.EnterpriseServices.Tests";
AssemblyBuilder proxyAssembly = AppDomain.CurrentDomain.DefineDynamicAssembly(an, AssemblyBuilderAccess.RunAndSave);
ModuleBuilder module = proxyAssembly.DefineDynamicModule(an.Name, an.Name + ".dll", true);
Type baseType = typeof(ServicedComponent);
if (useSpring)
{
baseType = EnterpriseServicesExporter.CreateSpringServicedComponentType(module, baseType);
}
object result = exporter.CreateWrapperType(module, baseType, targetType, useSpring);
Assert.IsNotNull(result);
Assert.IsTrue(result is Type);
return (Type)result;
}
#endregion
}
}
#endif // !MONO
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Threading;
interface IGen<T>
{
void Target();
T Dummy(T t);
}
struct GenInt : IGen<int>
{
public int Dummy(int t) { return t; }
public void Target()
{
Interlocked.Increment(ref Test.Xcounter);
}
public static void ThreadPoolTest()
{
Thread[] threads = new Thread[Test.nThreads];
IGen<int> obj = new GenInt();
for (int i = 0; i < Test.nThreads; i++)
{
threads[i] = new Thread(new ThreadStart(obj.Target));
threads[i].Start();
}
for (int i = 0; i < Test.nThreads; i++)
{
threads[i].Join();
}
Test.Eval(Test.Xcounter==Test.nThreads);
Test.Xcounter = 0;
}
}
struct GenDouble : IGen<double>
{
public double Dummy(double t) { return t; }
public void Target()
{
Interlocked.Increment(ref Test.Xcounter);
}
public static void ThreadPoolTest()
{
Thread[] threads = new Thread[Test.nThreads];
IGen<double> obj = new GenDouble();
for (int i = 0; i < Test.nThreads; i++)
{
threads[i] = new Thread(new ThreadStart(obj.Target));
threads[i].Start();
}
for (int i = 0; i < Test.nThreads; i++)
{
threads[i].Join();
}
Test.Eval(Test.Xcounter==Test.nThreads);
Test.Xcounter = 0;
}
}
struct GenString : IGen<string>
{
public string Dummy(string t) { return t; }
public void Target()
{
Interlocked.Increment(ref Test.Xcounter);
}
public static void ThreadPoolTest()
{
Thread[] threads = new Thread[Test.nThreads];
IGen<string> obj = new GenString();
for (int i = 0; i < Test.nThreads; i++)
{
threads[i] = new Thread(new ThreadStart(obj.Target));
threads[i].Start();
}
for (int i = 0; i < Test.nThreads; i++)
{
threads[i].Join();
}
Test.Eval(Test.Xcounter==Test.nThreads);
Test.Xcounter = 0;
}
}
struct GenObject : IGen<object>
{
public object Dummy(object t) { return t; }
public void Target()
{
Interlocked.Increment(ref Test.Xcounter);
}
public static void ThreadPoolTest()
{
Thread[] threads = new Thread[Test.nThreads];
IGen<object> obj = new GenObject();
for (int i = 0; i < Test.nThreads; i++)
{
threads[i] = new Thread(new ThreadStart(obj.Target));
threads[i].Start();
}
for (int i = 0; i < Test.nThreads; i++)
{
threads[i].Join();
}
Test.Eval(Test.Xcounter==Test.nThreads);
Test.Xcounter = 0;
}
}
struct GenGuid : IGen<Guid>
{
public Guid Dummy(Guid t) { return t; }
public void Target()
{
Interlocked.Increment(ref Test.Xcounter);
}
public static void ThreadPoolTest()
{
Thread[] threads = new Thread[Test.nThreads];
IGen<Guid> obj = new GenGuid();
for (int i = 0; i < Test.nThreads; i++)
{
threads[i] = new Thread(new ThreadStart(obj.Target));
threads[i].Start();
}
for (int i = 0; i < Test.nThreads; i++)
{
threads[i].Join();
}
Test.Eval(Test.Xcounter==Test.nThreads);
Test.Xcounter = 0;
}
}
public class Test
{
public static int nThreads =50;
public static int counter = 0;
public static int Xcounter = 0;
public static bool result = true;
public static void Eval(bool exp)
{
counter++;
if (!exp)
{
result = exp;
Console.WriteLine("Test Failed at location: " + counter);
}
}
public static int Main()
{
GenInt.ThreadPoolTest();
GenDouble.ThreadPoolTest();
GenString.ThreadPoolTest();
GenObject.ThreadPoolTest();
GenGuid.ThreadPoolTest();
if (result)
{
Console.WriteLine("Test Passed");
return 100;
}
else
{
Console.WriteLine("Test Failed");
return 1;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using Xunit;
namespace System.Reflection.Emit.Tests
{
[AttributeUsage(AttributeTargets.All, AllowMultiple = false)]
public class BoolAllAttribute : Attribute
{
private bool _s;
public BoolAllAttribute(bool s) { _s = s; }
}
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
public class IntClassAttribute : Attribute
{
public int i;
public IntClassAttribute(int i) { this.i = i; }
}
public class AssemblyTests
{
public static IEnumerable<object[]> DefineDynamicAssembly_TestData()
{
foreach (AssemblyBuilderAccess access in new AssemblyBuilderAccess[] { AssemblyBuilderAccess.Run, AssemblyBuilderAccess.RunAndCollect })
{
yield return new object[] { new AssemblyName("TestName") { Version = new Version(0, 0, 0, 0) }, access };
yield return new object[] { new AssemblyName("testname") { Version = new Version(1, 2, 3, 4) }, access };
yield return new object[] { new AssemblyName("class") { Version = new Version(0, 0, 0, 0) }, access };
yield return new object[] { new AssemblyName("\uD800\uDC00") { Version = new Version(0, 0, 0, 0) }, access };
}
}
[Theory]
[MemberData(nameof(DefineDynamicAssembly_TestData))]
public void DefineDynamicAssembly_AssemblyName_AssemblyBuilderAccess(AssemblyName name, AssemblyBuilderAccess access)
{
AssemblyBuilder assembly = AssemblyBuilder.DefineDynamicAssembly(name, access);
VerifyAssemblyBuilder(assembly, name, new CustomAttributeBuilder[0]);
}
public static IEnumerable<object[]> DefineDynamicAssembly_CustomAttributes_TestData()
{
foreach (object[] data in DefineDynamicAssembly_TestData())
{
yield return new object[] { data[0], data[1], null };
yield return new object[] { data[0], data[1], new CustomAttributeBuilder[0] };
ConstructorInfo constructor = typeof(IntClassAttribute).GetConstructor(new Type[] { typeof(int) });
yield return new object[] { data[0], data[1], new CustomAttributeBuilder[] { new CustomAttributeBuilder(constructor, new object[] { 10 }) } };
}
}
[Theory]
[MemberData(nameof(DefineDynamicAssembly_CustomAttributes_TestData))]
public void DefineDynamicAssembly_AssemblyName_AssemblyBuilderAccess_CustomAttributeBuilder(AssemblyName name, AssemblyBuilderAccess access, IEnumerable<CustomAttributeBuilder> attributes)
{
AssemblyBuilder assembly = AssemblyBuilder.DefineDynamicAssembly(name, access, attributes);
VerifyAssemblyBuilder(assembly, name, attributes);
}
[Fact]
public void DefineDynamicAssembly_NullName_ThrowsArgumentNullException()
{
Assert.Throws<ArgumentNullException>("name", () => AssemblyBuilder.DefineDynamicAssembly(null, AssemblyBuilderAccess.Run));
Assert.Throws<ArgumentNullException>("name", () => AssemblyBuilder.DefineDynamicAssembly(null, AssemblyBuilderAccess.Run, new CustomAttributeBuilder[0]));
}
[Theory]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "The coreclr doesn't support Save or ReflectionOnly AssemblyBuilders.")]
[InlineData((AssemblyBuilderAccess)2)] // Save (not supported)
[InlineData((AssemblyBuilderAccess)2 | AssemblyBuilderAccess.Run)] // RunAndSave (not supported)
[InlineData((AssemblyBuilderAccess)6)] // ReflectionOnly (not supported)
public void DefineDynamicAssembly_CoreclrNotSupportedAccess_ThrowsArgumentException(AssemblyBuilderAccess access)
{
DefineDynamicAssembly_InvalidAccess_ThrowsArgumentException(access);
}
[Theory]
[InlineData((AssemblyBuilderAccess)(-1))]
[InlineData((AssemblyBuilderAccess)0)]
[InlineData((AssemblyBuilderAccess)10)]
[InlineData((AssemblyBuilderAccess)int.MaxValue)]
public void DefineDynamicAssembly_InvalidAccess_ThrowsArgumentException(AssemblyBuilderAccess access)
{
Assert.Throws<ArgumentException>("access", () => AssemblyBuilder.DefineDynamicAssembly(new AssemblyName("Name"), access));
Assert.Throws<ArgumentException>("access", () => AssemblyBuilder.DefineDynamicAssembly(new AssemblyName("Name"), access, new CustomAttributeBuilder[0]));
}
[Fact]
public void DefineDynamicAssembly_NameIsCopy()
{
AssemblyName name = new AssemblyName("Name") { Version = new Version(0, 0, 0, 0) };
AssemblyBuilder assembly = AssemblyBuilder.DefineDynamicAssembly(name, AssemblyBuilderAccess.Run);
Assert.StartsWith(name.ToString(), assembly.FullName);
name.Name = "NewName";
Assert.False(assembly.FullName.StartsWith(name.ToString()));
}
public static IEnumerable<object[]> DefineDynamicModule_TestData()
{
yield return new object[] { "Module" };
yield return new object[] { "module" };
yield return new object[] { "class" };
yield return new object[] { "\uD800\uDC00" };
yield return new object[] { new string('a', 259) };
}
[Theory]
[MemberData(nameof(DefineDynamicModule_TestData))]
public void DefineDynamicModule(string name)
{
AssemblyBuilder assembly = Helpers.DynamicAssembly();
ModuleBuilder module = assembly.DefineDynamicModule(name);
Assert.Equal(assembly, module.Assembly);
Assert.Empty(module.CustomAttributes);
Assert.Equal("<In Memory Module>", module.Name);
// The coreclr ignores the name passed to AssemblyBuilder.DefineDynamicModule
if (PlatformDetection.IsFullFramework)
{
Assert.Equal(name, module.FullyQualifiedName);
}
else
{
Assert.Equal("RefEmit_InMemoryManifestModule", module.FullyQualifiedName);
}
Assert.Equal(module, assembly.GetDynamicModule(module.FullyQualifiedName));
}
[Fact]
public void DefineDynamicModule_NullName_ThrowsArgumentNullException()
{
AssemblyBuilder assembly = Helpers.DynamicAssembly();
Assert.Throws<ArgumentNullException>("name", () => assembly.DefineDynamicModule(null));
}
[Theory]
[InlineData("")]
[InlineData("\0test")]
public void DefineDynamicModule_InvalidName_ThrowsArgumentException(string name)
{
AssemblyBuilder assembly = Helpers.DynamicAssembly();
Assert.Throws<ArgumentException>("name", () => assembly.DefineDynamicModule(name));
}
[Fact]
[SkipOnTargetFramework(~TargetFrameworkMonikers.NetFramework, "The coreclr only supports AssemblyBuilders with one module.")]
public void DefineDynamicModule_NetFxModuleAlreadyDefined_ThrowsInvalidOperationException()
{
AssemblyBuilder assembly = Helpers.DynamicAssembly();
assembly.DefineDynamicModule("module1");
assembly.DefineDynamicModule("module2");
Assert.Throws<ArgumentException>(null, () => assembly.DefineDynamicModule("module1"));
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "The coreclr only supports AssemblyBuilders with one module.")]
public void DefineDynamicModule_CoreFxModuleAlreadyDefined_ThrowsInvalidOperationException()
{
AssemblyBuilder assembly = Helpers.DynamicAssembly();
assembly.DefineDynamicModule("module1");
Assert.Throws<InvalidOperationException>(() => assembly.DefineDynamicModule("module1"));
Assert.Throws<InvalidOperationException>(() => assembly.DefineDynamicModule("module2"));
}
[Fact]
public void GetManifestResourceNames_ThrowsNotSupportedException()
{
AssemblyBuilder assembly = Helpers.DynamicAssembly();
Assert.Throws<NotSupportedException>(() => assembly.GetManifestResourceNames());
}
[Fact]
public void GetManifestResourceStream_ThrowsNotSupportedException()
{
AssemblyBuilder assembly = Helpers.DynamicAssembly();
Assert.Throws<NotSupportedException>(() => assembly.GetManifestResourceStream(""));
}
[Fact]
public void GetManifestResourceInfo_ThrowsNotSupportedException()
{
AssemblyBuilder assembly = Helpers.DynamicAssembly();
Assert.Throws<NotSupportedException>(() => assembly.GetManifestResourceInfo(""));
}
[Fact]
public void ExportedTypes_ThrowsNotSupportedException()
{
AssemblyBuilder assembly = Helpers.DynamicAssembly();
Assert.Throws<NotSupportedException>(() => assembly.ExportedTypes);
Assert.Throws<NotSupportedException>(() => assembly.GetExportedTypes());
}
[Theory]
[InlineData("testmodule")]
[InlineData("\0test")]
public void GetDynamicModule_NoSuchModule_ReturnsNull(string name)
{
AssemblyBuilder assembly = Helpers.DynamicAssembly();
assembly.DefineDynamicModule("TestModule");
Assert.Null(assembly.GetDynamicModule(name));
}
[Fact]
public void GetDynamicModule_InvalidName_ThrowsArgumentException()
{
AssemblyBuilder assembly = Helpers.DynamicAssembly();
Assert.Throws<ArgumentNullException>("name", () => assembly.GetDynamicModule(null));
Assert.Throws<ArgumentException>("name", () => assembly.GetDynamicModule(""));
}
[Theory]
[InlineData(AssemblyBuilderAccess.Run)]
[InlineData(AssemblyBuilderAccess.RunAndCollect)]
public void SetCustomAttribute_ConstructorBuidler_ByteArray(AssemblyBuilderAccess access)
{
AssemblyBuilder assembly = Helpers.DynamicAssembly(access: access);
ConstructorInfo constructor = typeof(BoolAllAttribute).GetConstructor(new Type[] { typeof(bool) });
assembly.SetCustomAttribute(constructor, new byte[] { 1, 0, 1 });
IEnumerable<Attribute> attributes = assembly.GetCustomAttributes();
Assert.IsType<BoolAllAttribute>(attributes.First());
}
[Fact]
public void SetCustomAttribute_ConstructorBuidler_ByteArray_NullConstructorBuilder_ThrowsArgumentNullException()
{
AssemblyBuilder assembly = Helpers.DynamicAssembly();
Assert.Throws<ArgumentNullException>("con", () => assembly.SetCustomAttribute(null, new byte[0]));
}
[Fact]
public void SetCustomAttribute_ConstructorBuidler_ByteArray_NullByteArray_ThrowsArgumentNullException()
{
AssemblyBuilder assembly = Helpers.DynamicAssembly();
ConstructorInfo constructor = typeof(IntAllAttribute).GetConstructor(new Type[] { typeof(int) });
Assert.Throws<ArgumentNullException>("binaryAttribute", () => assembly.SetCustomAttribute(constructor, null));
}
[Theory]
[InlineData(AssemblyBuilderAccess.Run)]
[InlineData(AssemblyBuilderAccess.RunAndCollect)]
public void SetCustomAttribute_CustomAttributeBuilder(AssemblyBuilderAccess access)
{
AssemblyBuilder assembly = Helpers.DynamicAssembly(access: access);
ConstructorInfo constructor = typeof(IntClassAttribute).GetConstructor(new Type[] { typeof(int) });
CustomAttributeBuilder attributeBuilder = new CustomAttributeBuilder(constructor, new object[] { 5 });
assembly.SetCustomAttribute(attributeBuilder);
IEnumerable<Attribute> attributes = assembly.GetCustomAttributes();
Assert.IsType<IntClassAttribute>(attributes.First());
}
[Fact]
public void SetCustomAttribute_CustomAttributeBuilder_NullAttributeBuilder_ThrowsArgumentNullException()
{
AssemblyBuilder assembly = Helpers.DynamicAssembly();
Assert.Throws<ArgumentNullException>("customBuilder", () => assembly.SetCustomAttribute(null));
}
public static IEnumerable<object[]> Equals_TestData()
{
AssemblyBuilder assembly = Helpers.DynamicAssembly(name: "Name1");
yield return new object[] { assembly, assembly, true };
yield return new object[] { assembly, Helpers.DynamicAssembly("Name1"), false };
yield return new object[] { assembly, Helpers.DynamicAssembly("Name2"), false };
yield return new object[] { assembly, Helpers.DynamicAssembly("Name1", access: AssemblyBuilderAccess.RunAndCollect), false };
yield return new object[] { assembly, new object(), false };
yield return new object[] { assembly, null, false };
}
[Theory]
[MemberData(nameof(Equals_TestData))]
public void Equals(AssemblyBuilder assembly, object obj, bool expected)
{
Assert.Equal(expected, assembly.Equals(obj));
if (obj is AssemblyBuilder)
{
Assert.Equal(expected, assembly.GetHashCode().Equals(obj.GetHashCode()));
}
}
public static void VerifyAssemblyBuilder(AssemblyBuilder assembly, AssemblyName name, IEnumerable<CustomAttributeBuilder> attributes)
{
Assert.StartsWith(name.ToString(), assembly.FullName);
Assert.StartsWith(name.ToString(), assembly.GetName().ToString());
Assert.True(assembly.IsDynamic);
Assert.Equal(attributes?.Count() ?? 0, assembly.CustomAttributes.Count());
Assert.Equal(1, assembly.Modules.Count());
Module module = assembly.Modules.First();
Assert.NotEmpty(module.Name);
Assert.Equal(assembly.Modules, assembly.GetModules());
Assert.Empty(assembly.DefinedTypes);
Assert.Empty(assembly.GetTypes());
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.SignalR.Internal;
using Moq;
using Xunit;
namespace Microsoft.AspNetCore.SignalR.Tests
{
public class ClientHubProxyTests
{
public class FakeHub : Hub
{
}
[Fact]
public async Task UserProxy_SendAsync_ArrayArgumentNotExpanded()
{
object[] resultArgs = null;
var o = new Mock<HubLifetimeManager<FakeHub>>();
o.Setup(m => m.SendUserAsync(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<object[]>(), It.IsAny<CancellationToken>()))
.Callback<string, string, object[], CancellationToken>((userId, methodName, args, _) => { resultArgs = args; })
.Returns(Task.CompletedTask);
var proxy = new UserProxy<FakeHub>(o.Object, string.Empty);
var data = Encoding.UTF8.GetBytes("Hello world");
await proxy.SendAsync("Method", data);
Assert.NotNull(resultArgs);
var arg = (byte[]) Assert.Single(resultArgs);
Assert.Same(data, arg);
}
[Fact]
public async Task MultipleUserProxy_SendAsync_ArrayArgumentNotExpanded()
{
object[] resultArgs = null;
var o = new Mock<HubLifetimeManager<FakeHub>>();
o.Setup(m => m.SendUsersAsync(It.IsAny<IReadOnlyList<string>>(), It.IsAny<string>(), It.IsAny<object[]>(), It.IsAny<CancellationToken>()))
.Callback<IReadOnlyList<string>, string, object[], CancellationToken>((userIds, methodName, args, _) => { resultArgs = args; })
.Returns(Task.CompletedTask);
var proxy = new MultipleUserProxy<FakeHub>(o.Object, new List<string>());
var data = Encoding.UTF8.GetBytes("Hello world");
await proxy.SendAsync("Method", data);
Assert.NotNull(resultArgs);
var arg = (byte[])Assert.Single(resultArgs);
Assert.Same(data, arg);
}
[Fact]
public async Task GroupProxy_SendAsync_ArrayArgumentNotExpanded()
{
object[] resultArgs = null;
var o = new Mock<HubLifetimeManager<FakeHub>>();
o.Setup(m => m.SendGroupAsync(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<object[]>(), It.IsAny<CancellationToken>()))
.Callback<string, string, object[], CancellationToken>((groupName, methodName, args, _) => { resultArgs = args; })
.Returns(Task.CompletedTask);
var proxy = new GroupProxy<FakeHub>(o.Object, string.Empty);
var data = Encoding.UTF8.GetBytes("Hello world");
await proxy.SendAsync("Method", data);
Assert.NotNull(resultArgs);
var arg = (byte[])Assert.Single(resultArgs);
Assert.Same(data, arg);
}
[Fact]
public async Task MultipleGroupProxy_SendAsync_ArrayArgumentNotExpanded()
{
object[] resultArgs = null;
var o = new Mock<HubLifetimeManager<FakeHub>>();
o.Setup(m => m.SendGroupsAsync(It.IsAny<IReadOnlyList<string>>(), It.IsAny<string>(), It.IsAny<object[]>(), It.IsAny<CancellationToken>()))
.Callback<IReadOnlyList<string>, string, object[], CancellationToken>((groupNames, methodName, args, _) => { resultArgs = args; })
.Returns(Task.CompletedTask);
var proxy = new MultipleGroupProxy<FakeHub>(o.Object, new List<string>());
var data = Encoding.UTF8.GetBytes("Hello world");
await proxy.SendAsync("Method", data);
Assert.NotNull(resultArgs);
var arg = (byte[])Assert.Single(resultArgs);
Assert.Same(data, arg);
}
[Fact]
public async Task GroupExceptProxy_SendAsync_ArrayArgumentNotExpanded()
{
object[] resultArgs = null;
var o = new Mock<HubLifetimeManager<FakeHub>>();
o.Setup(m => m.SendGroupExceptAsync(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<object[]>(), It.IsAny<IReadOnlyList<string>>(), It.IsAny<CancellationToken>()))
.Callback<string, string, object[], IReadOnlyList<string>, CancellationToken>((groupName, methodName, args, excludedConnectionIds, _) => { resultArgs = args; })
.Returns(Task.CompletedTask);
var proxy = new GroupExceptProxy<FakeHub>(o.Object, string.Empty, new List<string>());
var data = Encoding.UTF8.GetBytes("Hello world");
await proxy.SendAsync("Method", data);
Assert.NotNull(resultArgs);
var arg = (byte[])Assert.Single(resultArgs);
Assert.Same(data, arg);
}
[Fact]
public async Task AllClientProxy_SendAsync_ArrayArgumentNotExpanded()
{
object[] resultArgs = null;
var o = new Mock<HubLifetimeManager<FakeHub>>();
o.Setup(m => m.SendAllAsync(It.IsAny<string>(), It.IsAny<object[]>(), It.IsAny<CancellationToken>()))
.Callback<string, object[], CancellationToken>((methodName, args, _) => { resultArgs = args; })
.Returns(Task.CompletedTask);
var proxy = new AllClientProxy<FakeHub>(o.Object);
var data = Encoding.UTF8.GetBytes("Hello world");
await proxy.SendAsync("Method", data);
Assert.NotNull(resultArgs);
var arg = (byte[])Assert.Single(resultArgs);
Assert.Same(data, arg);
}
[Fact]
public async Task AllClientsExceptProxy_SendAsync_ArrayArgumentNotExpanded()
{
object[] resultArgs = null;
var o = new Mock<HubLifetimeManager<FakeHub>>();
o.Setup(m => m.SendAllExceptAsync(It.IsAny<string>(), It.IsAny<object[]>(), It.IsAny<IReadOnlyList<string>>(), It.IsAny<CancellationToken>()))
.Callback<string, object[], IReadOnlyList<string>, CancellationToken>((methodName, args, excludedConnectionIds, _) => { resultArgs = args; })
.Returns(Task.CompletedTask);
var proxy = new AllClientsExceptProxy<FakeHub>(o.Object, new List<string>());
var data = Encoding.UTF8.GetBytes("Hello world");
await proxy.SendAsync("Method", data);
Assert.NotNull(resultArgs);
var arg = (byte[])Assert.Single(resultArgs);
Assert.Same(data, arg);
}
[Fact]
public async Task SingleClientProxy_SendAsync_ArrayArgumentNotExpanded()
{
object[] resultArgs = null;
var o = new Mock<HubLifetimeManager<FakeHub>>();
o.Setup(m => m.SendConnectionAsync(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<object[]>(), It.IsAny<CancellationToken>()))
.Callback<string, string, object[], CancellationToken>((connectionId, methodName, args, _) => { resultArgs = args; })
.Returns(Task.CompletedTask);
var proxy = new SingleClientProxy<FakeHub>(o.Object, string.Empty);
var data = Encoding.UTF8.GetBytes("Hello world");
await proxy.SendAsync("Method", data);
Assert.NotNull(resultArgs);
var arg = (byte[])Assert.Single(resultArgs);
Assert.Same(data, arg);
}
[Fact]
public async Task MultipleClientProxy_SendAsync_ArrayArgumentNotExpanded()
{
object[] resultArgs = null;
var o = new Mock<HubLifetimeManager<FakeHub>>();
o.Setup(m => m.SendConnectionsAsync(It.IsAny<IReadOnlyList<string>>(), It.IsAny<string>(), It.IsAny<object[]>(), It.IsAny<CancellationToken>()))
.Callback<IReadOnlyList<string>, string, object[], CancellationToken>((connectionIds, methodName, args, _) => { resultArgs = args; })
.Returns(Task.CompletedTask);
var proxy = new MultipleClientProxy<FakeHub>(o.Object, new List<string>());
var data = Encoding.UTF8.GetBytes("Hello world");
await proxy.SendAsync("Method", data);
Assert.NotNull(resultArgs);
var arg = (byte[])Assert.Single(resultArgs);
Assert.Same(data, arg);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Runtime.Intrinsics;
namespace System.Runtime.Intrinsics.X86
{
/// <summary>
/// This class provides access to Intel SSE4.1 hardware instructions via intrinsics
/// </summary>
[CLSCompliant(false)]
public static class Sse41
{
public static bool IsSupported { get { return false; } }
/// <summary>
/// __m128i _mm_blend_epi16 (__m128i a, __m128i b, const int imm8)
/// </summary>
public static Vector128<short> Blend(Vector128<short> left, Vector128<short> right, byte control) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_blend_epi16 (__m128i a, __m128i b, const int imm8)
/// </summary>
public static Vector128<ushort> Blend(Vector128<ushort> left, Vector128<ushort> right, byte control) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128 _mm_blend_ps (__m128 a, __m128 b, const int imm8)
/// </summary>
public static Vector128<float> Blend(Vector128<float> left, Vector128<float> right, byte control) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128d _mm_blend_pd (__m128d a, __m128d b, const int imm8)
/// </summary>
public static Vector128<double> Blend(Vector128<double> left, Vector128<double> right, byte control) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_blendv_epi8 (__m128i a, __m128i b, __m128i mask)
/// </summary>
public static Vector128<sbyte> BlendVariable(Vector128<sbyte> left, Vector128<sbyte> right, Vector128<sbyte> mask) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_blendv_epi8 (__m128i a, __m128i b, __m128i mask)
/// </summary>
public static Vector128<byte> BlendVariable(Vector128<byte> left, Vector128<byte> right, Vector128<byte> mask) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128 _mm_blendv_ps (__m128 a, __m128 b, __m128 mask)
/// </summary>
public static Vector128<float> BlendVariable(Vector128<float> left, Vector128<float> right, Vector128<float> mask) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128d _mm_blendv_pd (__m128d a, __m128d b, __m128d mask)
/// </summary>
public static Vector128<double> BlendVariable(Vector128<double> left, Vector128<double> right, Vector128<double> mask) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128 _mm_ceil_ps (__m128 a)
/// </summary>
public static Vector128<float> Ceiling(Vector128<float> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128d _mm_ceil_pd (__m128d a)
/// </summary>
public static Vector128<double> Ceiling(Vector128<double> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128d _mm_ceil_sd (__m128d a)
/// </summary>
public static Vector128<double> CeilingScalar(Vector128<double> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128 _mm_ceil_ss (__m128 a)
/// </summary>
public static Vector128<float> CeilingScalar(Vector128<float> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_cmpeq_epi64 (__m128i a, __m128i b)
/// </summary>
public static Vector128<long> CompareEqual(Vector128<long> left, Vector128<long> right) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_cmpeq_epi64 (__m128i a, __m128i b)
/// </summary>
public static Vector128<ulong> CompareEqual(Vector128<ulong> left, Vector128<ulong> right) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_cvtepi8_epi16 (__m128i a)
/// </summary>
public static Vector128<short> ConvertToVector128Int16(Vector128<sbyte> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_cvtepu8_epi16 (__m128i a)
/// </summary>
public static Vector128<short> ConvertToVector128Int16(Vector128<byte> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_cvtepi8_epi32 (__m128i a)
/// </summary>
public static Vector128<int> ConvertToVector128Int32(Vector128<sbyte> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_cvtepu8_epi32 (__m128i a)
/// </summary>
public static Vector128<int> ConvertToVector128Int32(Vector128<byte> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_cvtepi16_epi32 (__m128i a)
/// </summary>
public static Vector128<int> ConvertToVector128Int32(Vector128<short> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_cvtepu16_epi32 (__m128i a)
/// </summary>
public static Vector128<int> ConvertToVector128Int32(Vector128<ushort> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_cvtepi8_epi64 (__m128i a)
/// </summary>
public static Vector128<long> ConvertToVector128Int64(Vector128<sbyte> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_cvtepu8_epi64 (__m128i a)
/// </summary>
public static Vector128<long> ConvertToVector128Int64(Vector128<byte> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_cvtepi16_epi64 (__m128i a)
/// </summary>
public static Vector128<long> ConvertToVector128Int64(Vector128<short> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_cvtepu16_epi64 (__m128i a)
/// </summary>
public static Vector128<long> ConvertToVector128Int64(Vector128<ushort> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_cvtepi32_epi64 (__m128i a)
/// </summary>
public static Vector128<long> ConvertToVector128Int64(Vector128<int> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_cvtepu32_epi64 (__m128i a)
/// </summary>
public static Vector128<long> ConvertToVector128Int64(Vector128<uint> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128 _mm_dp_ps (__m128 a, __m128 b, const int imm8)
/// </summary>
public static Vector128<float> DotProduct(Vector128<float> left, Vector128<float> right, byte control) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128d _mm_dp_pd (__m128d a, __m128d b, const int imm8)
/// </summary>
public static Vector128<double> DotProduct(Vector128<double> left, Vector128<double> right, byte control) { throw new PlatformNotSupportedException(); }
/// <summary>
/// int _mm_extract_epi8 (__m128i a, const int imm8)
/// </summary>
public static sbyte Extract(Vector128<sbyte> value, byte index) { throw new PlatformNotSupportedException(); }
/// <summary>
/// int _mm_extract_epi8 (__m128i a, const int imm8)
/// </summary>
public static byte Extract(Vector128<byte> value, byte index) { throw new PlatformNotSupportedException(); }
/// <summary>
/// int _mm_extract_epi32 (__m128i a, const int imm8)
/// </summary>
public static int Extract(Vector128<int> value, byte index) { throw new PlatformNotSupportedException(); }
/// <summary>
/// int _mm_extract_epi32 (__m128i a, const int imm8)
/// </summary>
public static uint Extract(Vector128<uint> value, byte index) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __int64 _mm_extract_epi64 (__m128i a, const int imm8)
/// </summary>
public static long Extract(Vector128<long> value, byte index) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __int64 _mm_extract_epi64 (__m128i a, const int imm8)
/// </summary>
public static ulong Extract(Vector128<ulong> value, byte index) { throw new PlatformNotSupportedException(); }
/// <summary>
/// int _mm_extract_ps (__m128 a, const int imm8)
/// </summary>
public static float Extract(Vector128<float> value, byte index) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128 _mm_floor_ps (__m128 a)
/// </summary>
public static Vector128<float> Floor(Vector128<float> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128d _mm_floor_pd (__m128d a)
/// </summary>
public static Vector128<double> Floor(Vector128<double> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128d _mm_floor_sd (__m128d a)
/// </summary>
public static Vector128<double> FloorScalar(Vector128<double> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128 _mm_floor_ss (__m128 a)
/// </summary>
public static Vector128<float> FloorScalar(Vector128<float> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_insert_epi8 (__m128i a, int i, const int imm8)
/// </summary>
public static Vector128<sbyte> Insert(Vector128<sbyte> value, sbyte data, byte index) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_insert_epi8 (__m128i a, int i, const int imm8)
/// </summary>
public static Vector128<byte> Insert(Vector128<byte> value, byte data, byte index) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_insert_epi32 (__m128i a, int i, const int imm8)
/// </summary>
public static Vector128<int> Insert(Vector128<int> value, int data, byte index) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_insert_epi32 (__m128i a, int i, const int imm8)
/// </summary>
public static Vector128<uint> Insert(Vector128<uint> value, uint data, byte index) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_insert_epi64 (__m128i a, __int64 i, const int imm8)
/// </summary>
public static Vector128<long> Insert(Vector128<long> value, long data, byte index) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_insert_epi64 (__m128i a, __int64 i, const int imm8)
/// </summary>
public static Vector128<ulong> Insert(Vector128<ulong> value, ulong data, byte index) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128 _mm_insert_ps (__m128 a, __m128 b, const int imm8)
/// </summary>
public static Vector128<float> Insert(Vector128<float> value, float data, byte index) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_max_epi8 (__m128i a, __m128i b)
/// </summary>
public static Vector128<sbyte> Max(Vector128<sbyte> left, Vector128<sbyte> right) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_max_epu16 (__m128i a, __m128i b)
/// </summary>
public static Vector128<ushort> Max(Vector128<ushort> left, Vector128<ushort> right) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_max_epi32 (__m128i a, __m128i b)
/// </summary>
public static Vector128<int> Max(Vector128<int> left, Vector128<int> right) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_max_epu32 (__m128i a, __m128i b)
/// </summary>
public static Vector128<uint> Max(Vector128<uint> left, Vector128<uint> right) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_min_epi8 (__m128i a, __m128i b)
/// </summary>
public static Vector128<sbyte> Min(Vector128<sbyte> left, Vector128<sbyte> right) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_min_epu16 (__m128i a, __m128i b)
/// </summary>
public static Vector128<ushort> Min(Vector128<ushort> left, Vector128<ushort> right) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_min_epi32 (__m128i a, __m128i b)
/// </summary>
public static Vector128<int> Min(Vector128<int> left, Vector128<int> right) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_min_epu32 (__m128i a, __m128i b)
/// </summary>
public static Vector128<uint> Min(Vector128<uint> left, Vector128<uint> right) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_minpos_epu16 (__m128i a)
/// </summary>
public static Vector128<ushort> MinHorizontal(Vector128<ushort> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_mpsadbw_epu8 (__m128i a, __m128i b, const int imm8)
/// </summary>
public static Vector128<ushort> MultipleSumAbsoluteDifferences(Vector128<byte> left, Vector128<byte> right, byte mask) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_mul_epi32 (__m128i a, __m128i b)
/// </summary>
public static Vector128<long> Multiply(Vector128<int> left, Vector128<int> right) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_mullo_epi32 (__m128i a, __m128i b)
/// </summary>
public static Vector128<int> MultiplyLow(Vector128<int> left, Vector128<int> right) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_packus_epi32 (__m128i a, __m128i b)
/// </summary>
public static Vector128<ushort> PackUnsignedSaturate(Vector128<int> left, Vector128<int> right) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128 _mm_round_ps (__m128 a, int rounding)
/// _MM_FROUND_TO_NEAREST_INT |_MM_FROUND_NO_EXC
/// </summary>
public static Vector128<float> RoundToNearestInteger(Vector128<float> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// _MM_FROUND_TO_NEG_INF |_MM_FROUND_NO_EXC
/// </summary>
public static Vector128<float> RoundToNegativeInfinity(Vector128<float> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// _MM_FROUND_TO_POS_INF |_MM_FROUND_NO_EXC
/// </summary>
public static Vector128<float> RoundToPositiveInfinity(Vector128<float> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// _MM_FROUND_TO_ZERO |_MM_FROUND_NO_EXC
/// </summary>
public static Vector128<float> RoundToZero(Vector128<float> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// _MM_FROUND_CUR_DIRECTION
/// </summary>
public static Vector128<float> RoundCurrentDirection(Vector128<float> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128d _mm_round_pd (__m128d a, int rounding)
/// _MM_FROUND_TO_NEAREST_INT |_MM_FROUND_NO_EXC
/// </summary>
public static Vector128<double> RoundToNearestInteger(Vector128<double> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// _MM_FROUND_TO_NEG_INF |_MM_FROUND_NO_EXC
/// </summary>
public static Vector128<double> RoundToNegativeInfinity(Vector128<double> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// _MM_FROUND_TO_POS_INF |_MM_FROUND_NO_EXC
/// </summary>
public static Vector128<double> RoundToPositiveInfinity(Vector128<double> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// _MM_FROUND_TO_ZERO |_MM_FROUND_NO_EXC
/// </summary>
public static Vector128<double> RoundToZero(Vector128<double> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// _MM_FROUND_CUR_DIRECTION
/// </summary>
public static Vector128<double> RoundCurrentDirection(Vector128<double> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// _MM_FROUND_CUR_DIRECTION
/// </summary>
public static Vector128<double> RoundCurrentDirectionScalar(Vector128<double> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128d _mm_round_sd (__m128d a, int rounding)
/// _MM_FROUND_TO_NEAREST_INT |_MM_FROUND_NO_EXC
/// </summary>
public static Vector128<double> RoundToNearestIntegerScalar(Vector128<double> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// _MM_FROUND_TO_NEG_INF |_MM_FROUND_NO_EXC
/// </summary>
public static Vector128<double> RoundToNegativeInfinityScalar(Vector128<double> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// _MM_FROUND_TO_POS_INF |_MM_FROUND_NO_EXC
/// </summary>
public static Vector128<double> RoundToPositiveInfinityScalar(Vector128<double> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// _MM_FROUND_TO_ZERO |_MM_FROUND_NO_EXC
/// </summary>
public static Vector128<double> RoundToZeroScalar(Vector128<double> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// _MM_FROUND_CUR_DIRECTION
/// </summary>
public static Vector128<float> RoundCurrentDirectionScalar(Vector128<float> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128 _mm_round_ss (__m128 a, int rounding)
/// _MM_FROUND_TO_NEAREST_INT |_MM_FROUND_NO_EXC
/// </summary>
public static Vector128<float> RoundToNearestIntegerScalar(Vector128<float> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// _MM_FROUND_TO_NEG_INF |_MM_FROUND_NO_EXC
/// </summary>
public static Vector128<float> RoundToNegativeInfinityScalar(Vector128<float> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// _MM_FROUND_TO_POS_INF |_MM_FROUND_NO_EXC
/// </summary>
public static Vector128<float> RoundToPositiveInfinityScalar(Vector128<float> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// _MM_FROUND_TO_ZERO |_MM_FROUND_NO_EXC
/// </summary>
public static Vector128<float> RoundToZeroScalar(Vector128<float> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_stream_load_si128 (const __m128i* mem_addr)
/// </summary>
public static unsafe Vector128<sbyte> LoadAlignedNonTemporal(sbyte* address) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_stream_load_si128 (const __m128i* mem_addr)
/// </summary>
public static unsafe Vector128<byte> LoadAlignedNonTemporal(byte* address) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_stream_load_si128 (const __m128i* mem_addr)
/// </summary>
public static unsafe Vector128<short> LoadAlignedNonTemporal(short* address) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_stream_load_si128 (const __m128i* mem_addr)
/// </summary>
public static unsafe Vector128<ushort> LoadAlignedNonTemporal(ushort* address) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_stream_load_si128 (const __m128i* mem_addr)
/// </summary>
public static unsafe Vector128<int> LoadAlignedNonTemporal(int* address) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_stream_load_si128 (const __m128i* mem_addr)
/// </summary>
public static unsafe Vector128<uint> LoadAlignedNonTemporal(uint* address) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_stream_load_si128 (const __m128i* mem_addr)
/// </summary>
public static unsafe Vector128<long> LoadAlignedNonTemporal(long* address) { throw new PlatformNotSupportedException(); }
/// <summary>
/// __m128i _mm_stream_load_si128 (const __m128i* mem_addr)
/// </summary>
public static unsafe Vector128<ulong> LoadAlignedNonTemporal(ulong* address) { throw new PlatformNotSupportedException(); }
/// <summary>
/// int _mm_test_all_ones (__m128i a)
/// </summary>
public static bool TestAllOnes(Vector128<sbyte> value) { throw new PlatformNotSupportedException(); }
public static bool TestAllOnes(Vector128<byte> value) { throw new PlatformNotSupportedException(); }
public static bool TestAllOnes(Vector128<short> value) { throw new PlatformNotSupportedException(); }
public static bool TestAllOnes(Vector128<ushort> value) { throw new PlatformNotSupportedException(); }
public static bool TestAllOnes(Vector128<int> value) { throw new PlatformNotSupportedException(); }
public static bool TestAllOnes(Vector128<uint> value) { throw new PlatformNotSupportedException(); }
public static bool TestAllOnes(Vector128<long> value) { throw new PlatformNotSupportedException(); }
public static bool TestAllOnes(Vector128<ulong> value) { throw new PlatformNotSupportedException(); }
/// <summary>
/// int _mm_test_all_zeros (__m128i a, __m128i mask)
/// </summary>
public static bool TestAllZeros(Vector128<sbyte> left, Vector128<sbyte> right) { throw new PlatformNotSupportedException(); }
public static bool TestAllZeros(Vector128<byte> left, Vector128<byte> right) { throw new PlatformNotSupportedException(); }
public static bool TestAllZeros(Vector128<short> left, Vector128<short> right) { throw new PlatformNotSupportedException(); }
public static bool TestAllZeros(Vector128<ushort> left, Vector128<ushort> right) { throw new PlatformNotSupportedException(); }
public static bool TestAllZeros(Vector128<int> left, Vector128<int> right) { throw new PlatformNotSupportedException(); }
public static bool TestAllZeros(Vector128<uint> left, Vector128<uint> right) { throw new PlatformNotSupportedException(); }
public static bool TestAllZeros(Vector128<long> left, Vector128<long> right) { throw new PlatformNotSupportedException(); }
public static bool TestAllZeros(Vector128<ulong> left, Vector128<ulong> right) { throw new PlatformNotSupportedException(); }
/// <summary>
/// int _mm_testc_si128 (__m128i a, __m128i b)
/// </summary>
public static bool TestC(Vector128<sbyte> left, Vector128<sbyte> right) { throw new PlatformNotSupportedException(); }
public static bool TestC(Vector128<byte> left, Vector128<byte> right) { throw new PlatformNotSupportedException(); }
public static bool TestC(Vector128<short> left, Vector128<short> right) { throw new PlatformNotSupportedException(); }
public static bool TestC(Vector128<ushort> left, Vector128<ushort> right) { throw new PlatformNotSupportedException(); }
public static bool TestC(Vector128<int> left, Vector128<int> right) { throw new PlatformNotSupportedException(); }
public static bool TestC(Vector128<uint> left, Vector128<uint> right) { throw new PlatformNotSupportedException(); }
public static bool TestC(Vector128<long> left, Vector128<long> right) { throw new PlatformNotSupportedException(); }
public static bool TestC(Vector128<ulong> left, Vector128<ulong> right) { throw new PlatformNotSupportedException(); }
/// <summary>
/// int _mm_test_mix_ones_zeros (__m128i a, __m128i mask)
/// </summary>
public static bool TestMixOnesZeros(Vector128<sbyte> left, Vector128<sbyte> right) { throw new PlatformNotSupportedException(); }
public static bool TestMixOnesZeros(Vector128<byte> left, Vector128<byte> right) { throw new PlatformNotSupportedException(); }
public static bool TestMixOnesZeros(Vector128<short> left, Vector128<short> right) { throw new PlatformNotSupportedException(); }
public static bool TestMixOnesZeros(Vector128<ushort> left, Vector128<ushort> right) { throw new PlatformNotSupportedException(); }
public static bool TestMixOnesZeros(Vector128<int> left, Vector128<int> right) { throw new PlatformNotSupportedException(); }
public static bool TestMixOnesZeros(Vector128<uint> left, Vector128<uint> right) { throw new PlatformNotSupportedException(); }
public static bool TestMixOnesZeros(Vector128<long> left, Vector128<long> right) { throw new PlatformNotSupportedException(); }
public static bool TestMixOnesZeros(Vector128<ulong> left, Vector128<ulong> right) { throw new PlatformNotSupportedException(); }
/// <summary>
/// int _mm_testnzc_si128 (__m128i a, __m128i b)
/// </summary>
public static bool TestNotZAndNotC(Vector128<sbyte> left, Vector128<sbyte> right) { throw new PlatformNotSupportedException(); }
public static bool TestNotZAndNotC(Vector128<byte> left, Vector128<byte> right) { throw new PlatformNotSupportedException(); }
public static bool TestNotZAndNotC(Vector128<short> left, Vector128<short> right) { throw new PlatformNotSupportedException(); }
public static bool TestNotZAndNotC(Vector128<ushort> left, Vector128<ushort> right) { throw new PlatformNotSupportedException(); }
public static bool TestNotZAndNotC(Vector128<int> left, Vector128<int> right) { throw new PlatformNotSupportedException(); }
public static bool TestNotZAndNotC(Vector128<uint> left, Vector128<uint> right) { throw new PlatformNotSupportedException(); }
public static bool TestNotZAndNotC(Vector128<long> left, Vector128<long> right) { throw new PlatformNotSupportedException(); }
public static bool TestNotZAndNotC(Vector128<ulong> left, Vector128<ulong> right) { throw new PlatformNotSupportedException(); }
/// <summary>
/// int _mm_testz_si128 (__m128i a, __m128i b)
/// </summary>
public static bool TestZ(Vector128<sbyte> left, Vector128<sbyte> right) { throw new PlatformNotSupportedException(); }
public static bool TestZ(Vector128<byte> left, Vector128<byte> right) { throw new PlatformNotSupportedException(); }
public static bool TestZ(Vector128<short> left, Vector128<short> right) { throw new PlatformNotSupportedException(); }
public static bool TestZ(Vector128<ushort> left, Vector128<ushort> right) { throw new PlatformNotSupportedException(); }
public static bool TestZ(Vector128<int> left, Vector128<int> right) { throw new PlatformNotSupportedException(); }
public static bool TestZ(Vector128<uint> left, Vector128<uint> right) { throw new PlatformNotSupportedException(); }
public static bool TestZ(Vector128<long> left, Vector128<long> right) { throw new PlatformNotSupportedException(); }
public static bool TestZ(Vector128<ulong> left, Vector128<ulong> right) { throw new PlatformNotSupportedException(); }
}
}
| |
using System;
using System.Xml;
using System.IO;
using System.Net;
using SharpVectors.Net;
using SharpVectors.Dom.Css;
namespace SharpVectors.Dom.Svg
{
public sealed class SvgUriReference : ISvgUriReference
{
#region Private Fields
private string absoluteUri;
private SvgElement ownerElement;
private ISvgAnimatedString href;
#endregion
#region Constructors and Destructor
public SvgUriReference(SvgElement ownerElement)
{
this.ownerElement = ownerElement;
this.ownerElement.attributeChangeHandler += new NodeChangeHandler(AttributeChange);
}
#endregion
#region Public Events
public event NodeChangeHandler NodeChanged;
#endregion
#region Public Properties
public string AbsoluteUri
{
get
{
if (absoluteUri == null)
{
if (ownerElement.HasAttribute("href", SvgDocument.XLinkNamespace))
{
string href = Href.AnimVal.Trim();
if (href.StartsWith("#"))
{
return href;
}
else
{
string baseUri = ownerElement.BaseURI;
if (baseUri.Length == 0)
{
Uri sourceUri = new Uri(Href.AnimVal, UriKind.RelativeOrAbsolute);
if (sourceUri.IsAbsoluteUri)
{
absoluteUri = sourceUri.ToString();
}
}
else
{
Uri sourceUri = null;
string xmlBaseUrl = this.GetBaseUrl();
if (!String.IsNullOrEmpty(xmlBaseUrl))
{
sourceUri = new Uri(new Uri(ownerElement.BaseURI),
Path.Combine(xmlBaseUrl, Href.AnimVal));
}
else
{
sourceUri = new Uri(new Uri(ownerElement.BaseURI), Href.AnimVal);
}
absoluteUri = sourceUri.ToString();
}
}
}
}
return absoluteUri;
}
}
public XmlNode ReferencedNode
{
get
{
if (ownerElement.HasAttribute("href", SvgDocument.XLinkNamespace))
{
XmlNode referencedNode = ownerElement.OwnerDocument.GetNodeByUri(AbsoluteUri);
ISvgExternalResourcesRequired extReqElm =
ownerElement as ISvgExternalResourcesRequired;
if (referencedNode == null && extReqElm != null)
{
if (extReqElm.ExternalResourcesRequired.AnimVal)
{
throw new SvgExternalResourcesRequiredException();
}
}
return referencedNode;
}
return null;
}
}
public WebResponse ReferencedResource
{
get
{
if (ownerElement.HasAttribute("href", SvgDocument.XLinkNamespace))
{
string absoluteUri = this.AbsoluteUri;
if (!String.IsNullOrEmpty(absoluteUri))
{
WebResponse referencedResource = ownerElement.OwnerDocument.GetResource(
new Uri(absoluteUri));
ISvgExternalResourcesRequired extReqElm =
ownerElement as ISvgExternalResourcesRequired;
if (referencedResource == null && extReqElm != null)
{
if (extReqElm.ExternalResourcesRequired.AnimVal)
{
throw new SvgExternalResourcesRequiredException();
}
}
return referencedResource;
}
}
return null;
}
}
#endregion
#region Update handling
private void AttributeChange(Object src, XmlNodeChangedEventArgs args)
{
XmlAttribute attribute = src as XmlAttribute;
if (attribute.NamespaceURI == SvgDocument.XLinkNamespace &&
attribute.LocalName == "href")
{
href = null;
absoluteUri = null;
}
}
private void ReferencedNodeChange(Object src, XmlNodeChangedEventArgs args)
{
if (NodeChanged != null)
{
NodeChanged(src, args);
}
}
#endregion
#region ISvgURIReference Members
public ISvgAnimatedString Href
{
get
{
if (href == null)
{
href = new SvgAnimatedString(ownerElement.GetAttribute("href",
SvgDocument.XLinkNamespace));
}
return href;
}
}
#endregion
#region Private Methods
private string GetBaseUrl()
{
if (ownerElement.HasAttribute("xml:base"))
{
return ownerElement.GetAttribute("xml:base");
}
XmlElement parentNode = ownerElement.ParentNode as XmlElement;
if (parentNode != null && parentNode.HasAttribute("xml:base"))
{
return parentNode.GetAttribute("xml:base");
}
return null;
}
#endregion
}
}
| |
namespace IdentityBase.EntityFramework.IntegrationTests.Stores
{
using System;
using System.Collections.Generic;
using System.Linq;
using IdentityBase.Models;
using IdentityBase.EntityFramework.DbContexts;
using IdentityBase.EntityFramework.Mappers;
using IdentityBase.EntityFramework.Configuration;
using IdentityBase.EntityFramework.Stores;
using Microsoft.EntityFrameworkCore;
using ServiceBase.Logging;
using Xunit;
public class UserAccountStoreTests :
IClassFixture<DatabaseProviderFixture<UserAccountDbContext>>
{
private static readonly EntityFrameworkOptions StoreOptions =
new EntityFrameworkOptions();
public static readonly TheoryData<DbContextOptions<UserAccountDbContext>>
TestDatabaseProviders = new TheoryData<DbContextOptions<UserAccountDbContext>>
{
DatabaseProviderBuilder.BuildInMemory<UserAccountDbContext>(
nameof(UserAccountStoreTests), StoreOptions),
DatabaseProviderBuilder.BuildSqlite<UserAccountDbContext>(
nameof(UserAccountStoreTests), StoreOptions),
DatabaseProviderBuilder.BuildSqlServer<UserAccountDbContext>(
nameof(UserAccountStoreTests), StoreOptions)
};
public UserAccountStoreTests(
DatabaseProviderFixture<UserAccountDbContext> fixture)
{
fixture.Options = TestDatabaseProviders
.SelectMany(x => x
.Select(y => (DbContextOptions<UserAccountDbContext>)y))
.ToList();
fixture.StoreOptions = StoreOptions;
}
[Theory, MemberData(nameof(TestDatabaseProviders))]
public void LoadByIdAsync_WhenUserAccountExists_ExpectUserAccountRetured(
DbContextOptions<UserAccountDbContext> options)
{
var testUserAccount = new UserAccount
{
Id = Guid.NewGuid(),
Email = "jim@panse.de"
};
using (var context =
new UserAccountDbContext(options, StoreOptions))
{
context.UserAccounts.Add(testUserAccount.ToEntity());
context.SaveChanges();
}
UserAccount userAccount;
using (var context =
new UserAccountDbContext(options, StoreOptions))
{
var store = new UserAccountStore(
context, NullLogger<UserAccountStore>.Create());
userAccount = store.LoadByIdAsync(testUserAccount.Id).Result;
}
Assert.NotNull(userAccount);
}
[Theory, MemberData(nameof(TestDatabaseProviders))]
public void LoadByEmailAsync_WhenUserAccountExists_ExpectUserAccountRetured(
DbContextOptions<UserAccountDbContext> options)
{
var testUserAccount = new UserAccount
{
Email = "jim22@panse.de"
};
using (var context =
new UserAccountDbContext(options, StoreOptions))
{
context.UserAccounts.Add(testUserAccount.ToEntity());
context.SaveChanges();
}
UserAccount userAccount;
using (var context =
new UserAccountDbContext(options, StoreOptions))
{
var store = new UserAccountStore(
context,
NullLogger<UserAccountStore>.Create()
);
userAccount = store
.LoadByEmailAsync(testUserAccount.Email).Result;
}
Assert.NotNull(userAccount);
}
[Theory, MemberData(nameof(TestDatabaseProviders))]
public void LoadByEmailWithExternalAsync_WhenUserAccountExists_ExpectUserAccountRetured(
DbContextOptions<UserAccountDbContext> options)
{
var testUserAccount = new UserAccount
{
Id = Guid.NewGuid(),
Email = "jim2@panse.de",
Accounts = new List<ExternalAccount>
{
new ExternalAccount
{
Provider ="provider",
Email = "foo@provider.com",
Subject = "123456789"
},
new ExternalAccount
{
Provider = "provider",
Email = "bar@anotherprovider.com",
Subject = "asda5sd4a564da6"
}
}
};
using (var context =
new UserAccountDbContext(options, StoreOptions))
{
context.UserAccounts.Add(testUserAccount.ToEntity());
context.SaveChanges();
}
UserAccount userAccount;
using (var context =
new UserAccountDbContext(options, StoreOptions))
{
var store = new UserAccountStore(
context,
NullLogger<UserAccountStore>.Create()
);
userAccount = store
.LoadByEmailWithExternalAsync(testUserAccount.Email)
.Result;
}
Assert.NotNull(userAccount);
}
[Theory, MemberData(nameof(TestDatabaseProviders))]
public void LoadByVerificationKeyAsync_WhenUserAccountExists_ExpectUserAccountRetured(
DbContextOptions<UserAccountDbContext> options)
{
var testUserAccount = new UserAccount
{
Id = Guid.NewGuid(),
Email = "jim3@panse.de",
VerificationKey = Guid.NewGuid().ToString()
};
using (var context =
new UserAccountDbContext(options, StoreOptions))
{
context.UserAccounts.Add(testUserAccount.ToEntity());
context.SaveChanges();
}
UserAccount userAccount;
using (var context =
new UserAccountDbContext(options, StoreOptions))
{
var store = new UserAccountStore(
context,
NullLogger<UserAccountStore>.Create()
);
userAccount = store.LoadByVerificationKeyAsync(
testUserAccount.VerificationKey).Result;
}
Assert.NotNull(userAccount);
}
[Theory, MemberData(nameof(TestDatabaseProviders))]
public void LoadByExternalProviderAsync_WhenUserAccountExists_ExpectUserAccountRetured(
DbContextOptions<UserAccountDbContext> options)
{
var testExternalAccount = new ExternalAccount
{
Email = "jim4@panse.de",
Provider = "yahoo",
Subject = "123456789"
};
var testUserAccount = new UserAccount
{
Id = Guid.NewGuid(),
Email = "jim4@panse.de",
Accounts = new List<ExternalAccount>
{
testExternalAccount
}
};
using (var context =
new UserAccountDbContext(options, StoreOptions))
{
context.UserAccounts.Add(testUserAccount.ToEntity());
context.SaveChanges();
}
UserAccount userAccount;
using (var context =
new UserAccountDbContext(options, StoreOptions))
{
var store = new UserAccountStore(
context,
NullLogger<UserAccountStore>.Create()
);
userAccount = store.LoadByExternalProviderAsync(
testExternalAccount.Provider,
testExternalAccount.Subject).Result;
}
Assert.NotNull(userAccount);
}
[Theory, MemberData(nameof(TestDatabaseProviders))]
public void WriteAsync_NewUserAccount_ExpectUserAccountRetured(
DbContextOptions<UserAccountDbContext> options)
{
var testUserAccount1 = new UserAccount
{
Id = Guid.NewGuid(),
Email = "foo2@localhost",
Accounts = new List<ExternalAccount>
{
new ExternalAccount
{
Email = "foo2@provider",
Provider = "facebook",
Subject = "123456712",
},
new ExternalAccount
{
Email = "bar2@provider",
Provider = "google",
Subject = "789456111",
}
},
Claims = new List<UserAccountClaim>
{
new UserAccountClaim("name", "foo2"),
new UserAccountClaim("email", "foo2@localhost"),
}
};
using (var context =
new UserAccountDbContext(options, StoreOptions))
{
var store = new UserAccountStore(
context,
NullLogger<UserAccountStore>.Create()
);
var userAccount = store.WriteAsync(testUserAccount1).Result;
Assert.NotNull(userAccount);
}
}
[Theory, MemberData(nameof(TestDatabaseProviders))]
public void WriteAsync_UpdateUserAccount_ExpectUserAccountRetured(
DbContextOptions<UserAccountDbContext> options)
{
var testUserAccount1 = new UserAccount
{
Id = Guid.NewGuid(),
Email = "foox@localhost",
Accounts = new List<ExternalAccount>
{
new ExternalAccount
{
Email = "foox@provider",
Provider = "facebook",
Subject = "123456789",
},
new ExternalAccount
{
Email = "bar@provider",
Provider = "google",
Subject = "789456123",
}
},
Claims = new List<UserAccountClaim>
{
new UserAccountClaim("name", "foo"),
new UserAccountClaim("email", "foo@localhost"),
new UserAccountClaim("w00t", "some junk"),
}
};
using (var context =
new UserAccountDbContext(options, StoreOptions))
{
context.UserAccounts.Add(testUserAccount1.ToEntity());
context.SaveChanges();
testUserAccount1 = context.UserAccounts.AsNoTracking()
.FirstOrDefault(c => c.Id == testUserAccount1.Id)
.ToModel();
}
UserAccount userAccount;
using (var context =
new UserAccountDbContext(options, StoreOptions))
{
var store = new UserAccountStore(
context,
NullLogger<UserAccountStore>.Create()
);
testUserAccount1.VerificationKeySentAt = DateTime.Now;
testUserAccount1.VerificationPurpose = 1;
testUserAccount1.VerificationStorage = "hallo welt";
userAccount = store.WriteAsync(testUserAccount1).Result;
Assert.NotNull(userAccount);
}
using (var context =
new UserAccountDbContext(options, StoreOptions))
{
var updatedAccount = testUserAccount1 = context.UserAccounts
.Include(c => c.Accounts)
.Include(c => c.Claims)
.FirstOrDefault(c => c.Id == testUserAccount1.Id).ToModel();
Assert.NotNull(updatedAccount);
Assert.Equal(
updatedAccount.VerificationStorage,
userAccount.VerificationStorage);
Assert.Equal(2, updatedAccount.Accounts.Count());
Assert.Equal(3, updatedAccount.Claims.Count());
}
}
}
}
| |
// ******************************************************************************************************************************
// ****
// **** Copyright (c) 2016-2021 Rafael 'Monoman' Teixeira
// ****
// ******************************************************************************************************************************
namespace Commons.Collections;
internal class VerticalLinkedList<T> : IEnumerable<T> where T : IComparable
{
public IEnumerator<T> GetEnumerator() => ImplementedEnumerator();
IEnumerator IEnumerable.GetEnumerator() => ImplementedEnumerator();
internal VerticalLinkedList(T[] bigArray, int maxDepth, int firstIndex) {
_bigArray = bigArray;
_maxDepth = maxDepth;
_firstIndex = firstIndex;
Depth = 0;
}
internal VerticalLinkedList(T[] bigArray, int maxDepth, int firstIndex, T Value) : this(bigArray, maxDepth, firstIndex) {
Depth = 1;
_bigArray[_firstIndex] = Value;
}
internal int Depth { get; private set; }
internal T First => IsEmpty ? default : _bigArray[_firstIndex];
internal int Id => _firstIndex / _maxDepth;
internal bool IsEmpty => Depth < 1;
internal bool IsFull => Depth >= _maxDepth;
internal T Last => IsEmpty ? default : _bigArray[_lastIndex];
internal void Clear() => Depth = 0;
internal bool Contains(T value) => InRange(value) && BinarySearch(value) >= 0;
internal VerticalLinkedList<T> CopyTo(T[] newArray, int newMaxDepth, int firstIndex) {
var newList = new VerticalLinkedList<T>(newArray, newMaxDepth, firstIndex);
var index = _firstIndex;
for (int i = Depth; i > 0; i--)
newArray[firstIndex++] = _bigArray[index++];
newList.Depth = Depth;
return newList;
}
internal int Count(T value) {
lock (this) {
if (!InRange(value))
return 0;
var foundAt = BinarySearch(value);
if (foundAt < 0)
return 0;
int count = 1;
var up = foundAt + 1;
var top = _lastIndex;
while (up++ <= top && _bigArray[up].CompareTo(value) == 0)
count++;
var down = foundAt - 1;
while (down-- >= _firstIndex && _bigArray[down].CompareTo(value) == 0)
count++;
return count;
}
}
internal int DeleteWhere(Func<T, bool> predicate) {
int removed = 0;
var next = _firstIndex;
for (int i = Depth; i > 0; i--) {
var value = _bigArray[next];
if (predicate(value)) {
InnerRemove(next);
removed++;
} else
next++;
}
return removed;
}
internal bool InRange(T value) => (!IsEmpty) && First.CompareTo(value) <= 0 && Last.CompareTo(value) >= 0;
internal void Insert(T value) {
CheckCapacity();
if (IsEmpty) {
_bigArray[_firstIndex] = value;
Depth = 1;
return;
}
var up = _firstIndex;
var down = _lastIndex;
for (int i = Depth; i > 0; i--) {
if (_bigArray[up].CompareTo(value) > 0) {
AddBefore(up, value);
return;
}
if (_bigArray[down].CompareTo(value) <= 0) {
AddAfter(down, value);
return;
}
up++;
down--;
}
}
internal void InsertAsLast(T value) {
CheckCapacity();
Depth++;
_bigArray[_lastIndex] = value;
}
private void CheckCapacity() {
if (IsFull)
throw new InvalidOperationException("Can't add any more values!");
}
internal void OpenSpaceAndInsert(T value, VerticalLinkedList<T> listAfter, VerticalLinkedList<T> listBefore) {
if (!IsFull)
throw new InvalidOperationException();
var slot = WhereToInsert(value);
if (listAfter != null && listBefore != null && listAfter._lastIndex - slot < slot - listBefore._lastIndex)
listBefore = null;
if (listBefore == null) {
for (int i = listAfter._lastIndex; i >= slot; i--)
_bigArray[i + 1] = _bigArray[i];
listAfter.Depth += 1;
} else {
var nextFirst = listBefore._firstIndex + _maxDepth;
listBefore.Depth += 1;
_bigArray[listBefore._lastIndex] = _bigArray[nextFirst];
slot--;
for (int i = nextFirst; i < slot; i++)
_bigArray[i] = _bigArray[i + 1];
}
_bigArray[slot] = value;
}
internal void Receive(VerticalLinkedList<T> from) {
if (from == null)
throw new ArgumentNullException(nameof(from));
int delta = from._firstIndex;
for (int i = from.Depth - 1; i >= 0; i--)
_bigArray[i] = _bigArray[i + delta];
Depth = from.Depth;
from.Depth = 0;
}
internal int Remove(T value, bool removeAll) {
lock (this) {
if (!Contains(value))
return 0;
var up = _firstIndex;
int removed = 0;
for (int i = Depth; i > 0; i--) {
var upCompare = _bigArray[up].CompareTo(value);
if (upCompare > 0)
break;
if (upCompare < 0)
up++;
else {
var start = up;
while (upCompare == 0) {
removed++;
InnerRemove(up);
if ((!removeAll) || (--i <= 0))
break;
upCompare = _bigArray[up].CompareTo(value);
}
break;
}
}
return removed;
}
}
internal T RemoveFirst() => InnerRemove(_firstIndex);
private readonly T[] _bigArray;
private readonly int _firstIndex;
private readonly int _maxDepth;
private int _lastIndex => _firstIndex + Depth - 1;
private void AddAfter(int index, T value) => AddBefore(index + 1, value);
private void AddBefore(int index, T value) {
for (int i = _lastIndex; i >= index; i--)
_bigArray[i + 1] = _bigArray[i];
_bigArray[index] = value;
Depth++;
}
private int BinarySearch(T value) {
int foundAt = -1;
var bottom = _firstIndex;
var top = _lastIndex;
while (bottom <= top) {
var mid = (bottom + top) / 2;
var compare = _bigArray[mid].CompareTo(value);
if (compare == 0) {
foundAt = mid;
break;
} else if (compare > 0) {
top = mid - 1;
} else {
bottom = mid + 1;
}
}
return foundAt;
}
private IEnumerator<T> ImplementedEnumerator() {
if (IsEmpty)
yield break;
var next = _firstIndex;
for (int i = Depth; i > 0; i--)
yield return _bigArray[next++];
}
private T InnerRemove(int index) {
if (IsEmpty || index < _firstIndex || index > _lastIndex)
return default;
var value = _bigArray[index];
for (int i = index; i <= _lastIndex; i++)
_bigArray[i] = _bigArray[i + 1];
Depth--;
return value;
}
private int WhereToInsert(T value) {
var up = _firstIndex;
var down = _lastIndex;
for (int i = Depth; i > 0; i--) {
if (_bigArray[up].CompareTo(value) > 0)
return up;
if (_bigArray[down].CompareTo(value) <= 0)
return down + 1;
up++;
down--;
}
throw new ArgumentOutOfRangeException(nameof(value));
}
}
| |
// ReSharper disable All
using System.Collections.Generic;
using System.Diagnostics;
using System.Dynamic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Frapid.ApplicationState.Models;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Frapid.WebsiteBuilder.DataAccess;
using Frapid.WebsiteBuilder.Api.Fakes;
using Frapid.DataAccess;
using Frapid.DataAccess.Models;
using Xunit;
namespace Frapid.WebsiteBuilder.Api.Tests
{
public class EmailSubscriptionTests
{
public static EmailSubscriptionController Fixture()
{
EmailSubscriptionController controller = new EmailSubscriptionController(new EmailSubscriptionRepository());
return controller;
}
[Fact]
[Conditional("Debug")]
public void CountEntityColumns()
{
EntityView entityView = Fixture().GetEntityView();
Assert.Null(entityView.Columns);
}
[Fact]
[Conditional("Debug")]
public void Count()
{
long count = Fixture().Count();
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void GetAll()
{
int count = Fixture().GetAll().Count();
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void Export()
{
int count = Fixture().Export().Count();
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void Get()
{
Frapid.WebsiteBuilder.Entities.EmailSubscription emailSubscription = Fixture().Get(new System.Guid());
Assert.NotNull(emailSubscription);
}
[Fact]
[Conditional("Debug")]
public void First()
{
Frapid.WebsiteBuilder.Entities.EmailSubscription emailSubscription = Fixture().GetFirst();
Assert.NotNull(emailSubscription);
}
[Fact]
[Conditional("Debug")]
public void Previous()
{
Frapid.WebsiteBuilder.Entities.EmailSubscription emailSubscription = Fixture().GetPrevious(new System.Guid());
Assert.NotNull(emailSubscription);
}
[Fact]
[Conditional("Debug")]
public void Next()
{
Frapid.WebsiteBuilder.Entities.EmailSubscription emailSubscription = Fixture().GetNext(new System.Guid());
Assert.NotNull(emailSubscription);
}
[Fact]
[Conditional("Debug")]
public void Last()
{
Frapid.WebsiteBuilder.Entities.EmailSubscription emailSubscription = Fixture().GetLast();
Assert.NotNull(emailSubscription);
}
[Fact]
[Conditional("Debug")]
public void GetMultiple()
{
IEnumerable<Frapid.WebsiteBuilder.Entities.EmailSubscription> emailSubscriptions = Fixture().Get(new System.Guid[] { });
Assert.NotNull(emailSubscriptions);
}
[Fact]
[Conditional("Debug")]
public void GetPaginatedResult()
{
int count = Fixture().GetPaginatedResult().Count();
Assert.Equal(1, count);
count = Fixture().GetPaginatedResult(1).Count();
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void CountWhere()
{
long count = Fixture().CountWhere(new JArray());
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void GetWhere()
{
int count = Fixture().GetWhere(1, new JArray()).Count();
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void CountFiltered()
{
long count = Fixture().CountFiltered("");
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void GetFiltered()
{
int count = Fixture().GetFiltered(1, "").Count();
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void GetDisplayFields()
{
int count = Fixture().GetDisplayFields().Count();
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void GetCustomFields()
{
int count = Fixture().GetCustomFields().Count();
Assert.Equal(1, count);
count = Fixture().GetCustomFields("").Count();
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void AddOrEdit()
{
try
{
var form = new JArray { null, null };
Fixture().AddOrEdit(form);
}
catch (HttpResponseException ex)
{
Assert.Equal(HttpStatusCode.MethodNotAllowed, ex.Response.StatusCode);
}
}
[Fact]
[Conditional("Debug")]
public void Add()
{
try
{
Fixture().Add(null);
}
catch (HttpResponseException ex)
{
Assert.Equal(HttpStatusCode.MethodNotAllowed, ex.Response.StatusCode);
}
}
[Fact]
[Conditional("Debug")]
public void Edit()
{
try
{
Fixture().Edit(new System.Guid(), null);
}
catch (HttpResponseException ex)
{
Assert.Equal(HttpStatusCode.MethodNotAllowed, ex.Response.StatusCode);
}
}
[Fact]
[Conditional("Debug")]
public void BulkImport()
{
var collection = new JArray { null, null, null, null };
var actual = Fixture().BulkImport(collection);
Assert.NotNull(actual);
}
[Fact]
[Conditional("Debug")]
public void Delete()
{
try
{
Fixture().Delete(new System.Guid());
}
catch (HttpResponseException ex)
{
Assert.Equal(HttpStatusCode.InternalServerError, ex.Response.StatusCode);
}
}
}
}
| |
// Copyright 2003-2021 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.Diagnostics;
using System.Drawing.Printing;
using System.IO;
using System.Reflection;
using System.Text;
using Autodesk.Revit.DB;
using RevitLookup.Core.Collectors;
using RevitLookup.Core.RevitTypes;
using RevitLookup.Core.RevitTypes.PlaceHolders;
using RevitLookup.Views;
using Color = System.Drawing.Color;
using Exception = System.Exception;
using Form = System.Windows.Forms.Form;
namespace RevitLookup.Core;
public static class Utils
{
public static void Display(ListView listView, Collector snoopCollector)
{
listView.BeginUpdate();
listView.Items.Clear();
var oldFont = listView.Font;
var newStyle = listView.Font.Style ^ FontStyle.Bold;
var boldFont = new Font(oldFont, newStyle);
foreach (var data in snoopCollector.Data)
{
var snoopData = (Data) data;
// if it is a class separator, then color the background differently
// and don't add a SubItem for the "Field" value
if (snoopData.IsSeparator)
{
var lvItem = new ListViewItem(snoopData.AsValueString())
{
BackColor = snoopData is ClassSeparatorData ? Color.LightBlue : Color.WhiteSmoke,
Tag = snoopData
};
listView.Items.Add(lvItem);
}
else
{
var viewItem = new ListViewItem(snoopData.Label);
viewItem.SubItems.Add(snoopData.AsValueString());
if (snoopData.IsError)
{
var subItem = viewItem.SubItems[0];
subItem.ForeColor = Color.Red;
}
if (snoopData.HasDrillDown)
{
var subItem = viewItem.SubItems[0];
subItem.Font = boldFont;
}
viewItem.Tag = snoopData;
listView.Items.Add(viewItem);
}
}
listView.EndUpdate();
}
public static void DataItemSelected(ListView listView, ModelessWindowFactory windowFactory)
{
Debug.Assert(listView.SelectedItems.Count > 1 == false);
if (listView.SelectedItems.Count == 0) return;
var snoopData = (Data) listView.SelectedItems[0].Tag;
var newForm = snoopData.DrillDown();
if (newForm is not null) windowFactory.ShowForm(newForm);
}
private static void UpdateLastColumnWidth(ListView listView)
{
listView.Columns[listView.Columns.Count - 1].Width = -2;
}
public static void AddOnLoadForm(Form form)
{
form.Load += (_, _) =>
{
foreach (var control in form.Controls)
if (control is ListView listView)
{
UpdateLastColumnWidth(listView);
listView.Resize += (_, _) => UpdateLastColumnWidth(listView);
}
};
}
public static void BrowseReflection(object obj)
{
if (obj is null)
{
MessageBox.Show("Object is null");
return;
}
var pgForm = new GenericPropGridView(obj);
pgForm.Text = $"Object Data (System.Type = {obj.GetType().FullName})";
pgForm.ShowDialog();
}
private static string GetNamedObjectLabel(object obj)
{
var nameProperty = obj
.GetType()
.GetProperty("Name", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
if (nameProperty is null) return null;
var propertyValue = nameProperty.GetValue(obj) as string;
return $"< {obj.GetType().Name} {(string.IsNullOrEmpty(propertyValue) ? Labels.Undefined : propertyValue)} >";
}
public static string GetParameterObjectLabel(object obj)
{
var parameter = obj as Parameter;
return parameter?.Definition.Name;
}
private static string GetFamilyParameterObjectLabel(object obj)
{
var familyParameter = obj as FamilyParameter;
return familyParameter?.Definition.Name;
}
public static string GetLabel(object obj)
{
switch (obj)
{
case null:
return Labels.Null;
case ISnoopPlaceholder placeholder:
return placeholder.GetName();
case Element elem:
// TBD: Exceptions are thrown in certain cases when accessing the Name property.
// Eg. for the RoomTag object. So we will catch the exception and display the exception message
// arj - 1/23/07
try
{
var nameStr = elem.Name == string.Empty ? Labels.Undefined : elem.Name;
return $"< {nameStr} {elem.Id.IntegerValue} >";
}
catch (Exception ex)
{
return $"< {null} {ex.Message} >";
}
default:
return GetNamedObjectLabel(obj) ?? GetParameterObjectLabel(obj) ?? GetFamilyParameterObjectLabel(obj) ?? $"< {obj.GetType().Name} >";
}
}
public static void CopyToClipboard(ListView lv)
{
if (lv.Items.Count == 0)
{
Clipboard.Clear();
return;
}
//First find the longest piece of text in the Field column
//
var maxField = 0;
var maxValue = 0;
foreach (ListViewItem item in lv.Items)
{
if (item.Text.Length > maxField) maxField = item.Text.Length;
if (item.SubItems.Count > 1 && item.SubItems[1].Text.Length > maxValue) maxValue = item.SubItems[1].Text.Length;
}
var headerFormat = $"{{0,{maxField}}}----{new string('-', maxValue)}\r\n";
var tabbedFormat = $"{{0,{maxField}}} {{1}}\r\n";
var bldr = new StringBuilder();
foreach (ListViewItem item in lv.Items)
switch (item.SubItems.Count)
{
case 1:
{
var tmp = item.Text;
if (item.Text.Length < maxField) tmp = item.Text.PadLeft(item.Text.Length + (maxField - item.Text.Length), '-');
bldr.AppendFormat(headerFormat, tmp);
break;
}
case > 1:
bldr.AppendFormat(tabbedFormat, item.Text, item.SubItems[1].Text);
break;
}
var txt = bldr.ToString();
if (string.IsNullOrEmpty(txt) == false) Clipboard.SetDataObject(txt);
}
public static void CopyToClipboard(ListViewItem lvItem, bool multipleItems)
{
if (lvItem.SubItems.Count > 1)
{
if (!multipleItems)
Clipboard.SetDataObject(lvItem.SubItems[1].Text);
else
Clipboard.SetDataObject($"{lvItem.SubItems[0].Text} => {lvItem.SubItems[1].Text}");
}
else
{
Clipboard.Clear();
}
}
public static int Print(string title, ListView lv, PrintPageEventArgs e, int maxFieldWidth, int maxValueWidth, int currentItem)
{
float linesPerPage = 0;
float yPos = 0;
float leftMargin = e.MarginBounds.Left + (e.MarginBounds.Width - (maxFieldWidth + maxValueWidth)) / 2;
float topMargin = e.MarginBounds.Top;
var fontHeight = lv.Font.GetHeight(e.Graphics);
var count = 0;
ListViewItem item;
SolidBrush backgroundBrush;
SolidBrush subbackgroundBrush;
SolidBrush textBrush;
RectangleF rect;
var centerFormat = new StringFormat();
var fieldFormat = new StringFormat();
var valueFormat = new StringFormat();
centerFormat.Alignment = StringAlignment.Center;
fieldFormat.Alignment = HorizontalAlignmentToStringAligment(lv.Columns[0].TextAlign);
valueFormat.Alignment = HorizontalAlignmentToStringAligment(lv.Columns[1].TextAlign);
//Draw the title of the list.
//
rect = new RectangleF(leftMargin, topMargin, maxFieldWidth + maxValueWidth, fontHeight);
e.Graphics.DrawString(title, lv.Font, Brushes.Black, rect, centerFormat);
//Update the count so that we are giving ourselves a line between the title and the list.
//
count = 2;
//Calculate the number of lines per page
//
linesPerPage = e.MarginBounds.Height / fontHeight;
while (count < linesPerPage && currentItem < lv.Items.Count)
{
item = lv.Items[currentItem];
yPos = topMargin + count * fontHeight;
backgroundBrush = new SolidBrush(item.BackColor);
textBrush = new SolidBrush(item.ForeColor);
rect = new RectangleF(leftMargin, yPos, maxFieldWidth, fontHeight);
e.Graphics.FillRectangle(backgroundBrush, rect);
e.Graphics.DrawRectangle(Pens.Black, rect.X, rect.Y, rect.Width, rect.Height);
//Draw the field portion of the list view item
//
e.Graphics.DrawString($" {item.Text}", item.Font, textBrush, rect, fieldFormat);
//Draw the value portion of the list view item
//
rect = new RectangleF(leftMargin + maxFieldWidth, yPos, maxValueWidth, fontHeight);
if (item.SubItems.Count > 1)
{
subbackgroundBrush = new SolidBrush(item.SubItems[1].BackColor);
e.Graphics.FillRectangle(subbackgroundBrush, rect);
e.Graphics.DrawString($" {item.SubItems[1].Text}", item.Font, textBrush, rect, valueFormat);
}
else
{
e.Graphics.FillRectangle(backgroundBrush, rect);
}
e.Graphics.DrawRectangle(Pens.Black, rect.X, rect.Y, rect.Width, rect.Height);
count++;
currentItem++;
}
if (currentItem < lv.Items.Count)
{
e.HasMorePages = true;
}
else
{
e.HasMorePages = false;
currentItem = 0;
}
return currentItem;
}
public static StringAlignment HorizontalAlignmentToStringAligment(HorizontalAlignment ha)
{
return ha switch
{
HorizontalAlignment.Center => StringAlignment.Center,
HorizontalAlignment.Left => StringAlignment.Near,
HorizontalAlignment.Right => StringAlignment.Far,
_ => StringAlignment.Near
};
}
public static int[] GetMaximumColumnWidths(ListView lv)
{
var index = 0;
var widthArray = new int[lv.Columns.Count];
foreach (ColumnHeader col in lv.Columns)
{
widthArray[index] = col.Width;
index++;
}
var g = lv.CreateGraphics();
var offset = Convert.ToInt32(Math.Ceiling(g.MeasureString(" ", lv.Font).Width));
var width = 0;
foreach (ListViewItem item in lv.Items)
{
index = 0;
foreach (ListViewItem.ListViewSubItem subItem in item.SubItems)
{
width = Convert.ToInt32(Math.Ceiling(g.MeasureString(subItem.Text, item.Font).Width)) + offset;
if (width > widthArray[index]) widthArray[index] = width;
index++;
}
}
g.Dispose();
return widthArray;
}
private static TreeNode GetRootNode(TreeNode node)
{
while (true)
{
if (node.Parent is null) return node;
node = node.Parent;
}
}
public static string GetPrintDocumentName(TreeNode node)
{
var root = GetRootNode(node);
if (root.Tag is string str) return Path.GetFileNameWithoutExtension(str);
return string.Empty;
}
public static void UpdatePrintSettings(PrintDocument doc, TreeView tv, ListView lv, ref int[] widthArray)
{
if (tv.SelectedNode is null) return;
doc.DocumentName = GetPrintDocumentName(tv.SelectedNode);
widthArray = GetMaximumColumnWidths(lv);
}
public static void UpdatePrintSettings(ListView lv, ref int[] widthArray)
{
widthArray = GetMaximumColumnWidths(lv);
}
public static void PrintMenuItemClick(PrintDialog dlg, TreeView tv)
{
if (tv.SelectedNode is null)
{
MessageBox.Show(tv.Parent, "Please select a node in the tree to print.", "RevitLookup", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
if (dlg.ShowDialog(tv.Parent) == DialogResult.OK) dlg.Document.Print();
}
public static void PrintMenuItemClick(PrintDialog dlg)
{
dlg.Document.Print();
}
public static void PrintPreviewMenuItemClick(PrintPreviewDialog dlg, TreeView tv)
{
if (tv.SelectedNode is null)
{
MessageBox.Show(tv.Parent, "Please select a node in the tree to print.", "RevitLookup", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
dlg.ShowDialog(tv.Parent);
}
public static void PrintPreviewMenuItemClick(PrintPreviewDialog dlg, ListView lv)
{
dlg.ShowDialog(lv.Parent);
}
}
| |
using System.Linq;
using Terraria;
using Terraria.ID;
using Terraria.ModLoader;
namespace ExampleMod.NPCs
{
public class ExamplePerson : ModNPC
{
public override bool Autoload(ref string name, ref string texture, ref string[] altTextures)
{
name = "Example Person";
altTextures = new string[] { "ExampleMod/NPCs/ExamplePerson_Alt_1" };
return mod.Properties.Autoload;
}
public override void SetDefaults()
{
npc.name = "Example Person";
npc.townNPC = true;
npc.friendly = true;
npc.width = 18;
npc.height = 40;
npc.aiStyle = 7;
npc.damage = 10;
npc.defense = 15;
npc.lifeMax = 250;
npc.HitSound = SoundID.NPCHit1;
npc.DeathSound = SoundID.NPCDeath1;
npc.knockBackResist = 0.5f;
Main.npcFrameCount[npc.type] = 25;
NPCID.Sets.ExtraFramesCount[npc.type] = 9;
NPCID.Sets.AttackFrameCount[npc.type] = 4;
NPCID.Sets.DangerDetectRange[npc.type] = 700;
NPCID.Sets.AttackType[npc.type] = 0;
NPCID.Sets.AttackTime[npc.type] = 90;
NPCID.Sets.AttackAverageChance[npc.type] = 30;
NPCID.Sets.HatOffsetY[npc.type] = 4;
NPCID.Sets.ExtraTextureCount[npc.type] = 1;
animationType = NPCID.Guide;
}
public override void HitEffect(int hitDirection, double damage)
{
int num = npc.life > 0 ? 1 : 5;
for (int k = 0; k < num; k++)
{
Dust.NewDust(npc.position, npc.width, npc.height, mod.DustType("Sparkle"));
}
}
public override bool CanTownNPCSpawn(int numTownNPCs, int money)
{
for (int k = 0; k < 255; k++)
{
Player player = Main.player[k];
if (player.active)
{
for (int j = 0; j < player.inventory.Length; j++)
{
if (player.inventory[j].type == mod.ItemType("ExampleItem") || player.inventory[j].type == mod.ItemType("ExampleBlock"))
{
return true;
}
}
}
}
return false;
}
public override bool CheckConditions(int left, int right, int top, int bottom)
{
int score = 0;
for (int x = left; x <= right; x++)
{
for (int y = top; y <= bottom; y++)
{
int type = Main.tile[x, y].type;
if (type == mod.TileType("ExampleBlock") || type == mod.TileType("ExampleChair") || type == mod.TileType("ExampleWorkbench") || type == mod.TileType("ExampleBed") || type == mod.TileType("ExampleDoorOpen") || type == mod.TileType("ExampleDoorClosed"))
{
score++;
}
if (Main.tile[x, y].wall == mod.WallType("ExampleWall"))
{
score++;
}
}
}
return score >= (right - left) * (bottom - top) / 2;
}
public override string TownNPCName()
{
switch (WorldGen.genRand.Next(4))
{
case 0:
return "Someone";
case 1:
return "Somebody";
case 2:
return "Blocky";
default:
return "Colorless";
}
}
public override void FindFrame(int frameHeight)
{
/*npc.frame.Width = 40;
if (((int)Main.time / 10) % 2 == 0)
{
npc.frame.X = 40;
}
else
{
npc.frame.X = 0;
}*/
}
public override string GetChat()
{
int partyGirl = NPC.FindFirstNPC(NPCID.PartyGirl);
if (partyGirl >= 0 && Main.rand.Next(4) == 0)
{
return "Can you please tell " + Main.npc[partyGirl].displayName + " to stop decorating my house with colors?";
}
switch (Main.rand.Next(3))
{
case 0:
return "Sometimes I feel like I'm different from everyone else here.";
case 1:
return "What's your favorite color? My favorite colors are white and black.";
default:
return "What? I don't have any arms or legs? Oh, don't be ridiculous!";
}
}
public override void SetChatButtons(ref string button, ref string button2)
{
button = Lang.inter[28];
}
public override void OnChatButtonClicked(bool firstButton, ref bool shop)
{
if (firstButton)
{
shop = true;
}
}
public override void SetupShop(Chest shop, ref int nextSlot)
{
shop.item[nextSlot].SetDefaults(mod.ItemType("ExampleItem"));
nextSlot++;
shop.item[nextSlot].SetDefaults(mod.ItemType("EquipMaterial"));
nextSlot++;
shop.item[nextSlot].SetDefaults(mod.ItemType("BossItem"));
nextSlot++;
shop.item[nextSlot].SetDefaults(mod.ItemType("ExampleWorkbench"));
nextSlot++;
shop.item[nextSlot].SetDefaults(mod.ItemType("ExampleChair"));
nextSlot++;
shop.item[nextSlot].SetDefaults(mod.ItemType("ExampleDoor"));
nextSlot++;
shop.item[nextSlot].SetDefaults(mod.ItemType("ExampleBed"));
nextSlot++;
shop.item[nextSlot].SetDefaults(mod.ItemType("ExampleChest"));
nextSlot++;
shop.item[nextSlot].SetDefaults(mod.ItemType("ExamplePickaxe"));
nextSlot++;
shop.item[nextSlot].SetDefaults(mod.ItemType("ExampleHamaxe"));
nextSlot++;
if (Main.LocalPlayer.GetModPlayer<ExamplePlayer>(mod).ZoneExample)
{
shop.item[nextSlot].SetDefaults(mod.ItemType("ExampleWings"));
nextSlot++;
}
if (Main.moonPhase < 2)
{
shop.item[nextSlot].SetDefaults(mod.ItemType("ExampleSword"));
nextSlot++;
}
else if (Main.moonPhase < 4)
{
shop.item[nextSlot].SetDefaults(mod.ItemType("ExampleGun"));
nextSlot++;
shop.item[nextSlot].SetDefaults(mod.ItemType("ExampleBullet"));
nextSlot++;
}
else if (Main.moonPhase < 6)
{
shop.item[nextSlot].SetDefaults(mod.ItemType("ExampleStaff"));
nextSlot++;
}
else
{
}
// Here is an example of how your npc can sell items from other mods.
if (ModLoader.GetLoadedMods().Contains("SummonersAssociation"))
{
shop.item[nextSlot].SetDefaults(ModLoader.GetMod("SummonersAssociation").ItemType("BloodTalisman"));
nextSlot++;
}
}
public override void TownNPCAttackStrength(ref int damage, ref float knockback)
{
damage = 20;
knockback = 4f;
}
public override void TownNPCAttackCooldown(ref int cooldown, ref int randExtraCooldown)
{
cooldown = 30;
randExtraCooldown = 30;
}
public override void TownNPCAttackProj(ref int projType, ref int attackDelay)
{
projType = mod.ProjectileType("SparklingBall");
attackDelay = 1;
}
public override void TownNPCAttackProjSpeed(ref float multiplier, ref float gravityCorrection, ref float randomOffset)
{
multiplier = 12f;
randomOffset = 2f;
}
}
}
| |
using System.Net;
using FluentAssertions;
using JsonApiDotNetCore.Configuration;
using JsonApiDotNetCore.Serialization.Objects;
using Microsoft.Extensions.DependencyInjection;
using TestBuildingBlocks;
using Xunit;
namespace JsonApiDotNetCoreTests.IntegrationTests.QueryStrings.Pagination;
public sealed class PaginationWithoutTotalCountTests : IClassFixture<IntegrationTestContext<TestableStartup<QueryStringDbContext>, QueryStringDbContext>>
{
private const string HostPrefix = "http://localhost";
private const int DefaultPageSize = 5;
private readonly IntegrationTestContext<TestableStartup<QueryStringDbContext>, QueryStringDbContext> _testContext;
private readonly QueryStringFakers _fakers = new();
public PaginationWithoutTotalCountTests(IntegrationTestContext<TestableStartup<QueryStringDbContext>, QueryStringDbContext> testContext)
{
_testContext = testContext;
testContext.UseController<BlogPostsController>();
testContext.UseController<WebAccountsController>();
var options = (JsonApiOptions)testContext.Factory.Services.GetRequiredService<IJsonApiOptions>();
options.IncludeTotalResourceCount = false;
options.DefaultPageSize = new PageSize(DefaultPageSize);
options.AllowUnknownQueryStringParameters = true;
}
[Fact]
public async Task Hides_pagination_links_when_unconstrained_page_size()
{
// Arrange
var options = (JsonApiOptions)_testContext.Factory.Services.GetRequiredService<IJsonApiOptions>();
options.DefaultPageSize = null;
const string route = "/blogPosts?foo=bar";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.OK);
responseDocument.Links.ShouldNotBeNull();
responseDocument.Links.Self.Should().Be($"{HostPrefix}{route}");
responseDocument.Links.First.Should().BeNull();
responseDocument.Links.Last.Should().BeNull();
responseDocument.Links.Prev.Should().BeNull();
responseDocument.Links.Next.Should().BeNull();
}
[Fact]
public async Task Renders_pagination_links_when_page_size_is_specified_in_query_string_with_no_data()
{
// Arrange
var options = (JsonApiOptions)_testContext.Factory.Services.GetRequiredService<IJsonApiOptions>();
options.DefaultPageSize = null;
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
await dbContext.ClearTableAsync<BlogPost>();
await dbContext.SaveChangesAsync();
});
const string route = "/blogPosts?page[size]=8&foo=bar";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.OK);
responseDocument.Links.ShouldNotBeNull();
responseDocument.Links.Self.Should().Be($"{HostPrefix}{route}");
responseDocument.Links.First.Should().Be($"{HostPrefix}/blogPosts?page%5Bsize%5D=8&foo=bar");
responseDocument.Links.Last.Should().BeNull();
responseDocument.Links.Prev.Should().BeNull();
responseDocument.Links.Next.Should().BeNull();
}
[Fact]
public async Task Renders_pagination_links_when_page_number_is_specified_in_query_string_with_no_data()
{
// Arrange
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
await dbContext.ClearTableAsync<BlogPost>();
await dbContext.SaveChangesAsync();
});
const string route = "/blogPosts?page[number]=2&foo=bar";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.OK);
responseDocument.Links.ShouldNotBeNull();
responseDocument.Links.Self.Should().Be($"{HostPrefix}{route}");
responseDocument.Links.First.Should().Be($"{HostPrefix}/blogPosts?foo=bar");
responseDocument.Links.Last.Should().BeNull();
responseDocument.Links.Prev.Should().Be(responseDocument.Links.First);
responseDocument.Links.Next.Should().BeNull();
}
[Fact]
public async Task Renders_pagination_links_when_page_number_is_specified_in_query_string_with_partially_filled_page()
{
// Arrange
List<BlogPost> posts = _fakers.BlogPost.Generate(12);
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
await dbContext.ClearTableAsync<BlogPost>();
dbContext.Posts.AddRange(posts);
await dbContext.SaveChangesAsync();
});
const string route = "/blogPosts?foo=bar&page[number]=3";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.OK);
responseDocument.Data.ManyValue.Should().HaveCountLessThan(DefaultPageSize);
responseDocument.Links.ShouldNotBeNull();
responseDocument.Links.Self.Should().Be($"{HostPrefix}{route}");
responseDocument.Links.First.Should().Be($"{HostPrefix}/blogPosts?foo=bar");
responseDocument.Links.Last.Should().BeNull();
responseDocument.Links.Prev.Should().Be($"{HostPrefix}/blogPosts?foo=bar&page%5Bnumber%5D=2");
responseDocument.Links.Next.Should().BeNull();
}
[Fact]
public async Task Renders_pagination_links_when_page_number_is_specified_in_query_string_with_full_page()
{
// Arrange
List<BlogPost> posts = _fakers.BlogPost.Generate(DefaultPageSize * 3);
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
await dbContext.ClearTableAsync<BlogPost>();
dbContext.Posts.AddRange(posts);
await dbContext.SaveChangesAsync();
});
const string route = "/blogPosts?page[number]=3&foo=bar";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.OK);
responseDocument.Data.ManyValue.ShouldHaveCount(DefaultPageSize);
responseDocument.Links.ShouldNotBeNull();
responseDocument.Links.Self.Should().Be($"{HostPrefix}{route}");
responseDocument.Links.First.Should().Be($"{HostPrefix}/blogPosts?foo=bar");
responseDocument.Links.Last.Should().BeNull();
responseDocument.Links.Prev.Should().Be($"{HostPrefix}/blogPosts?page%5Bnumber%5D=2&foo=bar");
responseDocument.Links.Next.Should().Be($"{HostPrefix}/blogPosts?page%5Bnumber%5D=4&foo=bar");
}
[Fact]
public async Task Renders_pagination_links_when_page_number_is_specified_in_query_string_with_full_page_on_secondary_endpoint()
{
// Arrange
WebAccount account = _fakers.WebAccount.Generate();
account.Posts = _fakers.BlogPost.Generate(DefaultPageSize * 3);
await _testContext.RunOnDatabaseAsync(async dbContext =>
{
dbContext.Accounts.Add(account);
await dbContext.SaveChangesAsync();
});
string route = $"/webAccounts/{account.StringId}/posts?page[number]=3&foo=bar";
// Act
(HttpResponseMessage httpResponse, Document responseDocument) = await _testContext.ExecuteGetAsync<Document>(route);
// Assert
httpResponse.Should().HaveStatusCode(HttpStatusCode.OK);
responseDocument.Data.ManyValue.ShouldHaveCount(DefaultPageSize);
responseDocument.Links.ShouldNotBeNull();
responseDocument.Links.Self.Should().Be($"{HostPrefix}{route}");
responseDocument.Links.First.Should().Be($"{HostPrefix}/webAccounts/{account.StringId}/posts?foo=bar");
responseDocument.Links.Last.Should().BeNull();
responseDocument.Links.Prev.Should().Be($"{HostPrefix}/webAccounts/{account.StringId}/posts?page%5Bnumber%5D=2&foo=bar");
responseDocument.Links.Next.Should().Be($"{HostPrefix}/webAccounts/{account.StringId}/posts?page%5Bnumber%5D=4&foo=bar");
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.Runtime.InteropServices
{
using System;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Diagnostics.Contracts;
#if BIT64
using nint = System.Int64;
#else
using nint = System.Int32;
#endif
// These are the types of handles used by the EE.
// IMPORTANT: These must match the definitions in ObjectHandle.h in the EE.
// IMPORTANT: If new values are added to the enum the GCHandle::MaxHandleType
// constant must be updated.
public enum GCHandleType
{
Weak = 0,
WeakTrackResurrection = 1,
Normal = 2,
Pinned = 3
}
// This class allows you to create an opaque, GC handle to any
// COM+ object. A GC handle is used when an object reference must be
// reachable from unmanaged memory. There are 3 kinds of roots:
// Normal - keeps the object from being collected.
// Weak - allows object to be collected and handle contents will be zeroed.
// Weak references are zeroed before the finalizer runs, so if the
// object is resurrected in the finalizer the weak reference is
// still zeroed.
// WeakTrackResurrection - Same as weak, but stays until after object is
// really gone.
// Pinned - same as normal, but allows the address of the actual object
// to be taken.
//
[StructLayout(LayoutKind.Sequential)]
public struct GCHandle
{
// IMPORTANT: This must be kept in sync with the GCHandleType enum.
private const GCHandleType MaxHandleType = GCHandleType.Pinned;
#if MDA_SUPPORTED
static GCHandle()
{
s_probeIsActive = Mda.IsInvalidGCHandleCookieProbeEnabled();
if (s_probeIsActive)
s_cookieTable = new GCHandleCookieTable();
}
#endif
// Allocate a handle storing the object and the type.
internal GCHandle(Object value, GCHandleType type)
{
// Make sure the type parameter is within the valid range for the enum.
if ((uint)type > (uint)MaxHandleType)
ThrowArgumentOutOfRangeException_ArgumentOutOfRange_Enum();
Contract.EndContractBlock();
IntPtr handle = InternalAlloc(value, type);
if (type == GCHandleType.Pinned)
{
// Record if the handle is pinned.
handle = (IntPtr)((nint)handle | 1);
}
m_handle = handle;
}
// Used in the conversion functions below.
internal GCHandle(IntPtr handle)
{
m_handle = handle;
}
// Creates a new GC handle for an object.
//
// value - The object that the GC handle is created for.
// type - The type of GC handle to create.
//
// returns a new GC handle that protects the object.
public static GCHandle Alloc(Object value)
{
return new GCHandle(value, GCHandleType.Normal);
}
public static GCHandle Alloc(Object value, GCHandleType type)
{
return new GCHandle(value, type);
}
// Frees a GC handle.
public void Free()
{
// Free the handle if it hasn't already been freed.
IntPtr handle = Interlocked.Exchange(ref m_handle, IntPtr.Zero);
ValidateHandle(handle);
#if MDA_SUPPORTED
// If this handle was passed out to unmanaged code, we need to remove it
// from the cookie table.
// NOTE: the entry in the cookie table must be released before the
// internal handle is freed to prevent a race with reusing GC handles.
if (s_probeIsActive)
s_cookieTable.RemoveHandleIfPresent(handle);
#endif
InternalFree(GetHandleValue(handle));
}
// Target property - allows getting / updating of the handle's referent.
public Object Target
{
get
{
ValidateHandle();
return InternalGet(GetHandleValue());
}
set
{
ValidateHandle();
InternalSet(GetHandleValue(), value, IsPinned());
}
}
// Retrieve the address of an object in a Pinned handle. This throws
// an exception if the handle is any type other than Pinned.
public IntPtr AddrOfPinnedObject()
{
// Check if the handle was not a pinned handle.
if (!IsPinned())
{
ValidateHandle();
// You can only get the address of pinned handles.
throw new InvalidOperationException(SR.InvalidOperation_HandleIsNotPinned);
}
// Get the address.
return InternalAddrOfPinnedObject(GetHandleValue());
}
// Determine whether this handle has been allocated or not.
public bool IsAllocated => !m_handle.IsNull();
// Used to create a GCHandle from an int. This is intended to
// be used with the reverse conversion.
public static explicit operator GCHandle(IntPtr value)
{
ValidateHandle(value);
return new GCHandle(value);
}
public static GCHandle FromIntPtr(IntPtr value)
{
ValidateHandle(value);
Contract.EndContractBlock();
#if MDA_SUPPORTED
IntPtr handle = value;
if (s_probeIsActive)
{
// Make sure this cookie matches up with a GCHandle we've passed out a cookie for.
handle = s_cookieTable.GetHandle(value);
if (IntPtr.Zero == handle)
{
// Fire an MDA if we were unable to retrieve the GCHandle.
Mda.FireInvalidGCHandleCookieProbe(value);
return new GCHandle(IntPtr.Zero);
}
return new GCHandle(handle);
}
#endif
return new GCHandle(value);
}
// Used to get the internal integer representation of the handle out.
public static explicit operator IntPtr(GCHandle value)
{
return ToIntPtr(value);
}
public static IntPtr ToIntPtr(GCHandle value)
{
#if MDA_SUPPORTED
if (s_probeIsActive)
{
// Remember that we passed this GCHandle out by storing the cookie we returned so we
// can later validate.
return s_cookieTable.FindOrAddHandle(value.m_handle);
}
#endif
return value.m_handle;
}
public override int GetHashCode()
{
return m_handle.GetHashCode();
}
public override bool Equals(Object o)
{
GCHandle hnd;
// Check that o is a GCHandle first
if (o == null || !(o is GCHandle))
return false;
else
hnd = (GCHandle)o;
return m_handle == hnd.m_handle;
}
public static bool operator ==(GCHandle a, GCHandle b)
{
return a.m_handle == b.m_handle;
}
public static bool operator !=(GCHandle a, GCHandle b)
{
return a.m_handle != b.m_handle;
}
internal IntPtr GetHandleValue()
{
return GetHandleValue(m_handle);
}
private static IntPtr GetHandleValue(IntPtr handle)
{
// Remove Pin flag
return new IntPtr((nint)handle & ~(nint)1);
}
internal bool IsPinned()
{
// Check Pin flag
return ((nint)m_handle & 1) != 0;
}
// Internal native calls that this implementation uses.
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern IntPtr InternalAlloc(Object value, GCHandleType type);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void InternalFree(IntPtr handle);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern Object InternalGet(IntPtr handle);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern void InternalSet(IntPtr handle, Object value, bool isPinned);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern Object InternalCompareExchange(IntPtr handle, Object value, Object oldValue, bool isPinned);
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern IntPtr InternalAddrOfPinnedObject(IntPtr handle);
// The actual integer handle value that the EE uses internally.
private IntPtr m_handle;
#if MDA_SUPPORTED
// The GCHandle cookie table.
static private volatile GCHandleCookieTable s_cookieTable = null;
static private volatile bool s_probeIsActive = false;
#endif
private void ValidateHandle()
{
// Check if the handle was never initialized or was freed.
if (m_handle.IsNull())
ThrowInvalidOperationException_HandleIsNotInitialized();
}
private static void ValidateHandle(IntPtr handle)
{
// Check if the handle was never initialized or was freed.
if (handle.IsNull())
ThrowInvalidOperationException_HandleIsNotInitialized();
}
private static void ThrowArgumentOutOfRangeException_ArgumentOutOfRange_Enum()
{
throw ThrowHelper.GetArgumentOutOfRangeException(ExceptionArgument.type, ExceptionResource.ArgumentOutOfRange_Enum);
}
private static void ThrowInvalidOperationException_HandleIsNotInitialized()
{
throw ThrowHelper.GetInvalidOperationException(ExceptionResource.InvalidOperation_HandleIsNotInitialized);
}
}
}
| |
/**
* Copyright 2017 IBM Corp. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System.Collections.Generic;
using IBM.WatsonDeveloperCloud.Conversation.v1.Model;
using IBM.WatsonDeveloperCloud.Http;
using IBM.WatsonDeveloperCloud.Service;
using Newtonsoft.Json;
using System;
namespace IBM.WatsonDeveloperCloud.Conversation.v1
{
public class ConversationService : WatsonService, IConversationService
{
const string SERVICE_NAME = "conversation";
const string URL = "https://gateway.watsonplatform.net/conversation/api";
private string _versionDate;
public string VersionDate
{
get { return _versionDate; }
set { _versionDate = value; }
}
/** The Constant CONVERSATION_VERSION_DATE_2017_05_26. */
public static string CONVERSATION_VERSION_DATE_2017_05_26 = "2017-05-26";
public ConversationService() : base(SERVICE_NAME, URL)
{
if(!string.IsNullOrEmpty(this.Endpoint))
this.Endpoint = URL;
}
public ConversationService(string userName, string password, string versionDate) : this()
{
if (string.IsNullOrEmpty(userName))
throw new ArgumentNullException(nameof(userName));
if (string.IsNullOrEmpty(password))
throw new ArgumentNullException(nameof(password));
this.SetCredential(userName, password);
if(string.IsNullOrEmpty(versionDate))
throw new ArgumentNullException("versionDate cannot be null. Use 'CONVERSATION_VERSION_DATE_2017_05_26'");
VersionDate = versionDate;
}
public ConversationService(IClient httpClient) : this()
{
if (httpClient == null)
throw new ArgumentNullException(nameof(httpClient));
this.Client = httpClient;
}
public ExampleResponse CreateCounterexample(string workspaceId, CreateExample body)
{
if (string.IsNullOrEmpty(workspaceId))
throw new ArgumentNullException(nameof(workspaceId));
if (body == null)
throw new ArgumentNullException(nameof(body));
if(string.IsNullOrEmpty(VersionDate))
throw new ArgumentNullException("versionDate cannot be null. Use 'CONVERSATION_VERSION_DATE_2017_05_26'");
ExampleResponse result = null;
try
{
result = this.Client.WithAuthentication(this.UserName, this.Password)
.PostAsync($"{this.Endpoint}/v1/workspaces/{workspaceId}/counterexamples")
.WithArgument("version", VersionDate)
.WithBody<CreateExample>(body)
.As<ExampleResponse>()
.Result;
}
catch(AggregateException ae)
{
throw ae.Flatten();
}
return result;
}
public object DeleteCounterexample(string workspaceId, string text)
{
if (string.IsNullOrEmpty(workspaceId))
throw new ArgumentNullException(nameof(workspaceId));
if (string.IsNullOrEmpty(text))
throw new ArgumentNullException(nameof(text));
if(string.IsNullOrEmpty(VersionDate))
throw new ArgumentNullException("versionDate cannot be null. Use 'CONVERSATION_VERSION_DATE_2017_05_26'");
object result = null;
try
{
result = this.Client.WithAuthentication(this.UserName, this.Password)
.DeleteAsync($"{this.Endpoint}/v1/workspaces/{workspaceId}/counterexamples/{text}")
.WithArgument("version", VersionDate)
.As<object>()
.Result;
}
catch(AggregateException ae)
{
throw ae.Flatten();
}
return result;
}
public ExampleResponse GetCounterexample(string workspaceId, string text)
{
if (string.IsNullOrEmpty(workspaceId))
throw new ArgumentNullException(nameof(workspaceId));
if (string.IsNullOrEmpty(text))
throw new ArgumentNullException(nameof(text));
if(string.IsNullOrEmpty(VersionDate))
throw new ArgumentNullException("versionDate cannot be null. Use 'CONVERSATION_VERSION_DATE_2017_05_26'");
ExampleResponse result = null;
try
{
result = this.Client.WithAuthentication(this.UserName, this.Password)
.GetAsync($"{this.Endpoint}/v1/workspaces/{workspaceId}/counterexamples/{text}")
.WithArgument("version", VersionDate)
.As<ExampleResponse>()
.Result;
}
catch(AggregateException ae)
{
throw ae.Flatten();
}
return result;
}
public CounterexampleCollectionResponse ListCounterexamples(string workspaceId, long? pageLimit = null, bool? includeCount = null, string sort = null, string cursor = null)
{
if (string.IsNullOrEmpty(workspaceId))
throw new ArgumentNullException(nameof(workspaceId));
if(string.IsNullOrEmpty(VersionDate))
throw new ArgumentNullException("versionDate cannot be null. Use 'CONVERSATION_VERSION_DATE_2017_05_26'");
CounterexampleCollectionResponse result = null;
try
{
result = this.Client.WithAuthentication(this.UserName, this.Password)
.GetAsync($"{this.Endpoint}/v1/workspaces/{workspaceId}/counterexamples")
.WithArgument("version", VersionDate)
.WithArgument("page_limit", pageLimit)
.WithArgument("include_count", includeCount)
.WithArgument("sort", sort)
.WithArgument("cursor", cursor)
.As<CounterexampleCollectionResponse>()
.Result;
}
catch(AggregateException ae)
{
throw ae.Flatten();
}
return result;
}
public ExampleResponse UpdateCounterexample(string workspaceId, string text, UpdateExample body)
{
if (string.IsNullOrEmpty(workspaceId))
throw new ArgumentNullException(nameof(workspaceId));
if (string.IsNullOrEmpty(text))
throw new ArgumentNullException(nameof(text));
if (body == null)
throw new ArgumentNullException(nameof(body));
if(string.IsNullOrEmpty(VersionDate))
throw new ArgumentNullException("versionDate cannot be null. Use 'CONVERSATION_VERSION_DATE_2017_05_26'");
ExampleResponse result = null;
try
{
result = this.Client.WithAuthentication(this.UserName, this.Password)
.PostAsync($"{this.Endpoint}/v1/workspaces/{workspaceId}/counterexamples/{text}")
.WithArgument("version", VersionDate)
.WithBody<UpdateExample>(body)
.As<ExampleResponse>()
.Result;
}
catch(AggregateException ae)
{
throw ae.Flatten();
}
return result;
}
public EntityResponse CreateEntity(string workspaceId, CreateEntity body)
{
if (string.IsNullOrEmpty(workspaceId))
throw new ArgumentNullException(nameof(workspaceId));
if (body == null)
throw new ArgumentNullException(nameof(body));
if(string.IsNullOrEmpty(VersionDate))
throw new ArgumentNullException("versionDate cannot be null. Use 'CONVERSATION_VERSION_DATE_2017_05_26'");
EntityResponse result = null;
try
{
result = this.Client.WithAuthentication(this.UserName, this.Password)
.PostAsync($"{this.Endpoint}/v1/workspaces/{workspaceId}/entities")
.WithArgument("version", VersionDate)
.WithBody<CreateEntity>(body)
.As<EntityResponse>()
.Result;
}
catch(AggregateException ae)
{
throw ae.Flatten();
}
return result;
}
public object DeleteEntity(string workspaceId, string entity)
{
if (string.IsNullOrEmpty(workspaceId))
throw new ArgumentNullException(nameof(workspaceId));
if (string.IsNullOrEmpty(entity))
throw new ArgumentNullException(nameof(entity));
if(string.IsNullOrEmpty(VersionDate))
throw new ArgumentNullException("versionDate cannot be null. Use 'CONVERSATION_VERSION_DATE_2017_05_26'");
object result = null;
try
{
result = this.Client.WithAuthentication(this.UserName, this.Password)
.DeleteAsync($"{this.Endpoint}/v1/workspaces/{workspaceId}/entities/{entity}")
.WithArgument("version", VersionDate)
.As<object>()
.Result;
}
catch(AggregateException ae)
{
throw ae.Flatten();
}
return result;
}
public EntityExportResponse GetEntity(string workspaceId, string entity, bool? export = null)
{
if (string.IsNullOrEmpty(workspaceId))
throw new ArgumentNullException(nameof(workspaceId));
if (string.IsNullOrEmpty(entity))
throw new ArgumentNullException(nameof(entity));
if(string.IsNullOrEmpty(VersionDate))
throw new ArgumentNullException("versionDate cannot be null. Use 'CONVERSATION_VERSION_DATE_2017_05_26'");
EntityExportResponse result = null;
try
{
result = this.Client.WithAuthentication(this.UserName, this.Password)
.GetAsync($"{this.Endpoint}/v1/workspaces/{workspaceId}/entities/{entity}")
.WithArgument("version", VersionDate)
.WithArgument("export", export)
.As<EntityExportResponse>()
.Result;
}
catch(AggregateException ae)
{
throw ae.Flatten();
}
return result;
}
public EntityCollectionResponse ListEntities(string workspaceId, bool? export = null, long? pageLimit = null, bool? includeCount = null, string sort = null, string cursor = null)
{
if (string.IsNullOrEmpty(workspaceId))
throw new ArgumentNullException(nameof(workspaceId));
if(string.IsNullOrEmpty(VersionDate))
throw new ArgumentNullException("versionDate cannot be null. Use 'CONVERSATION_VERSION_DATE_2017_05_26'");
EntityCollectionResponse result = null;
try
{
result = this.Client.WithAuthentication(this.UserName, this.Password)
.GetAsync($"{this.Endpoint}/v1/workspaces/{workspaceId}/entities")
.WithArgument("version", VersionDate)
.WithArgument("export", export)
.WithArgument("page_limit", pageLimit)
.WithArgument("include_count", includeCount)
.WithArgument("sort", sort)
.WithArgument("cursor", cursor)
.As<EntityCollectionResponse>()
.Result;
}
catch(AggregateException ae)
{
throw ae.Flatten();
}
return result;
}
public EntityResponse UpdateEntity(string workspaceId, string entity, UpdateEntity body)
{
if (string.IsNullOrEmpty(workspaceId))
throw new ArgumentNullException(nameof(workspaceId));
if (string.IsNullOrEmpty(entity))
throw new ArgumentNullException(nameof(entity));
if (body == null)
throw new ArgumentNullException(nameof(body));
if(string.IsNullOrEmpty(VersionDate))
throw new ArgumentNullException("versionDate cannot be null. Use 'CONVERSATION_VERSION_DATE_2017_05_26'");
EntityResponse result = null;
try
{
result = this.Client.WithAuthentication(this.UserName, this.Password)
.PostAsync($"{this.Endpoint}/v1/workspaces/{workspaceId}/entities/{entity}")
.WithArgument("version", VersionDate)
.WithBody<UpdateEntity>(body)
.As<EntityResponse>()
.Result;
}
catch(AggregateException ae)
{
throw ae.Flatten();
}
return result;
}
public ExampleResponse CreateExample(string workspaceId, string intent, CreateExample body)
{
if (string.IsNullOrEmpty(workspaceId))
throw new ArgumentNullException(nameof(workspaceId));
if (string.IsNullOrEmpty(intent))
throw new ArgumentNullException(nameof(intent));
if (body == null)
throw new ArgumentNullException(nameof(body));
if(string.IsNullOrEmpty(VersionDate))
throw new ArgumentNullException("versionDate cannot be null. Use 'CONVERSATION_VERSION_DATE_2017_05_26'");
ExampleResponse result = null;
try
{
result = this.Client.WithAuthentication(this.UserName, this.Password)
.PostAsync($"{this.Endpoint}/v1/workspaces/{workspaceId}/intents/{intent}/examples")
.WithArgument("version", VersionDate)
.WithBody<CreateExample>(body)
.As<ExampleResponse>()
.Result;
}
catch(AggregateException ae)
{
throw ae.Flatten();
}
return result;
}
public object DeleteExample(string workspaceId, string intent, string text)
{
if (string.IsNullOrEmpty(workspaceId))
throw new ArgumentNullException(nameof(workspaceId));
if (string.IsNullOrEmpty(intent))
throw new ArgumentNullException(nameof(intent));
if (string.IsNullOrEmpty(text))
throw new ArgumentNullException(nameof(text));
if(string.IsNullOrEmpty(VersionDate))
throw new ArgumentNullException("versionDate cannot be null. Use 'CONVERSATION_VERSION_DATE_2017_05_26'");
object result = null;
try
{
result = this.Client.WithAuthentication(this.UserName, this.Password)
.DeleteAsync($"{this.Endpoint}/v1/workspaces/{workspaceId}/intents/{intent}/examples/{text}")
.WithArgument("version", VersionDate)
.As<object>()
.Result;
}
catch(AggregateException ae)
{
throw ae.Flatten();
}
return result;
}
public ExampleResponse GetExample(string workspaceId, string intent, string text)
{
if (string.IsNullOrEmpty(workspaceId))
throw new ArgumentNullException(nameof(workspaceId));
if (string.IsNullOrEmpty(intent))
throw new ArgumentNullException(nameof(intent));
if (string.IsNullOrEmpty(text))
throw new ArgumentNullException(nameof(text));
if(string.IsNullOrEmpty(VersionDate))
throw new ArgumentNullException("versionDate cannot be null. Use 'CONVERSATION_VERSION_DATE_2017_05_26'");
ExampleResponse result = null;
try
{
result = this.Client.WithAuthentication(this.UserName, this.Password)
.GetAsync($"{this.Endpoint}/v1/workspaces/{workspaceId}/intents/{intent}/examples/{text}")
.WithArgument("version", VersionDate)
.As<ExampleResponse>()
.Result;
}
catch(AggregateException ae)
{
throw ae.Flatten();
}
return result;
}
public ExampleCollectionResponse ListExamples(string workspaceId, string intent, long? pageLimit = null, bool? includeCount = null, string sort = null, string cursor = null)
{
if (string.IsNullOrEmpty(workspaceId))
throw new ArgumentNullException(nameof(workspaceId));
if (string.IsNullOrEmpty(intent))
throw new ArgumentNullException(nameof(intent));
if(string.IsNullOrEmpty(VersionDate))
throw new ArgumentNullException("versionDate cannot be null. Use 'CONVERSATION_VERSION_DATE_2017_05_26'");
ExampleCollectionResponse result = null;
try
{
result = this.Client.WithAuthentication(this.UserName, this.Password)
.GetAsync($"{this.Endpoint}/v1/workspaces/{workspaceId}/intents/{intent}/examples")
.WithArgument("version", VersionDate)
.WithArgument("page_limit", pageLimit)
.WithArgument("include_count", includeCount)
.WithArgument("sort", sort)
.WithArgument("cursor", cursor)
.As<ExampleCollectionResponse>()
.Result;
}
catch(AggregateException ae)
{
throw ae.Flatten();
}
return result;
}
public ExampleResponse UpdateExample(string workspaceId, string intent, string text, UpdateExample body)
{
if (string.IsNullOrEmpty(workspaceId))
throw new ArgumentNullException(nameof(workspaceId));
if (string.IsNullOrEmpty(intent))
throw new ArgumentNullException(nameof(intent));
if (string.IsNullOrEmpty(text))
throw new ArgumentNullException(nameof(text));
if (body == null)
throw new ArgumentNullException(nameof(body));
if(string.IsNullOrEmpty(VersionDate))
throw new ArgumentNullException("versionDate cannot be null. Use 'CONVERSATION_VERSION_DATE_2017_05_26'");
ExampleResponse result = null;
try
{
result = this.Client.WithAuthentication(this.UserName, this.Password)
.PostAsync($"{this.Endpoint}/v1/workspaces/{workspaceId}/intents/{intent}/examples/{text}")
.WithArgument("version", VersionDate)
.WithBody<UpdateExample>(body)
.As<ExampleResponse>()
.Result;
}
catch(AggregateException ae)
{
throw ae.Flatten();
}
return result;
}
public IntentResponse CreateIntent(string workspaceId, CreateIntent body)
{
if (string.IsNullOrEmpty(workspaceId))
throw new ArgumentNullException(nameof(workspaceId));
if (body == null)
throw new ArgumentNullException(nameof(body));
if(string.IsNullOrEmpty(VersionDate))
throw new ArgumentNullException("versionDate cannot be null. Use 'CONVERSATION_VERSION_DATE_2017_05_26'");
IntentResponse result = null;
try
{
result = this.Client.WithAuthentication(this.UserName, this.Password)
.PostAsync($"{this.Endpoint}/v1/workspaces/{workspaceId}/intents")
.WithArgument("version", VersionDate)
.WithBody<CreateIntent>(body)
.As<IntentResponse>()
.Result;
}
catch(AggregateException ae)
{
throw ae.Flatten();
}
return result;
}
public object DeleteIntent(string workspaceId, string intent)
{
if (string.IsNullOrEmpty(workspaceId))
throw new ArgumentNullException(nameof(workspaceId));
if (string.IsNullOrEmpty(intent))
throw new ArgumentNullException(nameof(intent));
if(string.IsNullOrEmpty(VersionDate))
throw new ArgumentNullException("versionDate cannot be null. Use 'CONVERSATION_VERSION_DATE_2017_05_26'");
object result = null;
try
{
result = this.Client.WithAuthentication(this.UserName, this.Password)
.DeleteAsync($"{this.Endpoint}/v1/workspaces/{workspaceId}/intents/{intent}")
.WithArgument("version", VersionDate)
.As<object>()
.Result;
}
catch(AggregateException ae)
{
throw ae.Flatten();
}
return result;
}
public IntentExportResponse GetIntent(string workspaceId, string intent, bool? export = null)
{
if (string.IsNullOrEmpty(workspaceId))
throw new ArgumentNullException(nameof(workspaceId));
if (string.IsNullOrEmpty(intent))
throw new ArgumentNullException(nameof(intent));
if(string.IsNullOrEmpty(VersionDate))
throw new ArgumentNullException("versionDate cannot be null. Use 'CONVERSATION_VERSION_DATE_2017_05_26'");
IntentExportResponse result = null;
try
{
result = this.Client.WithAuthentication(this.UserName, this.Password)
.GetAsync($"{this.Endpoint}/v1/workspaces/{workspaceId}/intents/{intent}")
.WithArgument("version", VersionDate)
.WithArgument("export", export)
.As<IntentExportResponse>()
.Result;
}
catch(AggregateException ae)
{
throw ae.Flatten();
}
return result;
}
public IntentCollectionResponse ListIntents(string workspaceId, bool? export = null, long? pageLimit = null, bool? includeCount = null, string sort = null, string cursor = null)
{
if (string.IsNullOrEmpty(workspaceId))
throw new ArgumentNullException(nameof(workspaceId));
if(string.IsNullOrEmpty(VersionDate))
throw new ArgumentNullException("versionDate cannot be null. Use 'CONVERSATION_VERSION_DATE_2017_05_26'");
IntentCollectionResponse result = null;
try
{
result = this.Client.WithAuthentication(this.UserName, this.Password)
.GetAsync($"{this.Endpoint}/v1/workspaces/{workspaceId}/intents")
.WithArgument("version", VersionDate)
.WithArgument("export", export)
.WithArgument("page_limit", pageLimit)
.WithArgument("include_count", includeCount)
.WithArgument("sort", sort)
.WithArgument("cursor", cursor)
.As<IntentCollectionResponse>()
.Result;
}
catch(AggregateException ae)
{
throw ae.Flatten();
}
return result;
}
public IntentResponse UpdateIntent(string workspaceId, string intent, UpdateIntent body)
{
if (string.IsNullOrEmpty(workspaceId))
throw new ArgumentNullException(nameof(workspaceId));
if (string.IsNullOrEmpty(intent))
throw new ArgumentNullException(nameof(intent));
if (body == null)
throw new ArgumentNullException(nameof(body));
if(string.IsNullOrEmpty(VersionDate))
throw new ArgumentNullException("versionDate cannot be null. Use 'CONVERSATION_VERSION_DATE_2017_05_26'");
IntentResponse result = null;
try
{
result = this.Client.WithAuthentication(this.UserName, this.Password)
.PostAsync($"{this.Endpoint}/v1/workspaces/{workspaceId}/intents/{intent}")
.WithArgument("version", VersionDate)
.WithBody<UpdateIntent>(body)
.As<IntentResponse>()
.Result;
}
catch(AggregateException ae)
{
throw ae.Flatten();
}
return result;
}
public LogCollectionResponse ListLogs(string workspaceId, string sort = null, string filter = null, long? pageLimit = null, string cursor = null)
{
if (string.IsNullOrEmpty(workspaceId))
throw new ArgumentNullException(nameof(workspaceId));
if(string.IsNullOrEmpty(VersionDate))
throw new ArgumentNullException("versionDate cannot be null. Use 'CONVERSATION_VERSION_DATE_2017_05_26'");
LogCollectionResponse result = null;
try
{
result = this.Client.WithAuthentication(this.UserName, this.Password)
.GetAsync($"{this.Endpoint}/v1/workspaces/{workspaceId}/logs")
.WithArgument("version", VersionDate)
.WithArgument("sort", sort)
.WithArgument("filter", filter)
.WithArgument("page_limit", pageLimit)
.WithArgument("cursor", cursor)
.As<LogCollectionResponse>()
.Result;
}
catch(AggregateException ae)
{
throw ae.Flatten();
}
return result;
}
public MessageResponse Message(string workspaceId, MessageRequest body = null)
{
if (string.IsNullOrEmpty(workspaceId))
throw new ArgumentNullException(nameof(workspaceId));
if(string.IsNullOrEmpty(VersionDate))
throw new ArgumentNullException("versionDate cannot be null. Use 'CONVERSATION_VERSION_DATE_2017_05_26'");
MessageResponse result = null;
try
{
result = this.Client.WithAuthentication(this.UserName, this.Password)
.PostAsync($"{this.Endpoint}/v1/workspaces/{workspaceId}/message")
.WithArgument("version", VersionDate)
.WithBody<MessageRequest>(body)
.As<MessageResponse>()
.Result;
}
catch(AggregateException ae)
{
throw ae.Flatten();
}
return result;
}
public SynonymResponse CreateSynonym(string workspaceId, string entity, string value, CreateSynonym body)
{
if (string.IsNullOrEmpty(workspaceId))
throw new ArgumentNullException(nameof(workspaceId));
if (string.IsNullOrEmpty(entity))
throw new ArgumentNullException(nameof(entity));
if (string.IsNullOrEmpty(value))
throw new ArgumentNullException(nameof(value));
if (body == null)
throw new ArgumentNullException(nameof(body));
if(string.IsNullOrEmpty(VersionDate))
throw new ArgumentNullException("versionDate cannot be null. Use 'CONVERSATION_VERSION_DATE_2017_05_26'");
SynonymResponse result = null;
try
{
result = this.Client.WithAuthentication(this.UserName, this.Password)
.PostAsync($"{this.Endpoint}/v1/workspaces/{workspaceId}/entities/{entity}/values/{value}/synonyms")
.WithArgument("version", VersionDate)
.WithBody<CreateSynonym>(body)
.As<SynonymResponse>()
.Result;
}
catch(AggregateException ae)
{
throw ae.Flatten();
}
return result;
}
public object DeleteSynonym(string workspaceId, string entity, string value, string synonym)
{
if (string.IsNullOrEmpty(workspaceId))
throw new ArgumentNullException(nameof(workspaceId));
if (string.IsNullOrEmpty(entity))
throw new ArgumentNullException(nameof(entity));
if (string.IsNullOrEmpty(value))
throw new ArgumentNullException(nameof(value));
if (string.IsNullOrEmpty(synonym))
throw new ArgumentNullException(nameof(synonym));
if(string.IsNullOrEmpty(VersionDate))
throw new ArgumentNullException("versionDate cannot be null. Use 'CONVERSATION_VERSION_DATE_2017_05_26'");
object result = null;
try
{
result = this.Client.WithAuthentication(this.UserName, this.Password)
.DeleteAsync($"{this.Endpoint}/v1/workspaces/{workspaceId}/entities/{entity}/values/{value}/synonyms/{synonym}")
.WithArgument("version", VersionDate)
.As<object>()
.Result;
}
catch(AggregateException ae)
{
throw ae.Flatten();
}
return result;
}
public SynonymResponse GetSynonym(string workspaceId, string entity, string value, string synonym)
{
if (string.IsNullOrEmpty(workspaceId))
throw new ArgumentNullException(nameof(workspaceId));
if (string.IsNullOrEmpty(entity))
throw new ArgumentNullException(nameof(entity));
if (string.IsNullOrEmpty(value))
throw new ArgumentNullException(nameof(value));
if (string.IsNullOrEmpty(synonym))
throw new ArgumentNullException(nameof(synonym));
if(string.IsNullOrEmpty(VersionDate))
throw new ArgumentNullException("versionDate cannot be null. Use 'CONVERSATION_VERSION_DATE_2017_05_26'");
SynonymResponse result = null;
try
{
result = this.Client.WithAuthentication(this.UserName, this.Password)
.GetAsync($"{this.Endpoint}/v1/workspaces/{workspaceId}/entities/{entity}/values/{value}/synonyms/{synonym}")
.WithArgument("version", VersionDate)
.As<SynonymResponse>()
.Result;
}
catch(AggregateException ae)
{
throw ae.Flatten();
}
return result;
}
public SynonymCollectionResponse ListSynonyms(string workspaceId, string entity, string value, long? pageLimit = null, bool? includeCount = null, string sort = null, string cursor = null)
{
if (string.IsNullOrEmpty(workspaceId))
throw new ArgumentNullException(nameof(workspaceId));
if (string.IsNullOrEmpty(entity))
throw new ArgumentNullException(nameof(entity));
if (string.IsNullOrEmpty(value))
throw new ArgumentNullException(nameof(value));
if(string.IsNullOrEmpty(VersionDate))
throw new ArgumentNullException("versionDate cannot be null. Use 'CONVERSATION_VERSION_DATE_2017_05_26'");
SynonymCollectionResponse result = null;
try
{
result = this.Client.WithAuthentication(this.UserName, this.Password)
.GetAsync($"{this.Endpoint}/v1/workspaces/{workspaceId}/entities/{entity}/values/{value}/synonyms")
.WithArgument("version", VersionDate)
.WithArgument("page_limit", pageLimit)
.WithArgument("include_count", includeCount)
.WithArgument("sort", sort)
.WithArgument("cursor", cursor)
.As<SynonymCollectionResponse>()
.Result;
}
catch(AggregateException ae)
{
throw ae.Flatten();
}
return result;
}
public SynonymResponse UpdateSynonym(string workspaceId, string entity, string value, string synonym, UpdateSynonym body)
{
if (string.IsNullOrEmpty(workspaceId))
throw new ArgumentNullException(nameof(workspaceId));
if (string.IsNullOrEmpty(entity))
throw new ArgumentNullException(nameof(entity));
if (string.IsNullOrEmpty(value))
throw new ArgumentNullException(nameof(value));
if (string.IsNullOrEmpty(synonym))
throw new ArgumentNullException(nameof(synonym));
if (body == null)
throw new ArgumentNullException(nameof(body));
if(string.IsNullOrEmpty(VersionDate))
throw new ArgumentNullException("versionDate cannot be null. Use 'CONVERSATION_VERSION_DATE_2017_05_26'");
SynonymResponse result = null;
try
{
result = this.Client.WithAuthentication(this.UserName, this.Password)
.PostAsync($"{this.Endpoint}/v1/workspaces/{workspaceId}/entities/{entity}/values/{value}/synonyms/{synonym}")
.WithArgument("version", VersionDate)
.WithBody<UpdateSynonym>(body)
.As<SynonymResponse>()
.Result;
}
catch(AggregateException ae)
{
throw ae.Flatten();
}
return result;
}
public ValueResponse CreateValue(string workspaceId, string entity, CreateValue body)
{
if (string.IsNullOrEmpty(workspaceId))
throw new ArgumentNullException(nameof(workspaceId));
if (string.IsNullOrEmpty(entity))
throw new ArgumentNullException(nameof(entity));
if (body == null)
throw new ArgumentNullException(nameof(body));
if(string.IsNullOrEmpty(VersionDate))
throw new ArgumentNullException("versionDate cannot be null. Use 'CONVERSATION_VERSION_DATE_2017_05_26'");
ValueResponse result = null;
try
{
result = this.Client.WithAuthentication(this.UserName, this.Password)
.PostAsync($"{this.Endpoint}/v1/workspaces/{workspaceId}/entities/{entity}/values")
.WithArgument("version", VersionDate)
.WithBody<CreateValue>(body)
.As<ValueResponse>()
.Result;
}
catch(AggregateException ae)
{
throw ae.Flatten();
}
return result;
}
public object DeleteValue(string workspaceId, string entity, string value)
{
if (string.IsNullOrEmpty(workspaceId))
throw new ArgumentNullException(nameof(workspaceId));
if (string.IsNullOrEmpty(entity))
throw new ArgumentNullException(nameof(entity));
if (string.IsNullOrEmpty(value))
throw new ArgumentNullException(nameof(value));
if(string.IsNullOrEmpty(VersionDate))
throw new ArgumentNullException("versionDate cannot be null. Use 'CONVERSATION_VERSION_DATE_2017_05_26'");
object result = null;
try
{
result = this.Client.WithAuthentication(this.UserName, this.Password)
.DeleteAsync($"{this.Endpoint}/v1/workspaces/{workspaceId}/entities/{entity}/values/{value}")
.WithArgument("version", VersionDate)
.As<object>()
.Result;
}
catch(AggregateException ae)
{
throw ae.Flatten();
}
return result;
}
public ValueExportResponse GetValue(string workspaceId, string entity, string value, bool? export = null)
{
if (string.IsNullOrEmpty(workspaceId))
throw new ArgumentNullException(nameof(workspaceId));
if (string.IsNullOrEmpty(entity))
throw new ArgumentNullException(nameof(entity));
if (string.IsNullOrEmpty(value))
throw new ArgumentNullException(nameof(value));
if(string.IsNullOrEmpty(VersionDate))
throw new ArgumentNullException("versionDate cannot be null. Use 'CONVERSATION_VERSION_DATE_2017_05_26'");
ValueExportResponse result = null;
try
{
result = this.Client.WithAuthentication(this.UserName, this.Password)
.GetAsync($"{this.Endpoint}/v1/workspaces/{workspaceId}/entities/{entity}/values/{value}")
.WithArgument("version", VersionDate)
.WithArgument("export", export)
.As<ValueExportResponse>()
.Result;
}
catch(AggregateException ae)
{
throw ae.Flatten();
}
return result;
}
public ValueCollectionResponse ListValues(string workspaceId, string entity, bool? export = null, long? pageLimit = null, bool? includeCount = null, string sort = null, string cursor = null)
{
if (string.IsNullOrEmpty(workspaceId))
throw new ArgumentNullException(nameof(workspaceId));
if (string.IsNullOrEmpty(entity))
throw new ArgumentNullException(nameof(entity));
if(string.IsNullOrEmpty(VersionDate))
throw new ArgumentNullException("versionDate cannot be null. Use 'CONVERSATION_VERSION_DATE_2017_05_26'");
ValueCollectionResponse result = null;
try
{
result = this.Client.WithAuthentication(this.UserName, this.Password)
.GetAsync($"{this.Endpoint}/v1/workspaces/{workspaceId}/entities/{entity}/values")
.WithArgument("version", VersionDate)
.WithArgument("export", export)
.WithArgument("page_limit", pageLimit)
.WithArgument("include_count", includeCount)
.WithArgument("sort", sort)
.WithArgument("cursor", cursor)
.As<ValueCollectionResponse>()
.Result;
}
catch(AggregateException ae)
{
throw ae.Flatten();
}
return result;
}
public ValueResponse UpdateValue(string workspaceId, string entity, string value, UpdateValue body)
{
if (string.IsNullOrEmpty(workspaceId))
throw new ArgumentNullException(nameof(workspaceId));
if (string.IsNullOrEmpty(entity))
throw new ArgumentNullException(nameof(entity));
if (string.IsNullOrEmpty(value))
throw new ArgumentNullException(nameof(value));
if (body == null)
throw new ArgumentNullException(nameof(body));
if(string.IsNullOrEmpty(VersionDate))
throw new ArgumentNullException("versionDate cannot be null. Use 'CONVERSATION_VERSION_DATE_2017_05_26'");
ValueResponse result = null;
try
{
result = this.Client.WithAuthentication(this.UserName, this.Password)
.PostAsync($"{this.Endpoint}/v1/workspaces/{workspaceId}/entities/{entity}/values/{value}")
.WithArgument("version", VersionDate)
.WithBody<UpdateValue>(body)
.As<ValueResponse>()
.Result;
}
catch(AggregateException ae)
{
throw ae.Flatten();
}
return result;
}
public WorkspaceResponse CreateWorkspace(CreateWorkspace body = null)
{
if(string.IsNullOrEmpty(VersionDate))
throw new ArgumentNullException("versionDate cannot be null. Use 'CONVERSATION_VERSION_DATE_2017_05_26'");
WorkspaceResponse result = null;
try
{
result = this.Client.WithAuthentication(this.UserName, this.Password)
.PostAsync($"{this.Endpoint}/v1/workspaces")
.WithArgument("version", VersionDate)
.WithBody<CreateWorkspace>(body)
.As<WorkspaceResponse>()
.Result;
}
catch(AggregateException ae)
{
throw ae.Flatten();
}
return result;
}
public object DeleteWorkspace(string workspaceId)
{
if (string.IsNullOrEmpty(workspaceId))
throw new ArgumentNullException(nameof(workspaceId));
if(string.IsNullOrEmpty(VersionDate))
throw new ArgumentNullException("versionDate cannot be null. Use 'CONVERSATION_VERSION_DATE_2017_05_26'");
object result = null;
try
{
result = this.Client.WithAuthentication(this.UserName, this.Password)
.DeleteAsync($"{this.Endpoint}/v1/workspaces/{workspaceId}")
.WithArgument("version", VersionDate)
.As<object>()
.Result;
}
catch(AggregateException ae)
{
throw ae.Flatten();
}
return result;
}
public WorkspaceExportResponse GetWorkspace(string workspaceId, bool? export = null)
{
if (string.IsNullOrEmpty(workspaceId))
throw new ArgumentNullException(nameof(workspaceId));
if(string.IsNullOrEmpty(VersionDate))
throw new ArgumentNullException("versionDate cannot be null. Use 'CONVERSATION_VERSION_DATE_2017_05_26'");
WorkspaceExportResponse result = null;
try
{
result = this.Client.WithAuthentication(this.UserName, this.Password)
.GetAsync($"{this.Endpoint}/v1/workspaces/{workspaceId}")
.WithArgument("version", VersionDate)
.WithArgument("export", export)
.As<WorkspaceExportResponse>()
.Result;
}
catch(AggregateException ae)
{
throw ae.Flatten();
}
return result;
}
public WorkspaceCollectionResponse ListWorkspaces(long? pageLimit = null, bool? includeCount = null, string sort = null, string cursor = null)
{
if(string.IsNullOrEmpty(VersionDate))
throw new ArgumentNullException("versionDate cannot be null. Use 'CONVERSATION_VERSION_DATE_2017_05_26'");
WorkspaceCollectionResponse result = null;
try
{
result = this.Client.WithAuthentication(this.UserName, this.Password)
.GetAsync($"{this.Endpoint}/v1/workspaces")
.WithArgument("version", VersionDate)
.WithArgument("page_limit", pageLimit)
.WithArgument("include_count", includeCount)
.WithArgument("sort", sort)
.WithArgument("cursor", cursor)
.As<WorkspaceCollectionResponse>()
.Result;
}
catch(AggregateException ae)
{
throw ae.Flatten();
}
return result;
}
public WorkspaceResponse UpdateWorkspace(string workspaceId, UpdateWorkspace body = null)
{
if (string.IsNullOrEmpty(workspaceId))
throw new ArgumentNullException(nameof(workspaceId));
if(string.IsNullOrEmpty(VersionDate))
throw new ArgumentNullException("versionDate cannot be null. Use 'CONVERSATION_VERSION_DATE_2017_05_26'");
WorkspaceResponse result = null;
try
{
result = this.Client.WithAuthentication(this.UserName, this.Password)
.PostAsync($"{this.Endpoint}/v1/workspaces/{workspaceId}")
.WithArgument("version", VersionDate)
.WithBody<UpdateWorkspace>(body)
.As<WorkspaceResponse>()
.Result;
}
catch(AggregateException ae)
{
throw ae.Flatten();
}
return result;
}
}
}
| |
// (c) Copyright Microsoft Corporation.
// This source is subject to the Microsoft Permissive License.
// See http://www.microsoft.com/opensource/licenses.mspx#Ms-PL.
// All other rights reserved.
/*******************************************************************
* Purpose: InternalHelper
*******************************************************************/
using System;
using System.CodeDom;
using System.Collections;
using System.Drawing;
using System.Globalization;
using System.Threading;
using System.Windows.Automation;
using System.Windows;
namespace Microsoft.Test.UIAutomation.Tests.Patterns
{
using InternalHelper;
using InternalHelper.Tests;
using InternalHelper.Enumerations;
using Microsoft.Test.UIAutomation;
using Microsoft.Test.UIAutomation.Core;
using Microsoft.Test.UIAutomation.TestManager;
using Microsoft.Test.UIAutomation.Interfaces;
/// -----------------------------------------------------------------------
/// <summary></summary>
/// -----------------------------------------------------------------------
public sealed class GridItemTests : PatternObject
{
#region Member variables
/// -------------------------------------------------------------------
/// <summary></summary>
/// -------------------------------------------------------------------
GridItemPattern _pattern = null;
/// -------------------------------------------------------------------
/// <summary></summary>
/// -------------------------------------------------------------------
const string THIS = "GridItemTests";
#endregion Member variables
/// -------------------------------------------------------------------
/// <summary></summary>
/// -------------------------------------------------------------------
public const string TestSuite = NAMESPACE + "." + THIS;
/// -------------------------------------------------------------------
/// <summary></summary>
/// -------------------------------------------------------------------
public static readonly string TestWhichPattern = Automation.PatternName(GridItemPattern.Pattern);
/// -------------------------------------------------------------------
/// <summary></summary>
/// -------------------------------------------------------------------
public GridItemTests(AutomationElement element, TestPriorities priority, string dirResults, bool testEvents, TypeOfControl typeOfControl, IApplicationCommands commands)
:
base(element, TestSuite, priority, typeOfControl, TypeOfPattern.GridItem, dirResults, testEvents, commands)
{
_pattern = (GridItemPattern)element.GetCurrentPattern(GridItemPattern.Pattern);
if (_pattern == null)
throw new Exception(Helpers.PatternNotSupported);
}
#region Tests
/// -------------------------------------------------------------------
/// <summary></summary>
/// -------------------------------------------------------------------
[TestCaseAttribute("GridItem.ContainingGridProperty.S.1.1",
Priority = TestPriorities.Pri0,
TestCaseType = TestCaseType.Events,
EventTested = "AutomationPropertyChangedEventHandler(GridItemPattern.ContainingGridProperty)",
Status = TestStatus.Works,
Author = "Microsoft Corp.",
Description = new string[]{
"Step: Traverse up the tree to find a AutomationElement that supports GridPattern",
"Step: Get the ContainingGrid property",
"Step: Verify that the two AutomationElements are the same"
})]
public void TestGridItemContainingGridPropertyS11(TestCaseAttribute checkType)
{
HeaderComment(checkType);
AutomationElement grid1 = null;
AutomationElement grid2 = null;
//"Step: Traverse up the tree to find a AutomationElement that supports GridPattern",
TS_GetContainGridByNavigation(m_le, out grid1, CheckType.Verification);
//"Step: Get the ContainingGrid property",
TS_GetContainGridByCall(out grid2, CheckType.Verification);
//"Step: Verify that the two AutomationElements are the same"
TS_AreTheseTheSame(grid1, grid2, true, CheckType.Verification);
}
/// -------------------------------------------------------------------
/// <summary></summary>
/// -------------------------------------------------------------------
[TestCaseAttribute("GridItem.ContainingGridProperty.S.1.3",
Priority = TestPriorities.Pri0,
TestCaseType = TestCaseType.Events,
EventTested = "AutomationPropertyChangedEventHandler(GridItemPattern.ContainingGridProperty)",
Status = TestStatus.Works,
Author = "Microsoft Corp.",
Description = new string[]{
"Step: Get the AutomationElement's col",
"Step: Get the AutomationElement's row",
"Step: Add and event listener for ContainingGridProperty property change event",
"Step: Call containing grid's GetCell(row, col)",
"Step: Wait for event to occur",
"Step: Verify that listener for ContainingGridProperty property change event did not fire",
"Step: Verify that AutomationElement and one from GetCell() are the same"
})]
public void TestGridItemContainingGridPropertyS13(TestCaseAttribute checkType)
{
HeaderComment(checkType);
int col;
int row;
AutomationElement cell = null;
//"Step: Get the AutomationElement's col",
TS_GetColumn(out col, CheckType.Verification);
//"Step: Get the AutomationElement's row",
TS_GetRow(out row, CheckType.Verification);
//"Step: Add and event listener for ContainingGridProperty property change event",
TSC_AddPropertyChangedListener(m_le, TreeScope.Element, new AutomationProperty[] { GridItemPattern.ContainingGridProperty }, CheckType.Verification);
//"Step: Call containing grid's GetCell(row, col)",
TS_GetCell(row, col, out cell, CheckType.Verification);
// "Step: Wait for event to occur",
TSC_WaitForEvents(1);
//"Step: Verify that listener for ContainingGridProperty property change event did not fire",
TSC_VerifyPropertyChangedListener(m_le, new EventFired[] { EventFired.False }, new AutomationProperty[] { GridItemPattern.ContainingGridProperty }, CheckType.Verification);
//"Step: Verify that AutomationElement and one from GetCell() are the same"
TS_AreTheseTheSame(m_le, cell, true, CheckType.Verification);
}
/// -------------------------------------------------------------------
/// <summary></summary>
/// -------------------------------------------------------------------
[TestCaseAttribute("GridItem.ColumnProperty.S.3.1",
Priority = TestPriorities.BuildVerificationTest,
TestCaseType = TestCaseType.Arguments,
Status = TestStatus.Works,
Author = "Microsoft Corp.",
Description = new string[]{
"Verify: Argument supplied is the expected ColumnProperty(y) of the logical element and is of System.Int32 type",
"Cell is at (x, y), verify that ColumnProperty returns y: ",
})]
public void TestGridItemColumnPropertyS31(TestCaseAttribute checkType, object args)
{
HeaderComment(checkType);
if (args == null)
throw new ArgumentException();
if (!args.GetType().Equals(typeof(int)))
ThrowMe(CheckType.Verification, "Invalid argument type");
if (!_pattern.Current.Column.Equals(Convert.ToInt32(args, CultureInfo.CurrentUICulture)))
ThrowMe(CheckType.Verification, "ColumnProperty returned " + _pattern.Current.Column);
}
/// -------------------------------------------------------------------
/// <summary></summary>
/// -------------------------------------------------------------------
[TestCaseAttribute("GridItem.RowSpanProperty.S.4.1",
Priority = TestPriorities.BuildVerificationTest,
TestCaseType = TestCaseType.Arguments,
Status = TestStatus.Works,
Author = "Microsoft Corp.",
Description = new string[]{
"Verify: Argument supplied is the expected RowSpanProperty with System.Int32 type",
"Cell is merged according to argument supplied",
})]
public void TestGridItemColumnPropertyS41(TestCaseAttribute checkType, object args)
{
HeaderComment(checkType);
if (args == null)
throw new ArgumentException();
if (!args.GetType().Equals(typeof(int)))
ThrowMe(CheckType.Verification, "Invalid argument type");
if (!_pattern.Current.ColumnSpan.Equals(Convert.ToInt32(args, CultureInfo.CurrentUICulture)))
ThrowMe(CheckType.Verification, "ColumnSpan returned " + _pattern.Current.ColumnSpan);
}
/// -------------------------------------------------------------------
/// <summary></summary>
/// -------------------------------------------------------------------
void TS_GetContainGridByCall(out AutomationElement grid, CheckType ct)
{
grid = Grid;
Comment("Found ContainingGrid(" + Library.GetUISpyLook(grid) + ")");
m_TestStep++;
}
/// -------------------------------------------------------------------
/// <summary></summary>
/// -------------------------------------------------------------------
void TS_GetCell(int row, int col, out AutomationElement cell, CheckType ct)
{
cell = (AutomationElement)GridPat.GetItem(row, col);
Comment("GetCell(" + row + ", " + col + ") = " + Library.GetUISpyLook(cell));
m_TestStep++;
}
/// -------------------------------------------------------------------
/// <summary></summary>
/// -------------------------------------------------------------------
void TS_GetColumn(out int col, CheckType ct)
{
col = _pattern.Current.Column;
Comment("Getting column count(" + col + ")");
m_TestStep++;
}
/// -------------------------------------------------------------------
/// <summary></summary>
/// -------------------------------------------------------------------
void TS_GetRow(out int row, CheckType ct)
{
row = _pattern.Current.Row;
Comment("Getting column count(" + row + ")");
m_TestStep++;
}
/// -------------------------------------------------------------------
/// <summary></summary>
/// -------------------------------------------------------------------
void TS_AreTheseTheSame(AutomationElement le1, AutomationElement le2, bool ShouldTheyBe, CheckType ct)
{
Comment("Comparing AutomationElements (" + Library.GetUISpyLook(le1) + ") and (" + Library.GetUISpyLook(le2) + ")");
bool results = Automation.Compare(le1, le2).Equals(ShouldTheyBe);
if (!results)
ThrowMe(ct, "Compare(" + Library.GetUISpyLook(le1) + ", " + Library.GetUISpyLook(le2) + ") = " + results + " but should be " + ShouldTheyBe);
Comment("Compare(" + Library.GetUISpyLook(le1) + ", " + Library.GetUISpyLook(le2) + ") == " + ShouldTheyBe);
m_TestStep++;
}
/// -------------------------------------------------------------------
/// <summary></summary>
/// -------------------------------------------------------------------
void TS_GetContainGridByNavigation(AutomationElement element, out AutomationElement grid, CheckType ct)
{
grid = element;
while (
!(bool)grid.GetCurrentPropertyValue(AutomationElement.IsGridPatternAvailableProperty)
&& element != AutomationElement.RootElement
)
{
grid = TreeWalker.RawViewWalker.GetParent(grid);
if (grid == null)
ThrowMe(ct, "There were not ancestors that suupported GridPattern");
}
if (element == AutomationElement.RootElement)
ThrowMe(ct, "Could not find parent element that supports GridPattern");
Comment("Found containing grid w/navigation(" + Library.GetUISpyLook(grid) + ")");
m_TestStep++;
}
#endregion Tests
#region Step/Verification
#endregion Step/Verification
/// -------------------------------------------------------------------
/// <summary></summary>
/// -------------------------------------------------------------------
GridPattern GridPat
{
get
{
return (GridPattern)((AutomationElement)_pattern.Current.ContainingGrid).GetCurrentPattern(GridPattern.Pattern);
}
}
/// -------------------------------------------------------------------
/// <summary></summary>
/// -------------------------------------------------------------------
AutomationElement Grid
{
get
{
return (AutomationElement)_pattern.Current.ContainingGrid;
}
}
}
}
| |
// Copyright 2011 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.
namespace Microsoft.Data.OData
{
#region Namespaces
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
#if ODATALIB_ASYNC
using System.Threading.Tasks;
#endif
using Microsoft.Data.Edm;
#endregion Namespaces
/// <summary>
/// Implementation of the OData input for RAW OData format (raw value and batch).
/// </summary>
internal sealed class ODataRawInputContext : ODataInputContext
{
/// <summary>Use a buffer size of 4k that is read from the stream at a time.</summary>
private const int BufferSize = 4096;
/// <summary>The <see cref="ODataPayloadKind"/> to read.</summary>
private readonly ODataPayloadKind readerPayloadKind;
/// <summary>The encoding to use to read from the batch stream.</summary>
private readonly Encoding encoding;
/// <summary>The input stream to read the data from.</summary>
private Stream stream;
/// <summary>The text reader to read non-binary values from.</summary>
private TextReader textReader;
/// <summary>Constructor.</summary>
/// <param name="format">The format for this input context.</param>
/// <param name="messageStream">The stream to read data from.</param>
/// <param name="encoding">The encoding to use to read the input.</param>
/// <param name="messageReaderSettings">Configuration settings of the OData reader.</param>
/// <param name="version">The OData protocol version to be used for reading the payload.</param>
/// <param name="readingResponse">true if reading a response message; otherwise false.</param>
/// <param name="synchronous">true if the input should be read synchronously; false if it should be read asynchronously.</param>
/// <param name="model">The model to use.</param>
/// <param name="urlResolver">The optional URL resolver to perform custom URL resolution for URLs read from the payload.</param>
/// <param name="readerPayloadKind">The <see cref="ODataPayloadKind"/> to read.</param>
private ODataRawInputContext(
ODataFormat format,
Stream messageStream,
Encoding encoding,
ODataMessageReaderSettings messageReaderSettings,
ODataVersion version,
bool readingResponse,
bool synchronous,
IEdmModel model,
IODataUrlResolver urlResolver,
ODataPayloadKind readerPayloadKind)
: base(format, messageReaderSettings, version, readingResponse, synchronous, model, urlResolver)
{
Debug.Assert(messageStream != null, "stream != null");
Debug.Assert(readerPayloadKind != ODataPayloadKind.Unsupported, "readerPayloadKind != ODataPayloadKind.Unsupported");
ExceptionUtils.CheckArgumentNotNull(format, "format");
ExceptionUtils.CheckArgumentNotNull(messageReaderSettings, "messageReaderSettings");
try
{
this.stream = messageStream;
this.encoding = encoding;
this.readerPayloadKind = readerPayloadKind;
}
catch (Exception e)
{
// Dispose the message stream if we failed to create the input context.
if (ExceptionUtils.IsCatchableExceptionType(e) && messageStream != null)
{
messageStream.Dispose();
}
throw;
}
}
/// <summary>
/// The stream of the raw input context.
/// </summary>
internal Stream Stream
{
get
{
DebugUtils.CheckNoExternalCallers();
return this.stream;
}
}
/// <summary>
/// Create RAW input context.
/// </summary>
/// <param name="format">The format for the input context.</param>
/// <param name="message">The message to use.</param>
/// <param name="encoding">The encoding to use.</param>
/// <param name="messageReaderSettings">Configuration settings of the OData reader.</param>
/// <param name="version">The OData protocol version to be used for reading the payload.</param>
/// <param name="readingResponse">true if reading a response message; otherwise false.</param>
/// <param name="model">The model to use.</param>
/// <param name="urlResolver">The optional URL resolver to perform custom URL resolution for URLs read from the payload.</param>
/// <param name="readerPayloadKind">The <see cref="ODataPayloadKind"/> to read.</param>
/// <returns>The newly created input context.</returns>
internal static ODataInputContext Create(
ODataFormat format,
ODataMessage message,
Encoding encoding,
ODataMessageReaderSettings messageReaderSettings,
ODataVersion version,
bool readingResponse,
IEdmModel model,
IODataUrlResolver urlResolver,
ODataPayloadKind readerPayloadKind)
{
DebugUtils.CheckNoExternalCallers();
Debug.Assert(format == ODataFormat.RawValue || format == ODataFormat.Batch, "This method only supports the RAW value or batch format.");
Debug.Assert(message != null, "message != null");
Debug.Assert(messageReaderSettings != null, "messageReaderSettings != null");
Debug.Assert(readerPayloadKind != ODataPayloadKind.Unsupported, "readerPayloadKind != ODataPayloadKind.Unsupported");
Stream messageStream = message.GetStream();
return new ODataRawInputContext(
format,
messageStream,
encoding,
messageReaderSettings,
version,
readingResponse,
true,
model,
urlResolver,
readerPayloadKind);
}
#if ODATALIB_ASYNC
/// <summary>
/// Asynchronously create RAW input context.
/// </summary>
/// <param name="format">The format for the input context.</param>
/// <param name="message">The message to use.</param>
/// <param name="encoding">The encoding to use.</param>
/// <param name="messageReaderSettings">Configuration settings of the OData reader.</param>
/// <param name="version">The OData protocol version to be used for reading the payload.</param>
/// <param name="readingResponse">true if reading a response message; otherwise false.</param>
/// <param name="model">The model to use.</param>
/// <param name="urlResolver">The optional URL resolver to perform custom URL resolution for URLs read from the payload.</param>
/// <param name="readerPayloadKind">The <see cref="ODataPayloadKind"/> to read.</param>
/// <returns>Task which when completed returns the newly create input context.</returns>
internal static Task<ODataInputContext> CreateAsync(
ODataFormat format,
ODataMessage message,
Encoding encoding,
ODataMessageReaderSettings messageReaderSettings,
ODataVersion version,
bool readingResponse,
IEdmModel model,
IODataUrlResolver urlResolver,
ODataPayloadKind readerPayloadKind)
{
DebugUtils.CheckNoExternalCallers();
Debug.Assert(format == ODataFormat.RawValue || format == ODataFormat.Batch, "This method only supports the RAW value or batch format.");
Debug.Assert(message != null, "message != null");
Debug.Assert(messageReaderSettings != null, "messageReaderSettings != null");
Debug.Assert(readerPayloadKind != ODataPayloadKind.Unsupported, "readerPayloadKind != ODataPayloadKind.Unsupported");
// TODO: Note that this will buffer the entire input. We need this for batch and for raw values since they
// both use TextReader - verify that this is really what we want to do.
return message.GetStreamAsync()
.FollowOnSuccessWith(
(streamTask) => (ODataInputContext)new ODataRawInputContext(
format,
streamTask.Result,
encoding,
messageReaderSettings,
version,
readingResponse,
false,
model,
urlResolver,
readerPayloadKind));
}
#endif
/// <summary>
/// Create a <see cref="ODataBatchReader"/>.
/// </summary>
/// <param name="batchBoundary">The batch boundary to use.</param>
/// <returns>The newly created <see cref="ODataCollectionReader"/>.</returns>
internal override ODataBatchReader CreateBatchReader(string batchBoundary)
{
DebugUtils.CheckNoExternalCallers();
return this.CreateBatchReaderImplementation(batchBoundary, /*synchronous*/ true);
}
#if ODATALIB_ASYNC
/// <summary>
/// Asynchronously create a <see cref="ODataBatchReader"/>.
/// </summary>
/// <param name="batchBoundary">The batch boundary to use.</param>
/// <returns>Task which when completed returns the newly created <see cref="ODataCollectionReader"/>.</returns>
internal override Task<ODataBatchReader> CreateBatchReaderAsync(string batchBoundary)
{
DebugUtils.CheckNoExternalCallers();
// Note that the reading is actually synchronous since we buffer the entire input when getting the stream from the message.
return TaskUtils.GetTaskForSynchronousOperation(() => this.CreateBatchReaderImplementation(batchBoundary, /*synchronous*/ false));
}
#endif
/// <summary>
/// Read a top-level value.
/// </summary>
/// <param name="expectedPrimitiveTypeReference">The expected primitive type for the value to be read; null if no expected type is available.</param>
/// <returns>An <see cref="object"/> representing the read value.</returns>
internal override object ReadValue(IEdmPrimitiveTypeReference expectedPrimitiveTypeReference)
{
DebugUtils.CheckNoExternalCallers();
return this.ReadValueImplementation(expectedPrimitiveTypeReference);
}
#if ODATALIB_ASYNC
/// <summary>
/// Asynchronously read a top-level value.
/// </summary>
/// <param name="expectedPrimitiveTypeReference">The expected type reference for the value to be read; null if no expected type is available.</param>
/// <returns>Task which when completed returns an <see cref="object"/> representing the read value.</returns>
internal override Task<object> ReadValueAsync(IEdmPrimitiveTypeReference expectedPrimitiveTypeReference)
{
DebugUtils.CheckNoExternalCallers();
// Note that the reading is actually synchronous since we buffer the entire input when getting the stream from the message.
return TaskUtils.GetTaskForSynchronousOperation(() => this.ReadValueImplementation(expectedPrimitiveTypeReference));
}
#endif
/// <summary>
/// Disposes the input context.
/// </summary>
protected override void DisposeImplementation()
{
try
{
if (this.textReader != null)
{
this.textReader.Dispose();
}
else if (this.stream != null)
{
this.stream.Dispose();
}
}
finally
{
this.textReader = null;
this.stream = null;
}
}
/// <summary>
/// Create a <see cref="ODataBatchReader"/>.
/// </summary>
/// <param name="batchBoundary">The batch boundary to use.</param>
/// <param name="synchronous">If the reader should be created for synchronous or asynchronous API.</param>
/// <returns>The newly created <see cref="ODataCollectionReader"/>.</returns>
private ODataBatchReader CreateBatchReaderImplementation(string batchBoundary, bool synchronous)
{
return new ODataBatchReader(this, batchBoundary, this.encoding, synchronous);
}
/// <summary>
/// Read a top-level value.
/// </summary>
/// <param name="expectedPrimitiveTypeReference">The expected primitive type for the value to be read; null if no expected type is available.</param>
/// <returns>An <see cref="object"/> representing the read value.</returns>
private object ReadValueImplementation(IEdmPrimitiveTypeReference expectedPrimitiveTypeReference)
{
// if an expected primitive type is specified it trumps the content type/reader payload kind
bool readBinary;
if (expectedPrimitiveTypeReference == null)
{
readBinary = this.readerPayloadKind == ODataPayloadKind.BinaryValue;
}
else
{
if (expectedPrimitiveTypeReference.PrimitiveKind() == EdmPrimitiveTypeKind.Binary)
{
readBinary = true;
}
else
{
readBinary = false;
}
}
if (readBinary)
{
return this.ReadBinaryValue();
}
else
{
Debug.Assert(this.textReader == null, "this.textReader == null");
this.textReader = this.encoding == null ? new StreamReader(this.stream) : new StreamReader(this.stream, this.encoding);
return this.ReadRawValue(expectedPrimitiveTypeReference);
}
}
/// <summary>
/// Read the binary value from the stream.
/// </summary>
/// <returns>A byte array containing all the data read.</returns>
private byte[] ReadBinaryValue()
{
//// This method is copied from Deserializer.ReadByteStream
byte[] data;
long numberOfBytesRead = 0;
int result;
List<byte[]> byteData = new List<byte[]>();
do
{
data = new byte[BufferSize];
result = this.stream.Read(data, 0, data.Length);
numberOfBytesRead += result;
byteData.Add(data);
}
while (result == data.Length);
// Find out the total number of bytes read and copy data from byteData to data
data = new byte[numberOfBytesRead];
for (int i = 0; i < byteData.Count - 1; i++)
{
Buffer.BlockCopy(byteData[i], 0, data, i * BufferSize, BufferSize);
}
// For the last buffer, copy the remaining number of bytes, not always the buffer size
Buffer.BlockCopy(byteData[byteData.Count - 1], 0, data, (byteData.Count - 1) * BufferSize, result);
return data;
}
/// <summary>
/// Reads the content of a text reader as string and, if <paramref name="expectedPrimitiveTypeReference"/> is specified and primitive type conversion
/// is enabled, converts the string to the expected type.
/// </summary>
/// <param name="expectedPrimitiveTypeReference">The expected type of the value being read or null if no type conversion should be performed.</param>
/// <returns>The raw value that was read from the text reader either as string or converted to the provided <paramref name="expectedPrimitiveTypeReference"/>.</returns>
private object ReadRawValue(IEdmPrimitiveTypeReference expectedPrimitiveTypeReference)
{
string stringFromStream = this.textReader.ReadToEnd();
object rawValue;
if (expectedPrimitiveTypeReference != null && !this.MessageReaderSettings.DisablePrimitiveTypeConversion)
{
rawValue = AtomValueUtils.ConvertStringToPrimitive(stringFromStream, expectedPrimitiveTypeReference);
}
else
{
rawValue = stringFromStream;
}
return rawValue;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
namespace Gem.Engine.Utilities
{
/// <summary>
/// Priority Queue data structure
/// </summary>
public class PriorityQueue<T>
where T : IComparable
{
protected List<T> storedValues;
public PriorityQueue()
{
//Initialize the array that will hold the values
storedValues = new List<T>();
//Fill the first cell in the array with an empty value
storedValues.Add(default(T));
}
/// <summary>
/// Gets the number of values stored within the Priority Queue
/// </summary>
public virtual int Count
{
get { return storedValues.Count - 1; }
}
/// <summary>
/// Returns the value at the head of the Priority Queue without removing it.
/// </summary>
public virtual T Peek()
{
if (this.Count == 0)
return default(T); //Priority Queue empty
else
return storedValues[1]; //head of the queue
}
/// <summary>
/// Adds a value to the Priority Queue
/// </summary>
public virtual void Enqueue(T value)
{
//Add the value to the internal array
storedValues.Add(value);
//Bubble up to preserve the heap property,
//starting at the inserted value
this.BubbleUp(storedValues.Count - 1);
}
/// <summary>
/// Returns the minimum value inside the Priority Queue
/// </summary>
public virtual T Dequeue()
{
if (this.Count == 0)
return default(T); //queue is empty
else
{
//The smallest value in the Priority Queue is the first item in the array
T minValue = this.storedValues[1];
//If there's more than one item, replace the first item in the array with the last one
if (this.storedValues.Count > 2)
{
T lastValue = this.storedValues[storedValues.Count - 1];
//Move last node to the head
this.storedValues.RemoveAt(storedValues.Count - 1);
this.storedValues[1] = lastValue;
//Bubble down
this.BubbleDown(1);
}
else
{
//Remove the only value stored in the queue
storedValues.RemoveAt(1);
}
return minValue;
}
}
/// <summary>
/// Restores the heap-order property between child and parent values going up towards the head
/// </summary>
protected virtual void BubbleUp(int startCell)
{
int cell = startCell;
//Bubble up as long as the parent is greater
while (this.IsParentBigger(cell))
{
//Get values of parent and child
T parentValue = this.storedValues[cell / 2];
T childValue = this.storedValues[cell];
//Swap the values
this.storedValues[cell / 2] = childValue;
this.storedValues[cell] = parentValue;
cell /= 2; //go up parents
}
}
/// <summary>
/// Restores the heap-order property between child and parent values going down towards the bottom
/// </summary>
protected virtual void BubbleDown(int startCell)
{
int cell = startCell;
//Bubble down as long as either child is smaller
while (this.IsLeftChildSmaller(cell) || this.IsRightChildSmaller(cell))
{
int child = this.CompareChild(cell);
if (child == -1) //Left Child
{
//Swap values
T parentValue = storedValues[cell];
T leftChildValue = storedValues[2 * cell];
storedValues[cell] = leftChildValue;
storedValues[2 * cell] = parentValue;
cell = 2 * cell; //move down to left child
}
else if (child == 1) //Right Child
{
//Swap values
T parentValue = storedValues[cell];
T rightChildValue = storedValues[2 * cell + 1];
storedValues[cell] = rightChildValue;
storedValues[2 * cell + 1] = parentValue;
cell = 2 * cell + 1; //move down to right child
}
}
}
/// <summary>
/// Returns if the value of a parent is greater than its child
/// </summary>
protected virtual bool IsParentBigger(int childCell)
{
if (childCell == 1)
return false; //top of heap, no parent
else
return storedValues[childCell / 2].CompareTo(storedValues[childCell]) > 0;
//return storedNodes[childCell / 2].Key > storedNodes[childCell].Key;
}
/// <summary>
/// Returns whether the left child cell is smaller than the parent cell.
/// Returns false if a left child does not exist.
/// </summary>
protected virtual bool IsLeftChildSmaller(int parentCell)
{
if (2 * parentCell >= storedValues.Count)
return false; //out of bounds
else
return storedValues[2 * parentCell].CompareTo(storedValues[parentCell]) < 0;
//return storedNodes[2 * parentCell].Key < storedNodes[parentCell].Key;
}
/// <summary>
/// Returns whether the right child cell is smaller than the parent cell.
/// Returns false if a right child does not exist.
/// </summary>
protected virtual bool IsRightChildSmaller(int parentCell)
{
if (2 * parentCell + 1 >= storedValues.Count)
return false; //out of bounds
else
return storedValues[2 * parentCell + 1].CompareTo(storedValues[parentCell]) < 0;
//return storedNodes[2 * parentCell + 1].Key < storedNodes[parentCell].Key;
}
/// <summary>
/// Compares the children cells of a parent cell. -1 indicates the left child is the smaller of the two,
/// 1 indicates the right child is the smaller of the two, 0 inidicates that neither child is smaller than the parent.
/// </summary>
protected virtual int CompareChild(int parentCell)
{
bool leftChildSmaller = this.IsLeftChildSmaller(parentCell);
bool rightChildSmaller = this.IsRightChildSmaller(parentCell);
if (leftChildSmaller || rightChildSmaller)
{
if (leftChildSmaller && rightChildSmaller)
{
//Figure out which of the two is smaller
int leftChild = 2 * parentCell;
int rightChild = 2 * parentCell + 1;
T leftValue = this.storedValues[leftChild];
T rightValue = this.storedValues[rightChild];
//Compare the values of the children
if (leftValue.CompareTo(rightValue) <= 0)
return -1; //left child is smaller
else
return 1; //right child is smaller
}
else if (leftChildSmaller)
return -1; //left child is smaller
else
return 1; //right child smaller
}
else
return 0; //both children are bigger or don't exist
}
}
}
| |
//
// Copyright (c) 2004-2017 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
using NLog.LayoutRenderers;
namespace NLog.Config
{
using System;
using System.Collections.Generic;
using NLog.Common;
using NLog.Internal;
/// <summary>
/// Factory for class-based items.
/// </summary>
/// <typeparam name="TBaseType">The base type of each item.</typeparam>
/// <typeparam name="TAttributeType">The type of the attribute used to annotate items.</typeparam>
internal class Factory<TBaseType, TAttributeType> : INamedItemFactory<TBaseType, Type>, IFactory
where TBaseType : class
where TAttributeType : NameBaseAttribute
{
private readonly Dictionary<string, GetTypeDelegate> _items = new Dictionary<string, GetTypeDelegate>(StringComparer.OrdinalIgnoreCase);
private ConfigurationItemFactory _parentFactory;
internal Factory(ConfigurationItemFactory parentFactory)
{
this._parentFactory = parentFactory;
}
private delegate Type GetTypeDelegate();
/// <summary>
/// Scans the assembly.
/// </summary>
/// <param name="types">The types to scan.</param>
/// <param name="prefix">The prefix.</param>
public void ScanTypes(Type[] types, string prefix)
{
foreach (Type t in types)
{
try
{
this.RegisterType(t, prefix);
}
catch (Exception exception)
{
InternalLogger.Error(exception, "Failed to add type '{0}'.", t.FullName);
if (exception.MustBeRethrown())
{
throw;
}
}
}
}
/// <summary>
/// Registers the type.
/// </summary>
/// <param name="type">The type to register.</param>
/// <param name="itemNamePrefix">The item name prefix.</param>
public void RegisterType(Type type, string itemNamePrefix)
{
TAttributeType[] attributes = (TAttributeType[])type.GetCustomAttributes(typeof(TAttributeType), false);
if (attributes != null)
{
foreach (TAttributeType attr in attributes)
{
this.RegisterDefinition(itemNamePrefix + attr.Name, type);
}
}
}
/// <summary>
/// Registers the item based on a type name.
/// </summary>
/// <param name="itemName">Name of the item.</param>
/// <param name="typeName">Name of the type.</param>
public void RegisterNamedType(string itemName, string typeName)
{
this._items[itemName] = () => Type.GetType(typeName, false);
}
/// <summary>
/// Clears the contents of the factory.
/// </summary>
public void Clear()
{
this._items.Clear();
}
/// <summary>
/// Registers a single type definition.
/// </summary>
/// <param name="name">The item name.</param>
/// <param name="type">The type of the item.</param>
public void RegisterDefinition(string name, Type type)
{
this._items[name] = () => type;
}
/// <summary>
/// Tries to get registered item definition.
/// </summary>
/// <param name="itemName">Name of the item.</param>
/// <param name="result">Reference to a variable which will store the item definition.</param>
/// <returns>Item definition.</returns>
public bool TryGetDefinition(string itemName, out Type result)
{
GetTypeDelegate getTypeDelegate;
if (!this._items.TryGetValue(itemName, out getTypeDelegate))
{
result = null;
return false;
}
try
{
result = getTypeDelegate();
return result != null;
}
catch (Exception ex)
{
if (ex.MustBeRethrown())
{
throw;
}
// delegate invocation failed - type is not available
result = null;
return false;
}
}
/// <summary>
/// Tries to create an item instance.
/// </summary>
/// <param name="itemName">Name of the item.</param>
/// <param name="result">The result.</param>
/// <returns>True if instance was created successfully, false otherwise.</returns>
public virtual bool TryCreateInstance(string itemName, out TBaseType result)
{
Type type;
if (!this.TryGetDefinition(itemName, out type))
{
result = null;
return false;
}
result = (TBaseType)this._parentFactory.CreateInstance(type);
return true;
}
/// <summary>
/// Creates an item instance.
/// </summary>
/// <param name="name">The name of the item.</param>
/// <returns>Created item.</returns>
public virtual TBaseType CreateInstance(string name)
{
TBaseType result;
if (this.TryCreateInstance(name, out result))
{
return result;
}
var message = typeof(TBaseType).Name + " cannot be found: '" + name + "'";
if (name != null && (name.StartsWith("aspnet", StringComparison.OrdinalIgnoreCase) ||
name.StartsWith("iis", StringComparison.OrdinalIgnoreCase)))
{
//common mistake and probably missing NLog.Web
message += ". Is NLog.Web not included?";
}
throw new ArgumentException(message);
}
}
/// <summary>
/// Factory specialized for <see cref="LayoutRenderer"/>s.
/// </summary>
class LayoutRendererFactory : Factory<LayoutRenderer, LayoutRendererAttribute>
{
public LayoutRendererFactory(ConfigurationItemFactory parentFactory) : base(parentFactory)
{
}
private Dictionary<string, FuncLayoutRenderer> _funcRenderers;
/// <summary>
/// Clear all func layouts
/// </summary>
public void ClearFuncLayouts()
{
_funcRenderers = null;
}
/// <summary>
/// Register a layout renderer with a callback function.
/// </summary>
/// <param name="name">Name of the layoutrenderer, without ${}.</param>
/// <param name="renderer">the renderer that renders the value.</param>
public void RegisterFuncLayout(string name, FuncLayoutRenderer renderer)
{
_funcRenderers = _funcRenderers ?? new Dictionary<string, FuncLayoutRenderer>(StringComparer.OrdinalIgnoreCase);
//overwrite current if there is one
_funcRenderers[name] = renderer;
}
/// <summary>
/// Tries to create an item instance.
/// </summary>
/// <param name="itemName">Name of the item.</param>
/// <param name="result">The result.</param>
/// <returns>True if instance was created successfully, false otherwise.</returns>
public override bool TryCreateInstance(string itemName, out LayoutRenderer result)
{
//first try func renderers, as they should have the possiblity to overwrite a current one.
if (_funcRenderers != null)
{
FuncLayoutRenderer funcResult;
var succesAsFunc = _funcRenderers.TryGetValue(itemName, out funcResult);
if (succesAsFunc)
{
result = funcResult;
return true;
}
}
var success = base.TryCreateInstance(itemName, out result);
return success;
}
}
}
| |
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.IO;
using FluentAssertions;
using Microsoft.DotNet.TestFramework;
using Microsoft.DotNet.Tools.Test.Utilities;
using NuGet.Frameworks;
using Xunit;
namespace Microsoft.DotNet.Cli.Utils.Tests
{
public class GivenAProjectDependenciesCommandFactory : TestBase
{
private static readonly NuGetFramework s_desktopTestFramework = FrameworkConstants.CommonFrameworks.Net451;
private RepoDirectoriesProvider _repoDirectoriesProvider;
public GivenAProjectDependenciesCommandFactory()
{
_repoDirectoriesProvider = new RepoDirectoriesProvider();
Environment.SetEnvironmentVariable(
Constants.MSBUILD_EXE_PATH,
Path.Combine(_repoDirectoriesProvider.Stage2Sdk, "MSBuild.dll"));
}
[WindowsOnlyFact]
public void It_resolves_desktop_apps_defaulting_to_Debug_Configuration()
{
var runtime = DotnetLegacyRuntimeIdentifiers.InferLegacyRestoreRuntimeIdentifier();
var configuration = "Debug";
var testInstance = TestAssets.Get(TestAssetKinds.DesktopTestProjects, "AppWithProjTool2Fx")
.CreateInstance()
.WithSourceFiles()
.WithNuGetConfig(_repoDirectoriesProvider.TestPackages);
var restoreCommand = new RestoreCommand()
.WithWorkingDirectory(testInstance.Root)
.WithRuntime(runtime)
.ExecuteWithCapturedOutput()
.Should().Pass();
var buildCommand = new BuildCommand()
.WithWorkingDirectory(testInstance.Root)
.WithConfiguration(configuration)
.WithRuntime(runtime)
.WithCapturedOutput()
.Execute()
.Should().Pass();
var factory = new ProjectDependenciesCommandFactory(
s_desktopTestFramework,
null,
null,
null,
testInstance.Root.FullName);
var command = factory.Create("dotnet-desktop-and-portable", null);
command.CommandName.Should().Contain(testInstance.Root.GetDirectory("bin", configuration).FullName);
Path.GetFileName(command.CommandName).Should().Be("dotnet-desktop-and-portable.exe");
}
[WindowsOnlyFact]
public void It_resolves_desktop_apps_when_configuration_is_Debug()
{
var runtime = DotnetLegacyRuntimeIdentifiers.InferLegacyRestoreRuntimeIdentifier();
var configuration = "Debug";
var testInstance = TestAssets.Get(TestAssetKinds.DesktopTestProjects, "AppWithProjTool2Fx")
.CreateInstance()
.WithSourceFiles()
.WithNuGetConfig(_repoDirectoriesProvider.TestPackages);
var restoreCommand = new RestoreCommand()
.WithWorkingDirectory(testInstance.Root)
.WithRuntime(runtime)
.ExecuteWithCapturedOutput()
.Should().Pass();
var buildCommand = new BuildCommand()
.WithWorkingDirectory(testInstance.Root)
.WithConfiguration(configuration)
.WithRuntime(runtime)
.Execute()
.Should().Pass();
var factory = new ProjectDependenciesCommandFactory(
s_desktopTestFramework,
configuration,
null,
null,
testInstance.Root.FullName);
var command = factory.Create("dotnet-desktop-and-portable", null);
command.CommandName.Should().Contain(testInstance.Root.GetDirectory("bin", configuration).FullName);
Path.GetFileName(command.CommandName).Should().Be("dotnet-desktop-and-portable.exe");
}
[WindowsOnlyFact]
public void It_resolves_desktop_apps_when_configuration_is_Release()
{
var runtime = DotnetLegacyRuntimeIdentifiers.InferLegacyRestoreRuntimeIdentifier();
var configuration = "Debug";
var testInstance = TestAssets.Get(TestAssetKinds.DesktopTestProjects, "AppWithProjTool2Fx")
.CreateInstance()
.WithSourceFiles()
.WithNuGetConfig(_repoDirectoriesProvider.TestPackages);
var restoreCommand = new RestoreCommand()
.WithWorkingDirectory(testInstance.Root)
.WithRuntime(runtime)
.ExecuteWithCapturedOutput()
.Should().Pass();
var buildCommand = new BuildCommand()
.WithWorkingDirectory(testInstance.Root)
.WithConfiguration(configuration)
.WithRuntime(runtime)
.WithCapturedOutput()
.Execute()
.Should().Pass();
var factory = new ProjectDependenciesCommandFactory(
s_desktopTestFramework,
configuration,
null,
null,
testInstance.Root.FullName);
var command = factory.Create("dotnet-desktop-and-portable", null);
command.CommandName.Should().Contain(testInstance.Root.GetDirectory("bin", configuration).FullName);
Path.GetFileName(command.CommandName).Should().Be("dotnet-desktop-and-portable.exe");
}
[WindowsOnlyFact]
public void It_resolves_desktop_apps_using_configuration_passed_to_create()
{
var runtime = DotnetLegacyRuntimeIdentifiers.InferLegacyRestoreRuntimeIdentifier();
var configuration = "Debug";
var testInstance = TestAssets.Get(TestAssetKinds.DesktopTestProjects, "AppWithProjTool2Fx")
.CreateInstance()
.WithSourceFiles()
.WithNuGetConfig(_repoDirectoriesProvider.TestPackages);
var restoreCommand = new RestoreCommand()
.WithWorkingDirectory(testInstance.Root)
.WithRuntime(runtime)
.ExecuteWithCapturedOutput()
.Should().Pass();
var buildCommand = new BuildCommand()
.WithWorkingDirectory(testInstance.Root)
.WithConfiguration(configuration)
.WithRuntime(runtime)
.WithCapturedOutput()
.Execute()
.Should().Pass();
var factory = new ProjectDependenciesCommandFactory(
s_desktopTestFramework,
"Debug",
null,
null,
testInstance.Root.FullName);
var command = factory.Create("dotnet-desktop-and-portable", null, configuration: configuration);
command.CommandName.Should().Contain(testInstance.Root.GetDirectory("bin", configuration).FullName);
Path.GetFileName(command.CommandName).Should().Be("dotnet-desktop-and-portable.exe");
}
[Fact]
public void It_resolves_tools_whose_package_name_is_different_than_dll_name()
{
Environment.SetEnvironmentVariable(
Constants.MSBUILD_EXE_PATH,
Path.Combine(new RepoDirectoriesProvider().Stage2Sdk, "MSBuild.dll"));
var configuration = "Debug";
var testInstance = TestAssets.Get("AppWithDirectDepWithOutputName")
.CreateInstance()
.WithSourceFiles()
.WithRestoreFiles();
var buildCommand = new BuildCommand()
.WithProjectDirectory(testInstance.Root)
.WithConfiguration(configuration)
.WithCapturedOutput()
.Execute()
.Should().Pass();
var factory = new ProjectDependenciesCommandFactory(
FrameworkConstants.CommonFrameworks.NetCoreApp10,
configuration,
null,
null,
testInstance.Root.FullName);
var command = factory.Create("dotnet-tool-with-output-name", null);
command.CommandArgs.Should().Contain(
Path.Combine("toolwithoutputname", "1.0.0", "lib", "netcoreapp1.0", "dotnet-tool-with-output-name.dll"));
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void ShiftRightLogical128BitLaneByte1()
{
var test = new SimpleUnaryOpTest__ShiftRightLogical128BitLaneByte1();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local works
test.RunLclFldScenario();
// Validates passing an instance member works
test.RunFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleUnaryOpTest__ShiftRightLogical128BitLaneByte1
{
private const int VectorSize = 32;
private const int Op1ElementCount = VectorSize / sizeof(Byte);
private const int RetElementCount = VectorSize / sizeof(Byte);
private static Byte[] _data = new Byte[Op1ElementCount];
private static Vector256<Byte> _clsVar;
private Vector256<Byte> _fld;
private SimpleUnaryOpTest__DataTable<Byte, Byte> _dataTable;
static SimpleUnaryOpTest__ShiftRightLogical128BitLaneByte1()
{
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (byte)8; }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Byte>, byte>(ref _clsVar), ref Unsafe.As<Byte, byte>(ref _data[0]), VectorSize);
}
public SimpleUnaryOpTest__ShiftRightLogical128BitLaneByte1()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (byte)8; }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Byte>, byte>(ref _fld), ref Unsafe.As<Byte, byte>(ref _data[0]), VectorSize);
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (byte)8; }
_dataTable = new SimpleUnaryOpTest__DataTable<Byte, Byte>(_data, new Byte[RetElementCount], VectorSize);
}
public bool IsSupported => Avx2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Avx2.ShiftRightLogical128BitLane(
Unsafe.Read<Vector256<Byte>>(_dataTable.inArrayPtr),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
var result = Avx2.ShiftRightLogical128BitLane(
Avx.LoadVector256((Byte*)(_dataTable.inArrayPtr)),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
var result = Avx2.ShiftRightLogical128BitLane(
Avx.LoadAlignedVector256((Byte*)(_dataTable.inArrayPtr)),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
var result = typeof(Avx2).GetMethod(nameof(Avx2.ShiftRightLogical128BitLane), new Type[] { typeof(Vector256<Byte>), typeof(byte) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<Byte>>(_dataTable.inArrayPtr),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Byte>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
var result = typeof(Avx2).GetMethod(nameof(Avx2.ShiftRightLogical128BitLane), new Type[] { typeof(Vector256<Byte>), typeof(byte) })
.Invoke(null, new object[] {
Avx.LoadVector256((Byte*)(_dataTable.inArrayPtr)),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Byte>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
var result = typeof(Avx2).GetMethod(nameof(Avx2.ShiftRightLogical128BitLane), new Type[] { typeof(Vector256<Byte>), typeof(byte) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((Byte*)(_dataTable.inArrayPtr)),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Byte>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
var result = Avx2.ShiftRightLogical128BitLane(
_clsVar,
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
var firstOp = Unsafe.Read<Vector256<Byte>>(_dataTable.inArrayPtr);
var result = Avx2.ShiftRightLogical128BitLane(firstOp, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
var firstOp = Avx.LoadVector256((Byte*)(_dataTable.inArrayPtr));
var result = Avx2.ShiftRightLogical128BitLane(firstOp, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
var firstOp = Avx.LoadAlignedVector256((Byte*)(_dataTable.inArrayPtr));
var result = Avx2.ShiftRightLogical128BitLane(firstOp, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclFldScenario()
{
var test = new SimpleUnaryOpTest__ShiftRightLogical128BitLaneByte1();
var result = Avx2.ShiftRightLogical128BitLane(test._fld, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
public void RunFldScenario()
{
var result = Avx2.ShiftRightLogical128BitLane(_fld, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld, _dataTable.outArrayPtr);
}
public void RunUnsupportedScenario()
{
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector256<Byte> firstOp, void* result, [CallerMemberName] string method = "")
{
Byte[] inArray = new Byte[Op1ElementCount];
Byte[] outArray = new Byte[RetElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray[0]), firstOp);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "")
{
Byte[] inArray = new Byte[Op1ElementCount];
Byte[] outArray = new Byte[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(Byte[] firstOp, Byte[] result, [CallerMemberName] string method = "")
{
if (result[0] != 8)
{
Succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if ((i == 31 || i == 15 ? result[i] != 0 : result[i] != 8))
{
Succeeded = false;
break;
}
}
}
if (!Succeeded)
{
Console.WriteLine($"{nameof(Avx2)}.{nameof(Avx2.ShiftRightLogical128BitLane)}<Byte>(Vector256<Byte><9>): {method} failed:");
Console.WriteLine($" firstOp: ({string.Join(", ", firstOp)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
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 Confingo.Services.Areas.HelpPage.ModelDescriptions;
using Confingo.Services.Areas.HelpPage.Models;
namespace Confingo.Services.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);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
namespace Elasticsearch.Net.Integration.Yaml.Search1
{
public partial class Search1YamlTests
{
[NCrunch.Framework.ExclusivelyUses("ElasticsearchYamlTests")]
public class SourceFiltering1Tests : YamlTestsBase
{
[Test]
public void SourceFiltering1Test()
{
//do index
_body = new {
include= new {
field1= "v1",
field2= "v2"
},
count= "1"
};
this.Do(()=> _client.Index("test_1", "test", "1", _body));
//do indices.refresh
this.Do(()=> _client.IndicesRefreshForAll());
//do search
_body = @"{ _source: true, query: { match_all: {} } }";
this.Do(()=> _client.Search(_body));
//length _response.hits.hits: 1;
this.IsLength(_response.hits.hits, 1);
//match _response.hits.hits[0]._source.count:
this.IsMatch(_response.hits.hits[0]._source.count, 1);
//do search
_body = @"{ _source: false, query: { match_all: {} } }";
this.Do(()=> _client.Search(_body));
//length _response.hits.hits: 1;
this.IsLength(_response.hits.hits, 1);
//is_false _response.hits.hits[0]._source;
this.IsFalse(_response.hits.hits[0]._source);
//do search
_body = new {
query= new {
match_all= new {}
}
};
this.Do(()=> _client.Search(_body));
//length _response.hits.hits: 1;
this.IsLength(_response.hits.hits, 1);
//match _response.hits.hits[0]._source.count:
this.IsMatch(_response.hits.hits[0]._source.count, 1);
//do search
_body = new {
_source= "include.field1",
query= new {
match_all= new {}
}
};
this.Do(()=> _client.Search(_body));
//match _response.hits.hits[0]._source.include.field1:
this.IsMatch(_response.hits.hits[0]._source.include.field1, @"v1");
//is_false _response.hits.hits[0]._source.include.field2;
this.IsFalse(_response.hits.hits[0]._source.include.field2);
//do search
_body = new {
_source= "include.field2",
query= new {
match_all= new {}
}
};
this.Do(()=> _client.Search(_body, nv=>nv
.AddQueryString("_source_include", @"include.field1")
));
//match _response.hits.hits[0]._source.include.field1:
this.IsMatch(_response.hits.hits[0]._source.include.field1, @"v1");
//is_false _response.hits.hits[0]._source.include.field2;
this.IsFalse(_response.hits.hits[0]._source.include.field2);
//do search
_body = new {
query= new {
match_all= new {}
}
};
this.Do(()=> _client.Search(_body, nv=>nv
.AddQueryString("_source_include", @"include.field1")
));
//match _response.hits.hits[0]._source.include.field1:
this.IsMatch(_response.hits.hits[0]._source.include.field1, @"v1");
//is_false _response.hits.hits[0]._source.include.field2;
this.IsFalse(_response.hits.hits[0]._source.include.field2);
//do search
_body = new {
query= new {
match_all= new {}
}
};
this.Do(()=> _client.Search(_body, nv=>nv
.AddQueryString("_source_exclude", @"count")
));
//match _response.hits.hits[0]._source.include:
this.IsMatch(_response.hits.hits[0]._source.include, new {
field1= "v1",
field2= "v2"
});
//is_false _response.hits.hits[0]._source.count;
this.IsFalse(_response.hits.hits[0]._source.count);
//do search
_body = new {
_source= new [] {
"include.field1",
"include.field2"
},
query= new {
match_all= new {}
}
};
this.Do(()=> _client.Search(_body));
//match _response.hits.hits[0]._source.include.field1:
this.IsMatch(_response.hits.hits[0]._source.include.field1, @"v1");
//match _response.hits.hits[0]._source.include.field2:
this.IsMatch(_response.hits.hits[0]._source.include.field2, @"v2");
//is_false _response.hits.hits[0]._source.count;
this.IsFalse(_response.hits.hits[0]._source.count);
//do search
_body = new {
_source= new {
include= new [] {
"include.field1",
"include.field2"
}
},
query= new {
match_all= new {}
}
};
this.Do(()=> _client.Search(_body));
//match _response.hits.hits[0]._source.include.field1:
this.IsMatch(_response.hits.hits[0]._source.include.field1, @"v1");
//match _response.hits.hits[0]._source.include.field2:
this.IsMatch(_response.hits.hits[0]._source.include.field2, @"v2");
//is_false _response.hits.hits[0]._source.count;
this.IsFalse(_response.hits.hits[0]._source.count);
//do search
_body = new {
_source= new {
includes= "include",
excludes= "*.field2"
},
query= new {
match_all= new {}
}
};
this.Do(()=> _client.Search(_body));
//match _response.hits.hits[0]._source.include.field1:
this.IsMatch(_response.hits.hits[0]._source.include.field1, @"v1");
//is_false _response.hits.hits[0]._source.include.field2;
this.IsFalse(_response.hits.hits[0]._source.include.field2);
//do search
_body = new {
fields= new [] {
"include.field2"
},
query= new {
match_all= new {}
}
};
this.Do(()=> _client.Search(_body));
//match _response.hits.hits[0].fields:
this.IsMatch(_response.hits.hits[0].fields, new Dictionary<string, object> {
{ @"include.field2", new [] {"v2"} }
});
//is_false _response.hits.hits[0]._source;
this.IsFalse(_response.hits.hits[0]._source);
//do search
_body = new {
fields= new [] {
"include.field2",
"_source"
},
query= new {
match_all= new {}
}
};
this.Do(()=> _client.Search(_body));
//match _response.hits.hits[0].fields:
this.IsMatch(_response.hits.hits[0].fields, new Dictionary<string, object> {
{ @"include.field2", new [] {"v2"} }
});
//is_true _response.hits.hits[0]._source;
this.IsTrue(_response.hits.hits[0]._source);
}
}
}
}
| |
// 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.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Buffers;
using System.Text;
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);
// Cache the invariant CompareInfo
internal static readonly CompareInfo Invariant = CultureInfo.InvariantCulture.CompareInfo;
//
// 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)
// _invariantMode is defined for the perf reason as accessing the instance field is faster than access the static property GlobalizationMode.Invariant
[NonSerialized]
private readonly bool _invariantMode = GlobalizationMode.Invariant;
private int culture; // Do not rename (binary serialization). The fields sole purpose is to support Desktop serialization.
internal CompareInfo(CultureInfo culture)
{
m_name = culture._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:
** ArgumentNullException 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);
}
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:
** ArgumentNullException 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));
}
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));
}
return CultureInfo.GetCultureInfo(name).CompareInfo;
}
public static unsafe bool IsSortable(char ch)
{
if (GlobalizationMode.Invariant)
{
return true;
}
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 (text.Length == 0)
{
// A zero length string is not invalid, but it is also not sortable.
return (false);
}
if (GlobalizationMode.Invariant)
{
return true;
}
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._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)
Debug.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 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
}
if (_invariantMode)
{
if ((options & CompareOptions.IgnoreCase) != 0)
return CompareOrdinalIgnoreCase(string1, string2);
return String.CompareOrdinal(string1, string2);
}
return CompareString(string1.AsSpan(), string2.AsSpan(), options);
}
// TODO https://github.com/dotnet/coreclr/issues/13827:
// This method shouldn't be necessary, as we should be able to just use the overload
// that takes two spans. But due to this issue, that's adding significant overhead.
internal int Compare(ReadOnlySpan<char> string1, string string2, CompareOptions options)
{
if (options == CompareOptions.OrdinalIgnoreCase)
{
return CompareOrdinalIgnoreCase(string1, string2.AsSpan());
}
// 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.AsSpan());
}
if ((options & ValidCompareMaskOffFlags) != 0)
{
throw new ArgumentException(SR.Argument_InvalidFlag, nameof(options));
}
// null sorts less than any other string.
if (string2 == null)
{
return 1;
}
if (_invariantMode)
{
return (options & CompareOptions.IgnoreCase) != 0 ?
CompareOrdinalIgnoreCase(string1, string2.AsSpan()) :
string.CompareOrdinal(string1, string2.AsSpan());
}
return CompareString(string1, string2, options);
}
internal int CompareOptionNone(ReadOnlySpan<char> string1, ReadOnlySpan<char> string2)
{
// Check for empty span or span from a null string
if (string1.Length == 0 || string2.Length == 0)
return string1.Length - string2.Length;
return _invariantMode ?
string.CompareOrdinal(string1, string2) :
CompareString(string1, string2, CompareOptions.None);
}
internal int CompareOptionIgnoreCase(ReadOnlySpan<char> string1, ReadOnlySpan<char> string2)
{
// Check for empty span or span from a null string
if (string1.Length == 0 || string2.Length == 0)
return string1.Length - string2.Length;
return _invariantMode ?
CompareOrdinalIgnoreCase(string1, string2) :
CompareString(string1, string2, CompareOptions.IgnoreCase);
}
////////////////////////////////////////////////////////////////////////
//
// 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 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 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 virtual int Compare(string string1, int offset1, string string2, int offset2)
{
return Compare(string1, offset1, string2, offset2, 0);
}
public 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);
}
ReadOnlySpan<char> span1 = string1.AsSpan(offset1, length1);
ReadOnlySpan<char> span2 = string2.AsSpan(offset2, length2);
if (options == CompareOptions.Ordinal)
{
return string.CompareOrdinal(span1, span2);
}
if (_invariantMode)
{
if ((options & CompareOptions.IgnoreCase) != 0)
return CompareOrdinalIgnoreCase(span1, span2);
return string.CompareOrdinal(span1, span2);
}
return CompareString(span1, span2, options);
}
//
// CompareOrdinalIgnoreCase compare two string ordinally 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 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);
return CompareOrdinalIgnoreCase(strA.AsSpan(indexA, lengthA), strB.AsSpan(indexB, lengthB));
}
internal static unsafe int CompareOrdinalIgnoreCase(ReadOnlySpan<char> strA, ReadOnlySpan<char> strB)
{
int length = Math.Min(strA.Length, strB.Length);
int range = length;
fixed (char* ap = &MemoryMarshal.GetReference(strA))
fixed (char* bp = &MemoryMarshal.GetReference(strB))
{
char* a = ap;
char* b = bp;
// in InvariantMode we support all range and not only the ascii characters.
char maxChar = (char) (GlobalizationMode.Invariant ? 0xFFFF : 0x7F);
while (length != 0 && (*a <= maxChar) && (*b <= maxChar))
{
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') <= 'z' - 'a') charA -= 0x20;
if ((uint)(charB - 'a') <= '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 strA.Length - strB.Length;
Debug.Assert(!GlobalizationMode.Invariant);
range -= length;
return CompareStringOrdinalIgnoreCase(a, strA.Length - range, b, strB.Length - range);
}
}
////////////////////////////////////////////////////////////////////////
//
// IsPrefix
//
// Determines whether prefix is a prefix of string. If prefix equals
// String.Empty, true is returned.
//
////////////////////////////////////////////////////////////////////////
public 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);
}
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));
}
if (_invariantMode)
{
return source.StartsWith(prefix, (options & CompareOptions.IgnoreCase) != 0 ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal);
}
return StartsWith(source, prefix, options);
}
internal bool IsPrefix(ReadOnlySpan<char> source, ReadOnlySpan<char> prefix, CompareOptions options)
{
Debug.Assert(prefix.Length != 0);
Debug.Assert(source.Length != 0);
Debug.Assert((options & ValidIndexMaskOffFlags) == 0);
Debug.Assert(!_invariantMode);
Debug.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0);
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 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);
}
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));
}
if (_invariantMode)
{
return source.EndsWith(suffix, (options & CompareOptions.IgnoreCase) != 0 ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal);
}
return EndsWith(source, suffix, options);
}
internal bool IsSuffix(ReadOnlySpan<char> source, ReadOnlySpan<char> suffix, CompareOptions options)
{
Debug.Assert(suffix.Length != 0);
Debug.Assert(source.Length != 0);
Debug.Assert((options & ValidIndexMaskOffFlags) == 0);
Debug.Assert(!_invariantMode);
Debug.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0);
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 virtual int IndexOf(string source, char value)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
return IndexOf(source, value, 0, source.Length, CompareOptions.None);
}
public virtual int IndexOf(string source, string value)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
return IndexOf(source, value, 0, source.Length, CompareOptions.None);
}
public virtual int IndexOf(string source, char value, CompareOptions options)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
return IndexOf(source, value, 0, source.Length, options);
}
public virtual int IndexOf(string source, string value, CompareOptions options)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
return IndexOf(source, value, 0, source.Length, options);
}
public virtual int IndexOf(string source, char value, int startIndex)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
return IndexOf(source, value, startIndex, source.Length - startIndex, CompareOptions.None);
}
public virtual int IndexOf(string source, string value, int startIndex)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
return IndexOf(source, value, startIndex, source.Length - startIndex, CompareOptions.None);
}
public virtual int IndexOf(string source, char value, int startIndex, CompareOptions options)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
return IndexOf(source, value, startIndex, source.Length - startIndex, options);
}
public virtual int IndexOf(string source, string value, int startIndex, CompareOptions options)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
return IndexOf(source, value, startIndex, source.Length - startIndex, options);
}
public virtual int IndexOf(string source, char value, int startIndex, int count)
{
return IndexOf(source, value, startIndex, count, CompareOptions.None);
}
public 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);
if (source.Length == 0)
{
return -1;
}
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));
if (_invariantMode)
return IndexOfOrdinal(source, new string(value, 1), startIndex, count, ignoreCase: (options & (CompareOptions.IgnoreCase | CompareOptions.OrdinalIgnoreCase)) != 0);
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);
}
// 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));
if (_invariantMode)
return IndexOfOrdinal(source, value, startIndex, count, ignoreCase: (options & (CompareOptions.IgnoreCase | CompareOptions.OrdinalIgnoreCase)) != 0);
return IndexOfCore(source, value, startIndex, count, options, null);
}
internal int IndexOfOrdinal(ReadOnlySpan<char> source, ReadOnlySpan<char> value, bool ignoreCase)
{
Debug.Assert(!_invariantMode);
Debug.Assert(!source.IsEmpty);
Debug.Assert(!value.IsEmpty);
return IndexOfOrdinalCore(source, value, ignoreCase);
}
internal unsafe int IndexOf(ReadOnlySpan<char> source, ReadOnlySpan<char> value, CompareOptions options)
{
Debug.Assert(!_invariantMode);
Debug.Assert(!source.IsEmpty);
Debug.Assert(!value.IsEmpty);
return IndexOfCore(source, value, 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;
}
if (_invariantMode)
{
int res = IndexOfOrdinal(source, value, startIndex, count, ignoreCase: (options & (CompareOptions.IgnoreCase | CompareOptions.OrdinalIgnoreCase)) != 0);
if (res >= 0)
{
*matchLengthPtr = value.Length;
}
return res;
}
return IndexOfCore(source, value, startIndex, count, options, matchLengthPtr);
}
internal int IndexOfOrdinal(string source, string value, int startIndex, int count, bool ignoreCase)
{
if (_invariantMode)
{
return InvariantIndexOf(source, value, startIndex, count, ignoreCase);
}
return IndexOfOrdinalCore(source, value, startIndex, count, ignoreCase);
}
////////////////////////////////////////////////////////////////////////
//
// 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 virtual int LastIndexOf(String source, char value)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
// 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));
// 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));
// 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 virtual int LastIndexOf(string source, string value, CompareOptions options)
{
if (source == null)
throw new ArgumentNullException(nameof(source));
// 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 virtual int LastIndexOf(string source, char value, int startIndex)
{
return LastIndexOf(source, value, startIndex, startIndex + 1, CompareOptions.None);
}
public virtual int LastIndexOf(string source, string value, int startIndex)
{
return LastIndexOf(source, value, startIndex, startIndex + 1, CompareOptions.None);
}
public virtual int LastIndexOf(string source, char value, int startIndex, CompareOptions options)
{
return LastIndexOf(source, value, startIndex, startIndex + 1, options);
}
public virtual int LastIndexOf(string source, string value, int startIndex, CompareOptions options)
{
return LastIndexOf(source, value, startIndex, startIndex + 1, options);
}
public virtual int LastIndexOf(string source, char value, int startIndex, int count)
{
return LastIndexOf(source, value, startIndex, count, CompareOptions.None);
}
public virtual int LastIndexOf(string source, string value, int startIndex, int count)
{
return LastIndexOf(source, value, startIndex, count, CompareOptions.None);
}
public virtual int LastIndexOf(string source, char value, int startIndex, int count, CompareOptions options)
{
// Verify Arguments
if (source == null)
throw new ArgumentNullException(nameof(source));
// 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);
}
if (_invariantMode)
return InvariantLastIndexOf(source, new string(value, 1), startIndex, count, (options & (CompareOptions.IgnoreCase | CompareOptions.OrdinalIgnoreCase)) != 0);
return LastIndexOfCore(source, value.ToString(), startIndex, count, options);
}
public 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));
// 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);
}
if (_invariantMode)
return InvariantLastIndexOf(source, value, startIndex, count, (options & (CompareOptions.IgnoreCase | CompareOptions.OrdinalIgnoreCase)) != 0);
return LastIndexOfCore(source, value, startIndex, count, options);
}
internal int LastIndexOfOrdinal(string source, string value, int startIndex, int count, bool ignoreCase)
{
if (_invariantMode)
{
return InvariantLastIndexOf(source, value, startIndex, count, ignoreCase);
}
return LastIndexOfOrdinalCore(source, value, startIndex, count, ignoreCase);
}
////////////////////////////////////////////////////////////////////////
//
// GetSortKey
//
// Gets the SortKey for the given string with the given options.
//
////////////////////////////////////////////////////////////////////////
public virtual SortKey GetSortKey(string source, CompareOptions options)
{
if (_invariantMode)
return InvariantCreateSortKey(source, options);
return CreateSortKey(source, options);
}
public virtual SortKey GetSortKey(string source)
{
if (_invariantMode)
return InvariantCreateSortKey(source, CompareOptions.None);
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());
}
internal static unsafe int GetIgnoreCaseHash(string source)
{
Debug.Assert(source != null, "source must not be null");
// Do not allocate on the stack if string is empty
if (source.Length == 0)
{
return source.GetHashCode();
}
char[] borrowedArr = null;
Span<char> span = source.Length <= 255 ?
stackalloc char[255] :
(borrowedArr = ArrayPool<char>.Shared.Rent(source.Length));
int charsWritten = source.AsSpan().ToUpperInvariant(span);
// Slice the array to the size returned by ToUpperInvariant.
int hash = Marvin.ComputeHash32(MemoryMarshal.AsBytes(span.Slice(0, charsWritten)), Marvin.DefaultSeed);
// Return the borrowed array if necessary.
if (borrowedArr != null)
{
ArrayPool<char>.Shared.Return(borrowedArr);
}
return hash;
}
////////////////////////////////////////////////////////////////////////
//
// 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));
}
if (_invariantMode)
{
return ((options & CompareOptions.IgnoreCase) != 0) ? GetIgnoreCaseHash(source) : source.GetHashCode();
}
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 GetIgnoreCaseHash(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)
{
if (_invariantMode)
{
m_SortVersion = new SortVersion(0, CultureInfo.LOCALE_INVARIANT, new Guid(0, 0, 0, 0, 0, 0, 0,
(byte) (CultureInfo.LOCALE_INVARIANT >> 24),
(byte) ((CultureInfo.LOCALE_INVARIANT & 0x00FF0000) >> 16),
(byte) ((CultureInfo.LOCALE_INVARIANT & 0x0000FF00) >> 8),
(byte) (CultureInfo.LOCALE_INVARIANT & 0xFF)));
}
else
{
m_SortVersion = GetSortVersion();
}
}
return m_SortVersion;
}
}
public int LCID
{
get
{
return CultureInfo.GetCultureInfo(Name).LCID;
}
}
}
}
| |
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
namespace System.ServiceModel.Description
{
using System;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Configuration;
using System.Diagnostics;
using System.Net.Security;
using System.Reflection;
using System.Runtime;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Configuration;
public class ServiceContractGenerator
{
CodeCompileUnit compileUnit;
ConfigWriter configWriter;
Configuration configuration;
NamespaceHelper namespaceManager;
// options
OptionsHelper options = new OptionsHelper(ServiceContractGenerationOptions.ChannelInterface |
ServiceContractGenerationOptions.ClientClass);
Dictionary<ContractDescription, Type> referencedTypes;
Dictionary<ContractDescription, ServiceContractGenerationContext> generatedTypes;
Dictionary<OperationDescription, OperationContractGenerationContext> generatedOperations;
Dictionary<MessageDescription, CodeTypeReference> generatedTypedMessages;
Collection<MetadataConversionError> errors = new Collection<MetadataConversionError>();
public ServiceContractGenerator()
: this(null, null)
{
}
public ServiceContractGenerator(Configuration targetConfig)
: this(null, targetConfig)
{
}
public ServiceContractGenerator(CodeCompileUnit targetCompileUnit)
: this(targetCompileUnit, null)
{
}
public ServiceContractGenerator(CodeCompileUnit targetCompileUnit, Configuration targetConfig)
{
this.compileUnit = targetCompileUnit ?? new CodeCompileUnit();
this.namespaceManager = new NamespaceHelper(this.compileUnit.Namespaces);
AddReferencedAssembly(typeof(ServiceContractGenerator).Assembly);
this.configuration = targetConfig;
if (targetConfig != null)
this.configWriter = new ConfigWriter(targetConfig);
this.generatedTypes = new Dictionary<ContractDescription, ServiceContractGenerationContext>();
this.generatedOperations = new Dictionary<OperationDescription, OperationContractGenerationContext>();
this.referencedTypes = new Dictionary<ContractDescription, Type>();
}
internal CodeTypeReference GetCodeTypeReference(Type type)
{
AddReferencedAssembly(type.Assembly);
return new CodeTypeReference(type);
}
internal void AddReferencedAssembly(Assembly assembly)
{
string assemblyName = System.IO.Path.GetFileName(assembly.Location);
bool alreadyExisting = false;
foreach (string existingName in this.compileUnit.ReferencedAssemblies)
{
if (String.Compare(existingName, assemblyName, StringComparison.OrdinalIgnoreCase) == 0)
{
alreadyExisting = true;
break;
}
}
if (!alreadyExisting)
this.compileUnit.ReferencedAssemblies.Add(assemblyName);
}
// options
public ServiceContractGenerationOptions Options
{
get { return this.options.Options; }
set { this.options = new OptionsHelper(value); }
}
internal OptionsHelper OptionsInternal
{
get { return this.options; }
}
public Dictionary<ContractDescription, Type> ReferencedTypes
{
get { return this.referencedTypes; }
}
public CodeCompileUnit TargetCompileUnit
{
get { return this.compileUnit; }
}
public Configuration Configuration
{
get { return this.configuration; }
}
public Dictionary<string, string> NamespaceMappings
{
get { return this.NamespaceManager.NamespaceMappings; }
}
public Collection<MetadataConversionError> Errors
{
get { return errors; }
}
internal NamespaceHelper NamespaceManager
{
get { return this.namespaceManager; }
}
public void GenerateBinding(Binding binding, out string bindingSectionName, out string configurationName)
{
configWriter.WriteBinding(binding, out bindingSectionName, out configurationName);
}
public CodeTypeReference GenerateServiceEndpoint(ServiceEndpoint endpoint, out ChannelEndpointElement channelElement)
{
if (endpoint == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("endpoint");
if (configuration == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.SFxServiceContractGeneratorConfigRequired)));
CodeTypeReference retVal;
string typeName;
Type existingType;
if (referencedTypes.TryGetValue(endpoint.Contract, out existingType))
{
retVal = GetCodeTypeReference(existingType);
typeName = existingType.FullName;
}
else
{
retVal = GenerateServiceContractType(endpoint.Contract);
typeName = retVal.BaseType;
}
channelElement = configWriter.WriteChannelDescription(endpoint, typeName);
return retVal;
}
public CodeTypeReference GenerateServiceContractType(ContractDescription contractDescription)
{
CodeTypeReference retVal = GenerateServiceContractTypeInternal(contractDescription);
System.CodeDom.Compiler.CodeGenerator.ValidateIdentifiers(TargetCompileUnit);
return retVal;
}
CodeTypeReference GenerateServiceContractTypeInternal(ContractDescription contractDescription)
{
if (contractDescription == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("contractDescription");
Type existingType;
if (referencedTypes.TryGetValue(contractDescription, out existingType))
{
return GetCodeTypeReference(existingType);
}
ServiceContractGenerationContext context;
CodeNamespace ns = this.NamespaceManager.EnsureNamespace(contractDescription.Namespace);
if (!generatedTypes.TryGetValue(contractDescription, out context))
{
context = new ContextInitializer(this, new CodeTypeFactory(this, options.IsSet(ServiceContractGenerationOptions.InternalTypes))).CreateContext(contractDescription);
ExtensionsHelper.CallContractExtensions(GetBeforeExtensionsBuiltInContractGenerators(), context);
ExtensionsHelper.CallOperationExtensions(GetBeforeExtensionsBuiltInOperationGenerators(), context);
ExtensionsHelper.CallBehaviorExtensions(context);
ExtensionsHelper.CallContractExtensions(GetAfterExtensionsBuiltInContractGenerators(), context);
ExtensionsHelper.CallOperationExtensions(GetAfterExtensionsBuiltInOperationGenerators(), context);
generatedTypes.Add(contractDescription, context);
}
return context.ContractTypeReference;
}
IEnumerable<IServiceContractGenerationExtension> GetBeforeExtensionsBuiltInContractGenerators()
{
return EmptyArray<IServiceContractGenerationExtension>.Instance;
}
IEnumerable<IOperationContractGenerationExtension> GetBeforeExtensionsBuiltInOperationGenerators()
{
yield return new FaultContractAttributeGenerator();
yield return new TransactionFlowAttributeGenerator();
}
IEnumerable<IServiceContractGenerationExtension> GetAfterExtensionsBuiltInContractGenerators()
{
if (this.options.IsSet(ServiceContractGenerationOptions.ChannelInterface))
{
yield return new ChannelInterfaceGenerator();
}
if (this.options.IsSet(ServiceContractGenerationOptions.ClientClass))
{
// unless the caller explicitly asks for TM we try to generate a helpful overload if we end up with TM
bool tryAddHelperMethod = !this.options.IsSet(ServiceContractGenerationOptions.TypedMessages);
bool generateEventAsyncMethods = this.options.IsSet(ServiceContractGenerationOptions.EventBasedAsynchronousMethods);
yield return new ClientClassGenerator(tryAddHelperMethod, generateEventAsyncMethods);
}
}
IEnumerable<IOperationContractGenerationExtension> GetAfterExtensionsBuiltInOperationGenerators()
{
return EmptyArray<IOperationContractGenerationExtension>.Instance;
}
internal static CodeExpression GetEnumReference<EnumType>(EnumType value)
{
return new CodeFieldReferenceExpression(new CodeTypeReferenceExpression(typeof(EnumType)), Enum.Format(typeof(EnumType), value, "G"));
}
internal Dictionary<MessageDescription, CodeTypeReference> GeneratedTypedMessages
{
get
{
if (generatedTypedMessages == null)
generatedTypedMessages = new Dictionary<MessageDescription, CodeTypeReference>(MessageDescriptionComparer.Singleton);
return generatedTypedMessages;
}
}
internal class ContextInitializer
{
readonly ServiceContractGenerator parent;
readonly CodeTypeFactory typeFactory;
readonly bool asyncMethods;
readonly bool taskMethod;
ServiceContractGenerationContext context;
UniqueCodeIdentifierScope contractMemberScope;
UniqueCodeIdentifierScope callbackMemberScope;
internal ContextInitializer(ServiceContractGenerator parent, CodeTypeFactory typeFactory)
{
this.parent = parent;
this.typeFactory = typeFactory;
this.asyncMethods = parent.OptionsInternal.IsSet(ServiceContractGenerationOptions.AsynchronousMethods);
this.taskMethod = parent.OptionsInternal.IsSet(ServiceContractGenerationOptions.TaskBasedAsynchronousMethod);
}
public ServiceContractGenerationContext CreateContext(ContractDescription contractDescription)
{
VisitContract(contractDescription);
Fx.Assert(this.context != null, "context was not initialized");
return this.context;
}
// this could usefully be factored into a base class for use by WSDL export and others
void VisitContract(ContractDescription contract)
{
this.Visit(contract);
foreach (OperationDescription operation in contract.Operations)
{
this.Visit(operation);
// not used in this case
//foreach (MessageDescription message in operation.Messages)
//{
// this.Visit(message);
//}
}
}
void Visit(ContractDescription contractDescription)
{
bool isDuplex = IsDuplex(contractDescription);
this.contractMemberScope = new UniqueCodeIdentifierScope();
this.callbackMemberScope = isDuplex ? new UniqueCodeIdentifierScope() : null;
UniqueCodeNamespaceScope codeNamespaceScope = new UniqueCodeNamespaceScope(parent.NamespaceManager.EnsureNamespace(contractDescription.Namespace));
CodeTypeDeclaration contract = typeFactory.CreateInterfaceType();
CodeTypeReference contractReference = codeNamespaceScope.AddUnique(contract, contractDescription.CodeName, Strings.DefaultContractName);
CodeTypeDeclaration callbackContract = null;
CodeTypeReference callbackContractReference = null;
if (isDuplex)
{
callbackContract = typeFactory.CreateInterfaceType();
callbackContractReference = codeNamespaceScope.AddUnique(callbackContract, contractDescription.CodeName + Strings.CallbackTypeSuffix, Strings.DefaultContractName);
}
this.context = new ServiceContractGenerationContext(parent, contractDescription, contract, callbackContract);
this.context.Namespace = codeNamespaceScope.CodeNamespace;
this.context.TypeFactory = this.typeFactory;
this.context.ContractTypeReference = contractReference;
this.context.DuplexCallbackTypeReference = callbackContractReference;
AddServiceContractAttribute(this.context);
}
void Visit(OperationDescription operationDescription)
{
bool isCallback = operationDescription.IsServerInitiated();
CodeTypeDeclaration declaringType = isCallback ? context.DuplexCallbackType : context.ContractType;
UniqueCodeIdentifierScope memberScope = isCallback ? this.callbackMemberScope : this.contractMemberScope;
Fx.Assert(declaringType != null, "missing callback type");
string syncMethodName = memberScope.AddUnique(operationDescription.CodeName, Strings.DefaultOperationName);
CodeMemberMethod syncMethod = new CodeMemberMethod();
syncMethod.Name = syncMethodName;
declaringType.Members.Add(syncMethod);
OperationContractGenerationContext operationContext;
CodeMemberMethod beginMethod = null;
CodeMemberMethod endMethod = null;
if (asyncMethods)
{
beginMethod = new CodeMemberMethod();
beginMethod.Name = ServiceReflector.BeginMethodNamePrefix + syncMethodName;
beginMethod.Parameters.Add(new CodeParameterDeclarationExpression(context.ServiceContractGenerator.GetCodeTypeReference(typeof(AsyncCallback)), Strings.AsyncCallbackArgName));
beginMethod.Parameters.Add(new CodeParameterDeclarationExpression(context.ServiceContractGenerator.GetCodeTypeReference(typeof(object)), Strings.AsyncStateArgName));
beginMethod.ReturnType = context.ServiceContractGenerator.GetCodeTypeReference(typeof(IAsyncResult));
declaringType.Members.Add(beginMethod);
endMethod = new CodeMemberMethod();
endMethod.Name = ServiceReflector.EndMethodNamePrefix + syncMethodName;
endMethod.Parameters.Add(new CodeParameterDeclarationExpression(context.ServiceContractGenerator.GetCodeTypeReference(typeof(IAsyncResult)), Strings.AsyncResultArgName));
declaringType.Members.Add(endMethod);
operationContext = new OperationContractGenerationContext(parent, context, operationDescription, declaringType, syncMethod, beginMethod, endMethod);
}
else
{
operationContext = new OperationContractGenerationContext(parent, context, operationDescription, declaringType, syncMethod);
}
if (taskMethod)
{
if (isCallback)
{
if (beginMethod == null)
{
operationContext = new OperationContractGenerationContext(parent, context, operationDescription, declaringType, syncMethod);
}
else
{
operationContext = new OperationContractGenerationContext(parent, context, operationDescription, declaringType, syncMethod, beginMethod, endMethod);
}
}
else
{
CodeMemberMethod taskBasedAsyncMethod = new CodeMemberMethod { Name = syncMethodName + ServiceReflector.AsyncMethodNameSuffix };
declaringType.Members.Add(taskBasedAsyncMethod);
if (beginMethod == null)
{
operationContext = new OperationContractGenerationContext(parent, context, operationDescription, declaringType, syncMethod, taskBasedAsyncMethod);
}
else
{
operationContext = new OperationContractGenerationContext(parent, context, operationDescription, declaringType, syncMethod, beginMethod, endMethod, taskBasedAsyncMethod);
}
}
}
operationContext.DeclaringTypeReference = operationDescription.IsServerInitiated() ? context.DuplexCallbackTypeReference : context.ContractTypeReference;
context.Operations.Add(operationContext);
AddOperationContractAttributes(operationContext);
}
void AddServiceContractAttribute(ServiceContractGenerationContext context)
{
CodeAttributeDeclaration serviceContractAttr = new CodeAttributeDeclaration(context.ServiceContractGenerator.GetCodeTypeReference(typeof(ServiceContractAttribute)));
if (context.ContractType.Name != context.Contract.CodeName)
{
// make sure that decoded Contract name can be used, if not, then override name with encoded value
// specified in wsdl; this only works beacuse our Encoding algorithm will leave alredy encoded names untouched
string friendlyName = NamingHelper.XmlName(context.Contract.CodeName) == context.Contract.Name ? context.Contract.CodeName : context.Contract.Name;
serviceContractAttr.Arguments.Add(new CodeAttributeArgument("Name", new CodePrimitiveExpression(friendlyName)));
}
if (NamingHelper.DefaultNamespace != context.Contract.Namespace)
serviceContractAttr.Arguments.Add(new CodeAttributeArgument("Namespace", new CodePrimitiveExpression(context.Contract.Namespace)));
serviceContractAttr.Arguments.Add(new CodeAttributeArgument("ConfigurationName", new CodePrimitiveExpression(NamespaceHelper.GetCodeTypeReference(context.Namespace, context.ContractType).BaseType)));
if (context.Contract.HasProtectionLevel)
{
serviceContractAttr.Arguments.Add(new CodeAttributeArgument("ProtectionLevel",
new CodeFieldReferenceExpression(
new CodeTypeReferenceExpression(typeof(ProtectionLevel)), context.Contract.ProtectionLevel.ToString())));
}
if (context.DuplexCallbackType != null)
{
serviceContractAttr.Arguments.Add(new CodeAttributeArgument("CallbackContract", new CodeTypeOfExpression(context.DuplexCallbackTypeReference)));
}
if (context.Contract.SessionMode != SessionMode.Allowed)
{
serviceContractAttr.Arguments.Add(new CodeAttributeArgument("SessionMode",
new CodeFieldReferenceExpression(
new CodeTypeReferenceExpression(typeof(SessionMode)), context.Contract.SessionMode.ToString())));
}
context.ContractType.CustomAttributes.Add(serviceContractAttr);
}
void AddOperationContractAttributes(OperationContractGenerationContext context)
{
if (context.SyncMethod != null)
{
context.SyncMethod.CustomAttributes.Add(CreateOperationContractAttributeDeclaration(context.Operation, false));
}
if (context.BeginMethod != null)
{
context.BeginMethod.CustomAttributes.Add(CreateOperationContractAttributeDeclaration(context.Operation, true));
}
if (context.TaskMethod != null)
{
context.TaskMethod.CustomAttributes.Add(CreateOperationContractAttributeDeclaration(context.Operation, false));
}
}
CodeAttributeDeclaration CreateOperationContractAttributeDeclaration(OperationDescription operationDescription, bool asyncPattern)
{
CodeAttributeDeclaration serviceOperationAttr = new CodeAttributeDeclaration(context.ServiceContractGenerator.GetCodeTypeReference(typeof(OperationContractAttribute)));
if (operationDescription.IsOneWay)
{
serviceOperationAttr.Arguments.Add(new CodeAttributeArgument("IsOneWay", new CodePrimitiveExpression(true)));
}
if ((operationDescription.DeclaringContract.SessionMode == SessionMode.Required) && operationDescription.IsTerminating)
{
serviceOperationAttr.Arguments.Add(new CodeAttributeArgument("IsTerminating", new CodePrimitiveExpression(true)));
}
if ((operationDescription.DeclaringContract.SessionMode == SessionMode.Required) && !operationDescription.IsInitiating)
{
serviceOperationAttr.Arguments.Add(new CodeAttributeArgument("IsInitiating", new CodePrimitiveExpression(false)));
}
if (asyncPattern)
{
serviceOperationAttr.Arguments.Add(new CodeAttributeArgument("AsyncPattern", new CodePrimitiveExpression(true)));
}
if (operationDescription.HasProtectionLevel)
{
serviceOperationAttr.Arguments.Add(new CodeAttributeArgument("ProtectionLevel",
new CodeFieldReferenceExpression(
new CodeTypeReferenceExpression(typeof(ProtectionLevel)), operationDescription.ProtectionLevel.ToString())));
}
return serviceOperationAttr;
}
static bool IsDuplex(ContractDescription contract)
{
foreach (OperationDescription operation in contract.Operations)
if (operation.IsServerInitiated())
return true;
return false;
}
}
class ChannelInterfaceGenerator : IServiceContractGenerationExtension
{
void IServiceContractGenerationExtension.GenerateContract(ServiceContractGenerationContext context)
{
CodeTypeDeclaration channelType = context.TypeFactory.CreateInterfaceType();
channelType.BaseTypes.Add(context.ContractTypeReference);
channelType.BaseTypes.Add(context.ServiceContractGenerator.GetCodeTypeReference(typeof(IClientChannel)));
new UniqueCodeNamespaceScope(context.Namespace).AddUnique(channelType, context.ContractType.Name + Strings.ChannelTypeSuffix, Strings.ChannelTypeSuffix);
}
}
internal class CodeTypeFactory
{
ServiceContractGenerator parent;
bool internalTypes;
public CodeTypeFactory(ServiceContractGenerator parent, bool internalTypes)
{
this.parent = parent;
this.internalTypes = internalTypes;
}
public CodeTypeDeclaration CreateClassType()
{
return CreateCodeType(false);
}
CodeTypeDeclaration CreateCodeType(bool isInterface)
{
CodeTypeDeclaration codeType = new CodeTypeDeclaration();
codeType.IsClass = !isInterface;
codeType.IsInterface = isInterface;
RunDecorators(codeType);
return codeType;
}
public CodeTypeDeclaration CreateInterfaceType()
{
return CreateCodeType(true);
}
void RunDecorators(CodeTypeDeclaration codeType)
{
AddPartial(codeType);
AddInternal(codeType);
AddDebuggerStepThroughAttribute(codeType);
AddGeneratedCodeAttribute(codeType);
}
#region CodeTypeDeclaration decorators
void AddDebuggerStepThroughAttribute(CodeTypeDeclaration codeType)
{
if (codeType.IsClass)
{
codeType.CustomAttributes.Add(new CodeAttributeDeclaration(parent.GetCodeTypeReference(typeof(DebuggerStepThroughAttribute))));
}
}
void AddGeneratedCodeAttribute(CodeTypeDeclaration codeType)
{
CodeAttributeDeclaration generatedCodeAttribute = new CodeAttributeDeclaration(parent.GetCodeTypeReference(typeof(GeneratedCodeAttribute)));
AssemblyName assemblyName = Assembly.GetExecutingAssembly().GetName();
generatedCodeAttribute.Arguments.Add(new CodeAttributeArgument(new CodePrimitiveExpression(assemblyName.Name)));
generatedCodeAttribute.Arguments.Add(new CodeAttributeArgument(new CodePrimitiveExpression(assemblyName.Version.ToString())));
codeType.CustomAttributes.Add(generatedCodeAttribute);
}
void AddInternal(CodeTypeDeclaration codeType)
{
if (internalTypes)
{
codeType.TypeAttributes &= ~TypeAttributes.Public;
}
}
void AddPartial(CodeTypeDeclaration codeType)
{
if (codeType.IsClass)
{
codeType.IsPartial = true;
}
}
#endregion
}
internal static class ExtensionsHelper
{
// calls the behavior extensions
static internal void CallBehaviorExtensions(ServiceContractGenerationContext context)
{
CallContractExtensions(EnumerateBehaviorExtensions(context.Contract), context);
foreach (OperationContractGenerationContext operationContext in context.Operations)
{
CallOperationExtensions(EnumerateBehaviorExtensions(operationContext.Operation), operationContext);
}
}
// calls a specific set of contract-level extensions
static internal void CallContractExtensions(IEnumerable<IServiceContractGenerationExtension> extensions, ServiceContractGenerationContext context)
{
foreach (IServiceContractGenerationExtension extension in extensions)
{
extension.GenerateContract(context);
}
}
// calls a specific set of operation-level extensions on each operation in the contract
static internal void CallOperationExtensions(IEnumerable<IOperationContractGenerationExtension> extensions, ServiceContractGenerationContext context)
{
foreach (OperationContractGenerationContext operationContext in context.Operations)
{
CallOperationExtensions(extensions, operationContext);
}
}
// calls a specific set of operation-level extensions
static void CallOperationExtensions(IEnumerable<IOperationContractGenerationExtension> extensions, OperationContractGenerationContext context)
{
foreach (IOperationContractGenerationExtension extension in extensions)
{
extension.GenerateOperation(context);
}
}
static IEnumerable<IServiceContractGenerationExtension> EnumerateBehaviorExtensions(ContractDescription contract)
{
foreach (IContractBehavior behavior in contract.Behaviors)
{
if (behavior is IServiceContractGenerationExtension)
{
yield return (IServiceContractGenerationExtension)behavior;
}
}
}
static IEnumerable<IOperationContractGenerationExtension> EnumerateBehaviorExtensions(OperationDescription operation)
{
foreach (IOperationBehavior behavior in operation.Behaviors)
{
if (behavior is IOperationContractGenerationExtension)
{
yield return (IOperationContractGenerationExtension)behavior;
}
}
}
}
class FaultContractAttributeGenerator : IOperationContractGenerationExtension
{
static CodeTypeReference voidTypeReference = new CodeTypeReference(typeof(void));
void IOperationContractGenerationExtension.GenerateOperation(OperationContractGenerationContext context)
{
CodeMemberMethod methodDecl = context.SyncMethod ?? context.BeginMethod;
foreach (FaultDescription fault in context.Operation.Faults)
{
CodeAttributeDeclaration faultAttr = CreateAttrDecl(context, fault);
if (faultAttr != null)
methodDecl.CustomAttributes.Add(faultAttr);
}
}
static CodeAttributeDeclaration CreateAttrDecl(OperationContractGenerationContext context, FaultDescription fault)
{
CodeTypeReference exceptionTypeReference = fault.DetailType != null ? context.Contract.ServiceContractGenerator.GetCodeTypeReference(fault.DetailType) : fault.DetailTypeReference;
if (exceptionTypeReference == null || exceptionTypeReference == voidTypeReference)
return null;
CodeAttributeDeclaration faultContractAttr = new CodeAttributeDeclaration(context.ServiceContractGenerator.GetCodeTypeReference(typeof(FaultContractAttribute)));
faultContractAttr.Arguments.Add(new CodeAttributeArgument(new CodeTypeOfExpression(exceptionTypeReference)));
if (fault.Action != null)
faultContractAttr.Arguments.Add(new CodeAttributeArgument("Action", new CodePrimitiveExpression(fault.Action)));
if (fault.HasProtectionLevel)
{
faultContractAttr.Arguments.Add(new CodeAttributeArgument("ProtectionLevel",
new CodeFieldReferenceExpression(
new CodeTypeReferenceExpression(typeof(ProtectionLevel)), fault.ProtectionLevel.ToString())));
}
// override name with encoded value specified in wsdl; this only works beacuse
// our Encoding algorithm will leave alredy encoded names untouched
if (!XmlName.IsNullOrEmpty(fault.ElementName))
faultContractAttr.Arguments.Add(new CodeAttributeArgument("Name", new CodePrimitiveExpression(fault.ElementName.EncodedName)));
if (fault.Namespace != context.Contract.Contract.Namespace)
faultContractAttr.Arguments.Add(new CodeAttributeArgument("Namespace", new CodePrimitiveExpression(fault.Namespace)));
return faultContractAttr;
}
}
class MessageDescriptionComparer : IEqualityComparer<MessageDescription>
{
static internal MessageDescriptionComparer Singleton = new MessageDescriptionComparer();
MessageDescriptionComparer() { }
bool IEqualityComparer<MessageDescription>.Equals(MessageDescription x, MessageDescription y)
{
if (x.XsdTypeName != y.XsdTypeName)
return false;
// compare headers
if (x.Headers.Count != y.Headers.Count)
return false;
MessageHeaderDescription[] xHeaders = new MessageHeaderDescription[x.Headers.Count];
x.Headers.CopyTo(xHeaders, 0);
MessageHeaderDescription[] yHeaders = new MessageHeaderDescription[y.Headers.Count];
y.Headers.CopyTo(yHeaders, 0);
if (x.Headers.Count > 1)
{
Array.Sort((MessagePartDescription[])xHeaders, MessagePartDescriptionComparer.Singleton);
Array.Sort((MessagePartDescription[])yHeaders, MessagePartDescriptionComparer.Singleton);
}
for (int i = 0; i < xHeaders.Length; i++)
{
if (MessagePartDescriptionComparer.Singleton.Compare(xHeaders[i], yHeaders[i]) != 0)
return false;
}
return true;
}
int IEqualityComparer<MessageDescription>.GetHashCode(MessageDescription obj)
{
return obj.XsdTypeName.GetHashCode();
}
class MessagePartDescriptionComparer : IComparer<MessagePartDescription>
{
static internal MessagePartDescriptionComparer Singleton = new MessagePartDescriptionComparer();
MessagePartDescriptionComparer() { }
public int Compare(MessagePartDescription p1, MessagePartDescription p2)
{
if (null == p1)
{
return (null == p2) ? 0 : -1;
}
if (null == p2)
{
return 1;
}
int i = String.CompareOrdinal(p1.Namespace, p2.Namespace);
if (i == 0)
{
i = String.CompareOrdinal(p1.Name, p2.Name);
}
return i;
}
}
}
internal class NamespaceHelper
{
static readonly object referenceKey = new object();
const string WildcardNamespaceMapping = "*";
readonly CodeNamespaceCollection codeNamespaces;
Dictionary<string, string> namespaceMappings;
public NamespaceHelper(CodeNamespaceCollection namespaces)
{
this.codeNamespaces = namespaces;
}
public Dictionary<string, string> NamespaceMappings
{
get
{
if (namespaceMappings == null)
namespaceMappings = new Dictionary<string, string>();
return namespaceMappings;
}
}
string DescriptionToCode(string descriptionNamespace)
{
string target = String.Empty;
// use field to avoid init'ing dictionary if possible
if (namespaceMappings != null)
{
if (!namespaceMappings.TryGetValue(descriptionNamespace, out target))
{
// try to fall back to wildcard
if (!namespaceMappings.TryGetValue(WildcardNamespaceMapping, out target))
{
return String.Empty;
}
}
}
return target;
}
public CodeNamespace EnsureNamespace(string descriptionNamespace)
{
string ns = DescriptionToCode(descriptionNamespace);
CodeNamespace codeNamespace = FindNamespace(ns);
if (codeNamespace == null)
{
codeNamespace = new CodeNamespace(ns);
this.codeNamespaces.Add(codeNamespace);
}
return codeNamespace;
}
CodeNamespace FindNamespace(string ns)
{
foreach (CodeNamespace codeNamespace in this.codeNamespaces)
{
if (codeNamespace.Name == ns)
return codeNamespace;
}
return null;
}
public static CodeTypeDeclaration GetCodeType(CodeTypeReference codeTypeReference)
{
return codeTypeReference.UserData[referenceKey] as CodeTypeDeclaration;
}
static internal CodeTypeReference GetCodeTypeReference(CodeNamespace codeNamespace, CodeTypeDeclaration codeType)
{
CodeTypeReference codeTypeReference = new CodeTypeReference(String.IsNullOrEmpty(codeNamespace.Name) ? codeType.Name : codeNamespace.Name + '.' + codeType.Name);
codeTypeReference.UserData[referenceKey] = codeType;
return codeTypeReference;
}
}
internal struct OptionsHelper
{
public readonly ServiceContractGenerationOptions Options;
public OptionsHelper(ServiceContractGenerationOptions options)
{
this.Options = options;
}
public bool IsSet(ServiceContractGenerationOptions option)
{
Fx.Assert(IsSingleBit((int)option), "");
return ((this.Options & option) != ServiceContractGenerationOptions.None);
}
static bool IsSingleBit(int x)
{
//figures out if the mode has a single bit set ( is a power of 2)
return (x != 0) && ((x & (x + ~0)) == 0);
}
}
static class Strings
{
public const string AsyncCallbackArgName = "callback";
public const string AsyncStateArgName = "asyncState";
public const string AsyncResultArgName = "result";
public const string CallbackTypeSuffix = "Callback";
public const string ChannelTypeSuffix = "Channel";
public const string DefaultContractName = "IContract";
public const string DefaultOperationName = "Method";
public const string InterfaceTypePrefix = "I";
}
// ideally this one would appear on TransactionFlowAttribute
class TransactionFlowAttributeGenerator : IOperationContractGenerationExtension
{
void IOperationContractGenerationExtension.GenerateOperation(OperationContractGenerationContext context)
{
System.ServiceModel.TransactionFlowAttribute attr = context.Operation.Behaviors.Find<System.ServiceModel.TransactionFlowAttribute>();
if (attr != null && attr.Transactions != TransactionFlowOption.NotAllowed)
{
CodeMemberMethod methodDecl = context.SyncMethod ?? context.BeginMethod;
methodDecl.CustomAttributes.Add(CreateAttrDecl(context, attr));
}
}
static CodeAttributeDeclaration CreateAttrDecl(OperationContractGenerationContext context, TransactionFlowAttribute attr)
{
CodeAttributeDeclaration attrDecl = new CodeAttributeDeclaration(context.Contract.ServiceContractGenerator.GetCodeTypeReference(typeof(TransactionFlowAttribute)));
attrDecl.Arguments.Add(new CodeAttributeArgument(ServiceContractGenerator.GetEnumReference<TransactionFlowOption>(attr.Transactions)));
return attrDecl;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using IxMilia.BCad.Entities;
using IxMilia.BCad.Extensions;
using IxMilia.BCad.Helpers;
using IxMilia.BCad.Primitives;
using Xunit;
namespace IxMilia.BCad.Core.Test
{
public class PrimitiveTests
{
#region Helpers
private static void TestIntersection(IPrimitive first, IPrimitive second, bool withinBounds, params Point[] points)
{
var p = first.IntersectionPoints(second, withinBounds).OrderBy(x => x.X).ThenBy(y => y.Y).ThenBy(z => z.Z).ToArray();
points = points.OrderBy(x => x.X).ThenBy(y => y.Y).ThenBy(z => z.Z).ToArray();
Assert.Equal(points.Length, p.Length);
for (int i = 0; i < p.Length; i++)
{
AssertClose(points[i], p[i]);
}
}
private static bool AreClose(double expected, double actual)
{
return Math.Abs(expected - actual) < MathHelper.Epsilon;
}
private static void AssertClose(double expected, double actual)
{
Assert.True(Math.Abs(expected - actual) < MathHelper.Epsilon, string.Format("Expected: {0}\nActual: {1}", expected, actual));
}
private static void AssertClose(Point expected, Point actual)
{
Assert.True(AreClose(expected.X, actual.X) && AreClose(expected.Y, actual.Y) && AreClose(expected.Z, actual.Z),
$"Expected: {expected}\nActual: {actual}");
}
private static void AssertClose(Vector expected, Vector actual)
{
AssertClose((Point)expected, (Point)actual);
}
private static void AssertClose(Vertex expected, Vertex actual)
{
AssertClose(expected.Location, actual.Location);
AssertClose(expected.IncludedAngle, actual.IncludedAngle);
Assert.Equal(expected.Direction, actual.Direction);
}
private static void TestThreePointArcNormal(Point a, Point b, Point c, Vector idealNormal, Point expectedCenter, double expectedRadius, double expectedStartAngle, double expectedEndAngle)
{
var arc = PrimitiveEllipse.ThreePointArc(a, b, c, idealNormal);
AssertClose(idealNormal, arc.Normal);
AssertClose(expectedCenter, arc.Center);
AssertClose(1.0, arc.MinorAxisRatio);
AssertClose(expectedRadius, arc.MajorAxis.Length);
AssertClose(expectedStartAngle, arc.StartAngle);
AssertClose(expectedEndAngle, arc.EndAngle);
}
private static PrimitiveLine Line(Point p1, Point p2)
{
return new PrimitiveLine(p1, p2);
}
private static PrimitiveEllipse Circle(Point center, double radius)
{
return new PrimitiveEllipse(center, radius, Vector.ZAxis);
}
private static PrimitiveEllipse Arc(Point center, double radius, double startAngle, double endAngle)
{
return new PrimitiveEllipse(center, radius, startAngle, endAngle, Vector.ZAxis);
}
private static PrimitiveEllipse Ellipse(Point center, double radiusX, double radiusY)
{
return new PrimitiveEllipse(center, new Vector(radiusX, 0, 0), Vector.ZAxis, radiusY / radiusX, 0, 360);
}
private static void TestPointContainment(IPrimitive primitive, IEnumerable<Point> contained = null, IEnumerable<Point> excluded = null)
{
if (contained != null)
Assert.True(contained.All(p => primitive.IsPointOnPrimitive(p)));
if (excluded != null)
Assert.True(excluded.All(p => !primitive.IsPointOnPrimitive(p)));
}
#endregion
[Fact]
public void LineIntersectionTest()
{
TestIntersection(
Line(new Point(-1, 0, 0), new Point(1, 0, 0)),
Line(new Point(0, -1, 0), new Point(0, 1, 0)),
true,
new Point(0, 0, 0));
}
[Fact]
public void LinePointDistanceTest()
{
var l = Line(new Point(0, 0, 0), new Point(2, 0, 0));
var p = new Point(1, 1, 0);
Assert.Equal(new Point(1, 0, 0), l.ClosestPoint(p));
}
[Fact]
public void LinePointDistanceTest2()
{
var a = Line(new Point(0, 0, 0), new Point(10, 0, 0));
var b = new Point(5, 3, 0);
var c = a.ClosestPoint(b);
Assert.Equal(new Point(5, 0, 0), c);
}
[Fact]
public void ThreePointCircleTest()
{
var a = new Point(0, 0, 0);
var b = new Point(0, 2, 0);
var c = new Point(1, 1, 0);
var circ = PrimitiveEllipse.ThreePointCircle(a, b, c);
Assert.NotNull(circ);
Assert.Equal(new Point(0, 1, 0), circ.Center);
Assert.Equal(Vector.XAxis, circ.MajorAxis);
Assert.Equal(Vector.ZAxis, circ.Normal);
}
[Fact]
public void ThreePointArcNormalizedNormalTest()
{
var rad = Math.Sqrt(2.0) / 2.0;
// up then left
//
// 3 2
//
// c
//
// 1
TestThreePointArcNormal(
new Point(1, 0, 0),
new Point(1, 1, 0),
new Point(0, 1, 0),
Vector.ZAxis,
new Point(0.5, 0.5, 0),
rad,
315.0,
135.0);
// up then right
//
// 2 3
//
// c
//
// 1
TestThreePointArcNormal(
new Point(0, 0, 0),
new Point(0, 1, 0),
new Point(1, 1, 0),
Vector.ZAxis,
new Point(0.5, 0.5, 0),
rad,
45.0,
225.0);
// down then left
//
// 1
//
// c
//
// 3 2
TestThreePointArcNormal(
new Point(1, 1, 0),
new Point(1, 0, 0),
new Point(0, 0, 0),
Vector.ZAxis,
new Point(0.5, 0.5, 0),
rad,
225.0,
45.0);
// down then right
//
// 1
//
// c
//
// 2 3
TestThreePointArcNormal(
new Point(0, 1, 0),
new Point(0, 0, 0),
new Point(1, 0, 0),
Vector.ZAxis,
new Point(0.5, 0.5, 0),
rad,
135.0,
315.0);
}
[Fact]
public void ThreePointArcWithLargeAngleTest()
{
var sqrt22 = Math.Sqrt(2.0) / 2.0;
// counter clockwise
//
// 1
//
// c 3
//
// 2
TestThreePointArcNormal(
new Point(0, 1, 0),
new Point(-sqrt22, -sqrt22, 0),
new Point(1, 0, 0),
idealNormal: Vector.ZAxis,
expectedCenter: Point.Origin,
expectedRadius: 1.0,
expectedStartAngle: 90.0,
expectedEndAngle: 0.0);
// clockwise
//
// 3
//
// c 1
//
// 2
TestThreePointArcNormal(
new Point(1, 0, 0),
new Point(-sqrt22, -sqrt22, 0),
new Point(0, 1, 0),
idealNormal: Vector.ZAxis,
expectedCenter: Point.Origin,
expectedRadius: 1.0,
expectedStartAngle: 90.0,
expectedEndAngle: 0.0);
}
[Fact]
public void LineCircleIntersectionTest1()
{
TestIntersection(
Circle(Point.Origin, 2),
Line(new Point(2, 0, -2), new Point(2, 0, 2)),
true,
new Point(2, 0, 0));
}
[Fact]
public void LineCircleIntersectionTest2()
{
TestIntersection(
Circle(new Point(1, 0, 0), 1.0),
Line(new Point(-4, 0, 0), new Point(4, 0, 0)),
true,
new Point(2, 0, 0),
new Point(0, 0, 0));
}
[Fact]
public void LineCircleIntersectionTest3()
{
TestIntersection(
Circle(new Point(1, 1, 0), 2),
Line(new Point(-3, 1, 0), new Point(3, 1, 0)),
true,
new Point(-1, 1, 0),
new Point(3, 1, 0));
}
[Fact]
public void LineCircleIntersectionTest4()
{
TestIntersection(
Circle(new Point(1, 1, 0), 2),
Line(new Point(2, 1, 0), new Point(4, 1, 0)),
true,
new Point(3, 1, 0));
}
[Fact]
public void LineCircleIntersectionTestOffPlane()
{
TestIntersection(
Circle(Point.Origin, 1),
Line(new Point(1, 0, 1), new Point(1, 0, -1)),
true,
new Point(1, 0, 0));
}
[Fact]
public void LineCircleIntersectionTestOffPlaneOutsideAngle()
{
TestIntersection(
Arc(Point.Origin, 1, 90, 270),
Line(new Point(1, 0, 1), new Point(1, 0, -1)),
true);
}
[Fact]
public void CircleCircleIntersectionTestSamePlaneOnePoint()
{
TestIntersection(
Circle(new Point(1, 1, 0), 2),
Circle(new Point(4, 1, 0), 1),
true,
new Point(3, 1, 0));
TestIntersection(
Circle(new Point(100, 100, 0), 10),
Circle(new Point(120, 100, 0), 10),
true,
new Point(110, 100, 0));
}
[Fact]
public void CircleCircleIntersectionTestSamePlaneTwoPoints()
{
var x = Math.Sqrt(3.0) / 2.0;
TestIntersection(
Circle(Point.Origin, 1),
Circle(new Point(1, 0, 0), 1),
true,
new Point(0.5, x, 0),
new Point(0.5, -x, 0));
TestIntersection(
Circle(new Point(100, 0, 0), 80),
Circle(new Point(100, 100, 0), 80),
true,
new Point(37.550020016016, 50, 0),
new Point(162.449979983983, 50, 0));
}
[Fact]
public void CircleCircleIntersectionTestSamePlaneNoPoints()
{
var x = Math.Sqrt(3.0) / 2.0;
TestIntersection(
Circle(Point.Origin, 1),
Circle(new Point(3, 0, 0), 1),
true);
}
[Fact]
public void CircleEllipseIntersectionTestSamePlaneOnePoint()
{
// x-axis alignment horizontal
TestIntersection(
Circle(new Point(1, 0, 0), 1),
Ellipse(new Point(4, 0, 0), 2, 1),
true,
new Point(2, 0, 0));
// x-axis alignment vertical
TestIntersection(
Circle(new Point(1, 0, 0), 1),
Ellipse(new Point(3, 0, 0), 1, 2),
true,
new Point(2, 0, 0));
// y-axis alignment horizontal
TestIntersection(
Circle(Point.Origin, 1),
Ellipse(new Point(0, 2, 0), 2, 1),
true,
new Point(0, 1, 0));
// y-axis alignment vertical
TestIntersection(
Circle(Point.Origin, 1),
Ellipse(new Point(0, 3, 0), 1, 2),
true,
new Point(0, 1, 0));
// rotates to x-axis alignment
TestIntersection(
Circle(Point.Origin, 1),
new PrimitiveEllipse(new Point(-Math.Sqrt(2), Math.Sqrt(2), 0), new Vector(Math.Sqrt(2), Math.Sqrt(2), 0), Vector.ZAxis, 0.5, 0, 360),
true,
new Point(-0.707106781187, 0.707106781187, 0));
}
[Fact]
public void CircleEllipseIntersectionTestSamePlaneTwoPoints()
{
// y-axis alignment
TestIntersection(
Circle(new Point(1, 0, 0), 1),
Ellipse(new Point(3, 0, 0), 2, 1),
true,
new Point(1.666666666667, -0.7453559925, 0),
new Point(1.666666666667, 0.7453559925, 0));
// no axis alignment
TestIntersection(
Circle(Point.Origin, 1),
Ellipse(new Point(2, 1, 0), 2, 1),
true,
new Point(0, 1, 0),
new Point(1, 0.133974596216, 0));
}
[Fact]
public void CircleEllipseIntersectionTestDifferentPlanes()
{
// 1 intersection point, x-axis plane intersection
TestIntersection(
Circle(Point.Origin, 1),
new PrimitiveEllipse(new Point(0, 1, 1), 1, Vector.YAxis),
true,
new Point(0, 1, 0));
// 1 intersection point, y-axis plane intersection
TestIntersection(
Circle(Point.Origin, 1),
new PrimitiveEllipse(new Point(1, 0, 1), 1, Vector.XAxis),
true,
new Point(1, 0, 0));
// 1 intersection point, z-axis plane intersection
TestIntersection(
new PrimitiveEllipse(Point.Origin, 1, Vector.XAxis),
new PrimitiveEllipse(new Point(1, 1, 0), 1, Vector.YAxis),
true,
new Point(0, 1, 0));
// 2 intersection points
TestIntersection(
Circle(new Point(1, 0, 0), 1),
new PrimitiveEllipse(new Point(1, 0, 0), new Vector(0, 0, 2), Vector.XAxis, 0.5, 0, 360),
true,
new Point(1, -1, 0),
new Point(1, 1, 0));
}
[Fact]
public void PointOnLineTest()
{
TestPointContainment(Line(new Point(0.0, 0.0, 0.0), new Point(1.0, 0.0, 0.0)),
contained: new[]
{
new Point(0.0, 0.0, 0.0),
new Point(0.5, 0.0, 0.0),
new Point(1.0, 0.0, 0.0)
});
TestPointContainment(Line(new Point(0.0, 0.0, 0.0), new Point(1.0, 1.0, 1.0)),
contained: new[]
{
new Point(0.0, 0.0, 0.0),
new Point(0.5, 0.5, 0.5),
new Point(1.0, 1.0, 1.0)
});
}
[Fact]
public void PointOnCircleTest()
{
var x = Math.Sin(45.0 * MathHelper.DegreesToRadians);
TestPointContainment(Circle(new Point(0.0, 0.0, 0.0), 1.0),
contained: new[]
{
new Point(1.0, 0.0, 0.0),
new Point(0.0, 1.0, 0.0),
new Point(-1.0, 0.0, 0.0),
new Point(0.0, -1.0, 0.0),
new Point(x, x, 0.0)
},
excluded: new[]
{
new Point(0.5, 0.0, 0.0),
new Point(1.5, 0.0, 0.0),
});
TestPointContainment(Circle(new Point(1.0, 1.0, 0.0), 1.0),
contained: new[]
{
new Point(2.0, 1.0, 0.0),
new Point(1.0, 2.0, 0.0),
new Point(0.0, 1.0, 0.0),
new Point(1.0, 0.0, 0.0),
new Point(x + 1.0, x + 1.0, 0.0)
});
TestPointContainment(Arc(new Point(0.0, 0.0, 0.0), 1.0, 90.0, 180.0),
contained: new[]
{
new Point(0.0, 1.0, 0.0), // 90 degrees
new Point(-1.0, 0.0, 0.0) // 180 degrees
},
excluded: new[]
{
new Point(0.0, -1.0, 0.0), // 270 degrees
new Point(0.0, 0.0, 0.0) // 0/360 degrees
});
}
[Fact]
public void PointInTextTest()
{
// text width = 9.23076923076923
TestPointContainment(new PrimitiveText(" ", new Point(0.0, 0.0, 0.0), 12.0, Vector.ZAxis, 0.0),
contained: new[]
{
new Point(0.0, 0.0, 0.0),
new Point(9.0, 12.0, 0.0)
},
excluded: new[]
{
new Point(0.0, 12.1, 0.0)
});
TestPointContainment(new PrimitiveText(" ", new Point(5.0, 5.0, 5.0), 12.0, Vector.ZAxis, 0.0),
contained: new[]
{
new Point(5.0, 5.0, 5.0),
new Point(14.0, 17.0, 5.0)
},
excluded: new[]
{
new Point(5.0, 17.1, 5.0)
});
}
[Fact]
public void EllipseAngleContainmentTest()
{
var el = new PrimitiveEllipse(Point.Origin, 1.0, 90.0, 360.0, Vector.ZAxis);
Assert.True(el.IsAngleContained(90.0));
Assert.True(el.IsAngleContained(180.0));
Assert.True(el.IsAngleContained(270.0));
Assert.True(el.IsAngleContained(360.0));
Assert.False(el.IsAngleContained(45.0));
}
[Fact]
public void EllipseGetPointTest()
{
var el = new PrimitiveEllipse(Point.Origin, 1.0, 0.0, 180.0, Vector.ZAxis);
Assert.True(el.StartPoint().CloseTo(new Point(1.0, 0.0, 0.0)));
Assert.True(el.EndPoint().CloseTo(new Point(-1.0, 0.0, 0.0)));
Assert.True(el.GetPoint(90.0).CloseTo(new Point(0.0, 1.0, 0.0)));
el = new PrimitiveEllipse(new Point(1.0, 1.0, 0.0), 1.0, 0.0, 180.0, Vector.ZAxis);
Assert.True(el.StartPoint().CloseTo(new Point(2.0, 1.0, 0.0)));
Assert.True(el.EndPoint().CloseTo(new Point(0.0, 1.0, 0.0)));
Assert.True(el.GetPoint(90.0).CloseTo(new Point(1.0, 2.0, 0.0)));
}
[Fact]
public void LinesToLineStripTest()
{
var lines = new List<PrimitiveLine>()
{
new PrimitiveLine(new Point(0.0, 0.0, 0.0), new Point(1.0, 0.0, 0.0)), // bottom of square
new PrimitiveLine(new Point(1.0, 1.0, 0.0), new Point(1.0, 0.0, 0.0)), // right edge of square, points reversed
new PrimitiveLine(new Point(1.0, 1.0, 0.0), new Point(0.0, 1.0, 0.0)), // top edge of square
new PrimitiveLine(new Point(0.0, 0.0, 0.0), new Point(0.0, 1.0, 0.0)), // left edge of square, points reversed
};
var points = lines.GetLineStripsFromPrimitives();
}
[Fact]
public void ArcsFromPointsAndRadiusTest1()
{
// given the points (0, 1) and (0, -1) and an included angle of 90 degrees, the possible centers for the arcs
// here are (1, 0) and (-1, 0) and a radius of sqrt(2)
var p1 = new Point(0, 1, 0);
var p2 = new Point(0, -1, 0);
var includedAngle = 90.0;
var sqrt2 = Math.Sqrt(2.0);
var arc1 = PrimitiveEllipse.ArcFromPointsAndIncludedAngle(p1, p2, includedAngle, VertexDirection.Clockwise);
AssertClose(new Point(-1, 0, 0), arc1.Center);
AssertClose(sqrt2, arc1.MajorAxis.Length);
AssertClose(315.0, arc1.StartAngle);
AssertClose(45.0, arc1.EndAngle);
var arc2 = PrimitiveEllipse.ArcFromPointsAndIncludedAngle(p1, p2, includedAngle, VertexDirection.CounterClockwise);
AssertClose(new Point(1, 0, 0), arc2.Center);
AssertClose(sqrt2, arc2.MajorAxis.Length);
AssertClose(135.0, arc2.StartAngle);
AssertClose(225.0, arc2.EndAngle);
}
[Fact]
public void LineStripsWithOutOfOrderArcsTest()
{
// In the following, the arc has start/end angles of 0/90, but the order of the lines
// indicates that the end point should be processed first.
// start
// ---------- // line 1
// - \ // arc
// origin> X | // line 2
// |
// | end
var primitives = new IPrimitive[]
{
new PrimitiveLine(new Point(-1.0, 1.0, 0.0), new Point(0.0, 1.0, 0.0)),
new PrimitiveEllipse(new Point(0.0, 0.0, 0.0), 1.0, 0.0, 90.0, Vector.ZAxis),
new PrimitiveLine(new Point(1.0, 0.0, 0.0), new Point(1.0, -1.0, 0.0)),
};
var lineStrips = primitives.GetLineStripsFromPrimitives();
var polys = lineStrips.GetPolylinesFromPrimitives();
var poly = polys.Single();
var vertices = poly.Vertices.ToList();
Assert.Equal(4, vertices.Count);
AssertClose(new Vertex(new Point(-1.0, 1.0, 0.0)), vertices[0]); // start point
AssertClose(new Vertex(new Point(0.0, 1.0, 0.0), 90.0, VertexDirection.Clockwise), vertices[1]); // end of line 1, start of arc
AssertClose(new Vertex(new Point(1.0, 0.0, 0.0)), vertices[2]); // end of arc, start of line 1
AssertClose(new Vertex(new Point(1.0, -1.0, 0.0)), vertices[3]); // end
}
[Fact]
public void LineStripStartingWithAnArcTest()
{
// In the following, the arc has start/end angles of 0/90, but the order of the lines
// indicates that the end point should be processed first. Since the strip starts with
// an arc, we have to proceed to the next line to determine the start order
// start -- \ // arc
// \
// origin> X | // line
// |
// | end
var primitives = new IPrimitive[]
{
new PrimitiveEllipse(new Point(0.0, 0.0, 0.0), 1.0, 0.0, 90.0, Vector.ZAxis),
new PrimitiveLine(new Point(1.0, 0.0, 0.0), new Point(1.0, -1.0, 0.0)),
};
var lineStrips = primitives.GetLineStripsFromPrimitives();
var polys = lineStrips.GetPolylinesFromPrimitives();
var poly = polys.Single();
var vertices = poly.Vertices.ToList();
Assert.Equal(3, vertices.Count);
AssertClose(new Vertex(new Point(0.0, 1.0, 0.0), 90.0, VertexDirection.Clockwise), vertices[0]); // start of arc
AssertClose(new Vertex(new Point(1.0, 0.0, 0.0)), vertices[1]); // end of arc, start of line
AssertClose(new Vertex(new Point(1.0, -1.0, 0.0)), vertices[2]); // end
}
[Fact]
public void LineStripsFromOutOfOrderLinesTest()
{
// In the following, the starting line's P1 is what aligns with the next primitive
// line's start point, so the first line will have to look ahead to determine the
// order in which to process the line. The end result is that the first line is added
// 'backwards' to the list.
var primitives = new IPrimitive[]
{
new PrimitiveLine(new Point(0.0, 0.0, 0.0), new Point(2.0, 2.0, 0.0)),
new PrimitiveLine(new Point(1.0, 3.0, 0.0), new Point(0.0, 0.0, 0.0))
};
var polyline = primitives.GetPolylinesFromSegments().Single();
var vertices = polyline.Vertices.ToList();
Assert.Equal(3, vertices.Count);
Assert.Equal(new Point(2.0, 2.0, 0.0), vertices[0].Location);
Assert.Equal(new Point(0.0, 0.0, 0.0), vertices[1].Location);
Assert.Equal(new Point(1.0, 3.0, 0.0), vertices[2].Location);
}
[Fact]
public void LineStripsFromSinglePrimitiveTest()
{
var line = new PrimitiveLine(new Point(0.0, 0.0, 0.0), new Point(1.0, 0.0, 0.0));
var polylines = new[] { line }.GetPolylinesFromSegments();
var poly = polylines.Single();
var primitive = (PrimitiveLine)poly.GetPrimitives().Single();
Assert.Equal(line.P1, primitive.P1);
Assert.Equal(line.P2, primitive.P2);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Linq.Expressions.Tests;
using Microsoft.CSharp.RuntimeBinder;
using Xunit;
namespace System.Dynamic.Tests
{
public class BinaryOperationTests
{
private class MinimumOverrideBinaryOperationBinder : BinaryOperationBinder
{
public MinimumOverrideBinaryOperationBinder(ExpressionType operation) : base(operation)
{
}
public override DynamicMetaObject FallbackBinaryOperation(
DynamicMetaObject target, DynamicMetaObject arg, DynamicMetaObject errorSuggestion)
{
throw new NotSupportedException();
}
}
private static readonly int[] SomeInt32 = {0, 1, 2, -1, int.MinValue, int.MaxValue, int.MaxValue - 1};
private static IEnumerable<object[]> CrossJoinInt32()
=> from i in SomeInt32 from j in SomeInt32 select new object[] {i, j};
private static readonly double[] SomeDouble = {0.0, 1.0, 2.0, -1.0, double.PositiveInfinity, double.NaN};
private static IEnumerable<object[]> CrossJoinDouble()
=> from i in SomeDouble from j in SomeDouble select new object[] {i, j};
private static IEnumerable<object[]> BinaryExpressionTypes()
{
yield return new object[] {ExpressionType.Add};
yield return new object[] {ExpressionType.And};
yield return new object[] {ExpressionType.Divide};
yield return new object[] {ExpressionType.Equal};
yield return new object[] {ExpressionType.ExclusiveOr};
yield return new object[] {ExpressionType.GreaterThan};
yield return new object[] {ExpressionType.GreaterThanOrEqual};
yield return new object[] {ExpressionType.LeftShift};
yield return new object[] {ExpressionType.LessThan};
yield return new object[] {ExpressionType.LessThanOrEqual};
yield return new object[] {ExpressionType.Modulo};
yield return new object[] {ExpressionType.Multiply};
yield return new object[] {ExpressionType.NotEqual};
yield return new object[] {ExpressionType.Or};
yield return new object[] {ExpressionType.Power};
yield return new object[] {ExpressionType.RightShift};
yield return new object[] {ExpressionType.Subtract};
yield return new object[] {ExpressionType.Extension};
yield return new object[] {ExpressionType.AddAssign};
yield return new object[] {ExpressionType.AndAssign};
yield return new object[] {ExpressionType.DivideAssign};
yield return new object[] {ExpressionType.ExclusiveOrAssign};
yield return new object[] {ExpressionType.LeftShiftAssign};
yield return new object[] {ExpressionType.ModuloAssign};
yield return new object[] {ExpressionType.MultiplyAssign};
yield return new object[] {ExpressionType.OrAssign};
yield return new object[] {ExpressionType.PowerAssign};
yield return new object[] {ExpressionType.RightShiftAssign};
yield return new object[] {ExpressionType.SubtractAssign};
}
private static IEnumerable<object[]> NonBinaryExpressionTypes()
{
yield return new object[] {ExpressionType.AddChecked};
yield return new object[] {ExpressionType.AndAlso};
yield return new object[] {ExpressionType.ArrayLength};
yield return new object[] {ExpressionType.ArrayIndex};
yield return new object[] {ExpressionType.Call};
yield return new object[] {ExpressionType.Coalesce};
yield return new object[] {ExpressionType.Conditional};
yield return new object[] {ExpressionType.Constant};
yield return new object[] {ExpressionType.Convert};
yield return new object[] {ExpressionType.ConvertChecked};
yield return new object[] {ExpressionType.Invoke};
yield return new object[] {ExpressionType.Lambda};
yield return new object[] {ExpressionType.ListInit};
yield return new object[] {ExpressionType.MemberAccess};
yield return new object[] {ExpressionType.MemberInit};
yield return new object[] {ExpressionType.MultiplyChecked};
yield return new object[] {ExpressionType.Negate};
yield return new object[] {ExpressionType.UnaryPlus};
yield return new object[] {ExpressionType.NegateChecked};
yield return new object[] {ExpressionType.New};
yield return new object[] {ExpressionType.NewArrayInit};
yield return new object[] {ExpressionType.NewArrayBounds};
yield return new object[] {ExpressionType.Not};
yield return new object[] {ExpressionType.OrElse};
yield return new object[] {ExpressionType.Parameter};
yield return new object[] {ExpressionType.Quote};
yield return new object[] {ExpressionType.SubtractChecked};
yield return new object[] {ExpressionType.TypeAs};
yield return new object[] {ExpressionType.TypeIs};
yield return new object[] {ExpressionType.Assign};
yield return new object[] {ExpressionType.Block};
yield return new object[] {ExpressionType.DebugInfo};
yield return new object[] {ExpressionType.Decrement};
yield return new object[] {ExpressionType.Dynamic};
yield return new object[] {ExpressionType.Default};
yield return new object[] {ExpressionType.Goto};
yield return new object[] {ExpressionType.Increment};
yield return new object[] {ExpressionType.Index};
yield return new object[] {ExpressionType.Label};
yield return new object[] {ExpressionType.RuntimeVariables};
yield return new object[] {ExpressionType.Loop};
yield return new object[] {ExpressionType.Switch};
yield return new object[] {ExpressionType.Throw};
yield return new object[] {ExpressionType.Try};
yield return new object[] {ExpressionType.Unbox};
yield return new object[] {ExpressionType.AddAssignChecked};
yield return new object[] {ExpressionType.MultiplyAssignChecked};
yield return new object[] {ExpressionType.SubtractAssignChecked};
yield return new object[] {ExpressionType.PreIncrementAssign};
yield return new object[] {ExpressionType.PreDecrementAssign};
yield return new object[] {ExpressionType.PostIncrementAssign};
yield return new object[] {ExpressionType.PostDecrementAssign};
yield return new object[] {ExpressionType.TypeEqual};
yield return new object[] {ExpressionType.OnesComplement};
yield return new object[] {ExpressionType.IsTrue};
yield return new object[] {ExpressionType.IsFalse};
}
[Theory, MemberData(nameof(CrossJoinInt32))]
public void AddInt32(int x, int y)
{
dynamic dX = x;
dynamic dY = y;
Assert.Equal(unchecked(x + y), unchecked(dX + dY));
}
[Theory, MemberData(nameof(CrossJoinInt32))]
public void AddOvfInt32(int x, int y)
{
dynamic dX = x;
dynamic dY = y;
int result;
try
{
result = checked(x + y);
}
catch (OverflowException)
{
Assert.Throws<OverflowException>(() => checked(dX + dY));
return;
}
Assert.Equal(result, checked(dX + dY));
}
[Theory, MemberData(nameof(CrossJoinInt32))]
public void AndInt32(int x, int y)
{
dynamic dX = x;
dynamic dY = y;
Assert.Equal(x & y, dX & dY);
}
[Theory, MemberData(nameof(CrossJoinInt32))]
public void DivideInt32(int x, int y)
{
dynamic dX = x;
dynamic dY = y;
if (y == 0)
Assert.Throws<DivideByZeroException>(() => dX / dY);
else if (y == -1 && x == int.MinValue)
Assert.Throws<OverflowException>(() => dX / dY);
else
Assert.Equal(x / y, dX / dY);
}
[Theory, MemberData(nameof(CrossJoinInt32))]
public void EqualInt32(int x, int y)
{
dynamic dX = x;
dynamic dY = y;
Assert.Equal(x == y, dX == dY);
}
[Theory, MemberData(nameof(CrossJoinInt32))]
public void ExclusiveOrInt32(int x, int y)
{
dynamic dX = x;
dynamic dY = y;
Assert.Equal(x ^ y, dX ^ dY);
}
[Theory, MemberData(nameof(CrossJoinInt32))]
public void GreaterThanInt32(int x, int y)
{
dynamic dX = x;
dynamic dY = y;
Assert.Equal(x > y, dX > dY);
}
[Theory, MemberData(nameof(CrossJoinInt32))]
public void GreaterThanOrEqualInt32(int x, int y)
{
dynamic dX = x;
dynamic dY = y;
Assert.Equal(x >= y, dX >= dY);
}
[Theory, MemberData(nameof(CrossJoinInt32))]
public void LeftShiftInt32(int x, int y)
{
dynamic dX = x;
dynamic dY = y;
Assert.Equal(x << y, dX << dY);
}
[Theory, MemberData(nameof(CrossJoinInt32))]
public void LessThanInt32(int x, int y)
{
dynamic dX = x;
dynamic dY = y;
Assert.Equal(x < y, dX < dY);
}
[Theory, MemberData(nameof(CrossJoinInt32))]
public void LessThanOrEqualInt32(int x, int y)
{
dynamic dX = x;
dynamic dY = y;
Assert.Equal(x <= y, dX <= dY);
}
[Theory, MemberData(nameof(CrossJoinInt32))]
public void ModuloInt32(int x, int y)
{
dynamic dX = x;
dynamic dY = y;
if (y == 0)
Assert.Throws<DivideByZeroException>(() => dX % dY);
else if (y == -1 && x == int.MinValue)
Assert.Throws<OverflowException>(() => dX % dY);
else
Assert.Equal(x % y, dX % dY);
}
[Theory, MemberData(nameof(CrossJoinInt32))]
public void MultiplyInt32(int x, int y)
{
dynamic dX = x;
dynamic dY = y;
Assert.Equal(unchecked(x * y), unchecked(dX * dY));
}
[Theory, MemberData(nameof(CrossJoinInt32))]
public void MultiplyOvfInt32(int x, int y)
{
dynamic dX = x;
dynamic dY = y;
int result;
try
{
result = checked(x * y);
}
catch (OverflowException)
{
Assert.Throws<OverflowException>(() => checked(dX * dY));
return;
}
Assert.Equal(result, dX * dY);
}
[Theory, MemberData(nameof(CrossJoinInt32))]
public void NotEqualInt32(int x, int y)
{
dynamic dX = x;
dynamic dY = y;
Assert.Equal(x != y, dX != dY);
}
[Theory, MemberData(nameof(CrossJoinInt32))]
public void OrInt32(int x, int y)
{
dynamic dX = x;
dynamic dY = y;
Assert.Equal(x | y, dX | dY);
}
[Theory, MemberData(nameof(CrossJoinInt32))]
public void RightShiftInt32(int x, int y)
{
dynamic dX = x;
dynamic dY = y;
Assert.Equal(x >> y, dX >> dY);
}
[Theory, MemberData(nameof(CrossJoinInt32))]
public void SubtractInt32(int x, int y)
{
dynamic dX = x;
dynamic dY = y;
Assert.Equal(unchecked(x - y), unchecked(dX - dY));
}
[Theory, MemberData(nameof(CrossJoinInt32))]
public void SubtractOvfInt32(int x, int y)
{
dynamic dX = x;
dynamic dY = y;
int result;
try
{
result = checked(x - y);
}
catch (OverflowException)
{
Assert.Throws<OverflowException>(() => checked(dX - dY));
return;
}
Assert.Equal(result, checked(dX - dY));
}
[Theory, MemberData(nameof(CrossJoinInt32))]
public void AddInt32Assign(int x, int y)
{
dynamic dX = x;
dynamic dY = y;
unchecked
{
dX += dY;
Assert.Equal(x + y, dX);
}
}
[Theory, MemberData(nameof(CrossJoinInt32))]
public void AddOvfInt32Assign(int x, int y)
{
dynamic dX = x;
dynamic dY = y;
int result;
try
{
result = checked(x + y);
}
catch (OverflowException)
{
Assert.Throws<OverflowException>(() => checked(dX += dY));
return;
}
checked
{
dX += dY;
}
Assert.Equal(result, dX);
}
[Theory, MemberData(nameof(CrossJoinInt32))]
public void AndInt32Assign(int x, int y)
{
dynamic dX = x;
dynamic dY = y;
dX &= dY;
Assert.Equal(x & y, dX);
}
[Theory, MemberData(nameof(CrossJoinInt32))]
public void DivideInt32Assign(int x, int y)
{
dynamic dX = x;
dynamic dY = y;
if (y == 0)
Assert.Throws<DivideByZeroException>(() => dX /= dY);
else if (y == -1 && x == int.MinValue)
Assert.Throws<OverflowException>(() => dX /= dY);
else
{
dX /= dY;
Assert.Equal(x / y, dX);
}
}
[Theory, MemberData(nameof(CrossJoinInt32))]
public void ExclusiveOrInt32Assign(int x, int y)
{
dynamic dX = x;
dynamic dY = y;
dX ^= dY;
Assert.Equal(x ^ y, dX);
}
[Theory, MemberData(nameof(CrossJoinInt32))]
public void LeftShiftInt32Assign(int x, int y)
{
dynamic dX = x;
dynamic dY = y;
dX <<= dY;
Assert.Equal(x << y, dX);
}
[Theory, MemberData(nameof(CrossJoinInt32))]
public void ModuloInt32Assign(int x, int y)
{
dynamic dX = x;
dynamic dY = y;
if (y == 0)
Assert.Throws<DivideByZeroException>(() => dX %= dY);
else if (y == -1 && x == int.MinValue)
Assert.Throws<OverflowException>(() => dX %= dY);
else
{
dX %= dY;
Assert.Equal(x % y, dX);
}
}
[Theory, MemberData(nameof(CrossJoinInt32))]
public void MultiplyInt32Assign(int x, int y)
{
dynamic dX = x;
dynamic dY = y;
unchecked
{
dX *= dY;
Assert.Equal(x * y, dX);
}
}
[Theory, MemberData(nameof(CrossJoinInt32))]
public void MultiplyOvfInt32Assign(int x, int y)
{
dynamic dX = x;
dynamic dY = y;
int result;
try
{
result = checked(x * y);
}
catch (OverflowException)
{
Assert.Throws<OverflowException>(() => checked(dX *= dY));
return;
}
dX *= dY;
Assert.Equal(result, dX);
}
[Theory, MemberData(nameof(CrossJoinInt32))]
public void OrInt32Assign(int x, int y)
{
dynamic dX = x;
dynamic dY = y;
dX |= dY;
Assert.Equal(x | y, dX);
}
[Theory, MemberData(nameof(CrossJoinInt32))]
public void RightShiftInt32Assign(int x, int y)
{
dynamic dX = x;
dynamic dY = y;
dX >>= dY;
Assert.Equal(x >> y, dX);
}
[Theory, MemberData(nameof(CrossJoinInt32))]
public void SubtractInt32Assign(int x, int y)
{
dynamic dX = x;
dynamic dY = y;
unchecked
{
dX -= dY;
Assert.Equal(x - y, dX);
}
}
[Theory, MemberData(nameof(CrossJoinInt32))]
public void SubtractOvfInt32Assign(int x, int y)
{
dynamic dX = x;
dynamic dY = y;
int result;
try
{
result = checked(x - y);
}
catch (OverflowException)
{
Assert.Throws<OverflowException>(() => checked(dX -= dY));
return;
}
checked
{
dX -= dY;
}
Assert.Equal(result, dX);
}
[Theory, MemberData(nameof(CrossJoinDouble))]
public void AddDouble(double x, double y)
{
dynamic dX = x;
dynamic dY = y;
Assert.Equal(x + y, dX + dY);
}
[Theory, MemberData(nameof(CrossJoinDouble))]
public void DivideDouble(double x, double y)
{
dynamic dX = x;
dynamic dY = y;
Assert.Equal(x / y, dX / dY);
}
[Theory, MemberData(nameof(CrossJoinDouble))]
public void EqualDouble(double x, double y)
{
dynamic dX = x;
dynamic dY = y;
Assert.Equal(x == y, dX == dY);
}
[Theory, MemberData(nameof(CrossJoinDouble))]
public void GreaterThanDouble(double x, double y)
{
dynamic dX = x;
dynamic dY = y;
Assert.Equal(x > y, dX > dY);
}
[Theory, MemberData(nameof(CrossJoinDouble))]
public void GreaterThanOrEqualDouble(double x, double y)
{
dynamic dX = x;
dynamic dY = y;
Assert.Equal(x >= y, dX >= dY);
}
[Theory, MemberData(nameof(CrossJoinDouble))]
public void LessThanDouble(double x, double y)
{
dynamic dX = x;
dynamic dY = y;
Assert.Equal(x < y, dX < dY);
}
[Theory, MemberData(nameof(CrossJoinDouble))]
public void LessThanOrEqualDouble(double x, double y)
{
dynamic dX = x;
dynamic dY = y;
Assert.Equal(x <= y, dX <= dY);
}
[Theory, MemberData(nameof(CrossJoinDouble))]
public void ModuloDouble(double x, double y)
{
dynamic dX = x;
dynamic dY = y;
Assert.Equal(x % y, dX % dY);
}
[Theory, MemberData(nameof(CrossJoinDouble))]
public void MultiplyDouble(double x, double y)
{
dynamic dX = x;
dynamic dY = y;
Assert.Equal(x * y, dX * dY);
}
[Theory, MemberData(nameof(CrossJoinDouble))]
public void NotEqualDouble(double x, double y)
{
dynamic dX = x;
dynamic dY = y;
Assert.Equal(x != y, dX != dY);
}
[Theory, MemberData(nameof(CrossJoinDouble))]
public void SubtractDouble(double x, double y)
{
dynamic dX = x;
dynamic dY = y;
Assert.Equal(x - y, dX - dY);
}
[Theory, MemberData(nameof(CrossJoinDouble))]
public void AddDoubleAssign(double x, double y)
{
dynamic dX = x;
dynamic dY = y;
dX += dY;
Assert.Equal(x + y, dX);
}
[Theory, MemberData(nameof(CrossJoinDouble))]
public void DivideDoubleAssign(double x, double y)
{
dynamic dX = x;
dynamic dY = y;
dX /= dY;
Assert.Equal(x / y, dX);
}
[Theory, MemberData(nameof(CrossJoinDouble))]
public void ModuloDoubleAssign(double x, double y)
{
dynamic dX = x;
dynamic dY = y;
dX %= dY;
Assert.Equal(x % y, dX);
}
[Theory, MemberData(nameof(CrossJoinDouble))]
public void MultiplyDoubleAssign(double x, double y)
{
dynamic dX = x;
dynamic dY = y;
dX *= dY;
Assert.Equal(x * y, dX);
}
[Theory, MemberData(nameof(CrossJoinDouble))]
public void SubtractDoubleAssign(double x, double y)
{
dynamic dX = x;
dynamic dY = y;
dX -= dY;
Assert.Equal(x - y, dX);
}
[Theory, MemberData(nameof(NonBinaryExpressionTypes))]
public void NonBinaryOperations(ExpressionType type)
{
AssertExtensions.Throws<ArgumentException>("operation", () => new MinimumOverrideBinaryOperationBinder(type));
}
[Theory, MemberData(nameof(BinaryExpressionTypes))]
public void ReturnType(ExpressionType type)
{
Assert.Equal(typeof(object), new MinimumOverrideBinaryOperationBinder(type).ReturnType);
}
[Theory, MemberData(nameof(BinaryExpressionTypes))]
public void ExpressionTypeMatches(ExpressionType type)
{
Assert.Equal(type, new MinimumOverrideBinaryOperationBinder(type).Operation);
}
[Fact]
public void NullTarget()
{
var binder = new MinimumOverrideBinaryOperationBinder(ExpressionType.Add);
var arg = new DynamicMetaObject(Expression.Parameter(typeof(object), null), BindingRestrictions.Empty);
AssertExtensions.Throws<ArgumentNullException>("target", () => binder.Bind(null, new[] {arg}));
}
[Fact]
public void NullArgumentArrayPassed()
{
var target = new DynamicMetaObject(Expression.Parameter(typeof(object), null), BindingRestrictions.Empty);
var binder = new MinimumOverrideBinaryOperationBinder(ExpressionType.Add);
AssertExtensions.Throws<ArgumentNullException>("args", () => binder.Bind(target, null));
}
[Fact]
public void NoArgumentsPassed()
{
var target = new DynamicMetaObject(Expression.Parameter(typeof(object), null), BindingRestrictions.Empty);
var binder = new MinimumOverrideBinaryOperationBinder(ExpressionType.Add);
AssertExtensions.Throws<ArgumentException>("args", () => binder.Bind(target, Array.Empty<DynamicMetaObject>()));
}
[Fact]
public void TooManyArgumentArrayPassed()
{
var target = new DynamicMetaObject(Expression.Parameter(typeof(object), null), BindingRestrictions.Empty);
var binder = new MinimumOverrideBinaryOperationBinder(ExpressionType.Add);
var arg0 = new DynamicMetaObject(Expression.Parameter(typeof(object), null), BindingRestrictions.Empty);
var arg1 = new DynamicMetaObject(Expression.Parameter(typeof(object), null), BindingRestrictions.Empty);
AssertExtensions.Throws<ArgumentException>("args", () => binder.Bind(target, new[] {arg0, arg1}));
}
[Fact]
public void SingleNullArgumentPassed()
{
var target = new DynamicMetaObject(Expression.Parameter(typeof(object), null), BindingRestrictions.Empty);
var binder = new MinimumOverrideBinaryOperationBinder(ExpressionType.Add);
AssertExtensions.Throws<ArgumentNullException>("args", () => binder.Bind(target, new DynamicMetaObject[1]));
}
[Fact]
public void InvalidOperationForType()
{
dynamic dX = "23";
dynamic dY = "49";
Assert.Throws<RuntimeBinderException>(() => dX * dY);
dX = 23;
dY = 49;
Assert.Throws<RuntimeBinderException>(() => dX && dY);
}
[Fact]
public void LiteralDoubleNaN()
{
dynamic d = double.NaN;
Assert.False(d == double.NaN);
Assert.True(d != double.NaN);
d = 3.0;
Assert.True(double.IsNaN(d + double.NaN));
}
[Fact]
public void LiteralSingleNaN()
{
dynamic d = float.NaN;
Assert.False(d == float.NaN);
Assert.True(d != float.NaN);
d = 3.0F;
Assert.True(float.IsNaN(d + float.NaN));
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public void BinaryCallSiteBinder_DynamicExpression(bool useInterpreter)
{
DynamicExpression expression = DynamicExpression.Dynamic(
new BinaryCallSiteBinder(),
typeof(object),
Expression.Constant(40, typeof(object)),
Expression.Constant(2, typeof(object)));
Func<object> func = Expression.Lambda<Func<object>>(expression).Compile(useInterpreter);
Assert.Equal("42", func().ToString());
}
private class BinaryCallSiteBinder : BinaryOperationBinder
{
public BinaryCallSiteBinder() : base(ExpressionType.Add) {}
public override DynamicMetaObject FallbackBinaryOperation(DynamicMetaObject target, DynamicMetaObject arg, DynamicMetaObject errorSuggestion)
{
return new DynamicMetaObject(
Expression.Convert(
Expression.Add(
Expression.Convert(target.Expression, typeof(int)),
Expression.Convert(arg.Expression, typeof(int))
), typeof(object)),
BindingRestrictions.GetTypeRestriction(target.Expression, typeof(int)).Merge(
BindingRestrictions.GetTypeRestriction(arg.Expression, typeof(int))
));
}
}
}
}
| |
//
// 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 Mono.Collections.Generic;
using SR = System.Reflection;
using Mono.Cecil.Metadata;
namespace Mono.Cecil {
#if !READ_ONLY
public interface IMetadataImporterProvider {
IMetadataImporter GetMetadataImporter (ModuleDefinition module);
}
public interface IMetadataImporter {
TypeReference ImportReference (TypeReference type, IGenericParameterProvider context);
FieldReference ImportReference (FieldReference field, IGenericParameterProvider context);
MethodReference ImportReference (MethodReference method, IGenericParameterProvider context);
}
#if !CF
public interface IReflectionImporterProvider {
IReflectionImporter GetReflectionImporter (ModuleDefinition module);
}
public interface IReflectionImporter {
TypeReference ImportReference (Type type, IGenericParameterProvider context);
FieldReference ImportReference (SR.FieldInfo field, IGenericParameterProvider context);
MethodReference ImportReference (SR.MethodBase method, IGenericParameterProvider context);
}
#endif
struct ImportGenericContext {
Collection<IGenericParameterProvider> stack;
public bool IsEmpty { get { return stack == null; } }
public ImportGenericContext (IGenericParameterProvider provider)
{
if (provider == null)
throw new ArgumentNullException ("provider");
stack = null;
Push (provider);
}
public void Push (IGenericParameterProvider provider)
{
if (stack == null)
stack = new Collection<IGenericParameterProvider> (1) { provider };
else
stack.Add (provider);
}
public void Pop ()
{
stack.RemoveAt (stack.Count - 1);
}
public TypeReference MethodParameter (string declTypeFullName, string method, int position)
{
for (int i = stack.Count - 1; i >= 0; i--) {
var candidate = stack [i] as MethodReference;
if (candidate == null)
continue;
if (method != candidate.Name || declTypeFullName != candidate.DeclaringType.FullName)
continue;
return candidate.GenericParameters [position];
}
throw new InvalidOperationException ();
}
public TypeReference TypeParameter (string type, int position)
{
for (int i = stack.Count - 1; i >= 0; i--) {
var candidate = GenericTypeFor (stack [i]);
if (candidate.FullName != type)
continue;
return candidate.GenericParameters [position];
}
throw new InvalidOperationException ();
}
static TypeReference GenericTypeFor (IGenericParameterProvider context)
{
var type = context as TypeReference;
if (type != null)
return type.GetElementType ();
var method = context as MethodReference;
if (method != null)
return method.DeclaringType.GetElementType ();
throw new InvalidOperationException ();
}
public static ImportGenericContext For (IGenericParameterProvider context)
{
return context != null ? new ImportGenericContext (context) : default (ImportGenericContext);
}
}
#if !CF
public class ReflectionImporter : IReflectionImporter {
readonly ModuleDefinition module;
public ReflectionImporter (ModuleDefinition module)
{
Mixin.CheckModule (module);
this.module = module;
}
enum ImportGenericKind {
Definition,
Open,
}
static readonly Dictionary<Type, ElementType> type_etype_mapping = new Dictionary<Type, ElementType> (18) {
{ typeof (void), ElementType.Void },
{ typeof (bool), ElementType.Boolean },
{ typeof (char), ElementType.Char },
{ typeof (sbyte), ElementType.I1 },
{ typeof (byte), ElementType.U1 },
{ typeof (short), ElementType.I2 },
{ typeof (ushort), ElementType.U2 },
{ typeof (int), ElementType.I4 },
{ typeof (uint), ElementType.U4 },
{ typeof (long), ElementType.I8 },
{ typeof (ulong), ElementType.U8 },
{ typeof (float), ElementType.R4 },
{ typeof (double), ElementType.R8 },
{ typeof (string), ElementType.String },
{ typeof (TypedReference), ElementType.TypedByRef },
{ typeof (IntPtr), ElementType.I },
{ typeof (UIntPtr), ElementType.U },
{ typeof (object), ElementType.Object },
};
TypeReference ImportType (Type type, ImportGenericContext context)
{
return ImportType (type, context, ImportGenericKind.Open);
}
TypeReference ImportType (Type type, ImportGenericContext context, ImportGenericKind import_kind)
{
if (IsTypeSpecification (type) || ImportOpenGenericType (type, import_kind))
return ImportTypeSpecification (type, context);
var reference = new TypeReference (
string.Empty,
type.Name,
module,
ImportScope (type.Assembly),
type.IsValueType);
reference.etype = ImportElementType (type);
if (IsNestedType (type))
reference.DeclaringType = ImportType (type.DeclaringType, context, import_kind);
else
reference.Namespace = type.Namespace ?? string.Empty;
if (type.IsGenericType)
ImportGenericParameters (reference, type.GetGenericArguments ());
return reference;
}
static bool ImportOpenGenericType (Type type, ImportGenericKind import_kind)
{
return type.IsGenericType && type.IsGenericTypeDefinition && import_kind == ImportGenericKind.Open;
}
static bool ImportOpenGenericMethod (SR.MethodBase method, ImportGenericKind import_kind)
{
return method.IsGenericMethod && method.IsGenericMethodDefinition && import_kind == ImportGenericKind.Open;
}
static bool IsNestedType (Type type)
{
#if !SILVERLIGHT
return type.IsNested;
#else
return type.DeclaringType != null;
#endif
}
TypeReference ImportTypeSpecification (Type type, ImportGenericContext context)
{
if (type.IsByRef)
return new ByReferenceType (ImportType (type.GetElementType (), context));
if (type.IsPointer)
return new PointerType (ImportType (type.GetElementType (), context));
if (type.IsArray)
return new ArrayType (ImportType (type.GetElementType (), context), type.GetArrayRank ());
if (type.IsGenericType)
return ImportGenericInstance (type, context);
if (type.IsGenericParameter)
return ImportGenericParameter (type, context);
throw new NotSupportedException (type.FullName);
}
static TypeReference ImportGenericParameter (Type type, ImportGenericContext context)
{
if (context.IsEmpty)
throw new InvalidOperationException ();
if (type.DeclaringMethod != null)
{
return context.MethodParameter (type.DeclaringType.FullName, type.DeclaringMethod.Name, type.GenericParameterPosition);
}
if (type.DeclaringType != null)
{
return context.TypeParameter (NormalizedFullName (type.DeclaringType), type.GenericParameterPosition);
}
throw new InvalidOperationException();
}
private static string NormalizedFullName (Type type)
{
if (IsNestedType (type))
return NormalizedFullName (type.DeclaringType) + "/" + type.Name;
return type.FullName;
}
TypeReference ImportGenericInstance (Type type, ImportGenericContext context)
{
var element_type = ImportType (type.GetGenericTypeDefinition (), context, ImportGenericKind.Definition);
var instance = new GenericInstanceType (element_type);
var arguments = type.GetGenericArguments ();
var instance_arguments = instance.GenericArguments;
context.Push (element_type);
try {
for (int i = 0; i < arguments.Length; i++)
instance_arguments.Add (ImportType (arguments [i], context));
return instance;
} finally {
context.Pop ();
}
}
static bool IsTypeSpecification (Type type)
{
return type.HasElementType
|| IsGenericInstance (type)
|| type.IsGenericParameter;
}
static bool IsGenericInstance (Type type)
{
return type.IsGenericType && !type.IsGenericTypeDefinition;
}
static ElementType ImportElementType (Type type)
{
ElementType etype;
if (!type_etype_mapping.TryGetValue (type, out etype))
return ElementType.None;
return etype;
}
AssemblyNameReference ImportScope (SR.Assembly assembly)
{
AssemblyNameReference scope;
#if !SILVERLIGHT
var name = assembly.GetName ();
if (TryGetAssemblyNameReference (name, out scope))
return scope;
scope = new AssemblyNameReference (name.Name, name.Version) {
Culture = name.CultureInfo.Name,
PublicKeyToken = name.GetPublicKeyToken (),
HashAlgorithm = (AssemblyHashAlgorithm) name.HashAlgorithm,
};
module.AssemblyReferences.Add (scope);
return scope;
#else
var name = AssemblyNameReference.Parse (assembly.FullName);
if (module.TryGetAssemblyNameReference (name, out scope))
return scope;
module.AssemblyReferences.Add (name);
return name;
#endif
}
#if !SILVERLIGHT
bool TryGetAssemblyNameReference (SR.AssemblyName name, out AssemblyNameReference assembly_reference)
{
var references = module.AssemblyReferences;
for (int i = 0; i < references.Count; i++) {
var reference = references [i];
if (name.FullName != reference.FullName) // TODO compare field by field
continue;
assembly_reference = reference;
return true;
}
assembly_reference = null;
return false;
}
#endif
FieldReference ImportField (SR.FieldInfo field, ImportGenericContext context)
{
var declaring_type = ImportType (field.DeclaringType, context);
if (IsGenericInstance (field.DeclaringType))
field = ResolveFieldDefinition (field);
context.Push (declaring_type);
try {
return new FieldReference {
Name = field.Name,
DeclaringType = declaring_type,
FieldType = ImportType (field.FieldType, context),
};
} finally {
context.Pop ();
}
}
static SR.FieldInfo ResolveFieldDefinition (SR.FieldInfo field)
{
#if !SILVERLIGHT
return field.Module.ResolveField (field.MetadataToken);
#else
return field.DeclaringType.GetGenericTypeDefinition ().GetField (field.Name,
SR.BindingFlags.Public
| SR.BindingFlags.NonPublic
| (field.IsStatic ? SR.BindingFlags.Static : SR.BindingFlags.Instance));
#endif
}
MethodReference ImportMethod (SR.MethodBase method, ImportGenericContext context, ImportGenericKind import_kind)
{
if (IsMethodSpecification (method) || ImportOpenGenericMethod (method, import_kind))
return ImportMethodSpecification (method, context);
var declaring_type = ImportType (method.DeclaringType, context);
if (IsGenericInstance (method.DeclaringType))
method = method.Module.ResolveMethod (method.MetadataToken);
var reference = new MethodReference {
Name = method.Name,
HasThis = HasCallingConvention (method, SR.CallingConventions.HasThis),
ExplicitThis = HasCallingConvention (method, SR.CallingConventions.ExplicitThis),
DeclaringType = ImportType (method.DeclaringType, context, ImportGenericKind.Definition),
};
if (HasCallingConvention (method, SR.CallingConventions.VarArgs))
reference.CallingConvention &= MethodCallingConvention.VarArg;
if (method.IsGenericMethod)
ImportGenericParameters (reference, method.GetGenericArguments ());
context.Push (reference);
try {
var method_info = method as SR.MethodInfo;
reference.ReturnType = method_info != null
? ImportType (method_info.ReturnType, context)
: ImportType (typeof (void), default (ImportGenericContext));
var parameters = method.GetParameters ();
var reference_parameters = reference.Parameters;
for (int i = 0; i < parameters.Length; i++)
reference_parameters.Add (
new ParameterDefinition (ImportType (parameters [i].ParameterType, context)));
reference.DeclaringType = declaring_type;
return reference;
} finally {
context.Pop ();
}
}
static void ImportGenericParameters (IGenericParameterProvider provider, Type [] arguments)
{
var provider_parameters = provider.GenericParameters;
for (int i = 0; i < arguments.Length; i++)
provider_parameters.Add (new GenericParameter (arguments [i].Name, provider));
}
static bool IsMethodSpecification (SR.MethodBase method)
{
return method.IsGenericMethod && !method.IsGenericMethodDefinition;
}
MethodReference ImportMethodSpecification (SR.MethodBase method, ImportGenericContext context)
{
var method_info = method as SR.MethodInfo;
if (method_info == null)
throw new InvalidOperationException ();
var element_method = ImportMethod (method_info.GetGenericMethodDefinition (), context, ImportGenericKind.Definition);
var instance = new GenericInstanceMethod (element_method);
var arguments = method.GetGenericArguments ();
var instance_arguments = instance.GenericArguments;
context.Push (element_method);
try {
for (int i = 0; i < arguments.Length; i++)
instance_arguments.Add (ImportType (arguments [i], context));
return instance;
} finally {
context.Pop ();
}
}
static bool HasCallingConvention (SR.MethodBase method, SR.CallingConventions conventions)
{
return (method.CallingConvention & conventions) != 0;
}
public virtual TypeReference ImportReference (Type type, IGenericParameterProvider context)
{
Mixin.CheckType (type);
return ImportType (
type,
ImportGenericContext.For (context),
context != null ? ImportGenericKind.Open : ImportGenericKind.Definition);
}
public virtual FieldReference ImportReference (SR.FieldInfo field, IGenericParameterProvider context)
{
Mixin.CheckField (field);
return ImportField (field, ImportGenericContext.For (context));
}
public virtual MethodReference ImportReference (SR.MethodBase method, IGenericParameterProvider context)
{
Mixin.CheckMethod (method);
return ImportMethod (method,
ImportGenericContext.For (context),
context != null ? ImportGenericKind.Open : ImportGenericKind.Definition);
}
}
#endif
public class MetadataImporter : IMetadataImporter {
readonly Dictionary<TypeRefKey, TypeReference> cache = new Dictionary<TypeRefKey, TypeReference>();
readonly ModuleDefinition module;
public MetadataImporter (ModuleDefinition module)
{
Mixin.CheckModule (module);
this.module = module;
}
struct TypeRefKey : IEquatable<TypeRefKey>
{
string fullname;
string assembly;
bool isValueType;
public static TypeRefKey From(TypeReference r)
{
return new TypeRefKey { fullname = r.FullName, assembly = r.Scope.ToString(), isValueType = r.IsValueType };
}
public override int GetHashCode()
{
return fullname.GetHashCode() + assembly.GetHashCode() + (isValueType ? 1 : 0);
}
public bool Equals(TypeRefKey other)
{
return other.fullname == fullname && other.assembly == assembly && other.isValueType == isValueType;
}
}
TypeReference ImportType (TypeReference type, ImportGenericContext context)
{
if (type.IsTypeSpecification ())
return ImportTypeSpecification (type, context);
var reference = default(TypeReference);
var key = TypeRefKey.From(type);
if (cache.TryGetValue(key, out reference))
{
// Cecil only fills TypeRef GenericParameters if used ( bug ?)
// Now that we cache them, we need to make sure the cached version has all of the needed ones
if (type.HasGenericParameters && reference.GenericParameters.Count != type.GenericParameters.Count)
{
for (int i = reference.GenericParameters.Count - 1; i < type.GenericParameters.Count; i++)
reference.GenericParameters.Add(new GenericParameter(reference));
}
return reference;
}
reference = new TypeReference (
type.Namespace,
type.Name,
module,
ImportScope (type.Scope),
type.IsValueType);
MetadataSystem.TryProcessPrimitiveTypeReference (reference);
if (type.IsNested)
reference.DeclaringType = ImportType (type.DeclaringType, context);
if (type.HasGenericParameters)
ImportGenericParameters (reference, type);
cache.Add(key, reference);
return reference;
}
IMetadataScope ImportScope (IMetadataScope scope)
{
switch (scope.MetadataScopeType) {
case MetadataScopeType.AssemblyNameReference:
return ImportAssemblyName ((AssemblyNameReference) scope);
case MetadataScopeType.ModuleDefinition:
if (scope == module) return scope;
return ImportAssemblyName (((ModuleDefinition) scope).Assembly.Name);
case MetadataScopeType.ModuleReference:
throw new NotImplementedException ();
}
throw new NotSupportedException ();
}
AssemblyNameReference ImportAssemblyName (AssemblyNameReference name)
{
AssemblyNameReference reference;
if (module.TryGetAssemblyNameReference (name, out reference))
return reference;
reference = new AssemblyNameReference (name.Name, name.Version) {
Culture = name.Culture,
HashAlgorithm = name.HashAlgorithm,
IsRetargetable = name.IsRetargetable,
IsWindowsRuntime = name.IsWindowsRuntime
};
var pk_token = !name.PublicKeyToken.IsNullOrEmpty ()
? new byte [name.PublicKeyToken.Length]
: Empty<byte>.Array;
if (pk_token.Length > 0)
Buffer.BlockCopy (name.PublicKeyToken, 0, pk_token, 0, pk_token.Length);
reference.PublicKeyToken = pk_token;
module.AssemblyReferences.Add (reference);
return reference;
}
static void ImportGenericParameters (IGenericParameterProvider imported, IGenericParameterProvider original)
{
var parameters = original.GenericParameters;
var imported_parameters = imported.GenericParameters;
for (int i = 0; i < parameters.Count; i++)
imported_parameters.Add (new GenericParameter (parameters [i].Name, imported));
}
TypeReference ImportTypeSpecification (TypeReference type, ImportGenericContext context)
{
switch (type.etype) {
case ElementType.SzArray:
var vector = (ArrayType) type;
return new ArrayType (ImportType (vector.ElementType, context));
case ElementType.Ptr:
var pointer = (PointerType) type;
return new PointerType (ImportType (pointer.ElementType, context));
case ElementType.ByRef:
var byref = (ByReferenceType) type;
return new ByReferenceType (ImportType (byref.ElementType, context));
case ElementType.Pinned:
var pinned = (PinnedType) type;
return new PinnedType (ImportType (pinned.ElementType, context));
case ElementType.Sentinel:
var sentinel = (SentinelType) type;
return new SentinelType (ImportType (sentinel.ElementType, context));
case ElementType.FnPtr:
var fnptr = (FunctionPointerType) type;
var imported_fnptr = new FunctionPointerType () {
HasThis = fnptr.HasThis,
ExplicitThis = fnptr.ExplicitThis,
CallingConvention = fnptr.CallingConvention,
ReturnType = ImportType (fnptr.ReturnType, context),
};
if (!fnptr.HasParameters)
return imported_fnptr;
for (int i = 0; i < fnptr.Parameters.Count; i++)
imported_fnptr.Parameters.Add (new ParameterDefinition (
ImportType (fnptr.Parameters [i].ParameterType, context)));
return imported_fnptr;
case ElementType.CModOpt:
var modopt = (OptionalModifierType) type;
return new OptionalModifierType (
ImportType (modopt.ModifierType, context),
ImportType (modopt.ElementType, context));
case ElementType.CModReqD:
var modreq = (RequiredModifierType) type;
return new RequiredModifierType (
ImportType (modreq.ModifierType, context),
ImportType (modreq.ElementType, context));
case ElementType.Array:
var array = (ArrayType) type;
var imported_array = new ArrayType (ImportType (array.ElementType, context));
if (array.IsVector)
return imported_array;
var dimensions = array.Dimensions;
var imported_dimensions = imported_array.Dimensions;
imported_dimensions.Clear ();
for (int i = 0; i < dimensions.Count; i++) {
var dimension = dimensions [i];
imported_dimensions.Add (new ArrayDimension (dimension.LowerBound, dimension.UpperBound));
}
return imported_array;
case ElementType.GenericInst:
var instance = (GenericInstanceType) type;
var element_type = ImportType (instance.ElementType, context);
var imported_instance = new GenericInstanceType (element_type);
var arguments = instance.GenericArguments;
var imported_arguments = imported_instance.GenericArguments;
for (int i = 0; i < arguments.Count; i++)
imported_arguments.Add (ImportType (arguments [i], context));
return imported_instance;
case ElementType.Var:
var var_parameter = (GenericParameter) type;
if (var_parameter.DeclaringType == null)
throw new InvalidOperationException ();
return context.TypeParameter (var_parameter.DeclaringType.FullName, var_parameter.Position);
case ElementType.MVar:
var mvar_parameter = (GenericParameter) type;
if (mvar_parameter.DeclaringMethod == null)
throw new InvalidOperationException ();
return context.MethodParameter (((MethodReference)mvar_parameter.Owner).DeclaringType.FullName, mvar_parameter.DeclaringMethod.Name, mvar_parameter.Position);
}
throw new NotSupportedException (type.etype.ToString ());
}
FieldReference ImportField (FieldReference field, ImportGenericContext context)
{
var declaring_type = ImportType (field.DeclaringType, context);
context.Push (declaring_type);
try {
return new FieldReference {
Name = field.Name,
DeclaringType = declaring_type,
FieldType = ImportType (field.FieldType, context),
};
} finally {
context.Pop ();
}
}
MethodReference ImportMethod (MethodReference method, ImportGenericContext context)
{
if (method.IsGenericInstance)
return ImportMethodSpecification (method, context);
var declaring_type = ImportType (method.DeclaringType, context);
var reference = new MethodReference {
Name = method.Name,
HasThis = method.HasThis,
ExplicitThis = method.ExplicitThis,
DeclaringType = declaring_type,
CallingConvention = method.CallingConvention,
};
if (method.HasGenericParameters)
ImportGenericParameters (reference, method);
context.Push (reference);
try {
reference.ReturnType = ImportType (method.ReturnType, context);
if (!method.HasParameters)
return reference;
var parameters = method.Parameters;
var reference_parameters = reference.parameters = new ParameterDefinitionCollection (reference, parameters.Count);
for (int i = 0; i < parameters.Count; i++)
reference_parameters.Add (
new ParameterDefinition (ImportType (parameters [i].ParameterType, context)));
return reference;
} finally {
context.Pop();
}
}
MethodSpecification ImportMethodSpecification (MethodReference method, ImportGenericContext context)
{
if (!method.IsGenericInstance)
throw new NotSupportedException ();
var instance = (GenericInstanceMethod) method;
var element_method = ImportMethod (instance.ElementMethod, context);
var imported_instance = new GenericInstanceMethod (element_method);
var arguments = instance.GenericArguments;
var imported_arguments = imported_instance.GenericArguments;
for (int i = 0; i < arguments.Count; i++)
imported_arguments.Add (ImportType (arguments [i], context));
return imported_instance;
}
public virtual TypeReference ImportReference (TypeReference type, IGenericParameterProvider context)
{
Mixin.CheckType (type);
return ImportType (type, ImportGenericContext.For (context));
}
public virtual FieldReference ImportReference (FieldReference field, IGenericParameterProvider context)
{
Mixin.CheckField (field);
return ImportField (field, ImportGenericContext.For (context));
}
public virtual MethodReference ImportReference (MethodReference method, IGenericParameterProvider context)
{
Mixin.CheckMethod (method);
return ImportMethod (method, ImportGenericContext.For (context));
}
}
static partial class Mixin {
public static void CheckModule (ModuleDefinition module)
{
if (module == null)
throw new ArgumentNullException ("module");
}
public static bool TryGetAssemblyNameReference (this ModuleDefinition module, AssemblyNameReference name_reference, out AssemblyNameReference assembly_reference)
{
var references = module.AssemblyReferences;
for (int i = 0; i < references.Count; i++) {
var reference = references [i];
if (!Equals (name_reference, reference))
continue;
assembly_reference = reference;
return true;
}
assembly_reference = null;
return false;
}
private static bool Equals (byte [] a, byte [] b)
{
if (ReferenceEquals (a, b))
return true;
if (a == null)
return false;
if (a.Length != b.Length)
return false;
for (int i = 0; i < a.Length; i++)
if (a [i] != b [i])
return false;
return true;
}
private static bool Equals<T> (T a, T b) where T : class, IEquatable<T>
{
if (ReferenceEquals (a, b))
return true;
if (a == null)
return false;
return a.Equals (b);
}
private static bool Equals (AssemblyNameReference a, AssemblyNameReference b)
{
if (ReferenceEquals (a, b))
return true;
if (a.Name != b.Name)
return false;
if (!Equals (a.Version, b.Version))
return false;
if (a.Culture != b.Culture)
return false;
if (!Equals (a.PublicKeyToken, b.PublicKeyToken))
return false;
return true;
}
}
#endif
}
| |
namespace XenAdmin.Wizards.NewNetworkWizard_Pages
{
partial class NetWDetails
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(NetWDetails));
this.panel1 = new System.Windows.Forms.Panel();
this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel();
this.infoMtuPanel = new System.Windows.Forms.Panel();
this.infoMtuMessage = new System.Windows.Forms.Label();
this.pictureBox2 = new System.Windows.Forms.PictureBox();
this.labelNIC = new System.Windows.Forms.Label();
this.labelVLAN = new System.Windows.Forms.Label();
this.lblNicHelp = new System.Windows.Forms.Label();
this.numericUpDownVLAN = new System.Windows.Forms.NumericUpDown();
this.comboBoxNICList = new System.Windows.Forms.ComboBox();
this.labelMTU = new System.Windows.Forms.Label();
this.numericUpDownMTU = new System.Windows.Forms.NumericUpDown();
this.panelVLANInfo = new System.Windows.Forms.Panel();
this.labelVlanError = new System.Windows.Forms.Label();
this.labelVLAN0Info = new System.Windows.Forms.Label();
this.checkBoxAutomatic = new System.Windows.Forms.CheckBox();
this.checkBoxSriov = new System.Windows.Forms.CheckBox();
this.panel1.SuspendLayout();
this.tableLayoutPanel1.SuspendLayout();
this.infoMtuPanel.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBox2)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.numericUpDownVLAN)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.numericUpDownMTU)).BeginInit();
this.panelVLANInfo.SuspendLayout();
this.SuspendLayout();
//
// panel1
//
resources.ApplyResources(this.panel1, "panel1");
this.panel1.BackColor = System.Drawing.SystemColors.Control;
this.panel1.Controls.Add(this.tableLayoutPanel1);
this.panel1.Name = "panel1";
//
// tableLayoutPanel1
//
resources.ApplyResources(this.tableLayoutPanel1, "tableLayoutPanel1");
this.tableLayoutPanel1.Controls.Add(this.infoMtuPanel, 2, 3);
this.tableLayoutPanel1.Controls.Add(this.labelNIC, 0, 1);
this.tableLayoutPanel1.Controls.Add(this.labelVLAN, 0, 2);
this.tableLayoutPanel1.Controls.Add(this.lblNicHelp, 0, 0);
this.tableLayoutPanel1.Controls.Add(this.numericUpDownVLAN, 1, 2);
this.tableLayoutPanel1.Controls.Add(this.comboBoxNICList, 1, 1);
this.tableLayoutPanel1.Controls.Add(this.labelMTU, 0, 3);
this.tableLayoutPanel1.Controls.Add(this.numericUpDownMTU, 1, 3);
this.tableLayoutPanel1.Controls.Add(this.panelVLANInfo, 2, 2);
this.tableLayoutPanel1.Controls.Add(this.checkBoxAutomatic, 0, 5);
this.tableLayoutPanel1.Controls.Add(this.checkBoxSriov, 0, 4);
this.tableLayoutPanel1.Name = "tableLayoutPanel1";
//
// infoMtuPanel
//
resources.ApplyResources(this.infoMtuPanel, "infoMtuPanel");
this.tableLayoutPanel1.SetColumnSpan(this.infoMtuPanel, 2);
this.infoMtuPanel.Controls.Add(this.infoMtuMessage);
this.infoMtuPanel.Controls.Add(this.pictureBox2);
this.infoMtuPanel.Name = "infoMtuPanel";
//
// infoMtuMessage
//
resources.ApplyResources(this.infoMtuMessage, "infoMtuMessage");
this.infoMtuMessage.Name = "infoMtuMessage";
//
// pictureBox2
//
resources.ApplyResources(this.pictureBox2, "pictureBox2");
this.pictureBox2.Image = global::XenAdmin.Properties.Resources._000_Info3_h32bit_16;
this.pictureBox2.Name = "pictureBox2";
this.pictureBox2.TabStop = false;
//
// labelNIC
//
resources.ApplyResources(this.labelNIC, "labelNIC");
this.labelNIC.Name = "labelNIC";
//
// labelVLAN
//
resources.ApplyResources(this.labelVLAN, "labelVLAN");
this.labelVLAN.Name = "labelVLAN";
//
// lblNicHelp
//
resources.ApplyResources(this.lblNicHelp, "lblNicHelp");
this.tableLayoutPanel1.SetColumnSpan(this.lblNicHelp, 4);
this.lblNicHelp.Name = "lblNicHelp";
//
// numericUpDownVLAN
//
resources.ApplyResources(this.numericUpDownVLAN, "numericUpDownVLAN");
this.numericUpDownVLAN.Maximum = new decimal(new int[] {
4094,
0,
0,
0});
this.numericUpDownVLAN.Minimum = new decimal(new int[] {
1,
0,
0,
0});
this.numericUpDownVLAN.Name = "numericUpDownVLAN";
this.numericUpDownVLAN.Value = new decimal(new int[] {
1,
0,
0,
0});
this.numericUpDownVLAN.ValueChanged += new System.EventHandler(this.nudVLAN_ValueChanged);
//
// comboBoxNICList
//
this.tableLayoutPanel1.SetColumnSpan(this.comboBoxNICList, 2);
this.comboBoxNICList.DisplayMember = "Server";
this.comboBoxNICList.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.comboBoxNICList.FormattingEnabled = true;
resources.ApplyResources(this.comboBoxNICList, "comboBoxNICList");
this.comboBoxNICList.Name = "comboBoxNICList";
this.comboBoxNICList.Sorted = true;
this.comboBoxNICList.SelectedIndexChanged += new System.EventHandler(this.cmbHostNicList_SelectedIndexChanged);
//
// labelMTU
//
resources.ApplyResources(this.labelMTU, "labelMTU");
this.labelMTU.Name = "labelMTU";
//
// numericUpDownMTU
//
resources.ApplyResources(this.numericUpDownMTU, "numericUpDownMTU");
this.numericUpDownMTU.Name = "numericUpDownMTU";
//
// panelVLANInfo
//
resources.ApplyResources(this.panelVLANInfo, "panelVLANInfo");
this.tableLayoutPanel1.SetColumnSpan(this.panelVLANInfo, 2);
this.panelVLANInfo.Controls.Add(this.labelVlanError);
this.panelVLANInfo.Controls.Add(this.labelVLAN0Info);
this.panelVLANInfo.Name = "panelVLANInfo";
//
// labelVlanError
//
resources.ApplyResources(this.labelVlanError, "labelVlanError");
this.labelVlanError.ForeColor = System.Drawing.Color.Red;
this.labelVlanError.Name = "labelVlanError";
//
// labelVLAN0Info
//
resources.ApplyResources(this.labelVLAN0Info, "labelVLAN0Info");
this.labelVLAN0Info.ForeColor = System.Drawing.SystemColors.ControlText;
this.labelVLAN0Info.Name = "labelVLAN0Info";
//
// checkBoxAutomatic
//
resources.ApplyResources(this.checkBoxAutomatic, "checkBoxAutomatic");
this.tableLayoutPanel1.SetColumnSpan(this.checkBoxAutomatic, 4);
this.checkBoxAutomatic.Name = "checkBoxAutomatic";
this.checkBoxAutomatic.UseVisualStyleBackColor = true;
//
// checkBoxSriov
//
resources.ApplyResources(this.checkBoxSriov, "checkBoxSriov");
this.tableLayoutPanel1.SetColumnSpan(this.checkBoxSriov, 4);
this.checkBoxSriov.Name = "checkBoxSriov";
this.checkBoxSriov.UseVisualStyleBackColor = true;
this.checkBoxSriov.CheckedChanged += new System.EventHandler(this.checkBoxSriov_CheckedChanged);
//
// NetWDetails
//
resources.ApplyResources(this, "$this");
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi;
this.BackColor = System.Drawing.SystemColors.Control;
this.Controls.Add(this.panel1);
this.Name = "NetWDetails";
this.panel1.ResumeLayout(false);
this.tableLayoutPanel1.ResumeLayout(false);
this.tableLayoutPanel1.PerformLayout();
this.infoMtuPanel.ResumeLayout(false);
this.infoMtuPanel.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBox2)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.numericUpDownVLAN)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.numericUpDownMTU)).EndInit();
this.panelVLANInfo.ResumeLayout(false);
this.panelVLANInfo.PerformLayout();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.Panel panel1;
private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1;
private System.Windows.Forms.Label labelNIC;
private System.Windows.Forms.ComboBox comboBoxNICList;
private System.Windows.Forms.NumericUpDown numericUpDownVLAN;
private System.Windows.Forms.Label labelVLAN;
private System.Windows.Forms.Label lblNicHelp;
private System.Windows.Forms.CheckBox checkBoxAutomatic;
private System.Windows.Forms.Label labelVlanError;
private System.Windows.Forms.Label labelMTU;
private System.Windows.Forms.NumericUpDown numericUpDownMTU;
private System.Windows.Forms.Panel panelVLANInfo;
private System.Windows.Forms.Label labelVLAN0Info;
private System.Windows.Forms.Panel infoMtuPanel;
private System.Windows.Forms.Label infoMtuMessage;
private System.Windows.Forms.PictureBox pictureBox2;
private System.Windows.Forms.CheckBox checkBoxSriov;
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Reflection;
using Xunit;
namespace System.Globalization.Tests
{
public partial class CompareInfoTests
{
[Theory]
[InlineData("")]
[InlineData("en-US")]
[InlineData("fr-FR")]
[InlineData("en")]
[InlineData("zh-Hans")]
[InlineData("zh-Hant")]
public void GetCompareInfo(string name)
{
CompareInfo compare = CompareInfo.GetCompareInfo(name);
Assert.Equal(name, compare.Name);
}
[Fact]
public void GetCompareInfo_Null_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("name", () => CompareInfo.GetCompareInfo(null));
}
public static IEnumerable<object[]> Equals_TestData()
{
yield return new object[] { CultureInfo.InvariantCulture.CompareInfo, CultureInfo.InvariantCulture.CompareInfo, true };
yield return new object[] { CultureInfo.InvariantCulture.CompareInfo, CompareInfo.GetCompareInfo(""), true };
yield return new object[] { new CultureInfo("en-US").CompareInfo, CompareInfo.GetCompareInfo("en-US"), true };
yield return new object[] { new CultureInfo("en-US").CompareInfo, CompareInfo.GetCompareInfo("fr-FR"), false };
yield return new object[] { new CultureInfo("en-US").CompareInfo, new object(), false };
}
[Theory]
[MemberData(nameof(Equals_TestData))]
public void Equals(CompareInfo compare1, object value, bool expected)
{
Assert.Equal(expected, compare1.Equals(value));
if (value is CompareInfo)
{
Assert.Equal(expected, compare1.GetHashCode().Equals(value.GetHashCode()));
}
}
public static IEnumerable<object[]> GetHashCodeTestData => new[]
{
new object[] { "abc", CompareOptions.OrdinalIgnoreCase, "ABC", CompareOptions.OrdinalIgnoreCase, true },
new object[] { "abc", CompareOptions.Ordinal, "ABC", CompareOptions.Ordinal, false },
new object[] { "abc", CompareOptions.Ordinal, "abc", CompareOptions.Ordinal, true },
new object[] { "abc", CompareOptions.None, "abc", CompareOptions.None, true },
};
[Theory]
[MemberData(nameof(GetHashCodeTestData))]
public void GetHashCode(string source1, CompareOptions options1, string source2, CompareOptions options2, bool expected)
{
CompareInfo invariantCompare = CultureInfo.InvariantCulture.CompareInfo;
Assert.Equal(expected, invariantCompare.GetHashCode(source1, options1).Equals(invariantCompare.GetHashCode(source2, options2)));
}
[Fact]
public void GetHashCode_EmptyString()
{
Assert.Equal(0, CultureInfo.InvariantCulture.CompareInfo.GetHashCode("", CompareOptions.None));
}
[Fact]
public void GetHashCode_Invalid()
{
AssertExtensions.Throws<ArgumentNullException>("source", () => CultureInfo.InvariantCulture.CompareInfo.GetHashCode(null, CompareOptions.None));
AssertExtensions.Throws<ArgumentException>("options", () => CultureInfo.InvariantCulture.CompareInfo.GetHashCode("Test", CompareOptions.StringSort));
AssertExtensions.Throws<ArgumentException>("options", () => CultureInfo.InvariantCulture.CompareInfo.GetHashCode("Test", CompareOptions.Ordinal | CompareOptions.IgnoreSymbols));
AssertExtensions.Throws<ArgumentException>("options", () => CultureInfo.InvariantCulture.CompareInfo.GetHashCode("Test", (CompareOptions)(-1)));
}
[Theory]
[InlineData("", "CompareInfo - ")]
[InlineData("en-US", "CompareInfo - en-US")]
[InlineData("EN-US", "CompareInfo - en-US")]
public void ToString(string name, string expected)
{
Assert.Equal(expected, new CultureInfo(name).CompareInfo.ToString());
}
public static IEnumerable<object[]> CompareInfo_TestData()
{
yield return new object[] { "en-US" , 0x0409 };
yield return new object[] { "ar-SA" , 0x0401 };
yield return new object[] { "ja-JP" , 0x0411 };
yield return new object[] { "zh-CN" , 0x0804 };
yield return new object[] { "en-GB" , 0x0809 };
yield return new object[] { "tr-TR" , 0x041f };
}
// On Windows, hiragana characters sort after katakana.
// On ICU, it is the opposite
private static int s_expectedHiraganaToKatakanaCompare = PlatformDetection.IsWindows ? 1 : -1;
// On Windows, all halfwidth characters sort before fullwidth characters.
// On ICU, half and fullwidth characters that aren't in the "Halfwidth and fullwidth forms" block U+FF00-U+FFEF
// sort before the corresponding characters that are in the block U+FF00-U+FFEF
private static int s_expectedHalfToFullFormsComparison = PlatformDetection.IsWindows ? -1 : 1;
private static CompareInfo s_invariantCompare = CultureInfo.InvariantCulture.CompareInfo;
private static CompareInfo s_turkishCompare = new CultureInfo("tr-TR").CompareInfo;
public static IEnumerable<object[]> SortKey_TestData()
{
CompareOptions ignoreKanaIgnoreWidthIgnoreCase = CompareOptions.IgnoreKanaType | CompareOptions.IgnoreWidth | CompareOptions.IgnoreCase;
yield return new object[] { s_invariantCompare, "\u3042", "\u30A2", ignoreKanaIgnoreWidthIgnoreCase, 0 };
yield return new object[] { s_invariantCompare, "\u3042", "\uFF71", ignoreKanaIgnoreWidthIgnoreCase, 0 };
yield return new object[] { s_invariantCompare, "\u304D\u3083", "\u30AD\u30E3", ignoreKanaIgnoreWidthIgnoreCase, 0 };
yield return new object[] { s_invariantCompare, "\u304D\u3083", "\u30AD\u3083", ignoreKanaIgnoreWidthIgnoreCase, 0 };
yield return new object[] { s_invariantCompare, "\u304D \u3083", "\u30AD\u3083", ignoreKanaIgnoreWidthIgnoreCase, -1 };
yield return new object[] { s_invariantCompare, "\u3044", "I", ignoreKanaIgnoreWidthIgnoreCase, 1 };
yield return new object[] { s_invariantCompare, "a", "A", ignoreKanaIgnoreWidthIgnoreCase, 0 };
yield return new object[] { s_invariantCompare, "a", "\uFF41", ignoreKanaIgnoreWidthIgnoreCase, 0 };
yield return new object[] { s_invariantCompare, "ABCDE", "\uFF21\uFF22\uFF23\uFF24\uFF25", ignoreKanaIgnoreWidthIgnoreCase, 0 };
yield return new object[] { s_invariantCompare, "ABCDE", "\uFF21\uFF22\uFF23D\uFF25", ignoreKanaIgnoreWidthIgnoreCase, 0 };
yield return new object[] { s_invariantCompare, "ABCDE", "a\uFF22\uFF23D\uFF25", ignoreKanaIgnoreWidthIgnoreCase, 0 };
yield return new object[] { s_invariantCompare, "ABCDE", "\uFF41\uFF42\uFF23D\uFF25", ignoreKanaIgnoreWidthIgnoreCase, 0 };
yield return new object[] { s_invariantCompare, "\u6FA4", "\u6CA2", ignoreKanaIgnoreWidthIgnoreCase, 1 };
yield return new object[] { s_invariantCompare, "\u3070\u3073\u3076\u3079\u307C", "\u30D0\u30D3\u30D6\u30D9\u30DC", ignoreKanaIgnoreWidthIgnoreCase, 0 };
yield return new object[] { s_invariantCompare, "\u3070\u3073\u3076\u3079\u307C", "\u30D0\u30D3\u3076\u30D9\u30DC", ignoreKanaIgnoreWidthIgnoreCase, 0 };
yield return new object[] { s_invariantCompare, "\u3070\u3073\u3076\u3079\u307C", "\u30D0\u30D3\u3076\u30D9\uFF8E\uFF9E", ignoreKanaIgnoreWidthIgnoreCase, 0 };
yield return new object[] { s_invariantCompare, "\u3070\u3073\uFF8C\uFF9E\uFF8D\uFF9E\u307C", "\u30D0\u30D3\u3076\u30D9\uFF8E\uFF9E", ignoreKanaIgnoreWidthIgnoreCase, 0 };
yield return new object[] { s_invariantCompare, "\u3070\u3073\uFF8C\uFF9E\uFF8D\uFF9E\u307C", "\uFF8E\uFF9E", ignoreKanaIgnoreWidthIgnoreCase, -1 };
yield return new object[] { s_invariantCompare, "\u3070\u30DC\uFF8C\uFF9E\uFF8D\uFF9E\u307C", "\uFF8E\uFF9E", ignoreKanaIgnoreWidthIgnoreCase, -1 };
yield return new object[] { s_invariantCompare, "\u3070\u30DC\uFF8C\uFF9E\uFF8D\uFF9E\u307C", "\u3079\uFF8E\uFF9E", ignoreKanaIgnoreWidthIgnoreCase, -1 };
yield return new object[] { s_invariantCompare, "\u3070\u3073\uFF8C\uFF9E\uFF8D\uFF9E\u307C", "\u30D6", ignoreKanaIgnoreWidthIgnoreCase, -1 };
yield return new object[] { s_invariantCompare, "\u3071\u3074\u30D7\u307A", "\uFF8B\uFF9F\uFF8C\uFF9F", ignoreKanaIgnoreWidthIgnoreCase, -1 };
yield return new object[] { s_invariantCompare, "\u3070\u30DC\uFF8C\uFF9E\uFF8D\uFF9E\u307C", "\u3070\uFF8E\uFF9E\u30D6", ignoreKanaIgnoreWidthIgnoreCase, 1 };
yield return new object[] { s_invariantCompare, "\u3070\u30DC\uFF8C\uFF9E\uFF8D\uFF9E\u307C\u3079\u307C", "\u3079\uFF8E\uFF9E", ignoreKanaIgnoreWidthIgnoreCase, -1 };
yield return new object[] { s_invariantCompare, "\u3070\uFF8C\uFF9E\uFF8D\uFF9E\u307C", "\u30D6", ignoreKanaIgnoreWidthIgnoreCase, -1 };
yield return new object[] { s_invariantCompare, "ABDDE", "D", ignoreKanaIgnoreWidthIgnoreCase, -1 };
yield return new object[] { s_invariantCompare, "ABCDE", "\uFF43D", ignoreKanaIgnoreWidthIgnoreCase, -1 };
yield return new object[] { s_invariantCompare, "ABCDE", "c", ignoreKanaIgnoreWidthIgnoreCase, -1 };
yield return new object[] { s_invariantCompare, "\u3060", "\u305F", ignoreKanaIgnoreWidthIgnoreCase, 1 };
yield return new object[] { s_invariantCompare, "\u3060", "\uFF80\uFF9E", ignoreKanaIgnoreWidthIgnoreCase, 0 };
yield return new object[] { s_invariantCompare, "\u3060", "\u30C0", ignoreKanaIgnoreWidthIgnoreCase, 0 };
yield return new object[] { s_invariantCompare, "\u30C7\u30BF\u30D9\u30B9", "\uFF83\uFF9E\uFF80\uFF8D\uFF9E\uFF7D", ignoreKanaIgnoreWidthIgnoreCase, 0 };
yield return new object[] { s_invariantCompare, "\u30C7", "\uFF83\uFF9E", ignoreKanaIgnoreWidthIgnoreCase, 0 };
yield return new object[] { s_invariantCompare, "\u30C7\u30BF", "\uFF83\uFF9E\uFF80", ignoreKanaIgnoreWidthIgnoreCase, 0 };
yield return new object[] { s_invariantCompare, "\u30C7\u30BF\u30D9", "\uFF83\uFF9E\uFF80\uFF8D\uFF9E", ignoreKanaIgnoreWidthIgnoreCase, 0 };
yield return new object[] { s_invariantCompare, "\u30BF", "\uFF80", ignoreKanaIgnoreWidthIgnoreCase, 0 };
yield return new object[] { s_invariantCompare, "\uFF83\uFF9E\uFF70\uFF80\uFF8D\uFF9E\uFF70\uFF7D", "\u3067\u30FC\u305F\u3079\u30FC\u3059", ignoreKanaIgnoreWidthIgnoreCase, 0 };
yield return new object[] { s_invariantCompare, "\u68EE\u9D0E\u5916", "\u68EE\u9DD7\u5916", ignoreKanaIgnoreWidthIgnoreCase, -1 };
yield return new object[] { s_invariantCompare, "\u68EE\u9DD7\u5916", "\u68EE\u9DD7\u5916", ignoreKanaIgnoreWidthIgnoreCase, 0 };
yield return new object[] { s_invariantCompare, "\u2019\u2019\u2019\u2019", "''''", ignoreKanaIgnoreWidthIgnoreCase, 1 };
yield return new object[] { s_invariantCompare, "\u2019", "'", ignoreKanaIgnoreWidthIgnoreCase, 1 };
yield return new object[] { s_invariantCompare, "", "'", ignoreKanaIgnoreWidthIgnoreCase, -1 };
yield return new object[] { s_invariantCompare, "\u4E00", "\uFF11", ignoreKanaIgnoreWidthIgnoreCase, 1 };
yield return new object[] { s_invariantCompare, "\u2160", "\uFF11", ignoreKanaIgnoreWidthIgnoreCase, 1 };
yield return new object[] { s_invariantCompare, "0", "\uFF10", ignoreKanaIgnoreWidthIgnoreCase, 0 };
yield return new object[] { s_invariantCompare, "10", "1\uFF10", ignoreKanaIgnoreWidthIgnoreCase, 0 };
yield return new object[] { s_invariantCompare, "9999\uFF1910", "1\uFF10", ignoreKanaIgnoreWidthIgnoreCase, 1 };
yield return new object[] { s_invariantCompare, "9999\uFF191010", "1\uFF10", ignoreKanaIgnoreWidthIgnoreCase, 1 };
yield return new object[] { s_invariantCompare, "'\u3000'", "' '", ignoreKanaIgnoreWidthIgnoreCase, 0 };
yield return new object[] { s_invariantCompare, "\uFF1B", ";", ignoreKanaIgnoreWidthIgnoreCase, 0 };
yield return new object[] { s_invariantCompare, "\uFF08", "(", ignoreKanaIgnoreWidthIgnoreCase, 0 };
yield return new object[] { s_invariantCompare, "\u30FC", "\uFF70", ignoreKanaIgnoreWidthIgnoreCase, 0 };
yield return new object[] { s_invariantCompare, "\u30FC", "\uFF0D", ignoreKanaIgnoreWidthIgnoreCase, 1 };
yield return new object[] { s_invariantCompare, "\u30FC", "\u30FC", ignoreKanaIgnoreWidthIgnoreCase, 0 };
yield return new object[] { s_invariantCompare, "\u30FC", "\u2015", ignoreKanaIgnoreWidthIgnoreCase, 1 };
yield return new object[] { s_invariantCompare, "\u30FC", "\u2010", ignoreKanaIgnoreWidthIgnoreCase, 1 };
yield return new object[] { s_invariantCompare, "/", "\uFF0F", ignoreKanaIgnoreWidthIgnoreCase, 0 };
yield return new object[] { s_invariantCompare, "'", "\uFF07", ignoreKanaIgnoreWidthIgnoreCase, PlatformDetection.IsWindows7 ? -1 : 0};
yield return new object[] { s_invariantCompare, "\"", "\uFF02", ignoreKanaIgnoreWidthIgnoreCase, 0 };
yield return new object[] { s_invariantCompare, "\u3042", "\u30A1", CompareOptions.None, s_expectedHiraganaToKatakanaCompare };
yield return new object[] { s_invariantCompare, "\u3042", "\u30A2", CompareOptions.None, s_expectedHiraganaToKatakanaCompare };
yield return new object[] { s_invariantCompare, "\u3042", "\uFF71", CompareOptions.None, s_expectedHiraganaToKatakanaCompare };
yield return new object[] { s_invariantCompare, "\u304D\u3083", "\u30AD\u30E3", CompareOptions.None, s_expectedHiraganaToKatakanaCompare };
yield return new object[] { s_invariantCompare, "\u304D\u3083", "\u30AD\u3083", CompareOptions.None, s_expectedHiraganaToKatakanaCompare };
yield return new object[] { s_invariantCompare, "\u304D \u3083", "\u30AD\u3083", CompareOptions.None, -1 };
yield return new object[] { s_invariantCompare, "\u3044", "I", CompareOptions.None, 1 };
yield return new object[] { s_invariantCompare, "a", "A", CompareOptions.None, -1 };
yield return new object[] { s_invariantCompare, "a", "\uFF41", CompareOptions.None, -1 };
yield return new object[] { s_invariantCompare, "ABCDE", "\uFF21\uFF22\uFF23\uFF24\uFF25", CompareOptions.None, -1 };
yield return new object[] { s_invariantCompare, "ABCDE", "\uFF21\uFF22\uFF23D\uFF25", CompareOptions.None, -1 };
yield return new object[] { s_invariantCompare, new string('a', 5555), new string('a', 5554) + "b", CompareOptions.None, -1 };
yield return new object[] { s_invariantCompare, "ABCDE", "\uFF41\uFF42\uFF23D\uFF25", CompareOptions.None, 1 };
yield return new object[] { s_invariantCompare, "\u6FA4", "\u6CA2", CompareOptions.None, 1 };
yield return new object[] { s_invariantCompare, "\u3070\u3073\u3076\u3079\u307C", "\u30D0\u30D3\u30D6\u30D9\u30DC", CompareOptions.None, s_expectedHiraganaToKatakanaCompare };
yield return new object[] { s_invariantCompare, "\u3070\u3073\u3076\u3079\u307C", "\u30D0\u30D3\u3076\u30D9\u30DC", CompareOptions.None, s_expectedHiraganaToKatakanaCompare };
yield return new object[] { s_invariantCompare, "\u3070\u3073\u3076\u3079\u307C", "\u30D0\u30D3\u3076\u30D9\uFF8E\uFF9E", CompareOptions.None, s_expectedHiraganaToKatakanaCompare };
yield return new object[] { s_invariantCompare, "\u3070\u3073\uFF8C\uFF9E\uFF8D\uFF9E\u307C", "\u30D0\u30D3\u3076\u30D9\uFF8E\uFF9E", CompareOptions.None, s_expectedHiraganaToKatakanaCompare };
yield return new object[] { s_invariantCompare, "\u3070\u3073\uFF8C\uFF9E\uFF8D\uFF9E\u307C", "\uFF8E\uFF9E", CompareOptions.None, -1 };
yield return new object[] { s_invariantCompare, "\u3070\u30DC\uFF8C\uFF9E\uFF8D\uFF9E\u307C", "\u3079\uFF8E\uFF9E", CompareOptions.None, -1 };
yield return new object[] { s_invariantCompare, "\u3070\u3073\uFF8C\uFF9E\uFF8D\uFF9E\u307C", "\u30D6", CompareOptions.None, -1 };
yield return new object[] { s_invariantCompare, "\u3071\u3074\u30D7\u307A", "\uFF8B\uFF9F\uFF8C\uFF9F", CompareOptions.None, -1 };
yield return new object[] { s_invariantCompare, "\u3070\u30DC\uFF8C\uFF9E\uFF8D\uFF9E\u307C", "\u3070\uFF8E\uFF9E\u30D6", CompareOptions.None, 1 };
yield return new object[] { s_invariantCompare, "\u3070\u30DC\uFF8C\uFF9E\uFF8D\uFF9E\u307C\u3079\u307C", "\u3079\uFF8E\uFF9E", CompareOptions.None, -1 };
yield return new object[] { s_invariantCompare, "\u3070\uFF8C\uFF9E\uFF8D\uFF9E\u307C", "\u30D6", CompareOptions.None, -1 };
yield return new object[] { s_invariantCompare, "ABDDE", "D", CompareOptions.None, -1 };
yield return new object[] { s_invariantCompare, "ABCDE", "\uFF43D\uFF25", CompareOptions.None, -1 };
yield return new object[] { s_invariantCompare, "ABCDE", "\uFF43D", CompareOptions.None, -1 };
yield return new object[] { s_invariantCompare, "ABCDE", "c", CompareOptions.None, -1 };
yield return new object[] { s_invariantCompare, "\u3060", "\u305F", CompareOptions.None, 1 };
yield return new object[] { s_invariantCompare, "\u3060", "\uFF80\uFF9E", CompareOptions.None, s_expectedHiraganaToKatakanaCompare };
yield return new object[] { s_invariantCompare, "\u3060", "\u30C0", CompareOptions.None, s_expectedHiraganaToKatakanaCompare };
yield return new object[] { s_invariantCompare, "\u68EE\u9D0E\u5916", "\u68EE\u9DD7\u5916", CompareOptions.None, -1 };
yield return new object[] { s_invariantCompare, "\u68EE\u9DD7\u5916", "\u68EE\u9DD7\u5916", CompareOptions.None, 0 };
yield return new object[] { s_invariantCompare, "\u2019\u2019\u2019\u2019", "''''", CompareOptions.None, 1 };
yield return new object[] { s_invariantCompare, "\u2019\u2019\u2019\u2019", "''''", CompareOptions.None, 1 };
yield return new object[] { s_invariantCompare, "\u2019\u2019\u2019\u2019", "''''", CompareOptions.None, 1 };
yield return new object[] { s_invariantCompare, "\u2019", "'", CompareOptions.None, 1 };
yield return new object[] { s_invariantCompare, "", "'", CompareOptions.None, -1 };
yield return new object[] { s_invariantCompare, "\u4E00", "\uFF11", CompareOptions.None, 1 };
yield return new object[] { s_invariantCompare, "\u2160", "\uFF11", CompareOptions.None, 1 };
yield return new object[] { s_invariantCompare, "0", "\uFF10", CompareOptions.None, -1 };
yield return new object[] { s_invariantCompare, "10", "1\uFF10", CompareOptions.None, -1 };
yield return new object[] { s_invariantCompare, "1\uFF10", "1\uFF10", CompareOptions.None, 0 };
yield return new object[] { s_invariantCompare, "9999\uFF1910", "1\uFF10", CompareOptions.None, 1 };
yield return new object[] { s_invariantCompare, "9999\uFF191010", "1\uFF10", CompareOptions.None, 1 };
yield return new object[] { s_invariantCompare, "'\u3000'", "' '", CompareOptions.None, 1 };
yield return new object[] { s_invariantCompare, "\uFF1B", ";", CompareOptions.None, 1 };
yield return new object[] { s_invariantCompare, "\uFF08", "(", CompareOptions.None, 1 };
yield return new object[] { s_invariantCompare, "\u30FC", "\uFF0D", CompareOptions.None, 1 };
yield return new object[] { s_invariantCompare, "\u30FC", "\u30FC", CompareOptions.None, 0 };
yield return new object[] { s_invariantCompare, "\u30FC", "\u2015", CompareOptions.None, 1 };
yield return new object[] { s_invariantCompare, "\u30FC", "\u2010", CompareOptions.None, 1 };
yield return new object[] { s_invariantCompare, "/", "\uFF0F", CompareOptions.None, -1 };
yield return new object[] { s_invariantCompare, "'", "\uFF07", CompareOptions.None, -1 };
yield return new object[] { s_invariantCompare, "\"", "\uFF02", CompareOptions.None, -1 };
// Turkish
yield return new object[] { s_turkishCompare, "i", "I", CompareOptions.None, 1 };
yield return new object[] { s_turkishCompare, "i", "I", CompareOptions.IgnoreCase, 1 };
yield return new object[] { s_invariantCompare, "i", "\u0130", CompareOptions.None, -1 };
yield return new object[] { s_turkishCompare, "i", "\u0130", CompareOptions.IgnoreCase, 0 };
yield return new object[] { s_invariantCompare, "i", "I", CompareOptions.None, -1 };
yield return new object[] { s_invariantCompare, "i", "I", CompareOptions.IgnoreCase, 0 };
yield return new object[] { s_invariantCompare, "i", "\u0130", CompareOptions.None, -1 };
yield return new object[] { s_invariantCompare, "i", "\u0130", CompareOptions.IgnoreCase, -1 };
yield return new object[] { s_invariantCompare, "\u00C0", "A\u0300", CompareOptions.None, 0 };
yield return new object[] { s_invariantCompare, "\u00C0", "a\u0300", CompareOptions.None, 1 };
yield return new object[] { s_invariantCompare, "\u00C0", "a\u0300", CompareOptions.IgnoreCase, 0 };
yield return new object[] { s_invariantCompare, "FooBA\u0300R", "FooB\u00C0R", CompareOptions.IgnoreNonSpace, 0 };
yield return new object[] { s_invariantCompare, "Test's", "Tests", CompareOptions.IgnoreSymbols, 0 };
yield return new object[] { s_invariantCompare, "Test's", "Tests", CompareOptions.StringSort, -1 };
yield return new object[] { s_invariantCompare, new string('a', 5555), new string('a', 5555), CompareOptions.None, 0 };
yield return new object[] { s_invariantCompare, "foobar", "FooB\u00C0R", CompareOptions.IgnoreNonSpace | CompareOptions.IgnoreCase, 0 };
yield return new object[] { s_invariantCompare, "foobar", "FooB\u00C0R", CompareOptions.IgnoreNonSpace, -1 };
yield return new object[] { s_invariantCompare, "\uFF9E", "\u3099", CompareOptions.IgnoreNonSpace, 0 };
yield return new object[] { s_invariantCompare, "\uFF9E", "\u3099", CompareOptions.IgnoreCase, 0 };
yield return new object[] { s_invariantCompare, "\u20A9", "\uFFE6", CompareOptions.IgnoreWidth, 0 };
yield return new object[] { s_invariantCompare, "\u20A9", "\uFFE6", CompareOptions.IgnoreCase, -1 };
yield return new object[] { s_invariantCompare, "\u20A9", "\uFFE6", CompareOptions.None, -1 };
yield return new object[] { s_invariantCompare, "\u0021", "\uFF01", CompareOptions.IgnoreSymbols, 0 };
yield return new object[] { s_invariantCompare, "\u00A2", "\uFFE0", CompareOptions.IgnoreSymbols, 0 };
yield return new object[] { s_invariantCompare, "$", "&", CompareOptions.IgnoreSymbols, 0 };
yield return new object[] { s_invariantCompare, "\uFF65", "\u30FB", CompareOptions.IgnoreSymbols, 0 };
yield return new object[] { s_invariantCompare, "\u0021", "\uFF01", CompareOptions.IgnoreWidth, 0 };
yield return new object[] { s_invariantCompare, "\u0021", "\uFF01", CompareOptions.None, -1 };
yield return new object[] { s_invariantCompare, "\uFF66", "\u30F2", CompareOptions.IgnoreWidth, 0 };
yield return new object[] { s_invariantCompare, "\uFF66", "\u30F2", CompareOptions.IgnoreSymbols, s_expectedHalfToFullFormsComparison };
yield return new object[] { s_invariantCompare, "\uFF66", "\u30F2", CompareOptions.IgnoreCase, s_expectedHalfToFullFormsComparison };
yield return new object[] { s_invariantCompare, "\uFF66", "\u30F2", CompareOptions.IgnoreNonSpace, s_expectedHalfToFullFormsComparison };
yield return new object[] { s_invariantCompare, "\uFF66", "\u30F2", CompareOptions.None, s_expectedHalfToFullFormsComparison };
yield return new object[] { s_invariantCompare, "\u3060", "\u30C0", CompareOptions.IgnoreKanaType, 0 };
yield return new object[] { s_invariantCompare, "\u3060", "\u30C0", CompareOptions.IgnoreCase, s_expectedHiraganaToKatakanaCompare };
yield return new object[] { s_invariantCompare, "c", "C", CompareOptions.IgnoreKanaType, -1 };
// Spanish
yield return new object[] { new CultureInfo("es-ES").CompareInfo, "llegar", "lugar", CompareOptions.None, -1 };
}
public static IEnumerable<object[]> IndexOf_TestData()
{
yield return new object[] { s_invariantCompare, "foo", "", 0, 0, 0 };
yield return new object[] { s_invariantCompare, "", "", 0, 0, 0 };
yield return new object[] { s_invariantCompare, "Hello", "l", 0, 2, -1 };
yield return new object[] { s_invariantCompare, "Hello", "l", 3, 3, 3 };
yield return new object[] { s_invariantCompare, "Hello", "l", 2, 2, 2 };
yield return new object[] { s_invariantCompare, "Hello", "L", 0, -1, -1 };
yield return new object[] { s_invariantCompare, "Hello", "h", 0, -1, -1 };
}
public static IEnumerable<object[]> IsSortable_TestData()
{
yield return new object[] { "", false, false };
yield return new object[] { "abcdefg", false, true };
yield return new object[] { "\uD800\uDC00", true, true };
yield return new object[] { "\uD800\uD800", true, false };
}
[Theory]
[MemberData(nameof(CompareInfo_TestData))]
public static void LcidTest(string cultureName, int lcid)
{
var ci = CompareInfo.GetCompareInfo(lcid);
Assert.Equal(cultureName, ci.Name);
Assert.Equal(lcid, ci.LCID);
Assembly assembly = typeof(string).Assembly;
ci = CompareInfo.GetCompareInfo(lcid, assembly);
Assert.Equal(cultureName, ci.Name);
Assert.Equal(lcid, ci.LCID);
ci = CompareInfo.GetCompareInfo(cultureName, assembly);
Assert.Equal(cultureName, ci.Name);
Assert.Equal(lcid, ci.LCID);
}
[Theory]
[MemberData(nameof(SortKey_TestData))]
public void SortKeyTest(CompareInfo compareInfo, string string1, string string2, CompareOptions options, int expected)
{
SortKey sk1 = compareInfo.GetSortKey(string1, options);
SortKey sk2 = compareInfo.GetSortKey(string2, options);
Assert.Equal(expected, SortKey.Compare(sk1, sk2));
Assert.Equal(string1, sk1.OriginalString);
Assert.Equal(string2, sk2.OriginalString);
}
[Fact]
public void SortKeyMiscTest()
{
CompareInfo ci = new CultureInfo("en-US").CompareInfo;
string s1 = "abc";
string s2 = "ABC";
SortKey sk1 = ci.GetSortKey(s1);
SortKey sk2 = ci.GetSortKey(s1);
SortKey sk3 = ci.GetSortKey(s2);
SortKey sk4 = ci.GetSortKey(s2, CompareOptions.IgnoreCase);
SortKey sk5 = ci.GetSortKey(s1, CompareOptions.IgnoreCase);
Assert.Equal(sk2, sk1);
Assert.Equal(sk2.GetHashCode(), sk1.GetHashCode());
Assert.Equal(sk2.KeyData, sk1.KeyData);
Assert.NotEqual(sk3, sk1);
Assert.NotEqual(sk3.GetHashCode(), sk1.GetHashCode());
Assert.NotEqual(sk3.KeyData, sk1.KeyData);
Assert.NotEqual(sk4, sk3);
Assert.NotEqual(sk4.GetHashCode(), sk3.GetHashCode());
Assert.NotEqual(sk4.KeyData, sk3.KeyData);
Assert.Equal(sk4, sk5);
Assert.Equal(sk4.GetHashCode(), sk5.GetHashCode());
Assert.Equal(sk4.KeyData, sk5.KeyData);
AssertExtensions.Throws<ArgumentNullException>("source", () => ci.GetSortKey(null));
AssertExtensions.Throws<ArgumentException>("options", () => ci.GetSortKey(s1, CompareOptions.Ordinal));
}
[Theory]
[MemberData(nameof(IndexOf_TestData))]
public void IndexOfTest(CompareInfo compareInfo, string source, string value, int startIndex, int indexOfExpected, int lastIndexOfExpected)
{
Assert.Equal(indexOfExpected, compareInfo.IndexOf(source, value, startIndex));
if (value.Length > 0)
{
Assert.Equal(indexOfExpected, compareInfo.IndexOf(source, value[0], startIndex));
}
Assert.Equal(lastIndexOfExpected, compareInfo.LastIndexOf(source, value, startIndex));
if (value.Length > 0)
{
Assert.Equal(lastIndexOfExpected, compareInfo.LastIndexOf(source, value[0], startIndex));
}
}
[Theory]
[MemberData(nameof(IsSortable_TestData))]
public void IsSortableTest(string source, bool hasSurrogate, bool expected)
{
Assert.Equal(expected, CompareInfo.IsSortable(source));
bool charExpectedResults = hasSurrogate ? false : expected;
foreach (char c in source)
Assert.Equal(charExpectedResults, CompareInfo.IsSortable(c));
}
[Fact]
public void VersionTest()
{
SortVersion sv1 = CultureInfo.GetCultureInfo("en-US").CompareInfo.Version;
SortVersion sv2 = CultureInfo.GetCultureInfo("ja-JP").CompareInfo.Version;
SortVersion sv3 = CultureInfo.GetCultureInfo("en").CompareInfo.Version;
Assert.Equal(sv1.FullVersion, sv3.FullVersion);
Assert.NotEqual(sv1.SortId, sv2.SortId);
}
[Theory]
[MemberData(nameof(GetHashCodeTestData))]
public void GetHashCode_Span(string source1, CompareOptions options1, string source2, CompareOptions options2, bool expectSameHashCode)
{
CompareInfo invariantCompare = CultureInfo.InvariantCulture.CompareInfo;
int hashOfSource1AsString = invariantCompare.GetHashCode(source1, options1);
int hashOfSource1AsSpan = invariantCompare.GetHashCode(source1.AsSpan(), options1);
Assert.Equal(hashOfSource1AsString, hashOfSource1AsSpan);
int hashOfSource2AsString = invariantCompare.GetHashCode(source2, options2);
int hashOfSource2AsSpan = invariantCompare.GetHashCode(source2.AsSpan(), options2);
Assert.Equal(hashOfSource2AsString, hashOfSource2AsSpan);
Assert.Equal(expectSameHashCode, hashOfSource1AsSpan == hashOfSource2AsSpan);
}
[Fact]
public void GetHashCode_EmptySpan()
{
Assert.Equal(0, CultureInfo.InvariantCulture.CompareInfo.GetHashCode(ReadOnlySpan<char>.Empty, CompareOptions.None));
}
[Fact]
public void GetHashCode_Span_Invalid()
{
AssertExtensions.Throws<ArgumentException>("options", () => CultureInfo.InvariantCulture.CompareInfo.GetHashCode("Test".AsSpan(), CompareOptions.StringSort));
AssertExtensions.Throws<ArgumentException>("options", () => CultureInfo.InvariantCulture.CompareInfo.GetHashCode("Test".AsSpan(), CompareOptions.Ordinal | CompareOptions.IgnoreSymbols));
AssertExtensions.Throws<ArgumentException>("options", () => CultureInfo.InvariantCulture.CompareInfo.GetHashCode("Test".AsSpan(), (CompareOptions)(-1)));
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.