context
stringlengths 2.52k
185k
| gt
stringclasses 1
value |
---|---|
// Licensed to the .NET Foundation under one or more agreements.
// See the LICENSE file in the project root for more information.
//
// System.Drawing.KnownColors
//
// Authors:
// Gonzalo Paniagua Javier (gonzalo@ximian.com)
// Peter Dennis Bartok (pbartok@novell.com)
// Sebastien Pouliot <sebastien@ximian.com>
//
// Copyright (C) 2007 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
namespace System.Drawing
{
internal static class KnownColors
{
// FindColorMatch relies on the index + 1 == KnowColor match
static internal uint[] ArgbValues = new uint[] {
0x00000000, /* 000 - Empty */
0xFFD4D0C8, /* 001 - ActiveBorder */
0xFF0054E3, /* 002 - ActiveCaption */
0xFFFFFFFF, /* 003 - ActiveCaptionText */
0xFF808080, /* 004 - AppWorkspace */
0xFFECE9D8, /* 005 - Control */
0xFFACA899, /* 006 - ControlDark */
0xFF716F64, /* 007 - ControlDarkDark */
0xFFF1EFE2, /* 008 - ControlLight */
0xFFFFFFFF, /* 009 - ControlLightLight */
0xFF000000, /* 010 - ControlText */
0xFF004E98, /* 011 - Desktop */
0xFFACA899, /* 012 - GrayText */
0xFF316AC5, /* 013 - Highlight */
0xFFFFFFFF, /* 014 - HighlightText */
0xFF000080, /* 015 - HotTrack */
0xFFD4D0C8, /* 016 - InactiveBorder */
0xFF7A96DF, /* 017 - InactiveCaption */
0xFFD8E4F8, /* 018 - InactiveCaptionText */
0xFFFFFFE1, /* 019 - Info */
0xFF000000, /* 020 - InfoText */
0xFFFFFFFF, /* 021 - Menu */
0xFF000000, /* 022 - MenuText */
0xFFD4D0C8, /* 023 - ScrollBar */
0xFFFFFFFF, /* 024 - Window */
0xFF000000, /* 025 - WindowFrame */
0xFF000000, /* 026 - WindowText */
0x00FFFFFF, /* 027 - Transparent */
0xFFF0F8FF, /* 028 - AliceBlue */
0xFFFAEBD7, /* 029 - AntiqueWhite */
0xFF00FFFF, /* 030 - Aqua */
0xFF7FFFD4, /* 031 - Aquamarine */
0xFFF0FFFF, /* 032 - Azure */
0xFFF5F5DC, /* 033 - Beige */
0xFFFFE4C4, /* 034 - Bisque */
0xFF000000, /* 035 - Black */
0xFFFFEBCD, /* 036 - BlanchedAlmond */
0xFF0000FF, /* 037 - Blue */
0xFF8A2BE2, /* 038 - BlueViolet */
0xFFA52A2A, /* 039 - Brown */
0xFFDEB887, /* 040 - BurlyWood */
0xFF5F9EA0, /* 041 - CadetBlue */
0xFF7FFF00, /* 042 - Chartreuse */
0xFFD2691E, /* 043 - Chocolate */
0xFFFF7F50, /* 044 - Coral */
0xFF6495ED, /* 045 - CornflowerBlue */
0xFFFFF8DC, /* 046 - Cornsilk */
0xFFDC143C, /* 047 - Crimson */
0xFF00FFFF, /* 048 - Cyan */
0xFF00008B, /* 049 - DarkBlue */
0xFF008B8B, /* 050 - DarkCyan */
0xFFB8860B, /* 051 - DarkGoldenrod */
0xFFA9A9A9, /* 052 - DarkGray */
0xFF006400, /* 053 - DarkGreen */
0xFFBDB76B, /* 054 - DarkKhaki */
0xFF8B008B, /* 055 - DarkMagenta */
0xFF556B2F, /* 056 - DarkOliveGreen */
0xFFFF8C00, /* 057 - DarkOrange */
0xFF9932CC, /* 058 - DarkOrchid */
0xFF8B0000, /* 059 - DarkRed */
0xFFE9967A, /* 060 - DarkSalmon */
0xFF8FBC8B, /* 061 - DarkSeaGreen */
0xFF483D8B, /* 062 - DarkSlateBlue */
0xFF2F4F4F, /* 063 - DarkSlateGray */
0xFF00CED1, /* 064 - DarkTurquoise */
0xFF9400D3, /* 065 - DarkViolet */
0xFFFF1493, /* 066 - DeepPink */
0xFF00BFFF, /* 067 - DeepSkyBlue */
0xFF696969, /* 068 - DimGray */
0xFF1E90FF, /* 069 - DodgerBlue */
0xFFB22222, /* 070 - Firebrick */
0xFFFFFAF0, /* 071 - FloralWhite */
0xFF228B22, /* 072 - ForestGreen */
0xFFFF00FF, /* 073 - Fuchsia */
0xFFDCDCDC, /* 074 - Gainsboro */
0xFFF8F8FF, /* 075 - GhostWhite */
0xFFFFD700, /* 076 - Gold */
0xFFDAA520, /* 077 - Goldenrod */
0xFF808080, /* 078 - Gray */
0xFF008000, /* 079 - Green */
0xFFADFF2F, /* 080 - GreenYellow */
0xFFF0FFF0, /* 081 - Honeydew */
0xFFFF69B4, /* 082 - HotPink */
0xFFCD5C5C, /* 083 - IndianRed */
0xFF4B0082, /* 084 - Indigo */
0xFFFFFFF0, /* 085 - Ivory */
0xFFF0E68C, /* 086 - Khaki */
0xFFE6E6FA, /* 087 - Lavender */
0xFFFFF0F5, /* 088 - LavenderBlush */
0xFF7CFC00, /* 089 - LawnGreen */
0xFFFFFACD, /* 090 - LemonChiffon */
0xFFADD8E6, /* 091 - LightBlue */
0xFFF08080, /* 092 - LightCoral */
0xFFE0FFFF, /* 093 - LightCyan */
0xFFFAFAD2, /* 094 - LightGoldenrodYellow */
0xFFD3D3D3, /* 095 - LightGray */
0xFF90EE90, /* 096 - LightGreen */
0xFFFFB6C1, /* 097 - LightPink */
0xFFFFA07A, /* 098 - LightSalmon */
0xFF20B2AA, /* 099 - LightSeaGreen */
0xFF87CEFA, /* 100 - LightSkyBlue */
0xFF778899, /* 101 - LightSlateGray */
0xFFB0C4DE, /* 102 - LightSteelBlue */
0xFFFFFFE0, /* 103 - LightYellow */
0xFF00FF00, /* 104 - Lime */
0xFF32CD32, /* 105 - LimeGreen */
0xFFFAF0E6, /* 106 - Linen */
0xFFFF00FF, /* 107 - Magenta */
0xFF800000, /* 108 - Maroon */
0xFF66CDAA, /* 109 - MediumAquamarine */
0xFF0000CD, /* 110 - MediumBlue */
0xFFBA55D3, /* 111 - MediumOrchid */
0xFF9370DB, /* 112 - MediumPurple */
0xFF3CB371, /* 113 - MediumSeaGreen */
0xFF7B68EE, /* 114 - MediumSlateBlue */
0xFF00FA9A, /* 115 - MediumSpringGreen */
0xFF48D1CC, /* 116 - MediumTurquoise */
0xFFC71585, /* 117 - MediumVioletRed */
0xFF191970, /* 118 - MidnightBlue */
0xFFF5FFFA, /* 119 - MintCream */
0xFFFFE4E1, /* 120 - MistyRose */
0xFFFFE4B5, /* 121 - Moccasin */
0xFFFFDEAD, /* 122 - NavajoWhite */
0xFF000080, /* 123 - Navy */
0xFFFDF5E6, /* 124 - OldLace */
0xFF808000, /* 125 - Olive */
0xFF6B8E23, /* 126 - OliveDrab */
0xFFFFA500, /* 127 - Orange */
0xFFFF4500, /* 128 - OrangeRed */
0xFFDA70D6, /* 129 - Orchid */
0xFFEEE8AA, /* 130 - PaleGoldenrod */
0xFF98FB98, /* 131 - PaleGreen */
0xFFAFEEEE, /* 132 - PaleTurquoise */
0xFFDB7093, /* 133 - PaleVioletRed */
0xFFFFEFD5, /* 134 - PapayaWhip */
0xFFFFDAB9, /* 135 - PeachPuff */
0xFFCD853F, /* 136 - Peru */
0xFFFFC0CB, /* 137 - Pink */
0xFFDDA0DD, /* 138 - Plum */
0xFFB0E0E6, /* 139 - PowderBlue */
0xFF800080, /* 140 - Purple */
0xFFFF0000, /* 141 - Red */
0xFFBC8F8F, /* 142 - RosyBrown */
0xFF4169E1, /* 143 - RoyalBlue */
0xFF8B4513, /* 144 - SaddleBrown */
0xFFFA8072, /* 145 - Salmon */
0xFFF4A460, /* 146 - SandyBrown */
0xFF2E8B57, /* 147 - SeaGreen */
0xFFFFF5EE, /* 148 - SeaShell */
0xFFA0522D, /* 149 - Sienna */
0xFFC0C0C0, /* 150 - Silver */
0xFF87CEEB, /* 151 - SkyBlue */
0xFF6A5ACD, /* 152 - SlateBlue */
0xFF708090, /* 153 - SlateGray */
0xFFFFFAFA, /* 154 - Snow */
0xFF00FF7F, /* 155 - SpringGreen */
0xFF4682B4, /* 156 - SteelBlue */
0xFFD2B48C, /* 157 - Tan */
0xFF008080, /* 158 - Teal */
0xFFD8BFD8, /* 159 - Thistle */
0xFFFF6347, /* 160 - Tomato */
0xFF40E0D0, /* 161 - Turquoise */
0xFFEE82EE, /* 162 - Violet */
0xFFF5DEB3, /* 163 - Wheat */
0xFFFFFFFF, /* 164 - White */
0xFFF5F5F5, /* 165 - WhiteSmoke */
0xFFFFFF00, /* 166 - Yellow */
0xFF9ACD32, /* 167 - YellowGreen */
0xFFECE9D8, /* 168 - ButtonFace */
0xFFFFFFFF, /* 169 - ButtonHighlight */
0xFFACA899, /* 170 - ButtonShadow */
0xFF3D95FF, /* 171 - GradientActiveCaption */
0xFF9DB9EB, /* 172 - GradientInactiveCaption */
0xFFECE9D8, /* 173 - MenuBar */
0xFF316AC5, /* 174 - MenuHighlight */
};
#if !MONOTOUCH && !MONOMAC && SUPPORTS_WINDOWS_COLORS
static KnownColors ()
{
if (GDIPlus.RunningOnWindows ()) {
// If we're on Windows we should behave like MS and pull the colors
RetrieveWindowsSystemColors ();
}
// note: Mono's SWF Theme class will call the static Update method to apply
// correct system colors outside Windows
}
// Windows values are in BGR format and without alpha
// so we force it to opaque (or everything will be transparent) and reverse B and R
static uint GetSysColor (GetSysColorIndex index)
{
uint bgr = SafeNativeMethods.Gdip.Win32GetSysColor (index);
return 0xFF000000 | (bgr & 0xFF) << 16 | (bgr & 0xFF00) | (bgr >> 16);
}
static void RetrieveWindowsSystemColors ()
{
ArgbValues [(int)KnownColor.ActiveBorder] = GetSysColor (GetSysColorIndex.COLOR_ACTIVEBORDER);
ArgbValues [(int)KnownColor.ActiveCaption] = GetSysColor (GetSysColorIndex.COLOR_ACTIVECAPTION);
ArgbValues [(int)KnownColor.ActiveCaptionText] = GetSysColor (GetSysColorIndex.COLOR_CAPTIONTEXT);
ArgbValues [(int)KnownColor.AppWorkspace] = GetSysColor (GetSysColorIndex.COLOR_APPWORKSPACE);
ArgbValues [(int)KnownColor.Control] = GetSysColor (GetSysColorIndex.COLOR_BTNFACE);
ArgbValues [(int)KnownColor.ControlDark] = GetSysColor (GetSysColorIndex.COLOR_BTNSHADOW);
ArgbValues [(int)KnownColor.ControlDarkDark] = GetSysColor (GetSysColorIndex.COLOR_3DDKSHADOW);
ArgbValues [(int)KnownColor.ControlLight] = GetSysColor (GetSysColorIndex.COLOR_3DLIGHT);
ArgbValues [(int)KnownColor.ControlLightLight] = GetSysColor (GetSysColorIndex.COLOR_BTNHIGHLIGHT);
ArgbValues [(int)KnownColor.ControlText] = GetSysColor (GetSysColorIndex.COLOR_BTNTEXT);
ArgbValues [(int)KnownColor.Desktop] = GetSysColor (GetSysColorIndex.COLOR_DESKTOP);
ArgbValues [(int)KnownColor.GrayText] = GetSysColor (GetSysColorIndex.COLOR_GRAYTEXT);
ArgbValues [(int)KnownColor.Highlight] = GetSysColor (GetSysColorIndex.COLOR_HIGHLIGHT);
ArgbValues [(int)KnownColor.HighlightText] = GetSysColor (GetSysColorIndex.COLOR_HIGHLIGHTTEXT);
ArgbValues [(int)KnownColor.HotTrack] = GetSysColor (GetSysColorIndex.COLOR_HOTLIGHT);
ArgbValues [(int)KnownColor.InactiveBorder] = GetSysColor (GetSysColorIndex.COLOR_INACTIVEBORDER);
ArgbValues [(int)KnownColor.InactiveCaption] = GetSysColor (GetSysColorIndex.COLOR_INACTIVECAPTION);
ArgbValues [(int)KnownColor.InactiveCaptionText] = GetSysColor (GetSysColorIndex.COLOR_INACTIVECAPTIONTEXT);
ArgbValues [(int)KnownColor.Info] = GetSysColor (GetSysColorIndex.COLOR_INFOBK);
ArgbValues [(int)KnownColor.InfoText] = GetSysColor (GetSysColorIndex.COLOR_INFOTEXT);
ArgbValues [(int)KnownColor.Menu] = GetSysColor (GetSysColorIndex.COLOR_MENU);
ArgbValues [(int)KnownColor.MenuText] = GetSysColor (GetSysColorIndex.COLOR_MENUTEXT);
ArgbValues [(int)KnownColor.ScrollBar] = GetSysColor (GetSysColorIndex.COLOR_SCROLLBAR);
ArgbValues [(int)KnownColor.Window] = GetSysColor (GetSysColorIndex.COLOR_WINDOW);
ArgbValues [(int)KnownColor.WindowFrame] = GetSysColor (GetSysColorIndex.COLOR_WINDOWFRAME);
ArgbValues [(int)KnownColor.WindowText] = GetSysColor (GetSysColorIndex.COLOR_WINDOWTEXT);
ArgbValues [(int)KnownColor.ButtonFace] = GetSysColor (GetSysColorIndex.COLOR_BTNFACE);
ArgbValues [(int)KnownColor.ButtonHighlight] = GetSysColor (GetSysColorIndex.COLOR_BTNHIGHLIGHT);
ArgbValues [(int)KnownColor.ButtonShadow] = GetSysColor (GetSysColorIndex.COLOR_BTNSHADOW);
ArgbValues [(int)KnownColor.GradientActiveCaption] = GetSysColor (GetSysColorIndex.COLOR_GRADIENTACTIVECAPTION);
ArgbValues [(int)KnownColor.GradientInactiveCaption] = GetSysColor (GetSysColorIndex.COLOR_GRADIENTINACTIVECAPTION);
ArgbValues [(int)KnownColor.MenuBar] = GetSysColor (GetSysColorIndex.COLOR_MENUBAR);
ArgbValues [(int)KnownColor.MenuHighlight] = GetSysColor (GetSysColorIndex.COLOR_MENUHIGHLIGHT);
}
#endif
public static Color FromKnownColor(KnownColor kc)
{
return ColorUtil.FromKnownColor(kc);
}
public static string GetName(short kc)
{
switch (kc)
{
case 1:
return "ActiveBorder";
case 2:
return "ActiveCaption";
case 3:
return "ActiveCaptionText";
case 4:
return "AppWorkspace";
case 5:
return "Control";
case 6:
return "ControlDark";
case 7:
return "ControlDarkDark";
case 8:
return "ControlLight";
case 9:
return "ControlLightLight";
case 10:
return "ControlText";
case 11:
return "Desktop";
case 12:
return "GrayText";
case 13:
return "Highlight";
case 14:
return "HighlightText";
case 15:
return "HotTrack";
case 16:
return "InactiveBorder";
case 17:
return "InactiveCaption";
case 18:
return "InactiveCaptionText";
case 19:
return "Info";
case 20:
return "InfoText";
case 21:
return "Menu";
case 22:
return "MenuText";
case 23:
return "ScrollBar";
case 24:
return "Window";
case 25:
return "WindowFrame";
case 26:
return "WindowText";
case 27:
return "Transparent";
case 28:
return "AliceBlue";
case 29:
return "AntiqueWhite";
case 30:
return "Aqua";
case 31:
return "Aquamarine";
case 32:
return "Azure";
case 33:
return "Beige";
case 34:
return "Bisque";
case 35:
return "Black";
case 36:
return "BlanchedAlmond";
case 37:
return "Blue";
case 38:
return "BlueViolet";
case 39:
return "Brown";
case 40:
return "BurlyWood";
case 41:
return "CadetBlue";
case 42:
return "Chartreuse";
case 43:
return "Chocolate";
case 44:
return "Coral";
case 45:
return "CornflowerBlue";
case 46:
return "Cornsilk";
case 47:
return "Crimson";
case 48:
return "Cyan";
case 49:
return "DarkBlue";
case 50:
return "DarkCyan";
case 51:
return "DarkGoldenrod";
case 52:
return "DarkGray";
case 53:
return "DarkGreen";
case 54:
return "DarkKhaki";
case 55:
return "DarkMagenta";
case 56:
return "DarkOliveGreen";
case 57:
return "DarkOrange";
case 58:
return "DarkOrchid";
case 59:
return "DarkRed";
case 60:
return "DarkSalmon";
case 61:
return "DarkSeaGreen";
case 62:
return "DarkSlateBlue";
case 63:
return "DarkSlateGray";
case 64:
return "DarkTurquoise";
case 65:
return "DarkViolet";
case 66:
return "DeepPink";
case 67:
return "DeepSkyBlue";
case 68:
return "DimGray";
case 69:
return "DodgerBlue";
case 70:
return "Firebrick";
case 71:
return "FloralWhite";
case 72:
return "ForestGreen";
case 73:
return "Fuchsia";
case 74:
return "Gainsboro";
case 75:
return "GhostWhite";
case 76:
return "Gold";
case 77:
return "Goldenrod";
case 78:
return "Gray";
case 79:
return "Green";
case 80:
return "GreenYellow";
case 81:
return "Honeydew";
case 82:
return "HotPink";
case 83:
return "IndianRed";
case 84:
return "Indigo";
case 85:
return "Ivory";
case 86:
return "Khaki";
case 87:
return "Lavender";
case 88:
return "LavenderBlush";
case 89:
return "LawnGreen";
case 90:
return "LemonChiffon";
case 91:
return "LightBlue";
case 92:
return "LightCoral";
case 93:
return "LightCyan";
case 94:
return "LightGoldenrodYellow";
case 95:
return "LightGray";
case 96:
return "LightGreen";
case 97:
return "LightPink";
case 98:
return "LightSalmon";
case 99:
return "LightSeaGreen";
case 100:
return "LightSkyBlue";
case 101:
return "LightSlateGray";
case 102:
return "LightSteelBlue";
case 103:
return "LightYellow";
case 104:
return "Lime";
case 105:
return "LimeGreen";
case 106:
return "Linen";
case 107:
return "Magenta";
case 108:
return "Maroon";
case 109:
return "MediumAquamarine";
case 110:
return "MediumBlue";
case 111:
return "MediumOrchid";
case 112:
return "MediumPurple";
case 113:
return "MediumSeaGreen";
case 114:
return "MediumSlateBlue";
case 115:
return "MediumSpringGreen";
case 116:
return "MediumTurquoise";
case 117:
return "MediumVioletRed";
case 118:
return "MidnightBlue";
case 119:
return "MintCream";
case 120:
return "MistyRose";
case 121:
return "Moccasin";
case 122:
return "NavajoWhite";
case 123:
return "Navy";
case 124:
return "OldLace";
case 125:
return "Olive";
case 126:
return "OliveDrab";
case 127:
return "Orange";
case 128:
return "OrangeRed";
case 129:
return "Orchid";
case 130:
return "PaleGoldenrod";
case 131:
return "PaleGreen";
case 132:
return "PaleTurquoise";
case 133:
return "PaleVioletRed";
case 134:
return "PapayaWhip";
case 135:
return "PeachPuff";
case 136:
return "Peru";
case 137:
return "Pink";
case 138:
return "Plum";
case 139:
return "PowderBlue";
case 140:
return "Purple";
case 141:
return "Red";
case 142:
return "RosyBrown";
case 143:
return "RoyalBlue";
case 144:
return "SaddleBrown";
case 145:
return "Salmon";
case 146:
return "SandyBrown";
case 147:
return "SeaGreen";
case 148:
return "SeaShell";
case 149:
return "Sienna";
case 150:
return "Silver";
case 151:
return "SkyBlue";
case 152:
return "SlateBlue";
case 153:
return "SlateGray";
case 154:
return "Snow";
case 155:
return "SpringGreen";
case 156:
return "SteelBlue";
case 157:
return "Tan";
case 158:
return "Teal";
case 159:
return "Thistle";
case 160:
return "Tomato";
case 161:
return "Turquoise";
case 162:
return "Violet";
case 163:
return "Wheat";
case 164:
return "White";
case 165:
return "WhiteSmoke";
case 166:
return "Yellow";
case 167:
return "YellowGreen";
case 168:
return "ButtonFace";
case 169:
return "ButtonHighlight";
case 170:
return "ButtonShadow";
case 171:
return "GradientActiveCaption";
case 172:
return "GradientInactiveCaption";
case 173:
return "MenuBar";
case 174:
return "MenuHighlight";
default:
return String.Empty;
}
}
public static string GetName(KnownColor kc)
{
return GetName((short)kc);
}
// FIXME: Linear scan
public static Color FindColorMatch(Color c)
{
uint argb = (uint)c.ToArgb();
// 1-based
const int first_real_color_index = (int)KnownColor.AliceBlue;
const int last_real_color_index = (int)KnownColor.YellowGreen;
for (int i = first_real_color_index - 1; i < last_real_color_index; i++)
{
if (argb == KnownColors.ArgbValues[i])
return KnownColors.FromKnownColor((KnownColor)i);
}
return Color.Empty;
}
// When this method is called, we teach any new color(s) to the Color class
// NOTE: This is called (reflection) by System.Windows.Forms.Theme (this isn't dead code)
public static void Update(int knownColor, int color)
{
ArgbValues[knownColor] = (uint)color;
}
}
}
| |
/*
* Copyright (c) InWorldz Halcyon Developers
* Copyright (c) Contributors, http://opensimulator.org/
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using Nwc.XmlRpc;
using System.Net;
using System.Net.Sockets;
using System.Reflection;
using System.Security.Authentication;
using log4net;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Communications;
using OpenSim.Framework.Servers;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
namespace OpenSim.Client.Linden
{
/// <summary>
/// Handles login user (expect user) and logoff user messages from the remote LL login server
/// </summary>
public class LLProxyLoginModule : IRegionModule
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
protected bool RegionLoginsEnabled
{
get
{
if (m_firstScene != null)
{
return m_firstScene.CommsManager.GridService.RegionLoginsEnabled;
}
else
{
return false;
}
}
}
private List<Scene> m_scenes = new List<Scene>();
private Scene m_firstScene;
private string _gridSendKey;
private bool m_enabled = false; // Module is only enabled if running in grid mode
#region IRegionModule Members
public void Initialise(Scene scene, IConfigSource source)
{
if (m_firstScene == null)
{
m_firstScene = scene;
IConfig startupConfig = source.Configs["Startup"];
if (startupConfig != null)
{
m_enabled = startupConfig.GetBoolean("gridmode", false);
}
IConfig netConfig = source.Configs["Network"];
if (netConfig != null)
{
_gridSendKey = netConfig.GetString("grid_send_key");
}
else
{
throw new Exception("LLProxyLoginModule: Network configuration not found");
}
if (m_enabled)
{
AddHttpHandlers();
}
}
if (m_enabled)
{
AddScene(scene);
}
}
public void PostInitialise()
{
}
public void Close()
{
}
public string Name
{
get { return "LLProxyLoginModule"; }
}
public bool IsSharedModule
{
get { return true; }
}
#endregion
/// <summary>
/// Adds "expect_user" and "logoff_user" xmlrpc method handlers
/// </summary>
protected void AddHttpHandlers()
{
//we will add our handlers to the first scene we received, as all scenes share a http server. But will this ever change?
m_firstScene.CommsManager.HttpServer.AddXmlRPCHandler("expect_user", ExpectUser);
m_firstScene.CommsManager.HttpServer.AddXmlRPCHandler("logoff_user", LogOffUser);
// New Style service interface
m_firstScene.CommsManager.HttpServer.AddStreamHandler(new XmlRpcStreamHandler("POST", Util.XmlRpcRequestPrefix("expect_user"), ExpectUser));
m_firstScene.CommsManager.HttpServer.AddStreamHandler(new XmlRpcStreamHandler("POST", Util.XmlRpcRequestPrefix("logoff_user"), LogOffUser));
}
protected void AddScene(Scene scene)
{
lock (m_scenes)
{
if (!m_scenes.Contains(scene))
{
m_scenes.Add(scene);
}
}
}
/// <summary>
/// Received from the user server when a user starts logging in. This call allows
/// the region to prepare for direct communication from the client. Sends back an empty
/// xmlrpc response on completion.
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
public XmlRpcResponse ExpectUser(XmlRpcRequest request, IPEndPoint remoteClient)
{
XmlRpcResponse resp = new XmlRpcResponse();
//check the send key
if (request.Params.Count < 2 || (string)request.Params[1] != _gridSendKey)
{
Hashtable respdata = new Hashtable();
respdata["success"] = "FALSE";
respdata["reason"] = "Grid authorization failed";
resp.Value = respdata;
return resp;
}
Hashtable requestData = (Hashtable)request.Params[0];
AgentCircuitData agentData = new AgentCircuitData();
agentData.SessionID = new UUID((string)requestData["session_id"]);
agentData.SecureSessionID = new UUID((string)requestData["secure_session_id"]);
agentData.FirstName = (string)requestData["firstname"];
agentData.LastName = (string)requestData["lastname"];
agentData.AgentID = new UUID((string)requestData["agent_id"]);
agentData.CircuitCode = Convert.ToUInt32(requestData["circuit_code"]);
agentData.CapsPath = (string)requestData["caps_path"];
ulong regionHandle = Convert.ToUInt64((string)requestData["regionhandle"]);
if (requestData.ContainsKey("client_version"))
agentData.ClientVersion = (string)requestData["client_version"];
else
m_log.Warn("[CLIENT]: ExpectUser missing client_version for " + agentData.AgentID.ToString());
// Appearance
if (requestData.ContainsKey("appearance"))
agentData.Appearance = new AvatarAppearance((Hashtable)requestData["appearance"]);
m_log.DebugFormat(
"[CLIENT]: Incoming connection from {0} {1} {2}, circuit {3}: {4}",
agentData.FirstName, agentData.LastName, agentData.AgentID, agentData.CircuitCode, agentData.ClientVersion);
if (requestData.ContainsKey("child_agent") && requestData["child_agent"].Equals("1"))
{
//m_log.Debug("[CLIENT]: Child agent detected");
agentData.child = true;
}
else
{
//m_log.Debug("[CLIENT]: Main agent detected");
agentData.startpos =
new Vector3((float)Convert.ToDouble((string)requestData["startpos_x"]),
(float)Convert.ToDouble((string)requestData["startpos_y"]),
(float)Convert.ToDouble((string)requestData["startpos_z"]));
agentData.child = false;
}
if (!RegionLoginsEnabled)
{
m_log.InfoFormat(
"[CLIENT]: Denying access for user {0} {1} because region login is currently disabled",
agentData.FirstName, agentData.LastName);
Hashtable respdata = new Hashtable();
respdata["success"] = "FALSE";
respdata["reason"] = "region login currently disabled";
resp.Value = respdata;
}
else
{
bool success = false;
string denyMess = "";
Scene scene;
if (TryGetRegion(regionHandle, out scene))
{
if (scene.IsBlacklistedUser(agentData.AgentID))
{
denyMess = "User is blacklisted from this region";
m_log.InfoFormat(
"[CLIENT]: Denying access for user {0} {1} because user is blacklisted",
agentData.FirstName, agentData.LastName);
}
else
if (scene.RegionInfo.EstateSettings.IsBanned(agentData.AgentID))
{
denyMess = "User is banned from this region";
m_log.InfoFormat(
"[CLIENT]: Denying access for user {0} {1} because user is banned",
agentData.FirstName, agentData.LastName);
}
else
{
string reason;
if (scene.NewUserLogin(agentData, out reason))
{
success = true;
}
else
{
denyMess = String.Format("Login refused by region: {0}", reason);
m_log.InfoFormat(
"[CLIENT]: Denying access for user {0} {1} because user connection was refused by the region",
agentData.FirstName, agentData.LastName);
}
}
}
else
{
denyMess = "Region not found";
}
if (success)
{
Hashtable respdata = new Hashtable();
respdata["success"] = "TRUE";
resp.Value = respdata;
}
else
{
Hashtable respdata = new Hashtable();
respdata["success"] = "FALSE";
respdata["reason"] = denyMess;
resp.Value = respdata;
}
}
return resp;
}
// Grid Request Processing
/// <summary>
/// Ooops, our Agent must be dead if we're getting this request!
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
public XmlRpcResponse LogOffUser(XmlRpcRequest request, IPEndPoint remoteClient)
{
m_log.Debug("[CONNECTION DEBUGGING]: LogOff User Called");
Hashtable requestData = (Hashtable)request.Params[0];
string message = (string)requestData["message"];
UUID agentID = UUID.Zero;
UUID RegionSecret = UUID.Zero;
UUID.TryParse((string)requestData["agent_id"], out agentID);
UUID.TryParse((string)requestData["region_secret"], out RegionSecret);
ulong regionHandle = Convert.ToUInt64((string)requestData["regionhandle"]);
Scene scene;
if (TryGetRegion(regionHandle, out scene))
{
scene.HandleLogOffUserFromGrid(agentID, RegionSecret, message);
}
return new XmlRpcResponse();
}
protected bool TryGetRegion(ulong regionHandle, out Scene scene)
{
lock (m_scenes)
{
foreach (Scene nextScene in m_scenes)
{
if (nextScene.RegionInfo.RegionHandle == regionHandle)
{
scene = nextScene;
return true;
}
}
}
scene = null;
return false;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Baseline;
using Marten.Events.Querying;
using Marten.Internal.Sessions;
using Marten.Internal.Storage;
using Marten.Linq;
using Marten.Linq.QueryHandlers;
using Marten.Storage;
#nullable enable
namespace Marten.Events
{
internal class QueryEventStore: IQueryEventStore
{
private readonly QuerySession _session;
private readonly ITenant _tenant;
private readonly DocumentStore _store;
public QueryEventStore(QuerySession session, DocumentStore store, ITenant tenant)
{
_session = session;
_store = store;
_tenant = tenant;
}
public IReadOnlyList<IEvent> FetchStream(Guid streamId, long version = 0, DateTime? timestamp = null, long fromVersion = 0)
{
var selector = _store.Events.EnsureAsGuidStorage(_session);
var statement = new EventStatement(selector)
{
StreamId = streamId, Version = version, Timestamp = timestamp, TenantId = _tenant.TenantId, FromVersion = fromVersion
};
IQueryHandler<IReadOnlyList<IEvent>> handler = new ListQueryHandler<IEvent>(statement, selector);
return _session.ExecuteHandler(handler);
}
public Task<IReadOnlyList<IEvent>> FetchStreamAsync(Guid streamId, long version = 0, DateTime? timestamp = null, long fromVersion = 0, CancellationToken token = default)
{
var selector = _store.Events.EnsureAsGuidStorage(_session);
var statement = new EventStatement(selector)
{
StreamId = streamId, Version = version, Timestamp = timestamp, TenantId = _tenant.TenantId, FromVersion = fromVersion
};
IQueryHandler<IReadOnlyList<IEvent>> handler = new ListQueryHandler<IEvent>(statement, selector);
return _session.ExecuteHandlerAsync(handler, token);
}
public IReadOnlyList<IEvent> FetchStream(string streamKey, long version = 0, DateTime? timestamp = null, long fromVersion = 0)
{
var selector = _store.Events.EnsureAsStringStorage(_session);
var statement = new EventStatement(selector)
{
StreamKey = streamKey, Version = version, Timestamp = timestamp, TenantId = _tenant.TenantId, FromVersion = fromVersion
};
IQueryHandler<IReadOnlyList<IEvent>> handler = new ListQueryHandler<IEvent>(statement, selector);
return _session.ExecuteHandler(handler);
}
public Task<IReadOnlyList<IEvent>> FetchStreamAsync(string streamKey, long version = 0, DateTime? timestamp = null, long fromVersion = 0, CancellationToken token = default)
{
var selector = _store.Events.EnsureAsStringStorage(_session);
var statement = new EventStatement(selector)
{
StreamKey = streamKey, Version = version, Timestamp = timestamp, TenantId = _tenant.TenantId, FromVersion = fromVersion
};
IQueryHandler<IReadOnlyList<IEvent>> handler = new ListQueryHandler<IEvent>(statement, selector);
return _session.ExecuteHandlerAsync(handler, token);
}
public T? AggregateStream<T>(Guid streamId, long version = 0, DateTime? timestamp = null, T? state = null, long fromVersion = 0) where T : class
{
var events = FetchStream(streamId, version, timestamp, fromVersion);
var aggregator = _store.Options.Projections.AggregatorFor<T>();
if (!events.Any()) return null;
var aggregate = aggregator.Build(events, _session, state);
var storage = _session.StorageFor<T>();
if (storage is IDocumentStorage<T, Guid> s) s.SetIdentity(aggregate, streamId);
return aggregate;
}
public async Task<T?> AggregateStreamAsync<T>(Guid streamId, long version = 0, DateTime? timestamp = null,
T? state = null, long fromVersion = 0, CancellationToken token = default) where T : class
{
var events = await FetchStreamAsync(streamId, version, timestamp, fromVersion, token).ConfigureAwait(false);
if (!events.Any()) return null;
var aggregator = _store.Options.Projections.AggregatorFor<T>();
var aggregate = await aggregator.BuildAsync(events, _session, state, token).ConfigureAwait(false);
if (aggregate == null) return null;
var storage = _session.StorageFor<T>();
if (storage is IDocumentStorage<T, Guid> s) s.SetIdentity(aggregate, streamId);
return aggregate;
}
public T? AggregateStream<T>(string streamKey, long version = 0, DateTime? timestamp = null, T? state = null, long fromVersion = 0) where T : class
{
var events = FetchStream(streamKey, version, timestamp, fromVersion);
if (!events.Any())
{
return null;
}
var aggregator = _store.Options.Projections.AggregatorFor<T>();
var aggregate = aggregator.Build(events, _session, state);
var storage = _session.StorageFor<T>();
if (storage is IDocumentStorage<T, string> s) s.SetIdentity(aggregate, streamKey);
return aggregate;
}
public async Task<T?> AggregateStreamAsync<T>(string streamKey, long version = 0, DateTime? timestamp = null,
T? state = null, long fromVersion = 0, CancellationToken token = default) where T : class
{
var events = await FetchStreamAsync(streamKey, version, timestamp, fromVersion, token).ConfigureAwait(false);
if (!events.Any())
{
return null;
}
var aggregator = _store.Options.Projections.AggregatorFor<T>();
var aggregate = await aggregator.BuildAsync(events, _session, state, token).ConfigureAwait(false);
var storage = _session.StorageFor<T>();
if (storage is IDocumentStorage<T, string> s) s.SetIdentity(aggregate, streamKey);
return aggregate;
}
public IMartenQueryable<T> QueryRawEventDataOnly<T>()
{
_tenant.EnsureStorageExists(typeof(StreamAction));
_store.Events.AddEventType(typeof(T));
return _session.Query<T>();
}
public IMartenQueryable<IEvent> QueryAllRawEvents()
{
_tenant.EnsureStorageExists(typeof(StreamAction));
return _session.Query<IEvent>();
}
public IEvent<T> Load<T>(Guid id) where T : class
{
_tenant.EnsureStorageExists(typeof(StreamAction));
_store.Events.AddEventType(typeof(T));
return Load(id).As<Event<T>>();
}
public async Task<IEvent<T>> LoadAsync<T>(Guid id, CancellationToken token = default) where T : class
{
await _tenant.EnsureStorageExistsAsync(typeof(StreamAction), token).ConfigureAwait(false);
_store.Events.AddEventType(typeof(T));
return (await LoadAsync(id, token).ConfigureAwait(false)).As<Event<T>>();
}
public IEvent Load(Guid id)
{
var handler = new SingleEventQueryHandler(id, _session.EventStorage());
return _session.ExecuteHandler(handler);
}
public Task<IEvent> LoadAsync(Guid id, CancellationToken token = default)
{
_tenant.EnsureStorageExists(typeof(StreamAction));
var handler = new SingleEventQueryHandler(id, _session.EventStorage());
return _session.ExecuteHandlerAsync(handler, token);
}
public StreamState FetchStreamState(Guid streamId)
{
var handler = _tenant.EventStorage().QueryForStream(StreamAction.ForReference(streamId, _tenant));
return _session.ExecuteHandler(handler);
}
public Task<StreamState> FetchStreamStateAsync(Guid streamId, CancellationToken token = default)
{
var handler = _tenant.EventStorage().QueryForStream(StreamAction.ForReference(streamId, _tenant));
return _session.ExecuteHandlerAsync(handler, token);
}
public StreamState FetchStreamState(string streamKey)
{
var handler = _tenant.EventStorage().QueryForStream(StreamAction.ForReference(streamKey, _tenant));
return _session.ExecuteHandler(handler);
}
public Task<StreamState> FetchStreamStateAsync(string streamKey, CancellationToken token = default)
{
var handler = _tenant.EventStorage().QueryForStream(StreamAction.ForReference(streamKey, _tenant));
return _session.ExecuteHandlerAsync(handler, token);
}
}
}
| |
using System;
using System.Collections.Generic;
#if !SILVERLIGHT
using System.Drawing;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;
#endif
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Threading;
using Dicom.Imaging.Algorithms;
using Dicom.Imaging.LUT;
using Dicom.Imaging.Render;
using Dicom.IO;
namespace Dicom.Imaging.Render {
/// <summary>
/// The Image Graphic implementation of <seealso cref="IGraphic"/>
/// </summary>
public class ImageGraphic : IGraphic {
#region Protected Members
protected IPixelData _originalData;
protected IPixelData _scaledData;
protected PinnedIntArray _pixels;
#if SILVERLIGHT
protected WriteableBitmap _bitmap;
#else
private const int DPI = 96;
protected BitmapSource _bitmapSource;
protected Bitmap _bitmap;
#endif
protected double _scaleFactor;
protected int _rotation;
protected bool _flipX;
protected bool _flipY;
protected int _offsetX;
protected int _offsetY;
protected int _zorder;
protected bool _applyLut;
protected List<OverlayGraphic> _overlays;
#endregion
#region Public Properties
/// <summary>
/// Number of pixel componenets (samples)
/// </summary>
public int Components {
get { return OriginalData.Components; }
}
/// <summary>
/// Original pixel data
/// </summary>
public IPixelData OriginalData {
get { return _originalData; }
}
public int OriginalWidth {
get { return _originalData.Width; }
}
public int OriginalHeight {
get { return _originalData.Height; }
}
public int OriginalOffsetX {
get { return _offsetX; }
}
public int OriginalOffsetY {
get { return _offsetY; }
}
public double ScaleFactor {
get { return _scaleFactor; }
}
/// <summary>
/// Scaled pixel data
/// </summary>
public IPixelData ScaledData {
get {
if (_scaledData == null) {
if (Math.Abs(_scaleFactor - 1.0) <= Double.Epsilon)
_scaledData = _originalData;
else
_scaledData = OriginalData.Rescale(_scaleFactor);
}
return _scaledData;
}
}
public int ScaledWidth {
get { return ScaledData.Width; }
}
public int ScaledHeight {
get { return ScaledData.Height; }
}
public int ScaledOffsetX {
get { return (int)(_offsetX * _scaleFactor); }
}
public int ScaledOffsetY {
get { return (int)(_offsetY * _scaleFactor); }
}
public int ZOrder {
get { return _zorder; }
set { _zorder = value; }
}
#endregion
#region Public Constructors
/// <summary>
/// Initialize new instance of <seealso cref="ImageGraphic"/>
/// </summary>
/// <param name="pixelData">Pixel data</param>
public ImageGraphic(IPixelData pixelData) : this() {
_originalData = pixelData;
Scale(1.0);
}
/// <summary>
/// Default constructor
/// </summary>
protected ImageGraphic() {
_zorder = 255;
_applyLut = true;
_overlays = new List<OverlayGraphic>();
}
#endregion
#region Public Members
/// <summary>
/// Add overlay to render over the resulted image
/// </summary>
/// <param name="overlay">Overlay graphic </param>
public void AddOverlay(OverlayGraphic overlay) {
_overlays.Add(overlay);
overlay.Scale(_scaleFactor);
}
public void Reset() {
Scale(1.0);
_rotation = 0;
_flipX = false;
_flipY = false;
}
public void Scale(double scale) {
if (Math.Abs(scale - _scaleFactor) <= Double.Epsilon)
return;
_scaleFactor = scale;
if (_bitmap != null) {
_scaledData = null;
_pixels.Dispose();
_pixels = null;
_bitmap = null;
}
foreach (var overlay in _overlays) {
overlay.Scale(scale);
}
}
public void BestFit(int width, int height) {
double xF = (double)width / (double)OriginalWidth;
double yF = (double)height / (double)OriginalHeight;
Scale(Math.Min(xF, yF));
}
public void Rotate(int angle) {
if (angle > 0) {
if (angle <= 90)
_rotation += 90;
else if (angle <= 180)
_rotation += 180;
else if (angle <= 270)
_rotation += 270;
} else if (angle < 0) {
if (angle >= -90)
_rotation -= 90;
else if (angle >= -180)
_rotation -= 180;
else if (angle >= -270)
_rotation -= 270;
}
if (angle != 0) {
if (_rotation >= 360)
_rotation -= 360;
else if (_rotation < 0)
_rotation += 360;
}
}
public void FlipX() {
_flipX = !_flipX;
}
public void FlipY() {
_flipY = !_flipY;
}
public void Transform(double scale, int rotation, bool flipx, bool flipy) {
Scale(scale);
Rotate(rotation);
_flipX = flipx;
_flipY = flipy;
}
#if SILVERLIGHT
public BitmapSource RenderImageSource(ILUT lut)
{
bool render = false;
if (_bitmap == null) {
_pixels = new PinnedIntArray(ScaledData.Width * ScaledData.Height);
_bitmap = new WriteableBitmap(ScaledData.Width, ScaledData.Height);
render = true;
}
if (_applyLut && lut != null && !lut.IsValid) {
lut.Recalculate();
render = true;
}
if (render) {
ScaledData.Render((_applyLut ? lut : null), _pixels.Data);
foreach (var overlay in _overlays) {
overlay.Render(_pixels.Data, ScaledData.Width, ScaledData.Height);
}
}
MultiThread.For(0, _pixels.Count, delegate(int i) { _bitmap.Pixels[i] = _pixels.Data[i]; });
_bitmap.Rotate(_rotation);
if (_flipX) _bitmap.Flip(WriteableBitmapExtensions.FlipMode.Horizontal);
if (_flipY) _bitmap.Flip(WriteableBitmapExtensions.FlipMode.Vertical);
_bitmap.Invalidate();
return _bitmap;
}
#else
public BitmapSource RenderImageSource(ILUT lut) {
bool render = false;
if (_applyLut && lut != null && !lut.IsValid) {
lut.Recalculate();
render = true;
}
if (_bitmapSource == null || render) {
_pixels = new PinnedIntArray(ScaledData.Width * ScaledData.Height);
ScaledData.Render((_applyLut ? lut : null), _pixels.Data);
foreach (var overlay in _overlays) {
overlay.Render(_pixels.Data, ScaledData.Width, ScaledData.Height);
}
_bitmapSource = RenderBitmapSource(ScaledData.Width, ScaledData.Height, _pixels.Data);
}
if (_rotation != 0 || _flipX || _flipY) {
TransformGroup rotFlipTransform = new TransformGroup();
rotFlipTransform.Children.Add(new RotateTransform(_rotation));
rotFlipTransform.Children.Add(new ScaleTransform(_flipX ? -1 : 1, _flipY ? -1 : 1));
_bitmapSource = new TransformedBitmap(_bitmapSource, rotFlipTransform);
}
return _bitmapSource;
}
private static BitmapSource RenderBitmapSource(int iWidth, int iHeight, int[] iPixelData) {
var bitmap = new WriteableBitmap(iWidth, iHeight, DPI, DPI, PixelFormats.Bgr32, null);
// Reserve the back buffer for updates.
bitmap.Lock();
Marshal.Copy(iPixelData, 0, bitmap.BackBuffer, iPixelData.Length);
// Specify the area of the bitmap that changed.
bitmap.AddDirtyRect(new Int32Rect(0, 0, (int)bitmap.Width, (int)bitmap.Height));
// Release the back buffer and make it available for display.
bitmap.Unlock();
return bitmap;
}
public Image RenderImage(ILUT lut) {
bool render = false;
if (_bitmap == null) {
System.Drawing.Imaging.PixelFormat format = Components == 4
? System.Drawing.Imaging.PixelFormat.Format32bppArgb
: System.Drawing.Imaging.PixelFormat.Format32bppRgb;
_pixels = new PinnedIntArray(ScaledData.Width * ScaledData.Height);
_bitmap = new Bitmap(ScaledData.Width, ScaledData.Height, ScaledData.Width * 4, format, _pixels.Pointer);
render = true;
}
if (_applyLut && lut != null && !lut.IsValid) {
lut.Recalculate();
render = true;
}
_bitmap.RotateFlip(RotateFlipType.RotateNoneFlipNone);
if (render) {
ScaledData.Render((_applyLut ? lut : null), _pixels.Data);
foreach (var overlay in _overlays) {
overlay.Render(_pixels.Data, ScaledData.Width, ScaledData.Height);
}
}
_bitmap.RotateFlip(GetRotateFlipType());
return _bitmap;
}
protected RotateFlipType GetRotateFlipType() {
if (_flipX && _flipY) {
switch (_rotation) {
case 90: return RotateFlipType.Rotate90FlipXY;
case 180: return RotateFlipType.Rotate180FlipXY;
case 270: return RotateFlipType.Rotate270FlipXY;
default: return RotateFlipType.RotateNoneFlipXY;
}
} else if (_flipX) {
switch (_rotation) {
case 90: return RotateFlipType.Rotate90FlipX;
case 180: return RotateFlipType.Rotate180FlipX;
case 270: return RotateFlipType.Rotate270FlipX;
default: return RotateFlipType.RotateNoneFlipX;
}
} else if (_flipY) {
switch (_rotation) {
case 90: return RotateFlipType.Rotate90FlipY;
case 180: return RotateFlipType.Rotate180FlipY;
case 270: return RotateFlipType.Rotate270FlipY;
default: return RotateFlipType.RotateNoneFlipY;
}
} else {
switch (_rotation) {
case 90: return RotateFlipType.Rotate90FlipNone;
case 180: return RotateFlipType.Rotate180FlipNone;
case 270: return RotateFlipType.Rotate270FlipNone;
default: return RotateFlipType.RotateNoneFlipNone;
}
}
}
#endif
#endregion
}
}
| |
//
// Copyright 2014 Matthew Ducker
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
namespace Obscur.Core.Packaging.Parsing
{
/// <summary>
/// Node in a tree representing a directory, or index of other nodes.
/// </summary>
/// <typeparam name="T"></typeparam>
public sealed class DirectoryTreeNode<T> : TreeNode<T>
{
private readonly List<TreeNode<T>> _children = new List<TreeNode<T>>();
private readonly bool _root;
/// <summary>
/// Creates a new directory node.
/// </summary>
/// <param name="name">Name of the directory.</param>
/// <param name="parent">Parent of the node.</param>
/// <param name="mutable">If <c>true</c>, node can be modified after creation.</param>
public DirectoryTreeNode(string name, DirectoryTreeNode<T> parent, bool mutable = true)
: base(mutable)
{
_root = false;
Name = name;
Parent = parent;
}
/// <summary>
/// Creates a root directory node.
/// </summary>
internal DirectoryTreeNode(bool mutable = true)
: base(mutable)
{
_root = true;
Name = "";
Parent = null;
}
/// <summary>
/// Nodes contained in the directory.
/// </summary>
public IList<TreeNode<T>> Children
{
get { return _children; }
}
/// <summary>
/// If <c>true</c>, node contains child nodes.
/// </summary>
public bool HasChildren
{
get { return _children != null && (_children != null || _children.Count > 0); }
}
/// <summary>
/// If node is the root of the tree.
/// </summary>
/// <returns>If <c>true</c>, node is the root.</returns>
public bool IsRoot()
{
Debug.Assert((Parent == null) == _root);
return _root;
}
/// <summary>
/// Add a subdirectory.
/// </summary>
/// <param name="name">Name of the directory to add.</param>
/// <returns>Directory node.</returns>
public DirectoryTreeNode<T> AddChildDirectory(string name)
{
ThrowIfImmutable();
var node = new DirectoryTreeNode<T>(name, this);
_children.Add(node);
return node;
}
/// <summary>
/// Add content to the directory.
/// </summary>
/// <param name="name">Name of the content.</param>
/// <param name="content">Content to add.</param>
/// <returns>Content tree node.</returns>
public ContentTreeNode<T> AddChildItem(string name, T content)
{
ThrowIfImmutable();
var node = new ContentTreeNode<T>(name, this, content);
_children.Add(node);
return node;
}
/// <summary>
/// Add a node to the directory.
/// </summary>
/// <param name="node">Node to add.</param>
/// <returns></returns>
internal void AddChildNode(TreeNode<T> node)
{
ThrowIfImmutable();
node.Parent = this;
_children.Add(node);
}
/// <summary>
/// Remove a node from the directory.
/// </summary>
/// <param name="node">Node to remove.</param>
/// <param name="moveChildrenToParent">If <c>true</c>, move all children of removed node to this directory.</param>
public void RemoveChildNode(TreeNode<T> node, bool moveChildrenToParent)
{
ThrowIfImmutable();
int index = _children.IndexOf(node);
if (index == -1) {
//throw new ArgumentException("Specified node not present.", "node");
return;
}
RemoveChildNode(index, moveChildrenToParent);
}
/// <summary>
/// Remove a node from the directory by name.
/// </summary>
/// <param name="name">Name of the node to remove.</param>
/// <param name="moveChildrenToParent">If <c>true</c>, move all children of removed node to this directory.</param>
public void RemoveChildNode(string name, bool moveChildrenToParent)
{
ThrowIfImmutable();
int index = _children.FindIndex(child => child.Name.Equals(name));
if (index == -1) {
throw new ArgumentException("Node with specified name not present.", "name");
}
RemoveChildNode(index, moveChildrenToParent);
}
/// <summary>
/// Remove a node from the directory by index.
/// </summary>
/// <param name="index">Index of the node to remove.</param>
/// <param name="moveChildrenToParent">If <c>true</c>, move all children of removed node to this directory.</param>
public void RemoveChildNode(int index, bool moveChildrenToParent)
{
ThrowIfImmutable();
if (index >= _children.Count) {
throw new ArgumentException("Node of specified index not present (index is larger than collection length.", "index");
}
TreeNode<T> node = _children[index];
if (moveChildrenToParent && node is DirectoryTreeNode<T>) {
var dirNode = node as DirectoryTreeNode<T>;
foreach (var childNode in dirNode.Children) {
childNode.Parent = this;
_children.Add(childNode);
}
}
_children.RemoveAt(index);
}
/// <summary>
/// Get the index of a child node of the directory by name.
/// </summary>
/// <param name="name">Name of the node to find.</param>
/// <returns>Index of the node. -1 if not found.</returns>
public int FindChildNodeIndex(string name)
{
return _children.FindIndex(child => child.Name.Equals(name));
}
/// <summary>
/// Get a sequence of all content tree nodes in the directory,
/// optionally including subdirectories.
/// </summary>
/// <param name="recursive">If <c>true</c>, recursively include all subdirectory nodes.</param>
/// <returns>Sequence of contained content nodes.</returns>
public IEnumerable<ContentTreeNode<T>> GetContent(bool recursive)
{
IEnumerable<ContentTreeNode<T>> e;
if (recursive) {
e = SelectSubtypeRecursive<TreeNode<T>, DirectoryTreeNode<T>, ContentTreeNode<T>>(_children,
node => node.Children);
} else {
e = Children.OfType<ContentTreeNode<T>>();
}
return e;
}
/// <summary>
/// Recursively enumerates nested structure for a specific type,
/// but does so iteratively using a stack for efficiency.
/// </summary>
/// <typeparam name="TBase">Type of objects to search.</typeparam>
/// <typeparam name="TCollection">
/// Type containing collection of <typeparamref name="TBase"/>.
/// </typeparam>
/// <typeparam name="TSubtype">
/// Type to select from collections of <typeparamref name="TCollection"/>.
/// </typeparam>
/// <param name="source">Source of objects to search.</param>
/// <param name="selector">
/// Predicate for inclusion of objects of type <typeparamref name="TSubtype"/> found.
/// </param>
/// <returns>Sequence of found objects of type <typeparamref name="TSubtype"/></returns>
public static IEnumerable<TSubtype> SelectSubtypeRecursive<TBase, TCollection, TSubtype>(
IEnumerable<TBase> source,
Func<TCollection, IEnumerable<TBase>> selector) where TSubtype : class, TBase
where TCollection : class, TBase
{
if (source == null) {
yield break;
}
var stack = new Stack<IEnumerator<TBase>>();
stack.Push(source.GetEnumerator());
while (stack.Count > 0) {
IEnumerator<TBase> item = stack.Peek();
if (item.MoveNext()) {
TBase current = item.Current;
if (current is TSubtype) {
yield return item.Current as TSubtype;
} else if (current is TCollection) {
stack.Push(selector(current as TCollection).GetEnumerator());
}
} else {
stack.Pop();
}
}
}
}
}
| |
//
// StringAnalyzer.cs
//
// Author:
// Aaron Bockover <abock@rd.io>
//
// Copyright 2012 Rdio, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.IO;
using System.Xml;
using System.Xml.Linq;
using System.Text.RegularExpressions;
using System.Collections.Generic;
using Vernacular.Tool;
namespace Vernacular.Analyzers
{
public class StringAnalyzer
{
private List<LocalizedString> localized_strings = new List<LocalizedString> ();
private Hunspell hunspell;
private AnalyzerConfiguration configuration;
public StringAnalyzer (string configurationPath = null, bool warningsAsErrors = false)
{
configuration = new AnalyzerConfiguration (configurationPath, warningsAsErrors);
if (File.Exists (configuration.HunspellAffixPath) && File.Exists (configuration.HunspellDictionaryPath)) {
try {
hunspell = new Hunspell (configuration.HunspellAffixPath, configuration.HunspellDictionaryPath);
} catch (DllNotFoundException) {
}
if (hunspell != null && configuration.SpellcheckDictionaries != null) {
foreach (var path in configuration.SpellcheckDictionaries) {
using (var reader = new StreamReader (path)) {
string word;
while ((word = reader.ReadLine ()) != null) {
word = word.Trim ().ToLower ();
if (!String.IsNullOrWhiteSpace (word)) {
hunspell.AddWordToDictionary (word);
}
}
}
}
}
}
}
public void Add (LocalizedString localizedString)
{
localized_strings.Add (localizedString);
}
public int Analyze ()
{
var count = 0;
foreach (var localized_string in localized_strings) {
if (Analyze (localized_string)) {
count++;
}
}
if (count > 0) {
Console.WriteLine ();
Console.WriteLine ();
Console.WriteLine ("{0} possibly problematic strings.", count);
}
return configuration.WarningsAsErrors ? count : 0;
}
private bool Analyze (LocalizedString localizedString)
{
var warnings = new List<string> ();
if (Check (CheckFormatArguments, localizedString) &&
String.IsNullOrWhiteSpace (localizedString.DeveloperComments)) {
warnings.Add ("String.Format without developer comment");
}
if (Check (CheckEmpty, localizedString)) {
warnings.Add ("Empty or whitespace");
}
if (Check (CheckIllegalWords, localizedString)) {
warnings.Add ("Possibly illegal words");
}
if (Check (CheckTags, localizedString)) {
warnings.Add ("Possibly invalid tags");
}
string misspelledWord;
if (CheckSpelling (localizedString.UntranslatedSingularValue, out misspelledWord) ||
CheckSpelling (localizedString.UntranslatedPluralValue, out misspelledWord)) {
warnings.Add ("Possibly misspelled word: " + misspelledWord);
}
warnings.AddRange (localizedString.Warnings);
if (warnings.Count == 0) {
return false;
}
ConsoleCrayon.ForegroundColor = ConsoleColor.DarkRed;
var label = configuration.WarningsAsErrors ? "Error" : "Warning";
if (localizedString.HasReferences) {
foreach (var reference in localizedString.References) {
Console.WriteLine ("{0}: @{1}", label, reference);
}
} else {
Console.WriteLine ("{0}: @<unknown source location>", label);
}
ConsoleCrayon.ForegroundColor = ConsoleColor.DarkYellow;
foreach (var warning in warnings) {
Console.WriteLine (" {0}", warning);
}
ConsoleCrayon.Reset ();
if (localizedString.DeveloperComments != null) {
Console.WriteLine (" Developer Comments = {0}", localizedString.DeveloperComments);
}
if (localizedString.UntranslatedSingularValue != null) {
Console.WriteLine (" Singular = {0}", localizedString.UntranslatedSingularValue);
}
if (localizedString.UntranslatedPluralValue != null) {
Console.WriteLine (" Plural = {0}", localizedString.UntranslatedPluralValue);
}
return true;
}
private bool Check (Func<string, bool> func, LocalizedString localizedString)
{
return func (localizedString.UntranslatedSingularValue) || func (localizedString.UntranslatedPluralValue);
}
public static bool CheckFormatArguments (string value)
{
if (String.IsNullOrEmpty (value)) {
return false;
}
return Regex.IsMatch (value, @"\{\d+", RegexOptions.Multiline);
}
private bool CheckEmpty (string value)
{
return String.IsNullOrWhiteSpace (value) && value != null;
}
private bool CheckIllegalWords (string value)
{
if (String.IsNullOrWhiteSpace (value)) {
return false;
}
value = value.ToLower ();
foreach (var word in configuration.IllegalWords) {
if (value.Contains (word.Key)) {
if (word.Value != null) {
foreach (var except in word.Value) {
if (value == except) {
return false;
}
}
}
return true;
}
}
return false;
}
private bool CheckTags (string value)
{
if (String.IsNullOrWhiteSpace (value) ||
configuration.SupportedTags == null || configuration.SupportedTags.Count == 0) {
return false;
}
foreach (var tag_regex in new [] { @"\%\((\w+)\)", @"\[(\w+)\]" }) {
foreach (Match match in new Regex (tag_regex, RegexOptions.Multiline).Matches (value)) {
if (match != null && match.Groups.Count > 1 &&
!configuration.SupportedTags.Contains (match.Groups [1].Value)) {
return true;
}
}
}
return false;
}
private bool CheckSpelling (string value, out string misspelledWord)
{
misspelledWord = null;
if (hunspell == null || String.IsNullOrWhiteSpace (value)) {
return false;
}
value = Regex.Replace (StringExtensions.Escape (value, decode: true), @"[^A-Za-z_\']+", " ");
foreach (var word in Regex.Split (value, @"\s+")) {
var sanitized_word = word;
if (sanitized_word.EndsWith ("'s") || sanitized_word.EndsWith ("s'")) {
sanitized_word = sanitized_word.Substring (0, sanitized_word.Length - 2);
}
if (!sanitized_word.StartsWith ("'") &&
!configuration.SupportedTags.Contains (sanitized_word) &&
!hunspell.SpellCheckWord (sanitized_word)) {
misspelledWord = sanitized_word;
return true;
}
}
return false;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/*============================================================
**
**
**
**
**
** Purpose: A Stream whose backing store is memory. Great
** for temporary storage without creating a temp file. Also
** lets users expose a byte[] as a stream.
**
**
===========================================================*/
using System;
using System.Runtime;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Threading;
using System.Threading.Tasks;
namespace System.IO
{
// A MemoryStream represents a Stream in memory (ie, it has no backing store).
// This stream may reduce the need for temporary buffers and files in
// an application.
//
// There are two ways to create a MemoryStream. You can initialize one
// from an unsigned byte array, or you can create an empty one. Empty
// memory streams are resizable, while ones created with a byte array provide
// a stream "view" of the data.
[Serializable]
public class MemoryStream : Stream
{
private byte[] _buffer; // Either allocated internally or externally.
private int _origin; // For user-provided arrays, start at this origin
private int _position; // read/write head.
[ContractPublicPropertyName("Length")]
private int _length; // Number of bytes within the memory stream
private int _capacity; // length of usable portion of buffer for stream
// Note that _capacity == _buffer.Length for non-user-provided byte[]'s
private bool _expandable; // User-provided buffers aren't expandable.
private bool _writable; // Can user write to this stream?
private bool _exposable; // Whether the array can be returned to the user.
private bool _isOpen; // Is this stream open or closed?
[NonSerialized]
private Task<int> _lastReadTask; // The last successful task returned from ReadAsync
private const int MemStreamMaxLength = Int32.MaxValue;
public MemoryStream()
: this(0)
{
}
public MemoryStream(int capacity)
{
if (capacity < 0)
{
throw new ArgumentOutOfRangeException(nameof(capacity), Environment.GetResourceString("ArgumentOutOfRange_NegativeCapacity"));
}
Contract.EndContractBlock();
_buffer = capacity != 0 ? new byte[capacity] : EmptyArray<byte>.Value;
_capacity = capacity;
_expandable = true;
_writable = true;
_exposable = true;
_origin = 0; // Must be 0 for byte[]'s created by MemoryStream
_isOpen = true;
}
public MemoryStream(byte[] buffer)
: this(buffer, true)
{
}
public MemoryStream(byte[] buffer, bool writable)
{
if (buffer == null) throw new ArgumentNullException(nameof(buffer), Environment.GetResourceString("ArgumentNull_Buffer"));
Contract.EndContractBlock();
_buffer = buffer;
_length = _capacity = buffer.Length;
_writable = writable;
_exposable = false;
_origin = 0;
_isOpen = true;
}
public MemoryStream(byte[] buffer, int index, int count)
: this(buffer, index, count, true, false)
{
}
public MemoryStream(byte[] buffer, int index, int count, bool writable)
: this(buffer, index, count, writable, false)
{
}
public MemoryStream(byte[] buffer, int index, int count, bool writable, bool publiclyVisible)
{
if (buffer == null)
throw new ArgumentNullException(nameof(buffer), Environment.GetResourceString("ArgumentNull_Buffer"));
if (index < 0)
throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (buffer.Length - index < count)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.EndContractBlock();
_buffer = buffer;
_origin = _position = index;
_length = _capacity = index + count;
_writable = writable;
_exposable = publiclyVisible; // Can TryGetBuffer/GetBuffer return the array?
_expandable = false;
_isOpen = true;
}
public override bool CanRead
{
[Pure]
get { return _isOpen; }
}
public override bool CanSeek
{
[Pure]
get { return _isOpen; }
}
public override bool CanWrite
{
[Pure]
get { return _writable; }
}
private void EnsureWriteable()
{
if (!CanWrite) __Error.WriteNotSupported();
}
protected override void Dispose(bool disposing)
{
try
{
if (disposing)
{
_isOpen = false;
_writable = false;
_expandable = false;
// Don't set buffer to null - allow TryGetBuffer, GetBuffer & ToArray to work.
_lastReadTask = null;
}
}
finally
{
// Call base.Close() to cleanup async IO resources
base.Dispose(disposing);
}
}
// returns a bool saying whether we allocated a new array.
private bool EnsureCapacity(int value)
{
// Check for overflow
if (value < 0)
throw new IOException(Environment.GetResourceString("IO.IO_StreamTooLong"));
if (value > _capacity)
{
int newCapacity = value;
if (newCapacity < 256)
newCapacity = 256;
// We are ok with this overflowing since the next statement will deal
// with the cases where _capacity*2 overflows.
if (newCapacity < _capacity * 2)
newCapacity = _capacity * 2;
// We want to expand the array up to Array.MaxArrayLengthOneDimensional
// And we want to give the user the value that they asked for
if ((uint)(_capacity * 2) > Array.MaxByteArrayLength)
newCapacity = value > Array.MaxByteArrayLength ? value : Array.MaxByteArrayLength;
Capacity = newCapacity;
return true;
}
return false;
}
public override void Flush()
{
}
public override Task FlushAsync(CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
return Task.FromCanceled(cancellationToken);
try
{
Flush();
return Task.CompletedTask;
}
catch (Exception ex)
{
return Task.FromException(ex);
}
}
public virtual byte[] GetBuffer()
{
if (!_exposable)
throw new UnauthorizedAccessException(Environment.GetResourceString("UnauthorizedAccess_MemStreamBuffer"));
return _buffer;
}
public virtual bool TryGetBuffer(out ArraySegment<byte> buffer)
{
if (!_exposable)
{
buffer = default(ArraySegment<byte>);
return false;
}
buffer = new ArraySegment<byte>(_buffer, offset: _origin, count: (_length - _origin));
return true;
}
// -------------- PERF: Internal functions for fast direct access of MemoryStream buffer (cf. BinaryReader for usage) ---------------
// PERF: Internal sibling of GetBuffer, always returns a buffer (cf. GetBuffer())
internal byte[] InternalGetBuffer()
{
return _buffer;
}
// PERF: Get origin and length - used in ResourceWriter.
[FriendAccessAllowed]
internal void InternalGetOriginAndLength(out int origin, out int length)
{
if (!_isOpen) __Error.StreamIsClosed();
origin = _origin;
length = _length;
}
// PERF: True cursor position, we don't need _origin for direct access
internal int InternalGetPosition()
{
if (!_isOpen) __Error.StreamIsClosed();
return _position;
}
// PERF: Takes out Int32 as fast as possible
internal int InternalReadInt32()
{
if (!_isOpen)
__Error.StreamIsClosed();
int pos = (_position += 4); // use temp to avoid a race condition
if (pos > _length)
{
_position = _length;
__Error.EndOfFile();
}
return (int)(_buffer[pos - 4] | _buffer[pos - 3] << 8 | _buffer[pos - 2] << 16 | _buffer[pos - 1] << 24);
}
// PERF: Get actual length of bytes available for read; do sanity checks; shift position - i.e. everything except actual copying bytes
internal int InternalEmulateRead(int count)
{
if (!_isOpen) __Error.StreamIsClosed();
int n = _length - _position;
if (n > count) n = count;
if (n < 0) n = 0;
Debug.Assert(_position + n >= 0, "_position + n >= 0"); // len is less than 2^31 -1.
_position += n;
return n;
}
// Gets & sets the capacity (number of bytes allocated) for this stream.
// The capacity cannot be set to a value less than the current length
// of the stream.
//
public virtual int Capacity
{
get
{
if (!_isOpen) __Error.StreamIsClosed();
return _capacity - _origin;
}
set
{
// Only update the capacity if the MS is expandable and the value is different than the current capacity.
// Special behavior if the MS isn't expandable: we don't throw if value is the same as the current capacity
if (value < Length) throw new ArgumentOutOfRangeException(nameof(value), Environment.GetResourceString("ArgumentOutOfRange_SmallCapacity"));
Contract.Ensures(_capacity - _origin == value);
Contract.EndContractBlock();
if (!_isOpen) __Error.StreamIsClosed();
if (!_expandable && (value != Capacity)) __Error.MemoryStreamNotExpandable();
// MemoryStream has this invariant: _origin > 0 => !expandable (see ctors)
if (_expandable && value != _capacity)
{
if (value > 0)
{
byte[] newBuffer = new byte[value];
if (_length > 0) Buffer.InternalBlockCopy(_buffer, 0, newBuffer, 0, _length);
_buffer = newBuffer;
}
else
{
_buffer = null;
}
_capacity = value;
}
}
}
public override long Length
{
get
{
if (!_isOpen) __Error.StreamIsClosed();
return _length - _origin;
}
}
public override long Position
{
get
{
if (!_isOpen) __Error.StreamIsClosed();
return _position - _origin;
}
set
{
if (value < 0)
throw new ArgumentOutOfRangeException(nameof(value), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
Contract.Ensures(Position == value);
Contract.EndContractBlock();
if (!_isOpen) __Error.StreamIsClosed();
if (value > MemStreamMaxLength)
throw new ArgumentOutOfRangeException(nameof(value), Environment.GetResourceString("ArgumentOutOfRange_StreamLength"));
_position = _origin + (int)value;
}
}
public override int Read([In, Out] byte[] buffer, int offset, int count)
{
if (buffer == null)
throw new ArgumentNullException(nameof(buffer), Environment.GetResourceString("ArgumentNull_Buffer"));
if (offset < 0)
throw new ArgumentOutOfRangeException(nameof(offset), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (buffer.Length - offset < count)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.EndContractBlock();
if (!_isOpen) __Error.StreamIsClosed();
int n = _length - _position;
if (n > count) n = count;
if (n <= 0)
return 0;
Debug.Assert(_position + n >= 0, "_position + n >= 0"); // len is less than 2^31 -1.
if (n <= 8)
{
int byteCount = n;
while (--byteCount >= 0)
buffer[offset + byteCount] = _buffer[_position + byteCount];
}
else
Buffer.InternalBlockCopy(_buffer, _position, buffer, offset, n);
_position += n;
return n;
}
public override Task<int> ReadAsync(Byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
if (buffer == null)
throw new ArgumentNullException(nameof(buffer), Environment.GetResourceString("ArgumentNull_Buffer"));
if (offset < 0)
throw new ArgumentOutOfRangeException(nameof(offset), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (buffer.Length - offset < count)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.EndContractBlock(); // contract validation copied from Read(...)
// If cancellation was requested, bail early
if (cancellationToken.IsCancellationRequested)
return Task.FromCanceled<int>(cancellationToken);
try
{
int n = Read(buffer, offset, count);
var t = _lastReadTask;
Debug.Assert(t == null || t.Status == TaskStatus.RanToCompletion,
"Expected that a stored last task completed successfully");
return (t != null && t.Result == n) ? t : (_lastReadTask = Task.FromResult<int>(n));
}
catch (OperationCanceledException oce)
{
return Task.FromCancellation<int>(oce);
}
catch (Exception exception)
{
return Task.FromException<int>(exception);
}
}
public override int ReadByte()
{
if (!_isOpen) __Error.StreamIsClosed();
if (_position >= _length) return -1;
return _buffer[_position++];
}
public override void CopyTo(Stream destination, int bufferSize)
{
// Since we did not originally override this method, validate the arguments
// the same way Stream does for back-compat.
StreamHelpers.ValidateCopyToArgs(this, destination, bufferSize);
// If we have been inherited into a subclass, the following implementation could be incorrect
// since it does not call through to Read() which a subclass might have overridden.
// To be safe we will only use this implementation in cases where we know it is safe to do so,
// and delegate to our base class (which will call into Read) when we are not sure.
if (GetType() != typeof(MemoryStream))
{
base.CopyTo(destination, bufferSize);
return;
}
int originalPosition = _position;
// Seek to the end of the MemoryStream.
int remaining = InternalEmulateRead(_length - originalPosition);
// If we were already at or past the end, there's no copying to do so just quit.
if (remaining > 0)
{
// Call Write() on the other Stream, using our internal buffer and avoiding any
// intermediary allocations.
destination.Write(_buffer, originalPosition, remaining);
}
}
public override Task CopyToAsync(Stream destination, Int32 bufferSize, CancellationToken cancellationToken)
{
// This implementation offers beter performance compared to the base class version.
StreamHelpers.ValidateCopyToArgs(this, destination, bufferSize);
// If we have been inherited into a subclass, the following implementation could be incorrect
// since it does not call through to ReadAsync() which a subclass might have overridden.
// To be safe we will only use this implementation in cases where we know it is safe to do so,
// and delegate to our base class (which will call into ReadAsync) when we are not sure.
if (this.GetType() != typeof(MemoryStream))
return base.CopyToAsync(destination, bufferSize, cancellationToken);
// If cancelled - return fast:
if (cancellationToken.IsCancellationRequested)
return Task.FromCanceled(cancellationToken);
// Avoid copying data from this buffer into a temp buffer:
// (require that InternalEmulateRead does not throw,
// otherwise it needs to be wrapped into try-catch-Task.FromException like memStrDest.Write below)
Int32 pos = _position;
Int32 n = InternalEmulateRead(_length - _position);
// If destination is not a memory stream, write there asynchronously:
MemoryStream memStrDest = destination as MemoryStream;
if (memStrDest == null)
return destination.WriteAsync(_buffer, pos, n, cancellationToken);
try
{
// If destination is a MemoryStream, CopyTo synchronously:
memStrDest.Write(_buffer, pos, n);
return Task.CompletedTask;
}
catch (Exception ex)
{
return Task.FromException(ex);
}
}
public override long Seek(long offset, SeekOrigin loc)
{
if (!_isOpen) __Error.StreamIsClosed();
if (offset > MemStreamMaxLength)
throw new ArgumentOutOfRangeException(nameof(offset), Environment.GetResourceString("ArgumentOutOfRange_StreamLength"));
switch (loc)
{
case SeekOrigin.Begin:
{
int tempPosition = unchecked(_origin + (int)offset);
if (offset < 0 || tempPosition < _origin)
throw new IOException(Environment.GetResourceString("IO.IO_SeekBeforeBegin"));
_position = tempPosition;
break;
}
case SeekOrigin.Current:
{
int tempPosition = unchecked(_position + (int)offset);
if (unchecked(_position + offset) < _origin || tempPosition < _origin)
throw new IOException(Environment.GetResourceString("IO.IO_SeekBeforeBegin"));
_position = tempPosition;
break;
}
case SeekOrigin.End:
{
int tempPosition = unchecked(_length + (int)offset);
if (unchecked(_length + offset) < _origin || tempPosition < _origin)
throw new IOException(Environment.GetResourceString("IO.IO_SeekBeforeBegin"));
_position = tempPosition;
break;
}
default:
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidSeekOrigin"));
}
Debug.Assert(_position >= 0, "_position >= 0");
return _position;
}
// Sets the length of the stream to a given value. The new
// value must be nonnegative and less than the space remaining in
// the array, Int32.MaxValue - origin
// Origin is 0 in all cases other than a MemoryStream created on
// top of an existing array and a specific starting offset was passed
// into the MemoryStream constructor. The upper bounds prevents any
// situations where a stream may be created on top of an array then
// the stream is made longer than the maximum possible length of the
// array (Int32.MaxValue).
//
public override void SetLength(long value)
{
if (value < 0 || value > Int32.MaxValue)
{
throw new ArgumentOutOfRangeException(nameof(value), Environment.GetResourceString("ArgumentOutOfRange_StreamLength"));
}
Contract.Ensures(_length - _origin == value);
Contract.EndContractBlock();
EnsureWriteable();
// Origin wasn't publicly exposed above.
Debug.Assert(MemStreamMaxLength == Int32.MaxValue); // Check parameter validation logic in this method if this fails.
if (value > (Int32.MaxValue - _origin))
{
throw new ArgumentOutOfRangeException(nameof(value), Environment.GetResourceString("ArgumentOutOfRange_StreamLength"));
}
int newLength = _origin + (int)value;
bool allocatedNewArray = EnsureCapacity(newLength);
if (!allocatedNewArray && newLength > _length)
Array.Clear(_buffer, _length, newLength - _length);
_length = newLength;
if (_position > newLength) _position = newLength;
}
public virtual byte[] ToArray()
{
BCLDebug.Perf(_exposable, "MemoryStream::GetBuffer will let you avoid a copy.");
byte[] copy = new byte[_length - _origin];
Buffer.InternalBlockCopy(_buffer, _origin, copy, 0, _length - _origin);
return copy;
}
public override void Write(byte[] buffer, int offset, int count)
{
if (buffer == null)
throw new ArgumentNullException(nameof(buffer), Environment.GetResourceString("ArgumentNull_Buffer"));
if (offset < 0)
throw new ArgumentOutOfRangeException(nameof(offset), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (buffer.Length - offset < count)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.EndContractBlock();
if (!_isOpen) __Error.StreamIsClosed();
EnsureWriteable();
int i = _position + count;
// Check for overflow
if (i < 0)
throw new IOException(Environment.GetResourceString("IO.IO_StreamTooLong"));
if (i > _length)
{
bool mustZero = _position > _length;
if (i > _capacity)
{
bool allocatedNewArray = EnsureCapacity(i);
if (allocatedNewArray)
mustZero = false;
}
if (mustZero)
Array.Clear(_buffer, _length, i - _length);
_length = i;
}
if ((count <= 8) && (buffer != _buffer))
{
int byteCount = count;
while (--byteCount >= 0)
_buffer[_position + byteCount] = buffer[offset + byteCount];
}
else
Buffer.InternalBlockCopy(buffer, offset, _buffer, _position, count);
_position = i;
}
public override Task WriteAsync(Byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
if (buffer == null)
throw new ArgumentNullException(nameof(buffer), Environment.GetResourceString("ArgumentNull_Buffer"));
if (offset < 0)
throw new ArgumentOutOfRangeException(nameof(offset), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (buffer.Length - offset < count)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.EndContractBlock(); // contract validation copied from Write(...)
// If cancellation is already requested, bail early
if (cancellationToken.IsCancellationRequested)
return Task.FromCanceled(cancellationToken);
try
{
Write(buffer, offset, count);
return Task.CompletedTask;
}
catch (OperationCanceledException oce)
{
return Task.FromCancellation<VoidTaskResult>(oce);
}
catch (Exception exception)
{
return Task.FromException(exception);
}
}
public override void WriteByte(byte value)
{
if (!_isOpen) __Error.StreamIsClosed();
EnsureWriteable();
if (_position >= _length)
{
int newLength = _position + 1;
bool mustZero = _position > _length;
if (newLength >= _capacity)
{
bool allocatedNewArray = EnsureCapacity(newLength);
if (allocatedNewArray)
mustZero = false;
}
if (mustZero)
Array.Clear(_buffer, _length, _position - _length);
_length = newLength;
}
_buffer[_position++] = value;
}
// Writes this MemoryStream to another stream.
public virtual void WriteTo(Stream stream)
{
if (stream == null)
throw new ArgumentNullException(nameof(stream), Environment.GetResourceString("ArgumentNull_Stream"));
Contract.EndContractBlock();
if (!_isOpen) __Error.StreamIsClosed();
stream.Write(_buffer, _origin, _length - _origin);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Terraria.GameContent.UI;
using Terraria.ID;
namespace Terraria.ModLoader
{
//todo: further documentation
/// <summary>
/// This serves as the central class from which NPC-related functions are carried out. It also stores a list of mod NPCs by ID.
/// </summary>
public static class NPCLoader
{
internal static bool loaded = false;
private static int nextNPC = NPCID.Count;
internal static readonly IList<ModNPC> npcs = new List<ModNPC>();
internal static readonly IList<GlobalNPC> globalNPCs = new List<GlobalNPC>();
internal static readonly IList<NPCInfo> infoList = new List<NPCInfo>();
internal static readonly IDictionary<string, int> infoIndexes = new Dictionary<string, int>();
internal static readonly IDictionary<int, int> bannerToItem = new Dictionary<int, int>();
private static int vanillaSkeletonCount = NPCID.Sets.Skeletons.Count;
private static readonly int[] shopToNPC = new int[Main.MaxShopIDs - 1];
//in Terraria.Item.NewItem after setting Main.item[400] add
// if(NPCLoader.blockLoot.Contains(Type)) { return num; }
/// <summary>
/// Allows you to stop an NPC from dropping loot by adding item IDs to this list. This list will be cleared whenever NPCLoot ends. Useful for either removing an item or change the drop rate of an item in the NPC's loot table. To change the drop rate of an item, use the PreNPCLoot hook, spawn the item yourself, then add the item's ID to this list.
/// </summary>
public static readonly IList<int> blockLoot = new List<int>();
private static Action<NPC>[] HookSetDefaults = new Action<NPC>[0];
private static Action<NPC, int, float>[] HookScaleExpertStats = new Action<NPC, int, float>[0];
private static Action<NPC>[] HookResetEffects;
private static Func<NPC, bool>[] HookPreAI;
private static Action<NPC>[] HookAI;
private static Action<NPC>[] HookPostAI;
private static Action<NPC, int>[] HookFindFrame;
private static Action<NPC, int, double>[] HookHitEffect;
private delegate void DelegateUpdateLifeRegen(NPC npc, ref int damage);
private static DelegateUpdateLifeRegen[] HookUpdateLifeRegen;
private static Func<NPC, bool>[] HookCheckActive;
private static Func<NPC, bool>[] HookCheckDead;
private static Func<NPC, bool>[] HookPreNPCLoot;
private static Action<NPC>[] HookNPCLoot;
private delegate bool DelegateCanHitPlayer(NPC npc, Player target, ref int cooldownSlot);
private static DelegateCanHitPlayer[] HookCanHitPlayer;
private delegate void DelegateModifyHitPlayer(NPC npc, Player target, ref int damage, ref bool crit);
private static DelegateModifyHitPlayer[] HookModifyHitPlayer;
private static Action<NPC, Player, int, bool>[] HookOnHitPlayer;
private static Func<NPC, NPC, bool?>[] HookCanHitNPC;
private delegate void DelegateModifyHitNPC(NPC npc, NPC target, ref int damage, ref float knockback, ref bool crit);
private static DelegateModifyHitNPC[] HookModifyHitNPC;
private static Action<NPC, NPC, int, float, bool>[] HookOnHitNPC;
private static Func<NPC, Player, Item, bool?>[] HookCanBeHitByItem;
private delegate void DelegateModifyHitByItem(NPC npc, Player player, Item item, ref int damage, ref float knockback, ref bool crit);
private static DelegateModifyHitByItem[] HookModifyHitByItem;
private static Action<NPC, Player, Item, int, float, bool>[] HookOnHitByItem;
private static Func<NPC, Projectile, bool?>[] HookCanBeHitByProjectile;
private delegate void DelegateModifyHitByProjectile(NPC npc, Projectile projectile, ref int damage, ref float knockback, ref bool crit, ref int hitDirection);
private static DelegateModifyHitByProjectile[] HookModifyHitByProjectile;
private static Action<NPC, Projectile, int, float, bool>[] HookOnHitByProjectile;
private delegate bool DelegateStrikeNPC(NPC npc, ref double damage, int defense, ref float knockback, int hitDirection, ref bool crit);
private static DelegateStrikeNPC[] HookStrikeNPC;
private delegate void DelegateBossHeadSlot(NPC npc, ref int index);
private static DelegateBossHeadSlot[] HookBossHeadSlot;
private delegate void DelegateBossHeadRotation(NPC npc, ref float rotation);
private static DelegateBossHeadRotation[] HookBossHeadRotation;
private delegate void DelegateBossHeadSpriteEffects(NPC npc, ref SpriteEffects spriteEffects);
private static DelegateBossHeadSpriteEffects[] HookBossHeadSpriteEffects;
private static Func<NPC, Color, Color?>[] HookGetAlpha;
private delegate void DelegateDrawEffects(NPC npc, ref Color drawColor);
private static DelegateDrawEffects[] HookDrawEffects;
private static Func<NPC, SpriteBatch, Color, bool>[] HookPreDraw;
private static Action<NPC, SpriteBatch, Color>[] HookPostDraw;
private delegate bool? DelegateDrawHealthBar(NPC npc, byte hbPosition, ref float scale, ref Vector2 offset);
private static DelegateDrawHealthBar[] HookDrawHealthBar;
private delegate void DelegateEditSpawnRate(Player player, ref int spawnRate, ref int maxSpawns);
private static DelegateEditSpawnRate[] HookEditSpawnRate;
private delegate void DelegateEditSpawnRange(Player player, ref int spawnRangeX, ref int spawnRangeY, ref int safeRangeX, ref int safeRangeY);
private static DelegateEditSpawnRange[] HookEditSpawnRange;
private static Action<IDictionary<int, float>, NPCSpawnInfo>[] HookEditSpawnPool;
private static Action<int, int, int>[] HookSpawnNPC;
private delegate void DelegateGetChat(NPC npc, ref string chat);
private static DelegateGetChat[] HookGetChat;
private delegate void DelegateSetupShop(int type, Chest shop, ref int nextSlot);
private static DelegateSetupShop[] HookSetupShop = new DelegateSetupShop[0];
private delegate void DelegateSetupTravelShop(int[] shop, ref int nextSlot);
private static DelegateSetupTravelShop[] HookSetupTravelShop = new DelegateSetupTravelShop[0];
private delegate void DelegateBuffTownNPC(ref float damageMult, ref int defense);
private static DelegateBuffTownNPC[] HookBuffTownNPC;
private delegate void DelegateTownNPCAttackStrength(NPC npc, ref int damage, ref float knockback);
private static DelegateTownNPCAttackStrength[] HookTownNPCAttackStrength;
private delegate void DelegateTownNPCAttackCooldown(NPC npc, ref int cooldown, ref int randExtraCooldown);
private static DelegateTownNPCAttackCooldown[] HookTownNPCAttackCooldown;
private delegate void DelegateTownNPCAttackProj(NPC npc, ref int projType, ref int attackDelay);
private static DelegateTownNPCAttackProj[] HookTownNPCAttackProj;
private delegate void DelegateTownNPCAttackProjSpeed(NPC npc, ref float multiplier, ref float gravityCorrection, ref float randomOffset);
private static DelegateTownNPCAttackProjSpeed[] HookTownNPCAttackProjSpeed;
private delegate void DelegateTownNPCAttackShoot(NPC npc, ref bool inBetweenShots);
private static DelegateTownNPCAttackShoot[] HookTownNPCAttackShoot;
private delegate void DelegateTownNPCAttackMagic(NPC npc, ref float auraLightMultiplier);
private static DelegateTownNPCAttackMagic[] HookTownNPCAttackMagic;
private delegate void DelegateTownNPCAttackSwing(NPC npc, ref int itemWidth, ref int itemHeight);
private static DelegateTownNPCAttackSwing[] HookTownNPCAttackSwing;
private delegate void DelegateDrawTownAttackGun(NPC npc, ref float scale, ref int item, ref int closeness);
private static DelegateDrawTownAttackGun[] HookDrawTownAttackGun;
private delegate void DelegateDrawTownAttackSwing(NPC npc, ref Texture2D item, ref int itemSize, ref float scale, ref Vector2 offset);
private static DelegateDrawTownAttackSwing[] HookDrawTownAttackSwing;
static NPCLoader()
{
shopToNPC[1] = NPCID.Merchant;
shopToNPC[2] = NPCID.ArmsDealer;
shopToNPC[3] = NPCID.Dryad;
shopToNPC[4] = NPCID.Demolitionist;
shopToNPC[5] = NPCID.Clothier;
shopToNPC[6] = NPCID.GoblinTinkerer;
shopToNPC[7] = NPCID.Wizard;
shopToNPC[8] = NPCID.Mechanic;
shopToNPC[9] = NPCID.SantaClaus;
shopToNPC[10] = NPCID.Truffle;
shopToNPC[11] = NPCID.Steampunker;
shopToNPC[12] = NPCID.DyeTrader;
shopToNPC[13] = NPCID.PartyGirl;
shopToNPC[14] = NPCID.Cyborg;
shopToNPC[15] = NPCID.Painter;
shopToNPC[16] = NPCID.WitchDoctor;
shopToNPC[17] = NPCID.Pirate;
shopToNPC[18] = NPCID.Stylist;
shopToNPC[19] = NPCID.TravellingMerchant;
shopToNPC[20] = NPCID.SkeletonMerchant;
shopToNPC[21] = NPCID.DD2Bartender;
}
internal static int ReserveNPCID()
{
if (ModNet.AllowVanillaClients) throw new Exception("Adding npcs breaks vanilla client compatiblity");
int reserveID = nextNPC;
nextNPC++;
return reserveID;
}
internal static int NPCCount => nextNPC;
/// <summary>
/// Gets the ModNPC instance corresponding to the specified type.
/// </summary>
/// <param name="type">The type of the npc</param>
/// <returns>The ModNPC instance in the npcs array, null if not found.</returns>
public static ModNPC GetNPC(int type)
{
return type >= NPCID.Count && type < NPCCount ? npcs[type - NPCID.Count] : null;
}
//change initial size of Terraria.Player.npcTypeNoAggro and NPCBannerBuff to NPCLoader.NPCCount()
//in Terraria.Main.MouseText replace 251 with NPCLoader.NPCCount()
//in Terraria.Main.DrawNPCs and Terraria.NPC.NPCLoot remove type too high check
//replace a lot of 540 immediates
//in Terraria.GameContent.UI.EmoteBubble make CountNPCs internal
internal static void ResizeArrays(bool unloading)
{
Array.Resize(ref Main.NPCLoaded, nextNPC);
Array.Resize(ref Main.nextNPC, nextNPC);
Array.Resize(ref Main.slimeRainNPC, nextNPC);
Array.Resize(ref Main.npcTexture, nextNPC);
Array.Resize(ref Main.npcAltTextures, nextNPC);
Array.Resize(ref Main.npcCatchable, nextNPC);
Array.Resize(ref Main.npcName, nextNPC);
Array.Resize(ref Main.npcNameEnglish, nextNPC);
Array.Resize(ref Main.npcFrameCount, nextNPC);
Array.Resize(ref NPC.killCount, nextNPC);
Array.Resize(ref NPC.npcsFoundForCheckActive, nextNPC);
Array.Resize(ref EmoteBubble.CountNPCs, nextNPC);
Array.Resize(ref NPCID.Sets.TrailingMode, nextNPC);
Array.Resize(ref NPCID.Sets.BelongsToInvasionOldOnesArmy, nextNPC);
Array.Resize(ref NPCID.Sets.TeleportationImmune, nextNPC);
Array.Resize(ref NPCID.Sets.UsesNewTargetting, nextNPC);
Array.Resize(ref NPCID.Sets.FighterUsesDD2PortalAppearEffect, nextNPC);
Array.Resize(ref NPCID.Sets.StatueSpawnedDropRarity, nextNPC);
Array.Resize(ref NPCID.Sets.NoEarlymodeLootWhenSpawnedFromStatue, nextNPC);
Array.Resize(ref NPCID.Sets.NeedsExpertScaling, nextNPC);
Array.Resize(ref NPCID.Sets.ProjectileNPC, nextNPC);
Array.Resize(ref NPCID.Sets.SavesAndLoads, nextNPC);
Array.Resize(ref NPCID.Sets.TrailCacheLength, nextNPC);
Array.Resize(ref NPCID.Sets.MPAllowedEnemies, nextNPC);
Array.Resize(ref NPCID.Sets.TownCritter, nextNPC);
Array.Resize(ref NPCID.Sets.HatOffsetY, nextNPC);
Array.Resize(ref NPCID.Sets.FaceEmote, nextNPC);
Array.Resize(ref NPCID.Sets.ExtraFramesCount, nextNPC);
Array.Resize(ref NPCID.Sets.AttackFrameCount, nextNPC);
Array.Resize(ref NPCID.Sets.DangerDetectRange, nextNPC);
Array.Resize(ref NPCID.Sets.AttackTime, nextNPC);
Array.Resize(ref NPCID.Sets.AttackAverageChance, nextNPC);
Array.Resize(ref NPCID.Sets.AttackType, nextNPC);
Array.Resize(ref NPCID.Sets.PrettySafe, nextNPC);
Array.Resize(ref NPCID.Sets.MagicAuraColor, nextNPC);
Array.Resize(ref NPCID.Sets.BossHeadTextures, nextNPC);
Array.Resize(ref NPCID.Sets.ExcludedFromDeathTally, nextNPC);
Array.Resize(ref NPCID.Sets.TechnicallyABoss, nextNPC);
Array.Resize(ref NPCID.Sets.MustAlwaysDraw, nextNPC);
Array.Resize(ref NPCID.Sets.ExtraTextureCount, nextNPC);
Array.Resize(ref NPCID.Sets.NPCFramingGroup, nextNPC);
Array.Resize(ref NPCID.Sets.TownNPCsFramingGroups, nextNPC);
for (int k = NPCID.Count; k < nextNPC; k++)
{
Main.NPCLoaded[k] = true;
Main.npcFrameCount[k] = 1;
NPCID.Sets.TrailingMode[k] = -1;
NPCID.Sets.StatueSpawnedDropRarity[k] = -1f;
NPCID.Sets.TrailCacheLength[k] = 10;
NPCID.Sets.DangerDetectRange[k] = -1;
NPCID.Sets.AttackTime[k] = -1;
NPCID.Sets.AttackAverageChance[k] = 1;
NPCID.Sets.AttackType[k] = -1;
NPCID.Sets.PrettySafe[k] = -1;
NPCID.Sets.MagicAuraColor[k] = Color.White;
NPCID.Sets.BossHeadTextures[k] = -1;
}
ModLoader.BuildGlobalHook(ref HookSetDefaults, globalNPCs, g => g.SetDefaults);
ModLoader.BuildGlobalHook(ref HookScaleExpertStats, globalNPCs, g => g.ScaleExpertStats);
ModLoader.BuildGlobalHook(ref HookResetEffects, globalNPCs, g => g.ResetEffects);
ModLoader.BuildGlobalHook(ref HookPreAI, globalNPCs, g => g.PreAI);
ModLoader.BuildGlobalHook(ref HookAI, globalNPCs, g => g.AI);
ModLoader.BuildGlobalHook(ref HookPostAI, globalNPCs, g => g.PostAI);
ModLoader.BuildGlobalHook(ref HookFindFrame, globalNPCs, g => g.FindFrame);
ModLoader.BuildGlobalHook(ref HookHitEffect, globalNPCs, g => g.HitEffect);
ModLoader.BuildGlobalHook(ref HookUpdateLifeRegen, globalNPCs, g => g.UpdateLifeRegen);
ModLoader.BuildGlobalHook(ref HookCheckActive, globalNPCs, g => g.CheckActive);
ModLoader.BuildGlobalHook(ref HookCheckDead, globalNPCs, g => g.CheckDead);
ModLoader.BuildGlobalHook(ref HookPreNPCLoot, globalNPCs, g => g.PreNPCLoot);
ModLoader.BuildGlobalHook(ref HookNPCLoot, globalNPCs, g => g.NPCLoot);
ModLoader.BuildGlobalHook(ref HookCanHitPlayer, globalNPCs, g => g.CanHitPlayer);
ModLoader.BuildGlobalHook(ref HookModifyHitPlayer, globalNPCs, g => g.ModifyHitPlayer);
ModLoader.BuildGlobalHook(ref HookOnHitPlayer, globalNPCs, g => g.OnHitPlayer);
ModLoader.BuildGlobalHook(ref HookCanHitNPC, globalNPCs, g => g.CanHitNPC);
ModLoader.BuildGlobalHook(ref HookModifyHitNPC, globalNPCs, g => g.ModifyHitNPC);
ModLoader.BuildGlobalHook(ref HookOnHitNPC, globalNPCs, g => g.OnHitNPC);
ModLoader.BuildGlobalHook(ref HookCanBeHitByItem, globalNPCs, g => g.CanBeHitByItem);
ModLoader.BuildGlobalHook(ref HookModifyHitByItem, globalNPCs, g => g.ModifyHitByItem);
ModLoader.BuildGlobalHook(ref HookOnHitByItem, globalNPCs, g => g.OnHitByItem);
ModLoader.BuildGlobalHook(ref HookCanBeHitByProjectile, globalNPCs, g => g.CanBeHitByProjectile);
ModLoader.BuildGlobalHook(ref HookModifyHitByProjectile, globalNPCs, g => g.ModifyHitByProjectile);
ModLoader.BuildGlobalHook(ref HookOnHitByProjectile, globalNPCs, g => g.OnHitByProjectile);
ModLoader.BuildGlobalHook(ref HookStrikeNPC, globalNPCs, g => g.StrikeNPC);
ModLoader.BuildGlobalHook(ref HookBossHeadSlot, globalNPCs, g => g.BossHeadSlot);
ModLoader.BuildGlobalHook(ref HookBossHeadRotation, globalNPCs, g => g.BossHeadRotation);
ModLoader.BuildGlobalHook(ref HookBossHeadSpriteEffects, globalNPCs, g => g.BossHeadSpriteEffects);
ModLoader.BuildGlobalHook(ref HookGetAlpha, globalNPCs, g => g.GetAlpha);
ModLoader.BuildGlobalHook(ref HookDrawEffects, globalNPCs, g => g.DrawEffects);
ModLoader.BuildGlobalHook(ref HookPreDraw, globalNPCs, g => g.PreDraw);
ModLoader.BuildGlobalHook(ref HookPostDraw, globalNPCs, g => g.PostDraw);
ModLoader.BuildGlobalHook(ref HookDrawHealthBar, globalNPCs, g => g.DrawHealthBar);
ModLoader.BuildGlobalHook(ref HookEditSpawnRate, globalNPCs, g => g.EditSpawnRate);
ModLoader.BuildGlobalHook(ref HookEditSpawnRange, globalNPCs, g => g.EditSpawnRange);
ModLoader.BuildGlobalHook(ref HookEditSpawnPool, globalNPCs, g => g.EditSpawnPool);
ModLoader.BuildGlobalHook(ref HookSpawnNPC, globalNPCs, g => g.SpawnNPC);
ModLoader.BuildGlobalHook(ref HookGetChat, globalNPCs, g => g.GetChat);
ModLoader.BuildGlobalHook(ref HookSetupShop, globalNPCs, g => g.SetupShop);
ModLoader.BuildGlobalHook(ref HookSetupTravelShop, globalNPCs, g => g.SetupTravelShop);
ModLoader.BuildGlobalHook(ref HookBuffTownNPC, globalNPCs, g => g.BuffTownNPC);
ModLoader.BuildGlobalHook(ref HookTownNPCAttackStrength, globalNPCs, g => g.TownNPCAttackStrength);
ModLoader.BuildGlobalHook(ref HookTownNPCAttackCooldown, globalNPCs, g => g.TownNPCAttackCooldown);
ModLoader.BuildGlobalHook(ref HookTownNPCAttackProj, globalNPCs, g => g.TownNPCAttackProj);
ModLoader.BuildGlobalHook(ref HookTownNPCAttackProjSpeed, globalNPCs, g => g.TownNPCAttackProjSpeed);
ModLoader.BuildGlobalHook(ref HookTownNPCAttackShoot, globalNPCs, g => g.TownNPCAttackShoot);
ModLoader.BuildGlobalHook(ref HookTownNPCAttackMagic, globalNPCs, g => g.TownNPCAttackMagic);
ModLoader.BuildGlobalHook(ref HookTownNPCAttackSwing, globalNPCs, g => g.TownNPCAttackSwing);
ModLoader.BuildGlobalHook(ref HookDrawTownAttackGun, globalNPCs, g => g.DrawTownAttackGun);
ModLoader.BuildGlobalHook(ref HookDrawTownAttackSwing, globalNPCs, g => g.DrawTownAttackSwing);
if (!unloading)
{
loaded = true;
}
}
internal static void Unload()
{
loaded = false;
npcs.Clear();
nextNPC = NPCID.Count;
globalNPCs.Clear();
infoList.Clear();
infoIndexes.Clear();
bannerToItem.Clear();
while (NPCID.Sets.Skeletons.Count > vanillaSkeletonCount)
{
NPCID.Sets.Skeletons.RemoveAt(NPCID.Sets.Skeletons.Count - 1);
}
}
internal static bool IsModNPC(NPC npc)
{
return npc.type >= NPCID.Count;
}
//in Terraria.NPC.SetDefaults after if else setting properties call NPCLoader.SetupNPC(this);
//in Terraria.NPC.SetDefaults move Lang stuff before SetupNPC and replace this.netID with this.type
internal static void SetupNPC(NPC npc)
{
SetupNPCInfo(npc);
if (IsModNPC(npc))
{
GetNPC(npc.type).SetupNPC(npc);
}
foreach (var hook in HookSetDefaults)
{
hook(npc);
}
}
internal static void SetupNPCInfo(NPC npc)
{
npc.npcInfo = infoList.Select(info => info.Clone()).ToArray();
}
internal static NPCInfo GetNPCInfo(NPC npc, Mod mod, string name)
{
int index;
return infoIndexes.TryGetValue(mod.Name + ':' + name, out index) ? npc.npcInfo[index] : null;
}
//at beginning of Terraria.Lang.npcName add
// if (l >= Main.maxNPCTypes) { return NPCLoader.DisplayName(l); }
public static string DisplayName(int type)
{
ModNPC npc = GetNPC(type);
string name = "";
if (npc != null)
{
if (npc.npc.displayName != null)
{
name = npc.npc.displayName;
}
if (name == "" && npc.npc.name != null)
{
name = npc.npc.name;
}
}
if (name == "" && Main.npcName[type] != null)
{
name = Main.npcName[type];
}
return name;
}
//in Terraria.NPC.scaleStats before setting def fields call
// NPCLoader.ScaleExpertStats(this, num4, num5);
public static void ScaleExpertStats(NPC npc, int numPlayers, float bossLifeScale)
{
npc.modNPC?.ScaleExpertStats(numPlayers, bossLifeScale);
foreach (var hook in HookScaleExpertStats)
{
hook(npc, numPlayers, bossLifeScale);
}
}
public static void ResetEffects(NPC npc)
{
npc.modNPC?.ResetEffects();
foreach (var hook in HookResetEffects)
{
hook(npc);
}
}
//in Terraria.NPC rename AI to VanillaAI then make AI call NPCLoader.NPCAI(this)
public static void NPCAI(NPC npc)
{
if (PreAI(npc))
{
int type = npc.type;
bool useAiType = npc.modNPC != null && npc.modNPC.aiType > 0;
if (useAiType)
{
npc.type = npc.modNPC.aiType;
}
npc.VanillaAI();
if (useAiType)
{
npc.type = type;
}
AI(npc);
}
PostAI(npc);
}
public static bool PreAI(NPC npc)
{
foreach (var hook in HookPreAI)
{
if (!hook(npc))
{
return false;
}
}
if (npc.modNPC != null)
{
return npc.modNPC.PreAI();
}
return true;
}
public static void AI(NPC npc)
{
npc.modNPC?.AI();
foreach (var hook in HookAI)
{
hook(npc);
}
}
public static void PostAI(NPC npc)
{
npc.modNPC?.PostAI();
foreach (var hook in HookPostAI)
{
hook(npc);
}
}
//in Terraria.NetMessage.SendData at end of case 23 call
// NPCLoader.SendExtraAI(nPC, writer);
public static void SendExtraAI(NPC npc, BinaryWriter writer)
{
if (npc.modNPC != null)
{
byte[] data;
using (MemoryStream stream = new MemoryStream())
{
using (BinaryWriter modWriter = new BinaryWriter(stream))
{
npc.modNPC.SendExtraAI(modWriter);
modWriter.Flush();
data = stream.ToArray();
}
}
writer.Write((byte)data.Length);
if (data.Length > 0)
{
writer.Write(data);
}
}
}
//in Terraria.MessageBuffer.GetData at end of case 27 add
// NPCLoader.ReceiveExtraAI(nPC, reader);
public static void ReceiveExtraAI(NPC npc, BinaryReader reader)
{
if (npc.modNPC != null)
{
byte[] extraAI = reader.ReadBytes(reader.ReadByte());
if (extraAI.Length > 0)
{
using (MemoryStream stream = new MemoryStream(extraAI))
{
using (BinaryReader modReader = new BinaryReader(stream))
{
npc.modNPC.ReceiveExtraAI(modReader);
}
}
}
}
}
//in Terraria.NPC split VanillaFindFrame from FindFrame and make FindFrame call this
public static void FindFrame(NPC npc, int frameHeight)
{
int type = npc.type;
if (npc.modNPC != null && npc.modNPC.animationType > 0)
{
npc.type = npc.modNPC.animationType;
}
npc.VanillaFindFrame(frameHeight);
npc.type = type;
npc.modNPC?.FindFrame(frameHeight);
foreach (var hook in HookFindFrame)
{
hook(npc, frameHeight);
}
}
//in Terraria.NPC rename HitEffect to vanillaHitEffect and make HitEffect call this
public static void HitEffect(NPC npc, int hitDirection, double damage)
{
npc.VanillaHitEffect(hitDirection, damage);
npc.modNPC?.HitEffect(hitDirection, damage);
foreach (var hook in HookHitEffect)
{
hook(npc, hitDirection, damage);
}
}
public static void UpdateLifeRegen(NPC npc, ref int damage)
{
npc.modNPC?.UpdateLifeRegen(ref damage);
foreach (var hook in HookUpdateLifeRegen)
{
hook(npc, ref damage);
}
}
public static bool CheckActive(NPC npc)
{
if (npc.modNPC != null && !npc.modNPC.CheckActive())
{
return false;
}
foreach (var hook in HookCheckActive)
{
if (!hook(npc))
{
return false;
}
}
return true;
}
public static bool CheckDead(NPC npc)
{
if (npc.modNPC != null && !npc.modNPC.CheckDead())
{
return false;
}
foreach (var hook in HookCheckDead)
{
if (!hook(npc))
{
return false;
}
}
return true;
}
//in Terraria.NPC.NPCLoot after hardmode meteor head check add
// if(!NPCLoader.PreNPCLoot(this)) { return; }
public static bool PreNPCLoot(NPC npc)
{
foreach (var hook in HookPreNPCLoot)
{
if (!hook(npc))
{
blockLoot.Clear();
return false;
}
}
if (npc.modNPC != null && !npc.modNPC.PreNPCLoot())
{
blockLoot.Clear();
return false;
}
return true;
}
//in Terraria.NPC.NPCLoot before heart and star drops add NPCLoader.NPCLoot(this);
public static void NPCLoot(NPC npc)
{
npc.modNPC?.NPCLoot();
foreach (var hook in HookNPCLoot)
{
hook(npc);
}
blockLoot.Clear();
}
//in Terraria.NPC.NPCLoot after determing potion type call
// NPCLoader.BossLoot(this, ref name, ref num70);
public static void BossLoot(NPC npc, ref string name, ref int potionType)
{
npc.modNPC?.BossLoot(ref name, ref potionType);
}
//in Terraria.NPC.DropBossBags after if statements setting bag type call
// NPCLoader.BossBag(this, ref num);
public static void BossBag(NPC npc, ref int bagType)
{
if (npc.modNPC != null)
{
bagType = npc.modNPC.bossBag;
}
}
//in Terraria.Player.Update for damage from NPCs in if statement checking immunities, etc.
// add NPCLoader.CanHitPlayer(Main.npc[num249], this, ref num250) &&
public static bool CanHitPlayer(NPC npc, Player target, ref int cooldownSlot)
{
foreach (var hook in HookCanHitPlayer)
{
if (!hook(npc, target, ref cooldownSlot))
{
return false;
}
}
if (npc.modNPC != null)
{
return npc.modNPC.CanHitPlayer(target, ref cooldownSlot);
}
return true;
}
//in Terraria.Player.Update for damage from NPCs after applying banner buff
// add local crit variable and call this
public static void ModifyHitPlayer(NPC npc, Player target, ref int damage, ref bool crit)
{
npc.modNPC?.ModifyHitPlayer(target, ref damage, ref crit);
foreach (var hook in HookModifyHitPlayer)
{
hook(npc, target, ref damage, ref crit);
}
}
//in Terraria.Player.Update for damage from NPCs
// assign return value from Player.Hurt to local variable then call this
public static void OnHitPlayer(NPC npc, Player target, int damage, bool crit)
{
npc.modNPC?.OnHitPlayer(target, damage, crit);
foreach (var hook in HookOnHitPlayer)
{
hook(npc, target, damage, crit);
}
}
//Terraria.NPC.UpdateNPC for friendly NPC taking damage (check patch files)
//Terraria.NPC.AI in aiStyle 7 for detecting threats (check patch files)
public static bool? CanHitNPC(NPC npc, NPC target)
{
bool? flag = null;
foreach (var hook in HookCanHitNPC)
{
bool? canHit = hook(npc, target);
if (canHit.HasValue && !canHit.Value)
{
return false;
}
if (canHit.HasValue)
{
flag = canHit.Value;
}
}
if (npc.modNPC != null)
{
bool? canHit = npc.modNPC.CanHitNPC(target);
if (canHit.HasValue && !canHit.Value)
{
return false;
}
if (canHit.HasValue)
{
flag = canHit.Value;
}
}
return flag;
}
//in Terraria.NPC.UpdateNPC for friendly NPC taking damage add local crit variable then call this
public static void ModifyHitNPC(NPC npc, NPC target, ref int damage, ref float knockback, ref bool crit)
{
npc.modNPC?.ModifyHitNPC(target, ref damage, ref knockback, ref crit);
foreach (var hook in HookModifyHitNPC)
{
hook(npc, target, ref damage, ref knockback, ref crit);
}
}
//in Terraria.NPC.UpdateNPC for friendly NPC taking damage before dryad ward call this
public static void OnHitNPC(NPC npc, NPC target, int damage, float knockback, bool crit)
{
npc.modNPC?.OnHitNPC(target, damage, knockback, crit);
foreach (var hook in HookOnHitNPC)
{
hook(npc, target, damage, knockback, crit);
}
}
//in Terraria.Player.ItemCheck call after ItemLoader.CanHitNPC
public static bool? CanBeHitByItem(NPC npc, Player player, Item item)
{
bool? flag = null;
foreach (var hook in HookCanBeHitByItem)
{
bool? canHit = hook(npc, player, item);
if (canHit.HasValue && !canHit.Value)
{
return false;
}
if (canHit.HasValue)
{
flag = canHit.Value;
}
}
if (npc.modNPC != null)
{
bool? canHit = npc.modNPC.CanBeHitByItem(player, item);
if (canHit.HasValue && !canHit.Value)
{
return false;
}
if (canHit.HasValue)
{
flag = canHit.Value;
}
}
return flag;
}
//in Terraria.Player.ItemCheck call after ItemLoader.ModifyHitNPC
public static void ModifyHitByItem(NPC npc, Player player, Item item, ref int damage, ref float knockback, ref bool crit)
{
npc.modNPC?.ModifyHitByItem(player, item, ref damage, ref knockback, ref crit);
foreach (var hook in HookModifyHitByItem)
{
hook(npc, player, item, ref damage, ref knockback, ref crit);
}
}
//in Terraria.Player.ItemCheck call after ItemLoader.OnHitNPC
public static void OnHitByItem(NPC npc, Player player, Item item, int damage, float knockback, bool crit)
{
npc.modNPC?.OnHitByItem(player, item, damage, knockback, crit);
foreach (var hook in HookOnHitByItem)
{
hook(npc, player, item, damage, knockback, crit);
}
}
//in Terraria.Projectile.Damage call after ProjectileLoader.CanHitNPC
public static bool? CanBeHitByProjectile(NPC npc, Projectile projectile)
{
bool? flag = null;
foreach (var hook in HookCanBeHitByProjectile)
{
bool? canHit = hook(npc, projectile);
if (canHit.HasValue && !canHit.Value)
{
return false;
}
if (canHit.HasValue)
{
flag = canHit.Value;
}
}
if (npc.modNPC != null)
{
bool? canHit = npc.modNPC.CanBeHitByProjectile(projectile);
if (canHit.HasValue && !canHit.Value)
{
return false;
}
if (canHit.HasValue)
{
flag = canHit.Value;
}
}
return flag;
}
//in Terraria.Projectile.Damage call after ProjectileLoader.ModifyHitNPC
public static void ModifyHitByProjectile(NPC npc, Projectile projectile, ref int damage, ref float knockback, ref bool crit, ref int hitDirection)
{
npc.modNPC?.ModifyHitByProjectile(projectile, ref damage, ref knockback, ref crit, ref hitDirection);
foreach (var hook in HookModifyHitByProjectile)
{
hook(npc, projectile, ref damage, ref knockback, ref crit, ref hitDirection);
}
}
//in Terraria.Projectile.Damage call after ProjectileLoader.OnHitNPC
public static void OnHitByProjectile(NPC npc, Projectile projectile, int damage, float knockback, bool crit)
{
npc.modNPC?.OnHitByProjectile(projectile, damage, knockback, crit);
foreach (var hook in HookOnHitByProjectile)
{
hook(npc, projectile, damage, knockback, crit);
}
}
//in Terraria.NPC.StrikeNPC place modifications to num in if statement checking this
public static bool StrikeNPC(NPC npc, ref double damage, int defense, ref float knockback, int hitDirection, ref bool crit)
{
bool flag = true;
if (npc.modNPC != null)
{
flag = npc.modNPC.StrikeNPC(ref damage, defense, ref knockback, hitDirection, ref crit);
}
foreach (var hook in HookStrikeNPC)
{
if (!hook(npc, ref damage, defense, ref knockback, hitDirection, ref crit))
{
flag = false;
}
}
return flag;
}
//in Terraria.NPC.GetBossHeadTextureIndex call this before returning
public static void BossHeadSlot(NPC npc, ref int index)
{
npc.modNPC?.BossHeadSlot(ref index);
foreach (var hook in HookBossHeadSlot)
{
hook(npc, ref index);
}
}
//in Terraria.NPC.GetBossHeadRotation call this before returning
public static void BossHeadRotation(NPC npc, ref float rotation)
{
npc.modNPC?.BossHeadRotation(ref rotation);
foreach (var hook in HookBossHeadRotation)
{
hook(npc, ref rotation);
}
}
//in Terraria.NPC.GetBossHeadSpriteEffects call this before returning
public static void BossHeadSpriteEffects(NPC npc, ref SpriteEffects spriteEffects)
{
npc.modNPC?.BossHeadSpriteEffects(ref spriteEffects);
foreach (var hook in HookBossHeadSpriteEffects)
{
hook(npc, ref spriteEffects);
}
}
//at beginning of Terraria.NPC.GetAlpha add
// Color? modColor = NPCLoader.GetAlpha(this, new Color); if(modColor.HasValue) { return modColor.Value; }
public static Color? GetAlpha(NPC npc, Color lightColor)
{
foreach (var hook in HookGetAlpha)
{
Color? color = hook(npc, lightColor);
if (color.HasValue)
{
return color.Value;
}
}
return npc.modNPC?.GetAlpha(lightColor);
}
public static void DrawEffects(NPC npc, ref Color drawColor)
{
npc.modNPC?.DrawEffects(ref drawColor);
foreach (var hook in HookDrawEffects)
{
hook(npc, ref drawColor);
}
}
//in Terraria.Main.DrawNPC after modifying draw color add
// if(!NPCLoader.PreDraw(Main.npc[i], Main.spriteBatch, color9))
// { NPCLoader.PostDraw(Main.npc[k], Main.spriteBatch, color9); return; }
public static bool PreDraw(NPC npc, SpriteBatch spriteBatch, Color drawColor)
{
foreach (var hook in HookPreDraw)
{
if (!hook(npc, spriteBatch, drawColor))
{
return false;
}
}
if (npc.modNPC != null)
{
return npc.modNPC.PreDraw(spriteBatch, drawColor);
}
return true;
}
//call this at end of Terraria.Main.DrawNPC
public static void PostDraw(NPC npc, SpriteBatch spriteBatch, Color drawColor)
{
npc.modNPC?.PostDraw(spriteBatch, drawColor);
foreach (var hook in HookPostDraw)
{
hook(npc, spriteBatch, drawColor);
}
}
public static bool DrawHealthBar(NPC npc, ref float scale)
{
Vector2 position = new Vector2(npc.position.X + npc.width / 2, npc.position.Y + npc.gfxOffY);
if (Main.HealthBarDrawSettings == 1)
{
position.Y += npc.height + 10f + Main.NPCAddHeight(npc.whoAmI);
}
else if (Main.HealthBarDrawSettings == 2)
{
position.Y -= 24f + Main.NPCAddHeight(npc.whoAmI) / 2f;
}
foreach (var hook in HookDrawHealthBar)
{
bool? result = hook(npc, Main.HealthBarDrawSettings, ref scale, ref position);
if (result.HasValue)
{
if (result.Value)
{
DrawHealthBar(npc, position, scale);
}
return false;
}
}
if (NPCLoader.IsModNPC(npc))
{
bool? result = npc.modNPC.DrawHealthBar(Main.HealthBarDrawSettings, ref scale, ref position);
if (result.HasValue)
{
if (result.Value)
{
DrawHealthBar(npc, position, scale);
}
return false;
}
}
return true;
}
private static void DrawHealthBar(NPC npc, Vector2 position, float scale)
{
float alpha = Lighting.Brightness((int)(npc.Center.X / 16f), (int)(npc.Center.Y / 16f));
Main.instance.DrawHealthBar(position.X, position.Y, npc.life, npc.lifeMax, alpha, scale);
}
//in Terraria.NPC.SpawnNPC after modifying NPC.spawnRate and NPC.maxSpawns call
// NPCLoader.EditSpawnRate(Main.player[j], ref NPC.spawnRate, ref NPC.maxSpawns);
public static void EditSpawnRate(Player player, ref int spawnRate, ref int maxSpawns)
{
foreach (var hook in HookEditSpawnRate)
{
hook(player, ref spawnRate, ref maxSpawns);
}
}
//in Terraria.NPC.SpawnNPC after modifying spawn ranges call
// NPCLoader.EditSpawnRange(Main.player[j], ref NPC.spawnRangeX, ref NPC.spawnRangeY,
// ref NPC.safeRangeX, ref NPC.safeRangeY);
public static void EditSpawnRange(Player player, ref int spawnRangeX, ref int spawnRangeY,
ref int safeRangeX, ref int safeRangeY)
{
foreach (var hook in HookEditSpawnRange)
{
hook(player, ref spawnRangeX, ref spawnRangeY, ref safeRangeX, ref safeRangeY);
}
}
//in Terraria.NPC.SpawnNPC after initializing variables and before actual spawning add
// int? spawnChoice = NPCLoader.ChooseSpawn(spawnInfo); if(!spawnChoice.HasValue) { return; }
// int spawn = spawnChoice.Value; if(spawn != 0) { goto endVanillaSpawn; }
public static int? ChooseSpawn(NPCSpawnInfo spawnInfo)
{
NPCSpawnHelper.Reset();
NPCSpawnHelper.DoChecks(spawnInfo);
IDictionary<int, float> pool = new Dictionary<int, float>();
pool[0] = 1f;
foreach (ModNPC npc in npcs)
{
float weight = npc.CanSpawn(spawnInfo);
if (weight > 0f)
{
pool[npc.npc.type] = weight;
}
}
foreach (var hook in HookEditSpawnPool)
{
hook(pool, spawnInfo);
}
float totalWeight = 0f;
foreach (int type in pool.Keys)
{
totalWeight += pool[type];
}
float choice = (float)Main.rand.NextDouble() * totalWeight;
foreach (int type in pool.Keys)
{
float weight = pool[type];
if (choice < weight)
{
return type;
}
choice -= weight;
}
return null;
}
//in Terraria.NPC.SpawnNPC before spawning pinky add
// endVanillaSpawn: if(spawn != 0) { num46 = NPCLoader.SpawnNPC(spawn, num, num2); }
public static int SpawnNPC(int type, int tileX, int tileY)
{
var npc = type >= NPCID.Count ?
GetNPC(type).SpawnNPC(tileX, tileY) :
NPC.NewNPC(tileX * 16 + 8, tileY * 16, type);
foreach (var hook in HookSpawnNPC)
{
hook(npc, tileX, tileY);
}
return npc;
}
//at end of Terraria.Main.UpdateTime inside blocks add NPCLoader.CanTownNPCSpawn(num40, num42);
public static void CanTownNPCSpawn(int numTownNPCs, int money)
{
foreach (ModNPC npc in npcs)
{
if (npc.npc.townNPC && NPC.TypeToHeadIndex(npc.npc.type) >= 0 && !NPC.AnyNPCs(npc.npc.type) &&
npc.CanTownNPCSpawn(numTownNPCs, money))
{
Main.nextNPC[npc.npc.type] = true;
if (WorldGen.spawnNPC == 0)
{
WorldGen.spawnNPC = npc.npc.type;
}
}
}
}
//at beginning of Terraria.WorldGen.CheckConditions add
// if(!NPCLoader.CheckConditions(type)) { return false; }
public static bool CheckConditions(int type)
{
return GetNPC(type)?.CheckConditions(WorldGen.roomX1, WorldGen.roomX2, WorldGen.roomY1, WorldGen.roomY2) ?? true;
}
//in Terraria.NPC.getNewNPCName replace final return with return NPCLoader.TownNPCName(npcType);
public static string TownNPCName(int type)
{
return GetNPC(type)?.TownNPCName() ?? "";
}
public static bool UsesPartyHat(NPC npc)
{
return npc.modNPC?.UsesPartyHat() ?? true;
}
//in Terraria.NPC.GetChat before returning result add NPCLoader.GetChat(this, ref result);
public static void GetChat(NPC npc, ref string chat)
{
if (npc.modNPC != null)
{
chat = npc.modNPC.GetChat();
}
foreach (var hook in HookGetChat)
{
hook(npc, ref chat);
}
}
//in Terraria.Main.GUIChatDrawInner after if/else chain setting text and text2 call
// NPCLoader.SetChatButtons(ref text, ref text2);
public static void SetChatButtons(ref string button, ref string button2)
{
if (Main.player[Main.myPlayer].talkNPC >= 0)
{
NPC npc = Main.npc[Main.player[Main.myPlayer].talkNPC];
npc.modNPC?.SetChatButtons(ref button, ref button2);
}
}
//add 1 to Terraria.Main.numShops
//in Terraria.Main.GUIChatDrawInner after type checks for first button click call
// NPCLoader.OnChatButtonClicked(true);
// after type checks for second button click call NPCLoader.OnChatButtonClicked(false);
public static void OnChatButtonClicked(bool firstButton)
{
NPC npc = Main.npc[Main.player[Main.myPlayer].talkNPC];
if (npc.modNPC != null)
{
bool shop = false;
npc.modNPC.OnChatButtonClicked(firstButton, ref shop);
Main.PlaySound(12, -1, -1, 1);
if (shop)
{
Main.playerInventory = true;
Main.npcChatText = "";
Main.npcShop = Main.MaxShopIDs - 1;
Main.instance.shop[Main.npcShop].SetupShop(npc.type);
}
}
}
//in Terraria.Chest.SetupShop before discount call NPCLoader.SetupShop(type, this, ref num);
public static void SetupShop(int type, Chest shop, ref int nextSlot)
{
if (type < shopToNPC.Length)
{
type = shopToNPC[type];
}
else
{
GetNPC(type)?.SetupShop(shop, ref nextSlot);
}
foreach (var hook in HookSetupShop)
{
hook(type, shop, ref nextSlot);
}
}
//at end of Terraria.Chest.SetupTravelShop call NPCLoader.SetupTravelShop(Main.travelShop, ref num2);
public static void SetupTravelShop(int[] shop, ref int nextSlot)
{
foreach (var hook in HookSetupTravelShop)
{
hook(shop, ref nextSlot);
}
}
//in Terraria.NPC.AI in aiStyle 7 after buffing damage multiplier and defense add
// NPCLoader.BuffTownNPC(ref num378, ref this.defense);
public static void BuffTownNPC(ref float damageMult, ref int defense)
{
foreach (var hook in HookBuffTownNPC)
{
hook(ref damageMult, ref defense);
}
}
//attack type 0 = throwing
// num405 = type, num406 = damage, knockBack, scaleFactor7 = speed multiplier, num407 = attack delay
// num408 = unknown, maxValue3 = unknown, num409 = gravity correction factor, num411 = random speed offset
//attack type 1 = shooting
// num413 = type, num414 = damage, scaleFactor8 = speed multiplier, num415 = attack delay,
// num416 = unknown, maxValue4 = unknown, knockBack2, num417 = gravity correction,
// flag53 = in between shots, num418 = random speed offset
//attack type 2 = magic
// num423 = type, num424 = damage, scaleFactor9 = speed multiplier, num425 = attack delay,
// num426 = unknown, maxValue5 = unknown, knockBack3, num427 = gravity correction factor,
// num429 = aura light multiplier, num430 = random speed offset
//attack type 3 = swinging
// num439 = unknown, maxValue6 = unknown, num440 = damage, num441 = knockback,
// num442 = item width, num443 = item height
//unknowns are associated with ai[1], localAI[1], and localAI[3] when ai[0] is either 0 or 8
//check patch files for town NPC attacks
public static void TownNPCAttackStrength(NPC npc, ref int damage, ref float knockback)
{
npc.modNPC?.TownNPCAttackStrength(ref damage, ref knockback);
foreach (var hook in HookTownNPCAttackStrength)
{
hook(npc, ref damage, ref knockback);
}
}
public static void TownNPCAttackCooldown(NPC npc, ref int cooldown, ref int randExtraCooldown)
{
npc.modNPC?.TownNPCAttackCooldown(ref cooldown, ref randExtraCooldown);
foreach (var hook in HookTownNPCAttackCooldown)
{
hook(npc, ref cooldown, ref randExtraCooldown);
}
}
public static void TownNPCAttackProj(NPC npc, ref int projType, ref int attackDelay)
{
npc.modNPC?.TownNPCAttackProj(ref projType, ref attackDelay);
foreach (var hook in HookTownNPCAttackProj)
{
hook(npc, ref projType, ref attackDelay);
}
}
public static void TownNPCAttackProjSpeed(NPC npc, ref float multiplier, ref float gravityCorrection,
ref float randomOffset)
{
npc.modNPC?.TownNPCAttackProjSpeed(ref multiplier, ref gravityCorrection, ref randomOffset);
foreach (var hook in HookTownNPCAttackProjSpeed)
{
hook(npc, ref multiplier, ref gravityCorrection, ref randomOffset);
}
}
public static void TownNPCAttackShoot(NPC npc, ref bool inBetweenShots)
{
npc.modNPC?.TownNPCAttackShoot(ref inBetweenShots);
foreach (var hook in HookTownNPCAttackShoot)
{
hook(npc, ref inBetweenShots);
}
}
public static void TownNPCAttackMagic(NPC npc, ref float auraLightMultiplier)
{
npc.modNPC?.TownNPCAttackMagic(ref auraLightMultiplier);
foreach (var hook in HookTownNPCAttackMagic)
{
hook(npc, ref auraLightMultiplier);
}
}
public static void TownNPCAttackSwing(NPC npc, ref int itemWidth, ref int itemHeight)
{
npc.modNPC?.TownNPCAttackSwing(ref itemWidth, ref itemHeight);
foreach (var hook in HookTownNPCAttackSwing)
{
hook(npc, ref itemWidth, ref itemHeight);
}
}
//in Terraria.Main.DrawNPCExtras for attack type 1 after if else chain setting num2-4 call
// NPCLoader.DrawTownAttackGun(n, ref num2, ref num3, ref num4);
public static void DrawTownAttackGun(NPC npc, ref float scale, ref int item, ref int closeness)
{
npc.modNPC?.DrawTownAttackGun(ref scale, ref item, ref closeness);
foreach (var hook in HookDrawTownAttackGun)
{
hook(npc, ref scale, ref item, ref closeness);
}
}
//in Terraria.Main.DrawNPCExtras for attack type 3 after if else chain call
// NPCLoader.DrawTownAttackSwing(n, ref texture2D5, ref num6, ref scaleFactor, ref zero);
public static void DrawTownAttackSwing(NPC npc, ref Texture2D item, ref int itemSize, ref float scale, ref Vector2 offset)
{
npc.modNPC?.DrawTownAttackSwing(ref item, ref itemSize, ref scale, ref offset);
foreach (var hook in HookDrawTownAttackSwing)
{
hook(npc, ref item, ref itemSize, ref scale, ref offset);
}
}
}
}
| |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the support-2013-04-15.normal.json service model.
*/
using System;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Generic;
using Amazon.AWSSupport.Model;
namespace Amazon.AWSSupport
{
/// <summary>
/// Interface for accessing AWSSupport
///
/// AWS Support
/// <para>
/// The AWS Support API reference is intended for programmers who need detailed information
/// about the AWS Support operations and data types. This service enables you to manage
/// your AWS Support cases programmatically. It uses HTTP methods that return results
/// in JSON format.
/// </para>
///
/// <para>
/// The AWS Support service also exposes a set of <a href="https://aws.amazon.com/premiumsupport/trustedadvisor/">Trusted
/// Advisor</a> features. You can retrieve a list of checks and their descriptions, get
/// check results, specify checks to refresh, and get the refresh status of checks.
/// </para>
///
/// <para>
/// The following list describes the AWS Support case management operations:
/// </para>
/// <ul> <li> <b>Service names, issue categories, and available severity levels. </b>The
/// <a>DescribeServices</a> and <a>DescribeSeverityLevels</a> operations return AWS service
/// names, service codes, service categories, and problem severity levels. You use these
/// values when you call the <a>CreateCase</a> operation. </li> <li> <b>Case creation,
/// case details, and case resolution.</b> The <a>CreateCase</a>, <a>DescribeCases</a>,
/// <a>DescribeAttachment</a>, and <a>ResolveCase</a> operations create AWS Support cases,
/// retrieve information about cases, and resolve cases.</li> <li> <b>Case communication.</b>
/// The <a>DescribeCommunications</a>, <a>AddCommunicationToCase</a>, and <a>AddAttachmentsToSet</a>
/// operations retrieve and add communications and attachments to AWS Support cases. </li>
/// </ul>
/// <para>
/// The following list describes the operations available from the AWS Support service
/// for Trusted Advisor:
/// </para>
/// <ul> <li> <a>DescribeTrustedAdvisorChecks</a> returns the list of checks that run
/// against your AWS resources.</li> <li>Using the <code>CheckId</code> for a specific
/// check returned by <a>DescribeTrustedAdvisorChecks</a>, you can call <a>DescribeTrustedAdvisorCheckResult</a>
/// to obtain the results for the check you specified.</li> <li> <a>DescribeTrustedAdvisorCheckSummaries</a>
/// returns summarized results for one or more Trusted Advisor checks.</li> <li> <a>RefreshTrustedAdvisorCheck</a>
/// requests that Trusted Advisor rerun a specified check. </li> <li> <a>DescribeTrustedAdvisorCheckRefreshStatuses</a>
/// reports the refresh status of one or more checks. </li> </ul>
/// <para>
/// For authentication of requests, AWS Support uses <a href="http://docs.aws.amazon.com/general/latest/gr/signature-version-4.html">Signature
/// Version 4 Signing Process</a>.
/// </para>
///
/// <para>
/// See <a href="http://docs.aws.amazon.com/awssupport/latest/user/Welcome.html">About
/// the AWS Support API</a> in the <i>AWS Support User Guide</i> for information about
/// how to use this service to create and manage your support cases, and how to call Trusted
/// Advisor for results of checks on your resources.
/// </para>
/// </summary>
public partial interface IAmazonAWSSupport : IDisposable
{
#region AddAttachmentsToSet
/// <summary>
/// Initiates the asynchronous execution of the AddAttachmentsToSet operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the AddAttachmentsToSet operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<AddAttachmentsToSetResponse> AddAttachmentsToSetAsync(AddAttachmentsToSetRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region AddCommunicationToCase
/// <summary>
/// Initiates the asynchronous execution of the AddCommunicationToCase operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the AddCommunicationToCase operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<AddCommunicationToCaseResponse> AddCommunicationToCaseAsync(AddCommunicationToCaseRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region CreateCase
/// <summary>
/// Initiates the asynchronous execution of the CreateCase operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the CreateCase operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<CreateCaseResponse> CreateCaseAsync(CreateCaseRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region DescribeAttachment
/// <summary>
/// Initiates the asynchronous execution of the DescribeAttachment operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DescribeAttachment operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<DescribeAttachmentResponse> DescribeAttachmentAsync(DescribeAttachmentRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region DescribeCases
/// <summary>
/// Initiates the asynchronous execution of the DescribeCases operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DescribeCases operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<DescribeCasesResponse> DescribeCasesAsync(DescribeCasesRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region DescribeCommunications
/// <summary>
/// Initiates the asynchronous execution of the DescribeCommunications operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DescribeCommunications operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<DescribeCommunicationsResponse> DescribeCommunicationsAsync(DescribeCommunicationsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region DescribeServices
/// <summary>
/// Returns the current list of AWS services and a list of service categories that applies
/// to each one. You then use service names and categories in your <a>CreateCase</a> requests.
/// Each AWS service has its own set of categories.
///
///
/// <para>
/// The service codes and category codes correspond to the values that are displayed in
/// the <b>Service</b> and <b>Category</b> drop-down lists on the AWS Support Center <a
/// href="https://console.aws.amazon.com/support/home#/case/create">Create Case</a> page.
/// The values in those fields, however, do not necessarily match the service codes and
/// categories returned by the <code>DescribeServices</code> request. Always use the service
/// codes and categories obtained programmatically. This practice ensures that you always
/// have the most recent set of service and category codes.
/// </para>
/// </summary>
/// <param name="cancellationToken"> ttd1
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the DescribeServices service method, as returned by AWSSupport.</returns>
/// <exception cref="Amazon.AWSSupport.Model.InternalServerErrorException">
/// An internal server error occurred.
/// </exception>
Task<DescribeServicesResponse> DescribeServicesAsync(System.Threading.CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Initiates the asynchronous execution of the DescribeServices operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DescribeServices operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<DescribeServicesResponse> DescribeServicesAsync(DescribeServicesRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region DescribeSeverityLevels
/// <summary>
/// Returns the list of severity levels that you can assign to an AWS Support case. The
/// severity level for a case is also a field in the <a>CaseDetails</a> data type included
/// in any <a>CreateCase</a> request.
/// </summary>
/// <param name="cancellationToken"> ttd1
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
///
/// <returns>The response from the DescribeSeverityLevels service method, as returned by AWSSupport.</returns>
/// <exception cref="Amazon.AWSSupport.Model.InternalServerErrorException">
/// An internal server error occurred.
/// </exception>
Task<DescribeSeverityLevelsResponse> DescribeSeverityLevelsAsync(System.Threading.CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Initiates the asynchronous execution of the DescribeSeverityLevels operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DescribeSeverityLevels operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<DescribeSeverityLevelsResponse> DescribeSeverityLevelsAsync(DescribeSeverityLevelsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region DescribeTrustedAdvisorCheckRefreshStatuses
/// <summary>
/// Initiates the asynchronous execution of the DescribeTrustedAdvisorCheckRefreshStatuses operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DescribeTrustedAdvisorCheckRefreshStatuses operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<DescribeTrustedAdvisorCheckRefreshStatusesResponse> DescribeTrustedAdvisorCheckRefreshStatusesAsync(DescribeTrustedAdvisorCheckRefreshStatusesRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region DescribeTrustedAdvisorCheckResult
/// <summary>
/// Initiates the asynchronous execution of the DescribeTrustedAdvisorCheckResult operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DescribeTrustedAdvisorCheckResult operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<DescribeTrustedAdvisorCheckResultResponse> DescribeTrustedAdvisorCheckResultAsync(DescribeTrustedAdvisorCheckResultRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region DescribeTrustedAdvisorChecks
/// <summary>
/// Initiates the asynchronous execution of the DescribeTrustedAdvisorChecks operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DescribeTrustedAdvisorChecks operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<DescribeTrustedAdvisorChecksResponse> DescribeTrustedAdvisorChecksAsync(DescribeTrustedAdvisorChecksRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region DescribeTrustedAdvisorCheckSummaries
/// <summary>
/// Initiates the asynchronous execution of the DescribeTrustedAdvisorCheckSummaries operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the DescribeTrustedAdvisorCheckSummaries operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<DescribeTrustedAdvisorCheckSummariesResponse> DescribeTrustedAdvisorCheckSummariesAsync(DescribeTrustedAdvisorCheckSummariesRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region RefreshTrustedAdvisorCheck
/// <summary>
/// Initiates the asynchronous execution of the RefreshTrustedAdvisorCheck operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the RefreshTrustedAdvisorCheck operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<RefreshTrustedAdvisorCheckResponse> RefreshTrustedAdvisorCheckAsync(RefreshTrustedAdvisorCheckRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
#region ResolveCase
/// <summary>
/// Initiates the asynchronous execution of the ResolveCase operation.
/// </summary>
///
/// <param name="request">Container for the necessary parameters to execute the ResolveCase operation.</param>
/// <param name="cancellationToken">
/// A cancellation token that can be used by other objects or threads to receive notice of cancellation.
/// </param>
/// <returns>The task object representing the asynchronous operation.</returns>
Task<ResolveCaseResponse> ResolveCaseAsync(ResolveCaseRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken));
#endregion
}
}
| |
using System;
using System.Diagnostics;
namespace VolumeInfo.Extension
{
public static partial class ExtensionVolumeInfo
{
#region VolumeByte
[DebuggerStepThroughAttribute]
public static VolumeByte Byte(this System.Int16 value)
{
return new VolumeByte(value);
}
[DebuggerStepThroughAttribute]
public static VolumeByte Byte(this System.Int32 value)
{
return new VolumeByte(value);
}
[DebuggerStepThroughAttribute]
public static VolumeByte Byte(this System.Int64 value)
{
return new VolumeByte(value);
}
[DebuggerStepThroughAttribute]
public static VolumeByte Byte(this System.UInt32 value)
{
return new VolumeByte(value);
}
[DebuggerStepThroughAttribute]
public static VolumeByte Byte(this System.UInt64 value)
{
return new VolumeByte(value);
}
[DebuggerStepThroughAttribute]
public static VolumeByte Byte(this System.Single value)
{
return new VolumeByte(value);
}
[DebuggerStepThroughAttribute]
public static VolumeByte Byte(this System.Double value)
{
return new VolumeByte(value);
}
#endregion
#region VolumeGibibyte
[DebuggerStepThroughAttribute]
public static VolumeGibibyte Gibibyte(this System.Int16 value)
{
return new VolumeGibibyte(value);
}
[DebuggerStepThroughAttribute]
public static VolumeGibibyte Gibibyte(this System.Int32 value)
{
return new VolumeGibibyte(value);
}
[DebuggerStepThroughAttribute]
public static VolumeGibibyte Gibibyte(this System.Int64 value)
{
return new VolumeGibibyte(value);
}
[DebuggerStepThroughAttribute]
public static VolumeGibibyte Gibibyte(this System.UInt32 value)
{
return new VolumeGibibyte(value);
}
[DebuggerStepThroughAttribute]
public static VolumeGibibyte Gibibyte(this System.UInt64 value)
{
return new VolumeGibibyte(value);
}
[DebuggerStepThroughAttribute]
public static VolumeGibibyte Gibibyte(this System.Single value)
{
return new VolumeGibibyte(value);
}
[DebuggerStepThroughAttribute]
public static VolumeGibibyte Gibibyte(this System.Double value)
{
return new VolumeGibibyte(value);
}
#endregion
#region VolumeKibibyte
[DebuggerStepThroughAttribute]
public static VolumeKibibyte Kibibyte(this System.Int16 value)
{
return new VolumeKibibyte(value);
}
[DebuggerStepThroughAttribute]
public static VolumeKibibyte Kibibyte(this System.Int32 value)
{
return new VolumeKibibyte(value);
}
[DebuggerStepThroughAttribute]
public static VolumeKibibyte Kibibyte(this System.Int64 value)
{
return new VolumeKibibyte(value);
}
[DebuggerStepThroughAttribute]
public static VolumeKibibyte Kibibyte(this System.UInt32 value)
{
return new VolumeKibibyte(value);
}
[DebuggerStepThroughAttribute]
public static VolumeKibibyte Kibibyte(this System.UInt64 value)
{
return new VolumeKibibyte(value);
}
[DebuggerStepThroughAttribute]
public static VolumeKibibyte Kibibyte(this System.Single value)
{
return new VolumeKibibyte(value);
}
[DebuggerStepThroughAttribute]
public static VolumeKibibyte Kibibyte(this System.Double value)
{
return new VolumeKibibyte(value);
}
#endregion
#region VolumeMebibyte
[DebuggerStepThroughAttribute]
public static VolumeMebibyte Mebibyte(this System.Int16 value)
{
return new VolumeMebibyte(value);
}
[DebuggerStepThroughAttribute]
public static VolumeMebibyte Mebibyte(this System.Int32 value)
{
return new VolumeMebibyte(value);
}
[DebuggerStepThroughAttribute]
public static VolumeMebibyte Mebibyte(this System.Int64 value)
{
return new VolumeMebibyte(value);
}
[DebuggerStepThroughAttribute]
public static VolumeMebibyte Mebibyte(this System.UInt32 value)
{
return new VolumeMebibyte(value);
}
[DebuggerStepThroughAttribute]
public static VolumeMebibyte Mebibyte(this System.UInt64 value)
{
return new VolumeMebibyte(value);
}
[DebuggerStepThroughAttribute]
public static VolumeMebibyte Mebibyte(this System.Single value)
{
return new VolumeMebibyte(value);
}
[DebuggerStepThroughAttribute]
public static VolumeMebibyte Mebibyte(this System.Double value)
{
return new VolumeMebibyte(value);
}
#endregion
#region VolumePebibyte
[DebuggerStepThroughAttribute]
public static VolumePebibyte Pebibyte(this System.Int16 value)
{
return new VolumePebibyte(value);
}
[DebuggerStepThroughAttribute]
public static VolumePebibyte Pebibyte(this System.Int32 value)
{
return new VolumePebibyte(value);
}
[DebuggerStepThroughAttribute]
public static VolumePebibyte Pebibyte(this System.Int64 value)
{
return new VolumePebibyte(value);
}
[DebuggerStepThroughAttribute]
public static VolumePebibyte Pebibyte(this System.UInt32 value)
{
return new VolumePebibyte(value);
}
[DebuggerStepThroughAttribute]
public static VolumePebibyte Pebibyte(this System.UInt64 value)
{
return new VolumePebibyte(value);
}
[DebuggerStepThroughAttribute]
public static VolumePebibyte Pebibyte(this System.Single value)
{
return new VolumePebibyte(value);
}
[DebuggerStepThroughAttribute]
public static VolumePebibyte Pebibyte(this System.Double value)
{
return new VolumePebibyte(value);
}
#endregion
#region VolumeTebibyte
[DebuggerStepThroughAttribute]
public static VolumeTebibyte Tebibyte(this System.Int16 value)
{
return new VolumeTebibyte(value);
}
[DebuggerStepThroughAttribute]
public static VolumeTebibyte Tebibyte(this System.Int32 value)
{
return new VolumeTebibyte(value);
}
[DebuggerStepThroughAttribute]
public static VolumeTebibyte Tebibyte(this System.Int64 value)
{
return new VolumeTebibyte(value);
}
[DebuggerStepThroughAttribute]
public static VolumeTebibyte Tebibyte(this System.UInt32 value)
{
return new VolumeTebibyte(value);
}
[DebuggerStepThroughAttribute]
public static VolumeTebibyte Tebibyte(this System.UInt64 value)
{
return new VolumeTebibyte(value);
}
[DebuggerStepThroughAttribute]
public static VolumeTebibyte Tebibyte(this System.Single value)
{
return new VolumeTebibyte(value);
}
[DebuggerStepThroughAttribute]
public static VolumeTebibyte Tebibyte(this System.Double value)
{
return new VolumeTebibyte(value);
}
#endregion
}
}
| |
/* ====================================================================
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.DDF
{
using System;
using NPOI.Util;
using System.Collections.Generic;
using System.Text;
/// <summary>
/// The base abstract record from which all escher records are defined. Subclasses will need
/// to define methods for serialization/deserialization and for determining the record size.
/// </summary>
abstract public class EscherRecord : ICloneable
{
private static BitField fInstance = BitFieldFactory.GetInstance(0xfff0);
private static BitField fVersion = BitFieldFactory.GetInstance(0x000f);
private short _options;
private short _recordId;
/// <summary>
/// Initializes a new instance of the <see cref="EscherRecord"/> class.
/// </summary>
public EscherRecord()
{
}
/// <summary>
/// Delegates to FillFields(byte[], int, EscherRecordFactory)
/// </summary>
/// <param name="data">the bytes to serialize from</param>
/// <param name="f">the escher record factory</param>
/// <returns>The number of bytes written.</returns>
public int FillFields(byte[] data, IEscherRecordFactory f)
{
return FillFields(data, 0, f);
}
/// <summary>
/// The contract of this method is to deSerialize an escher record including
/// it's children.
/// </summary>
/// <param name="data">The byte array containing the Serialized escher
/// records.</param>
/// <param name="offset">The offset into the byte array.</param>
/// <param name="recordFactory">A factory for creating new escher records.</param>
/// <returns>The number of bytes written.</returns>
public abstract int FillFields(byte[] data, int offset, IEscherRecordFactory recordFactory);
/// <summary>
/// Reads the 8 byte header information and populates the
/// <c>options</c>
/// and
/// <c>recordId</c>
/// records.
/// </summary>
/// <param name="data">the byte array to Read from</param>
/// <param name="offset">the offset to start Reading from</param>
/// <returns>the number of bytes remaining in this record. This</returns>
protected int ReadHeader(byte[] data, int offset)
{
//EscherRecordHeader header = EscherRecordHeader.ReadHeader(data, offset);
//_options = header.Options;
//_recordId = header.RecordId;
//return header.RemainingBytes;
_options = LittleEndian.GetShort(data, offset);
_recordId = LittleEndian.GetShort(data, offset + 2);
int remainingBytes = LittleEndian.GetInt(data, offset + 4);
return remainingBytes;
}
/// <summary>
/// Read the options field from header and return instance part of it.
/// </summary>
/// <param name="data">the byte array to read from</param>
/// <param name="offset">the offset to start reading from</param>
/// <returns>value of instance part of options field</returns>
protected static short ReadInstance( byte[] data, int offset )
{
short options = LittleEndian.GetShort( data, offset );
return fInstance.GetShortValue( options );
}
/// <summary>
/// Determine whether this is a container record by inspecting the option
/// field.
/// </summary>
/// <value>
/// <c>true</c> if this instance is container record; otherwise, <c>false</c>.
/// </value>
public bool IsContainerRecord
{
get { return Version == (short)0x000f; }
}
/// <summary>
/// Gets or sets the options field for this record. All records have one
/// </summary>
/// <value>The options.</value>
internal virtual short Options
{
get { return _options; }
set
{
Version = (fVersion.GetShortValue(value));
Instance = (fInstance.GetShortValue(value));
this._options = value;
}
}
/// <summary>
/// Serializes to a new byte array. This is done by delegating to
/// Serialize(int, byte[]);
/// </summary>
/// <returns>the Serialized record.</returns>
public byte[] Serialize()
{
byte[] retval = new byte[RecordSize];
int length=Serialize(0, retval);
return retval;
}
/// <summary>
/// Serializes to an existing byte array without serialization listener.
/// This is done by delegating to Serialize(int, byte[], EscherSerializationListener).
/// </summary>
/// <param name="offset">the offset within the data byte array.</param>
/// <param name="data">the data array to Serialize to.</param>
/// <returns>The number of bytes written.</returns>
public int Serialize(int offset, byte[] data)
{
return Serialize(offset, data, new NullEscherSerializationListener());
}
/// <summary>
/// Serializes the record to an existing byte array.
/// </summary>
/// <param name="offset">the offset within the byte array.</param>
/// <param name="data">the offset within the byte array</param>
/// <param name="listener">a listener for begin and end serialization events. This.
/// is useful because the serialization is
/// hierarchical/recursive and sometimes you need to be able
/// break into that.
/// </param>
/// <returns></returns>
public abstract int Serialize(int offset, byte[] data, EscherSerializationListener listener);
/// <summary>
/// Subclasses should effeciently return the number of bytes required to
/// Serialize the record.
/// </summary>
/// <value>number of bytes</value>
abstract public int RecordSize { get; }
/// <summary>
/// Return the current record id.
/// </summary>
/// <value>The 16 bit record id.</value>
public virtual short RecordId
{
get { return _recordId; }
set { this._recordId = value; }
}
/// <summary>
/// Gets or sets the child records.
/// </summary>
/// <value>Returns the children of this record. By default this will
/// be an empty list. EscherCotainerRecord is the only record that may contain children.</value>
public virtual List<EscherRecord> ChildRecords
{
get { return new List<EscherRecord>(); }
set { throw new ArgumentException("This record does not support child records."); }
}
/// <summary>
/// Creates a new object that is a copy of the current instance.
/// </summary>
/// <returns>
/// A new object that is a copy of this instance.
/// </returns>
public virtual object Clone()
{
throw new NotSupportedException("The class " + this.GetType().Name + " needs to define a clone method");
}
/// <summary>
/// Returns the indexed child record.
/// </summary>
/// <param name="index">The index.</param>
/// <returns></returns>
public EscherRecord GetChild(int index)
{
return (EscherRecord)ChildRecords[index];
}
/// <summary>
/// The display methods allows escher variables to print the record names
/// according to their hierarchy.
/// </summary>
/// <param name="indent">The current indent level.</param>
public virtual void Display(int indent)
{
for (int i = 0; i < indent * 4; i++)
{
Console.Write(' ');
}
Console.WriteLine(RecordName);
}
/// <summary>
/// Gets the name of the record.
/// </summary>
/// <value>The name of the record.</value>
public abstract String RecordName { get; }
/// <summary>
/// This class Reads the standard escher header.
/// </summary>
internal class DeleteEscherRecordHeader
{
private short options;
private short recordId;
private int remainingBytes;
private DeleteEscherRecordHeader()
{
}
/// <summary>
/// Reads the header.
/// </summary>
/// <param name="data">The data.</param>
/// <param name="offset">The off set.</param>
/// <returns></returns>
public static DeleteEscherRecordHeader ReadHeader(byte[] data, int offset)
{
DeleteEscherRecordHeader header = new DeleteEscherRecordHeader();
header.options = LittleEndian.GetShort(data, offset);
header.recordId = LittleEndian.GetShort(data, offset + 2);
header.remainingBytes = LittleEndian.GetInt(data, offset + 4);
return header;
}
/// <summary>
/// Gets the options.
/// </summary>
/// <value>The options.</value>
public short Options
{
get { return options; }
}
/// <summary>
/// Gets the record id.
/// </summary>
/// <value>The record id.</value>
public virtual short RecordId
{
get { return recordId; }
}
/// <summary>
/// Gets the remaining bytes.
/// </summary>
/// <value>The remaining bytes.</value>
public int RemainingBytes
{
get { return remainingBytes; }
}
/// <summary>
/// Returns a <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>.
/// </summary>
/// <returns>
/// A <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>.
/// </returns>
public override String ToString()
{
return "EscherRecordHeader{" +
"options=" + options +
", recordId=" + recordId +
", remainingBytes=" + remainingBytes +
"}";
}
}
/// <summary>
/// Get or set the instance part of the option record.
/// </summary>
public virtual short Instance
{
get { return fInstance.GetShortValue(_options); }
set { _options = fInstance.SetShortValue(_options, value); }
}
/// <summary>
/// Get or set the version part of the option record.
/// </summary>
public virtual short Version
{
get { return fVersion.GetShortValue(_options); }
set { _options = fVersion.SetShortValue(_options, value); }
}
/**
* @param tab - each children must be a right of his parent
* @return xml representation of this record
*/
public virtual String ToXml(String tab)
{
StringBuilder builder = new StringBuilder();
builder.Append(tab).Append("<").Append(GetType().Name).Append(">\n")
.Append(tab).Append("\t").Append("<RecordId>0x").Append(HexDump.ToHex(_recordId)).Append("</RecordId>\n")
.Append(tab).Append("\t").Append("<Options>").Append(_options).Append("</Options>\n")
.Append(tab).Append("</").Append(GetType().Name).Append(">\n");
return builder.ToString();
}
protected String FormatXmlRecordHeader(String className, String recordId, String version, String instance)
{
StringBuilder builder = new StringBuilder();
builder.Append("<").Append(className).Append(" recordId=\"0x").Append(recordId).Append("\" version=\"0x")
.Append(version).Append("\" instance=\"0x").Append(instance).Append("\" size=\"").Append(RecordSize).Append("\">\n");
return builder.ToString();
}
public String ToXml()
{
return ToXml("");
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using BestPlaylists.Common;
using BestPlaylists.Data.Models;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
namespace BestPlaylists.Data.Migrations
{
using System.Data.Entity.Migrations;
using BestPlaylists.Data;
public sealed class Configuration : DbMigrationsConfiguration<BestPlaylistsDbContext>
{
public Configuration()
{
this.AutomaticMigrationsEnabled = true;
this.AutomaticMigrationDataLossAllowed = true;
}
protected override void Seed(BestPlaylistsDbContext context)
{
this.SeedCategories(context);
this.SeedRoles(context);
this.SeedUsers(context);
this.SeedPlaylists(context);
this.SeedComments(context);
}
private void SeedCategories(BestPlaylistsDbContext context)
{
if (!context.Categories.Any())
{
for (int i = 0; i < DbConstants.musicGenres.Count; i++)
{
var category = new Category()
{
Name = DbConstants.musicGenres[i]
};
context.Categories.Add(category);
if (i % 20 == 0)
{
context.SaveChanges();
}
}
}
}
private void SeedRoles(BestPlaylistsDbContext context)
{
var store = new RoleStore<IdentityRole>(context);
var manager = new RoleManager<IdentityRole>(store);
if (!context.Roles.Any(r => r.Name == DbConstants.RoleAdmin))
{
var roleAdmin = new IdentityRole
{
Name = DbConstants.RoleAdmin
};
manager.Create(roleAdmin);
}
if (!context.Roles.Any(r => r.Name == DbConstants.RoleEditor))
{
var roleEditor = new IdentityRole()
{
Name = DbConstants.RoleEditor
};
manager.Create(roleEditor);
}
}
private void SeedUsers(BestPlaylistsDbContext context)
{
var store = new UserStore<User>(context);
var manager = new UserManager<User>(store);
if (!context.Users.Any(u => u.UserName == DbConstants.Admin1Name))
{
var user = new User()
{
UserName = DbConstants.Admin1Name,
Email = DbConstants.Admin1Email,
FirstName = DbConstants.Admin1FirstName,
LastName = DbConstants.Admin1LastName
};
manager.Create(user, DbConstants.Admin1Pass);
manager.AddToRole(user.Id, DbConstants.RoleAdmin);
}
if (!context.Users.Any(u => u.UserName == DbConstants.Editor1Name))
{
var user = new User()
{
UserName = DbConstants.Editor1Name,
Email = DbConstants.Editor1Email,
FirstName = DbConstants.Editor1FirstName,
LastName = DbConstants.Editor1LastName
};
manager.Create(user, DbConstants.Editor1Pass);
manager.AddToRole(user.Id, DbConstants.RoleEditor);
}
// Adding 20 more users
for (int i = 1; i <= 20; i++)
{
var userName = DbConstants.Editor1Name + i;
if (!context.Users.Any(u => u.UserName == userName))
{
var user = new User()
{
UserName = userName,
Email = userName + "@gmail.com",
FirstName = userName,
LastName = userName
};
manager.Create(user, DbConstants.Editor1Pass);
manager.AddToRole(user.Id, DbConstants.RoleEditor);
}
}
}
private void SeedPlaylists(BestPlaylistsDbContext context)
{
var categoriesCount = context.Categories.Count();
var allUsers = context
.Users
.Select(x => x.Id)
.ToList();
if (!context.Playlists.Any())
{
var randomGenerator = new RandomGenerator();
for (int i = 0; i < 100; i++)
{
var playlist = new Playlist()
{
Title = randomGenerator.GetRandowSentance(ModelsConstats.MinVideoTitleLength, ModelsConstats.MaxVideoTitleLength - 50),
Description = randomGenerator.GetRandowSentance(ModelsConstats.MinVideoTitleLength, ModelsConstats.MaxVideoDescriptionLength - 1800),
CreationDate = randomGenerator.GetRandomDate(DateTime.Now.AddYears(-i), DateTime.Now),
IsPrivate = (i % 2 == 0),
CurrentRating = randomGenerator.GetRandomNumber(1, 5) % 6,
CategoryId = randomGenerator.GetRandomNumber(1, categoriesCount),
UserId = allUsers[randomGenerator.GetRandomNumber(0, allUsers.Count - 1)],
};
context.Playlists.Add(playlist);
if (i % 10 == 0)
{
context.SaveChanges();
}
}
var playlistsCount = context.Playlists.Count();
for (int i = 0; i < playlistsCount; i++)
{
for (int j = 0; j < 10; j++)
{
var video = new Video()
{
PlaylistId = i + 1,
Url = GetRandomVideo(),
UserId = context.Playlists.First(id => id.Id == i + 1).UserId
};
context.Videos.Add(video);
}
context.SaveChanges();
}
}
}
private void SeedComments(BestPlaylistsDbContext context)
{
if (!context.Comments.Any())
{
var randomGenerator = new RandomGenerator();
var playLists = context.Playlists.ToList();
var users = context.Users.Select(x => x.Id).ToList();
foreach (var playlist in playLists)
{
var commentsCount = randomGenerator.GetRandomNumber(3, 9);
for (int i = 0; i < commentsCount; i++)
{
playlist.Comments.Add(new Comment()
{
CreationDate = randomGenerator.GetRandomDate(DateTime.Now.AddYears(-i), DateTime.Now),
Text = randomGenerator.GetRandowSentance(ModelsConstats.MinVideoTitleLength, ModelsConstats.MaxVideoDescriptionLength - 1800),
UserId = users[randomGenerator.GetRandomNumber(0, users.Count - 1)]
});
context.Playlists.AddOrUpdate(playlist);
context.SaveChanges();
}
}
}
}
private string GetRandomVideo()
{
var youTubeVideos = new List<string>()
{
"https://www.youtube.com/watch?v=bVRfloSVFFs",
"https://www.youtube.com/watch?v=EIxfpanpyrs",
"https://www.youtube.com/watch?v=KxlcEOY-7hg",
"https://www.youtube.com/watch?v=1RjE915E4mg",
"https://www.youtube.com/watch?v=OGWehEcKArE",
"https://www.youtube.com/watch?v=BiADfKN_1Sc",
"https://www.youtube.com/watch?v=62OL7SC5_A8",
"https://www.youtube.com/watch?v=O6gkm-nklyw",
"https://www.youtube.com/watch?v=lPmOcJ9YdYw",
"https://www.youtube.com/watch?v=b6m-XlOxjbk",
"https://www.youtube.com/watch?v=tPxcFm_S1qc",
"https://www.youtube.com/watch?v=LTIJZJsLG8o",
"https://www.youtube.com/watch?v=q2DqctUI8ho",
"https://www.youtube.com/watch?v=Nqh3LI6l1fk",
"https://www.youtube.com/watch?v=oq2mykyhl-0",
"https://www.youtube.com/watch?v=6H9aHntpjcE",
"https://www.youtube.com/watch?v=gojyDYI8bzY",
"https://www.youtube.com/watch?v=nWLYUdejPWc",
"https://www.youtube.com/watch?v=4Esni96oBdQ",
"https://www.youtube.com/watch?v=1CxPGDZJPDw",
"https://www.youtube.com/watch?v=fk9iJougDFE",
"https://www.youtube.com/watch?v=GF60Iuh643I",
"https://www.youtube.com/watch?v=59Zcx9YbZxI",
"https://www.youtube.com/watch?v=VAZ5te90vlc",
"https://www.youtube.com/watch?v=APoCpZOrI4w",
"https://www.youtube.com/watch?v=APoCpZOrI4w",
"https://www.youtube.com/watch?v=V4LnorVVxfw",
"https://www.youtube.com/watch?v=Cs4OUFAr5Hc",
"https://www.youtube.com/watch?v=MBsEPgjE7KU",
"https://www.youtube.com/watch?v=axm-N9L2c_E",
"https://www.youtube.com/watch?v=dGpZEuXoFWw",
"https://www.youtube.com/watch?v=JgzgcAlpxNU",
"https://www.youtube.com/watch?v=0FEYvKxCnYw",
"https://www.youtube.com/watch?v=MveqXxB12YA",
"https://www.youtube.com/watch?v=-4FlKZIo8B4",
"https://www.youtube.com/watch?v=JWZMzcmqMwc",
"https://www.youtube.com/watch?v=Snw0rEWyvLk",
"https://www.youtube.com/watch?v=DaxB9y--CGI",
"https://www.youtube.com/watch?v=Md7bfNTR0TM",
"https://www.youtube.com/watch?v=zmIxovkV3Ro",
"https://www.youtube.com/watch?v=tntOCGkgt98",
"https://www.youtube.com/watch?v=CE-JlvmnRtY",
"https://www.youtube.com/watch?v=UIrEM_9qvZU",
"https://www.youtube.com/watch?v=25OUFtdno8U",
"https://www.youtube.com/watch?v=HxM46vRJMZs",
"https://www.youtube.com/watch?v=G8KpPw303PY",
"https://www.youtube.com/watch?v=mW3S0u8bj58",
"https://www.youtube.com/watch?v=-hIugp7p5O0",
"https://www.youtube.com/watch?v=9Mk_t78IeO8",
"https://www.youtube.com/watch?v=tcPVzzyB7OI",
"https://www.youtube.com/watch?v=JgjXG_9L_Jw",
};
var randomGenerator = new RandomGenerator();
var videoUrl = youTubeVideos[randomGenerator.GetRandomNumber(0, youTubeVideos.Count - 1)];
return videoUrl;
}
}
}
| |
using UnityEngine;
using UnityEngine.SceneManagement;
#if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN
using XInputDotNetPure;
#endif
namespace XboxCtrlrInput
{
// ================= Enumerations ==================== //
/// <summary>
/// List of enumerated identifiers for Xbox controllers.
/// </summary>
public enum XboxController
{
All = 0,
First = 1,
Second = 2,
Third = 3,
Fourth = 4
}
/// <summary>
/// List of enumerated identifiers for Xbox buttons.
/// </summary>
public enum XboxButton
{
A,
B,
X,
Y,
Start,
Back,
LeftStick,
RightStick,
LeftBumper,
RightBumper,
DPadUp,
DPadDown,
DPadLeft,
DPadRight
}
/// <summary>
/// List of enumerated identifiers for Xbox D-Pad directions.
/// </summary>
public enum XboxDPad
{
Up,
Down,
Left,
Right
}
/// <summary>
/// List of enumerated identifiers for Xbox axis.
/// </summary>
public enum XboxAxis
{
LeftStickX,
LeftStickY,
RightStickX,
RightStickY,
LeftTrigger,
RightTrigger
}
// ================ Classes =================== //
public static class XCI
{
// ------------ Public Methods --------------- //
// >>> For Buttons <<< //
/// <summary>
/// Returns <c>true</c> if the specified button is held down by any controller.
/// </summary>
/// <param name='button'>
/// Identifier for the Xbox button to be tested.
/// </param>
public static bool GetButton(XboxButton button)
{
if (button.IsDPad())
return GetDPad(button.ToDPad());
if(OnWindowsNative())
{
#if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN
if(!XInputStillInCurrFrame())
{
XInputUpdateAllStates();
}
GamePadState ctrlrState = XInputGetSingleState();
if( XInputGetButtonState(ctrlrState.Buttons, button) == ButtonState.Pressed )
{
return true;
}
#endif
}
else
{
string btnCode = DetermineButtonCode(button, 0);
if(Input.GetKey(btnCode))
{
return true;
}
}
return false;
}
/// <summary>
/// Returns <c>true</c> if the specified button is held down by a specified controller.
/// </summary>
/// <param name='button'>
/// Identifier for the Xbox button to be tested.
/// </param>
/// <param name='controller'>
/// An identifier for the specific controller on which to test the button.
/// </param>
public static bool GetButton(XboxButton button, XboxController controller)
{
if (button.IsDPad())
return GetDPad(button.ToDPad(), controller);
if (controller == XboxController.All)
return GetButton(button);
int controllerNumber = (int)controller;
if(OnWindowsNative())
{
#if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN
if(!XInputStillInCurrFrame())
{
XInputUpdateAllStates();
}
GamePadState ctrlrState = XInputGetPaticularState(controllerNumber);
if( XInputGetButtonState(ctrlrState.Buttons, button) == ButtonState.Pressed )
{
return true;
}
#endif
}
else
{
string btnCode = DetermineButtonCode(button, controllerNumber);
if(Input.GetKey(btnCode))
{
return true;
}
}
return false;
}
/// <summary>
/// Returns <c>true</c> at the frame the specified button starts to press down (not held down) by any controller.
/// </summary>
/// <param name='button'>
/// Identifier for the Xbox button to be tested.
/// </param>
public static bool GetButtonDown(XboxButton button)
{
if (button.IsDPad())
return GetDPadDown(button.ToDPad());
if(OnWindowsNative())
{
#if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN
if(!XInputStillInCurrFrame())
{
XInputUpdateAllStates();
}
GamePadState ctrlrState = XInputGetSingleState();
GamePadState ctrlrStatePrev = XInputGetSingleStatePrev();
if( ( XInputGetButtonState(ctrlrState.Buttons, button) == ButtonState.Pressed ) &&
( XInputGetButtonState(ctrlrStatePrev.Buttons, button) == ButtonState.Released ) )
{
return true;
}
#endif
}
else
{
string btnCode = DetermineButtonCode(button, 0);
if(Input.GetKeyDown(btnCode))
{
return true;
}
}
return false;
}
/// <summary>
/// Returns <c>true</c> at the frame the specified button starts to press down (not held down) by a specified controller.
/// </summary>
/// <param name='button'>
/// Identifier for the Xbox button to be tested.
/// </param>
/// <param name='controller'>
/// An identifier for the specific controller on which to test the button.
/// </param>
public static bool GetButtonDown(XboxButton button, XboxController controller)
{
if (button.IsDPad())
return GetDPadDown(button.ToDPad(), controller);
if (controller == XboxController.All)
return GetButtonDown(button);
int controllerNumber = (int)controller;
if(OnWindowsNative())
{
#if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN
if(!XInputStillInCurrFrame())
{
XInputUpdateAllStates();
}
GamePadState ctrlrState = XInputGetPaticularState(controllerNumber);
GamePadState ctrlrStatePrev = XInputGetPaticularStatePrev(controllerNumber);
if( ( XInputGetButtonState(ctrlrState.Buttons, button) == ButtonState.Pressed ) &&
( XInputGetButtonState(ctrlrStatePrev.Buttons, button) == ButtonState.Released ) )
{
return true;
}
#endif
}
else
{
string btnCode = DetermineButtonCode(button, controllerNumber);
if(Input.GetKeyDown(btnCode))
{
return true;
}
}
return false;
}
/// <summary>
/// Returns <c>true</c> at the frame the specified button is released by any controller.
/// </summary>
/// <param name='button'>
/// Identifier for the Xbox button to be tested.
/// </param>
public static bool GetButtonUp(XboxButton button)
{
if (button.IsDPad())
return GetDPadUp(button.ToDPad());
if(OnWindowsNative())
{
#if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN
if(Time.frameCount < 2)
{
return false;
}
if(!XInputStillInCurrFrame())
{
XInputUpdateAllStates();
}
GamePadState ctrlrState = XInputGetSingleState();
GamePadState ctrlrStatePrev = XInputGetSingleStatePrev();
if( ( XInputGetButtonState(ctrlrState.Buttons, button) == ButtonState.Released ) &&
( XInputGetButtonState(ctrlrStatePrev.Buttons, button) == ButtonState.Pressed ) )
{
return true;
}
#endif
}
else
{
string btnCode = DetermineButtonCode(button, 0);
if(Input.GetKeyUp(btnCode))
{
return true;
}
}
return false;
}
/// <summary>
/// Returns <c>true</c> at the frame the specified button is released by a specified controller.
/// </summary>
/// <param name='button'>
/// Identifier for the Xbox button to be tested.
/// </param>
/// <param name='controller'>
/// An identifier for the specific controller on which to test the button.
/// </param>
public static bool GetButtonUp(XboxButton button, XboxController controller)
{
if (button.IsDPad())
return GetDPadUp(button.ToDPad(), controller);
if (controller == XboxController.All)
return GetButtonUp(button);
int controllerNumber = (int)controller;
if(OnWindowsNative())
{
#if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN
if(Time.frameCount < 2)
{
return false;
}
if(!XInputStillInCurrFrame())
{
XInputUpdateAllStates();
}
GamePadState ctrlrState = XInputGetPaticularState(controllerNumber);
GamePadState ctrlrStatePrev = XInputGetPaticularStatePrev(controllerNumber);
if( ( XInputGetButtonState(ctrlrState.Buttons, button) == ButtonState.Released ) &&
( XInputGetButtonState(ctrlrStatePrev.Buttons, button) == ButtonState.Pressed ) )
{
return true;
}
#endif
}
else
{
string btnCode = DetermineButtonCode(button, controllerNumber);
if(Input.GetKeyUp(btnCode))
{
return true;
}
}
return false;
}
// >>> For D-Pad <<< //
/// <summary>
/// Returns <c>true</c> if the specified D-Pad direction is pressed down by any controller.
/// </summary>
/// <param name='padDirection'>
/// An identifier for the specified D-Pad direction to be tested.
/// </param>
public static bool GetDPad(XboxDPad padDirection)
{
bool r = false;
if(OnWindowsNative())
{
#if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN
if(!XInputStillInCurrFrame())
{
XInputUpdateAllStates();
}
GamePadState ctrlrState = XInputGetSingleState();
if( XInputGetDPadState(ctrlrState.DPad, padDirection) == ButtonState.Pressed )
{
return true;
}
#endif
}
else
{
string inputCode = "";
if(OnMac())
{
inputCode = DetermineDPadMac(padDirection, 0);
r = Input.GetKey(inputCode);
}
else if(OnLinux() && IsControllerWireless())
{
inputCode = DetermineDPadWirelessLinux(padDirection, 0);
r = Input.GetKey(inputCode);
}
else // Windows Web Player and Linux Wired Controller
{
inputCode = DetermineDPad(padDirection, 0);
switch(padDirection)
{
case XboxDPad.Up: r = Input.GetAxis(inputCode) > 0; break;
case XboxDPad.Down: r = Input.GetAxis(inputCode) < 0; break;
case XboxDPad.Left: r = Input.GetAxis(inputCode) < 0; break;
case XboxDPad.Right: r = Input.GetAxis(inputCode) > 0; break;
default: r = false; break;
}
}
}
return r;
}
/// <summary>
/// Returns <c>true</c> if the specified D-Pad direction is pressed down by a specified controller.
/// </summary>
/// <param name='padDirection'>
/// An identifier for the specified D-Pad direction to be tested.
/// </param>
/// <param name='controller'>
/// An identifier for the specific controller on which to test the D-Pad.
/// </param>
public static bool GetDPad(XboxDPad padDirection, XboxController controller)
{
if (controller == XboxController.All)
return GetDPad(padDirection);
int controllerNumber = (int)controller;
bool r = false;
if(OnWindowsNative())
{
#if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN
if(!XInputStillInCurrFrame())
{
XInputUpdateAllStates();
}
GamePadState ctrlrState = XInputGetPaticularState(controllerNumber);
if( XInputGetDPadState(ctrlrState.DPad, padDirection) == ButtonState.Pressed )
{
return true;
}
#endif
}
else
{
string inputCode = "";
if(OnMac())
{
inputCode = DetermineDPadMac(padDirection, controllerNumber);
r = Input.GetKey(inputCode);
}
else if(OnLinux() && IsControllerWireless(controllerNumber))
{
inputCode = DetermineDPadWirelessLinux(padDirection, controllerNumber);
r = Input.GetKey(inputCode);
}
else // Windows Web Player and Linux Wired Controller
{
inputCode = DetermineDPad(padDirection, controllerNumber);
switch(padDirection)
{
case XboxDPad.Up: r = Input.GetAxis(inputCode) > 0; break;
case XboxDPad.Down: r = Input.GetAxis(inputCode) < 0; break;
case XboxDPad.Left: r = Input.GetAxis(inputCode) < 0; break;
case XboxDPad.Right: r = Input.GetAxis(inputCode) > 0; break;
default: r = false; break;
}
}
}
return r;
}
// From @ProjectEnder
/// <summary>
/// Returns <c>true</c> at the frame the specified button is released.
/// Does NOT work on Linux with Wired Controllers.
/// </summary>
/// <param name='button'>
/// Identifier for the Xbox button to be tested.
/// </param>
public static bool GetDPadUp(XboxDPad padDirection)
{
bool r = false;
if(OnWindowsNative())
{
#if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN
if(Time.frameCount < 2)
{
return false;
}
if(!XInputStillInCurrFrame())
{
XInputUpdateAllStates();
}
GamePadState ctrlrState = XInputGetSingleState();
GamePadState ctrlrStatePrev = XInputGetSingleStatePrev();
if( ( XInputGetDPadState(ctrlrState.DPad, padDirection) == ButtonState.Released ) &&
( XInputGetDPadState(ctrlrStatePrev.DPad, padDirection) == ButtonState.Pressed ) )
{
return true;
}
#endif
}
else
{
string inputCode = "";
if(OnMac())
{
inputCode = DetermineDPadMac(padDirection, 0);
r = Input.GetKeyUp(inputCode);
}
else if(OnLinux() && IsControllerWireless())
{
inputCode = DetermineDPadWirelessLinux(padDirection, 0);
r = Input.GetKeyUp(inputCode);
}
else
{
//Place Holder for Wired Linux
r = false;
}
}
return r;
}
// From @ProjectEnder
/// <summary>
/// Returns <c>true</c> at the frame the specified button is released by a specified controller.
/// Does NOT work on Linux with Wired Controllers.
/// </summary>
/// <param name='button'>
/// Identifier for the Xbox button to be tested.
/// </param>
/// <param name='controller'>
/// An identifier for the specific controller on which to test the button.
/// </param>
public static bool GetDPadUp(XboxDPad padDirection, XboxController controller)
{
if (controller == XboxController.All)
return GetDPadUp(padDirection);
int controllerNumber = (int)controller;
bool r = false;
if(OnWindowsNative())
{
#if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN
if(Time.frameCount < 2)
{
return false;
}
if(!XInputStillInCurrFrame())
{
XInputUpdateAllStates();
}
GamePadState ctrlrState = XInputGetPaticularState(controllerNumber);
GamePadState ctrlrStatePrev = XInputGetPaticularStatePrev(controllerNumber);
if( ( XInputGetDPadState(ctrlrState.DPad, padDirection) == ButtonState.Released ) &&
( XInputGetDPadState(ctrlrStatePrev.DPad, padDirection) == ButtonState.Pressed ) )
{
return true;
}
#endif
}
else
{
string inputCode = "";
if(OnMac())
{
inputCode = DetermineDPadMac(padDirection, controllerNumber);
r = Input.GetKeyUp(inputCode);
}
else if(OnLinux() && IsControllerWireless(controllerNumber))
{
inputCode = DetermineDPadWirelessLinux(padDirection, controllerNumber);
r = Input.GetKeyUp(inputCode);
}
else
{
//Place Holder for Wired Linux
r = false;
}
}
return r;
}
// From @ProjectEnder
/// <summary>
/// Returns <c>true</c> at the frame the specified button is Pressed.
/// Does NOT work on Linux with Wired Controllers.
/// </summary>
/// <param name='button'>
/// Identifier for the Xbox button to be tested.
/// </param>
public static bool GetDPadDown(XboxDPad padDirection)
{
bool r = false;
if(OnWindowsNative())
{
#if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN
if(Time.frameCount < 2)
{
return false;
}
if(!XInputStillInCurrFrame())
{
XInputUpdateAllStates();
}
GamePadState ctrlrState = XInputGetSingleState();
GamePadState ctrlrStatePrev = XInputGetSingleStatePrev();
if( ( XInputGetDPadState(ctrlrState.DPad, padDirection) == ButtonState.Pressed ) &&
( XInputGetDPadState(ctrlrStatePrev.DPad, padDirection) == ButtonState.Released ) )
{
return true;
}
#endif
}
else
{
string inputCode = "";
if(OnMac())
{
inputCode = DetermineDPadMac(padDirection, 0);
r = Input.GetKeyDown(inputCode);
}
else if(OnLinux() && IsControllerWireless())
{
inputCode = DetermineDPadWirelessLinux(padDirection, 0);
r = Input.GetKeyDown(inputCode);
}
else
{
//Place Holder for Wired Linux
r = false;
}
}
return r;
}
// From @ProjectEnder
/// <summary>
/// Returns <c>true</c> at the frame the specified button is Pressed by a specified controller.
/// Does NOT work on Linux with Wired Controllers.
/// </summary>
/// <param name='button'>
/// Identifier for the Xbox button to be tested.
/// </param>
/// <param name='controller'>
/// An identifier for the specific controller on which to test the button.
/// </param>
public static bool GetDPadDown(XboxDPad padDirection, XboxController controller)
{
if (controller == XboxController.All)
return GetDPadDown(padDirection);
int controllerNumber = (int)controller;
bool r = false;
if(OnWindowsNative())
{
#if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN
if(Time.frameCount < 2)
{
return false;
}
if(!XInputStillInCurrFrame())
{
XInputUpdateAllStates();
}
GamePadState ctrlrState = XInputGetPaticularState(controllerNumber);
GamePadState ctrlrStatePrev = XInputGetPaticularStatePrev(controllerNumber);
if( ( XInputGetDPadState(ctrlrState.DPad, padDirection) == ButtonState.Pressed ) &&
( XInputGetDPadState(ctrlrStatePrev.DPad, padDirection) == ButtonState.Released ) )
{
return true;
}
#endif
}
else
{
string inputCode = "";
if(OnMac())
{
inputCode = DetermineDPadMac(padDirection, controllerNumber);
r = Input.GetKeyDown(inputCode);
}
else if(OnLinux() && IsControllerWireless(controllerNumber))
{
inputCode = DetermineDPadWirelessLinux(padDirection, controllerNumber);
r = Input.GetKeyDown(inputCode);
}
else
{
//Place Holder for Wired Linux
r = false;
}
}
return r;
}
// >>> For Axis <<< //
/// <summary>
/// Returns the analog number of the specified axis from any controller.
/// </summary>
/// <param name='axis'>
/// An identifier for the specified Xbox axis to be tested.
/// </param>
public static float GetAxis(XboxAxis axis)
{
float r = 0.0f;
if(OnWindowsNative())
{
#if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN
if(!XInputStillInCurrFrame())
{
XInputUpdateAllStates();
}
GamePadState ctrlrState = XInputGetSingleState();
if(axis == XboxAxis.LeftTrigger || axis == XboxAxis.RightTrigger)
{
r = XInputGetAxisState(ctrlrState.Triggers, axis);
}
else
{
r = XInputGetAxisState(ctrlrState.ThumbSticks, axis);
}
#endif
}
else
{
string axisCode = DetermineAxisCode(axis, 0);
r = Input.GetAxis(axisCode);
r = AdjustAxisValues(r, axis, 0);
}
return r;
}
/// <summary>
/// Returns the float number of the specified axis from a specified controller.
/// </summary>
/// <param name='axis'>
/// An identifier for the specified Xbox axis to be tested.
/// </param>
/// <param name='controller'>
/// An identifier for the specific controller on which to test the axis.
/// </param>
public static float GetAxis(XboxAxis axis, XboxController controller)
{
if (controller == XboxController.All)
return GetAxis(axis);
int controllerNumber = (int)controller;
float r = 0.0f;
if(OnWindowsNative())
{
#if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN
if(!XInputStillInCurrFrame())
{
XInputUpdateAllStates();
}
GamePadState ctrlrState = XInputGetPaticularState(controllerNumber);
if(axis == XboxAxis.LeftTrigger || axis == XboxAxis.RightTrigger)
{
r = XInputGetAxisState(ctrlrState.Triggers, axis);
}
else
{
r = XInputGetAxisState(ctrlrState.ThumbSticks, axis);
}
#endif
}
else
{
string axisCode = DetermineAxisCode(axis, controllerNumber);
r = Input.GetAxis(axisCode);
r = AdjustAxisValues(r, axis, controllerNumber);
}
return r;
}
/// <summary>
/// Returns the float number of the specified axis from any controller without Unity's smoothing filter.
/// </summary>
/// <param name='axis'>
/// An identifier for the specified Xbox axis to be tested.
/// </param>
public static float GetAxisRaw(XboxAxis axis)
{
float r = 0.0f;
if(OnWindowsNative())
{
#if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN
if(!XInputStillInCurrFrame())
{
XInputUpdateAllStates();
}
GamePadState ctrlrState = XInputGetSingleState();
if(axis == XboxAxis.LeftTrigger || axis == XboxAxis.RightTrigger)
{
r = XInputGetAxisState(ctrlrState.Triggers, axis);
}
else
{
r = XInputGetAxisState(ctrlrState.ThumbSticks, axis);
}
#endif
}
else
{
string axisCode = DetermineAxisCode(axis, 0);
r = Input.GetAxisRaw(axisCode);
r = AdjustAxisValues(r, axis, 0);
}
return r;
}
/// <summary>
/// Returns the float number of the specified axis from a specified controller without Unity's smoothing filter.
/// </summary>
/// <param name='axis'>
/// An identifier for the specified Xbox axis to be tested.
/// </param>
/// <param name='controller'>
/// An identifier for the specific controller on which to test the axis.
/// </param>
public static float GetAxisRaw(XboxAxis axis, XboxController controller)
{
if (controller == XboxController.All)
return GetAxisRaw(axis);
int controllerNumber = (int)controller;
float r = 0.0f;
if(OnWindowsNative())
{
#if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN
if(!XInputStillInCurrFrame())
{
XInputUpdateAllStates();
}
GamePadState ctrlrState = XInputGetPaticularState(controllerNumber);
if(axis == XboxAxis.LeftTrigger || axis == XboxAxis.RightTrigger)
{
r = XInputGetAxisState(ctrlrState.Triggers, axis);
}
else
{
r = XInputGetAxisState(ctrlrState.ThumbSticks, axis);
}
#endif
}
else
{
string axisCode = DetermineAxisCode(axis, controllerNumber);
r = Input.GetAxisRaw(axisCode);
r = AdjustAxisValues(r, axis, controllerNumber);
}
return r;
}
// >>> Other important functions <<< //
/// <summary>
/// Returns the number of Xbox controllers plugged to the computer.
/// </summary>
public static int GetNumPluggedCtrlrs()
{
int r = 0;
if(OnWindowsNative())
{
#if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN
if(!xiNumOfCtrlrsQueried || !XInputStillInCurrFrame())
{
xiNumOfCtrlrsQueried = true;
XInputUpdateAllStates();
}
for(int i = 0; i < 4; i++)
{
if(xInputCtrlrs[i].IsConnected)
{
r++;
}
}
#endif
}
else
{
string[] ctrlrNames = Input.GetJoystickNames();
for(int i = 0; i < ctrlrNames.Length; i++)
{
if(ctrlrNames[i].Contains("Xbox") || ctrlrNames[i].Contains("XBOX") || ctrlrNames[i].Contains("Microsoft"))
{
r++;
}
}
}
return r;
}
/// <summary>
/// DEBUG function. Log all controller names to Unity's console.
/// </summary>
public static void DEBUG_LogControllerNames()
{
string[] cNames = Input.GetJoystickNames();
for(int i = 0; i < cNames.Length; i++)
{
Debug.Log("Ctrlr " + i.ToString() + ": " + cNames[i]);
}
}
// From @xoorath
/// <summary>
/// Determines if the controller is plugged in the specified controllerNumber.
/// CAUTION: Only works on Windows Native (Desktop and Editor)!
/// </summary>
/// <param name="controllerNumber">
/// An identifier for the specific controller on which to test the axis. An int between 1 and 4.
/// </param>
public static bool IsPluggedIn(int controllerNumber)
{
#if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN
if(OnWindowsNative())
{
if (!XInputStillInCurrFrame())
{
XInputUpdateAllStates();
}
GamePadState ctrlrState = XInputGetPaticularState(controllerNumber);
return ctrlrState.IsConnected;
}
#endif
// NOT IMPLEMENTED for other platforms
return false;
}
////
// ------------- Private -------------- //
////
// ------------ Methods --------------- //
private static bool OnMac()
{
// All Mac mappings are based off TattieBogle Xbox Controller drivers
// http://tattiebogle.net/index.php/ProjectRoot/Xbox360Controller/OsxDriver
// http://wiki.unity3d.com/index.php?title=Xbox360Controller
return (Application.platform == RuntimePlatform.OSXEditor ||
Application.platform == RuntimePlatform.OSXPlayer );
}
private static bool OnWindows()
{
return (Application.platform == RuntimePlatform.WindowsEditor ||
Application.platform == RuntimePlatform.WindowsPlayer );
}
private static bool OnWindowsNative()
{
return (Application.platform == RuntimePlatform.WindowsEditor ||
Application.platform == RuntimePlatform.WindowsPlayer );
}
private static bool OnLinux()
{
// Linux mapping based on observation of mapping from default drivers on Ubuntu 13.04
return Application.platform == RuntimePlatform.LinuxPlayer;
}
private static bool IsControllerWireless()
{
// 0 means for any controller
return IsControllerWireless(0);
}
private static bool IsControllerWireless(int ctrlNum)
{
if (ctrlNum < 0 || ctrlNum > 4) return false;
// If 0 is passed in, that assumes that only 1 controller is plugged in.
if(ctrlNum == 0)
{
return ( (string) Input.GetJoystickNames()[0]).Contains("Wireless");
}
return ( (string) Input.GetJoystickNames()[ctrlNum-1]).Contains("Wireless");
}
private static bool IsControllerNumberValid(int ctrlrNum)
{
if(ctrlrNum > 0 && ctrlrNum <= 4)
{
return true;
}
else
{
Debug.LogError("XCI.IsControllerNumberValid(): " +
"Invalid contoller number! Should be between 1 and 4.");
}
return false;
}
private static float RefactorRange(float oldRangeValue, int ctrlrNum, XboxAxis axis)
{
// HACK: On OS X, Left and right trigger under OSX return 0.5 until touched
// Issue #16 on Github: https://github.com/JISyed/Unity-XboxCtrlrInput/issues/16
if(XCI.OnMac())
{
if(axis == XboxAxis.LeftTrigger)
{
switch(ctrlrNum)
{
case 0:
{
if(!XCI.XciHandler.Instance.u3dTrigger0LeftIsTouched)
{
if(oldRangeValue != 0.0f)
{
XCI.XciHandler.Instance.u3dTrigger0LeftIsTouched = true;
}
else
{
return 0.0f;
}
}
break;
}
case 1:
{
if(!XCI.XciHandler.Instance.u3dTrigger1LeftIsTouched)
{
if(oldRangeValue != 0.0f)
{
XCI.XciHandler.Instance.u3dTrigger1LeftIsTouched = true;
}
else
{
return 0.0f;
}
}
break;
}
case 2:
{
if(!XCI.XciHandler.Instance.u3dTrigger2LeftIsTouched)
{
if(oldRangeValue != 0.0f)
{
XCI.XciHandler.Instance.u3dTrigger2LeftIsTouched = true;
}
else
{
return 0.0f;
}
}
break;
}
case 3:
{
if(!XCI.XciHandler.Instance.u3dTrigger3LeftIsTouched)
{
if(oldRangeValue != 0.0f)
{
XCI.XciHandler.Instance.u3dTrigger3LeftIsTouched = true;
}
else
{
return 0.0f;
}
}
break;
}
case 4:
{
if(!XCI.XciHandler.Instance.u3dTrigger4LeftIsTouched)
{
if(oldRangeValue != 0.0f)
{
XCI.XciHandler.Instance.u3dTrigger4LeftIsTouched = true;
}
else
{
return 0.0f;
}
}
break;
}
default:
break;
}
}
else if(axis == XboxAxis.RightTrigger)
{
switch(ctrlrNum)
{
case 0:
{
if(!XCI.XciHandler.Instance.u3dTrigger0RightIsTouched)
{
if(oldRangeValue != 0.0f)
{
XCI.XciHandler.Instance.u3dTrigger0RightIsTouched = true;
}
else
{
return 0.0f;
}
}
break;
}
case 1:
{
if(!XCI.XciHandler.Instance.u3dTrigger1RightIsTouched)
{
if(oldRangeValue != 0.0f)
{
XCI.XciHandler.Instance.u3dTrigger1RightIsTouched = true;
}
else
{
return 0.0f;
}
}
break;
}
case 2:
{
if(!XCI.XciHandler.Instance.u3dTrigger2RightIsTouched)
{
if(oldRangeValue != 0.0f)
{
XCI.XciHandler.Instance.u3dTrigger2RightIsTouched = true;
}
else
{
return 0.0f;
}
}
break;
}
case 3:
{
if(!XCI.XciHandler.Instance.u3dTrigger3RightIsTouched)
{
if(oldRangeValue != 0.0f)
{
XCI.XciHandler.Instance.u3dTrigger3RightIsTouched = true;
}
else
{
return 0.0f;
}
}
break;
}
case 4:
{
if(!XCI.XciHandler.Instance.u3dTrigger4RightIsTouched)
{
if(oldRangeValue != 0.0f)
{
XCI.XciHandler.Instance.u3dTrigger4RightIsTouched = true;
}
else
{
return 0.0f;
}
}
break;
}
default:
break;
}
}
}
// Assumes you want to take a number from -1 to 1 range
// And turn it into a number from a 0 to 1 range
return ((oldRangeValue + 1.0f) / 2.0f );
}
private static string DetermineButtonCode(XboxButton btn, int ctrlrNum)
{
string r = "";
string sJoyCode = "";
string sKeyCode = "";
bool invalidCode = false;
if(ctrlrNum == 0)
{
sJoyCode = "";
}
else
{
sJoyCode = " " + ctrlrNum.ToString();
}
if(OnMac())
{
switch(btn)
{
case XboxButton.A: sKeyCode = "16"; break;
case XboxButton.B: sKeyCode = "17"; break;
case XboxButton.X: sKeyCode = "18"; break;
case XboxButton.Y: sKeyCode = "19"; break;
case XboxButton.Start: sKeyCode = "9"; break;
case XboxButton.Back: sKeyCode = "10"; break;
case XboxButton.LeftStick: sKeyCode = "11"; break;
case XboxButton.RightStick: sKeyCode = "12"; break;
case XboxButton.LeftBumper: sKeyCode = "13"; break;
case XboxButton.RightBumper: sKeyCode = "14"; break;
default: invalidCode = true; break;
}
}
else if (OnLinux())
{
switch(btn)
{
case XboxButton.A: sKeyCode = "0"; break;
case XboxButton.B: sKeyCode = "1"; break;
case XboxButton.X: sKeyCode = "2"; break;
case XboxButton.Y: sKeyCode = "3"; break;
case XboxButton.Start: sKeyCode = "7"; break;
case XboxButton.Back: sKeyCode = "6"; break;
case XboxButton.LeftStick: sKeyCode = "9"; break;
case XboxButton.RightStick: sKeyCode = "10"; break;
case XboxButton.LeftBumper: sKeyCode = "4"; break;
case XboxButton.RightBumper: sKeyCode = "5"; break;
default: invalidCode = true; break;
}
}
else // Windows Web Player
{
switch(btn)
{
case XboxButton.A: sKeyCode = "0"; break;
case XboxButton.B: sKeyCode = "1"; break;
case XboxButton.X: sKeyCode = "2"; break;
case XboxButton.Y: sKeyCode = "3"; break;
case XboxButton.Start: sKeyCode = "7"; break;
case XboxButton.Back: sKeyCode = "6"; break;
case XboxButton.LeftStick: sKeyCode = "8"; break;
case XboxButton.RightStick: sKeyCode = "9"; break;
case XboxButton.LeftBumper: sKeyCode = "4"; break;
case XboxButton.RightBumper: sKeyCode = "5"; break;
default: invalidCode = true; break;
}
}
r = "joystick" + sJoyCode + " button " + sKeyCode;
if(invalidCode)
{
r = "";
}
return r;
}
private static string DetermineAxisCode(XboxAxis axs, int ctrlrNum)
{
string r = "";
string sJoyCode = ctrlrNum.ToString();
string sAxisCode = "";
bool invalidCode = false;
if(OnMac())
{
switch(axs)
{
case XboxAxis.LeftStickX: sAxisCode = "X"; break;
case XboxAxis.LeftStickY: sAxisCode = "Y"; break;
case XboxAxis.RightStickX: sAxisCode = "3"; break;
case XboxAxis.RightStickY: sAxisCode = "4"; break;
case XboxAxis.LeftTrigger: sAxisCode = "5"; break;
case XboxAxis.RightTrigger: sAxisCode = "6"; break;
default: invalidCode = true; break;
}
}
else if(OnLinux())
{
switch(axs)
{
case XboxAxis.LeftStickX: sAxisCode = "X"; break;
case XboxAxis.LeftStickY: sAxisCode = "Y"; break;
case XboxAxis.RightStickX: sAxisCode = "4"; break;
case XboxAxis.RightStickY: sAxisCode = "5"; break;
case XboxAxis.LeftTrigger: sAxisCode = "3"; break;
case XboxAxis.RightTrigger: sAxisCode = "6"; break;
default: invalidCode = true; break;
}
}
else // Windows Web Player
{
switch(axs)
{
case XboxAxis.LeftStickX: sAxisCode = "X"; break;
case XboxAxis.LeftStickY: sAxisCode = "Y"; break;
case XboxAxis.RightStickX: sAxisCode = "4"; break;
case XboxAxis.RightStickY: sAxisCode = "5"; break;
case XboxAxis.LeftTrigger: sAxisCode = "9"; break;
case XboxAxis.RightTrigger: sAxisCode = "10"; break;
default: invalidCode = true; break;
}
}
r = "XboxAxis" + sAxisCode + "Joy" + sJoyCode;
if(invalidCode)
{
r = "";
}
return r;
}
private static float AdjustAxisValues(float axisValue, XboxAxis axis, int ctrlrNum)
{
float newAxisValue = axisValue;
if(OnMac())
{
if(axis == XboxAxis.LeftTrigger)
{
newAxisValue = -newAxisValue;
newAxisValue = RefactorRange(newAxisValue, ctrlrNum, axis);
}
else if(axis == XboxAxis.RightTrigger)
{
newAxisValue = RefactorRange(newAxisValue, ctrlrNum, axis);
}
else if(axis == XboxAxis.RightStickY)
{
newAxisValue = -newAxisValue;
}
}
else if(OnLinux())
{
if(axis == XboxAxis.RightTrigger)
{
newAxisValue = RefactorRange(newAxisValue, ctrlrNum, axis);
}
else if(axis == XboxAxis.LeftTrigger)
{
newAxisValue = RefactorRange(newAxisValue, ctrlrNum, axis);
}
}
return newAxisValue;
}
private static string DetermineDPad(XboxDPad padDir, int ctrlrNum)
{
string r = "";
string sJoyCode = ctrlrNum.ToString();
string sPadCode = "";
bool invalidCode = false;
if(OnLinux())
{
switch(padDir)
{
case XboxDPad.Up: sPadCode = "8"; break;
case XboxDPad.Down: sPadCode = "8"; break;
case XboxDPad.Left: sPadCode = "7"; break;
case XboxDPad.Right: sPadCode = "7"; break;
default: invalidCode = true; break;
}
}
else // Windows Web Player
{
switch(padDir)
{
case XboxDPad.Up: sPadCode = "7"; break;
case XboxDPad.Down: sPadCode = "7"; break;
case XboxDPad.Left: sPadCode = "6"; break;
case XboxDPad.Right: sPadCode = "6"; break;
default: invalidCode = true; break;
}
}
r = "XboxAxis" + sPadCode + "Joy" + sJoyCode;
if(invalidCode)
{
r = "";
}
return r;
}
private static string DetermineDPadMac(XboxDPad padDir, int ctrlrNum)
{
string r = "";
string sJoyCode = "";
string sPadCode = "";
bool invalidCode = false;
if(ctrlrNum == 0)
{
sJoyCode = "";
}
else
{
sJoyCode = " " + ctrlrNum.ToString();
}
switch(padDir)
{
case XboxDPad.Up: sPadCode = "5"; break;
case XboxDPad.Down: sPadCode = "6"; break;
case XboxDPad.Left: sPadCode = "7"; break;
case XboxDPad.Right: sPadCode = "8"; break;
default: invalidCode = true; break;
}
r = "joystick" + sJoyCode + " button " + sPadCode;
if(invalidCode)
{
r = "";
}
return r;
}
private static string DetermineDPadWirelessLinux(XboxDPad padDir, int ctrlrNum)
{
string r = "";
string sJoyCode = "";
string sPadCode = "";
bool invalidCode = false;
if(ctrlrNum == 0)
{
sJoyCode = "";
}
else
{
sJoyCode = " " + ctrlrNum.ToString();
}
switch(padDir)
{
case XboxDPad.Up: sPadCode = "13"; break;
case XboxDPad.Down: sPadCode = "14"; break;
case XboxDPad.Left: sPadCode = "11"; break;
case XboxDPad.Right: sPadCode = "12"; break;
default: invalidCode = true; break;
}
r = "joystick" + sJoyCode + " button " + sPadCode;
if(invalidCode)
{
r = "";
}
return r;
}
// ------------- Private XInput Wrappers (for Windows Native player and editor only) -------------- //
#if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN
// ------------ Inner Class ------------//
// Used to setup XInput for Windows
class XciXInputInitializer
{
// Ctor
public XciXInputInitializer()
{
// Only runs once.
// Setup XInput here...
// Call input states twice in order to make sure that
// the previous states and current states are the same.
// This is needed to prevent errors where GetButtonUp will trigger unexpectledly
for (int i = 0; i < 4; i++)
{
PlayerIndex plyNum = (PlayerIndex)i;
xInputCtrlrsPrev[i] = xInputCtrlrs[i];
xInputCtrlrs[i] = GamePad.GetState(plyNum, XCI.WindowsDeadzoneMethod);
}
for (int i = 0; i < 4; i++)
{
PlayerIndex plyNum = (PlayerIndex)i;
xInputCtrlrsPrev[i] = xInputCtrlrs[i];
xInputCtrlrs[i] = GamePad.GetState(plyNum, XCI.WindowsDeadzoneMethod);
}
}
public void Dummy()
{
// Intentionally does nothing to prevent warnings
}
}
// ------------ Members --------------- //
// Windows variables
private static GamePadState[] xInputCtrlrs = new GamePadState[4];
private static GamePadState[] xInputCtrlrsPrev = new GamePadState[4];
private static int xiPrevFrameCount = -1;
private static bool xiUpdateAlreadyCalled = false;
private static bool xiNumOfCtrlrsQueried = false;
private static XciXInputInitializer xinputInitalizer = new XCI.XciXInputInitializer();
// This can be set to something different if you want
private const GamePadDeadZone WindowsDeadzoneMethod = GamePadDeadZone.Circular;
// ------------ Methods --------------- //
//>> For updating states <<
private static void XInputUpdateAllStates()
{
if(xiUpdateAlreadyCalled) return;
for(int i = 0; i < 4; i++)
{
PlayerIndex plyNum = (PlayerIndex) i;
xInputCtrlrsPrev[i] = xInputCtrlrs[i];
xInputCtrlrs[i] = GamePad.GetState(plyNum, XCI.WindowsDeadzoneMethod);
}
xiUpdateAlreadyCalled = true;
}
//>> For getting states <<
private static GamePadState XInputGetSingleState()
{
return xInputCtrlrs[0];
}
private static GamePadState XInputGetPaticularState(int ctrlNum)
{
if (!IsControllerNumberValid(ctrlNum)) return xInputCtrlrs[0];
return xInputCtrlrs[ctrlNum-1];
}
private static GamePadState XInputGetSingleStatePrev()
{
return xInputCtrlrsPrev[0];
}
private static GamePadState XInputGetPaticularStatePrev(int ctrlNum)
{
if (!IsControllerNumberValid(ctrlNum)) return xInputCtrlrsPrev[0];
return xInputCtrlrsPrev[ctrlNum-1];
}
//>> For getting input <<
private static ButtonState XInputGetButtonState(GamePadButtons xiButtons, XboxButton xciBtn)
{
ButtonState stateToReturn = ButtonState.Pressed;
switch(xciBtn)
{
case XboxButton.A: stateToReturn = xiButtons.A; break;
case XboxButton.B: stateToReturn = xiButtons.B; break;
case XboxButton.X: stateToReturn = xiButtons.X; break;
case XboxButton.Y: stateToReturn = xiButtons.Y; break;
case XboxButton.Start: stateToReturn = xiButtons.Start; break;
case XboxButton.Back: stateToReturn = xiButtons.Back; break;
case XboxButton.LeftBumper: stateToReturn = xiButtons.LeftShoulder; break;
case XboxButton.RightBumper: stateToReturn = xiButtons.RightShoulder; break;
case XboxButton.LeftStick: stateToReturn = xiButtons.LeftStick; break;
case XboxButton.RightStick: stateToReturn = xiButtons.RightStick; break;
}
return stateToReturn;
}
private static ButtonState XInputGetDPadState(GamePadDPad xiDPad, XboxDPad xciDPad)
{
ButtonState stateToReturn = ButtonState.Released;
switch(xciDPad)
{
case XboxDPad.Up: stateToReturn = xiDPad.Up; break;
case XboxDPad.Down: stateToReturn = xiDPad.Down; break;
case XboxDPad.Left: stateToReturn = xiDPad.Left; break;
case XboxDPad.Right: stateToReturn = xiDPad.Right; break;
}
return stateToReturn;
}
private static float XInputGetAxisState(GamePadTriggers xiTriggers, XboxAxis xciAxis)
{
float stateToReturn = 0.0f;
switch(xciAxis)
{
case XboxAxis.LeftTrigger: stateToReturn = xiTriggers.Left; break;
case XboxAxis.RightTrigger: stateToReturn = xiTriggers.Right; break;
default: stateToReturn = 0.0f; break;
}
return stateToReturn;
}
private static float XInputGetAxisState(GamePadThumbSticks xiThumbSticks, XboxAxis xciAxis)
{
float stateToReturn = 0.0f;
switch(xciAxis)
{
case XboxAxis.LeftStickX: stateToReturn = xiThumbSticks.Left.X; break;
case XboxAxis.LeftStickY: stateToReturn = xiThumbSticks.Left.Y; break;
case XboxAxis.RightStickX: stateToReturn = xiThumbSticks.Right.X; break;
case XboxAxis.RightStickY: stateToReturn = xiThumbSticks.Right.Y; break;
default: stateToReturn = 0.0f; break;
}
return stateToReturn;
}
private static bool XInputStillInCurrFrame()
{
bool r = false;
xinputInitalizer.Dummy(); // Stop warnings about not using the initilaizer
// Get the current frame
int currFrame = Time.frameCount;
// Are we still in the current frame?
if(xiPrevFrameCount == currFrame)
{
r = true;
}
else
{
r = false;
xiUpdateAlreadyCalled = false;
}
// Assign the previous frame count regardless of whether it's the same or not.
xiPrevFrameCount = currFrame;
return r;
}
#endif
// END of Windows only subsystem ==========================================
// -------------------------- Handler Script -------------------
// Secret Private Script that does some maintainace work for XCI states. User should not use this script at all.
private class XciHandler : MonoBehaviour
{
private static XciHandler instance = null;
public bool u3dTrigger0LeftIsTouched = false;
public bool u3dTrigger0RightIsTouched = false;
public bool u3dTrigger1LeftIsTouched = false;
public bool u3dTrigger1RightIsTouched = false;
public bool u3dTrigger2LeftIsTouched = false;
public bool u3dTrigger2RightIsTouched = false;
public bool u3dTrigger3LeftIsTouched = false;
public bool u3dTrigger3RightIsTouched = false;
public bool u3dTrigger4LeftIsTouched = false;
public bool u3dTrigger4RightIsTouched = false;
void Awake()
{
if(XciHandler.instance != null)
{
GameObject.Destroy(this.gameObject);
}
XciHandler.instance = this;
// Lives for the life of the game
DontDestroyOnLoad(this.gameObject);
}
void OnEnable()
{
SceneManager.sceneLoaded += OnSceneFinishedLoading;
}
void OnDisable()
{
SceneManager.sceneLoaded -= OnSceneFinishedLoading;
}
// Callback made to replace obsolete method OnLevelWasLoaded(int)
void OnSceneFinishedLoading(Scene currentScene, LoadSceneMode mode)
{
this.ResetTriggerTouches();
}
void OnApplicationFocus(bool isWindowInFocusNow)
{
if(!isWindowInFocusNow)
{
this.ResetTriggerTouches();
}
}
private void ResetTriggerTouches()
{
this.u3dTrigger0LeftIsTouched = false;
this.u3dTrigger0RightIsTouched = false;
this.u3dTrigger1LeftIsTouched = false;
this.u3dTrigger1RightIsTouched = false;
this.u3dTrigger2LeftIsTouched = false;
this.u3dTrigger2RightIsTouched = false;
this.u3dTrigger3LeftIsTouched = false;
this.u3dTrigger3RightIsTouched = false;
this.u3dTrigger4LeftIsTouched = false;
this.u3dTrigger4RightIsTouched = false;
}
public static XciHandler Instance
{
get
{
if(XciHandler.instance == null)
{
GameObject xciHandleObj = new GameObject("XboxCtrlrInput Handler Object");
xciHandleObj.AddComponent<XciHandler>();
}
return XciHandler.instance;
}
}
} // end of XciHandler
} // end of XCI
public static class XboxButtonExtensions
{
public static bool IsDPad(this XboxButton button)
{
return (button == XboxButton.DPadUp ||
button == XboxButton.DPadDown ||
button == XboxButton.DPadLeft ||
button == XboxButton.DPadRight);
}
public static XboxDPad ToDPad(this XboxButton button)
{
if (button == XboxButton.DPadUp)
return XboxDPad.Up;
if (button == XboxButton.DPadDown)
return XboxDPad.Down;
if (button == XboxButton.DPadLeft)
return XboxDPad.Left;
if (button == XboxButton.DPadRight)
return XboxDPad.Right;
return default(XboxDPad);
}
}
}
| |
using Kitware.VTK;
using System;
// input file is C:\VTK\Graphics\Testing\Tcl\multipleIso.tcl
// output file is AVmultipleIso.cs
/// <summary>
/// The testing class derived from AVmultipleIso
/// </summary>
public class AVmultipleIsoClass
{
/// <summary>
/// The main entry method called by the CSharp driver
/// </summary>
/// <param name="argv"></param>
public static void AVmultipleIso(String [] argv)
{
//Prefix Content is: ""
// get the interactor ui[]
//# Graphics stuff[]
// Create the RenderWindow, Renderer and both Actors[]
//[]
ren1 = vtkRenderer.New();
renWin = vtkRenderWindow.New();
renWin.AddRenderer((vtkRenderer)ren1);
iren = new vtkRenderWindowInteractor();
iren.SetRenderWindow((vtkRenderWindow)renWin);
pl3d = new vtkMultiBlockPLOT3DReader();
pl3d.SetXYZFileName((string)"" + (VTK_DATA_ROOT.ToString()) + "/Data/combxyz.bin");
pl3d.SetQFileName((string)"" + (VTK_DATA_ROOT.ToString()) + "/Data/combq.bin");
pl3d.SetScalarFunctionNumber((int)100);
pl3d.SetVectorFunctionNumber((int)202);
pl3d.Update();
range = ((vtkDataSet)pl3d.GetOutput().GetBlock(0)).GetPointData().GetScalars().GetRange();
min = (double)(lindex(range,0));
max = (double)(lindex(range,1));
value = (min+max)/2.0;
cf = new vtkContourFilter();
cf.SetInputData((vtkDataSet)pl3d.GetOutput().GetBlock(0));
cf.SetValue((int)0,(double)value);
cf.UseScalarTreeOn();
numberOfContours = 5;
epsilon = (double)(max-min)/(double)(numberOfContours*10);
min = min+epsilon;
max = max-epsilon;
i = 1;
while((i) <= numberOfContours)
{
cf.SetValue((int)0,(double)min+((i-1)/(double)(numberOfContours-1))*(max-min));
cf.Update();
pd[i] = new vtkPolyData();
pd[i].CopyStructure((vtkDataSet)cf.GetOutput());
pd[i].GetPointData().DeepCopy((vtkFieldData)cf.GetOutput().GetPointData());
mapper[i] = vtkPolyDataMapper.New();
mapper[i].SetInputData((vtkPolyData)pd[i]);
mapper[i].SetScalarRange((double)((vtkDataSet)pl3d.GetOutput().GetBlock(0)).GetPointData().GetScalars().GetRange()[0],
(double)((vtkDataSet)pl3d.GetOutput().GetBlock(0)).GetPointData().GetScalars().GetRange()[1]);
actor[i] = new vtkActor();
actor[i].AddPosition((double)0,(double)i*12,(double)0);
actor[i].SetMapper((vtkMapper)mapper[i]);
ren1.AddActor((vtkProp)actor[i]);
i = i + 1;
}
// Add the actors to the renderer, set the background and size[]
//[]
ren1.SetBackground((double).3,(double).3,(double).3);
renWin.SetSize((int)450,(int)150);
cam1 = ren1.GetActiveCamera();
ren1.GetActiveCamera().SetPosition((double)-36.3762,(double)32.3855,(double)51.3652);
ren1.GetActiveCamera().SetFocalPoint((double)8.255,(double)33.3861,(double)29.7687);
ren1.GetActiveCamera().SetViewAngle((double)30);
ren1.GetActiveCamera().SetViewUp((double)0,(double)0,(double)1);
ren1.ResetCameraClippingRange();
iren.Initialize();
// render the image[]
//[]
// prevent the tk window from showing up then start the event loop[]
//deleteAllVTKObjects();
}
static string VTK_DATA_ROOT;
static int threshold;
static vtkRenderer ren1;
static vtkRenderWindow renWin;
static vtkRenderWindowInteractor iren;
static vtkMultiBlockPLOT3DReader pl3d;
static double[] range;
static double min;
static double max;
static double value;
static vtkContourFilter cf;
static int numberOfContours;
static double epsilon;
static int i;
static vtkPolyData[] pd = new vtkPolyData[100];
static vtkPolyDataMapper[] mapper = new vtkPolyDataMapper[100];
static vtkActor[] actor = new vtkActor[100];
static vtkCamera cam1;
/// <summary>
/// Returns the variable in the index [i] of the System.Array [arr]
/// </summary>
/// <param name="arr"></param>
/// <param name="i"></param>
public static Object lindex(System.Array arr, int i)
{
return arr.GetValue(i);
}
/// <summary>
/// Returns the variable in the index [index] of the array [arr]
/// </summary>
/// <param name="arr"></param>
/// <param name="index"></param>
public static double lindex(IntPtr arr, int index)
{
double[] destination = new double[index + 1];
System.Runtime.InteropServices.Marshal.Copy(arr, destination, 0, index + 1);
return destination[index];
}
/// <summary>
/// Returns the variable in the index [index] of the vtkLookupTable [arr]
/// </summary>
/// <param name="arr"></param>
/// <param name="index"></param>
public static long lindex(vtkLookupTable arr, double index)
{
return arr.GetIndex(index);
}
/// <summary>
/// Returns the substring ([index], [index]+1) in the string [arr]
/// </summary>
/// <param name="arr"></param>
/// <param name="index"></param>
public static int lindex(String arr, int index)
{
string[] str = arr.Split(new char[]{' '});
return System.Int32.Parse(str[index]);
}
/// <summary>
/// Returns the index [index] in the int array [arr]
/// </summary>
/// <param name="arr"></param>
/// <param name="index"></param>
public static int lindex(int[] arr, int index)
{
return arr[index];
}
/// <summary>
/// Returns the index [index] in the float array [arr]
/// </summary>
/// <param name="arr"></param>
/// <param name="index"></param>
public static float lindex(float[] arr, int index)
{
return arr[index];
}
/// <summary>
/// Returns the index [index] in the double array [arr]
/// </summary>
/// <param name="arr"></param>
/// <param name="index"></param>
public static double lindex(double[] arr, int index)
{
return arr[index];
}
///<summary> A Get Method for Static Variables </summary>
public static string GetVTK_DATA_ROOT()
{
return VTK_DATA_ROOT;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetVTK_DATA_ROOT(string toSet)
{
VTK_DATA_ROOT = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static int Getthreshold()
{
return threshold;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setthreshold(int toSet)
{
threshold = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkRenderer Getren1()
{
return ren1;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setren1(vtkRenderer toSet)
{
ren1 = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkRenderWindow GetrenWin()
{
return renWin;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetrenWin(vtkRenderWindow toSet)
{
renWin = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkRenderWindowInteractor Getiren()
{
return iren;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setiren(vtkRenderWindowInteractor toSet)
{
iren = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkMultiBlockPLOT3DReader Getpl3d()
{
return pl3d;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setpl3d(vtkMultiBlockPLOT3DReader toSet)
{
pl3d = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static double[] Getrange()
{
return range;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setrange(double[] toSet)
{
range = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static double Getmin()
{
return min;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setmin(double toSet)
{
min = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static double Getmax()
{
return max;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setmax(double toSet)
{
max = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static double Getvalue()
{
return value;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setvalue(double toSet)
{
value = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkContourFilter Getcf()
{
return cf;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setcf(vtkContourFilter toSet)
{
cf = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static int GetnumberOfContours()
{
return numberOfContours;
}
///<summary> A Set Method for Static Variables </summary>
public static void SetnumberOfContours(int toSet)
{
numberOfContours = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static double Getepsilon()
{
return epsilon;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setepsilon(double toSet)
{
epsilon = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static int Geti()
{
return i;
}
///<summary> A Set Method for Static Variables </summary>
public static void Seti(int toSet)
{
i = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkPolyData[] Getpd()
{
return pd;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setpd(vtkPolyData[] toSet)
{
pd = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkPolyDataMapper[] Getmapper()
{
return mapper;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setmapper(vtkPolyDataMapper[] toSet)
{
mapper = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkActor[] Getactor()
{
return actor;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setactor(vtkActor[] toSet)
{
actor = toSet;
}
///<summary> A Get Method for Static Variables </summary>
public static vtkCamera Getcam1()
{
return cam1;
}
///<summary> A Set Method for Static Variables </summary>
public static void Setcam1(vtkCamera toSet)
{
cam1 = toSet;
}
///<summary>Deletes all static objects created</summary>
public static void deleteAllVTKObjects()
{
//clean up vtk objects
if(ren1!= null){ren1.Dispose();}
if(renWin!= null){renWin.Dispose();}
if(iren!= null){iren.Dispose();}
if(pl3d!= null){pl3d.Dispose();}
if(cf!= null){cf.Dispose();}
if(cam1!= null){cam1.Dispose();}
}
}
//--- end of script --//
| |
using Pid = System.UInt32;
using IPage = Core.PgHdr;
using System;
using System.Diagnostics;
using Core.IO;
namespace Core
{
public partial class Btree
{
static ushort MX_CELL_SIZE(BtShared bt) { return (ushort)(bt.PageSize - 8); }
static ushort MX_CELL(BtShared bt) { return (ushort)((bt.PageSize - 8) / 6); }
const string FILE_HEADER = "SQLite format 3\0";
const int DEFAULT_CACHE_SIZE = 2000;
const int MASTER_ROOT = 1;
const byte PTF_INTKEY = 0x01;
const byte PTF_ZERODATA = 0x02;
const byte PTF_LEAFDATA = 0x04;
const byte PTF_LEAF = 0x08;
public struct OverflowCell // Cells that will not fit on aData[]
{
internal byte[] Cell; // Pointers to the body of the overflow cell
internal OverflowCell Copy()
{
var cp = new OverflowCell();
if (Cell != null)
{
cp.Cell = SysEx.Alloc(Cell.Length);
Buffer.BlockCopy(Cell, 0, cp.Cell, 0, Cell.Length);
}
return cp;
}
};
public class MemPage
{
internal bool IsInit; // True if previously initialized. MUST BE FIRST!
internal byte Overflows; // Number of overflow cell bodies in aCell[]
internal bool IntKey; // True if intkey flag is set
internal bool Leaf; // True if leaf flag is set
internal bool HasData; // True if this page stores data
internal byte HdrOffset; // 100 for page 1. 0 otherwise
internal byte ChildPtrSize; // 0 if leaf. 4 if !leaf
internal byte Max1bytePayload; // min(maxLocal,127)
internal ushort MaxLocal; // Copy of BtShared.maxLocal or BtShared.maxLeaf
internal ushort MinLocal; // Copy of BtShared.minLocal or BtShared.minLeaf
internal ushort CellOffset; // Index in aData of first cell pou16er
internal ushort Frees; // Number of free bytes on the page
internal ushort Cells; // Number of cells on this page, local and ovfl
internal ushort MaskPage; // Mask for page offset
internal ushort[] OvflIdxs = new ushort[5];
internal OverflowCell[] Ovfls = new OverflowCell[5];
internal BtShared Bt; // Pointer to BtShared that this page is part of
internal byte[] Data; // Pointer to disk image of the page data
//object byte[] DataEnd; // One byte past the end of usable data
//object byte[] CellIdx; // The cell index area
internal IPage DBPage; // Pager page handle
internal Pid ID; // Page number for this page
internal MemPage memcopy()
{
var cp = (MemPage)MemberwiseClone();
//if (Overflows != null)
//{
// cp.Overflows = new OverflowCell[Overflows.Length];
// for (int i = 0; i < Overflows.Length; i++)
// cp.Overflows[i] = Overflows[i].Copy();
//}
//if (Data != null)
//{
// cp.Data = SysEx.Alloc(Data.Length);
// Buffer.BlockCopy(Data, 0, cp.Data, 0, Data.Length);
//}
return cp;
}
};
const int EXTRA_SIZE = 0; // No used in C#, since we use create a class; was MemPage.Length;
public enum BTS : ushort
{
READ_ONLY = 0x0001, // Underlying file is readonly
PAGESIZE_FIXED = 0x0002,// Page size can no longer be changed
SECURE_DELETE = 0x0004, // PRAGMA secure_delete is enabled
INITIALLY_EMPTY = 0x0008, // Database was empty at trans start
NO_WAL = 0x0010, // Do not open write-ahead-log files
EXCLUSIVE = 0x0020, // pWriter has an exclusive lock
PENDING = 0x0040, // Waiting for read-locks to clear
}
public class BtShared
{
static int _autoID; // For C#
internal int AutoID; // For C#
public BtShared() { AutoID = _autoID++; } // For C#
internal Pager Pager; // The page cache
internal Context Ctx; // Database connection currently using this Btree
internal BtCursor Cursor; // A list of all open cursors
internal MemPage Page1; // First page of the database
internal Btree.OPEN OpenFlags; // Flags to sqlite3BtreeOpen()
#if !OMIT_AUTOVACUUM
internal bool AutoVacuum; // True if auto-vacuum is enabled
internal bool IncrVacuum; // True if incr-vacuum is enabled
internal bool DoTruncate; // True to truncate db on commit
#endif
internal TRANS InTransaction; // Transaction state
internal byte Max1bytePayload; // Maximum first byte of cell for a 1-byte payload
internal BTS BtsFlags; // Boolean parameters. See BTS_* macros below
internal ushort MaxLocal; // Maximum local payload in non-LEAFDATA tables
internal ushort MinLocal; // Minimum local payload in non-LEAFDATA tables
internal ushort MaxLeaf; // Maximum local payload in a LEAFDATA table
internal ushort MinLeaf; // Minimum local payload in a LEAFDATA table
internal uint PageSize; // Total number of bytes on a page
internal uint UsableSize; // Number of usable bytes on each page
internal int Transactions; // Number of open transactions (read + write)
internal Pid Pages; // Number of pages in the database
internal ISchema Schema; // Pointer to space allocated by sqlite3BtreeSchema()
internal Action<object> FreeSchema; // Destructor for BtShared.pSchema
internal MutexEx Mutex; // Non-recursive mutex required to access this object
internal Bitvec HasContent; // Set of pages moved to free-list this transaction
#if !OMIT_SHARED_CACHE
internal int Refs; // Number of references to this structure
internal BtShared Next; // Next on a list of sharable BtShared structs
internal BtLock Lock; // List of locks held on this shared-btree struct
internal Btree Writer; // Btree with currently open write transaction
#endif
internal byte[] TmpSpace; // BtShared.pageSize bytes of space for tmp use
}
public struct CellInfo
{
internal uint Cell_; // Offset to start of cell content -- Needed for C#
internal long Key; // The key for INTKEY tables, or number of bytes in key
internal byte[] Cell; // Pointer to the start of cell content
internal uint Data; // Number of bytes of data
internal uint Payload; // Total amount of payload
internal ushort Header; // Size of the cell content header in bytes
internal ushort Local; // Amount of payload held locally
internal ushort Overflow; // Offset to overflow page number. Zero if no overflow
internal ushort Size; // Size of the cell content on the main b-tree page
internal bool Equals(CellInfo ci)
{
if (ci.Cell_ >= ci.Cell.Length || Cell_ >= this.Cell.Length)
return false;
if (ci.Cell[ci.Cell_] != this.Cell[Cell_])
return false;
if (ci.Key != this.Key || ci.Data != this.Data || ci.Payload != this.Payload)
return false;
if (ci.Header != this.Header || ci.Local != this.Local)
return false;
if (ci.Overflow != this.Overflow || ci.Size != this.Size)
return false;
return true;
}
}
const int BTCURSOR_MAX_DEPTH = 20;
public enum CURSOR : byte
{
INVALID = 0,
VALID = 1,
REQUIRESEEK = 2,
FAULT = 3,
}
public class BtCursor
{
internal Btree Btree; // The Btree to which this cursor belongs
internal BtShared Bt; // The BtShared this cursor points to
internal BtCursor Next, Prev; // Forms a linked list of all cursors
internal KeyInfo KeyInfo; // Argument passed to comparison function
#if !OMIT_INCRBLOB
internal Pid[] Overflows; // Cache of overflow page locations
#endif
internal Pid RootID; // The root page of this tree
internal long CachedRowID; // Next rowid cache. 0 means not valid
internal CellInfo Info = new CellInfo(); // A parse of the cell we are pointing at
internal long KeyLength; // Size of pKey, or last integer key
internal byte[] Key; // Saved key that was cursor's last known position
internal int SkipNext; // Prev() is noop if negative. Next() is noop if positive
internal bool WrFlag; // True if writable
internal byte AtLast; // VdbeCursor pointing to the last entry
internal bool ValidNKey; // True if info.nKey is valid
internal CURSOR State; // One of the CURSOR_XXX constants (see below)
#if !OMIT_INCRBLOB
internal bool IsIncrblobHandle; // True if this cursor is an incr. io handle
#endif
internal byte Hints; // As configured by CursorSetHints()
internal short ID; // Index of current page in apPage
internal ushort[] Idxs = new ushort[BTCURSOR_MAX_DEPTH]; // Current index in apPage[i]
internal MemPage[] Pages = new MemPage[BTCURSOR_MAX_DEPTH]; // Pages from root to current page
internal void memset()
{
Next = Prev = null;
KeyInfo = null;
RootID = 0;
CachedRowID = 0;
Info = new CellInfo();
WrFlag = false;
AtLast = 0;
ValidNKey = false;
State = 0;
KeyLength = 0;
Key = null;
SkipNext = 0;
#if !OMIT_INCRBLOB
IsIncrblobHandle = false;
Overflows = null;
#endif
ID = 0;
}
public BtCursor Copy()
{
var cp = (BtCursor)MemberwiseClone();
return cp;
}
}
static Pid PENDING_BYTE_PAGE(BtShared bt) { return Pager.MJ_PID(bt.Pager); }
static Pid PTRMAP_PAGENO(BtShared bt, Pid id) { return ptrmapPageno(bt, id); }
static Pid PTRMAP_PTROFFSET(Pid ptrmapID, Pid id) { return (5 * (id - ptrmapID - 1)); }
static bool PTRMAP_ISPAGE(BtShared bt, Pid id) { return (PTRMAP_PAGENO((bt), (id)) == (id)); }
internal enum PTRMAP : byte
{
ROOTPAGE = 1,
FREEPAGE = 2,
OVERFLOW1 = 3,
OVERFLOW2 = 4,
BTREE = 5,
}
#if DEBUG
static void btreeIntegrity(Btree p)
{
Debug.Assert(p.Bt.InTransaction != TRANS.NONE || p.Bt.Transactions == 0);
Debug.Assert(p.Bt.InTransaction >= p.InTrans);
}
#else
static void btreeIntegrity(Btree p) { }
#endif
internal class IntegrityCk
{
public BtShared Bt; // The tree being checked out
public Pager Pager; // The associated pager. Also accessible by pBt.pPager
public byte[] PgRefs; // 1 bit per page in the db (see above)
public Pid Pages; // Number of pages in the database
public int MaxErrors; // Stop accumulating errors when this reaches zero
public int Errors; // Number of messages written to zErrMsg so far
public bool MallocFailed; // A memory allocation error has occurred
public Text.StringBuilder ErrMsg = new Text.StringBuilder(); // Accumulate the error message text here
};
}
}
| |
#if REAL_T_IS_DOUBLE
using real_t = System.Double;
#else
using real_t = System.Single;
#endif
using System;
namespace Godot
{
public static partial class Mathf
{
// Define constants with Decimal precision and cast down to double or float.
/// <summary>
/// The circle constant, the circumference of the unit circle in radians.
/// </summary>
// 6.2831855f and 6.28318530717959
public const real_t Tau = (real_t)6.2831853071795864769252867666M;
/// <summary>
/// Constant that represents how many times the diameter of a circle
/// fits around its perimeter. This is equivalent to `Mathf.Tau / 2`.
/// </summary>
// 3.1415927f and 3.14159265358979
public const real_t Pi = (real_t)3.1415926535897932384626433833M;
/// <summary>
/// Positive infinity. For negative infinity, use `-Mathf.Inf`.
/// </summary>
public const real_t Inf = real_t.PositiveInfinity;
/// <summary>
/// "Not a Number", an invalid value. `NaN` has special properties, including
/// that it is not equal to itself. It is output by some invalid operations,
/// such as dividing zero by zero.
/// </summary>
public const real_t NaN = real_t.NaN;
// 0.0174532924f and 0.0174532925199433
private const real_t Deg2RadConst = (real_t)0.0174532925199432957692369077M;
// 57.29578f and 57.2957795130823
private const real_t Rad2DegConst = (real_t)57.295779513082320876798154814M;
/// <summary>
/// Returns the absolute value of `s` (i.e. positive value).
/// </summary>
/// <param name="s">The input number.</param>
/// <returns>The absolute value of `s`.</returns>
public static int Abs(int s)
{
return Math.Abs(s);
}
/// <summary>
/// Returns the absolute value of `s` (i.e. positive value).
/// </summary>
/// <param name="s">The input number.</param>
/// <returns>The absolute value of `s`.</returns>
public static real_t Abs(real_t s)
{
return Math.Abs(s);
}
/// <summary>
/// Returns the arc cosine of `s` in radians. Use to get the angle of cosine s.
/// </summary>
/// <param name="s">The input cosine value. Must be on the range of -1.0 to 1.0.</param>
/// <returns>An angle that would result in the given cosine value. On the range `0` to `Tau/2`.</returns>
public static real_t Acos(real_t s)
{
return (real_t)Math.Acos(s);
}
/// <summary>
/// Returns the arc sine of `s` in radians. Use to get the angle of sine s.
/// </summary>
/// <param name="s">The input sine value. Must be on the range of -1.0 to 1.0.</param>
/// <returns>An angle that would result in the given sine value. On the range `-Tau/4` to `Tau/4`.</returns>
public static real_t Asin(real_t s)
{
return (real_t)Math.Asin(s);
}
/// <summary>
/// Returns the arc tangent of `s` in radians. Use to get the angle of tangent s.
///
/// The method cannot know in which quadrant the angle should fall.
/// See <see cref="Atan2(real_t, real_t)"/> if you have both `y` and `x`.
/// </summary>
/// <param name="s">The input tangent value.</param>
/// <returns>An angle that would result in the given tangent value. On the range `-Tau/4` to `Tau/4`.</returns>
public static real_t Atan(real_t s)
{
return (real_t)Math.Atan(s);
}
/// <summary>
/// Returns the arc tangent of `y` and `x` in radians. Use to get the angle
/// of the tangent of `y/x`. To compute the value, the method takes into
/// account the sign of both arguments in order to determine the quadrant.
///
/// Important note: The Y coordinate comes first, by convention.
/// </summary>
/// <param name="y">The Y coordinate of the point to find the angle to.</param>
/// <param name="x">The X coordinate of the point to find the angle to.</param>
/// <returns>An angle that would result in the given tangent value. On the range `-Tau/2` to `Tau/2`.</returns>
public static real_t Atan2(real_t y, real_t x)
{
return (real_t)Math.Atan2(y, x);
}
/// <summary>
/// Converts a 2D point expressed in the cartesian coordinate
/// system (X and Y axis) to the polar coordinate system
/// (a distance from the origin and an angle).
/// </summary>
/// <param name="x">The input X coordinate.</param>
/// <param name="y">The input Y coordinate.</param>
/// <returns>A <see cref="Vector2"/> with X representing the distance and Y representing the angle.</returns>
public static Vector2 Cartesian2Polar(real_t x, real_t y)
{
return new Vector2(Sqrt(x * x + y * y), Atan2(y, x));
}
/// <summary>
/// Rounds `s` upward (towards positive infinity).
/// </summary>
/// <param name="s">The number to ceil.</param>
/// <returns>The smallest whole number that is not less than `s`.</returns>
public static real_t Ceil(real_t s)
{
return (real_t)Math.Ceiling(s);
}
/// <summary>
/// Clamps a `value` so that it is not less than `min` and not more than `max`.
/// </summary>
/// <param name="value">The value to clamp.</param>
/// <param name="min">The minimum allowed value.</param>
/// <param name="max">The maximum allowed value.</param>
/// <returns>The clamped value.</returns>
public static int Clamp(int value, int min, int max)
{
return value < min ? min : value > max ? max : value;
}
/// <summary>
/// Clamps a `value` so that it is not less than `min` and not more than `max`.
/// </summary>
/// <param name="value">The value to clamp.</param>
/// <param name="min">The minimum allowed value.</param>
/// <param name="max">The maximum allowed value.</param>
/// <returns>The clamped value.</returns>
public static real_t Clamp(real_t value, real_t min, real_t max)
{
return value < min ? min : value > max ? max : value;
}
/// <summary>
/// Returns the cosine of angle `s` in radians.
/// </summary>
/// <param name="s">The angle in radians.</param>
/// <returns>The cosine of that angle.</returns>
public static real_t Cos(real_t s)
{
return (real_t)Math.Cos(s);
}
/// <summary>
/// Returns the hyperbolic cosine of angle `s` in radians.
/// </summary>
/// <param name="s">The angle in radians.</param>
/// <returns>The hyperbolic cosine of that angle.</returns>
public static real_t Cosh(real_t s)
{
return (real_t)Math.Cosh(s);
}
/// <summary>
/// Converts an angle expressed in degrees to radians.
/// </summary>
/// <param name="deg">An angle expressed in degrees.</param>
/// <returns>The same angle expressed in radians.</returns>
public static real_t Deg2Rad(real_t deg)
{
return deg * Deg2RadConst;
}
/// <summary>
/// Easing function, based on exponent. The curve values are:
/// `0` is constant, `1` is linear, `0` to `1` is ease-in, `1` or more is ease-out.
/// Negative values are in-out/out-in.
/// </summary>
/// <param name="s">The value to ease.</param>
/// <param name="curve">`0` is constant, `1` is linear, `0` to `1` is ease-in, `1` or more is ease-out.</param>
/// <returns>The eased value.</returns>
public static real_t Ease(real_t s, real_t curve)
{
if (s < 0f)
{
s = 0f;
}
else if (s > 1.0f)
{
s = 1.0f;
}
if (curve > 0f)
{
if (curve < 1.0f)
{
return 1.0f - Pow(1.0f - s, 1.0f / curve);
}
return Pow(s, curve);
}
if (curve < 0f)
{
if (s < 0.5f)
{
return Pow(s * 2.0f, -curve) * 0.5f;
}
return (1.0f - Pow(1.0f - (s - 0.5f) * 2.0f, -curve)) * 0.5f + 0.5f;
}
return 0f;
}
/// <summary>
/// The natural exponential function. It raises the mathematical
/// constant `e` to the power of `s` and returns it.
/// </summary>
/// <param name="s">The exponent to raise `e` to.</param>
/// <returns>`e` raised to the power of `s`.</returns>
public static real_t Exp(real_t s)
{
return (real_t)Math.Exp(s);
}
/// <summary>
/// Rounds `s` downward (towards negative infinity).
/// </summary>
/// <param name="s">The number to floor.</param>
/// <returns>The largest whole number that is not more than `s`.</returns>
public static real_t Floor(real_t s)
{
return (real_t)Math.Floor(s);
}
/// <summary>
/// Returns a normalized value considering the given range.
/// This is the opposite of <see cref="Lerp(real_t, real_t, real_t)"/>.
/// </summary>
/// <param name="from">The interpolated value.</param>
/// <param name="to">The destination value for interpolation.</param>
/// <param name="weight">A value on the range of 0.0 to 1.0, representing the amount of interpolation.</param>
/// <returns>The resulting value of the inverse interpolation.</returns>
public static real_t InverseLerp(real_t from, real_t to, real_t weight)
{
return (weight - from) / (to - from);
}
/// <summary>
/// Returns true if `a` and `b` are approximately equal to each other.
/// The comparison is done using a tolerance calculation with <see cref="Epsilon"/>.
/// </summary>
/// <param name="a">One of the values.</param>
/// <param name="b">The other value.</param>
/// <returns>A bool for whether or not the two values are approximately equal.</returns>
public static bool IsEqualApprox(real_t a, real_t b)
{
// Check for exact equality first, required to handle "infinity" values.
if (a == b)
{
return true;
}
// Then check for approximate equality.
real_t tolerance = Epsilon * Abs(a);
if (tolerance < Epsilon)
{
tolerance = Epsilon;
}
return Abs(a - b) < tolerance;
}
/// <summary>
/// Returns whether `s` is an infinity value (either positive infinity or negative infinity).
/// </summary>
/// <param name="s">The value to check.</param>
/// <returns>A bool for whether or not the value is an infinity value.</returns>
public static bool IsInf(real_t s)
{
return real_t.IsInfinity(s);
}
/// <summary>
/// Returns whether `s` is a `NaN` ("Not a Number" or invalid) value.
/// </summary>
/// <param name="s">The value to check.</param>
/// <returns>A bool for whether or not the value is a `NaN` value.</returns>
public static bool IsNaN(real_t s)
{
return real_t.IsNaN(s);
}
/// <summary>
/// Returns true if `s` is approximately zero.
/// The comparison is done using a tolerance calculation with <see cref="Epsilon"/>.
///
/// This method is faster than using <see cref="IsEqualApprox(real_t, real_t)"/> with one value as zero.
/// </summary>
/// <param name="s">The value to check.</param>
/// <returns>A bool for whether or not the value is nearly zero.</returns>
public static bool IsZeroApprox(real_t s)
{
return Abs(s) < Epsilon;
}
/// <summary>
/// Linearly interpolates between two values by a normalized value.
/// This is the opposite <see cref="InverseLerp(real_t, real_t, real_t)"/>.
/// </summary>
/// <param name="from">The start value for interpolation.</param>
/// <param name="to">The destination value for interpolation.</param>
/// <param name="weight">A value on the range of 0.0 to 1.0, representing the amount of interpolation.</param>
/// <returns>The resulting value of the interpolation.</returns>
public static real_t Lerp(real_t from, real_t to, real_t weight)
{
return from + (to - from) * weight;
}
/// <summary>
/// Linearly interpolates between two angles (in radians) by a normalized value.
///
/// Similar to <see cref="Lerp(real_t, real_t, real_t)"/>,
/// but interpolates correctly when the angles wrap around <see cref="Tau"/>.
/// </summary>
/// <param name="from">The start angle for interpolation.</param>
/// <param name="to">The destination angle for interpolation.</param>
/// <param name="weight">A value on the range of 0.0 to 1.0, representing the amount of interpolation.</param>
/// <returns>The resulting angle of the interpolation.</returns>
public static real_t LerpAngle(real_t from, real_t to, real_t weight)
{
real_t difference = (to - from) % Mathf.Tau;
real_t distance = ((2 * difference) % Mathf.Tau) - difference;
return from + distance * weight;
}
/// <summary>
/// Natural logarithm. The amount of time needed to reach a certain level of continuous growth.
///
/// Note: This is not the same as the "log" function on most calculators, which uses a base 10 logarithm.
/// </summary>
/// <param name="s">The input value.</param>
/// <returns>The natural log of `s`.</returns>
public static real_t Log(real_t s)
{
return (real_t)Math.Log(s);
}
/// <summary>
/// Returns the maximum of two values.
/// </summary>
/// <param name="a">One of the values.</param>
/// <param name="b">The other value.</param>
/// <returns>Whichever of the two values is higher.</returns>
public static int Max(int a, int b)
{
return a > b ? a : b;
}
/// <summary>
/// Returns the maximum of two values.
/// </summary>
/// <param name="a">One of the values.</param>
/// <param name="b">The other value.</param>
/// <returns>Whichever of the two values is higher.</returns>
public static real_t Max(real_t a, real_t b)
{
return a > b ? a : b;
}
/// <summary>
/// Returns the minimum of two values.
/// </summary>
/// <param name="a">One of the values.</param>
/// <param name="b">The other value.</param>
/// <returns>Whichever of the two values is lower.</returns>
public static int Min(int a, int b)
{
return a < b ? a : b;
}
/// <summary>
/// Returns the minimum of two values.
/// </summary>
/// <param name="a">One of the values.</param>
/// <param name="b">The other value.</param>
/// <returns>Whichever of the two values is lower.</returns>
public static real_t Min(real_t a, real_t b)
{
return a < b ? a : b;
}
/// <summary>
/// Moves `from` toward `to` by the `delta` value.
///
/// Use a negative delta value to move away.
/// </summary>
/// <param name="from">The start value.</param>
/// <param name="to">The value to move towards.</param>
/// <param name="delta">The amount to move by.</param>
/// <returns>The value after moving.</returns>
public static real_t MoveToward(real_t from, real_t to, real_t delta)
{
return Abs(to - from) <= delta ? to : from + Sign(to - from) * delta;
}
/// <summary>
/// Returns the nearest larger power of 2 for the integer `value`.
/// </summary>
/// <param name="value">The input value.</param>
/// <returns>The nearest larger power of 2.</returns>
public static int NearestPo2(int value)
{
value--;
value |= value >> 1;
value |= value >> 2;
value |= value >> 4;
value |= value >> 8;
value |= value >> 16;
value++;
return value;
}
/// <summary>
/// Converts a 2D point expressed in the polar coordinate
/// system (a distance from the origin `r` and an angle `th`)
/// to the cartesian coordinate system (X and Y axis).
/// </summary>
/// <param name="r">The distance from the origin.</param>
/// <param name="th">The angle of the point.</param>
/// <returns>A <see cref="Vector2"/> representing the cartesian coordinate.</returns>
public static Vector2 Polar2Cartesian(real_t r, real_t th)
{
return new Vector2(r * Cos(th), r * Sin(th));
}
/// <summary>
/// Performs a canonical Modulus operation, where the output is on the range `[0, b)`.
/// </summary>
/// <param name="a">The dividend, the primary input.</param>
/// <param name="b">The divisor. The output is on the range `[0, b)`.</param>
/// <returns>The resulting output.</returns>
public static int PosMod(int a, int b)
{
int c = a % b;
if ((c < 0 && b > 0) || (c > 0 && b < 0))
{
c += b;
}
return c;
}
/// <summary>
/// Performs a canonical Modulus operation, where the output is on the range `[0, b)`.
/// </summary>
/// <param name="a">The dividend, the primary input.</param>
/// <param name="b">The divisor. The output is on the range `[0, b)`.</param>
/// <returns>The resulting output.</returns>
public static real_t PosMod(real_t a, real_t b)
{
real_t c = a % b;
if ((c < 0 && b > 0) || (c > 0 && b < 0))
{
c += b;
}
return c;
}
/// <summary>
/// Returns the result of `x` raised to the power of `y`.
/// </summary>
/// <param name="x">The base.</param>
/// <param name="y">The exponent.</param>
/// <returns>`x` raised to the power of `y`.</returns>
public static real_t Pow(real_t x, real_t y)
{
return (real_t)Math.Pow(x, y);
}
/// <summary>
/// Converts an angle expressed in radians to degrees.
/// </summary>
/// <param name="rad">An angle expressed in radians.</param>
/// <returns>The same angle expressed in degrees.</returns>
public static real_t Rad2Deg(real_t rad)
{
return rad * Rad2DegConst;
}
/// <summary>
/// Rounds `s` to the nearest whole number,
/// with halfway cases rounded towards the nearest multiple of two.
/// </summary>
/// <param name="s">The number to round.</param>
/// <returns>The rounded number.</returns>
public static real_t Round(real_t s)
{
return (real_t)Math.Round(s);
}
/// <summary>
/// Returns the sign of `s`: `-1` or `1`. Returns `0` if `s` is `0`.
/// </summary>
/// <param name="s">The input number.</param>
/// <returns>One of three possible values: `1`, `-1`, or `0`.</returns>
public static int Sign(int s)
{
if (s == 0)
return 0;
return s < 0 ? -1 : 1;
}
/// <summary>
/// Returns the sign of `s`: `-1` or `1`. Returns `0` if `s` is `0`.
/// </summary>
/// <param name="s">The input number.</param>
/// <returns>One of three possible values: `1`, `-1`, or `0`.</returns>
public static int Sign(real_t s)
{
if (s == 0)
return 0;
return s < 0 ? -1 : 1;
}
/// <summary>
/// Returns the sine of angle `s` in radians.
/// </summary>
/// <param name="s">The angle in radians.</param>
/// <returns>The sine of that angle.</returns>
public static real_t Sin(real_t s)
{
return (real_t)Math.Sin(s);
}
/// <summary>
/// Returns the hyperbolic sine of angle `s` in radians.
/// </summary>
/// <param name="s">The angle in radians.</param>
/// <returns>The hyperbolic sine of that angle.</returns>
public static real_t Sinh(real_t s)
{
return (real_t)Math.Sinh(s);
}
/// <summary>
/// Returns a number smoothly interpolated between `from` and `to`,
/// based on the `weight`. Similar to <see cref="Lerp(real_t, real_t, real_t)"/>,
/// but interpolates faster at the beginning and slower at the end.
/// </summary>
/// <param name="from">The start value for interpolation.</param>
/// <param name="to">The destination value for interpolation.</param>
/// <param name="weight">A value representing the amount of interpolation.</param>
/// <returns>The resulting value of the interpolation.</returns>
public static real_t SmoothStep(real_t from, real_t to, real_t weight)
{
if (IsEqualApprox(from, to))
{
return from;
}
real_t x = Clamp((weight - from) / (to - from), (real_t)0.0, (real_t)1.0);
return x * x * (3 - 2 * x);
}
/// <summary>
/// Returns the square root of `s`, where `s` is a non-negative number.
///
/// If you need negative inputs, use `System.Numerics.Complex`.
/// </summary>
/// <param name="s">The input number. Must not be negative.</param>
/// <returns>The square root of `s`.</returns>
public static real_t Sqrt(real_t s)
{
return (real_t)Math.Sqrt(s);
}
/// <summary>
/// Returns the position of the first non-zero digit, after the
/// decimal point. Note that the maximum return value is 10,
/// which is a design decision in the implementation.
/// </summary>
/// <param name="step">The input value.</param>
/// <returns>The position of the first non-zero digit.</returns>
public static int StepDecimals(real_t step)
{
double[] sd = new double[] {
0.9999,
0.09999,
0.009999,
0.0009999,
0.00009999,
0.000009999,
0.0000009999,
0.00000009999,
0.000000009999,
};
double abs = Mathf.Abs(step);
double decs = abs - (int)abs; // Strip away integer part
for (int i = 0; i < sd.Length; i++)
{
if (decs >= sd[i])
{
return i;
}
}
return 0;
}
/// <summary>
/// Snaps float value `s` to a given `step`.
/// This can also be used to round a floating point
/// number to an arbitrary number of decimals.
/// </summary>
/// <param name="s">The value to snap.</param>
/// <param name="step">The step size to snap to.</param>
/// <returns></returns>
public static real_t Snapped(real_t s, real_t step)
{
if (step != 0f)
{
return Floor(s / step + 0.5f) * step;
}
return s;
}
/// <summary>
/// Returns the tangent of angle `s` in radians.
/// </summary>
/// <param name="s">The angle in radians.</param>
/// <returns>The tangent of that angle.</returns>
public static real_t Tan(real_t s)
{
return (real_t)Math.Tan(s);
}
/// <summary>
/// Returns the hyperbolic tangent of angle `s` in radians.
/// </summary>
/// <param name="s">The angle in radians.</param>
/// <returns>The hyperbolic tangent of that angle.</returns>
public static real_t Tanh(real_t s)
{
return (real_t)Math.Tanh(s);
}
/// <summary>
/// Wraps `value` between `min` and `max`. Usable for creating loop-alike
/// behavior or infinite surfaces. If `min` is `0`, this is equivalent
/// to <see cref="PosMod(int, int)"/>, so prefer using that instead.
/// </summary>
/// <param name="value">The value to wrap.</param>
/// <param name="min">The minimum allowed value and lower bound of the range.</param>
/// <param name="max">The maximum allowed value and upper bound of the range.</param>
/// <returns>The wrapped value.</returns>
public static int Wrap(int value, int min, int max)
{
int range = max - min;
return range == 0 ? min : min + ((value - min) % range + range) % range;
}
/// <summary>
/// Wraps `value` between `min` and `max`. Usable for creating loop-alike
/// behavior or infinite surfaces. If `min` is `0`, this is equivalent
/// to <see cref="PosMod(real_t, real_t)"/>, so prefer using that instead.
/// </summary>
/// <param name="value">The value to wrap.</param>
/// <param name="min">The minimum allowed value and lower bound of the range.</param>
/// <param name="max">The maximum allowed value and upper bound of the range.</param>
/// <returns>The wrapped value.</returns>
public static real_t Wrap(real_t value, real_t min, real_t max)
{
real_t range = max - min;
return IsZeroApprox(range) ? min : min + ((value - min) % range + range) % range;
}
}
}
| |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using Microsoft.VisualStudio.Services.Agent.Util;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Xml.Serialization;
using System.Text;
using System.Xml;
using System.Security.Cryptography.X509Certificates;
namespace Microsoft.VisualStudio.Services.Agent.Worker.Build
{
public sealed class TFCommandManager : TfsVCCommandManager, ITfsVCCommandManager
{
public override TfsVCFeatures Features
{
get
{
return TfsVCFeatures.DefaultWorkfoldMap |
TfsVCFeatures.EscapedUrl |
TfsVCFeatures.GetFromUnmappedRoot |
TfsVCFeatures.LoginType |
TfsVCFeatures.Scorch;
}
}
// When output is redirected, TF.exe writes output using the current system code page
// (i.e. CP_ACP or code page 0). E.g. code page 1252 on an en-US box.
protected override Encoding OutputEncoding => StringUtil.GetSystemEncoding();
protected override string Switch => "/";
public override string FilePath => Path.Combine(HostContext.GetDirectory(WellKnownDirectory.Tf), "tf.exe");
private string AppConfigFile => Path.Combine(HostContext.GetDirectory(WellKnownDirectory.Tf), "tf.exe.config");
private string AppConfigRestoreFile => Path.Combine(HostContext.GetDirectory(WellKnownDirectory.Tf), "tf.exe.config.restore");
// TODO: Remove AddAsync after last-saved-checkin-metadata problem is fixed properly.
public async Task AddAsync(string localPath)
{
ArgUtil.NotNullOrEmpty(localPath, nameof(localPath));
await RunPorcelainCommandAsync(FormatFlags.OmitCollectionUrl, "vc", "add", localPath);
}
public void CleanupProxySetting()
{
ArgUtil.File(AppConfigRestoreFile, "tf.exe.config.restore");
ExecutionContext.Debug("Restore default tf.exe.config.");
IOUtil.DeleteFile(AppConfigFile);
File.Copy(AppConfigRestoreFile, AppConfigFile);
}
public Task EulaAsync()
{
throw new NotSupportedException();
}
public async Task GetAsync(string localPath)
{
ArgUtil.NotNullOrEmpty(localPath, nameof(localPath));
await RunCommandAsync(FormatFlags.OmitCollectionUrl, "vc", "get", $"/version:{SourceVersion}", "/recursive", "/overwrite", localPath);
}
public string ResolvePath(string serverPath)
{
ArgUtil.NotNullOrEmpty(serverPath, nameof(serverPath));
string localPath = RunPorcelainCommandAsync(FormatFlags.OmitCollectionUrl, "vc", "resolvePath", serverPath).GetAwaiter().GetResult();
return localPath?.Trim() ?? string.Empty;
}
// TODO: Fix scorch. Scorch blows up if a root mapping does not exist.
//
// No good workaround appears to exist. Attempting to resolve by workspace fails with
// the same error. Switching to "*" instead of passing "SourcesDirectory" allows the
// command to exit zero, but causes every source file to be deleted.
//
// The current approach taken is: allow the exception to bubble. The TfsVCSourceProvider
// will catch the exception, log it as a warning, throw away the workspace, and re-clone.
public async Task ScorchAsync() => await RunCommandAsync(FormatFlags.OmitCollectionUrl, "vc", "scorch", SourcesDirectory, "/recursive", "/diff", "/unmapped");
public void SetupProxy(string proxyUrl, string proxyUsername, string proxyPassword)
{
ArgUtil.File(AppConfigFile, "tf.exe.config");
if (!File.Exists(AppConfigRestoreFile))
{
Trace.Info("Take snapshot of current appconfig for restore modified appconfig.");
File.Copy(AppConfigFile, AppConfigRestoreFile);
}
else
{
// cleanup any appconfig changes from previous build.
CleanupProxySetting();
}
if (!string.IsNullOrEmpty(proxyUrl))
{
XmlDocument appConfig = new XmlDocument();
using (var appConfigStream = new FileStream(AppConfigFile, FileMode.Open, FileAccess.Read))
{
appConfig.Load(appConfigStream);
}
var configuration = appConfig.SelectSingleNode("configuration");
ArgUtil.NotNull(configuration, "configuration");
var exist_defaultProxy = appConfig.SelectSingleNode("configuration/system.net/defaultProxy");
if (exist_defaultProxy == null)
{
var system_net = appConfig.SelectSingleNode("configuration/system.net");
if (system_net == null)
{
Trace.Verbose("Create system.net section in appconfg.");
system_net = appConfig.CreateElement("system.net");
}
Trace.Verbose("Create defaultProxy section in appconfg.");
var defaultProxy = appConfig.CreateElement("defaultProxy");
defaultProxy.SetAttribute("useDefaultCredentials", "True");
Trace.Verbose("Create proxy section in appconfg.");
var proxy = appConfig.CreateElement("proxy");
proxy.SetAttribute("proxyaddress", proxyUrl);
defaultProxy.AppendChild(proxy);
system_net.AppendChild(defaultProxy);
configuration.AppendChild(system_net);
using (var appConfigStream = new FileStream(AppConfigFile, FileMode.Open, FileAccess.ReadWrite))
{
appConfig.Save(appConfigStream);
}
}
else
{
//proxy setting exist.
ExecutionContext.Debug("Proxy setting already exist in app.config file.");
}
// when tf.exe talk to any devfabric site, it will always bypass proxy.
// for testing, we need set this variable to let tf.exe hit the proxy server on devfabric.
if (Endpoint.Url.Host.Contains(".me.tfsallin.net") || Endpoint.Url.Host.Contains(".vsts.me"))
{
ExecutionContext.Debug("Set TFS_BYPASS_PROXY_ON_LOCAL on devfabric.");
AdditionalEnvironmentVariables["TFS_BYPASS_PROXY_ON_LOCAL"] = "0";
}
}
}
public void SetupClientCertificate(string clientCert, string clientCertKey, string clientCertArchive, string clientCertPassword)
{
ArgUtil.File(clientCert, nameof(clientCert));
X509Certificate2 cert = new X509Certificate2(clientCert);
ExecutionContext.Debug($"Set VstsClientCertificate={cert.Thumbprint} for Tf.exe to support client certificate.");
AdditionalEnvironmentVariables["VstsClientCertificate"] = cert.Thumbprint;
// Script Tf commands in tasks
ExecutionContext.SetVariable("VstsClientCertificate", cert.Thumbprint, false, false);
}
public async Task ShelveAsync(string shelveset, string commentFile, bool move)
{
ArgUtil.NotNullOrEmpty(shelveset, nameof(shelveset));
ArgUtil.NotNullOrEmpty(commentFile, nameof(commentFile));
// TODO: Remove parameter "move" after last-saved-checkin-metadata problem is fixed properly.
if (move)
{
await RunPorcelainCommandAsync(FormatFlags.OmitCollectionUrl, "vc", "shelve", "/move", "/replace", "/recursive", $"/comment:@{commentFile}", shelveset, SourcesDirectory);
return;
}
await RunPorcelainCommandAsync(FormatFlags.OmitCollectionUrl, "vc", "shelve", "/saved", "/replace", "/recursive", $"/comment:@{commentFile}", shelveset, SourcesDirectory);
}
public async Task<ITfsVCShelveset> ShelvesetsAsync(string shelveset)
{
ArgUtil.NotNullOrEmpty(shelveset, nameof(shelveset));
string xml = await RunPorcelainCommandAsync("vc", "shelvesets", "/format:xml", shelveset);
// Deserialize the XML.
// The command returns a non-zero exit code if the shelveset is not found.
// The assertions performed here should never fail.
var serializer = new XmlSerializer(typeof(TFShelvesets));
ArgUtil.NotNullOrEmpty(xml, nameof(xml));
using (var reader = new StringReader(xml))
{
var tfShelvesets = serializer.Deserialize(reader) as TFShelvesets;
ArgUtil.NotNull(tfShelvesets, nameof(tfShelvesets));
ArgUtil.NotNull(tfShelvesets.Shelvesets, nameof(tfShelvesets.Shelvesets));
ArgUtil.Equal(1, tfShelvesets.Shelvesets.Length, nameof(tfShelvesets.Shelvesets.Length));
return tfShelvesets.Shelvesets[0];
}
}
public async Task<ITfsVCStatus> StatusAsync(string localPath)
{
// It is expected that the caller only invokes this method against the sources root
// directory. The "status" subcommand cannot correctly resolve the workspace from the
// an unmapped root folder. For example, if a workspace contains only two mappings,
// $/foo -> $(build.sourcesDirectory)\foo and $/bar -> $(build.sourcesDirectory)\bar,
// then "tf status $(build.sourcesDirectory) /r" will not be able to resolve the workspace.
// Therefore, the "localPath" parameter is not actually passed to the "status" subcommand -
// the collection URL and workspace name are used instead.
ArgUtil.Equal(SourcesDirectory, localPath, nameof(localPath));
string xml = await RunPorcelainCommandAsync("vc", "status", $"/workspace:{WorkspaceName}", "/recursive", "/nodetect", "/format:xml");
var serializer = new XmlSerializer(typeof(TFStatus));
using (var reader = new StringReader(xml ?? string.Empty))
{
return serializer.Deserialize(reader) as TFStatus;
}
}
public bool TestEulaAccepted()
{
throw new NotSupportedException();
}
public async Task<bool> TryWorkspaceDeleteAsync(ITfsVCWorkspace workspace)
{
ArgUtil.NotNull(workspace, nameof(workspace));
try
{
await RunCommandAsync("vc", "workspace", "/delete", $"{workspace.Name};{workspace.Owner}");
return true;
}
catch (Exception ex)
{
ExecutionContext.Warning(ex.Message);
return false;
}
}
public async Task UndoAsync(string localPath)
{
ArgUtil.NotNullOrEmpty(localPath, nameof(localPath));
await RunCommandAsync(FormatFlags.OmitCollectionUrl, "vc", "undo", "/recursive", localPath);
}
public async Task UnshelveAsync(string shelveset)
{
ArgUtil.NotNullOrEmpty(shelveset, nameof(shelveset));
await RunCommandAsync(FormatFlags.OmitCollectionUrl, "vc", "unshelve", shelveset);
}
public async Task WorkfoldCloakAsync(string serverPath)
{
ArgUtil.NotNullOrEmpty(serverPath, nameof(serverPath));
await RunCommandAsync("vc", "workfold", "/cloak", $"/workspace:{WorkspaceName}", serverPath);
}
public async Task WorkfoldMapAsync(string serverPath, string localPath)
{
ArgUtil.NotNullOrEmpty(serverPath, nameof(serverPath));
ArgUtil.NotNullOrEmpty(localPath, nameof(localPath));
await RunCommandAsync("vc", "workfold", "/map", $"/workspace:{WorkspaceName}", serverPath, localPath);
}
public async Task WorkfoldUnmapAsync(string serverPath)
{
ArgUtil.NotNullOrEmpty(serverPath, nameof(serverPath));
await RunCommandAsync("vc", "workfold", "/unmap", $"/workspace:{WorkspaceName}", serverPath);
}
public async Task WorkspaceDeleteAsync(ITfsVCWorkspace workspace)
{
ArgUtil.NotNull(workspace, nameof(workspace));
await RunCommandAsync("vc", "workspace", "/delete", $"{workspace.Name};{workspace.Owner}");
}
public async Task WorkspaceNewAsync()
{
var useServerWorkspace = ExecutionContext.Variables.Build_UseServerWorkspaces ?? false;
ExecutionContext.Debug($"useServerWorkspace is set to : '{useServerWorkspace}'");
if (useServerWorkspace)
{
await RunCommandAsync("vc", "workspace", "/new", "/location:server", "/permission:Public", WorkspaceName);
}
else
{
await RunCommandAsync("vc", "workspace", "/new", "/location:local", "/permission:Public", WorkspaceName);
}
}
public async Task<ITfsVCWorkspace[]> WorkspacesAsync(bool matchWorkspaceNameOnAnyComputer = false)
{
// Build the args.
var args = new List<string>();
args.Add("vc");
args.Add("workspaces");
if (matchWorkspaceNameOnAnyComputer)
{
args.Add(WorkspaceName);
args.Add($"/computer:*");
}
args.Add("/format:xml");
// Run the command.
// Ignore STDERR from TF.exe, tf.exe use STDERR to report warning.
string xml = await RunPorcelainCommandAsync(true, args.ToArray()) ?? string.Empty;
// Deserialize the XML.
var serializer = new XmlSerializer(typeof(TFWorkspaces));
using (var reader = new StringReader(xml))
{
return (serializer.Deserialize(reader) as TFWorkspaces)
?.Workspaces
?.Cast<ITfsVCWorkspace>()
.ToArray();
}
}
public async Task WorkspacesRemoveAsync(ITfsVCWorkspace workspace)
{
ArgUtil.NotNull(workspace, nameof(workspace));
await RunCommandAsync("vc", "workspace", $"/remove:{workspace.Name};{workspace.Owner}");
}
}
////////////////////////////////////////////////////////////////////////////////
// tf shelvesets data objects
////////////////////////////////////////////////////////////////////////////////
[XmlRoot(ElementName = "Shelvesets", Namespace = "")]
public sealed class TFShelvesets
{
[XmlElement(ElementName = "Shelveset", Namespace = "")]
public TFShelveset[] Shelvesets { get; set; }
}
public sealed class TFShelveset : ITfsVCShelveset
{
// Attributes.
[XmlAttribute(AttributeName = "date", Namespace = "")]
public string Date { get; set; }
[XmlAttribute(AttributeName = "name", Namespace = "")]
public string Name { get; set; }
[XmlAttribute(AttributeName = "owner", Namespace = "")]
public string Owner { get; set; }
// Elements.
[XmlElement(ElementName = "Comment", Namespace = "")]
public string Comment { get; set; }
}
////////////////////////////////////////////////////////////////////////////////
// tf status data objects.
////////////////////////////////////////////////////////////////////////////////
[XmlRoot(ElementName = "Status", Namespace = "")]
public sealed class TFStatus : ITfsVCStatus
{
// Elements.
[XmlElement(ElementName = "PendingSet", Namespace = "")]
public TFPendingSet[] PendingSets { get; set; }
// Interface-only properties.
[XmlIgnore]
public IEnumerable<ITfsVCPendingChange> AllAdds
{
get
{
return PendingSets
?.SelectMany(x => x.PendingChanges ?? new TFPendingChange[0])
.Where(x => (x.ChangeType ?? string.Empty).Split(' ').Any(y => string.Equals(y, "Add", StringComparison.OrdinalIgnoreCase)));
}
}
[XmlIgnore]
public bool HasPendingChanges => PendingSets?.Any(x => x.PendingChanges?.Any() ?? false) ?? false;
}
public sealed class TFPendingSet
{
// Attributes.
[XmlAttribute(AttributeName = "computer", Namespace = "")]
public string Computer { get; set; }
[XmlAttribute(AttributeName = "name", Namespace = "")]
public string Name { get; set; }
[XmlAttribute(AttributeName = "owner", Namespace = "")]
public string Owner { get; set; }
[XmlAttribute(AttributeName = "ownerdisp", Namespace = "")]
public string OwnerDisplayName { get; set; }
[XmlAttribute(AttributeName = "ownership", Namespace = "")]
public string Ownership { get; set; }
// Elements.
[XmlArray(ElementName = "PendingChanges", Namespace = "")]
[XmlArrayItem(ElementName = "PendingChange", Namespace = "")]
public TFPendingChange[] PendingChanges { get; set; }
}
public sealed class TFPendingChange : ITfsVCPendingChange
{
// Attributes.
[XmlAttribute(AttributeName = "chg", Namespace = "")]
public string ChangeType { get; set; }
[XmlAttribute(AttributeName = "date", Namespace = "")]
public string Date { get; set; }
[XmlAttribute(AttributeName = "enc", Namespace = "")]
public string Encoding { get; set; }
[XmlAttribute(AttributeName = "hash", Namespace = "")]
public string Hash { get; set; }
[XmlAttribute(AttributeName = "item", Namespace = "")]
public string Item { get; set; }
[XmlAttribute(AttributeName = "itemid", Namespace = "")]
public string ItemId { get; set; }
[XmlAttribute(AttributeName = "local", Namespace = "")]
public string LocalItem { get; set; }
[XmlAttribute(AttributeName = "pcid", Namespace = "")]
public string PCId { get; set; }
[XmlAttribute(AttributeName = "psn", Namespace = "")]
public string Psn { get; set; }
[XmlAttribute(AttributeName = "pso", Namespace = "")]
public string Pso { get; set; }
[XmlAttribute(AttributeName = "psod", Namespace = "")]
public string Psod { get; set; }
[XmlAttribute(AttributeName = "srcitem", Namespace = "")]
public string SourceItem { get; set; }
[XmlAttribute(AttributeName = "svrfm", Namespace = "")]
public string Svrfm { get; set; }
[XmlAttribute(AttributeName = "type", Namespace = "")]
public string Type { get; set; }
[XmlAttribute(AttributeName = "uhash", Namespace = "")]
public string UHash { get; set; }
[XmlAttribute(AttributeName = "ver", Namespace = "")]
public string Version { get; set; }
}
////////////////////////////////////////////////////////////////////////////////
// tf workspaces data objects.
////////////////////////////////////////////////////////////////////////////////
[XmlRoot(ElementName = "Workspaces", Namespace = "")]
public sealed class TFWorkspaces
{
[XmlElement(ElementName = "Workspace", Namespace = "")]
public TFWorkspace[] Workspaces { get; set; }
}
public sealed class TFWorkspace : ITfsVCWorkspace
{
// Attributes.
[XmlAttribute(AttributeName = "computer", Namespace = "")]
public string Computer { get; set; }
[XmlAttribute(AttributeName = "islocal", Namespace = "")]
public string IsLocal { get; set; }
[XmlAttribute(AttributeName = "name", Namespace = "")]
public string Name { get; set; }
[XmlAttribute(AttributeName = "owner", Namespace = "")]
public string Owner { get; set; }
[XmlAttribute(AttributeName = "ownerdisp", Namespace = "")]
public string OwnerDisplayName { get; set; }
[XmlAttribute(AttributeName = "ownerid", Namespace = "")]
public string OwnerId { get; set; }
[XmlAttribute(AttributeName = "ownertype", Namespace = "")]
public string OwnerType { get; set; }
[XmlAttribute(AttributeName = "owneruniq", Namespace = "")]
public string OwnerUnique { get; set; }
// Elements.
[XmlArray(ElementName = "Folders", Namespace = "")]
[XmlArrayItem(ElementName = "WorkingFolder", Namespace = "")]
public TFMapping[] TFMappings { get; set; }
// Interface-only properties.
[XmlIgnore]
public ITfsVCMapping[] Mappings => TFMappings?.Cast<ITfsVCMapping>().ToArray();
}
public sealed class TFMapping : ITfsVCMapping
{
[XmlIgnore]
public bool Cloak => string.Equals(Type, "Cloak", StringComparison.OrdinalIgnoreCase);
[XmlAttribute(AttributeName = "depth", Namespace = "")]
public string Depth { get; set; }
[XmlAttribute(AttributeName = "local", Namespace = "")]
public string LocalPath { get; set; }
[XmlIgnore]
public bool Recursive => !string.Equals(Depth, "1", StringComparison.OrdinalIgnoreCase);
[XmlAttribute(AttributeName = "item", Namespace = "")]
public string ServerPath { get; set; }
[XmlAttribute(AttributeName = "type", Namespace = "")]
public string Type { get; set; }
}
}
| |
using Discord.Commands;
using NadekoBot.Attributes;
using NadekoBot.Extensions;
using System.Linq;
using NadekoBot.Services;
using NadekoBot.Services.Database.Models;
using System.Collections.Generic;
using System.Threading.Tasks;
using Discord;
using NLog;
using System;
using Newtonsoft.Json;
using System.IO;
using System.Collections.Concurrent;
namespace NadekoBot.Modules.Pokemon
{
[NadekoModule("Pokemon", ">")]
public class Pokemon : NadekoTopLevelModule
{
private static readonly List<PokemonType> _pokemonTypes = new List<PokemonType>();
private static readonly ConcurrentDictionary<ulong, PokeStats> _stats = new ConcurrentDictionary<ulong, PokeStats>();
public const string PokemonTypesFile = "data/pokemon_types.json";
private new static Logger _log { get; }
static Pokemon()
{
_log = LogManager.GetCurrentClassLogger();
if (File.Exists(PokemonTypesFile))
{
_pokemonTypes = JsonConvert.DeserializeObject<List<PokemonType>>(File.ReadAllText(PokemonTypesFile));
}
else
{
_log.Warn(PokemonTypesFile + " is missing. Pokemon types not loaded.");
}
}
private int GetDamage(PokemonType usertype, PokemonType targetType)
{
var rng = new Random();
var damage = rng.Next(40, 60);
foreach (var multiplierObj in usertype.Multipliers)
{
if (multiplierObj.Type != targetType.Name) continue;
damage = (int)(damage * multiplierObj.Multiplication);
}
return damage;
}
private static PokemonType GetPokeType(ulong id)
{
Dictionary<ulong, string> setTypes;
using (var uow = DbHandler.UnitOfWork())
{
setTypes = uow.PokeGame.GetAll().ToDictionary(x => x.UserId, y => y.type);
}
if (setTypes.ContainsKey(id))
{
return StringToPokemonType(setTypes[id]);
}
var count = _pokemonTypes.Count;
var remainder = Math.Abs((int)(id % (ulong)count));
return _pokemonTypes[remainder];
}
private static PokemonType StringToPokemonType(string v)
{
var str = v?.ToUpperInvariant();
var list = _pokemonTypes;
foreach (var p in list)
{
if (str == p.Name)
{
return p;
}
}
return null;
}
[NadekoCommand, Usage, Description, Aliases]
[RequireContext(ContextType.Guild)]
public async Task Attack(string move, IGuildUser targetUser = null)
{
IGuildUser user = (IGuildUser)Context.User;
if (string.IsNullOrWhiteSpace(move)) {
return;
}
if (targetUser == null)
{
await ReplyErrorLocalized("user_not_found").ConfigureAwait(false);
return;
}
if (targetUser == user)
{
await ReplyErrorLocalized("cant_attack_yourself").ConfigureAwait(false);
return;
}
// Checking stats first, then move
//Set up the userstats
var userStats = _stats.GetOrAdd(user.Id, new PokeStats());
//Check if able to move
//User not able if HP < 0, has made more than 4 attacks
if (userStats.Hp < 0)
{
await ReplyErrorLocalized("you_fainted").ConfigureAwait(false);
return;
}
if (userStats.MovesMade >= 5)
{
await ReplyErrorLocalized("too_many_moves").ConfigureAwait(false);
return;
}
if (userStats.LastAttacked.Contains(targetUser.Id))
{
await ReplyErrorLocalized("cant_attack_again").ConfigureAwait(false);
return;
}
//get target stats
var targetStats = _stats.GetOrAdd(targetUser.Id, new PokeStats());
//If target's HP is below 0, no use attacking
if (targetStats.Hp <= 0)
{
await ReplyErrorLocalized("too_many_moves", targetUser).ConfigureAwait(false);
return;
}
//Check whether move can be used
PokemonType userType = GetPokeType(user.Id);
var enabledMoves = userType.Moves;
if (!enabledMoves.Contains(move.ToLowerInvariant()))
{
await ReplyErrorLocalized("invalid_move", Format.Bold(move), Prefix).ConfigureAwait(false);
return;
}
//get target type
PokemonType targetType = GetPokeType(targetUser.Id);
//generate damage
int damage = GetDamage(userType, targetType);
//apply damage to target
targetStats.Hp -= damage;
var response = GetText("attack", Format.Bold(move), userType.Icon, Format.Bold(targetUser.ToString()), targetType.Icon, Format.Bold(damage.ToString()));
//Damage type
if (damage < 40)
{
response += "\n" + GetText("not_effective");
}
else if (damage > 60)
{
response += "\n" + GetText("super_effective");
}
else
{
response += "\n" + GetText("somewhat_effective");
}
//check fainted
if (targetStats.Hp <= 0)
{
response += "\n" + GetText("fainted", Format.Bold(targetUser.ToString()));
}
else
{
response += "\n" + GetText("hp_remaining", Format.Bold(targetUser.ToString()), targetStats.Hp);
}
//update other stats
userStats.LastAttacked.Add(targetUser.Id);
userStats.MovesMade++;
targetStats.MovesMade = 0;
if (targetStats.LastAttacked.Contains(user.Id))
{
targetStats.LastAttacked.Remove(user.Id);
}
//update dictionary
//This can stay the same right?
_stats[user.Id] = userStats;
_stats[targetUser.Id] = targetStats;
await Context.Channel.SendConfirmAsync(Context.User.Mention + " " + response).ConfigureAwait(false);
}
[NadekoCommand, Usage, Description, Aliases]
[RequireContext(ContextType.Guild)]
public async Task Movelist()
{
IGuildUser user = (IGuildUser)Context.User;
var userType = GetPokeType(user.Id);
var movesList = userType.Moves;
var embed = new EmbedBuilder().WithOkColor()
.WithTitle(GetText("moves", userType))
.WithDescription(string.Join("\n", movesList.Select(m => userType.Icon + " " + m)));
await Context.Channel.EmbedAsync(embed).ConfigureAwait(false);
}
[NadekoCommand, Usage, Description, Aliases]
[RequireContext(ContextType.Guild)]
public async Task Heal(IGuildUser targetUser = null)
{
IGuildUser user = (IGuildUser)Context.User;
if (targetUser == null)
{
await ReplyErrorLocalized("user_not_found").ConfigureAwait(false);
return;
}
if (_stats.ContainsKey(targetUser.Id))
{
var targetStats = _stats[targetUser.Id];
if (targetStats.Hp == targetStats.MaxHp)
{
await ReplyErrorLocalized("already_full", Format.Bold(targetUser.ToString())).ConfigureAwait(false);
return;
}
//Payment~
var amount = 1;
var target = (targetUser.Id == user.Id) ? "yourself" : targetUser.Mention;
if (amount > 0)
{
if (!await CurrencyHandler.RemoveCurrencyAsync(user, $"Poke-Heal {target}", amount, true).ConfigureAwait(false))
{
await ReplyErrorLocalized("no_currency", NadekoBot.BotConfig.CurrencySign).ConfigureAwait(false);
return;
}
}
//healing
targetStats.Hp = targetStats.MaxHp;
if (targetStats.Hp < 0)
{
//Could heal only for half HP?
_stats[targetUser.Id].Hp = (targetStats.MaxHp / 2);
if (target == "yourself")
{
await ReplyConfirmLocalized("revive_yourself", NadekoBot.BotConfig.CurrencySign).ConfigureAwait(false);
return;
}
await ReplyConfirmLocalized("revive_other", Format.Bold(targetUser.ToString()), NadekoBot.BotConfig.CurrencySign).ConfigureAwait(false);
}
await ReplyConfirmLocalized("healed", Format.Bold(targetUser.ToString()), NadekoBot.BotConfig.CurrencySign).ConfigureAwait(false);
}
else
{
await ErrorLocalized("already_full", Format.Bold(targetUser.ToString()));
}
}
[NadekoCommand, Usage, Description, Aliases]
[RequireContext(ContextType.Guild)]
public async Task Type(IGuildUser targetUser = null)
{
targetUser = targetUser ?? (IGuildUser)Context.User;
var pType = GetPokeType(targetUser.Id);
await ReplyConfirmLocalized("type_of_user", Format.Bold(targetUser.ToString()), pType).ConfigureAwait(false);
}
[NadekoCommand, Usage, Description, Aliases]
[RequireContext(ContextType.Guild)]
public async Task Settype([Remainder] string typeTargeted = null)
{
IGuildUser user = (IGuildUser)Context.User;
var targetType = StringToPokemonType(typeTargeted);
if (targetType == null)
{
await Context.Channel.EmbedAsync(_pokemonTypes.Aggregate(new EmbedBuilder().WithDescription("List of the available types:"),
(eb, pt) => eb.AddField(efb => efb.WithName(pt.Name)
.WithValue(pt.Icon)
.WithIsInline(true)))
.WithColor(NadekoBot.OkColor)).ConfigureAwait(false);
return;
}
if (targetType == GetPokeType(user.Id))
{
await ReplyErrorLocalized("already_that_type", targetType).ConfigureAwait(false);
return;
}
//Payment~
var amount = 1;
if (amount > 0)
{
if (!await CurrencyHandler.RemoveCurrencyAsync(user, $"{user} change type to {typeTargeted}", amount, true).ConfigureAwait(false))
{
await ReplyErrorLocalized("no_currency", NadekoBot.BotConfig.CurrencySign).ConfigureAwait(false);
return;
}
}
//Actually changing the type here
using (var uow = DbHandler.UnitOfWork())
{
var pokeUsers = uow.PokeGame.GetAll().ToArray();
var setTypes = pokeUsers.ToDictionary(x => x.UserId, y => y.type);
var pt = new UserPokeTypes
{
UserId = user.Id,
type = targetType.Name,
};
if (!setTypes.ContainsKey(user.Id))
{
//create user in db
uow.PokeGame.Add(pt);
}
else
{
//update user in db
var pokeUserCmd = pokeUsers.FirstOrDefault(p => p.UserId == user.Id);
pokeUserCmd.type = targetType.Name;
uow.PokeGame.Update(pokeUserCmd);
}
await uow.CompleteAsync();
}
//Now for the response
await ReplyConfirmLocalized("settype_success",
targetType,
NadekoBot.BotConfig.CurrencySign).ConfigureAwait(false);
}
}
}
| |
using J2N.Collections.Generic.Extensions;
using Lucene.Net.Diagnostics;
using System;
using System.Collections.Generic;
using JCG = J2N.Collections.Generic;
namespace Lucene.Net.Search
{
/*
* 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 FixedBitSet = Lucene.Net.Util.FixedBitSet;
using Similarity = Lucene.Net.Search.Similarities.Similarity;
using Term = Lucene.Net.Index.Term;
internal sealed class SloppyPhraseScorer : Scorer
{
private PhrasePositions min, max;
private float sloppyFreq; //phrase frequency in current doc as computed by phraseFreq().
private readonly Similarity.SimScorer docScorer;
private readonly int slop;
private readonly int numPostings;
private readonly PhraseQueue pq; // for advancing min position
private int end; // current largest phrase position
private bool hasRpts; // flag indicating that there are repetitions (as checked in first candidate doc)
private bool checkedRpts; // flag to only check for repetitions in first candidate doc
private bool hasMultiTermRpts;
private PhrasePositions[][] rptGroups; // in each group are PPs that repeats each other (i.e. same term), sorted by (query) offset
private PhrasePositions[] rptStack; // temporary stack for switching colliding repeating pps
private int numMatches;
private readonly long cost;
internal SloppyPhraseScorer(Weight weight, PhraseQuery.PostingsAndFreq[] postings, int slop, Similarity.SimScorer docScorer)
: base(weight)
{
this.docScorer = docScorer;
this.slop = slop;
this.numPostings = postings == null ? 0 : postings.Length;
pq = new PhraseQueue(postings.Length);
// min(cost)
cost = postings[0].postings.GetCost();
// convert tps to a list of phrase positions.
// note: phrase-position differs from term-position in that its position
// reflects the phrase offset: pp.pos = tp.pos - offset.
// this allows to easily identify a matching (exact) phrase
// when all PhrasePositions have exactly the same position.
if (postings.Length > 0)
{
min = new PhrasePositions(postings[0].postings, postings[0].position, 0, postings[0].terms);
max = min;
max.doc = -1;
for (int i = 1; i < postings.Length; i++)
{
PhrasePositions pp = new PhrasePositions(postings[i].postings, postings[i].position, i, postings[i].terms);
max.next = pp;
max = pp;
max.doc = -1;
}
max.next = min; // make it cyclic for easier manipulation
}
}
/// <summary>
/// Score a candidate doc for all slop-valid position-combinations (matches)
/// encountered while traversing/hopping the PhrasePositions.
/// <para/> The score contribution of a match depends on the distance:
/// <para/> - highest score for distance=0 (exact match).
/// <para/> - score gets lower as distance gets higher.
/// <para/>Example: for query "a b"~2, a document "x a b a y" can be scored twice:
/// once for "a b" (distance=0), and once for "b a" (distance=2).
/// <para/>Possibly not all valid combinations are encountered, because for efficiency
/// we always propagate the least PhrasePosition. This allows to base on
/// <see cref="Util.PriorityQueue{T}"/> and move forward faster.
/// As result, for example, document "a b c b a"
/// would score differently for queries "a b c"~4 and "c b a"~4, although
/// they really are equivalent.
/// Similarly, for doc "a b c b a f g", query "c b"~2
/// would get same score as "g f"~2, although "c b"~2 could be matched twice.
/// We may want to fix this in the future (currently not, for performance reasons).
/// </summary>
private float PhraseFreq()
{
if (!InitPhrasePositions())
{
return 0.0f;
}
float freq = 0.0f;
numMatches = 0;
PhrasePositions pp = pq.Pop();
int matchLength = end - pp.position;
int next = pq.Top.position;
while (AdvancePP(pp))
{
if (hasRpts && !AdvanceRpts(pp))
{
break; // pps exhausted
}
if (pp.position > next) // done minimizing current match-length
{
if (matchLength <= slop)
{
freq += docScorer.ComputeSlopFactor(matchLength); // score match
numMatches++;
}
pq.Add(pp);
pp = pq.Pop();
next = pq.Top.position;
matchLength = end - pp.position;
}
else
{
int matchLength2 = end - pp.position;
if (matchLength2 < matchLength)
{
matchLength = matchLength2;
}
}
}
if (matchLength <= slop)
{
freq += docScorer.ComputeSlopFactor(matchLength); // score match
numMatches++;
}
return freq;
}
/// <summary>
/// Advance a PhrasePosition and update 'end', return false if exhausted </summary>
private bool AdvancePP(PhrasePositions pp)
{
if (!pp.NextPosition())
{
return false;
}
if (pp.position > end)
{
end = pp.position;
}
return true;
}
/// <summary>
/// pp was just advanced. If that caused a repeater collision, resolve by advancing the lesser
/// of the two colliding pps. Note that there can only be one collision, as by the initialization
/// there were no collisions before pp was advanced.
/// </summary>
private bool AdvanceRpts(PhrasePositions pp)
{
if (pp.rptGroup < 0)
{
return true; // not a repeater
}
PhrasePositions[] rg = rptGroups[pp.rptGroup];
FixedBitSet bits = new FixedBitSet(rg.Length); // for re-queuing after collisions are resolved
int k0 = pp.rptInd;
int k;
while ((k = Collide(pp)) >= 0)
{
pp = Lesser(pp, rg[k]); // always advance the lesser of the (only) two colliding pps
if (!AdvancePP(pp))
{
return false; // exhausted
}
if (k != k0) // careful: mark only those currently in the queue
{
bits = FixedBitSet.EnsureCapacity(bits, k);
bits.Set(k); // mark that pp2 need to be re-queued
}
}
// collisions resolved, now re-queue
// empty (partially) the queue until seeing all pps advanced for resolving collisions
int n = 0;
// TODO would be good if we can avoid calling cardinality() in each iteration!
int numBits = bits.Length; // larges bit we set
while (bits.Cardinality() > 0)
{
PhrasePositions pp2 = pq.Pop();
rptStack[n++] = pp2;
if (pp2.rptGroup >= 0 && pp2.rptInd < numBits && bits.Get(pp2.rptInd)) // this bit may not have been set
{
bits.Clear(pp2.rptInd);
}
}
// add back to queue
for (int i = n - 1; i >= 0; i--)
{
pq.Add(rptStack[i]);
}
return true;
}
/// <summary>
/// Compare two pps, but only by position and offset </summary>
private PhrasePositions Lesser(PhrasePositions pp, PhrasePositions pp2)
{
if (pp.position < pp2.position || (pp.position == pp2.position && pp.offset < pp2.offset))
{
return pp;
}
return pp2;
}
/// <summary>
/// Index of a pp2 colliding with pp, or -1 if none </summary>
private int Collide(PhrasePositions pp)
{
int tpPos = TpPos(pp);
PhrasePositions[] rg = rptGroups[pp.rptGroup];
for (int i = 0; i < rg.Length; i++)
{
PhrasePositions pp2 = rg[i];
if (pp2 != pp && TpPos(pp2) == tpPos)
{
return pp2.rptInd;
}
}
return -1;
}
/// <summary>
/// Initialize <see cref="PhrasePositions"/> in place.
/// A one time initialization for this scorer (on first doc matching all terms):
/// <list type="bullet">
/// <item><description>Check if there are repetitions</description></item>
/// <item><description>If there are, find groups of repetitions.</description></item>
/// </list>
/// Examples:
/// <list type="number">
/// <item><description>no repetitions: <b>"ho my"~2</b></description></item>
/// <item><description>>repetitions: <b>"ho my my"~2</b></description></item>
/// <item><description>repetitions: <b>"my ho my"~2</b></description></item>
/// </list>
/// </summary>
/// <returns> <c>false</c> if PPs are exhausted (and so current doc will not be a match) </returns>
private bool InitPhrasePositions()
{
end = int.MinValue;
if (!checkedRpts)
{
return InitFirstTime();
}
if (!hasRpts)
{
InitSimple();
return true; // PPs available
}
return InitComplex();
}
/// <summary>
/// No repeats: simplest case, and most common. It is important to keep this piece of the code simple and efficient </summary>
private void InitSimple()
{
//System.err.println("initSimple: doc: "+min.doc);
pq.Clear();
// position pps and build queue from list
for (PhrasePositions pp = min, prev = null; prev != max; pp = (prev = pp).next) // iterate cyclic list: done once handled max
{
pp.FirstPosition();
if (pp.position > end)
{
end = pp.position;
}
pq.Add(pp);
}
}
/// <summary>
/// With repeats: not so simple. </summary>
private bool InitComplex()
{
//System.err.println("initComplex: doc: "+min.doc);
PlaceFirstPositions();
if (!AdvanceRepeatGroups())
{
return false; // PPs exhausted
}
FillQueue();
return true; // PPs available
}
/// <summary>
/// Move all PPs to their first position </summary>
private void PlaceFirstPositions()
{
for (PhrasePositions pp = min, prev = null; prev != max; pp = (prev = pp).next) // iterate cyclic list: done once handled max
{
pp.FirstPosition();
}
}
/// <summary>
/// Fill the queue (all pps are already placed) </summary>
private void FillQueue()
{
pq.Clear();
for (PhrasePositions pp = min, prev = null; prev != max; pp = (prev = pp).next) // iterate cyclic list: done once handled max
{
if (pp.position > end)
{
end = pp.position;
}
pq.Add(pp);
}
}
/// <summary>
/// At initialization (each doc), each repetition group is sorted by (query) offset.
/// this provides the start condition: no collisions.
/// <para/>Case 1: no multi-term repeats
/// <para/>
/// It is sufficient to advance each pp in the group by one less than its group index.
/// So lesser pp is not advanced, 2nd one advance once, 3rd one advanced twice, etc.
/// <para/>Case 2: multi-term repeats
/// </summary>
/// <returns> <c>false</c> if PPs are exhausted. </returns>
private bool AdvanceRepeatGroups()
{
foreach (PhrasePositions[] rg in rptGroups)
{
if (hasMultiTermRpts)
{
// more involved, some may not collide
int incr;
for (int i = 0; i < rg.Length; i += incr)
{
incr = 1;
PhrasePositions pp = rg[i];
int k;
while ((k = Collide(pp)) >= 0)
{
PhrasePositions pp2 = Lesser(pp, rg[k]);
if (!AdvancePP(pp2)) // at initialization always advance pp with higher offset
{
return false; // exhausted
}
if (pp2.rptInd < i) // should not happen?
{
incr = 0;
break;
}
}
}
}
else
{
// simpler, we know exactly how much to advance
for (int j = 1; j < rg.Length; j++)
{
for (int k = 0; k < j; k++)
{
if (!rg[j].NextPosition())
{
return false; // PPs exhausted
}
}
}
}
}
return true; // PPs available
}
/// <summary>
/// Initialize with checking for repeats. Heavy work, but done only for the first candidate doc.
/// <para/>
/// If there are repetitions, check if multi-term postings (MTP) are involved.
/// <para/>
/// Without MTP, once PPs are placed in the first candidate doc, repeats (and groups) are visible.
/// <para/>
/// With MTP, a more complex check is needed, up-front, as there may be "hidden collisions".
/// <para/>
/// For example P1 has {A,B}, P1 has {B,C}, and the first doc is: "A C B". At start, P1 would point
/// to "A", p2 to "C", and it will not be identified that P1 and P2 are repetitions of each other.
/// <para/>
/// The more complex initialization has two parts:
/// <para/>
/// (1) identification of repetition groups.
/// <para/>
/// (2) advancing repeat groups at the start of the doc.
/// <para/>
/// For (1), a possible solution is to just create a single repetition group,
/// made of all repeating pps. But this would slow down the check for collisions,
/// as all pps would need to be checked. Instead, we compute "connected regions"
/// on the bipartite graph of postings and terms.
/// </summary>
private bool InitFirstTime()
{
//System.err.println("initFirstTime: doc: "+min.doc);
checkedRpts = true;
PlaceFirstPositions();
var rptTerms = RepeatingTerms();
hasRpts = rptTerms.Count > 0;
if (hasRpts)
{
rptStack = new PhrasePositions[numPostings]; // needed with repetitions
IList<IList<PhrasePositions>> rgs = GatherRptGroups(rptTerms);
SortRptGroups(rgs);
if (!AdvanceRepeatGroups())
{
return false; // PPs exhausted
}
}
FillQueue();
return true; // PPs available
}
/// <summary>
/// Sort each repetition group by (query) offset.
/// Done only once (at first doc) and allows to initialize faster for each doc.
/// </summary>
private void SortRptGroups(IList<IList<PhrasePositions>> rgs)
{
rptGroups = new PhrasePositions[rgs.Count][];
IComparer<PhrasePositions> cmprtr = Comparer<PhrasePositions>.Create((pp1, pp2) => pp1.offset - pp2.offset);
for (int i = 0; i < rptGroups.Length; i++)
{
PhrasePositions[] rg = rgs[i].ToArray();
Array.Sort(rg, cmprtr);
rptGroups[i] = rg;
for (int j = 0; j < rg.Length; j++)
{
rg[j].rptInd = j; // we use this index for efficient re-queuing
}
}
}
/// <summary>
/// Detect repetition groups. Done once - for first doc. </summary>
private IList<IList<PhrasePositions>> GatherRptGroups(JCG.LinkedDictionary<Term, int?> rptTerms)
{
PhrasePositions[] rpp = RepeatingPPs(rptTerms);
IList<IList<PhrasePositions>> res = new List<IList<PhrasePositions>>();
if (!hasMultiTermRpts)
{
// simpler - no multi-terms - can base on positions in first doc
for (int i = 0; i < rpp.Length; i++)
{
PhrasePositions pp = rpp[i];
if (pp.rptGroup >= 0) // already marked as a repetition
{
continue;
}
int tpPos = TpPos(pp);
for (int j = i + 1; j < rpp.Length; j++)
{
PhrasePositions pp2 = rpp[j];
if (pp2.rptGroup >= 0 || pp2.offset == pp.offset || TpPos(pp2) != tpPos) // not a repetition - not a repetition: two PPs are originally in same offset in the query! - already marked as a repetition
{
continue;
}
// a repetition
int g = pp.rptGroup;
if (g < 0)
{
g = res.Count;
pp.rptGroup = g;
List<PhrasePositions> rl = new List<PhrasePositions>(2);
rl.Add(pp);
res.Add(rl);
}
pp2.rptGroup = g;
res[g].Add(pp2);
}
}
}
else
{
// more involved - has multi-terms
IList<JCG.HashSet<PhrasePositions>> tmp = new List<JCG.HashSet<PhrasePositions>>();
IList<FixedBitSet> bb = PpTermsBitSets(rpp, rptTerms);
UnionTermGroups(bb);
IDictionary<Term, int> tg = TermGroups(rptTerms, bb);
JCG.HashSet<int> distinctGroupIDs = new JCG.HashSet<int>(tg.Values);
for (int i = 0; i < distinctGroupIDs.Count; i++)
{
tmp.Add(new JCG.HashSet<PhrasePositions>());
}
foreach (PhrasePositions pp in rpp)
{
foreach (Term t in pp.terms)
{
if (rptTerms.ContainsKey(t))
{
int g = tg[t];
tmp[g].Add(pp);
if (Debugging.AssertsEnabled) Debugging.Assert(pp.rptGroup == -1 || pp.rptGroup == g);
pp.rptGroup = g;
}
}
}
foreach (JCG.HashSet<PhrasePositions> hs in tmp)
{
res.Add(new List<PhrasePositions>(hs));
}
}
return res;
}
/// <summary>
/// Actual position in doc of a PhrasePosition, relies on that position = tpPos - offset) </summary>
private int TpPos(PhrasePositions pp)
{
return pp.position + pp.offset;
}
/// <summary>
/// Find repeating terms and assign them ordinal values </summary>
private JCG.LinkedDictionary<Term, int?> RepeatingTerms()
{
JCG.LinkedDictionary<Term, int?> tord = new JCG.LinkedDictionary<Term, int?>();
Dictionary<Term, int?> tcnt = new Dictionary<Term, int?>();
for (PhrasePositions pp = min, prev = null; prev != max; pp = (prev = pp).next) // iterate cyclic list: done once handled max
{
foreach (Term t in pp.terms)
{
int? cnt0;
tcnt.TryGetValue(t, out cnt0);
int? cnt = cnt0 == null ? new int?(1) : new int?(1 + (int)cnt0);
tcnt[t] = cnt;
if (cnt == 2)
{
tord[t] = tord.Count;
}
}
}
return tord;
}
/// <summary>
/// Find repeating pps, and for each, if has multi-terms, update this.hasMultiTermRpts </summary>
private PhrasePositions[] RepeatingPPs(IDictionary<Term, int?> rptTerms)
{
List<PhrasePositions> rp = new List<PhrasePositions>();
for (PhrasePositions pp = min, prev = null; prev != max; pp = (prev = pp).next) // iterate cyclic list: done once handled max
{
foreach (Term t in pp.terms)
{
if (rptTerms.ContainsKey(t))
{
rp.Add(pp);
hasMultiTermRpts |= (pp.terms.Length > 1);
break;
}
}
}
return rp.ToArray();
}
/// <summary>
/// bit-sets - for each repeating pp, for each of its repeating terms, the term ordinal values is set </summary>
private IList<FixedBitSet> PpTermsBitSets(PhrasePositions[] rpp, IDictionary<Term, int?> tord)
{
List<FixedBitSet> bb = new List<FixedBitSet>(rpp.Length);
foreach (PhrasePositions pp in rpp)
{
FixedBitSet b = new FixedBitSet(tord.Count);
var ord = new int?();
foreach (var t in pp.terms)
{
if (tord.TryGetValue(t, out ord) && ord != null)
b.Set((int)ord);
}
bb.Add(b);
}
return bb;
}
/// <summary>
/// Union (term group) bit-sets until they are disjoint (O(n^^2)), and each group have different terms </summary>
private void UnionTermGroups(IList<FixedBitSet> bb)
{
int incr;
for (int i = 0; i < bb.Count - 1; i += incr)
{
incr = 1;
int j = i + 1;
while (j < bb.Count)
{
if (bb[i].Intersects(bb[j]))
{
bb[i].Or(bb[j]);
bb.RemoveAt(j);
incr = 0;
}
else
{
++j;
}
}
}
}
/// <summary>
/// Map each term to the single group that contains it </summary>
private IDictionary<Term, int> TermGroups(JCG.LinkedDictionary<Term, int?> tord, IList<FixedBitSet> bb)
{
Dictionary<Term, int> tg = new Dictionary<Term, int>();
Term[] t = tord.Keys.ToArray(/*new Term[0]*/);
for (int i = 0; i < bb.Count; i++) // i is the group no.
{
DocIdSetIterator bits = bb[i].GetIterator();
int ord;
while ((ord = bits.NextDoc()) != NO_MORE_DOCS)
{
tg[t[ord]] = i;
}
}
return tg;
}
public override int Freq => numMatches;
internal float SloppyFreq => sloppyFreq;
// private void printQueue(PrintStream ps, PhrasePositions ext, String title) {
// //if (min.doc != ?) return;
// ps.println();
// ps.println("---- "+title);
// ps.println("EXT: "+ext);
// PhrasePositions[] t = new PhrasePositions[pq.size()];
// if (pq.size()>0) {
// t[0] = pq.pop();
// ps.println(" " + 0 + " " + t[0]);
// for (int i=1; i<t.length; i++) {
// t[i] = pq.pop();
// assert t[i-1].position <= t[i].position;
// ps.println(" " + i + " " + t[i]);
// }
// // add them back
// for (int i=t.length-1; i>=0; i--) {
// pq.add(t[i]);
// }
// }
// }
private bool AdvanceMin(int target)
{
if (!min.SkipTo(target))
{
max.doc = NO_MORE_DOCS; // for further calls to docID()
return false;
}
min = min.next; // cyclic
max = max.next; // cyclic
return true;
}
public override int DocID => max.doc;
public override int NextDoc()
{
return Advance(max.doc + 1); // advance to the next doc after #docID()
}
public override float GetScore()
{
return docScorer.Score(max.doc, sloppyFreq);
}
public override int Advance(int target)
{
if (Debugging.AssertsEnabled) Debugging.Assert(target > DocID);
do
{
if (!AdvanceMin(target))
{
return NO_MORE_DOCS;
}
while (min.doc < max.doc)
{
if (!AdvanceMin(max.doc))
{
return NO_MORE_DOCS;
}
}
// found a doc with all of the terms
sloppyFreq = PhraseFreq(); // check for phrase
target = min.doc + 1; // next target in case sloppyFreq is still 0
} while (sloppyFreq == 0f);
// found a match
return max.doc;
}
public override long GetCost()
{
return cost;
}
public override string ToString()
{
return "scorer(" + m_weight + ")";
}
}
}
| |
using WPAppStudio.Entities.Base;
using WPAppStudio.Localization;
using WPAppStudio.Services.Interfaces;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Tasks;
using Microsoft.Xna.Framework.Media;
using Microsoft.Xna.Framework.Media.PhoneExtensions;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Windows;
using System.Windows.Resources;
namespace WPAppStudio.Services
{
/// <summary>
/// Implementation of the Share service.
/// </summary>
public class ShareService : IShareService
{
private IProximityService _proximityService;
private enum ShareTypeEnum
{
TapSend,
ShareLink,
ShareImage,
ShareStatus,
ShareByEmail
}
public const string IMAGES = "Images/";
public ShareService(IProximityService proximityService)
{
_proximityService = proximityService;
}
/// <summary>
/// Executes the Share service.
/// </summary>
/// <param name="title">The title shared.</param>
/// <param name="message">The message shared.</param>
/// <param name="link">The link shared.</param>
/// <param name="type">The image shared.</param>
public void Share(string title, string message, string link = "", string image = "")
{
var availableShareTypes = GetAvailableShareTypes(title, message, link, image);
OpenShareTypeSelector(availableShareTypes, title, message, link, image);
}
/// <summary>
/// Check if current app exist in marketplace.
/// </summary>
public bool AppExistInMarketPlace()
{
var result = false;
try
{
var link = Windows.ApplicationModel.Store.CurrentApp.LinkUri;
WebClient client = new WebClient();
client.OpenReadCompleted += (s, e) =>
{
if (e.Error == null)
{
result = true;
}
};
client.OpenReadAsync(link);
}
catch { }
return result;
}
private List<ShareTypeEnum> GetAvailableShareTypes(string title, string message, string link = "", string image = "")
{
var result = new List<ShareTypeEnum>();
if (Uri.IsWellFormedUriString(link, UriKind.Absolute)
&& _proximityService.IsProximityAvailable)
result.Add(ShareTypeEnum.TapSend);
if (!string.IsNullOrEmpty(title)
&& !string.IsNullOrEmpty(message)
&& Uri.IsWellFormedUriString(link, UriKind.Absolute))
result.Add(ShareTypeEnum.ShareLink);
if (!string.IsNullOrEmpty(image)
&& IsValidMedia(image))
result.Add(ShareTypeEnum.ShareImage);
if (!string.IsNullOrEmpty(title)
|| !string.IsNullOrEmpty(message))
result.Add(ShareTypeEnum.ShareStatus);
if (!string.IsNullOrEmpty(title)
&& !string.IsNullOrEmpty(message))
result.Add(ShareTypeEnum.ShareByEmail);
return result;
}
private void OpenShareTypeSelector(List<ShareTypeEnum> availableShareTypes, string title, string message, string link = "", string image = "")
{
var listSelector = new System.Windows.Controls.ListBox
{
ItemsSource = availableShareTypes,
ItemTemplate = App.Current.Resources["SelectorItemTemplate"] as DataTemplate
};
listSelector.SelectionChanged += (sender, e) =>
{
var selectedItem = (ShareTypeEnum)e.AddedItems[0];
switch (selectedItem)
{
case ShareTypeEnum.TapSend:
_proximityService.ShareUri(link);
break;
case ShareTypeEnum.ShareLink:
ShareLink(title, message, link);
break;
case ShareTypeEnum.ShareImage:
ShareMedia(image);
break;
case ShareTypeEnum.ShareStatus:
ShareStatus(string.IsNullOrEmpty(message) ? title : message);
break;
case ShareTypeEnum.ShareByEmail:
ShareByEmail(title, message, link);
break;
default:
break;
}
};
var customMessageBox = new CustomMessageBox
{
Message = AppResources.ShareMessage,
Content = listSelector,
IsLeftButtonEnabled = false,
IsRightButtonEnabled = false,
IsFullScreen = true
};
customMessageBox.Show();
}
/// <summary>
/// Executes the Share Link service.
/// </summary>
/// <param name="title">The title shared.</param>
/// <param name="message">The message shared.</param>
/// <param name="link">The link shared.</param>
private void ShareLink(string title, string message, string link = "")
{
title = string.IsNullOrEmpty(title) ? string.Empty : HtmlUtil.CleanHtml(title);
message = string.IsNullOrEmpty(message) ? string.Empty : HtmlUtil.CleanHtml(message);
var linkUri = string.IsNullOrEmpty(link) ? new System.Uri(AppResources.HomeUrl) : new System.Uri(link, System.UriKind.Absolute);
var shareLinkTask = new ShareLinkTask
{
Title = title,
Message = message,
LinkUri = linkUri
};
shareLinkTask.Show();
}
/// <summary>
/// Executes the Share Status service.
/// </summary>
/// <param name="status">The status to share.</param>
private void ShareStatus(string status)
{
ShareStatusTask shareStatusTask = new ShareStatusTask();
shareStatusTask.Status = status;
shareStatusTask.Show();
}
/// <summary>
/// Executes the Compose Mail service.
/// </summary>
/// <param name="subject">The message subject.</param>
/// <param name="body">The message body.</param>
/// <param name="to">The email of the recipient.</param>
private void ShareByEmail(string subject, string body, string link = "")
{
EmailComposeTask emailComposeTask = new EmailComposeTask();
emailComposeTask.Subject = subject;
if (string.IsNullOrEmpty(link))
emailComposeTask.Body = body;
else
emailComposeTask.Body = string.Format("{0}{1}{1}{2}", body, Environment.NewLine, link);
emailComposeTask.Show();
}
/// <summary>
/// Executes the Share Media service.
/// </summary>
/// <param name="media">The media to share.</param>
private void ShareMedia(string media)
{
if (media.StartsWith("http"))
DownloadToMediaLibraryAndShare(media);
else
SaveToMediaLibraryAndShare(media);
}
private bool IsValidMedia(string media)
{
return media.StartsWith("http") || GetLocalResource(media) != null;
}
private StreamResourceInfo GetLocalResource(string media)
{
var uri = new Uri(IMAGES + Path.GetFileName(media), UriKind.RelativeOrAbsolute);
return App.GetResourceStream(uri);
}
private void DownloadToMediaLibraryAndShare(string media)
{
try
{
WebClient client = new WebClient();
client.OpenReadCompleted += (s, e) =>
{
if (e.Error == null)
{
var picture = SaveToMediaLibrary(media, e.Result);
Share(picture.GetPath());
}
};
client.OpenReadAsync(new Uri(media, UriKind.Absolute));
}
catch (Exception ex)
{
Debug.WriteLine("{0} {1}", AppResources.Error, ex.ToString());
}
}
private void SaveToMediaLibraryAndShare(string media)
{
try
{
var resource = GetLocalResource(media);
if (resource != null)
{
using (var stream = resource.Stream)
{
var picture = SaveToMediaLibrary(media, stream);
Share(picture.GetPath());
}
}
}
catch (Exception ex)
{
Debug.WriteLine("{0} {1}", AppResources.Error, ex.ToString());
}
}
private Picture SaveToMediaLibrary(string media, Stream stream)
{
MediaLibrary library = new MediaLibrary();
var picture = library.SavePicture(Path.GetFileName(media), stream);
return picture;
}
private void Share(string media)
{
ShareMediaTask mediaTask = new ShareMediaTask();
mediaTask.FilePath = media;
mediaTask.Show();
}
}
}
| |
#region Copyright notice and license
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://github.com/jskeet/dotnet-protobufs/
// Original C++/Java/Python code:
// http://code.google.com/p/protobuf/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Text;
namespace Google.ProtocolBuffers.ProtoGen
{
/// <summary>
/// Tests protoc-gen-cs plugin.
/// </summary>
[TestFixture]
[Category("Preprocessor")]
public partial class ProtocGenCsUnittests
{
private static readonly string TempPath = Path.Combine(Path.GetTempPath(), "protoc-gen-cs.Test");
private const string DefaultProto =
@"
package nunit.simple;
// Test a very simple message.
message MyMessage {
optional string name = 1;
}";
#region TestFixture SetUp/TearDown
private static readonly string OriginalWorkingDirectory = Environment.CurrentDirectory;
private StringBuilder buffer = new StringBuilder();
[TestFixtureSetUp]
public virtual void Setup()
{
Teardown();
Directory.CreateDirectory(TempPath);
Environment.CurrentDirectory = TempPath;
this.buffer.Length = 0;
}
[TestFixtureTearDown]
public virtual void Teardown()
{
Environment.CurrentDirectory = OriginalWorkingDirectory;
if (Directory.Exists(TempPath))
{
Directory.Delete(TempPath, true);
}
}
#endregion
#region Helper Methods RunProtoGen / RunCsc
private void RunProtoc(int expect, string protoFile, params string[] args)
{
string protoPath = string.Format("-I. -I\"{0}\"", OriginalWorkingDirectory);
string plugin = string.Format("--plugin=\"{0}\"", Path.Combine(OriginalWorkingDirectory, "protoc-gen-cs.exe"));
string csOut = args.Length == 0 ? "--cs_out=." : string.Format("--cs_out=\"{0}:.\"", string.Join(" ", args));
// Start the child process.
Process p = new Process();
// Redirect the output stream of the child process.
p.StartInfo.CreateNoWindow = true;
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.WorkingDirectory = TempPath;
p.StartInfo.FileName = Path.Combine(OriginalWorkingDirectory, "protoc.exe");
p.StartInfo.Arguments = string.Join(" ", new string[] { plugin, csOut, protoPath, protoFile });
p.Start();
// Read the output stream first and then wait.
buffer.AppendLine(string.Format("{0}> \"{1}\" {2}", p.StartInfo.WorkingDirectory, p.StartInfo.FileName, p.StartInfo.Arguments));
buffer.AppendLine(p.StandardError.ReadToEnd());
buffer.AppendLine(p.StandardOutput.ReadToEnd());
p.WaitForExit();
Assert.AreEqual(expect, p.ExitCode, this.buffer.ToString());
}
private Assembly RunCsc(int expect, params string[] sources)
{
using (TempFile tempDll = new TempFile(String.Empty))
{
tempDll.ChangeExtension(".dll");
List<string> args = new List<string>();
args.Add("/nologo");
args.Add("/target:library");
args.Add("/debug-");
args.Add(String.Format(@"""/out:{0}""", tempDll.TempPath));
args.Add("/r:System.dll");
args.Add(String.Format(@"""/r:{0}""",
typeof(Google.ProtocolBuffers.DescriptorProtos.DescriptorProto).Assembly.
Location));
args.AddRange(sources);
string exe = Path.Combine(System.Runtime.InteropServices.RuntimeEnvironment.GetRuntimeDirectory(),
"csc.exe");
ProcessStartInfo psi = new ProcessStartInfo(exe);
psi.WorkingDirectory = TempPath;
psi.CreateNoWindow = true;
psi.UseShellExecute = false;
psi.RedirectStandardOutput = true;
psi.RedirectStandardError = true;
psi.Arguments = string.Join(" ", args.ToArray());
Process p = Process.Start(psi);
buffer.AppendLine(string.Format("{0}> \"{1}\" {2}", p.StartInfo.WorkingDirectory, p.StartInfo.FileName, p.StartInfo.Arguments));
buffer.AppendLine(p.StandardError.ReadToEnd());
buffer.AppendLine(p.StandardOutput.ReadToEnd());
p.WaitForExit();
Assert.AreEqual(expect, p.ExitCode, this.buffer.ToString());
Assembly asm = null;
if (p.ExitCode == 0)
{
byte[] allbytes = File.ReadAllBytes(tempDll.TempPath);
asm = Assembly.Load(allbytes);
foreach (Type t in asm.GetTypes())
{
Debug.WriteLine(t.FullName, asm.FullName);
}
}
return asm;
}
}
#endregion
// *******************************************************************
// The following tests excercise options for protogen.exe
// *******************************************************************
[Test]
public void TestProtoFile()
{
string test = new StackFrame(false).GetMethod().Name;
Setup();
using (TempFile source = TempFile.Attach(test + ".cs"))
using (ProtoFile proto = new ProtoFile(test + ".proto", DefaultProto))
{
RunProtoc(0, proto.TempPath);
Assembly a = RunCsc(0, source.TempPath);
//assert that the message type is in the expected namespace
Type t = a.GetType("nunit.simple.MyMessage", true, true);
Assert.IsTrue(typeof(IMessage).IsAssignableFrom(t), "Expect an IMessage");
//assert that we can find the static descriptor type
a.GetType("nunit.simple." + test, true, true);
}
}
[Test]
public void TestProtoFileWithConflictingType()
{
string test = new StackFrame(false).GetMethod().Name;
Setup();
using (TempFile source = TempFile.Attach(test + ".cs"))
using (
ProtoFile proto = new ProtoFile(test + ".proto",
@"
package nunit.simple;
// Test a very simple message.
message " +
test + @" {
optional string name = 1;
} "))
{
RunProtoc(0, proto.TempPath);
Assembly a = RunCsc(0, source.TempPath);
//assert that the message type is in the expected namespace
Type t = a.GetType("nunit.simple." + test, true, true);
Assert.IsTrue(typeof(IMessage).IsAssignableFrom(t), "Expect an IMessage");
//assert that we can find the static descriptor type
a.GetType("nunit.simple.Proto." + test, true, true);
}
}
[Test]
public void TestProtoFileWithNamespace()
{
string test = new StackFrame(false).GetMethod().Name;
Setup();
using (TempFile source = TempFile.Attach(test + ".cs"))
using (ProtoFile proto = new ProtoFile(test + ".proto", DefaultProto))
{
RunProtoc(0, proto.TempPath, "-namespace=MyNewNamespace");
Assembly a = RunCsc(0, source.TempPath);
//assert that the message type is in the expected namespace
Type t = a.GetType("MyNewNamespace.MyMessage", true, true);
Assert.IsTrue(typeof(IMessage).IsAssignableFrom(t), "Expect an IMessage");
//assert that we can find the static descriptor type
a.GetType("MyNewNamespace." + test, true, true);
}
}
[Test]
public void TestProtoFileWithUmbrellaClassName()
{
string test = new StackFrame(false).GetMethod().Name;
Setup();
using (TempFile source = TempFile.Attach("MyUmbrellaClassname.cs"))
using (ProtoFile proto = new ProtoFile(test + ".proto", DefaultProto))
{
RunProtoc(0, proto.TempPath, "/umbrella_classname=MyUmbrellaClassname");
Assembly a = RunCsc(0, source.TempPath);
//assert that the message type is in the expected namespace
Type t = a.GetType("nunit.simple.MyMessage", true, true);
Assert.IsTrue(typeof(IMessage).IsAssignableFrom(t), "Expect an IMessage");
//assert that we can find the static descriptor type
a.GetType("nunit.simple.MyUmbrellaClassname", true, true);
}
}
[Test]
public void TestProtoFileWithNestedClass()
{
string test = new StackFrame(false).GetMethod().Name;
Setup();
using (TempFile source = TempFile.Attach(test + ".cs"))
using (ProtoFile proto = new ProtoFile(test + ".proto", DefaultProto))
{
RunProtoc(0, proto.TempPath, "-nest_classes=true");
Assembly a = RunCsc(0, source.TempPath);
//assert that the message type is in the expected namespace
Type t = a.GetType("nunit.simple." + test + "+MyMessage", true, true);
Assert.IsTrue(typeof(IMessage).IsAssignableFrom(t), "Expect an IMessage");
//assert that we can find the static descriptor type
a.GetType("nunit.simple." + test, true, true);
}
}
[Test]
public void TestProtoFileWithExpandedNsDirectories()
{
string test = new StackFrame(false).GetMethod().Name;
Setup();
using (TempFile source = TempFile.Attach(@"nunit\simple\" + test + ".cs"))
using (ProtoFile proto = new ProtoFile(test + ".proto", DefaultProto))
{
RunProtoc(0, proto.TempPath, "-expand_namespace_directories=true");
Assembly a = RunCsc(0, source.TempPath);
//assert that the message type is in the expected namespace
Type t = a.GetType("nunit.simple.MyMessage", true, true);
Assert.IsTrue(typeof(IMessage).IsAssignableFrom(t), "Expect an IMessage");
//assert that we can find the static descriptor type
a.GetType("nunit.simple." + test, true, true);
}
}
[Test]
public void TestProtoFileWithNewExtension()
{
string test = new StackFrame(false).GetMethod().Name;
Setup();
using (TempFile source = TempFile.Attach(test + ".Generated.cs"))
using (ProtoFile proto = new ProtoFile(test + ".proto", DefaultProto))
{
RunProtoc(0, proto.TempPath, "-file_extension=.Generated.cs");
Assembly a = RunCsc(0, source.TempPath);
//assert that the message type is in the expected namespace
Type t = a.GetType("nunit.simple.MyMessage", true, true);
Assert.IsTrue(typeof(IMessage).IsAssignableFrom(t), "Expect an IMessage");
//assert that we can find the static descriptor type
a.GetType("nunit.simple." + test, true, true);
}
}
[Test]
public void TestProtoFileWithUmbrellaNamespace()
{
string test = new StackFrame(false).GetMethod().Name;
Setup();
using (TempFile source = TempFile.Attach(test + ".cs"))
using (ProtoFile proto = new ProtoFile(test + ".proto", DefaultProto))
{
RunProtoc(0, proto.TempPath, "-umbrella_namespace=MyUmbrella.Namespace");
Assembly a = RunCsc(0, source.TempPath);
//assert that the message type is in the expected namespace
Type t = a.GetType("nunit.simple.MyMessage", true, true);
Assert.IsTrue(typeof(IMessage).IsAssignableFrom(t), "Expect an IMessage");
//assert that we can find the static descriptor type
a.GetType("nunit.simple.MyUmbrella.Namespace." + test, true, true);
}
}
[Test]
public void TestProtoFileWithIgnoredUmbrellaNamespaceDueToNesting()
{
string test = new StackFrame(false).GetMethod().Name;
Setup();
using (TempFile source = TempFile.Attach(test + ".cs"))
using (ProtoFile proto = new ProtoFile(test + ".proto", DefaultProto))
{
RunProtoc(0, proto.TempPath, "-nest_classes=true", "-umbrella_namespace=MyUmbrella.Namespace");
Assembly a = RunCsc(0, source.TempPath);
//assert that the message type is in the expected namespace
Type t = a.GetType("nunit.simple." + test + "+MyMessage", true, true);
Assert.IsTrue(typeof(IMessage).IsAssignableFrom(t), "Expect an IMessage");
//assert that we can find the static descriptor type
a.GetType("nunit.simple." + test, true, true);
}
}
[Test]
public void TestProtoFileWithExplicitEmptyUmbrellaNamespace()
{
string test = new StackFrame(false).GetMethod().Name;
Setup();
using (TempFile source = TempFile.Attach(test + ".cs"))
using (
ProtoFile proto = new ProtoFile(test + ".proto",
@"
package nunit.simple;
// Test a very simple message.
message " +
test + @" {
optional string name = 1;
} "))
{
//Forces the umbrella class to not use a namespace even if a collision with a type is detected.
RunProtoc(0, proto.TempPath, "-umbrella_namespace=");
//error CS0441: 'nunit.simple.TestProtoFileWithExplicitEmptyUmbrellaNamespace': a class cannot be both static and sealed
RunCsc(1, source.TempPath);
}
}
[Test]
public void TestProtoFileWithNewOutputFolder()
{
string test = new StackFrame(false).GetMethod().Name;
Setup();
using (TempFile source = TempFile.Attach(@"generated-code\" + test + ".cs"))
using (ProtoFile proto = new ProtoFile(test + ".proto", DefaultProto))
{
RunProtoc(1, proto.TempPath, "-output_directory=generated-code");
Directory.CreateDirectory("generated-code");
RunProtoc(0, proto.TempPath, "-output_directory=generated-code");
Assembly a = RunCsc(0, source.TempPath);
//assert that the message type is in the expected namespace
Type t = a.GetType("nunit.simple.MyMessage", true, true);
Assert.IsTrue(typeof(IMessage).IsAssignableFrom(t), "Expect an IMessage");
//assert that we can find the static descriptor type
a.GetType("nunit.simple." + test, true, true);
}
}
[Test]
public void TestProtoFileAndIgnoreGoogleProtobuf()
{
string test = new StackFrame(false).GetMethod().Name;
Setup();
using (TempFile source = TempFile.Attach(test + ".cs"))
using (
ProtoFile proto = new ProtoFile(test + ".proto",
@"
import ""google/protobuf/csharp_options.proto"";
option (google.protobuf.csharp_file_options).namespace = ""MyNewNamespace"";
" +
DefaultProto))
{
string google = Path.Combine(TempPath, "google\\protobuf");
Directory.CreateDirectory(google);
foreach (string file in Directory.GetFiles(Path.Combine(OriginalWorkingDirectory, "google\\protobuf")))
{
File.Copy(file, Path.Combine(google, Path.GetFileName(file)));
}
Assert.AreEqual(0, Directory.GetFiles(TempPath, "*.cs").Length);
RunProtoc(0, proto.TempPath);
Assert.AreEqual(1, Directory.GetFiles(TempPath, "*.cs").Length);
Assembly a = RunCsc(0, source.TempPath);
//assert that the message type is in the expected namespace
Type t = a.GetType("MyNewNamespace.MyMessage", true, true);
Assert.IsTrue(typeof(IMessage).IsAssignableFrom(t), "Expect an IMessage");
//assert that we can find the static descriptor type
a.GetType("MyNewNamespace." + test, true, true);
}
}
[Test]
public void TestProtoFileWithoutIgnoreGoogleProtobuf()
{
string test = new StackFrame(false).GetMethod().Name;
Setup();
using (TempFile source = TempFile.Attach(test + ".cs"))
using (
ProtoFile proto = new ProtoFile(test + ".proto",
@"
import ""google/protobuf/csharp_options.proto"";
option (google.protobuf.csharp_file_options).namespace = ""MyNewNamespace"";
" +
DefaultProto))
{
string google = Path.Combine(TempPath, "google\\protobuf");
Directory.CreateDirectory(google);
foreach (string file in Directory.GetFiles(Path.Combine(OriginalWorkingDirectory, "google\\protobuf")))
{
File.Copy(file, Path.Combine(google, Path.GetFileName(file)));
}
Assert.AreEqual(0, Directory.GetFiles(TempPath, "*.cs").Length);
//Without the option this fails due to being unable to resolve google/protobuf descriptors
RunProtoc(0, proto.TempPath);
}
}
// *******************************************************************
// The following tests excercise options for protoc.exe
// *******************************************************************
[Test]
public void TestProtoFileWithIncludeImports()
{
string test = new StackFrame(false).GetMethod().Name;
Setup();
using (TempFile source = TempFile.Attach(test + ".cs"))
using (
ProtoFile proto = new ProtoFile(test + ".proto",
@"
import ""google/protobuf/csharp_options.proto"";
option (google.protobuf.csharp_file_options).namespace = ""MyNewNamespace"";
package nunit.simple;
// Test a very simple message.
message MyMessage {
optional string name = 1;
} ")
)
{
string google = Path.Combine(TempPath, "google\\protobuf");
Directory.CreateDirectory(google);
foreach (string file in Directory.GetFiles(Path.Combine(OriginalWorkingDirectory, "google\\protobuf")))
{
File.Copy(file, Path.Combine(google, Path.GetFileName(file)));
}
Assert.AreEqual(0, Directory.GetFiles(TempPath, "*.cs").Length);
//if you specify the protoc option --include_imports this should build three source files
RunProtoc(0, proto.TempPath);
Assert.AreEqual(1, Directory.GetFiles(TempPath, "*.cs").Length);
//you can (and should) simply omit the inclusion of the extra source files in your project
Assembly a = RunCsc(0, source.TempPath);
//assert that the message type is in the expected namespace
Type t = a.GetType("MyNewNamespace.MyMessage", true, true);
Assert.IsTrue(typeof(IMessage).IsAssignableFrom(t), "Expect an IMessage");
//assert that we can find the static descriptor type
a.GetType("MyNewNamespace." + test, true, true);
}
}
//Seems the --proto_path or -I option is non-functional for me. Maybe others have luck?
[Test]
public void TestProtoFileInDifferentDirectory()
{
string test = new StackFrame(false).GetMethod().Name;
Setup();
using (TempFile source = TempFile.Attach(test + ".cs"))
using (ProtoFile proto = new ProtoFile(test + ".proto", DefaultProto))
{
Environment.CurrentDirectory = OriginalWorkingDirectory;
RunProtoc(0, proto.TempPath);
Assembly a = RunCsc(0, source.TempPath);
//assert that the message type is in the expected namespace
Type t = a.GetType("nunit.simple.MyMessage", true, true);
Assert.IsTrue(typeof(IMessage).IsAssignableFrom(t), "Expect an IMessage");
//assert that we can find the static descriptor type
a.GetType("nunit.simple." + test, true, true);
}
}
// *******************************************************************
// Handling of mutliple input files
// *******************************************************************
[Test]
public void TestMultipleProtoFiles()
{
Setup();
using (TempFile source1 = TempFile.Attach("MyMessage.cs"))
using (
ProtoFile proto1 = new ProtoFile("MyMessage.proto",
@"
package nunit.simple;
// Test a very simple message.
message MyMessage {
optional string name = 1;
}")
)
using (TempFile source2 = TempFile.Attach("MyMessageList.cs"))
using (
ProtoFile proto2 = new ProtoFile("MyMessageList.proto",
@"
package nunit.simple;
import ""MyMessage.proto"";
// Test a very simple message.
message MyMessageList {
repeated MyMessage messages = 1;
}")
)
{
RunProtoc(0, proto1.TempPath);
RunProtoc(0, proto2.TempPath);
Assembly a = RunCsc(0, source1.TempPath, source2.TempPath);
//assert that the message type is in the expected namespace
Type t1 = a.GetType("nunit.simple.MyMessage", true, true);
Assert.IsTrue(typeof(IMessage).IsAssignableFrom(t1), "Expect an IMessage");
//assert that the message type is in the expected namespace
Type t2 = a.GetType("nunit.simple.MyMessageList", true, true);
Assert.IsTrue(typeof(IMessage).IsAssignableFrom(t2), "Expect an IMessage");
//assert that we can find the static descriptor type
a.GetType("nunit.simple.Proto.MyMessage", true, true);
a.GetType("nunit.simple.Proto.MyMessageList", true, true);
}
}
[Test]
public void TestOneProtoFileWithBufferFile()
{
Setup();
using (TempFile source1 = TempFile.Attach("MyMessage.cs"))
using (
ProtoFile proto1 = new ProtoFile("MyMessage.proto",
@"
package nunit.simple;
// Test a very simple message.
message MyMessage {
optional string name = 1;
}")
)
using (TempFile source2 = TempFile.Attach("MyMessageList.cs"))
using (
ProtoFile proto2 = new ProtoFile("MyMessageList.proto",
@"
package nunit.simple;
import ""MyMessage.proto"";
// Test a very simple message.
message MyMessageList {
repeated MyMessage messages = 1;
}")
)
{
//build the proto buffer for MyMessage
RunProtoc(0, proto1.TempPath);
//build the MyMessageList proto-buffer and generate code by including MyMessage.pb
RunProtoc(0, proto2.TempPath);
Assembly a = RunCsc(0, source1.TempPath, source2.TempPath);
//assert that the message type is in the expected namespace
Type t1 = a.GetType("nunit.simple.MyMessage", true, true);
Assert.IsTrue(typeof(IMessage).IsAssignableFrom(t1), "Expect an IMessage");
//assert that the message type is in the expected namespace
Type t2 = a.GetType("nunit.simple.MyMessageList", true, true);
Assert.IsTrue(typeof(IMessage).IsAssignableFrom(t2), "Expect an IMessage");
//assert that we can find the static descriptor type
a.GetType("nunit.simple.Proto.MyMessage", true, true);
a.GetType("nunit.simple.Proto.MyMessageList", true, true);
}
}
[Test]
public void TestProtoFileWithService()
{
string test = new StackFrame(false).GetMethod().Name;
Setup();
using (TempFile source = TempFile.Attach(test + ".cs"))
using (ProtoFile proto = new ProtoFile(test + ".proto",
@"
import ""google/protobuf/csharp_options.proto"";
option (google.protobuf.csharp_file_options).service_generator_type = GENERIC;
package nunit.simple;
// Test a very simple message.
message MyMessage {
optional string name = 1;
}
// test a very simple service.
service TestService {
rpc Execute (MyMessage) returns (MyMessage);
}"))
{
CopyInGoogleProtoFiles();
RunProtoc(0, proto.TempPath, "-nest_classes=false");
Assert.AreEqual(1, Directory.GetFiles(TempPath, "*.cs").Length);
Assembly a = RunCsc(0, source.TempPath);
//assert that the service type is in the expected namespace
Type t1 = a.GetType("nunit.simple.TestService", true, true);
Assert.IsTrue(typeof(IService).IsAssignableFrom(t1), "Expect an IService");
Assert.IsTrue(t1.IsAbstract, "Expect abstract class");
//assert that the Stub subclass type is in the expected namespace
Type t2 = a.GetType("nunit.simple.TestService+Stub", true, true);
Assert.IsTrue(t1.IsAssignableFrom(t2), "Expect a sub of TestService");
Assert.IsFalse(t2.IsAbstract, "Expect concrete class");
}
}
[Test]
public void TestProtoFileWithServiceInternal()
{
string test = new StackFrame(false).GetMethod().Name;
Setup();
using (TempFile source = TempFile.Attach(test + ".cs"))
using (ProtoFile proto = new ProtoFile(test + ".proto",
@"
import ""google/protobuf/csharp_options.proto"";
option (google.protobuf.csharp_file_options).service_generator_type = GENERIC;
package nunit.simple;
// Test a very simple message.
message MyMessage {
optional string name = 1;
}
// test a very simple service.
service TestService {
rpc Execute (MyMessage) returns (MyMessage);
}"))
{
CopyInGoogleProtoFiles();
RunProtoc(0, proto.TempPath, "-nest_classes=false", "-public_classes=false");
Assert.AreEqual(1, Directory.GetFiles(TempPath, "*.cs").Length);
Assembly a = RunCsc(0, source.TempPath);
//assert that the service type is in the expected namespace
Type t1 = a.GetType("nunit.simple.TestService", true, true);
Assert.IsTrue(typeof(IService).IsAssignableFrom(t1), "Expect an IService");
Assert.IsTrue(t1.IsAbstract, "Expect abstract class");
//assert that the Stub subclass type is in the expected namespace
Type t2 = a.GetType("nunit.simple.TestService+Stub", true, true);
Assert.IsTrue(t1.IsAssignableFrom(t2), "Expect a sub of TestService");
Assert.IsFalse(t2.IsAbstract, "Expect concrete class");
}
}
private static void CopyInGoogleProtoFiles()
{
string google = Path.Combine(TempPath, "google\\protobuf");
Directory.CreateDirectory(google);
foreach (string file in Directory.GetFiles(Path.Combine(OriginalWorkingDirectory, "google\\protobuf")))
{
File.Copy(file, Path.Combine(google, Path.GetFileName(file)));
}
}
}
}
| |
// Graph Engine
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE.md file in the project root for full license information.
//
using FanoutSearch.Protocols.TSL;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Trinity;
using Trinity.Diagnostics;
using Trinity.Network;
using Trinity.Storage;
using System.Runtime.Serialization;
using Trinity.Network.Messaging;
namespace FanoutSearch
{
public partial class FanoutSearchModule : FanoutSearchBase
{
/// <summary>
/// Register the query and initialize the aggregation object (the context),
/// so that it is ready for fan-out search.
/// </summary>
/// <returns>
/// true on a successful registration. It is guaranteed that the return value only depends
/// on the validity of the predicates, and the same queryMessage will have the same return
/// value on all the servers, so that we only have to check on one server for the status.
/// </returns>
private bool RegisterQuery(FanoutQueryMessage queryMessage, int transaction_id, int aggregate_server_id)
{
try
{
var obj = new AggregationObject
{
results = new List<FanoutPathDescriptor>(),
local_signals = new SemaphoreSlim(0),
aggregationServer = aggregate_server_id,
maxHop = queryMessage.maxHop,
predicates = m_compiler.CompileQueryPredicates(queryMessage.predicates),
edgeTypes = queryMessage.edge_types,
stopwatch = new Stopwatch(),
};
obj.stopwatch.Start();
m_aggregationObjects[transaction_id] = obj;
}
catch (Exception ex)
{
Log.WriteLine(LogLevel.Error, ex.ToString());
return false;
}
return true;
}
#region Handlers
public override void GetTransactionIdHandler(TransactionIdMessageWriter response)
{
response.transaction_id = Interlocked.Increment(ref m_globalTransactionId);
}
public override void QueryInitializationHandler(QueryInitializationMessageReader request)
{
Log.WriteLine(LogLevel.Debug, "Initializing query #{0}", request.transaction_id);
RegisterQuery(request.message, request.transaction_id, request.aggregate_server_id);
Log.WriteLine(LogLevel.Debug, "Finished initializing query #{0}", request.transaction_id);
}
public override void QueryUninitializationHandler(TransactionIdMessageReader request)
{
Log.WriteLine(LogLevel.Debug, "Uninitializing query #{0}", request.transaction_id);
AggregationObject aggregation_obj;
if (m_aggregationObjects.TryRemove(request.transaction_id, out aggregation_obj))
aggregation_obj.Dispose();
Log.WriteLine(LogLevel.Debug, "Finished uninitializing query #{0}", request.transaction_id);
}
/// <summary>
/// The main query handler.
/// </summary>
public override void FanoutSearchQueryHandler(FanoutQueryMessageReader request, FanoutResultMessageWriter response)
{
int my_transaction = -1;
List<ResultPathDescriptor> rpaths = null;
Stopwatch query_timer = new Stopwatch();
AggregationObject aggregation_obj = null;
bool cached = false;
int eresult = FanoutSearchErrorCode.OK;
//obtain a transaction id atomically
using (var _transaction = GetTransactionId(c_master_server_id))
{
my_transaction = _transaction.transaction_id;
}
Log.WriteLine("Transaction #{0} begins.", my_transaction);
query_timer.Start();
if (s_cache_enabled) { aggregation_obj = m_cache.GetCachedQueryResult(request); }
if (aggregation_obj != null) { cached = true; }
else { aggregation_obj = _DoFanoutSearch(my_transaction, request); }
if (aggregation_obj == null) { eresult = FanoutSearchErrorCode.Error; }
if (aggregation_obj != null && aggregation_obj.timed_out && !s_timeout_return_partial_results) { eresult = FanoutSearchErrorCode.Timeout; aggregation_obj = null; }
if (aggregation_obj != null) { rpaths = _PullSelectionsAndAssembleResults(my_transaction, request, aggregation_obj); }
else { rpaths = new List<ResultPathDescriptor>(); }
response.transaction_id = (aggregation_obj != null) ? my_transaction : eresult;
response.paths = rpaths;
if (aggregation_obj != null && s_cache_enabled && !aggregation_obj.timed_out) { m_cache.RegisterQueryResult(my_transaction, request, aggregation_obj); }
response.metadata_keys.Add("results_pulled_from_cache");
response.metadata_values.Add(cached.ToString());
s_metadataUpdateFunc(request, response);
query_timer.Stop();
Log.WriteLine("Transaction #{0} finished. Time = {1}ms.", my_transaction, query_timer.ElapsedMilliseconds);
}
private AggregationObject _DoFanoutSearch(int transaction_id, FanoutQueryMessageReader request)
{
AggregationObject aggregation_obj = null;
Stopwatch fanout_timer = new Stopwatch();
bool query_registered = false;
do
{
List<FanoutPathDescriptor> origin_path_descriptors = _GetOriginPathDescriptors(request);
fanout_timer.Start();
if (origin_path_descriptors == null)
{
aggregation_obj = null;
break;
}
// Broadcast initialization message
Parallel.For(0, Global.ServerCount, i =>
{
using (var init_msg = new QueryInitializationMessageWriter(request, transaction_id, Global.MyServerID))
{
QueryInitialization(i, init_msg);
}
});
/* From this point on, we cannot abort this query without uninitializing our peers. */
Log.WriteLine(LogLevel.Debug, "Transaction #{0} initialization synchronization complete, time = {1}ms.", transaction_id, fanout_timer.ElapsedMilliseconds);
query_registered = m_aggregationObjects.TryGetValue(transaction_id, out aggregation_obj);
if (!query_registered)
{
Log.WriteLine(LogLevel.Error, "Transaction #{0}: Query registration failed.", transaction_id);
aggregation_obj = null;
break;
}
// For 0-hop queries, we simply return what we have in origin_path_descriptors
if (request.maxHop == 0)
{
aggregation_obj.results = origin_path_descriptors;
break;
}
_SendSeedMessagesAndWaitForResults(request, transaction_id, aggregation_obj, origin_path_descriptors);
} while (false);
// Query complete. Clean it up.
if (query_registered)
{
Parallel.For(0, Global.ServerCount, i =>
{
using (var uninit_msg = new TransactionIdMessageWriter(transaction_id))
{
QueryUninitialization(i, uninit_msg);
}
});
}
fanout_timer.Stop();
Log.WriteLine("Transaction #{0} Fanout finished. Time = {1}ms.", transaction_id, fanout_timer.ElapsedMilliseconds);
return aggregation_obj;
}
private List<FanoutPathDescriptor> _GetOriginPathDescriptors(FanoutQueryMessageReader request)
{
List<FanoutPathDescriptor> origins = new List<FanoutPathDescriptor>();
if (request.originQuery.Length == 0) // no query string for origin. use the provided origin IDs.
{
origins.AddRange(request.origin.Select(_ => new FanoutPathDescriptor(_)));
Log.WriteLine(LogLevel.Debug, "FanoutSearchQueryHandler: origin = {0}", string.Join(",", request.origin));
}
else // use the query string to get origin IDs.
{
try
{
Log.WriteLine(LogLevel.Debug, "FanoutSearchQueryHandler: origin query string = {0}", request.originQuery);
JObject query_object = JObject.Parse(request.originQuery);
object match_object = query_object[JsonDSL.Match];
string type_string = (string)query_object[JsonDSL.Type];
var idx_timer = Stopwatch.StartNew();
origins.AddRange(s_indexServiceFunc(match_object, type_string).Select(_ => new FanoutPathDescriptor(_)));
idx_timer.Stop();
Log.WriteLine(LogLevel.Info, "FanoutSearchQueryHandler: starting node index query complete. Time = {0}ms.", idx_timer.ElapsedMilliseconds);
}
catch (IndexingServiceNotRegisteredException)
{
Log.WriteLine(LogLevel.Error, "FanoutSearchQueryHandler: index service not registered.");
return null;
}
catch (Exception ex)
{
Log.WriteLine(LogLevel.Error, "Failed to query index service: {0}", ex.ToString());
return null;
}
}
return origins;
}
private void _SendSeedMessagesAndWaitForResults(FanoutQueryMessageReader request, int my_transaction, AggregationObject aggregation_obj, List<FanoutPathDescriptor> origin_path_descriptors)
{
Debug.Assert(origin_path_descriptors.Count != 0);
// send the first(seed) search messages out.
var grouped_origin_path_descs = from pd in origin_path_descriptors
group pd by Global.CloudStorage.GetServerIdByCellId(pd.hop_0);
var seed_message_cnt = grouped_origin_path_descs.Count();
var wait_count_per_seed = GetWaitCount(request.maxHop);
foreach (var g in grouped_origin_path_descs)
{
MessageDispatcher.DispatchOriginMessage(g.Key, my_transaction, g);
}
var quota_stopwatch = Stopwatch.StartNew();
int minimum_nowait_result_count = MinimalRequiredResultCount(request);
if (minimum_nowait_result_count == 0) { minimum_nowait_result_count = int.MaxValue; }
long waitCount = 0;
long waitMax = seed_message_cnt * wait_count_per_seed;
for (; waitCount < waitMax; ++waitCount)
{
var time_left = s_query_time_quota - quota_stopwatch.ElapsedMilliseconds;
if (!_QueryTimeoutEnabled()) { aggregation_obj.local_signals.Wait(); }
else if (time_left > 0) { if (!aggregation_obj.local_signals.Wait((int)time_left)) break; }
else { /*time out*/ break; }
if (aggregation_obj.results.Count >= minimum_nowait_result_count)
break;
}
if (_QueryTimeoutEnabled() && quota_stopwatch.ElapsedMilliseconds >= s_query_time_quota)
{
Log.WriteLine(LogLevel.Warning, "Transaction #{0} timed out. Returning partial results. Signal: {1}/{2}", my_transaction, waitCount, waitMax);
aggregation_obj.timed_out = true;
}
}
internal static int MinimalRequiredResultCount(FanoutQueryMessageReader request)
{
int minimum_result_count;
if (request.take_count != 0)
{
minimum_result_count = request.take_count + request.skip_count;
}
else
{
minimum_result_count = 0;
}
return minimum_result_count;
}
private List<ResultPathDescriptor> _PullSelectionsAndAssembleResults(int transaction_id, FanoutQueryMessageReader request, AggregationObject aggregation_obj)
{
int result_set_capacity;
IEnumerable<FanoutPathDescriptor> result_set;
List<ResultPathDescriptor> rpaths;
Protocols.TSL.NodeDescriptor r_desc;
bool[] has_return_selections;
bool[] has_outlink_selections;
lock (aggregation_obj)
{
if (request.take_count == 0)
{
result_set_capacity = aggregation_obj.results.Count - request.skip_count;
result_set = aggregation_obj.results.Skip(request.skip_count);
}
else
{
result_set_capacity = request.take_count;
result_set = aggregation_obj.results.Skip(request.skip_count).Take(request.take_count);
}
if (result_set_capacity < 0) result_set_capacity = 0;
// Assemble result message.
rpaths = new List<ResultPathDescriptor>(capacity: result_set_capacity);
r_desc = new Protocols.TSL.NodeDescriptor(field_selections: null);
has_return_selections = request.return_selection.Select(_ => _.Count != 0).ToArray();
has_outlink_selections = request.return_selection.Select(_ => _.Contains(JsonDSL.graph_outlinks)).ToArray();
foreach (var fpath in result_set)
{
ResultPathDescriptor rpath = new ResultPathDescriptor(nodes: new List<Protocols.TSL.NodeDescriptor>());
r_desc.id = fpath.hop_0;
r_desc.field_selections = has_return_selections[0] ? new List<string>() : null;
rpath.nodes.Add(r_desc);
if (fpath.hop_1.HasValue)
{
r_desc.id = fpath.hop_1.Value;
r_desc.field_selections = has_return_selections[1] ? new List<string>() : null;
rpath.nodes.Add(r_desc);
}
if (fpath.hop_2.HasValue)
{
r_desc.id = fpath.hop_2.Value;
r_desc.field_selections = has_return_selections[2] ? new List<string>() : null;
rpath.nodes.Add(r_desc);
}
if (fpath.hop_3.HasValue)
{
r_desc.id = fpath.hop_3.Value;
r_desc.field_selections = has_return_selections[3] ? new List<string>() : null;
rpath.nodes.Add(r_desc);
}
if (fpath.hop_n != null)
{
int n = 4;
foreach (var id in fpath.hop_n)
{
r_desc.id = id;
r_desc.field_selections = has_return_selections[n] ? new List<string>() : null;
rpath.nodes.Add(r_desc);
++n;
}
}
rpaths.Add(rpath);
}
}
if (request.return_selection.Any(_ => _.Count > 0))
{
Log.WriteLine("Transaction #{0}: pulling selections.", transaction_id);
Stopwatch pull_selection_timer = Stopwatch.StartNew();
int hop_count = request.maxHop + 1;
List<List<string>> return_selections = request.return_selection.Select(s => s.Select(_ => (string)_).ToList()).ToList();
GetNodesInfoRequestWriter[,] node_info_writers = new GetNodesInfoRequestWriter[hop_count, Global.ServerCount];
GetNodesInfoResponse[,] node_info_readers = new GetNodesInfoResponse[hop_count, Global.ServerCount];
int[,] reader_idx = new int[hop_count, Global.ServerCount];
Func<long, int> hash_func = Global.CloudStorage.GetServerIdByCellId;
Parallel.For(0, hop_count, i =>
{
if (has_return_selections[i])
{
// create msg
for (int j = 0; j < Global.ServerCount; ++j)
{
node_info_writers[i, j] = new GetNodesInfoRequestWriter(fields: return_selections[i]);
if (has_outlink_selections[i])
{
node_info_writers[i, j].secondary_ids = new List<long>();
}
}
// populate msg
foreach (var rpath in rpaths)
{
if (i < rpath.nodes.Count)
{
var id = rpath.nodes[i].id;
node_info_writers[i, hash_func(id)].ids.Add(id);
if (has_outlink_selections[i])
{
long edge_dest_id = (i < rpath.nodes.Count - 1) ? rpath.nodes[i + 1].id : -1;
node_info_writers[i, hash_func(id)].secondary_ids.Add(edge_dest_id);
}
}
}
// dispatch msg
Parallel.For(0, Global.ServerCount, j =>
{
var reader = _GetNodesInfo_impl(j, node_info_writers[i, j]);
node_info_readers[i, j] = reader;
reader.Dispose();
});
// consume msg
foreach (var rpath in rpaths)
{
if (i < rpath.nodes.Count)
{
var id = rpath.nodes[i].id;
var j = hash_func(id);
var idx = reader_idx[i, j]++;
rpath.nodes[i].field_selections.AddRange(node_info_readers[i, j].infoList[idx].values);
}
}
// destruct msg
for (int j = 0; j < Global.ServerCount; ++j)
{
node_info_writers[i, j].Dispose();
}
}
});
pull_selection_timer.Stop();
Log.WriteLine("Transaction #{0}: pulling selections complete. Time = {1}ms.", transaction_id, pull_selection_timer.ElapsedMilliseconds);
}
return rpaths;
}
internal unsafe void FanoutSearch_impl_Send(int moduleId, byte* bufferPtr, int length)
{
this.SendMessage(
moduleId,
bufferPtr,
length);
}
public override void FanoutSearch_implHandler(FanoutSearchMessagePackageReader request)
{
throw new NotImplementedException("Overridden by raw handler");
}
// The original message package:
// struct FanoutSearchMessagePackage
// {
// int hop;
// int transaction_id;
// List<FanoutPathDescriptor> paths;
// }
// The binary replication:
// [header_len|msg_type|msg_id|hop(4B)|transaction(4B)|paths(array of long)]
// The # of paths can be calculated:
// (header_len-12)/8/(hop+1)
// - or -
// (AsynReqArgs.Size - 8)/8/(hop+1)
private unsafe void FanoutSearch_impl_Recv(AsynReqArgs request_args)
{
int request_size = request_args.Size;
byte* request_buffer = request_args.Buffer + request_args.Offset;
int current_hop = *(int*)(request_buffer);
int request_transaction_id = *(int*)(request_buffer + 4);
int request_path_cnt = (request_size - 2 * sizeof(int)) / (sizeof(long) * (current_hop + 1));
long* request_paths_ptr = (long*)(request_buffer + 2 * sizeof(int));
int single_path_len = current_hop + 1;
AggregationObject aggregation_obj;
//Console.WriteLine("hop: {0}", current_hop);
//Console.WriteLine("tx: {0}", request_transaction_id);
if (!m_aggregationObjects.TryGetValue(request_transaction_id, out aggregation_obj)
||
(_QueryTimeoutEnabled() && aggregation_obj.stopwatch.ElapsedMilliseconds > s_query_time_quota))
{ /* Timeout. */ return; }
var predicate = current_hop == 0 ?
p => Action.Continue :
aggregation_obj.predicates[current_hop - 1];
if (current_hop == aggregation_obj.maxHop)
{
System.Collections.Concurrent.ConcurrentBag<int> result_indices = new System.Collections.Concurrent.ConcurrentBag<int>();
Parallel.For(0, request_path_cnt, i =>
{
long cell_id = request_paths_ptr[i * single_path_len + current_hop];
try
{
Verbs.m_path_ptr = request_paths_ptr + i * single_path_len;
Verbs.m_path_len = single_path_len;
using (var cell = s_useICellFunc(cell_id))
{
if ((~predicate(cell)).HasFlag(c_action_inv_return))
result_indices.Add(i);
}
}
catch { }
});
var results = result_indices.Select(i => GetPathDescriptor(&request_paths_ptr[i * single_path_len], current_hop)).ToList();
CommitAggregationResults(request_transaction_id, aggregation_obj, results);
return;
}
var edgeType_list = aggregation_obj.edgeTypes[current_hop];
bool enumerate_all_edges = edgeType_list.Count == 0;
var negate_edge_types = new HashSet<string>(edgeType_list.Where(_ => _.FirstOrDefault() == '!').Select(_ => _.Substring(1)));
if (negate_edge_types.Count == 0)
negate_edge_types = null;
int enumerated_path_cnt = 0;
using (var dispatcher = new MessageDispatcher(current_hop + 1, request_transaction_id))
{
Lazy<List<FanoutPathDescriptor>> intermediate_result_paths = new Lazy<List<FanoutPathDescriptor>>(isThreadSafe: true);
Parallel.For(0, request_path_cnt, (i, loopstate) =>
{
long cell_id = request_paths_ptr[i * single_path_len + current_hop];
long last_id = -1;
if (current_hop > 0)
last_id = request_paths_ptr[i * single_path_len + (current_hop - 1)];
try
{
Verbs.m_path_ptr = request_paths_ptr + i * single_path_len;
Verbs.m_path_len = single_path_len;
using (var cell = s_useICellFunc(cell_id))
{
var action = ~predicate(cell);
if (action.HasFlag(c_action_inv_return))
{
var intermediate_paths = intermediate_result_paths.Value;
lock (intermediate_paths)
{
intermediate_paths.Add(GetPathDescriptor(&request_paths_ptr[i * single_path_len], current_hop));
}
}
if (action.HasFlag(c_action_inv_continue))
{
VisitNeighbors(current_hop, edgeType_list, enumerate_all_edges, negate_edge_types, dispatcher, &request_paths_ptr[i * single_path_len], last_id, cell);
}
}
}
catch { }
if (0 == (enumerated_path_cnt & 0xFF) && _QueryTimeoutEnabled() && aggregation_obj.stopwatch.ElapsedMilliseconds > s_query_time_quota)
{
loopstate.Break();
return;
}
++enumerated_path_cnt;
});//END Parallel.For
if (intermediate_result_paths.IsValueCreated)
{
using (var intermediate_results = new FanoutAggregationMessageWriter(intermediate_result_paths.Value, request_transaction_id))
{
IntermediateResult(aggregation_obj.aggregationServer, intermediate_results);
}
}
}
}
/// <summary>
/// Commit = the step before pushing the results to the aggregator
/// </summary>
private void CommitAggregationResults(int transaction_id, AggregationObject aggregation_obj, IEnumerable<FanoutPathDescriptor> results)
{
aggregation_obj.CommitAggregationResults(results);
if (aggregation_obj.aggregationServer == Global.MyServerId)
{
aggregation_obj.ReleaseLocalSignal(1);
}
else
{
aggregation_obj.SetCommitLatch(() =>
{
lock (aggregation_obj)
{
using (var result_msg = new FanoutAggregationMessageWriter(aggregation_obj.results, transaction_id, packaged_message_cnt: aggregation_obj.remote_packedMessageCount))
{
AggregateResult(aggregation_obj.aggregationServer, result_msg);
}
Console.WriteLine("Sending {0} packed messages", aggregation_obj.remote_packedMessageCount);
aggregation_obj.results.Clear();
aggregation_obj.remote_packedMessageCount = 0;
}
});
}
}
public override void AggregateResultHandler(FanoutAggregationMessageReader request)
{
AggregationObject obj;
if (m_aggregationObjects.TryGetValue(request.transaction_id, out obj))
{
obj.AddPathDescs(request);
if (request.packaged_message_cnt != 0)
obj.ReleaseLocalSignal(request.packaged_message_cnt);
else
obj.ReleaseLocalSignal(1);
}
// !if we don't get aggregate object, it means time out. we don't want
// incomplete results in our cache, so we ignore.
}
public override void IntermediateResultHandler(FanoutAggregationMessageReader request)
{
AggregationObject obj;
if (m_aggregationObjects.TryGetValue(request.transaction_id, out obj))
{
obj.AddPathDescs(request);
};
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static unsafe void VisitNeighbors(int current_hop, List<string> edgeType_list, bool enumerate_all_edges, HashSet<string> negate_edge_types, MessageDispatcher dispatcher, long* pathptr, long last_id, ICellAccessor cell)
{
if (enumerate_all_edges)
{
foreach (var neighbor_node in cell.EnumerateValues<long>("GraphEdge"))
{
if (neighbor_node != last_id)
VisitNeighbor(current_hop, dispatcher, pathptr, neighbor_node);
}
}
else if (negate_edge_types == null)
{
foreach (var edge_type in edgeType_list)
{
try
{
foreach (var neighbor_node in cell.GetField<List<long>>(edge_type))
{
if (neighbor_node != last_id)
VisitNeighbor(current_hop, dispatcher, pathptr, neighbor_node);
}
}
catch { }
}
}
else
{
foreach (var edges in cell.SelectFields<List<long>>("GraphEdge"))
{
if (negate_edge_types.Contains(edges.Key))
continue;
foreach (var neighbor_node in edges.Value)
{
if (neighbor_node != last_id)
VisitNeighbor(current_hop, dispatcher, pathptr, neighbor_node);
}
}
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static unsafe void VisitNeighbor(int current_hop, MessageDispatcher dispatcher, long* path, long neighbor_node)
{
dispatcher.addAugmentedPath(path, current_hop, neighbor_node);
}
#endregion
}
[Serializable]
internal class IndexingServiceNotRegisteredException : Exception { }
}
| |
// 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.Threading;
using Xunit;
namespace System.Linq.Parallel.Tests
{
public class AverageTests
{
//
// Average
//
// Get a set of ranges from 0 to each count, with an extra parameter containing the expected average.
public static IEnumerable<object[]> AverageData(int[] counts)
{
Func<int, double> average = x => (x - 1) / 2.0;
foreach (object[] results in UnorderedSources.Ranges(counts.Cast<int>(), average)) yield return results;
}
[Theory]
[MemberData(nameof(AverageData), new[] { 1, 2, 16 })]
public static void Average_Int(Labeled<ParallelQuery<int>> labeled, int count, double average)
{
ParallelQuery<int> query = labeled.Item;
Assert.Equal(average, query.Average());
Assert.Equal((double?)average, query.Select(x => (int?)x).Average());
Assert.Equal(-average, query.Average(x => -x));
Assert.Equal(-(double?)average, query.Average(x => -(int?)x));
}
[Theory]
[OuterLoop]
[MemberData(nameof(AverageData), new[] { 1024 * 1024, 1024 * 1024 * 4 })]
public static void Average_Int_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, double average)
{
Average_Int(labeled, count, average);
}
[Theory]
[MemberData(nameof(AverageData), new[] { 1, 2, 16 })]
public static void Average_Int_SomeNull(Labeled<ParallelQuery<int>> labeled, int count, double average)
{
ParallelQuery<int> query = labeled.Item;
Assert.Equal(Math.Truncate(average), query.Select(x => (x % 2 == 0) ? (int?)x : null).Average());
Assert.Equal(Math.Truncate(-average), query.Average(x => (x % 2 == 0) ? -(int?)x : null));
}
[Theory]
[MemberData(nameof(AverageData), new[] { 1, 2, 16 })]
public static void Average_Int_AllNull(Labeled<ParallelQuery<int>> labeled, int count, double average)
{
ParallelQuery<int> query = labeled.Item;
Assert.Null(query.Select(x => (int?)null).Average());
Assert.Null(query.Average(x => (int?)null));
}
[Theory]
[MemberData(nameof(AverageData), new[] { 1, 2, 16 })]
public static void Average_Long(Labeled<ParallelQuery<int>> labeled, int count, double average)
{
ParallelQuery<int> query = labeled.Item;
Assert.Equal(average, query.Select(x => (long)x).Average());
Assert.Equal((double?)average, query.Select(x => (long?)x).Average());
Assert.Equal(-average, query.Average(x => -(long)x));
Assert.Equal(-(double?)average, query.Average(x => -(long?)x));
}
[Theory]
[OuterLoop]
[MemberData(nameof(AverageData), new[] { 1024 * 1024, 1024 * 1024 * 4 })]
public static void Average_Long_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, double average)
{
Average_Long(labeled, count, average);
}
[Theory]
[MemberData(nameof(UnorderedSources.Ranges), new[] { 2 }, MemberType = typeof(UnorderedSources))]
public static void Average_Long_Overflow(Labeled<ParallelQuery<int>> labeled, int count)
{
Functions.AssertThrowsWrapped<OverflowException>(() => labeled.Item.Select(x => x == 0 ? 1 : long.MaxValue).Average());
Functions.AssertThrowsWrapped<OverflowException>(() => labeled.Item.Select(x => x == 0 ? (long?)1 : long.MaxValue).Average());
Functions.AssertThrowsWrapped<OverflowException>(() => labeled.Item.Average(x => x == 0 ? -1 : long.MinValue));
Functions.AssertThrowsWrapped<OverflowException>(() => labeled.Item.Average(x => x == 0 ? (long?)-1 : long.MinValue));
}
[Theory]
[MemberData(nameof(AverageData), new[] { 1, 2, 16 })]
public static void Average_Long_SomeNull(Labeled<ParallelQuery<int>> labeled, int count, double average)
{
ParallelQuery<int> query = labeled.Item;
Assert.Equal(Math.Truncate(average), query.Select(x => (x % 2 == 0) ? (long?)x : null).Average());
Assert.Equal(Math.Truncate(-average), query.Average(x => (x % 2 == 0) ? -(long?)x : null));
}
[Theory]
[MemberData(nameof(AverageData), new[] { 1, 2, 16 })]
public static void Average_Long_AllNull(Labeled<ParallelQuery<int>> labeled, int count, double average)
{
ParallelQuery<int> query = labeled.Item;
Assert.Null(query.Select(x => (long?)null).Average());
Assert.Null(query.Average(x => (long?)null));
}
[Theory]
[MemberData(nameof(AverageData), new[] { 1, 2, 16 })]
public static void Average_Float(Labeled<ParallelQuery<int>> labeled, int count, float average)
{
ParallelQuery<int> query = labeled.Item;
Assert.Equal(average, query.Select(x => (float)x).Average());
Assert.Equal((float?)average, query.Select(x => (float?)x).Average());
Assert.Equal(-average, query.Average(x => -(float)x));
Assert.Equal(-(float?)average, query.Average(x => -(float?)x));
}
[Theory]
[OuterLoop]
[MemberData(nameof(AverageData), new[] { 1024 * 1024, 1024 * 1024 * 4 })]
public static void Average_Float_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, float average)
{
Average_Float(labeled, count, average);
}
[Theory]
[MemberData(nameof(AverageData), new[] { 1, 2, 16 })]
public static void Average_Float_SomeNull(Labeled<ParallelQuery<int>> labeled, int count, float average)
{
ParallelQuery<int> query = labeled.Item;
Assert.Equal((float?)Math.Truncate(average), query.Select(x => (x % 2 == 0) ? (float?)x : null).Average());
Assert.Equal((float?)Math.Truncate(-average), query.Average(x => (x % 2 == 0) ? -(float?)x : null));
}
[Theory]
[MemberData(nameof(AverageData), new[] { 1, 2, 16 })]
public static void Average_Float_AllNull(Labeled<ParallelQuery<int>> labeled, int count, float average)
{
ParallelQuery<int> query = labeled.Item;
Assert.Null(query.Select(x => (float?)null).Average());
Assert.Null(query.Average(x => (float?)null));
}
[Theory]
[MemberData(nameof(AverageData), new[] { 1, 2, 16 })]
public static void Average_Double(Labeled<ParallelQuery<int>> labeled, int count, double average)
{
ParallelQuery<int> query = labeled.Item;
Assert.Equal(average, query.Select(x => (double)x).Average());
Assert.Equal((double?)average, query.Select(x => (double?)x).Average());
Assert.Equal(-average, query.Average(x => -(double)x));
Assert.Equal(-(double?)average, query.Average(x => -(double?)x));
}
[Theory]
[OuterLoop]
[MemberData(nameof(AverageData), new[] { 1024 * 1024, 1024 * 1024 * 4 })]
public static void Average_Double_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, double average)
{
Average_Double(labeled, count, average);
}
[Theory]
[MemberData(nameof(AverageData), new[] { 1, 2, 16 })]
public static void Average_Double_SomeNull(Labeled<ParallelQuery<int>> labeled, int count, double average)
{
ParallelQuery<int> query = labeled.Item;
Assert.Equal(Math.Truncate(average), query.Select(x => (x % 2 == 0) ? (double?)x : null).Average());
Assert.Equal(Math.Truncate(-average), query.Average(x => (x % 2 == 0) ? -(double?)x : null));
}
[Theory]
[MemberData(nameof(AverageData), new[] { 1, 2, 16 })]
public static void Average_Double_AllNull(Labeled<ParallelQuery<int>> labeled, int count, double average)
{
ParallelQuery<int> query = labeled.Item;
Assert.Null(query.Select(x => (double?)null).Average());
Assert.Null(query.Average(x => (double?)null));
}
[Theory]
[MemberData(nameof(AverageData), new[] { 1, 2, 16 })]
public static void Average_Decimal(Labeled<ParallelQuery<int>> labeled, int count, decimal average)
{
ParallelQuery<int> query = labeled.Item;
Assert.Equal(average, query.Select(x => (decimal)x).Average());
Assert.Equal((decimal?)average, query.Select(x => (decimal?)x).Average());
Assert.Equal(-average, query.Average(x => -(decimal)x));
Assert.Equal(-(decimal?)average, query.Average(x => -(decimal?)x));
}
[Theory]
[OuterLoop]
[MemberData(nameof(AverageData), new[] { 1024 * 1024, 1024 * 1024 * 4 })]
public static void Average_Decimal_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, decimal average)
{
Average_Decimal(labeled, count, average);
}
[Theory]
[MemberData(nameof(AverageData), new[] { 1, 2, 16 })]
public static void Average_Decimal_SomeNull(Labeled<ParallelQuery<int>> labeled, int count, decimal average)
{
ParallelQuery<int> query = labeled.Item;
Assert.Equal(Math.Truncate(average), query.Select(x => (x % 2 == 0) ? (decimal?)x : null).Average());
Assert.Equal(Math.Truncate(-average), query.Average(x => (x % 2 == 0) ? -(decimal?)x : null));
}
[Theory]
[MemberData(nameof(AverageData), new[] { 1, 2, 16 })]
public static void Average_Decimal_AllNull(Labeled<ParallelQuery<int>> labeled, int count, decimal average)
{
ParallelQuery<int> query = labeled.Item;
Assert.Null(query.Select(x => (decimal?)null).Average());
Assert.Null(query.Average(x => (decimal?)null));
}
[Fact]
public static void Average_InvalidOperationException()
{
Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Empty<int>().Average());
Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Empty<int>().Average(x => x));
Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Empty<long>().Average());
Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Empty<long>().Average(x => x));
Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Empty<float>().Average());
Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Empty<float>().Average(x => x));
Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Empty<double>().Average());
Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Empty<double>().Average(x => x));
Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Empty<decimal>().Average());
Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Empty<decimal>().Average(x => x));
// Nullables return null when empty
Assert.Null(ParallelEnumerable.Empty<int?>().Average());
Assert.Null(ParallelEnumerable.Empty<int?>().Average(x => x));
Assert.Null(ParallelEnumerable.Empty<long?>().Average());
Assert.Null(ParallelEnumerable.Empty<long?>().Average(x => x));
Assert.Null(ParallelEnumerable.Empty<float?>().Average());
Assert.Null(ParallelEnumerable.Empty<float?>().Average(x => x));
Assert.Null(ParallelEnumerable.Empty<double?>().Average());
Assert.Null(ParallelEnumerable.Empty<double?>().Average(x => x));
Assert.Null(ParallelEnumerable.Empty<decimal?>().Average());
Assert.Null(ParallelEnumerable.Empty<decimal?>().Average(x => x));
}
[Theory]
[MemberData(nameof(UnorderedSources.Ranges), new[] { 1 }, MemberType = typeof(UnorderedSources))]
public static void Average_OperationCanceledException_PreCanceled(Labeled<ParallelQuery<int>> labeled, int count)
{
CancellationTokenSource cs = new CancellationTokenSource();
cs.Cancel();
Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Average(x => x));
Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Average(x => (int?)x));
Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Average(x => (long)x));
Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Average(x => (long?)x));
Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Average(x => (float)x));
Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Average(x => (float?)x));
Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Average(x => (double)x));
Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Average(x => (double?)x));
Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Average(x => (decimal)x));
Functions.AssertIsCanceled(cs, () => labeled.Item.WithCancellation(cs.Token).Average(x => (decimal?)x));
}
[Theory]
[MemberData(nameof(UnorderedSources.Ranges), new[] { 1 }, MemberType = typeof(UnorderedSources))]
public static void Average_AggregateException(Labeled<ParallelQuery<int>> labeled, int count)
{
Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Average((Func<int, int>)(x => { throw new DeliberateTestException(); })));
Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Average((Func<int, int?>)(x => { throw new DeliberateTestException(); })));
Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Average((Func<int, long>)(x => { throw new DeliberateTestException(); })));
Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Average((Func<int, long?>)(x => { throw new DeliberateTestException(); })));
Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Average((Func<int, float>)(x => { throw new DeliberateTestException(); })));
Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Average((Func<int, float?>)(x => { throw new DeliberateTestException(); })));
Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Average((Func<int, double>)(x => { throw new DeliberateTestException(); })));
Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Average((Func<int, double?>)(x => { throw new DeliberateTestException(); })));
Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Average((Func<int, decimal>)(x => { throw new DeliberateTestException(); })));
Functions.AssertThrowsWrapped<DeliberateTestException>(() => labeled.Item.Average((Func<int, decimal?>)(x => { throw new DeliberateTestException(); })));
}
[Fact]
public static void Average_ArgumentNullException()
{
Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<int>)null).Average());
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Repeat(0, 1).Average((Func<int, int>)null));
Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<int?>)null).Average());
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Repeat((int?)0, 1).Average((Func<int?, int?>)null));
Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<long>)null).Average());
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Repeat((long)0, 1).Average((Func<long, long>)null));
Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<long?>)null).Average());
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Repeat((long?)0, 1).Average((Func<long?, long?>)null));
Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<float>)null).Average());
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Repeat((float)0, 1).Average((Func<float, float>)null));
Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<float?>)null).Average());
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Repeat((float?)0, 1).Average((Func<float?, float?>)null));
Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<double>)null).Average());
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Repeat((double)0, 1).Average((Func<double, double>)null));
Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<double?>)null).Average());
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Repeat((double?)0, 1).Average((Func<double?, double?>)null));
Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<decimal>)null).Average());
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Repeat((decimal)0, 1).Average((Func<decimal, decimal>)null));
Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<decimal?>)null).Average());
Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Repeat((decimal?)0, 1).Average((Func<decimal?, decimal?>)null));
}
}
}
| |
using System;
using System.Collections;
using System.Text;
namespace HttpServer.Helpers
{
/// <summary>
/// Helpers making it easier to work with forms.
/// </summary>
/// <seealso cref="ObjectForm"/>
public static class FormHelper
{
/// <summary>
/// Used to let the website use different JavaScript libraries.
/// Default is <see cref="Implementations.PrototypeImp"/>
/// </summary>
public static JavascriptHelperImplementation JSImplementation = WebHelper.JSImplementation;
/// <summary>
/// Create a <form> tag.
/// </summary>
/// <param name="id">name of form</param>
/// <param name="action">action to invoke on submit</param>
/// <param name="isAjax">form should be posted as Ajax</param>
/// <returns>HTML code</returns>
/// <example>
/// <code>
/// // without options
/// WebHelper.FormStart("frmLogin", "/user/login", Request.IsAjax);
///
/// // with options
/// WebHelper.FormStart("frmLogin", "/user/login", Request.IsAjax, "style", "display:inline", "class", "greenForm");
/// </code>
/// </example>
/// <param name="options">HTML attributes or JavaScript options.</param>
/// <remarks>Method will ALWAYS be POST.</remarks>
/// <exception cref="ArgumentException">options must consist of name, value, name, value</exception>
public static string Start(string id, string action, bool isAjax, params string[] options)
{
Check.Require(id, "id");
Check.NotEmpty(action, "action");
if (options == null || options.Length % 2 != 0)
throw new ArgumentException("options must consist of name, value, name, value");
StringBuilder sb = new StringBuilder();
sb.Append("<form action=\"");
sb.Append(action);
sb.Append("\"");
if (isAjax)
{
string onsubmit = JSImplementation.AjaxFormOnSubmit(options) + "return false;";
WebHelper.GenerateHtmlAttributes(sb, options, new[]{"onsubmit", onsubmit, "id", id, "method", "post"});
}
else
WebHelper.GenerateHtmlAttributes(sb, options, new[]{"id", id, "method", "post"});
sb.Append(">");
return sb.ToString();
}
/// <summary>
/// Creates a select list with the values in a collection.
/// </summary>
/// <param name="name">Name of the SELECT-tag</param>
/// <param name="collection">collection used to generate options.</param>
/// <param name="getIdTitle">delegate used to return id and title from objects.</param>
/// <param name="selectedValue">value that should be marked as selected.</param>
/// <param name="firstEmpty">First row should contain an empty value.</param>
/// <returns>string containing a SELECT-tag.</returns>
/// <seealso cref="GetIdTitle"/>
public static string Select(string name, IEnumerable collection, GetIdTitle getIdTitle, object selectedValue, bool firstEmpty)
{
return Select(name, name, collection, getIdTitle, selectedValue, firstEmpty);
}
/// <summary>
/// Creates a select list with the values in a collection.
/// </summary>
/// <param name="name">Name of the SELECT-tag</param>
/// <param name="id">Id of the SELECT-tag</param>
/// <param name="collection">collection used to generate options.</param>
/// <param name="getIdTitle">delegate used to return id and title from objects.</param>
/// <param name="selectedValue">value that should be marked as selected.</param>
/// <param name="firstEmpty">First row should contain an empty value.</param>
/// <returns>string containing a SELECT-tag.</returns>
/// <seealso cref="GetIdTitle"/>
/// <example>
/// <code>
/// // Class that is going to be used in a SELECT-tag.
/// public class User
/// {
/// private readonly string _realName;
/// private readonly int _id;
/// public User(int id, string realName)
/// {
/// _id = id;
/// _realName = realName;
/// }
/// public string RealName
/// {
/// get { return _realName; }
/// }
///
/// public int Id
/// {
/// get { return _id; }
/// }
/// }
///
/// // Using an inline delegate to generate the select list
/// public void UserInlineDelegate()
/// {
/// List<User> items = new List<User>();
/// items.Add(new User(1, "adam"));
/// items.Add(new User(2, "bertial"));
/// items.Add(new User(3, "david"));
/// string htmlSelect = Select("users", "users", items, delegate(object o, out object id, out object value)
/// {
/// User user = (User)o;
/// id = user.Id;
/// value = user.RealName;
/// }, 2, true);
/// }
///
/// // Using an method as delegate to generate the select list.
/// public void UseExternalDelegate()
/// {
/// List<User> items = new List<User>();
/// items.Add(new User(1, "adam"));
/// items.Add(new User(2, "bertial"));
/// items.Add(new User(3, "david"));
/// string htmlSelect = Select("users", "users", items, UserOptions, 1, true);
/// }
///
/// // delegate returning id and title
/// public static void UserOptions(object o, out object id, out object title)
/// {
/// User user = (User)o;
/// id = user.Id;
/// value = user.RealName;
/// }
/// </code>
/// </example>
/// <exception cref="ArgumentNullException"><c>name</c>, <c>id</c>, <c>collection</c> or <c>getIdTitle</c> is null.</exception>
public static string Select(string name, string id, IEnumerable collection, GetIdTitle getIdTitle, object selectedValue, bool firstEmpty)
{
if (name == null)
throw new ArgumentNullException("name");
if (id == null)
throw new ArgumentNullException("id");
if (collection == null)
throw new ArgumentNullException("collection");
if (getIdTitle == null)
throw new ArgumentNullException("getIdTitle");
StringBuilder sb = new StringBuilder();
sb.AppendLine("<select name=\"" + name + "\" id=\"" + id + "\">");
Options(sb, collection, getIdTitle, selectedValue, firstEmpty);
sb.AppendLine("</select>");
return sb.ToString();
}
/// <summary>
/// Creates a select list with the values in a collection.
/// </summary>
/// <param name="name">Name of the SELECT-tag</param>
/// <param name="id">Id of the SELECT-tag</param>
/// <param name="collection">collection used to generate options.</param>
/// <param name="getIdTitle">delegate used to return id and title from objects.</param>
/// <param name="selectedValue">value that should be marked as selected.</param>
/// <param name="firstEmpty">First row should contain an empty value.</param>
/// <param name="htmlAttributes">name, value collection of extra HTML attributes.</param>
/// <returns>string containing a SELECT-tag.</returns>
/// <seealso cref="GetIdTitle"/>
/// <exception cref="ArgumentNullException"><c>name</c>, <c>id</c>, <c>collection</c> or <c>getIdTitle</c> is null.</exception>
/// <exception cref="ArgumentException">Invalid HTML attribute list.</exception>
public static string Select(string name, string id, IEnumerable collection, GetIdTitle getIdTitle, object selectedValue, bool firstEmpty, params string[] htmlAttributes)
{
if (name == null)
throw new ArgumentNullException("name");
if (id == null)
throw new ArgumentNullException("id");
if (collection == null)
throw new ArgumentNullException("collection");
if (getIdTitle == null)
throw new ArgumentNullException("getIdTitle");
if (htmlAttributes != null && (htmlAttributes.Length % 2) != 0)
throw new ArgumentException("Invalid HTML attribute list.");
StringBuilder sb = new StringBuilder();
sb.Append("<select name=\"" + name + "\" id=\"" + id + "\"");
WebHelper.GenerateHtmlAttributes(sb, htmlAttributes);
sb.AppendLine(">");
Options(sb, collection, getIdTitle, selectedValue, firstEmpty);
sb.AppendLine("</select>");
return sb.ToString();
}
/// <summary>
/// Generate a list of HTML options
/// </summary>
/// <param name="collection">collection used to generate options.</param>
/// <param name="getIdTitle">delegate used to return id and title from objects.</param>
/// <param name="selectedValue">value that should be marked as selected.</param>
/// <param name="firstEmpty">First row should contain an empty value.</param>
/// <returns></returns>
/// <exception cref="ArgumentNullException"><c>collection</c> or <c>getIdTitle</c> is null.</exception>
public static string Options(IEnumerable collection, GetIdTitle getIdTitle, object selectedValue, bool firstEmpty)
{
if (collection == null)
throw new ArgumentNullException("collection");
if (getIdTitle == null)
throw new ArgumentNullException("getIdTitle");
StringBuilder sb = new StringBuilder();
Options(sb, collection, getIdTitle, selectedValue, firstEmpty);
return sb.ToString();
}
/// <exception cref="ArgumentNullException"><c>sb</c> is null.</exception>
private static void Options(StringBuilder sb, IEnumerable collection, GetIdTitle getIdTitle, object selectedValue, bool firstEmpty)
{
if (sb == null)
throw new ArgumentNullException("sb");
if (collection == null)
throw new ArgumentNullException("collection");
if (getIdTitle == null)
throw new ArgumentNullException("getIdTitle");
if (firstEmpty)
sb.AppendLine("<option value=\"\"> </option>");
foreach (object o in collection)
{
object value;
string title;
getIdTitle(o, out value, out title);
sb.Append("<option value=\"");
if (value != null)
sb.Append(value);
sb.Append("\"");
if (value != null && selectedValue != null && value.Equals(selectedValue))
sb.Append(" selected=\"selected\"");
sb.Append(">");
if (title == null)
sb.AppendLine(" </option>");
else
{
sb.Append(title);
sb.AppendLine("</option>");
}
}
}
/// <summary>
/// Creates a check box.
/// </summary>
/// <param name="name">element name</param>
/// <param name="value">element value</param>
/// <param name="isChecked">determines if the check box is selected or not. This is done differently depending on the
/// type of variable. A boolean simply triggers checked or not, all other types are compared with "value" to determine if
/// the box is checked or not. </param>
/// <param name="htmlAttributes">a list with additional attributes (name, value, name, value).</param>
/// <returns>a generated radio button</returns>
public static string CheckBox(string name, object value, object isChecked, params string[] htmlAttributes)
{
return CheckBox(name, null, value, isChecked, htmlAttributes);
}
/// <summary>
/// Creates a check box.
/// </summary>
/// <param name="name">element name</param>
/// <param name="id">element id</param>
/// <param name="value">element value</param>
/// <param name="isChecked">determines if the check box is selected or not. This is done differently depending on the
/// type of variable. A boolean simply triggers checked or not, all other types are compared with "value" to determine if
/// the box is checked or not. </param>
/// <param name="htmlAttributes">a list with additional attributes (name, value, name, value).</param>
/// <returns>a generated radio button</returns>
/// <remarks>
/// value in your business object. (check box will be selected if it matches the element value)
/// </remarks>
public static string CheckBox(string name, string id, object value, object isChecked, params string[] htmlAttributes)
{
StringBuilder sb = new StringBuilder();
sb.Append("<input type=\"checkbox\" name=\"");
sb.Append(name);
sb.Append("\"");
if (id != null)
{
sb.Append(" id=\"");
sb.Append(id);
sb.Append("\"");
}
sb.Append(" value=\"");
sb.Append(value);
sb.Append("\"");
if (isChecked is bool && (bool)isChecked)
sb.Append("checked=\"checked\"");
else if (isChecked == value)
sb.Append("checked=\"checked\"");
WebHelper.GenerateHtmlAttributes(sb, htmlAttributes);
sb.Append("/>");
return sb.ToString();
}
/// <summary>
/// Creates a check box.
/// </summary>
/// <param name="name">element name</param>
/// <param name="id">element id</param>
/// <param name="isChecked">determines if the check box is selected or not. This is done differently depending on the
/// type of variable. A boolean simply triggers checked or not, all other types are compared with "value" to determine if
/// the box is checked or not. </param>
/// <param name="htmlAttributes">a list with additional attributes (name, value, name, value).</param>
/// <returns>a generated radio button</returns>
/// <remarks>will set value to "1".</remarks>
public static string CheckBox(string name, string id, object isChecked, params string[] htmlAttributes)
{
return CheckBox(name, id, 1, isChecked, htmlAttributes);
}
/// <summary>
/// Creates a RadioButton.
/// </summary>
/// <param name="name">element name</param>
/// <param name="value">element value</param>
/// <param name="isSelected">determines if the radio button is selected or not. This is done differently depending on the
/// type of variable. A boolean simply triggers checked or not, all other types are compared with "value" to determine if
/// the box is checked or not. </param>
/// <param name="htmlAttributes">a list with additional attributes (name, value, name, value).</param>
/// <returns>a generated radio button</returns>
public static string RadioButton(string name, object value, object isSelected, params string[] htmlAttributes)
{
return RadioButton(name, null, value, isSelected, htmlAttributes);
}
/// <summary>
/// Creates a RadioButton.
/// </summary>
/// <param name="name">element name</param>
/// <param name="id">element id</param>
/// <param name="value">element value</param>
/// <param name="isSelected">determines if the radio button is selected or not. This is done differently depending on the
/// type of variable. A boolean simply triggers checked or not, all other types are compared with "value" to determine if
/// the box is checked or not. </param>
/// <param name="htmlAttributes">a list with additional attributes (name, value, name, value).</param>
/// <returns>a generated radio button</returns>
public static string RadioButton(string name, string id, object value, object isSelected, params string[] htmlAttributes)
{
StringBuilder sb = new StringBuilder();
sb.Append("<input type=\"radio\" name=\"");
sb.Append(name);
sb.Append("\"");
if (id != null)
{
sb.Append(" id=\"");
sb.Append(id);
sb.Append("\"");
}
sb.Append(" value=\"");
sb.Append(value);
sb.Append("\"");
if (isSelected is bool && (bool)isSelected)
sb.Append("checked=\"checked\"");
else if (isSelected.Equals(value))
sb.Append("checked=\"checked\"");
WebHelper.GenerateHtmlAttributes(sb, htmlAttributes);
sb.Append("/>");
return sb.ToString();
}
/// <summary>
/// form close tag
/// </summary>
/// <returns></returns>
public static string End()
{
return "</form>";
}
}
}
| |
#region File Description
//-----------------------------------------------------------------------------
// Settings.cs
//
// Microsoft XNA Community Game Platform
// Copyright (C) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
#endregion
#region Using Statements
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;
using System.IO;
using System.Xml.Serialization;
#endregion
namespace Spacewar
{
/// <summary>
/// The Setting class handles loading and saving of global application settings.
/// The normal .Net classes (System.Configuration) for doing this are not available on the CF (and therefore 360)
/// </summary>
public class Settings
{
#region General App Settings
/// <summary>
/// The path to look for all media in
/// </summary>
public string MediaPath = @"";
/// <summary>
/// The name of the window when running in windowed mode
/// </summary>
public string WindowTitle = "Spacewar";
/// <summary>
/// The length of each level in seconds;
/// </summary>
public int LevelTime = 30;
/// <summary>
/// How much maximum thrust to apply
/// </summary>
public float ThrustPower = 100f;
/// <summary>
/// How much friction to apply to slow down the ship
/// </summary>
public float FrictionFactor = .1f;
/// <summary>
/// Maximum speed a ship will accelerate to
/// </summary>
public float MaxSpeed = 200f;
/// <summary>
/// Time ships spend in recovery after destruction
/// </summary>
public float ShipRecoveryTime = 1.6f;
#endregion
#region Sun settings
/// <summary>
/// The position of the sun
/// </summary>
public Vector2 SunPosition = new Vector2(0f, 0f);
/// <summary>
/// How fast items are pulled towards the sun
/// </summary>
public double GravityStrength = 500000.0;
/// <summary>
/// Power defines the fall off of the suns gravity. 2.0 is 1/(n^2) as in normal gravity.
/// Bigger numbers fall off faster.
/// </summary>
public int GravityPower = 2;
/// <summary>
/// Affect the color of the sun shader
/// </summary>
public float ColorDistribution = 3.0f;
/// <summary>
/// Affects the fade of the sun shader
/// </summary>
public float Fade = 4.0f;
/// <summary>
/// Affects the flame speed of the sun shader
/// </summary>
public float FlameSpeed = 0.22f;
/// <summary>
/// Affects the spread of flames of the sun shder
/// </summary>
public float Spread = 0.50f;
/// <summary>
/// Affects the flames of the sun shader
/// </summary>
public float Flamability = 1.74f;
/// <summary>
/// Size of the sun
/// </summary>
public float Size = 70f;
#endregion
#region AsteroidSettings
/// <summary>
/// Realtive Scale of Asteroids
/// </summary>
public float AsteroidScale = .02f;
#endregion
#region BulletSettings
/// <summary>
/// RelativeScale of bullets
/// </summary>
public float BulletScale = .02f;
#endregion
#region Ship settings
/// <summary>
/// Relative scaling of the ships
/// </summary>
public float ShipScale = 0.02f;
/// <summary>
/// Stores settings for the player ships
/// </summary>
public struct PlayerShipInfo
{
/// <summary>
/// The start position of this ship
/// </summary>
public Vector2 StartPosition;
/// <summary>
/// The start angle of this ship
/// </summary>
public double StartAngle;
/// <summary>
/// Makes a new ShipInfo
/// </summary>
/// <param name="startPosition">Start position</param>
/// <param name="startAngle">Start Angle</param>
public PlayerShipInfo(Vector2 startPosition, double startAngle)
{
StartPosition = startPosition;
StartAngle = startAngle;
}
}
/// <summary>
/// Store default information about the ships
/// </summary>
public PlayerShipInfo[] Ships = new PlayerShipInfo[2] {new PlayerShipInfo(new Vector2(-300, 0), 90),
new PlayerShipInfo(new Vector2(300, 0), 90)};
#endregion
#region WeaponParameters
/// <summary>
/// Stores information about weapons
/// </summary>
public struct WeaponInfo
{
/// <summary>
/// Cost of the weapon
/// </summary>
public int Cost;
/// <summary>
/// Nubmer of seconds the projectile lasts for
/// </summary>
public double Lifetime;
/// <summary>
/// Maximum number of ths projectile that can be shot at a time
/// </summary>
public int Max;
/// <summary>
/// How many projectile fired per trigger pull
/// </summary>
public int Burst;
/// <summary>
/// Acceleration of the projectile
/// </summary>
public float Acceleration;
/// <summary>
/// How much damage this bullet does
/// </summary>
public int Damage;
/// <summary>
/// Creates a new weapon
/// </summary>
/// <param name="cost">Cost of the weapon</param>
public WeaponInfo(int cost, double lifetime, int max, int burst, float acceleration, int damage)
{
Cost = cost;
Lifetime = lifetime;
Max = max;
Burst = burst;
Acceleration = acceleration;
Damage = damage;
}
}
/// <summary>
/// Stores default information about the weapons
/// </summary>
public WeaponInfo[] Weapons = new WeaponInfo[]
{
new WeaponInfo(0, 3.0, 5, 1, 0, 1), //Pea
new WeaponInfo(1000, 3.0, 4, 3, 0, 1), //mgun
new WeaponInfo(2000, 3.0, 3, 3, 0, 1), //double mgun
new WeaponInfo(3000, 2.0, 1, 1, 1.0f, 5), //Rocket
new WeaponInfo(4000, 2.0, 3, 1, 0f, 5), //BFG
};
#endregion
#region Backdrop
/// <summary>
/// How fast the 2 backdrops fade between each other
/// </summary>
public float CrossFadeSpeed = 0.2f;
/// <summary>
/// How much the 2 backdrops move
/// </summary>
public float OffsetSpeed = 0.1f;
#endregion
#region Lighting
/// <summary>
/// Store informtion about lighting the scenes
/// </summary>
public struct ShipLighting
{
/// <summary>
/// Ambient component color
/// </summary>
public Vector4 Ambient;
/// <summary>
/// The direction of the directional light
/// </summary>
public Vector4 DirectionalDirection;
/// <summary>
/// The color of the directional light
/// </summary>
public Vector4 DirectionalColor;
/// <summary>
/// The position of the point light
/// </summary>
public Vector4 PointPosition;
/// <summary>
/// The color of the point light
/// </summary>
public Vector4 PointColor;
/// <summary>
/// The fall off of the point light
/// </summary>
public float PointFactor;
/// <summary>
/// Creates a new lighting scheme
/// </summary>
/// <param name="ambient">Ambient color</param>
/// <param name="directionalDirection">Directional light direction</param>
/// <param name="directionalColor">Directional light color</param>
/// <param name="pointPosition">Point light position</param>
/// <param name="pointColor">Point light color</param>
/// <param name="pointFactor">Point light fall off</param>
public ShipLighting(Vector4 ambient, Vector4 directionalDirection, Vector4 directionalColor, Vector4 pointPosition, Vector4 pointColor, float pointFactor)
{
Ambient = ambient;
DirectionalDirection = directionalDirection;
DirectionalColor = directionalColor;
PointPosition = pointPosition;
PointColor = pointColor;
PointFactor = pointFactor;
}
}
/// <summary>
/// Lighting parameters for in game and menu shaders
/// </summary>
public ShipLighting[] ShipLights = new ShipLighting[]
{ //0 is in game
new ShipLighting(new Vector4(1f, 1f, 1f, 1.0f),
new Vector4(1f, 1f, 1f, 0f),
new Vector4(.4f, .4f, .8f, 1.0f),
new Vector4(0f, 0f, 0f, 0f),
new Vector4(.8f, .6f, 0f, 1.0f),
.01f),
//1 is menu screens
new ShipLighting(new Vector4(.2f, .2f, .2f, 1.0f),
new Vector4(1f, 1f, 1f, 0f),
new Vector4(.4f, .4f, .8f, 1.0f),
new Vector4(0f, 0f, 0f, 0f),
new Vector4(.8f, .6f, 0f, 1.0f),
.008f),
};
#endregion
#region Keyboard Settings
/// <summary>
/// Keyboard settings for two players
/// Note: not allowing extensibility for more than 2 players
/// </summary>
// player 1
public Keys Player1Start = Keys.LeftControl;
public Keys Player1Back = Keys.LeftShift;
public Keys Player1A = Keys.V;
public Keys Player1B = Keys.G;
public Keys Player1X = Keys.F;
public Keys Player1Y = Keys.T;
public Keys Player1ThumbstickLeftXmin = Keys.A;
public Keys Player1ThumbstickLeftXmax = Keys.D;
public Keys Player1ThumbstickLeftYmin = Keys.S;
public Keys Player1ThumbstickLeftYmax = Keys.W;
public Keys Player1Left = Keys.A;
public Keys Player1Right = Keys.D;
public Keys Player1Down = Keys.S;
public Keys Player1Up = Keys.W;
public Keys Player1LeftTrigger = Keys.Q;
public Keys Player1RightTrigger = Keys.E;
// player 2
public Keys Player2Start = Keys.RightControl;
public Keys Player2Back = Keys.RightShift;
public Keys Player2A = Keys.Home;
public Keys Player2B = Keys.End;
public Keys Player2X = Keys.PageUp;
public Keys Player2Y = Keys.PageDown;
public Keys Player2ThumbstickLeftXmin = Keys.Left;
public Keys Player2ThumbstickLeftXmax = Keys.Right;
public Keys Player2ThumbstickLeftYmin = Keys.Down;
public Keys Player2ThumbstickLeftYmax = Keys.Up;
public Keys Player2Left = Keys.Left;
public Keys Player2Right = Keys.Right;
public Keys Player2Down = Keys.Down;
public Keys Player2Up = Keys.Up;
public Keys Player2LeftTrigger = Keys.Insert;
public Keys Player2RightTrigger = Keys.Delete;
#endregion
#region Load/Save code
/// <summary>
/// Saves the current settings
/// </summary>
/// <param name="filename">The filename to save to</param>
public void Save(string filename)
{
Stream stream = File.Create(filename);
XmlSerializer serializer = new XmlSerializer(typeof(Settings));
serializer.Serialize(stream, this);
stream.Close();
}
/// <summary>
/// Loads settings from a file
/// </summary>
/// <param name="filename">The filename to load</param>
public static Settings Load(string filename)
{
Stream stream = File.OpenRead(filename);
XmlSerializer serializer = new XmlSerializer(typeof(Settings));
return (Settings)serializer.Deserialize(stream);
}
#endregion
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using log4net;
using Mono.Addins;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Server.Base;
using OpenSim.Services.Interfaces;
using System;
using System.Collections.Generic;
using System.Reflection;
namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Inventory
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "LocalInventoryServicesConnector")]
public class LocalInventoryServicesConnector : ISharedRegionModule, IInventoryService
{
private static readonly ILog m_log =
LogManager.GetLogger(
MethodBase.GetCurrentMethod().DeclaringType);
private bool m_Enabled = false;
private IInventoryService m_InventoryService;
private IUserManagement m_UserManager;
public string Name
{
get { return "LocalInventoryServicesConnector"; }
}
public Type ReplaceableInterface
{
get { return null; }
}
/// <summary>
/// Scene used by this module. This currently needs to be publicly settable for HGInventoryBroker.
/// </summary>
public Scene Scene { get; set; }
private IUserManagement UserManager
{
get
{
if (m_UserManager == null)
{
m_UserManager = Scene.RequestModuleInterface<IUserManagement>();
}
return m_UserManager;
}
}
public void AddRegion(Scene scene)
{
if (!m_Enabled)
return;
scene.RegisterModuleInterface<IInventoryService>(this);
if (Scene == null)
Scene = scene;
}
public void Close()
{
}
public void Initialise(IConfigSource source)
{
IConfig moduleConfig = source.Configs["Modules"];
if (moduleConfig != null)
{
string name = moduleConfig.GetString("InventoryServices", "");
if (name == Name)
{
IConfig inventoryConfig = source.Configs["InventoryService"];
if (inventoryConfig == null)
{
m_log.Error("[LOCAL INVENTORY SERVICES CONNECTOR]: InventoryService missing from OpenSim.ini");
return;
}
string serviceDll = inventoryConfig.GetString("LocalServiceModule", String.Empty);
if (serviceDll == String.Empty)
{
m_log.Error("[LOCAL INVENTORY SERVICES CONNECTOR]: No LocalServiceModule named in section InventoryService");
return;
}
Object[] args = new Object[] { source };
m_log.DebugFormat("[LOCAL INVENTORY SERVICES CONNECTOR]: Service dll = {0}", serviceDll);
m_InventoryService = ServerUtils.LoadPlugin<IInventoryService>(serviceDll, args);
if (m_InventoryService == null)
{
m_log.Error("[LOCAL INVENTORY SERVICES CONNECTOR]: Can't load inventory service");
throw new Exception("Unable to proceed. Please make sure your ini files in config-include are updated according to .example's");
}
m_Enabled = true;
m_log.Info("[LOCAL INVENTORY SERVICES CONNECTOR]: Local inventory connector enabled");
}
}
}
public void PostInitialise()
{
}
public void RegionLoaded(Scene scene)
{
if (!m_Enabled)
return;
}
public void RemoveRegion(Scene scene)
{
if (!m_Enabled)
return;
}
#region IInventoryService
/// <summary>
/// Add a new folder to the user's inventory
/// </summary>
/// <param name="folder"></param>
/// <returns>true if the folder was successfully added</returns>
public bool AddFolder(InventoryFolderBase folder)
{
return m_InventoryService.AddFolder(folder);
}
public bool AddItem(InventoryItemBase item)
{
// m_log.DebugFormat(
// "[LOCAL INVENTORY SERVICES CONNECTOR]: Adding inventory item {0} to user {1} folder {2}",
// item.Name, item.Owner, item.Folder);
return m_InventoryService.AddItem(item);
}
public bool CreateUserInventory(UUID user)
{
return m_InventoryService.CreateUserInventory(user);
}
public bool DeleteFolders(UUID ownerID, List<UUID> folderIDs)
{
return m_InventoryService.DeleteFolders(ownerID, folderIDs);
}
/// <summary>
/// Delete an item from the user's inventory
/// </summary>
/// <param name="item"></param>
/// <returns>true if the item was successfully deleted</returns>
public bool DeleteItems(UUID ownerID, List<UUID> itemIDs)
{
return m_InventoryService.DeleteItems(ownerID, itemIDs);
}
public List<InventoryItemBase> GetActiveGestures(UUID userId)
{
return m_InventoryService.GetActiveGestures(userId);
}
public InventoryFolderBase GetFolder(InventoryFolderBase folder)
{
return m_InventoryService.GetFolder(folder);
}
public InventoryCollection GetFolderContent(UUID userID, UUID folderID)
{
InventoryCollection invCol = m_InventoryService.GetFolderContent(userID, folderID);
if (UserManager != null)
{
// Protect ourselves against the caller subsequently modifying the items list
List<InventoryItemBase> items = new List<InventoryItemBase>(invCol.Items);
Util.RunThreadNoTimeout(delegate
{
foreach (InventoryItemBase item in items)
if (!string.IsNullOrEmpty(item.CreatorData))
UserManager.AddUser(item.CreatorIdAsUuid, item.CreatorData);
}, "GetFolderContent", null);
}
return invCol;
}
public InventoryFolderBase GetFolderForType(UUID userID, AssetType type)
{
return m_InventoryService.GetFolderForType(userID, type);
}
public List<InventoryItemBase> GetFolderItems(UUID userID, UUID folderID)
{
return m_InventoryService.GetFolderItems(userID, folderID);
}
public List<InventoryFolderBase> GetInventorySkeleton(UUID userId)
{
return m_InventoryService.GetInventorySkeleton(userId);
}
public InventoryItemBase GetItem(InventoryItemBase item)
{
// m_log.DebugFormat("[LOCAL INVENTORY SERVICES CONNECTOR]: Requesting inventory item {0}", item.ID);
// UUID requestedItemId = item.ID;
item = m_InventoryService.GetItem(item);
// if (null == item)
// m_log.ErrorFormat(
// "[LOCAL INVENTORY SERVICES CONNECTOR]: Could not find item with id {0}", requestedItemId);
return item;
}
public InventoryFolderBase GetRootFolder(UUID userID)
{
return m_InventoryService.GetRootFolder(userID);
}
/// <summary>
/// Does the given user have an inventory structure?
/// </summary>
/// <param name="userID"></param>
/// <returns></returns>
public bool HasInventoryForUser(UUID userID)
{
return m_InventoryService.HasInventoryForUser(userID);
}
/// <summary>
/// Move an inventory folder to a new location
/// </summary>
/// <param name="folder">A folder containing the details of the new location</param>
/// <returns>true if the folder was successfully moved</returns>
public bool MoveFolder(InventoryFolderBase folder)
{
return m_InventoryService.MoveFolder(folder);
}
public bool MoveItems(UUID ownerID, List<InventoryItemBase> items)
{
return m_InventoryService.MoveItems(ownerID, items);
}
/// <summary>
/// Purge an inventory folder of all its items and subfolders.
/// </summary>
/// <param name="folder"></param>
/// <returns>true if the folder was successfully purged</returns>
public bool PurgeFolder(InventoryFolderBase folder)
{
return m_InventoryService.PurgeFolder(folder);
}
/// <summary>
/// Update a folder in the user's inventory
/// </summary>
/// <param name="folder"></param>
/// <returns>true if the folder was successfully updated</returns>
public bool UpdateFolder(InventoryFolderBase folder)
{
return m_InventoryService.UpdateFolder(folder);
}
/// <summary>
/// Update an item in the user's inventory
/// </summary>
/// <param name="item"></param>
/// <returns>true if the item was successfully updated</returns>
public bool UpdateItem(InventoryItemBase item)
{
return m_InventoryService.UpdateItem(item);
}
#endregion IInventoryService
}
}
| |
//
// BasePipelineWrapper.cs
//
// Author:
// Tomas Restrepo (tomasr@mvps.org)
//
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Xml;
using Microsoft.BizTalk.PipelineOM;
using Microsoft.BizTalk.Message.Interop;
using Microsoft.BizTalk.Component.Interop;
using Microsoft.XLANGs.BaseTypes;
using IPipeline = Microsoft.Test.BizTalk.PipelineObjects.IPipeline;
using PStage = Microsoft.Test.BizTalk.PipelineObjects.Stage;
using PCallEventArgs = Microsoft.Test.BizTalk.PipelineObjects.CallEventArgs;
namespace Winterdom.BizTalk.PipelineTesting
{
/// <summary>
/// Wrapper around a pipeline you can execute
/// </summary>
public abstract class BasePipelineWrapper : IEnumerable<IBaseComponent>
{
private IPipeline _pipeline;
private IPipelineContext _pipelineContext;
private bool _isReceivePipeline;
#region Properties
//
// Properties
//
internal IPipeline Pipeline
{
get { return _pipeline; }
}
internal IPipelineContext Context
{
get { return _pipelineContext; }
}
/// <summary>
/// Gets or Set the thumbprint for the Group
/// Signing Certificate. Null by default
/// </summary>
public string GroupSigningCertificate
{
get { return _pipelineContext.GetGroupSigningCertificate(); }
set
{
IConfigurePipelineContext ctxt = (IConfigurePipelineContext)_pipelineContext;
ctxt.SetGroupSigningCertificate(value);
}
}
#endregion // Properties
/// <summary>
/// Initializes an instance
/// </summary>
/// <param name="pipeline">Pipeline object to wrap</param>
/// <param name="isReceivePipeline">True if it's a receive pipeline</param>
protected BasePipelineWrapper(IPipeline pipeline, bool isReceivePipeline)
{
if ( pipeline == null )
throw new ArgumentNullException("pipeline");
_pipeline = pipeline;
pipeline.Calling += OnCallingStage;
_pipelineContext = CreatePipelineContext();
_isReceivePipeline = isReceivePipeline;
}
/// <summary>
/// Adds a component to the specified stage
/// </summary>
/// <param name="component">Component to add to the stage</param>
/// <param name="stage">Stage to add it to</param>
public void AddComponent(IBaseComponent component, PipelineStage stage)
{
if ( component == null )
throw new ArgumentNullException("component");
if ( stage == null )
throw new ArgumentNullException("stage");
if ( stage.IsReceiveStage != _isReceivePipeline )
throw new ArgumentException("Invalid Stage", "stage");
PStage theStage = FindStage(stage);
theStage.AddComponent(component);
}
/// <summary>
/// Adds a new document specification to the list
/// of Known Schemas for this pipeline.
/// </summary>
/// <remarks>
/// Adding known schemas is necessary so that
/// document type resolution works in the disassembler/assembler
/// stages
/// </remarks>
/// <param name="schemaType">Type of the document schema to add</param>
public void AddDocSpec(Type schemaType)
{
if ( schemaType == null )
throw new ArgumentNullException("schemaType");
DocSpecLoader loader = new DocSpecLoader();
Type[] roots = GetSchemaRoots(schemaType);
foreach ( Type root in roots )
{
IDocumentSpec docSpec = loader.LoadDocSpec(root);
AddDocSpecToContext(docSpec);
}
}
/// <summary>
/// Adds a new document specification to the list
/// of Known Schemas for this pipeline.
/// </summary>
/// <remarks>
/// Adding known schemas is necessary so that
/// document type resolution works in the disassembler/assembler
/// stages. Notice that this overload does NOT do automatic checking
/// for multiple roots.
/// </remarks>
/// <param name="typeName">The fully qualified (namespace.class) name of
/// the schema</param>
/// <param name="assemblyName">The partial or full name of the assembly
/// containing the schema</param>
public void AddDocSpec(string typeName, string assemblyName)
{
if ( String.IsNullOrEmpty(typeName) )
throw new ArgumentNullException("typeName");
if ( String.IsNullOrEmpty(assemblyName) )
throw new ArgumentNullException("assemblyName");
DocSpecLoader loader = new DocSpecLoader();
IDocumentSpec spec = loader.LoadDocSpec(typeName, assemblyName);
AddDocSpecToContext(spec);
}
/// <summary>
/// Returns the document spec object for a known doc
/// spec given the fully qualified type name
/// </summary>
/// <param name="name">Typename of the schema</param>
/// <returns>The docSpec object</returns>
public IDocumentSpec GetKnownDocSpecByName(string name)
{
return Context.GetDocumentSpecByName(name);
}
/// <summary>
/// Returns the document spec object for a known doc
/// spec given the name of the root (namespace#root)
/// </summary>
/// <param name="name">Name of the root</param>
/// <returns>The docSpec object</returns>
public IDocumentSpec GetKnownDocSpecByType(string name)
{
return Context.GetDocumentSpecByType(name);
}
/// <summary>
/// Enables transactional support for the pipeline
/// execution, so that the pipeline context
/// returns a valid transaction
/// </summary>
/// <returns>An object to control the transaction lifetime and result</returns>
public TransactionControl EnableTransactions()
{
IConfigurePipelineContext ctxt = (IConfigurePipelineContext)_pipelineContext;
return ctxt.EnableTransactionSupport();
}
/// <summary>
/// Looks up a component in the pipeline
/// </summary>
/// <param name="stage">The stage the component is in</param>
/// <param name="index">The 0-based index inside the stage</param>
/// <returns>The component, or null if it was not found</returns>
public IBaseComponent GetComponent(PipelineStage stage, int index)
{
foreach ( PStage st in _pipeline.Stages )
{
if ( st.Id == stage.ID )
{
IEnumerator enumerator = st.GetComponentEnumerator();
while ( enumerator.MoveNext() )
{
if ( index-- == 0 )
{
return (IBaseComponent)enumerator.Current;
}
}
}
}
return null;
}
/// <summary>
/// Apply per-instance pipeline configuration
/// </summary>
/// <param name="file">Path to the XML file with the configuration</param>
/// <remarks>
/// Per-instance pipeline configuration uses the same XML format used
/// by the BizTalk Admin console that gets exported to binding files,
/// for example, in the <SendPipelineData> element
/// </remarks>
public void ApplyInstanceConfig(string file)
{
using ( XmlReader reader = new XmlTextReader(file) )
ApplyInstanceConfig(reader);
}
/// <summary>
/// Apply per-instance pipeline configuration
/// </summary>
/// <param name="reader">XML reader with the configuration</param>
/// <remarks>
/// Per-instance pipeline configuration uses the same XML format used
/// by the BizTalk Admin console that gets exported to binding files,
/// for example, in the <SendPipelineData> element
/// </remarks>
public void ApplyInstanceConfig(XmlReader reader)
{
Guid stageId = Guid.Empty;
int index = 0;
while ( reader.Read() )
{
if ( reader.NodeType == XmlNodeType.Element )
{
if ( reader.LocalName == "Stage" )
{
stageId = new Guid(reader.GetAttribute("CategoryId"));
index = 0;
} else if ( reader.LocalName == "Component" )
{
string name = reader.GetAttribute("Name");
reader.ReadToDescendant("Properties");
XmlReader propReader = reader.ReadSubtree();
propReader.Read();
ApplyComponentConfig(stageId, name, index, propReader);
index++;
}
}
}
}
#region Protected Methods
//
// Protected Methods
//
/// <summary>
/// Finds a stage in the pipeline
/// </summary>
/// <param name="stage">Stage definition</param>
/// <returns>The stage, if found, or a new stage if necessary</returns>
protected PStage FindStage(PipelineStage stage)
{
PStage theStage = null;
foreach ( PStage pstage in _pipeline.Stages )
{
if ( pstage.Id == stage.ID )
{
theStage = pstage;
break;
}
}
if ( theStage == null )
{
theStage = new PStage(stage.Name, stage.ExecuteMethod, stage.ID, _pipeline);
_pipeline.Stages.Add(theStage);
}
return theStage;
}
/// <summary>
/// Creates a new pipeline context for the execution
/// </summary>
/// <returns>The new pipeline context.</returns>
protected IPipelineContext CreatePipelineContext()
{
return new PipelineContext();
}
#endregion // Protected Methods
#region Private Methods
//
// Private Methods
//
/// <summary>
/// Gets the namespace#root name for a schema.
/// If the schema has multiple roots, all are returned.
/// </summary>
/// <param name="schemaType">Type of the schema</param>
/// <returns>Roots of the schema</returns>
private Type[] GetSchemaRoots(Type schemaType)
{
string root = GetSchemaRoot(schemaType);
if ( root != null )
{
return new Type[] { schemaType };
} else
{
Type[] rts = schemaType.GetNestedTypes();
return rts;
}
}
/// <summary>
/// Gets the root name (namespace#root) for a schema type
/// </summary>
/// <param name="schemaType">Type of the schema</param>
/// <returns>Roots of the schema</returns>
private string GetSchemaRoot(Type schemaType)
{
SchemaAttribute[] attrs = (SchemaAttribute[])
schemaType.GetCustomAttributes(typeof(SchemaAttribute), true);
if ( attrs.Length > 0 )
{
if ( String.IsNullOrEmpty(attrs[0].TargetNamespace) )
return attrs[0].RootElement;
return string.Format("{0}#{1}", attrs[0].TargetNamespace, attrs[0].RootElement);
}
return null;
}
/// <summary>
/// Adds a document specification to the context
/// </summary>
/// <param name="docSpec">Specification to add</param>
private void AddDocSpecToContext(IDocumentSpec docSpec)
{
IConfigurePipelineContext ctxt = (IConfigurePipelineContext)Context;
ctxt.AddDocSpecByType(docSpec.DocType, docSpec);
// Pipelines referencing local schemas in the same
// assembly don't have use the assembly qualified name
// of the schema when trying to find it.
ctxt.AddDocSpecByName(docSpec.DocSpecStrongName, docSpec);
ctxt.AddDocSpecByName(docSpec.DocSpecName, docSpec);
}
/// <summary>
/// Applies the loaded configuration to a component
/// </summary>
/// <param name="stageId">The stage the component is in</param>
/// <param name="name">The component name</param>
/// <param name="index">The index of the component within the pipeline</param>
/// <param name="reader">The per-instance configuration</param>
private void ApplyComponentConfig(Guid stageId, string name, int index, XmlReader reader)
{
PipelineStage stage = PipelineStage.Lookup(stageId);
IPersistPropertyBag component = GetComponent(stage, index)
as IPersistPropertyBag;
if ( component != null )
{
String compName = component.GetType().FullName;
if ( compName != name )
throw new InvalidOperationException(String.Format(
"Component in stage '{0}', index {1} is '{2}', expected '{3}'",
stage.Name, index, compName, name));
IPropertyBag bag = new InstConfigPropertyBag(reader);
component.Load(bag, 1);
}
}
/// <summary>
/// Fired when a stage is processed or when a component
/// is going to be called
/// </summary>
/// <param name="sender">stage or component called</param>
/// <param name="args">stage message</param>
private void OnCallingStage(object sender, PCallEventArgs args)
{
PStage stage = sender as PStage;
if ( stage != null )
{
var configure = _pipelineContext as IConfigurePipelineContext;
if ( configure != null )
{
configure.SetCurrentStage(stage.Id);
}
}
}
#endregion // Private Methods
#region IEnumerable<IBaseComponent> Members
IEnumerator<IBaseComponent> IEnumerable<IBaseComponent>.GetEnumerator()
{
foreach ( PStage stage in _pipeline.Stages )
{
IEnumerator enumerator = stage.GetComponentEnumerator();
while ( enumerator.MoveNext() )
{
yield return (IBaseComponent)enumerator.Current;
}
}
}
#endregion
#region IEnumerable Members
IEnumerator IEnumerable.GetEnumerator()
{
return ((IEnumerable<IBaseComponent>)this).GetEnumerator();
}
#endregion
} // class BasePipelineWrapper
} // namespace Winterdom.BizTalk.PipelineTesting
| |
/*
Copyright 2019 Esri
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using System.ComponentModel;
using ESRI.ArcGIS.Geodatabase;
namespace ArcDataBinding
{
/// <summary>
/// This class provides a wrapper for an ITable that allows it to be bound to
/// a .NET control.
/// </summary>
/// <remarks>
/// This class inherits from <see cref="BindingList"/> to provide a default
/// implementation of a list of objects that can be bound to a .NET control.
/// For the purposes of this sample, it is easier to use BindingList and add
/// IRows to it than it is to implement all the interfaces required for a
/// bindable list. A more correct implementation would allow direct access to
/// the wrapped ITable rather than simply adding all of its rows to a list.
/// The class also implements <see cref="ITypedList"/> to allow a control to
/// query it for any properties required to correctly display the data in a
/// control. Normally properties are determined by using reflection. We want
/// the individual fields in the given ITable to look like properties of an
/// IRow. As this is not the case, we need to create a collection of 'fake'
/// properties with one for each field in the ITable. This is contained in the
/// fakePropertiesList member and is used by the ITypedList implementation.
/// </remarks>
[Guid("5a239147-b06a-49e5-aa1c-e47f81adc10e")]
[ClassInterface(ClassInterfaceType.None)]
[ProgId("ArcDataBinding.TableWrapper")]
public class TableWrapper: BindingList<IRow>, ITypedList
{
#region Private Members
/// <summary>
/// Reference to the table we are wrapping
/// </summary>
private ITable wrappedTable;
/// <summary>
/// This is a list of <see cref="PropertyDescriptor"/> instances with each one
/// representing one field of the wrapped ITable.
/// </summary>
private List<PropertyDescriptor> fakePropertiesList = new List<PropertyDescriptor>();
/// <summary>
/// Used to start and stop editing when adding/updating/deleting rows
/// </summary>
private IWorkspaceEdit wkspcEdit;
#endregion Private Members
#region Construction/Destruction
/// <summary>
/// This constructor stores a reference to the wrapped ITable and uses it to
/// generate a list of properties before adding the ITable's data to the binding
/// list.
/// </summary>
/// <param name="tableToWrap">ITable that we wish to bind to .NET controls</param>
public TableWrapper(ITable tableToWrap)
{
wrappedTable = tableToWrap;
GenerateFakeProperties();
AddData();
wkspcEdit = ((IDataset)wrappedTable).Workspace as IWorkspaceEdit;
AllowNew = true;
AllowRemove = true;
}
#endregion Construction/Destruction
#region ITypedList Members
/// <summary>
/// Returns the <see cref="T:System.ComponentModel.PropertyDescriptorCollection"></see>
/// that represents the properties on each item used to bind data.
/// </summary>
/// <param name="listAccessors">An array of <see cref="T:System.ComponentModel.PropertyDescriptor"></see>
/// objects to find in the collection as bindable. This can be null.</param>
/// <returns>
/// The <see cref="T:System.ComponentModel.PropertyDescriptorCollection"></see>
/// that represents the properties on each item used to bind data.
/// </returns>
public PropertyDescriptorCollection GetItemProperties(PropertyDescriptor[] listAccessors)
{
PropertyDescriptorCollection propCollection = null;
if (null == listAccessors)
{
// Return all properties
propCollection = new PropertyDescriptorCollection(fakePropertiesList.ToArray());
}
else
{
// Return the requested properties by checking each item in listAccessors
// to make sure it exists in our property collection.
List<PropertyDescriptor> tempList = new List<PropertyDescriptor>();
foreach (PropertyDescriptor curPropDesc in listAccessors)
{
if (fakePropertiesList.Contains(curPropDesc))
{
tempList.Add(curPropDesc);
}
}
propCollection = new PropertyDescriptorCollection(tempList.ToArray());
}
return propCollection;
}
/// <summary>
/// Returns the name of the list.
/// </summary>
/// <param name="listAccessors">An array of <see cref="T:System.ComponentModel.PropertyDescriptor"></see>
/// objects, the list name for which is returned. This can be null.</param>
/// <returns>The name of the list.</returns>
public string GetListName(PropertyDescriptor[] listAccessors)
{
return ((IDataset)wrappedTable).Name;
}
#endregion ITypedList Members
public bool UseCVDomains
{
set
{
foreach (FieldPropertyDescriptor curPropDesc in fakePropertiesList)
{
if (curPropDesc.HasCVDomain)
{
// Field has a coded value domain so turn the usage of this on or off
// as requested
curPropDesc.UseCVDomain = value;
}
}
}
}
#region Protected Overrides
/// <summary>
/// Raises the <see cref="E:System.ComponentModel.BindingList`1.AddingNew"></see> event.
/// </summary>
/// <remarks>
/// This override sets the NewObject property of the event arguments parameter
/// to be a new IRow.
/// </remarks>
/// <param name="e">An <see cref="T:System.ComponentModel.AddingNewEventArgs"></see>
/// that contains the event data.</param>
protected override void OnAddingNew(AddingNewEventArgs e)
{
// Check that we can still add rows, this property could have been changed
if (AllowNew)
{
// Need to create a new IRow
IRow newRow = wrappedTable.CreateRow();
e.NewObject = newRow;
// Loop through fields and set default values
for (int fieldCount = 0; fieldCount < newRow.Fields.FieldCount; fieldCount++)
{
IField curField = newRow.Fields.get_Field(fieldCount);
if (curField.Editable)
{
newRow.set_Value(fieldCount, curField.DefaultValue);
}
}
// Save default values
bool weStartedEditing = StartEditOp();
newRow.Store();
StopEditOp(weStartedEditing);
base.OnAddingNew(e);
}
}
/// <summary>
/// Removes the item at the specified index.
/// </summary>
/// <remarks>
/// This override calls the Delete method of the IRow that is being removed
/// </remarks>
/// <param name="index">The zero-based index of the item to remove.</param>
protected override void RemoveItem(int index)
{
// Check that we can still delete rows, this property could have been changed
if (AllowRemove)
{
// Get the corresponding IRow
IRow itemToRemove = Items[index];
bool weStartedEditing = StartEditOp();
// Delete the row
itemToRemove.Delete();
StopEditOp(weStartedEditing);
base.RemoveItem(index);
}
}
#endregion Protected Overrides
#region Private Methods
/// <summary>
/// Generates 'fake' properties.
/// </summary>
/// <remarks>
/// We need this method to create a list of properties for each field in the
/// ITable as an IRow does not have a property for each field.
/// </remarks>
private void GenerateFakeProperties()
{
// Loop through fields in wrapped table
for (int fieldCount = 0; fieldCount < wrappedTable.Fields.FieldCount; fieldCount++)
{
// Create a new property descriptor to represent the field
FieldPropertyDescriptor newPropertyDesc = new FieldPropertyDescriptor(
wrappedTable, wrappedTable.Fields.get_Field(fieldCount).Name, fieldCount);
fakePropertiesList.Add(newPropertyDesc);
}
}
/// <summary>
/// Adds the data to the binding list.
/// </summary>
/// <remarks>
/// Note that this is a pretty inefficient way of accessing the data to be
/// bound to a control. If we implemented each of the interfaces required for
/// a bindable list rather than using BindingList, we could write code that
/// only reads rows from the ITable as they need to be displayed rather than
/// reading all of them.
/// </remarks>
private void AddData()
{
// Get a search cursor that returns all rows. Note we do not want to recycle
// the returned IRow otherwise all rows in the bound control will be identical
// to the last row read...
ICursor cur = wrappedTable.Search(null, false);
IRow curRow = cur.NextRow();
while (null != curRow)
{
Add(curRow);
curRow = cur.NextRow();
}
}
/// <summary>
/// Starts an edit operation.
/// </summary>
/// <remarks>
/// This method is used to start an edit operation before changing any data.
/// It checks to see if we are in an edit session or not and starts a new
/// one if appropriate. If we do start an edit session, the method will return
/// true to indicate that we started an edit session and should therefore also
/// stop it.
/// </remarks>
/// <returns>True if we started an edit session, false if we didn't</returns>
private bool StartEditOp()
{
bool retVal = false;
// Check to see if we're editing
if (!wkspcEdit.IsBeingEdited())
{
// Not being edited so start here
wkspcEdit.StartEditing(false);
retVal = true;
}
// Start operation
wkspcEdit.StartEditOperation();
return retVal;
}
/// <summary>
/// Stops the edit operation.
/// </summary>
/// <remarks>
/// This method stops an edit operation started with a call to
/// <see cref="StartEditOp"/>. If the weStartedEditing parameter is true, this
/// method will also end the edit session.
/// </remarks>
/// <param name="weStartedEditing">if set to <c>true</c> [we started editing].</param>
private void StopEditOp(bool weStartedEditing)
{
// Stop edit operation
wkspcEdit.StopEditOperation();
if (weStartedEditing)
{
// We started the edit session so stop it here
wkspcEdit.StopEditing(true);
}
}
#endregion Private Methods
}
}
| |
/* ****************************************************************************
*
* Copyright (c) Microsoft Corporation.
*
* This source code is subject to terms and conditions of the Apache License, Version 2.0. A
* copy of the license can be found in the License.html file at the root of this distribution. If
* you cannot locate the Apache License, Version 2.0, please send an email to
* dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
* by the terms of the Apache License, Version 2.0.
*
* You must not remove this notice, or any other, from this software.
*
*
* ***************************************************************************/
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Scripting.Hosting;
using System.Reflection;
using System.IO;
using Microsoft.Scripting.Runtime;
using System.Xml;
using System.Windows;
using System.Windows.Browser;
using Microsoft.Scripting.Utils;
using System.Dynamic;
namespace Microsoft.Scripting.Silverlight {
/// <summary>
/// Responcible for executing all dynamic language code
/// </summary>
public class DynamicEngine {
#region Properties
/// <summary>
/// Avaliable languages
/// </summary>
public DynamicLanguageConfig LangConfig { get; private set; }
/// <summary>
/// DLR ScriptRuntime to execute code against
/// </summary>
public ScriptRuntime Runtime { get; private set; }
/// <summary>
/// DLR ScriptRuntimeSetup to initialize ScriptRuntime from. It's
/// stored in case the user needs to create another ScriptRuntime.
/// </summary>
public ScriptRuntimeSetup RuntimeSetup { get; private set; }
/// <summary>
/// Current ScriptEngine for the language executing code.
/// </summary>
public ScriptEngine Engine { get; internal set; }
/// <summary>
/// The ScriptScope all entry-point code is executed against.
/// </summary>
public ScriptScope EntryPointScope { get; private set; }
/// <summary>
/// true while the entry-point is running, false otherwise
/// </summary>
internal bool RunningEntryPoint { get; set; }
#endregion
#region implementation
/// <summary>
/// Finds the avaliable languages, initializes the ScriptRuntime,
/// and initializes the entry-points ScriptScope.
/// </summary>
public DynamicEngine() : this(null) { }
/// <summary>
/// Initializes the languages, ScriptRuntime, and entry-point ScriptScope.
/// </summary>
public DynamicEngine(DynamicLanguageConfig langConfig) {
RunningEntryPoint = false;
if (langConfig == null) {
LangConfig = InitializeLangConfig();
} else {
LangConfig = langConfig;
}
Runtime = CreateRuntime(Settings.Debug, LangConfig);
Runtime.LoadAssembly(GetType().Assembly);
LangConfig.Runtime = Runtime;
RuntimeSetup = Runtime.Setup;
EntryPointScope = CreateScope(Runtime);
}
/// <summary>
/// Run a script. Get's the contents from the script's path, uses the
/// script's file extension to find the corresponding ScriptEngine,
/// setting the "Engine" property, and execute the script against the
/// entry point scope as a file.
/// </summary>
/// <param name="entryPoint">path to the script</param>
public void Run(string entryPoint) {
if (entryPoint != null) {
var vfs = ((BrowserPAL)Runtime.Host.PlatformAdaptationLayer).VirtualFilesystem;
string code = vfs.GetFileContents(entryPoint);
Engine = Runtime.GetEngineByFileExtension(Path.GetExtension(entryPoint));
ScriptSource sourceCode = Engine.CreateScriptSourceFromString(code, entryPoint, SourceCodeKind.File);
RunningEntryPoint = true;
sourceCode.Compile(new ErrorFormatter.Sink()).Execute(EntryPointScope);
RunningEntryPoint = false;
}
}
/// <summary>
/// Initializes the language config
/// </summary>
private static DynamicLanguageConfig InitializeLangConfig() {
return DynamicApplication.Current == null ?
CreateLangConfig() :
DynamicApplication.Current.LanguagesConfig;
}
/// <summary>
/// Create a new language config
/// </summary>
private static DynamicLanguageConfig CreateLangConfig() {
return DynamicLanguageConfig.Create(new DynamicAppManifest().Assemblies);
}
#endregion
#region Public Hosting API
#region CreateRuntimeSetup
/// <summary>
/// Create a ScriptRuntimeSetup for generating optimized (non-debuggable) code.
/// </summary>
public static ScriptRuntimeSetup CreateRuntimeSetup() {
return CreateRuntimeSetup(false);
}
/// <summary>
/// Creates a new ScriptRuntimeSetup.
/// </summary>
/// <param name="debugMode">Tells the setup to generate debuggable code</param>
/// <returns>new ScriptRuntimeSetup</returns>
public static ScriptRuntimeSetup CreateRuntimeSetup(bool debugMode) {
DynamicLanguageConfig langConfig = CreateLangConfig();
return CreateRuntimeSetup(debugMode, langConfig);
}
/// <summary>
/// Creates a new ScriptRuntimeSetup, given a language config.
/// </summary>
/// <param name="langConfig">Use this language config to generate the setup</param>
/// <param name="debugMode">Tells the setup to generate debuggable code</param>
/// <returns>new ScriptRuntimeSetup</returns>
public static ScriptRuntimeSetup CreateRuntimeSetup(bool debugMode, DynamicLanguageConfig langConfig) {
var setup = langConfig.CreateRuntimeSetup();
setup.HostType = typeof(BrowserScriptHost);
setup.Options["SearchPaths"] = new string[] { String.Empty };
setup.DebugMode = debugMode;
return setup;
}
/// <summary>
/// Creates a new ScriptRuntimeSetup, given a list of assemblies.
/// </summary>
/// <param name="assemblies">List of assemblies to find DLR's language configuration</param>
/// <returns>new ScriptRuntimeSetup</returns>
public static ScriptRuntimeSetup CreateRuntimeSetup(List<Assembly> assemblies) {
return CreateRuntimeSetup(Settings.Debug, DynamicLanguageConfig.LoadFromAssemblies(assemblies));
}
#endregion
#region CreateRuntime
public static ScriptRuntime CreateRuntime() {
return CreateRuntimeHelper(CreateRuntimeSetup());
}
public static ScriptRuntime CreateRuntime(bool debugMode) {
return CreateRuntimeHelper(CreateRuntimeSetup(debugMode));
}
public static ScriptRuntime CreateRuntime(bool debugMode, DynamicLanguageConfig langConfig) {
return CreateRuntimeHelper(CreateRuntimeSetup(debugMode, langConfig));
}
/// <summary>
/// Load default references into the runtime, including this assembly
/// and a select set of platform assemblies.
/// </summary>
/// <param name="runtime">Pre-initialized ScriptRuntime to load assemblies into.</param>
public static void LoadDefaultAssemblies(ScriptRuntime runtime) {
foreach (string name in new string[] { "mscorlib", "System", "System.Windows", "System.Windows.Browser", "System.Net" }) {
runtime.LoadAssembly(runtime.Host.PlatformAdaptationLayer.LoadAssembly(name));
}
}
private static ScriptRuntime CreateRuntimeHelper(ScriptRuntimeSetup setup) {
var runtime = new ScriptRuntime(setup);
LoadDefaultAssemblies(runtime);
return runtime;
}
#endregion
#region CreateScope
/// <summary>
/// Creates a new scope, adding any convenience globals and modules.
/// </summary>
public static ScriptScope CreateScope(ScriptRuntime runtime) {
var scope = runtime.CreateScope();
if (HtmlPage.IsEnabled) {
scope.SetVariable("document", HtmlPage.Document);
scope.SetVariable("window", HtmlPage.Window);
}
if (DynamicApplication.Current != null) {
scope.SetVariable("me", DynamicApplication.Current.RootVisual);
scope.SetVariable("xaml", DynamicApplication.Current.RootVisual);
}
return scope;
}
/// <summary>
/// Creates a new scope, adding any convenience globals and modules.
/// </summary>
public ScriptScope CreateScope() {
return CreateScope(Runtime);
}
#endregion
#endregion
}
}
| |
/*
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the MIT License. See License.txt in the project root for license information.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using Adxstudio.Xrm.Resources;
using Microsoft.Xrm.Client.Diagnostics;
using Microsoft.Xrm.Portal;
using Microsoft.Xrm.Portal.Web;
using Microsoft.Xrm.Sdk;
namespace Adxstudio.Xrm.Web.UI.CrmEntityListView
{
/// <summary>
/// Settings for displaying a map.
/// </summary>
public class MapConfiguration
{
private const string DefaultRestUrl = "https://dev.virtualearth.net/REST/v1/Locations";
private string _restUrl;
/// <summary>
/// Unit of measure for the distance search
/// </summary>
public enum DistanceUnits
{
/// <summary>
/// miles
/// </summary>
Miles = 756150001,
/// <summary>
/// km
/// </summary>
Km = 756150000
}
/// <summary>
/// Indicates whether the map control is enabled or not.
/// </summary>
public bool Enabled { get; set; }
/// <summary>
/// Key used to authorize map service transactions.
/// </summary>
public string Credentials { get; set; }
/// <summary>
/// Gets or sets the REST URL for the map service. Default: https://dev.virtualearth.net/REST/v1/Locations
/// </summary>
public string RestUrl
{
get
{
return string.IsNullOrWhiteSpace(_restUrl) ? DefaultRestUrl : _restUrl;
}
set
{
_restUrl = value;
}
}
/// <summary>
/// Latitude of the map's default center position.
/// </summary>
public double DefaultCenterLatitude { get; set; }
/// <summary>
/// Longitude of the map's default center position.
/// </summary>
public double DefaultCenterLongitude { get; set; }
/// <summary>
/// Default zoom level of the map. An integer value from 1 - 19 indicating the default zoom level of the map. Default: 12
/// </summary>
public int DefaultZoom { get; set; }
/// <summary>
/// An integer value of the horizontal offset of the map pushpin infobox. Default: 25
/// </summary>
public int InfoboxOffsetX { get; set; }
/// <summary>
/// An integer value of the vertical offset of the map pushpin infobox. Default: 46
/// </summary>
public int InfoboxOffsetY { get; set; }
/// <summary>
/// An integer value of the height of the map pushpin image. Default: 39
/// </summary>
public int PinImageHeight { get; set; }
/// <summary>
/// An integer value of the width of the map pushpin image. Default: 32
/// </summary>
public int PinImageWidth { get; set; }
/// <summary>
/// A URL to an image file to be used as the pushpin on the map. If none is specified, a default pin image will be used.
/// </summary>
public string PinImageUrl { get; set; }
/// <summary>
/// The unit of measure for distance values. One of the following, miles or Km. Default: miles
/// </summary>
public DistanceUnits DistanceUnit { get; set; }
/// <summary>
/// List of integer values to be populated in the dropdown used in the web portal for selecting the distance to search for location on the map to. Note: The first value in the list is the default search distance used when initially rendering the map. Default: 5,10,25,50,100
/// </summary>
public List<int> DistanceValues { get; set; }
/// <summary>
/// Attribute logical name of the latitude field on the target entity.
/// </summary>
/// <remarks>Recommended attribute schema settings. Type: Floating Point Number, Precision: 5, Min. Value: -90, Max. Value: 90, IME Mode: disabled</remarks>
public string LatitudeFieldName { get; set; }
/// <summary>
/// Attribute logical name of the longitude field on the target entity.
/// </summary>
/// <remarks>Recommended attribute schema settings. Type: Floating Point Number, Precision: 5, Min. Value: -180, Max. Value: 180, IME Mode: disabled</remarks>
public string LongitudeFieldName { get; set; }
/// <summary>
/// Attribute logical name on the target entity that represents the title displayed in the popup infobox for the map pushpin.
/// </summary>
public string InfoboxTitleFieldName { get; set; }
/// <summary>
/// Attribute logical name on the target entity that represents the description displayed in the popup infobox for the map pushpin.
/// </summary>
public string InfoboxDescriptionFieldName { get; set; }
/// <summary>
/// URL to handle the search request.
/// </summary>
public string SearchUrl { get; set; }
/// <summary>
/// Contstructor
/// </summary>
/// <param name="credentials"></param>
/// <param name="restUrl"></param>
/// <param name="searchUrl"></param>
/// <param name="enabled"></param>
/// <param name="defaultCenterLatitude"></param>
/// <param name="defaultCenterLongitude"></param>
/// <param name="defaultZoom"></param>
/// <param name="infoboxOffsetX"></param>
/// <param name="infoboxOffsetY"></param>
/// <param name="pinImageHeight"></param>
/// <param name="pinImageWidth"></param>
/// <param name="pinImageUrl"></param>
/// <param name="distanceUnit"></param>
/// <param name="distanceValues"></param>
public MapConfiguration(string credentials = null, string restUrl = null, string searchUrl = null, bool enabled = false,
double defaultCenterLatitude = 0, double defaultCenterLongitude = 0, int defaultZoom = 12, int infoboxOffsetX = 25,
int infoboxOffsetY = 46, int pinImageHeight = 39, int pinImageWidth = 32, string pinImageUrl = null,
DistanceUnits distanceUnit = DistanceUnits.Miles, List<int> distanceValues = null)
{
Credentials = credentials;
RestUrl = restUrl;
SearchUrl = searchUrl;
Enabled = enabled;
DefaultCenterLatitude = defaultCenterLatitude;
DefaultCenterLongitude = defaultCenterLongitude;
DefaultZoom = defaultZoom;
InfoboxOffsetX = infoboxOffsetX;
InfoboxOffsetY = infoboxOffsetY;
PinImageHeight = pinImageHeight;
PinImageWidth = pinImageWidth;
PinImageUrl = pinImageUrl;
DistanceUnit = distanceUnit;
DistanceValues = distanceValues;
}
public MapConfiguration(IPortalContext portalContext, bool mapEnabled, OptionSetValue mapDistanceUnit,
string mapDistanceValues, int? mapInfoboxOffsetY, int? mapInfoboxOffsetX, int? mapPushpinWidth,
string mapPushpinUrl, int? mapZoom, double? mapLongitude, double? mapLatitude, string mapRestUrl,
string mapCredentials, int? mapPushpinHeight)
{
Enabled = mapEnabled;
if (!string.IsNullOrWhiteSpace(mapCredentials)) { Credentials = mapCredentials; }
RestUrl = mapRestUrl;
DefaultCenterLatitude = mapLatitude ?? 0;
DefaultCenterLongitude = mapLongitude ?? 0;
DefaultZoom = mapZoom ?? 12;
PinImageUrl = mapPushpinUrl;
PinImageWidth = mapPushpinWidth ?? 32;
PinImageHeight = mapPushpinHeight ?? 39;
InfoboxOffsetX = mapInfoboxOffsetX ?? 25;
InfoboxOffsetY = mapInfoboxOffsetY ?? 46;
if (!string.IsNullOrWhiteSpace(mapDistanceValues))
{
var distanceItems = mapDistanceValues.Split(',');
var distanceList = new List<int>();
if (distanceItems.Any())
{
foreach (var distance in distanceItems)
{
int distanceValue;
if (int.TryParse(distance, out distanceValue))
{
distanceList.Add(distanceValue);
}
}
}
else
{
distanceList = new List<int> { 5, 10, 25, 100 };
}
DistanceValues = distanceList;
}
if (mapDistanceUnit != null)
{
if (Enum.IsDefined(typeof(DistanceUnits), mapDistanceUnit.Value))
{
DistanceUnit = (DistanceUnits)mapDistanceUnit.Value;
}
else
{
ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("Distance Unit value '{0}' is not a valid value defined by MapConfiguration.DistanceUnits class.",
mapDistanceUnit.Value));
}
}
SearchUrl = WebsitePathUtility.ToAbsolute(portalContext.Website, "/EntityList/Map/Search/");
}
}
}
| |
using Jint.Native;
using Jint.Tests.Runtime.Domain;
using System.Collections.Generic;
using System.Linq;
using Xunit;
using Xunit.Abstractions;
using System.IO;
using System.Text;
namespace Jint.Tests.Runtime.ExtensionMethods
{
public class ExtensionMethodsTest
{
[Fact]
public void ShouldInvokeObjectExtensionMethod()
{
var person = new Person();
person.Name = "Mickey Mouse";
person.Age = 35;
var options = new Options();
options.AddExtensionMethods(typeof(PersonExtensions));
var engine = new Engine(options);
engine.SetValue("person", person);
var age = engine.Evaluate("person.MultiplyAge(2)").AsInteger();
Assert.Equal(70, age);
}
[Fact]
public void ShouldInvokeStringExtensionMethod()
{
var options = new Options();
options.AddExtensionMethods(typeof(CustomStringExtensions));
var engine = new Engine(options);
var result = engine.Evaluate("\"Hello World!\".Backwards()").AsString();
Assert.Equal("!dlroW olleH", result);
}
[Fact]
public void ShouldInvokeNumberExtensionMethod()
{
var options = new Options();
options.AddExtensionMethods(typeof(DoubleExtensions));
var engine = new Engine(options);
var result = engine.Evaluate("let numb = 27; numb.Add(13)").AsInteger();
Assert.Equal(40, result);
}
[Fact]
public void ShouldPrioritizingNonGenericMethod()
{
var options = new Options();
options.AddExtensionMethods(typeof(CustomStringExtensions));
var engine = new Engine(options);
var result = engine.Evaluate("\"{'name':'Mickey'}\".DeserializeObject()").ToObject() as dynamic;
Assert.Equal("Mickey", result.name);
}
[Fact]
public void PrototypeFunctionsShouldNotBeOverridden()
{
var engine = new Engine(opts =>
{
opts.AddExtensionMethods(typeof(CustomStringExtensions));
});
//uses split function from StringPrototype
var arr = engine.Evaluate("'yes,no'.split(',')").AsArray();
Assert.Equal("yes", arr[0]);
Assert.Equal("no", arr[1]);
//uses split function from CustomStringExtensions
var arr2 = engine.Evaluate("'yes,no'.split(2)").AsArray();
Assert.Equal("ye", arr2[0]);
Assert.Equal("s,no", arr2[1]);
}
[Fact]
public void OverridePrototypeFunctions()
{
var engine = new Engine(opts =>
{
opts.AddExtensionMethods(typeof(OverrideStringPrototypeExtensions));
});
//uses the overridden split function from OverrideStringPrototypeExtensions
var arr = engine.Evaluate("'yes,no'.split(',')").AsArray();
Assert.Equal("YES", arr[0]);
Assert.Equal("NO", arr[1]);
}
[Fact]
public void HasOwnPropertyShouldWorkCorrectlyInPresenceOfExtensionMethods()
{
var person = new Person();
var options = new Options();
options.AddExtensionMethods(typeof(PersonExtensions));
var engine = new Engine(options);
engine.SetValue("person", person);
var isBogusInPerson = engine.Evaluate("'bogus' in person").AsBoolean();
Assert.False(isBogusInPerson);
var propertyValue = engine.Evaluate("person.bogus");
Assert.Equal(JsValue.Undefined, propertyValue);
}
private Engine GetLinqEngine()
{
return new Engine(opts =>
{
opts.AddExtensionMethods(typeof(Enumerable));
});
}
[Fact]
public void LinqExtensionMethodWithoutGenericParameter()
{
var engine = GetLinqEngine();
var intList = new List<int>() { 0, 1, 2, 3 };
engine.SetValue("intList", intList);
var intSumRes = engine.Evaluate("intList.Sum()").AsNumber();
Assert.Equal(6, intSumRes);
}
[Fact]
public void LinqExtensionMethodWithSingleGenericParameter()
{
var engine = GetLinqEngine();
var stringList = new List<string>() { "working", "linq" };
engine.SetValue("stringList", stringList);
var stringSumRes = engine.Evaluate("stringList.Sum(x => x.length)").AsNumber();
Assert.Equal(11, stringSumRes);
}
[Fact]
public void LinqExtensionMethodWithMultipleGenericParameters()
{
var engine = GetLinqEngine();
var stringList = new List<string>() { "working", "linq" };
engine.SetValue("stringList", stringList);
var stringRes = engine.Evaluate("stringList.Select((x) => x + 'a').ToArray().join()").AsString();
Assert.Equal("workinga,linqa", stringRes);
// The method ambiguity resolver is not so smart to choose the Select method with the correct number of parameters
// Thus, the following script will not work as expected.
// stringList.Select((x, i) => x + i).ToArray().join()
}
[Fact]
public void GenericTypeExtension()
{
var options = new Options();
options.AddExtensionMethods(typeof(ObservableExtensions));
var engine = new Engine(options);
engine.SetValue("log", new System.Action<object>(System.Console.WriteLine));
NameObservable observable = new NameObservable();
engine.SetValue("observable", observable);
engine.Evaluate(@"
log('before');
observable.Subscribe((name) =>{
log('observable: subscribe: name: ' + name);
});
observable.UpdateName('foobar');
log('after');
");
Assert.Equal("foobar", observable.Last);
}
private class Converter : TextWriter
{
ITestOutputHelper _output;
public Converter(ITestOutputHelper output)
{
_output = output;
}
public override Encoding Encoding
{
get { return Encoding.ASCII; }
}
public override void WriteLine(string message)
{
_output.WriteLine(message);
}
public override void WriteLine(string format, params object[] args)
{
_output.WriteLine(format, args);
}
public override void Write(char value)
{
throw new System.Exception("This text writer only supports WriteLine(string) and WriteLine(string, params object[]).");
}
}
}
}
| |
using System;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using AllReady.Features.Login;
using AllReady.Features.Manage;
using AllReady.Models;
using AllReady.Security;
using AllReady.ViewModels.Manage;
using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Routing;
namespace AllReady.Controllers
{
[Authorize]
public class ManageController : Controller
{
private readonly UserManager<ApplicationUser> _userManager;
private readonly SignInManager<ApplicationUser> _signInManager;
private readonly IMediator _mediator;
public ManageController(
UserManager<ApplicationUser> userManager,
SignInManager<ApplicationUser> signInManager,
IMediator mediator)
{
_userManager = userManager;
_signInManager = signInManager;
_mediator = mediator;
}
// GET: /Manage/Index
[HttpGet]
public async Task<IActionResult> Index(ManageMessageId? message = null)
{
ViewData[STATUS_MESSAGE] =
message == ManageMessageId.ChangePasswordSuccess ? "Your password has been changed."
: message == ManageMessageId.SetPasswordSuccess ? "Your password has been set."
: message == ManageMessageId.SetTwoFactorSuccess ? "Your two-factor authentication provider has been set."
: message == ManageMessageId.Error ? ERROR_OCCURRED
: message == ManageMessageId.AddPhoneSuccess ? "Your mobile phone number was added."
: message == ManageMessageId.RemovePhoneSuccess ? "Your mobile phone number was removed."
: "";
var user = await GetCurrentUser();
return View(await user.ToViewModel(_userManager, _signInManager));
}
// POST: /Manage/Index
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Index(IndexViewModel model)
{
var shouldRefreshSignin = false;
var user = await GetCurrentUser();
if (!ModelState.IsValid)
{
var viewModelWithInputs = await user.ToViewModel(_userManager, _signInManager);
viewModelWithInputs.FirstName= model.FirstName;
viewModelWithInputs.LastName = model.LastName;
viewModelWithInputs.TimeZoneId = model.TimeZoneId;
viewModelWithInputs.AssociatedSkills = model.AssociatedSkills;
return View(viewModelWithInputs);
}
if (!string.IsNullOrEmpty(model.FirstName))
{
user.FirstName= model.FirstName;
shouldRefreshSignin = true;
}
if (!string.IsNullOrEmpty(model.LastName))
{
user.LastName= model.LastName;
shouldRefreshSignin = true;
}
if (user.TimeZoneId != model.TimeZoneId)
{
user.TimeZoneId = model.TimeZoneId;
await _userManager.RemoveClaimsAsync(user, User.Claims.Where(c => c.Type == Security.ClaimTypes.TimeZoneId));
await _userManager.AddClaimAsync(user, new Claim(Security.ClaimTypes.TimeZoneId, user.TimeZoneId));
shouldRefreshSignin = true;
}
user.AssociatedSkills.RemoveAll(usk => model.AssociatedSkills == null || !model.AssociatedSkills.Any(msk => msk.SkillId == usk.SkillId));
if (model.AssociatedSkills != null)
{
user.AssociatedSkills.AddRange(model.AssociatedSkills.Where(msk => !user.AssociatedSkills.Any(usk => usk.SkillId == msk.SkillId)));
}
user.AssociatedSkills?.ForEach(usk => usk.UserId = user.Id);
await _mediator.SendAsync(new UpdateUser { User = user });
if (shouldRefreshSignin)
{
await _signInManager.RefreshSignInAsync(user);
}
await UpdateUserProfileCompleteness(user);
return RedirectToAction(nameof(Index));
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> ResendEmailConfirmation()
{
var user = await _userManager.GetUserAsync(User);
var token = await _userManager.GenerateEmailConfirmationTokenAsync(user);
var callbackUrl = Url.Action(new UrlActionContext { Action = nameof(AccountController.ConfirmEmail), Controller = "Account", Values = new { userId = user.Id, token },
Protocol = HttpContext.Request.Scheme });
await _mediator.SendAsync(new SendConfirmAccountEmail { Email = user.Email, CallbackUrl = callbackUrl });
return RedirectToAction(nameof(EmailConfirmationSent));
}
[HttpGet]
public IActionResult EmailConfirmationSent()
{
return View();
}
// GET: /Account/RemoveLogin
[HttpGet]
public async Task<IActionResult> RemoveLogin()
{
var user = await GetCurrentUser();
var linkedAccounts = await _userManager.GetLoginsAsync(user);
ViewData[SHOW_REMOVE_BUTTON] = await _userManager.HasPasswordAsync(user) || linkedAccounts.Count > 1;
return View(linkedAccounts);
}
// POST: /Manage/RemoveLogin
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> RemoveLogin(string loginProvider, string providerKey)
{
ManageMessageId? message = ManageMessageId.Error;
var user = await GetCurrentUser();
if (user != null)
{
var result = await _userManager.RemoveLoginAsync(user, loginProvider, providerKey);
if (result.Succeeded)
{
await _signInManager.SignInAsync(user, isPersistent: false);
message = ManageMessageId.RemoveLoginSuccess;
}
}
return RedirectToAction(nameof(ManageLogins), new { Message = message });
}
// GET: /Account/AddPhoneNumber
public IActionResult AddPhoneNumber()
{
return View();
}
// POST: /Account/AddPhoneNumber
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> AddPhoneNumber(AddPhoneNumberViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
// Generate the token and send it
await GenerateChangePhoneNumberTokenAndSendAccountSecurityTokenSms(await GetCurrentUser(), model.PhoneNumber);
return RedirectToAction(nameof(VerifyPhoneNumber), new { model.PhoneNumber });
}
// POST: /Account/ResendPhoneNumberConfirmation
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> ResendPhoneNumberConfirmation(string phoneNumber)
{
await GenerateChangePhoneNumberTokenAndSendAccountSecurityTokenSms(await GetCurrentUser(), phoneNumber);
return RedirectToAction(nameof(VerifyPhoneNumber), new { PhoneNumber = phoneNumber });
}
// POST: /Manage/EnableTwoFactorAuthentication
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> EnableTwoFactorAuthentication()
{
var user = await GetCurrentUser();
if (user != null)
{
await _userManager.SetTwoFactorEnabledAsync(user, true);
await _signInManager.SignInAsync(user, isPersistent: false);
}
return RedirectToAction(nameof(Index));
}
// POST: /Manage/DisableTwoFactorAuthentication
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DisableTwoFactorAuthentication()
{
var user = await GetCurrentUser();
if (user != null)
{
await _userManager.SetTwoFactorEnabledAsync(user, false);
await _signInManager.SignInAsync(user, isPersistent: false);
}
return RedirectToAction(nameof(Index));
}
// GET: /Account/VerifyPhoneNumber
[HttpGet]
public IActionResult VerifyPhoneNumber(string phoneNumber)
{
// Send an SMS to verify the mobile phone number
return phoneNumber == null ? View(ERROR_VIEW) : View(new VerifyPhoneNumberViewModel { PhoneNumber = phoneNumber });
}
// POST: /Account/VerifyPhoneNumber
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> VerifyPhoneNumber(VerifyPhoneNumberViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
var user = await GetCurrentUser();
if (user != null)
{
var result = await _userManager.ChangePhoneNumberAsync(user, model.PhoneNumber, model.Code);
if (result.Succeeded)
{
await UpdateUserProfileCompleteness(user);
await _signInManager.SignInAsync(user, isPersistent: false);
return RedirectToAction(nameof(Index), new { Message = ManageMessageId.AddPhoneSuccess });
}
}
// If we got this far, something failed, redisplay the form
ModelState.AddModelError(string.Empty, "Failed to verify mobile phone number");
return View(model);
}
// GET: /Account/RemovePhoneNumber
[HttpGet]
public async Task<IActionResult> RemovePhoneNumber()
{
var user = await GetCurrentUser();
if (user != null)
{
var result = await _userManager.SetPhoneNumberAsync(user, null);
if (result.Succeeded)
{
await _signInManager.SignInAsync(user, isPersistent: false);
await UpdateUserProfileCompleteness(user);
return RedirectToAction(nameof(Index), new { Message = ManageMessageId.RemovePhoneSuccess });
}
}
return RedirectToAction(nameof(Index), new { Message = ManageMessageId.Error });
}
// GET: /Manage/ChangePassword
[HttpGet]
public IActionResult ChangePassword()
{
return View();
}
// POST: /Account/Manage
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> ChangePassword(ChangePasswordViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
var user = await GetCurrentUser();
if (user != null)
{
var result = await _userManager.ChangePasswordAsync(user, model.OldPassword, model.NewPassword);
if (result.Succeeded)
{
await _signInManager.SignInAsync(user, isPersistent: false);
return RedirectToAction(nameof(Index), new { Message = ManageMessageId.ChangePasswordSuccess });
}
AddErrorsToModelState(result);
return View(model);
}
return RedirectToAction(nameof(Index), new { Message = ManageMessageId.Error });
}
// GET: /Manage/ChangeEmail
[HttpGet]
public IActionResult ChangeEmail()
{
return View();
}
// POST: /Account/ChangeEmail
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> ChangeEmail(ChangeEmailViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
var user = await GetCurrentUser();
if (user != null)
{
if(!await _userManager.CheckPasswordAsync(user, model.Password))
{
ModelState.AddModelError(nameof(model.Password), "The password supplied is not correct");
return View(model);
}
var existingUser = await _userManager.FindByEmailAsync(model.NewEmail.Normalize());
if(existingUser != null)
{
// The username/email is already registered
ModelState.AddModelError(nameof(model.NewEmail), "The email supplied is already registered");
return View(model);
}
user.PendingNewEmail = model.NewEmail;
await _userManager.UpdateAsync(user);
await BuildCallbackUrlAndSendNewEmailAddressConfirmationEmail(user, model.NewEmail);
return RedirectToAction(nameof(EmailConfirmationSent));
}
return RedirectToAction(nameof(Index), new { Message = ManageMessageId.Error });
}
// GET: /Manage/ConfirmNewEmail
[HttpGet]
public async Task<IActionResult> ConfirmNewEmail(string token)
{
if (token == null)
{
return View(ERROR_VIEW);
}
var user = await GetCurrentUser();
if (user == null)
{
return View(ERROR_VIEW);
}
var result = await _userManager.ChangeEmailAsync(user, user.PendingNewEmail, token);
if(result.Succeeded)
{
await _userManager.SetUserNameAsync(user, user.PendingNewEmail);
user.PendingNewEmail = null;
await _userManager.UpdateAsync(user);
}
return RedirectToAction(nameof(Index), new { Message = ManageMessageId.ChangeEmailSuccess });
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> ResendChangeEmailConfirmation()
{
var user = await GetCurrentUser();
if(string.IsNullOrEmpty(user?.PendingNewEmail))
{
return View(ERROR_VIEW);
}
await BuildCallbackUrlAndSendNewEmailAddressConfirmationEmail(user, user.PendingNewEmail);
return RedirectToAction(nameof(EmailConfirmationSent));
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> CancelChangeEmail()
{
var user = await GetCurrentUser();
user.PendingNewEmail = null;
await _userManager.UpdateAsync(user);
return RedirectToAction(nameof(Index));
}
// GET: /Manage/SetPassword
[HttpGet]
public IActionResult SetPassword()
{
return View();
}
// POST: /Manage/SetPassword
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> SetPassword(SetPasswordViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
var user = await GetCurrentUser();
if (user != null)
{
var result = await _userManager.AddPasswordAsync(user, model.NewPassword);
if (result.Succeeded)
{
await _signInManager.SignInAsync(user, isPersistent: false);
return RedirectToAction(nameof(Index), new { Message = ManageMessageId.SetPasswordSuccess });
}
AddErrorsToModelState(result);
return View(model);
}
return RedirectToAction(nameof(Index), new { Message = ManageMessageId.Error });
}
//GET: /Account/Manage
[HttpGet]
public async Task<IActionResult> ManageLogins(ManageMessageId? message = null)
{
ViewData[STATUS_MESSAGE] =
message == ManageMessageId.RemoveLoginSuccess ? "The external login was removed."
: message == ManageMessageId.AddLoginSuccess ? "The external login was added."
: message == ManageMessageId.Error ? ERROR_OCCURRED
: "";
var user = await GetCurrentUser();
if (user == null)
{
return View(ERROR_VIEW);
}
var userLogins = await _userManager.GetLoginsAsync(user);
var schemes = await _signInManager.GetExternalAuthenticationSchemesAsync();
var otherLogins = schemes.Where(auth => userLogins.All(ul => auth.Name != ul.LoginProvider)).ToList();
ViewData[SHOW_REMOVE_BUTTON] = user.PasswordHash != null || userLogins.Count > 1;
return View(new ManageLoginsViewModel
{
CurrentLogins = userLogins,
OtherLogins = otherLogins
});
}
// POST: /Manage/LinkLogin
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult LinkLogin(string provider)
{
// Request a redirect to the external login provider to link a login for the current user
var redirectUrl = Url.Action(new UrlActionContext { Action = nameof(LinkLoginCallback), Controller = MANAGE_CONTROLLER });
var properties = _signInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl, _userManager.GetUserId(User));
return new ChallengeResult(provider, properties);
}
// GET: /Manage/LinkLoginCallback
[HttpGet]
public async Task<ActionResult> LinkLoginCallback()
{
var user = await GetCurrentUser();
if (user == null)
{
return View(ERROR_VIEW);
}
var info = await _signInManager.GetExternalLoginInfoAsync(_userManager.GetUserId(User));
if (info == null)
{
return RedirectToAction(nameof(ManageLogins), new { Message = ManageMessageId.Error });
}
var result = await _userManager.AddLoginAsync(user, info);
var message = result.Succeeded ? ManageMessageId.AddLoginSuccess : ManageMessageId.Error;
return RedirectToAction(nameof(ManageLogins), new { Message = message });
}
private async Task BuildCallbackUrlAndSendNewEmailAddressConfirmationEmail(ApplicationUser applicationUser, string userEmail)
{
var token = await _userManager.GenerateChangeEmailTokenAsync(applicationUser, userEmail);
var callbackUrl = Url.Action(new UrlActionContext { Action = nameof(ConfirmNewEmail), Controller = MANAGE_CONTROLLER, Values = new { token = token },
Protocol = HttpContext.Request.Scheme
});
await _mediator.SendAsync(new SendNewEmailAddressConfirmationEmail { Email = userEmail, CallbackUrl = callbackUrl });
}
private async Task GenerateChangePhoneNumberTokenAndSendAccountSecurityTokenSms(ApplicationUser applicationUser, string phoneNumber)
{
var token = await _userManager.GenerateChangePhoneNumberTokenAsync(applicationUser, phoneNumber);
await _mediator.SendAsync(new SendAccountSecurityTokenSms { PhoneNumber = phoneNumber, Token = token });
}
private async Task UpdateUserProfileCompleteness(ApplicationUser user)
{
if (user.IsProfileComplete())
{
await _mediator.SendAsync(new RemoveUserProfileIncompleteClaimCommand { UserId = user.Id });
await _signInManager.RefreshSignInAsync(user);
}
}
private void AddErrorsToModelState(IdentityResult result)
{
foreach (var error in result.Errors)
{
ModelState.AddModelError(string.Empty, error.Description);
}
}
public enum ManageMessageId
{
AddPhoneSuccess,
AddLoginSuccess,
ChangePasswordSuccess,
ChangeEmailSuccess,
SetTwoFactorSuccess,
SetPasswordSuccess,
RemoveLoginSuccess,
RemovePhoneSuccess,
Error
}
private async Task<ApplicationUser> GetCurrentUser()
{
return await _mediator.SendAsync(new UserByUserIdQuery { UserId = _userManager.GetUserId(User) });
}
//ViewData Constants
private const string SHOW_REMOVE_BUTTON = "ShowRemoveButton";
private const string STATUS_MESSAGE = "StatusMessage";
//Message Constants
private const string ERROR_OCCURRED = "An error has occurred.";
//Controller Names
private const string MANAGE_CONTROLLER = "Manage";
//View Names
private const string ERROR_VIEW = "Error";
}
}
| |
//
// MetadataResolver.cs
//
// Author:
// Jb Evain (jbevain@gmail.com)
//
// Copyright (c) 2008 - 2011 Jb Evain
//
// 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 Mono.Collections.Generic;
namespace Mono.Cecil
{
public interface IAssemblyResolver
{
AssemblyDefinition Resolve(AssemblyNameReference name);
AssemblyDefinition Resolve(AssemblyNameReference name, ReaderParameters parameters);
AssemblyDefinition Resolve(string fullName);
AssemblyDefinition Resolve(string fullName, ReaderParameters parameters);
event AssemblyResolveEventHandler ResolveFailure;
}
public interface IMetadataResolver
{
TypeDefinition Resolve(TypeReference type);
FieldDefinition Resolve(FieldReference field);
MethodDefinition Resolve(MethodReference method);
}
public class ResolutionException : Exception
{
readonly MemberReference member;
public MemberReference Member
{
get { return member; }
}
public ResolutionException(MemberReference member)
: base("Failed to resolve " + member.FullName)
{
this.member = member;
}
}
public class MetadataResolver : IMetadataResolver
{
readonly IAssemblyResolver assembly_resolver;
public IAssemblyResolver AssemblyResolver
{
get { return assembly_resolver; }
}
public MetadataResolver(IAssemblyResolver assemblyResolver)
{
if (assemblyResolver == null)
throw new ArgumentNullException("assemblyResolver");
assembly_resolver = assemblyResolver;
}
public virtual TypeDefinition Resolve(TypeReference type)
{
if (type == null)
throw new ArgumentNullException("type");
type = type.GetElementType();
var scope = type.Scope;
switch (scope.MetadataScopeType)
{
case MetadataScopeType.AssemblyNameReference:
var assembly = assembly_resolver.Resolve((AssemblyNameReference)scope);
if (assembly == null)
return null;
return GetType(assembly.MainModule, type);
case MetadataScopeType.ModuleDefinition:
return GetType((ModuleDefinition)scope, type);
case MetadataScopeType.ModuleReference:
var modules = type.Module.Assembly.Modules;
var module_ref = (ModuleReference)scope;
for (int i = 0; i < modules.Count; i++)
{
var netmodule = modules[i];
if (netmodule.Name == module_ref.Name)
return GetType(netmodule, type);
}
break;
}
throw new NotSupportedException();
}
static TypeDefinition GetType(ModuleDefinition module, TypeReference reference)
{
var type = GetTypeDefinition(module, reference);
if (type != null)
return type;
if (!module.HasExportedTypes)
return null;
var exported_types = module.ExportedTypes;
for (int i = 0; i < exported_types.Count; i++)
{
var exported_type = exported_types[i];
if (exported_type.Name != reference.Name)
continue;
if (exported_type.Namespace != reference.Namespace)
continue;
return exported_type.Resolve();
}
return null;
}
static TypeDefinition GetTypeDefinition(ModuleDefinition module, TypeReference type)
{
if (!type.IsNested)
return module.GetType(type.Namespace, type.Name);
var declaring_type = type.DeclaringType.Resolve();
if (declaring_type == null)
return null;
return Mixin.GetNestedType(declaring_type, type.Name);
}
public virtual FieldDefinition Resolve(FieldReference field)
{
if (field == null)
throw new ArgumentNullException("field");
var type = Resolve(field.DeclaringType);
if (type == null)
return null;
if (!type.HasFields)
return null;
return GetField(type, field);
}
FieldDefinition GetField(TypeDefinition type, FieldReference reference)
{
while (type != null)
{
var field = GetField(type.Fields, reference);
if (field != null)
return field;
if (type.BaseType == null)
return null;
type = Resolve(type.BaseType);
}
return null;
}
static FieldDefinition GetField(Collection<FieldDefinition> fields, FieldReference reference)
{
for (int i = 0; i < fields.Count; i++)
{
var field = fields[i];
if (field.Name != reference.Name)
continue;
if (!AreSame(field.FieldType, reference.FieldType))
continue;
return field;
}
return null;
}
public virtual MethodDefinition Resolve(MethodReference method)
{
if (method == null)
throw new ArgumentNullException("method");
var type = Resolve(method.DeclaringType);
if (type == null)
return null;
method = method.GetElementMethod();
if (!type.HasMethods)
return null;
return GetMethod(type, method);
}
MethodDefinition GetMethod(TypeDefinition type, MethodReference reference)
{
while (type != null)
{
var method = GetMethod(type.Methods, reference);
if (method != null)
return method;
if (type.BaseType == null)
return null;
type = Resolve(type.BaseType);
}
return null;
}
public static MethodDefinition GetMethod(Collection<MethodDefinition> methods, MethodReference reference)
{
for (int i = 0; i < methods.Count; i++)
{
var method = methods[i];
if (method.Name != reference.Name)
continue;
if (method.HasGenericParameters != reference.HasGenericParameters)
continue;
if (method.HasGenericParameters && method.GenericParameters.Count != reference.GenericParameters.Count)
continue;
if (!AreSame(method.ReturnType, reference.ReturnType))
continue;
if (method.HasParameters != reference.HasParameters)
continue;
if (!method.HasParameters && !reference.HasParameters)
return method;
if (!AreSame(method.Parameters, reference.Parameters))
continue;
return method;
}
return null;
}
static bool AreSame(Collection<ParameterDefinition> a, Collection<ParameterDefinition> b)
{
var count = a.Count;
if (count != b.Count)
return false;
if (count == 0)
return true;
for (int i = 0; i < count; i++)
if (!AreSame(a[i].ParameterType, b[i].ParameterType))
return false;
return true;
}
static bool AreSame(TypeSpecification a, TypeSpecification b)
{
if (!AreSame(a.ElementType, b.ElementType))
return false;
if (a.IsGenericInstance)
return AreSame((GenericInstanceType)a, (GenericInstanceType)b);
if (a.IsRequiredModifier || a.IsOptionalModifier)
return AreSame((IModifierType)a, (IModifierType)b);
if (a.IsArray)
return AreSame((ArrayType)a, (ArrayType)b);
return true;
}
static bool AreSame(ArrayType a, ArrayType b)
{
if (a.Rank != b.Rank)
return false;
// TODO: dimensions
return true;
}
static bool AreSame(IModifierType a, IModifierType b)
{
return AreSame(a.ModifierType, b.ModifierType);
}
static bool AreSame(GenericInstanceType a, GenericInstanceType b)
{
if (a.GenericArguments.Count != b.GenericArguments.Count)
return false;
for (int i = 0; i < a.GenericArguments.Count; i++)
if (!AreSame(a.GenericArguments[i], b.GenericArguments[i]))
return false;
return true;
}
static bool AreSame(GenericParameter a, GenericParameter b)
{
return a.Position == b.Position;
}
static bool AreSame(TypeReference a, TypeReference b)
{
if (ReferenceEquals(a, b))
return true;
if (a == null || b == null)
return false;
if (a.etype != b.etype)
return false;
if (a.IsGenericParameter)
return AreSame((GenericParameter)a, (GenericParameter)b);
if (Mixin.IsTypeSpecification(a))
return AreSame((TypeSpecification)a, (TypeSpecification)b);
if (a.Name != b.Name || a.Namespace != b.Namespace)
return false;
//TODO: check scope
return AreSame(a.DeclaringType, b.DeclaringType);
}
}
}
| |
using System;
using Csla;
using SelfLoadSoftDelete.DataAccess;
using SelfLoadSoftDelete.DataAccess.ERLevel;
namespace SelfLoadSoftDelete.Business.ERLevel
{
/// <summary>
/// G11_City_ReChild (editable child object).<br/>
/// This is a generated base class of <see cref="G11_City_ReChild"/> business object.
/// </summary>
/// <remarks>
/// This class is an item of <see cref="G10_City"/> collection.
/// </remarks>
[Serializable]
public partial class G11_City_ReChild : BusinessBase<G11_City_ReChild>
{
#region Business Properties
/// <summary>
/// Maintains metadata about <see cref="City_Child_Name"/> property.
/// </summary>
public static readonly PropertyInfo<string> City_Child_NameProperty = RegisterProperty<string>(p => p.City_Child_Name, "CityRoads Child Name");
/// <summary>
/// Gets or sets the CityRoads Child Name.
/// </summary>
/// <value>The CityRoads Child Name.</value>
public string City_Child_Name
{
get { return GetProperty(City_Child_NameProperty); }
set { SetProperty(City_Child_NameProperty, value); }
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Creates a new <see cref="G11_City_ReChild"/> object.
/// </summary>
/// <returns>A reference to the created <see cref="G11_City_ReChild"/> object.</returns>
internal static G11_City_ReChild NewG11_City_ReChild()
{
return DataPortal.CreateChild<G11_City_ReChild>();
}
/// <summary>
/// Factory method. Loads a <see cref="G11_City_ReChild"/> object, based on given parameters.
/// </summary>
/// <param name="city_ID2">The City_ID2 parameter of the G11_City_ReChild to fetch.</param>
/// <returns>A reference to the fetched <see cref="G11_City_ReChild"/> object.</returns>
internal static G11_City_ReChild GetG11_City_ReChild(int city_ID2)
{
return DataPortal.FetchChild<G11_City_ReChild>(city_ID2);
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="G11_City_ReChild"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public G11_City_ReChild()
{
// Use factory methods and do not use direct creation.
// show the framework that this is a child object
MarkAsChild();
}
#endregion
#region Data Access
/// <summary>
/// Loads default values for the <see cref="G11_City_ReChild"/> object properties.
/// </summary>
[Csla.RunLocal]
protected override void Child_Create()
{
var args = new DataPortalHookArgs();
OnCreate(args);
base.Child_Create();
}
/// <summary>
/// Loads a <see cref="G11_City_ReChild"/> object from the database, based on given criteria.
/// </summary>
/// <param name="city_ID2">The City ID2.</param>
protected void Child_Fetch(int city_ID2)
{
var args = new DataPortalHookArgs(city_ID2);
OnFetchPre(args);
using (var dalManager = DalFactorySelfLoadSoftDelete.GetManager())
{
var dal = dalManager.GetProvider<IG11_City_ReChildDal>();
var data = dal.Fetch(city_ID2);
Fetch(data);
}
OnFetchPost(args);
// check all object rules and property rules
BusinessRules.CheckRules();
}
/// <summary>
/// Loads a <see cref="G11_City_ReChild"/> object from the given <see cref="G11_City_ReChildDto"/>.
/// </summary>
/// <param name="data">The G11_City_ReChildDto to use.</param>
private void Fetch(G11_City_ReChildDto data)
{
// Value properties
LoadProperty(City_Child_NameProperty, data.City_Child_Name);
var args = new DataPortalHookArgs(data);
OnFetchRead(args);
}
/// <summary>
/// Inserts a new <see cref="G11_City_ReChild"/> object in the database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Insert(G10_City parent)
{
var dto = new G11_City_ReChildDto();
dto.Parent_City_ID = parent.City_ID;
dto.City_Child_Name = City_Child_Name;
using (var dalManager = DalFactorySelfLoadSoftDelete.GetManager())
{
var args = new DataPortalHookArgs(dto);
OnInsertPre(args);
var dal = dalManager.GetProvider<IG11_City_ReChildDal>();
using (BypassPropertyChecks)
{
var resultDto = dal.Insert(dto);
args = new DataPortalHookArgs(resultDto);
}
OnInsertPost(args);
}
}
/// <summary>
/// Updates in the database all changes made to the <see cref="G11_City_ReChild"/> object.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Update(G10_City parent)
{
if (!IsDirty)
return;
var dto = new G11_City_ReChildDto();
dto.Parent_City_ID = parent.City_ID;
dto.City_Child_Name = City_Child_Name;
using (var dalManager = DalFactorySelfLoadSoftDelete.GetManager())
{
var args = new DataPortalHookArgs(dto);
OnUpdatePre(args);
var dal = dalManager.GetProvider<IG11_City_ReChildDal>();
using (BypassPropertyChecks)
{
var resultDto = dal.Update(dto);
args = new DataPortalHookArgs(resultDto);
}
OnUpdatePost(args);
}
}
/// <summary>
/// Self deletes the <see cref="G11_City_ReChild"/> object from database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_DeleteSelf(G10_City parent)
{
using (var dalManager = DalFactorySelfLoadSoftDelete.GetManager())
{
var args = new DataPortalHookArgs();
OnDeletePre(args);
var dal = dalManager.GetProvider<IG11_City_ReChildDal>();
using (BypassPropertyChecks)
{
dal.Delete(parent.City_ID);
}
OnDeletePost(args);
}
}
#endregion
#region DataPortal Hooks
/// <summary>
/// Occurs after setting all defaults for object creation.
/// </summary>
partial void OnCreate(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation.
/// </summary>
partial void OnDeletePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after the delete operation, before Commit().
/// </summary>
partial void OnDeletePost(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the fetch operation.
/// </summary>
partial void OnFetchPre(DataPortalHookArgs args);
/// <summary>
/// Occurs after the fetch operation (object or collection is fully loaded and set up).
/// </summary>
partial void OnFetchPost(DataPortalHookArgs args);
/// <summary>
/// Occurs after the low level fetch operation, before the data reader is destroyed.
/// </summary>
partial void OnFetchRead(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the update operation.
/// </summary>
partial void OnUpdatePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit().
/// </summary>
partial void OnUpdatePost(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation.
/// </summary>
partial void OnInsertPre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit().
/// </summary>
partial void OnInsertPost(DataPortalHookArgs args);
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Runtime.InteropServices;
using System.Runtime.WindowsRuntime.Internal;
using System.Threading.Tasks;
using System.Threading;
using Windows.Foundation;
using Windows.Storage.Streams;
namespace System.IO
{
/// <summary>
/// An <code>wrapper</code> for a managed stream that implements all WinRT stream operations.
/// This class must not implement any WinRT stream interfaces directly.
/// We never create instances of this class directly; instead we use classes defined in
/// the region Interface adapters to implement WinRT ifaces and create instances of those types.
/// See comment in that region for technical details.
/// </summary>
internal abstract class NetFxToWinRtStreamAdapter : IDisposable
{
#region Construction
#region Interface adapters
// Instances of private types defined in this section will be returned from NetFxToWinRtStreamAdapter.Create(..).
// Depending on the capabilities of the .NET stream for which we need to construct the adapter, we need to return
// an object that can be QIed (COM speak for "cast") to a well-defined set of ifaces.
// E.g, if the specified stream CanRead, but not CanSeek and not CanWrite, then we *must* return an object that
// can be QIed to IInputStream, but *not* IRandomAccessStream and *not* IOutputStream.
// There are two ways to do that:
// - We could explicitly implement ICustomQueryInterface and respond to QI requests by analyzing the stream capabilities
// - We can use the runtime's ability to do that for us, based on the ifaces the concrete class implements (or does not).
// The latter is much more elegant, and likely also faster.
private class InputStream : NetFxToWinRtStreamAdapter, IInputStream, IDisposable
{
internal InputStream(Stream stream, StreamReadOperationOptimization readOptimization)
: base(stream, readOptimization)
{
}
}
private class OutputStream : NetFxToWinRtStreamAdapter, IOutputStream, IDisposable
{
internal OutputStream(Stream stream, StreamReadOperationOptimization readOptimization)
: base(stream, readOptimization)
{
}
}
private class RandomAccessStream : NetFxToWinRtStreamAdapter, IRandomAccessStream, IInputStream, IOutputStream, IDisposable
{
internal RandomAccessStream(Stream stream, StreamReadOperationOptimization readOptimization)
: base(stream, readOptimization)
{
}
}
private class InputOutputStream : NetFxToWinRtStreamAdapter, IInputStream, IOutputStream, IDisposable
{
internal InputOutputStream(Stream stream, StreamReadOperationOptimization readOptimization)
: base(stream, readOptimization)
{
}
}
#endregion Interface adapters
// We may want to define different behaviour for different types of streams.
// For instance, ReadAsync treats MemoryStream special for performance reasons.
// The enum 'StreamReadOperationOptimization' describes the read optimization to employ for a
// given NetFxToWinRtStreamAdapter instance. In future, we might define other enums to follow a
// similar pattern, e.g. 'StreamWriteOperationOptimization' or 'StreamFlushOperationOptimization'.
private enum StreamReadOperationOptimization
{
AbstractStream = 0, MemoryStream
}
internal static NetFxToWinRtStreamAdapter Create(Stream stream)
{
if (stream == null)
throw new ArgumentNullException(nameof(stream));
StreamReadOperationOptimization readOptimization = StreamReadOperationOptimization.AbstractStream;
if (stream.CanRead)
readOptimization = DetermineStreamReadOptimization(stream);
NetFxToWinRtStreamAdapter adapter;
if (stream.CanSeek)
adapter = new RandomAccessStream(stream, readOptimization);
else if (stream.CanRead && stream.CanWrite)
adapter = new InputOutputStream(stream, readOptimization);
else if (stream.CanRead)
adapter = new InputStream(stream, readOptimization);
else if (stream.CanWrite)
adapter = new OutputStream(stream, readOptimization);
else
throw new ArgumentException(SR.Argument_NotSufficientCapabilitiesToConvertToWinRtStream);
return adapter;
}
private static StreamReadOperationOptimization DetermineStreamReadOptimization(Stream stream)
{
Contract.Requires(stream != null);
if (CanApplyReadMemoryStreamOptimization(stream))
return StreamReadOperationOptimization.MemoryStream;
return StreamReadOperationOptimization.AbstractStream;
}
private static bool CanApplyReadMemoryStreamOptimization(Stream stream)
{
MemoryStream memStream = stream as MemoryStream;
if (memStream == null)
return false;
ArraySegment<byte> arrSeg;
return memStream.TryGetBuffer(out arrSeg);
}
private NetFxToWinRtStreamAdapter(Stream stream, StreamReadOperationOptimization readOptimization)
{
Contract.Requires(stream != null);
Contract.Requires(stream.CanRead || stream.CanWrite || stream.CanSeek);
Contract.EndContractBlock();
Debug.Assert(!stream.CanRead || (stream.CanRead && this is IInputStream));
Debug.Assert(!stream.CanWrite || (stream.CanWrite && this is IOutputStream));
Debug.Assert(!stream.CanSeek || (stream.CanSeek && this is IRandomAccessStream));
_readOptimization = readOptimization;
_managedStream = stream;
}
#endregion Construction
#region Instance variables
private Stream _managedStream = null;
private bool _leaveUnderlyingStreamOpen = true;
private readonly StreamReadOperationOptimization _readOptimization;
#endregion Instance variables
#region Tools and Helpers
/// <summary>
/// We keep tables for mappings between managed and WinRT streams to make sure to always return the same adapter for a given underlying stream.
/// However, in order to avoid global locks on those tables, several instances of this type may be created and then can race to be entered
/// into the appropriate map table. All except for the winning instances will be thrown away. However, we must ensure that when the losers are
/// finalized, they do not dispose the underlying stream. To ensure that, we must call this method on the winner to notify it that it is safe to
/// dispose the underlying stream.
/// </summary>
internal void SetWonInitializationRace()
{
_leaveUnderlyingStreamOpen = false;
}
public Stream GetManagedStream()
{
return _managedStream;
}
private Stream EnsureNotDisposed()
{
Stream str = _managedStream;
if (str == null)
{
ObjectDisposedException ex = new ObjectDisposedException(SR.ObjectDisposed_CannotPerformOperation);
ex.SetErrorCode(HResults.RO_E_CLOSED);
throw ex;
}
return str;
}
#endregion Tools and Helpers
#region Common public interface
/// <summary>Implements IDisposable.Dispose (IClosable.Close in WinRT)</summary>
void IDisposable.Dispose()
{
Stream str = _managedStream;
if (str == null)
return;
_managedStream = null;
if (!_leaveUnderlyingStreamOpen)
str.Dispose();
}
#endregion Common public interface
#region IInputStream public interface
public IAsyncOperationWithProgress<IBuffer, UInt32> ReadAsync(IBuffer buffer, UInt32 count, InputStreamOptions options)
{
if (buffer == null)
{
// Mapped to E_POINTER.
throw new ArgumentNullException(nameof(buffer));
}
if (count < 0 || Int32.MaxValue < count)
{
ArgumentOutOfRangeException ex = new ArgumentOutOfRangeException(nameof(count));
ex.SetErrorCode(HResults.E_INVALIDARG);
throw ex;
}
if (buffer.Capacity < count)
{
ArgumentException ex = new ArgumentException(SR.Argument_InsufficientBufferCapacity);
ex.SetErrorCode(HResults.E_INVALIDARG);
throw ex;
}
if (!(options == InputStreamOptions.None || options == InputStreamOptions.Partial || options == InputStreamOptions.ReadAhead))
{
ArgumentOutOfRangeException ex = new ArgumentOutOfRangeException(nameof(options),
SR.ArgumentOutOfRange_InvalidInputStreamOptionsEnumValue);
ex.SetErrorCode(HResults.E_INVALIDARG);
throw ex;
}
// Commented due to a reported CCRewrite bug. Should uncomment when fixed:
//Contract.Ensures(Contract.Result<IAsyncOperationWithProgress<IBuffer, UInt32>>() != null);
//Contract.EndContractBlock();
Stream str = EnsureNotDisposed();
IAsyncOperationWithProgress<IBuffer, UInt32> readAsyncOperation;
switch (_readOptimization)
{
case StreamReadOperationOptimization.MemoryStream:
readAsyncOperation = StreamOperationsImplementation.ReadAsync_MemoryStream(str, buffer, count);
break;
case StreamReadOperationOptimization.AbstractStream:
readAsyncOperation = StreamOperationsImplementation.ReadAsync_AbstractStream(str, buffer, count, options);
break;
// Use this pattern to add more optimisation options if necessary:
//case StreamReadOperationOptimization.XxxxStream:
// readAsyncOperation = StreamOperationsImplementation.ReadAsync_XxxxStream(str, buffer, count, options);
// break;
default:
Debug.Assert(false, "We should never get here. Someone forgot to handle an input stream optimisation option.");
readAsyncOperation = null;
break;
}
return readAsyncOperation;
}
#endregion IInputStream public interface
#region IOutputStream public interface
public IAsyncOperationWithProgress<UInt32, UInt32> WriteAsync(IBuffer buffer)
{
if (buffer == null)
{
// Mapped to E_POINTER.
throw new ArgumentNullException(nameof(buffer));
}
if (buffer.Capacity < buffer.Length)
{
ArgumentException ex = new ArgumentException(SR.Argument_BufferLengthExceedsCapacity);
ex.SetErrorCode(HResults.E_INVALIDARG);
throw ex;
}
// Commented due to a reported CCRewrite bug. Should uncomment when fixed:
//Contract.Ensures(Contract.Result<IAsyncOperationWithProgress<UInt32, UInt32>>() != null);
//Contract.EndContractBlock();
Stream str = EnsureNotDisposed();
return StreamOperationsImplementation.WriteAsync_AbstractStream(str, buffer);
}
public IAsyncOperation<Boolean> FlushAsync()
{
Contract.Ensures(Contract.Result<IAsyncOperation<Boolean>>() != null);
Contract.EndContractBlock();
Stream str = EnsureNotDisposed();
return StreamOperationsImplementation.FlushAsync_AbstractStream(str);
}
#endregion IOutputStream public interface
#region IRandomAccessStream public interface
#region IRandomAccessStream public interface: Not cloning related
public void Seek(UInt64 position)
{
if (position > Int64.MaxValue)
{
ArgumentException ex = new ArgumentException(SR.IO_CannotSeekBeyondInt64MaxValue);
ex.SetErrorCode(HResults.E_INVALIDARG);
throw ex;
}
// Commented due to a reported CCRewrite bug. Should uncomment when fixed:
//Contract.EndContractBlock();
Stream str = EnsureNotDisposed();
Int64 pos = unchecked((Int64)position);
Debug.Assert(str != null);
Debug.Assert(str.CanSeek, "The underlying str is expected to support Seek, but it does not.");
Debug.Assert(0 <= pos && pos <= Int64.MaxValue, "Unexpected pos=" + pos + ".");
str.Seek(pos, SeekOrigin.Begin);
}
public bool CanRead
{
get
{
Stream str = EnsureNotDisposed();
return str.CanRead;
}
}
public bool CanWrite
{
get
{
Stream str = EnsureNotDisposed();
return str.CanWrite;
}
}
public UInt64 Position
{
get
{
Contract.Ensures(Contract.Result<UInt64>() >= 0);
Stream str = EnsureNotDisposed();
return (UInt64)str.Position;
}
}
public UInt64 Size
{
get
{
Contract.Ensures(Contract.Result<UInt64>() >= 0);
Stream str = EnsureNotDisposed();
return (UInt64)str.Length;
}
set
{
if (value > Int64.MaxValue)
{
ArgumentException ex = new ArgumentException(SR.IO_CannotSetSizeBeyondInt64MaxValue);
ex.SetErrorCode(HResults.E_INVALIDARG);
throw ex;
}
// Commented due to a reported CCRewrite bug. Should uncomment when fixed:
//Contract.EndContractBlock();
Stream str = EnsureNotDisposed();
if (!str.CanWrite)
{
InvalidOperationException ex = new InvalidOperationException(SR.InvalidOperation_CannotSetStreamSizeCannotWrite);
ex.SetErrorCode(HResults.E_ILLEGAL_METHOD_CALL);
throw ex;
}
Int64 val = unchecked((Int64)value);
Debug.Assert(str != null);
Debug.Assert(str.CanSeek, "The underlying str is expected to support Seek, but it does not.");
Debug.Assert(0 <= val && val <= Int64.MaxValue, "Unexpected val=" + val + ".");
str.SetLength(val);
}
}
#endregion IRandomAccessStream public interface: Not cloning related
#region IRandomAccessStream public interface: Cloning related
// We do not want to support the cloning-related operation for now.
// They appear to mainly target corner-case scenarios in Windows itself,
// and are (mainly) a historical artefact of abandoned early designs
// for IRandonAccessStream.
// Cloning can be added in future, however, it would be quite complex
// to support it correctly for generic streams.
private static void ThrowCloningNotSuported(String methodName)
{
NotSupportedException nse = new NotSupportedException(SR.Format(SR.NotSupported_CloningNotSupported, methodName));
nse.SetErrorCode(HResults.E_NOTIMPL);
throw nse;
}
public IRandomAccessStream CloneStream()
{
ThrowCloningNotSuported("CloneStream");
return null;
}
public IInputStream GetInputStreamAt(UInt64 position)
{
ThrowCloningNotSuported("GetInputStreamAt");
return null;
}
public IOutputStream GetOutputStreamAt(UInt64 position)
{
ThrowCloningNotSuported("GetOutputStreamAt");
return null;
}
#endregion IRandomAccessStream public interface: Cloning related
#endregion IRandomAccessStream public interface
} // class NetFxToWinRtStreamAdapter
} // namespace
// NetFxToWinRtStreamAdapter.cs
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
using System;
using System.Numerics;
using System.Threading.Tasks;
namespace Algorithms
{
// This class contains renderers that use Vector (SIMD) floats
internal class VectorFloatRenderer : FractalRenderer
{
private const float limit = 4.0f;
public VectorFloatRenderer(Action<int, int, int> dp, Func<bool> abortFunc)
: base(dp, abortFunc)
{
}
// Render the fractal on a single thread using the ComplexFloatVec data type
// This is the implementation that has the best comments.
public void RenderSingleThreadedWithADT(float xmin, float xmax, float ymin, float ymax, float step)
{
// Initialize a pile of method constant vectors
Vector<int> vmax_iters = new Vector<int>(max_iters);
Vector<float> vlimit = new Vector<float>(limit);
Vector<float> vstep = new Vector<float>(step);
Vector<float> vxmax = new Vector<float>(xmax);
Vector<float> vinc = new Vector<float>((float)Vector<float>.Count * step);
// Use my little helper routine: it's kind of slow, but I find it pleasantly readable.
// The alternative would be this:
// float[] xmins = new float[Vector<float>.Count];
// for (int i = 0; i < xmins.Count; i++)
// xmins[i] = xmin + step * i;
// Vector<float> vxmin = new Vector<float>(xmins);
// Both allocate some memory, this one just does it in a separate routine :-)
Vector<float> vxmin = VectorHelper.Create(i => xmin + step * i);
float y = ymin;
int yp = 0;
for (Vector<float> vy = new Vector<float>(ymin);
y <= ymax && !Abort;
vy += vstep, y += step, yp++)
{
int xp = 0;
for (Vector<float> vx = vxmin;
Vector.LessThanOrEqualAny(vx, vxmax); // Vector.{comparision}Any|All return bools, not masks
vx += vinc, xp += Vector<int>.Count)
{
ComplexVecFloat num = new ComplexVecFloat(vx, vy);
ComplexVecFloat accum = num;
Vector<int> viters = Vector<int>.Zero; // Iteration counts start at all zeros
Vector<int> increment = Vector<int>.One; // Increment starts out as all ones
do
{
// This is work that can be vectorized
accum = accum.square() + num;
// Increment the iteration count Only pixels that haven't already hit the
// limit will be incremented because the increment variable gets masked below
viters += increment;
// Create a mask that correspons to the element-wise logical operation
// "accum <= limit && iters <= max_iters" Note that the bitwise and is used,
// because the Vector.{comparision} operations return masks, not boolean values
Vector<int> vCond = Vector.LessThanOrEqual(accum.sqabs(), vlimit) &
Vector.LessThanOrEqual(viters, vmax_iters);
// increment becomes zero for the elems that have hit the limit because
// vCond is a mask of all zeros or ones, based on the results of the
// Vector.{comparison} operations
increment = increment & vCond;
// Keep going until we have no elements that haven't either hit the value
// limit or the iteration count
} while (increment != Vector<int>.Zero);
// This is another little helper I created. It's definitely kind of slow but I
// find it pleasantly succinct. It could also be written like this:
//
// for (int eNum = 0; eNum < Vector<int>.Count; eNum++)
// DrawPixel(xp + eNum, yp, viters[eNum]);
//
// Neither implementation is particularly fast, because pulling individual elements
// is a slow operation for vector types.
viters.ForEach((iter, elemNum) => DrawPixel(xp + elemNum, yp, iter));
}
}
}
// Render the fractal on a single thread using raw Vector<float> data types
// For a well commented version, go see VectorFloatRenderer.RenderSingleThreadedWithADT
public void RenderSingleThreadedNoADT(float xmin, float xmax, float ymin, float ymax, float step)
{
Vector<int> vmax_iters = new Vector<int>(max_iters);
Vector<float> vlimit = new Vector<float>(limit);
Vector<float> vstep = new Vector<float>(step);
Vector<float> vxmax = new Vector<float>(xmax);
Vector<float> vinc = new Vector<float>((float)Vector<float>.Count * step);
Vector<float> vxmin = VectorHelper.Create(i => xmin + step * i);
float y = ymin;
int yp = 0;
for (Vector<float> vy = new Vector<float>(ymin); y <= ymax && !Abort; vy += vstep, y += step, yp++)
{
int xp = 0;
for (Vector<float> vx = vxmin; Vector.LessThanOrEqualAny(vx, vxmax); vx += vinc, xp += Vector<int>.Count)
{
Vector<float> accumx = vx;
Vector<float> accumy = vy;
Vector<int> viters = Vector<int>.Zero;
Vector<int> increment = Vector<int>.One;
do
{
Vector<float> naccumx = accumx * accumx - accumy * accumy;
Vector<float> naccumy = accumx * accumy + accumx * accumy;
accumx = naccumx + vx;
accumy = naccumy + vy;
viters += increment;
Vector<float> sqabs = accumx * accumx + accumy * accumy;
Vector<int> vCond = Vector.LessThanOrEqual(sqabs, vlimit) &
Vector.LessThanOrEqual(viters, vmax_iters);
increment = increment & vCond;
} while (increment != Vector<int>.Zero);
viters.ForEach((iter, elemNum) => DrawPixel(xp + elemNum, yp, (int)iter));
}
}
}
// Render the fractal on multiple threads using raw Vector<float> data types
// For a well commented version, go see VectorFloatRenderer.RenderSingleThreadedWithADT
public void RenderMultiThreadedNoADT(float xmin, float xmax, float ymin, float ymax, float step)
{
Vector<int> vmax_iters = new Vector<int>(max_iters);
Vector<float> vlimit = new Vector<float>(limit);
Vector<float> vstep = new Vector<float>(step);
Vector<float> vinc = new Vector<float>((float)Vector<float>.Count * step);
Vector<float> vxmax = new Vector<float>(xmax);
Vector<float> vxmin = VectorHelper.Create(i => xmin + step * i);
Parallel.For(0, (int)(((ymax - ymin) / step) + .5f), (yp) =>
{
if (Abort)
return;
Vector<float> vy = new Vector<float>(ymin + step * yp);
int xp = 0;
for (Vector<float> vx = vxmin; Vector.LessThanOrEqualAny(vx, vxmax); vx += vinc, xp += Vector<int>.Count)
{
Vector<float> accumx = vx;
Vector<float> accumy = vy;
Vector<int> viters = Vector<int>.Zero;
Vector<int> increment = Vector<int>.One;
do
{
Vector<float> naccumx = accumx * accumx - accumy * accumy;
Vector<float> XtimesY = accumx * accumy;
Vector<float> naccumy = XtimesY + XtimesY;
accumx = naccumx + vx;
accumy = naccumy + vy;
viters += increment;
Vector<float> sqabs = accumx * accumx + accumy * accumy;
Vector<int> vCond = Vector.LessThanOrEqual(sqabs, vlimit) &
Vector.LessThanOrEqual(viters, vmax_iters);
increment = increment & vCond;
} while (increment != Vector<int>.Zero);
viters.ForEach((iter, elemNum) => DrawPixel(xp + elemNum, yp, (int)iter));
}
});
}
// Render the fractal on multiple threads using the ComplexFloatVec data type
// For a well commented version, go see VectorFloatRenderer.RenderSingleThreadedWithADT
public void RenderMultiThreadedWithADT(float xmin, float xmax, float ymin, float ymax, float step)
{
Vector<int> vmax_iters = new Vector<int>(max_iters);
Vector<float> vlimit = new Vector<float>(limit);
Vector<float> vstep = new Vector<float>(step);
Vector<float> vinc = new Vector<float>((float)Vector<float>.Count * step);
Vector<float> vxmax = new Vector<float>(xmax);
Vector<float> vxmin = VectorHelper.Create(i => xmin + step * i);
Parallel.For(0, (int)(((ymax - ymin) / step) + .5f), (yp) =>
{
if (Abort)
return;
Vector<float> vy = new Vector<float>(ymin + step * yp);
int xp = 0;
for (Vector<float> vx = vxmin; Vector.LessThanOrEqualAny(vx, vxmax); vx += vinc, xp += Vector<int>.Count)
{
ComplexVecFloat num = new ComplexVecFloat(vx, vy);
ComplexVecFloat accum = num;
Vector<int> viters = Vector<int>.Zero;
Vector<int> increment = Vector<int>.One;
do
{
accum = accum.square() + num;
viters += increment;
Vector<int> vCond = Vector.LessThanOrEqual(accum.sqabs(), vlimit) &
Vector.LessThanOrEqual(viters, vmax_iters);
increment = increment & vCond;
} while (increment != Vector<int>.Zero);
viters.ForEach((iter, elemNum) => DrawPixel(xp + elemNum, yp, iter));
}
});
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure;
using Microsoft.Azure.Management.Automation;
using Microsoft.Azure.Management.Automation.Models;
namespace Microsoft.Azure.Management.Automation
{
public static partial class SoftwareUpdateConfigurationOperationsExtensions
{
/// <summary>
/// Create a softwareUpdateConfigurations. (see
/// http://aka.ms/azureautomationsdk/softwareUpdateConfigurationOperations
/// for more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Automation.ISoftwareUpdateConfigurationOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <param name='parameters'>
/// Required. The parameters supplied to the create or update of
/// software update configuration operation.
/// </param>
/// <returns>
/// The response model for the create or software update configuration
/// operation.
/// </returns>
public static SoftwareUpdateConfigurationCreateOrUpdateResponse CreateOrUpdate(this ISoftwareUpdateConfigurationOperations operations, string resourceGroupName, string automationAccount, SoftwareUpdateConfigurationCreateOrUpdateParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((ISoftwareUpdateConfigurationOperations)s).CreateOrUpdateAsync(resourceGroupName, automationAccount, parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Create a softwareUpdateConfigurations. (see
/// http://aka.ms/azureautomationsdk/softwareUpdateConfigurationOperations
/// for more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Automation.ISoftwareUpdateConfigurationOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <param name='parameters'>
/// Required. The parameters supplied to the create or update of
/// software update configuration operation.
/// </param>
/// <returns>
/// The response model for the create or software update configuration
/// operation.
/// </returns>
public static Task<SoftwareUpdateConfigurationCreateOrUpdateResponse> CreateOrUpdateAsync(this ISoftwareUpdateConfigurationOperations operations, string resourceGroupName, string automationAccount, SoftwareUpdateConfigurationCreateOrUpdateParameters parameters)
{
return operations.CreateOrUpdateAsync(resourceGroupName, automationAccount, parameters, CancellationToken.None);
}
/// <summary>
/// Delete the softwareUpdateConfigurations. (see
/// http://aka.ms/azureautomationsdk/softwareUpdateConfigurationOperations
/// for more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Automation.ISoftwareUpdateConfigurationOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <param name='softwareUpdateConfigurationName'>
/// Required. The name of softwareUpdateConfigurations.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static AzureOperationResponse Delete(this ISoftwareUpdateConfigurationOperations operations, string resourceGroupName, string automationAccount, string softwareUpdateConfigurationName)
{
return Task.Factory.StartNew((object s) =>
{
return ((ISoftwareUpdateConfigurationOperations)s).DeleteAsync(resourceGroupName, automationAccount, softwareUpdateConfigurationName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Delete the softwareUpdateConfigurations. (see
/// http://aka.ms/azureautomationsdk/softwareUpdateConfigurationOperations
/// for more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Automation.ISoftwareUpdateConfigurationOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <param name='softwareUpdateConfigurationName'>
/// Required. The name of softwareUpdateConfigurations.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static Task<AzureOperationResponse> DeleteAsync(this ISoftwareUpdateConfigurationOperations operations, string resourceGroupName, string automationAccount, string softwareUpdateConfigurationName)
{
return operations.DeleteAsync(resourceGroupName, automationAccount, softwareUpdateConfigurationName, CancellationToken.None);
}
/// <summary>
/// Retrieve the updateDeployment identified by
/// softwareUpdateConfigurations name. (see
/// http://aka.ms/azureautomationsdk/softwareUpdateConfigurationOperations
/// for more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Automation.ISoftwareUpdateConfigurationOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <param name='softwareUpdateConfigurationName'>
/// Required. The name of softwareUpdateConfigurations.
/// </param>
/// <returns>
/// The response model for the get software update configuration
/// operation.
/// </returns>
public static SoftwareUpdateConfigurationGetResponse Get(this ISoftwareUpdateConfigurationOperations operations, string resourceGroupName, string automationAccount, string softwareUpdateConfigurationName)
{
return Task.Factory.StartNew((object s) =>
{
return ((ISoftwareUpdateConfigurationOperations)s).GetAsync(resourceGroupName, automationAccount, softwareUpdateConfigurationName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Retrieve the updateDeployment identified by
/// softwareUpdateConfigurations name. (see
/// http://aka.ms/azureautomationsdk/softwareUpdateConfigurationOperations
/// for more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Automation.ISoftwareUpdateConfigurationOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <param name='softwareUpdateConfigurationName'>
/// Required. The name of softwareUpdateConfigurations.
/// </param>
/// <returns>
/// The response model for the get software update configuration
/// operation.
/// </returns>
public static Task<SoftwareUpdateConfigurationGetResponse> GetAsync(this ISoftwareUpdateConfigurationOperations operations, string resourceGroupName, string automationAccount, string softwareUpdateConfigurationName)
{
return operations.GetAsync(resourceGroupName, automationAccount, softwareUpdateConfigurationName, CancellationToken.None);
}
/// <summary>
/// Retrieve a list of softwareUpdateConfigurations. (see
/// http://aka.ms/azureautomationsdk/softwareUpdateConfigurationOperations
/// for more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Automation.ISoftwareUpdateConfigurationOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <returns>
/// The response model for the list software update configuration
/// operation.
/// </returns>
public static SoftwareUpdateConfigurationListResponse List(this ISoftwareUpdateConfigurationOperations operations, string resourceGroupName, string automationAccount)
{
return Task.Factory.StartNew((object s) =>
{
return ((ISoftwareUpdateConfigurationOperations)s).ListAsync(resourceGroupName, automationAccount);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Retrieve a list of softwareUpdateConfigurations. (see
/// http://aka.ms/azureautomationsdk/softwareUpdateConfigurationOperations
/// for more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Automation.ISoftwareUpdateConfigurationOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <returns>
/// The response model for the list software update configuration
/// operation.
/// </returns>
public static Task<SoftwareUpdateConfigurationListResponse> ListAsync(this ISoftwareUpdateConfigurationOperations operations, string resourceGroupName, string automationAccount)
{
return operations.ListAsync(resourceGroupName, automationAccount, CancellationToken.None);
}
/// <summary>
/// Retrieve next list of softwareUpdateConfigurations. (see
/// http://aka.ms/azureautomationsdk/softwareUpdateConfigurationOperations
/// for more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Automation.ISoftwareUpdateConfigurationOperations.
/// </param>
/// <param name='nextLink'>
/// Required. The link to retrieve next set of items.
/// </param>
/// <returns>
/// The response model for the list software update configuration
/// operation.
/// </returns>
public static SoftwareUpdateConfigurationListResponse ListNext(this ISoftwareUpdateConfigurationOperations operations, string nextLink)
{
return Task.Factory.StartNew((object s) =>
{
return ((ISoftwareUpdateConfigurationOperations)s).ListNextAsync(nextLink);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Retrieve next list of softwareUpdateConfigurations. (see
/// http://aka.ms/azureautomationsdk/softwareUpdateConfigurationOperations
/// for more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Automation.ISoftwareUpdateConfigurationOperations.
/// </param>
/// <param name='nextLink'>
/// Required. The link to retrieve next set of items.
/// </param>
/// <returns>
/// The response model for the list software update configuration
/// operation.
/// </returns>
public static Task<SoftwareUpdateConfigurationListResponse> ListNextAsync(this ISoftwareUpdateConfigurationOperations operations, string nextLink)
{
return operations.ListNextAsync(nextLink, CancellationToken.None);
}
}
}
| |
using System;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;
namespace SelfLoad.Business.ERLevel
{
/// <summary>
/// C04Level11 (editable child object).<br/>
/// This is a generated base class of <see cref="C04Level11"/> business object.
/// </summary>
/// <remarks>
/// This class contains one child collection:<br/>
/// - <see cref="C05Level111Objects"/> of type <see cref="C05Level111Coll"/> (1:M relation to <see cref="C06Level111"/>)<br/>
/// This class is an item of <see cref="C03Level11Coll"/> collection.
/// </remarks>
[Serializable]
public partial class C04Level11 : BusinessBase<C04Level11>
{
#region Static Fields
private static int _lastID;
#endregion
#region Business Properties
/// <summary>
/// Maintains metadata about <see cref="Level_1_1_ID"/> property.
/// </summary>
public static readonly PropertyInfo<int> Level_1_1_IDProperty = RegisterProperty<int>(p => p.Level_1_1_ID, "Level_1_1 ID");
/// <summary>
/// Gets the Level_1_1 ID.
/// </summary>
/// <value>The Level_1_1 ID.</value>
public int Level_1_1_ID
{
get { return GetProperty(Level_1_1_IDProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="Level_1_1_Name"/> property.
/// </summary>
public static readonly PropertyInfo<string> Level_1_1_NameProperty = RegisterProperty<string>(p => p.Level_1_1_Name, "Level_1_1 Name");
/// <summary>
/// Gets or sets the Level_1_1 Name.
/// </summary>
/// <value>The Level_1_1 Name.</value>
public string Level_1_1_Name
{
get { return GetProperty(Level_1_1_NameProperty); }
set { SetProperty(Level_1_1_NameProperty, value); }
}
/// <summary>
/// Maintains metadata about child <see cref="C05Level111SingleObject"/> property.
/// </summary>
public static readonly PropertyInfo<C05Level111Child> C05Level111SingleObjectProperty = RegisterProperty<C05Level111Child>(p => p.C05Level111SingleObject, "A5 Level111 Single Object", RelationshipTypes.Child);
/// <summary>
/// Gets the C05 Level111 Single Object ("self load" child property).
/// </summary>
/// <value>The C05 Level111 Single Object.</value>
public C05Level111Child C05Level111SingleObject
{
get { return GetProperty(C05Level111SingleObjectProperty); }
private set { LoadProperty(C05Level111SingleObjectProperty, value); }
}
/// <summary>
/// Maintains metadata about child <see cref="C05Level111ASingleObject"/> property.
/// </summary>
public static readonly PropertyInfo<C05Level111ReChild> C05Level111ASingleObjectProperty = RegisterProperty<C05Level111ReChild>(p => p.C05Level111ASingleObject, "A5 Level111 ASingle Object", RelationshipTypes.Child);
/// <summary>
/// Gets the C05 Level111 ASingle Object ("self load" child property).
/// </summary>
/// <value>The C05 Level111 ASingle Object.</value>
public C05Level111ReChild C05Level111ASingleObject
{
get { return GetProperty(C05Level111ASingleObjectProperty); }
private set { LoadProperty(C05Level111ASingleObjectProperty, value); }
}
/// <summary>
/// Maintains metadata about child <see cref="C05Level111Objects"/> property.
/// </summary>
public static readonly PropertyInfo<C05Level111Coll> C05Level111ObjectsProperty = RegisterProperty<C05Level111Coll>(p => p.C05Level111Objects, "A5 Level111 Objects", RelationshipTypes.Child);
/// <summary>
/// Gets the C05 Level111 Objects ("self load" child property).
/// </summary>
/// <value>The C05 Level111 Objects.</value>
public C05Level111Coll C05Level111Objects
{
get { return GetProperty(C05Level111ObjectsProperty); }
private set { LoadProperty(C05Level111ObjectsProperty, value); }
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Creates a new <see cref="C04Level11"/> object.
/// </summary>
/// <returns>A reference to the created <see cref="C04Level11"/> object.</returns>
internal static C04Level11 NewC04Level11()
{
return DataPortal.CreateChild<C04Level11>();
}
/// <summary>
/// Factory method. Loads a <see cref="C04Level11"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
/// <returns>A reference to the fetched <see cref="C04Level11"/> object.</returns>
internal static C04Level11 GetC04Level11(SafeDataReader dr)
{
C04Level11 obj = new C04Level11();
// show the framework that this is a child object
obj.MarkAsChild();
obj.Fetch(dr);
obj.MarkOld();
return obj;
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="C04Level11"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
private C04Level11()
{
// Prevent direct creation
// show the framework that this is a child object
MarkAsChild();
}
#endregion
#region Data Access
/// <summary>
/// Loads default values for the <see cref="C04Level11"/> object properties.
/// </summary>
[Csla.RunLocal]
protected override void Child_Create()
{
LoadProperty(Level_1_1_IDProperty, System.Threading.Interlocked.Decrement(ref _lastID));
LoadProperty(C05Level111SingleObjectProperty, DataPortal.CreateChild<C05Level111Child>());
LoadProperty(C05Level111ASingleObjectProperty, DataPortal.CreateChild<C05Level111ReChild>());
LoadProperty(C05Level111ObjectsProperty, DataPortal.CreateChild<C05Level111Coll>());
var args = new DataPortalHookArgs();
OnCreate(args);
base.Child_Create();
}
/// <summary>
/// Loads a <see cref="C04Level11"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
private void Fetch(SafeDataReader dr)
{
// Value properties
LoadProperty(Level_1_1_IDProperty, dr.GetInt32("Level_1_1_ID"));
LoadProperty(Level_1_1_NameProperty, dr.GetString("Level_1_1_Name"));
var args = new DataPortalHookArgs(dr);
OnFetchRead(args);
}
/// <summary>
/// Loads child objects.
/// </summary>
internal void FetchChildren()
{
LoadProperty(C05Level111SingleObjectProperty, C05Level111Child.GetC05Level111Child(Level_1_1_ID));
LoadProperty(C05Level111ASingleObjectProperty, C05Level111ReChild.GetC05Level111ReChild(Level_1_1_ID));
LoadProperty(C05Level111ObjectsProperty, C05Level111Coll.GetC05Level111Coll(Level_1_1_ID));
}
/// <summary>
/// Inserts a new <see cref="C04Level11"/> object in the database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Insert(C02Level1 parent)
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("AddC04Level11", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Level_1_ID", parent.Level_1_ID).DbType = DbType.Int32;
cmd.Parameters.AddWithValue("@Level_1_1_ID", ReadProperty(Level_1_1_IDProperty)).Direction = ParameterDirection.Output;
cmd.Parameters.AddWithValue("@Level_1_1_Name", ReadProperty(Level_1_1_NameProperty)).DbType = DbType.String;
var args = new DataPortalHookArgs(cmd);
OnInsertPre(args);
cmd.ExecuteNonQuery();
OnInsertPost(args);
LoadProperty(Level_1_1_IDProperty, (int) cmd.Parameters["@Level_1_1_ID"].Value);
}
FieldManager.UpdateChildren(this);
}
}
/// <summary>
/// Updates in the database all changes made to the <see cref="C04Level11"/> object.
/// </summary>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Update()
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
using (var cmd = new SqlCommand("UpdateC04Level11", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Level_1_1_ID", ReadProperty(Level_1_1_IDProperty)).DbType = DbType.Int32;
cmd.Parameters.AddWithValue("@Level_1_1_Name", ReadProperty(Level_1_1_NameProperty)).DbType = DbType.String;
var args = new DataPortalHookArgs(cmd);
OnUpdatePre(args);
cmd.ExecuteNonQuery();
OnUpdatePost(args);
}
FieldManager.UpdateChildren(this);
}
}
/// <summary>
/// Self deletes the <see cref="C04Level11"/> object from database.
/// </summary>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_DeleteSelf()
{
using (var ctx = ConnectionManager<SqlConnection>.GetManager("DeepLoad"))
{
// flushes all pending data operations
FieldManager.UpdateChildren(this);
using (var cmd = new SqlCommand("DeleteC04Level11", ctx.Connection))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Level_1_1_ID", ReadProperty(Level_1_1_IDProperty)).DbType = DbType.Int32;
var args = new DataPortalHookArgs(cmd);
OnDeletePre(args);
cmd.ExecuteNonQuery();
OnDeletePost(args);
}
}
// removes all previous references to children
LoadProperty(C05Level111SingleObjectProperty, DataPortal.CreateChild<C05Level111Child>());
LoadProperty(C05Level111ASingleObjectProperty, DataPortal.CreateChild<C05Level111ReChild>());
LoadProperty(C05Level111ObjectsProperty, DataPortal.CreateChild<C05Level111Coll>());
}
#endregion
#region Pseudo Events
/// <summary>
/// Occurs after setting all defaults for object creation.
/// </summary>
partial void OnCreate(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation.
/// </summary>
partial void OnDeletePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after the delete operation, before Commit().
/// </summary>
partial void OnDeletePost(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the fetch operation.
/// </summary>
partial void OnFetchPre(DataPortalHookArgs args);
/// <summary>
/// Occurs after the fetch operation (object or collection is fully loaded and set up).
/// </summary>
partial void OnFetchPost(DataPortalHookArgs args);
/// <summary>
/// Occurs after the low level fetch operation, before the data reader is destroyed.
/// </summary>
partial void OnFetchRead(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the update operation.
/// </summary>
partial void OnUpdatePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit().
/// </summary>
partial void OnUpdatePost(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation.
/// </summary>
partial void OnInsertPre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit().
/// </summary>
partial void OnInsertPost(DataPortalHookArgs args);
#endregion
}
}
| |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// File System.Windows.Media.VisualTreeHelper.cs
// Automatically generated contract file.
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Diagnostics.Contracts;
using System;
// Disable the "this variable is not used" warning as every field would imply it.
#pragma warning disable 0414
// Disable the "this variable is never assigned to".
#pragma warning disable 0067
// Disable the "this event is never assigned to".
#pragma warning disable 0649
// Disable the "this variable is never used".
#pragma warning disable 0169
// Disable the "new keyword not required" warning.
#pragma warning disable 0109
// Disable the "extern without DllImport" warning.
#pragma warning disable 0626
// Disable the "could hide other member" warning, can happen on certain properties.
#pragma warning disable 0108
namespace System.Windows.Media
{
static public partial class VisualTreeHelper
{
#region Methods and constructors
public static System.Windows.Media.Effects.BitmapEffect GetBitmapEffect(Visual reference)
{
Contract.Requires(reference != null);
// May return null
return default(System.Windows.Media.Effects.BitmapEffect);
}
public static System.Windows.Media.Effects.BitmapEffectInput GetBitmapEffectInput(Visual reference)
{
Contract.Requires(reference != null);
// May return null
return default(System.Windows.Media.Effects.BitmapEffectInput);
}
public static CacheMode GetCacheMode(Visual reference)
{
return default(CacheMode);
}
public static System.Windows.DependencyObject GetChild(System.Windows.DependencyObject reference, int childIndex)
{
Contract.Requires(reference != null);
Contract.Ensures(Contract.Result<System.Windows.DependencyObject>() != null);
return default(System.Windows.DependencyObject);
}
public static int GetChildrenCount(System.Windows.DependencyObject reference)
{
Contract.Requires(reference != null);
Contract.Ensures(Contract.Result<int>() >= 0);
return default(int);
}
public static Geometry GetClip(Visual reference)
{
Contract.Requires(reference != null);
// May return null
return default(Geometry);
}
public static System.Windows.Rect GetContentBounds(Visual reference)
{
Contract.Requires(reference != null);
return default(System.Windows.Rect);
}
public static System.Windows.Media.Media3D.Rect3D GetContentBounds(System.Windows.Media.Media3D.Visual3D reference)
{
Contract.Requires(reference != null);
return default(System.Windows.Media.Media3D.Rect3D);
}
public static System.Windows.Media.Media3D.Rect3D GetDescendantBounds(System.Windows.Media.Media3D.Visual3D reference)
{
Contract.Requires(reference != null);
return default(System.Windows.Media.Media3D.Rect3D);
}
public static System.Windows.Rect GetDescendantBounds(Visual reference)
{
Contract.Requires(reference != null);
return default(System.Windows.Rect);
}
public static DrawingGroup GetDrawing(Visual reference)
{
Contract.Requires(reference != null);
return default(DrawingGroup);
}
public static EdgeMode GetEdgeMode(Visual reference)
{
Contract.Requires(reference != null);
return default(EdgeMode);
}
public static System.Windows.Media.Effects.Effect GetEffect(Visual reference)
{
Contract.Requires(reference != null);
return default(System.Windows.Media.Effects.Effect);
}
public static System.Windows.Vector GetOffset(Visual reference)
{
Contract.Requires(reference != null);
return default(System.Windows.Vector);
}
public static double GetOpacity(Visual reference)
{
Contract.Requires(reference != null);
return default(double);
}
public static Brush GetOpacityMask(Visual reference)
{
Contract.Requires(reference != null);
return default(Brush);
}
public static System.Windows.DependencyObject GetParent(System.Windows.DependencyObject reference)
{
Contract.Requires(reference != null);
return default(System.Windows.DependencyObject);
}
public static Transform GetTransform(Visual reference)
{
Contract.Requires(reference != null);
return default(Transform);
}
public static DoubleCollection GetXSnappingGuidelines(Visual reference)
{
Contract.Requires(reference != null);
return default(DoubleCollection);
}
public static DoubleCollection GetYSnappingGuidelines(Visual reference)
{
Contract.Requires(reference != null);
return default(DoubleCollection);
}
public static void HitTest(System.Windows.Media.Media3D.Visual3D reference, HitTestFilterCallback filterCallback, HitTestResultCallback resultCallback, System.Windows.Media.Media3D.HitTestParameters3D hitTestParameters)
{
Contract.Requires(reference != null);
}
public static void HitTest(Visual reference, HitTestFilterCallback filterCallback, HitTestResultCallback resultCallback, HitTestParameters hitTestParameters)
{
Contract.Requires(reference != null);
}
public static HitTestResult HitTest(Visual reference, System.Windows.Point point)
{
Contract.Requires(reference != null);
return default(HitTestResult);
}
#endregion
}
}
| |
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 ResourcesServer.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>>
{
DefaultSampleObjectFactory,
};
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order,
/// stopping when the factory successfully returns a non-<see langref="null"/> object.
/// </summary>
/// <remarks>
/// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use
/// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and
/// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",
Justification = "This is an appropriate nesting of generic types")]
public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames.
// If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames.
// If still not found, try to get the sample provided for the specified mediaType and type.
// Finally, try to get the sample provided for the specified mediaType.
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create
/// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other
/// factories in <see cref="SampleObjectFactories"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")]
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// No specific object available, try our factories.
foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories)
{
if (factory == null)
{
continue;
}
try
{
sampleObject = factory(this, type);
if (sampleObject != null)
{
break;
}
}
catch
{
// Ignore any problems encountered in the factory; go on to the next one (if any).
}
}
}
return sampleObject;
}
/// <summary>
/// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The type.</returns>
public virtual Type ResolveHttpRequestMessageType(ApiDescription api)
{
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters);
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
UnwrapException(e).Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
internal static Exception UnwrapException(Exception exception)
{
AggregateException aggregateException = exception as AggregateException;
if (aggregateException != null)
{
return aggregateException.Flatten().InnerException;
}
return exception;
}
// Default factory for sample objects
private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type)
{
// Try to create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.IO;
using System.Reflection;
using System.Text.Json;
using System.Threading.Tasks;
using Azure.Identity;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading;
using Azure.Core.Pipeline;
using NUnit.Framework;
namespace Azure.Core.TestFramework
{
/// <summary>
/// Represents the ambient environment in which the test suite is
/// being run.
/// </summary>
public abstract class TestEnvironment
{
[EditorBrowsableAttribute(EditorBrowsableState.Never)]
public static string RepositoryRoot { get; }
public static string DevCertPath { get; }
public const string DevCertPassword = "password";
private static readonly Dictionary<Type, Task> s_environmentStateCache = new();
private readonly string _prefix;
private TokenCredential _credential;
private TestRecording _recording;
private readonly string _serviceName;
private Dictionary<string, string> _environmentFile;
private readonly string _serviceSdkDirectory;
private static readonly HashSet<Type> s_bootstrappingAttemptedTypes = new();
private static readonly object s_syncLock = new();
private static readonly bool s_isWindows = RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
private Exception _bootstrappingException;
private readonly Type _type;
private readonly ClientDiagnostics _clientDiagnostics;
protected TestEnvironment()
{
if (RepositoryRoot == null)
{
throw new InvalidOperationException("Unexpected error, repository root not found");
}
var testProject = GetSourcePath(GetType().Assembly);
var sdkDirectory = Path.GetFullPath(Path.Combine(RepositoryRoot, "sdk"));
_serviceName = Path.GetFullPath(testProject)
.Substring(sdkDirectory.Length)
.Trim(Path.DirectorySeparatorChar)
.Split(Path.DirectorySeparatorChar).FirstOrDefault();
if (string.IsNullOrWhiteSpace(_serviceName))
{
throw new InvalidOperationException($"Unable to determine the service name from test project path {testProject}");
}
_serviceSdkDirectory = Path.Combine(sdkDirectory, _serviceName);
if (!Directory.Exists(sdkDirectory))
{
throw new InvalidOperationException($"SDK directory {_serviceSdkDirectory} not found");
}
_prefix = _serviceName.ToUpperInvariant() + "_";
_type = GetType();
_clientDiagnostics = new ClientDiagnostics(ClientOptions.Default);
ParseEnvironmentFile();
}
private void ParseEnvironmentFile()
{
_environmentFile = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
var testEnvironmentFiles = new[]
{
Path.Combine(_serviceSdkDirectory, "test-resources.bicep.env"),
Path.Combine(_serviceSdkDirectory, "test-resources.json.env")
};
foreach (var testEnvironmentFile in testEnvironmentFiles)
{
if (File.Exists(testEnvironmentFile))
{
var json = JsonDocument.Parse(
ProtectedData.Unprotect(File.ReadAllBytes(testEnvironmentFile), null, DataProtectionScope.CurrentUser)
);
foreach (var property in json.RootElement.EnumerateObject())
{
_environmentFile[property.Name] = property.Value.GetString();
}
break;
}
}
}
static TestEnvironment()
{
// Traverse parent directories until we find an "artifacts" directory
// parent of that would become a repo root for test environment resolution purposes
var directoryInfo = new DirectoryInfo(Assembly.GetExecutingAssembly().Location);
while (directoryInfo.Name != "artifacts")
{
if (directoryInfo.Parent == null)
{
return;
}
directoryInfo = directoryInfo.Parent;
}
RepositoryRoot = directoryInfo?.Parent?.FullName;
DevCertPath = Path.Combine(
RepositoryRoot,
"eng",
"common",
"testproxy",
"dotnet-devcert.pfx");
}
public RecordedTestMode? Mode { get; set; }
/// <summary>
/// The name of the Azure subscription containing the resource group to be used for Live tests. Recorded.
/// </summary>
public string SubscriptionId => GetRecordedVariable("SUBSCRIPTION_ID");
/// <summary>
/// The name of the Azure resource group to be used for Live tests. Recorded.
/// </summary>
public string ResourceGroup => GetRecordedVariable("RESOURCE_GROUP");
/// <summary>
/// The location of the Azure resource group to be used for Live tests (e.g. westus2). Recorded.
/// </summary>
public string Location => GetRecordedVariable("LOCATION");
/// <summary>
/// The environment of the Azure resource group to be used for Live tests (e.g. AzureCloud). Recorded.
/// </summary>
public string AzureEnvironment => GetRecordedVariable("ENVIRONMENT");
/// <summary>
/// The name of the Azure Active Directory tenant that holds the service principal to use during Live tests. Recorded.
/// </summary>
public string TenantId => GetRecordedVariable("TENANT_ID");
/// <summary>
/// The URL of the Azure Resource Manager to be used for management plane operations. Recorded.
/// </summary>
public string ResourceManagerUrl => GetRecordedOptionalVariable("RESOURCE_MANAGER_URL");
/// <summary>
/// The URL of the Azure Service Management endpoint to be used for management plane authentication. Recorded.
/// </summary>
public string ServiceManagementUrl => GetRecordedOptionalVariable("SERVICE_MANAGEMENT_URL");
/// <summary>
/// The URL of the Azure Authority host to be used for authentication. Recorded.
/// </summary>
public string AuthorityHostUrl => GetRecordedOptionalVariable("AZURE_AUTHORITY_HOST") ?? AzureAuthorityHosts.AzurePublicCloud.ToString();
/// <summary>
/// The suffix for Azure Storage accounts for the active cloud environment, such as "core.windows.net". Recorded.
/// </summary>
public string StorageEndpointSuffix => GetRecordedOptionalVariable("STORAGE_ENDPOINT_SUFFIX");
/// <summary>
/// The client id of the Azure Active Directory service principal to use during Live tests. Recorded.
/// </summary>
public string ClientId => GetRecordedVariable("CLIENT_ID");
/// <summary>
/// The client secret of the Azure Active Directory service principal to use during Live tests. Not recorded.
/// </summary>
public string ClientSecret => GetVariable("CLIENT_SECRET");
public virtual TokenCredential Credential
{
get
{
if (_credential != null)
{
return _credential;
}
if (Mode == RecordedTestMode.Playback)
{
_credential = new MockCredential();
}
else
{
_credential = new ClientSecretCredential(
GetVariable("TENANT_ID"),
GetVariable("CLIENT_ID"),
GetVariable("CLIENT_SECRET"),
new ClientSecretCredentialOptions()
{
AuthorityHost = new Uri(GetVariable("AZURE_AUTHORITY_HOST"))
}
);
}
return _credential;
}
}
/// <summary>
/// Returns whether environment is ready to use. Should be overridden to provide service specific sampling scenario.
/// The test framework will wait until this returns true before starting tests.
/// Use this place to hook up logic that polls if eventual consistency has happened.
///
/// Return true if environment is ready to use.
/// Return false if environment is not ready to use and framework should wait.
/// Throw if you want to fail the run fast.
/// </summary>
/// <returns>Whether environment is ready to use.</returns>
protected virtual ValueTask<bool> IsEnvironmentReadyAsync()
{
return new ValueTask<bool>(true);
}
/// <summary>
/// Waits until environment becomes ready to use. See <see cref="IsEnvironmentReadyAsync"/> to define sampling scenario.
/// </summary>
/// <returns>A task.</returns>
public async ValueTask WaitForEnvironmentAsync()
{
Task task;
lock (s_environmentStateCache)
{
if (!s_environmentStateCache.TryGetValue(_type, out task))
{
task = WaitForEnvironmentInternalAsync();
s_environmentStateCache[_type] = task;
}
}
await task;
}
private async Task WaitForEnvironmentInternalAsync()
{
if (GlobalIsRunningInCI)
{
if (Mode == RecordedTestMode.Live)
{
int numberOfTries = 60;
TimeSpan delay = TimeSpan.FromSeconds(10);
for (int i = 0; i < numberOfTries; i++)
{
var isReady = await IsEnvironmentReadyAsync();
if (isReady)
{
return;
}
await Task.Delay(delay);
}
throw new InvalidOperationException(
"The environment has not become ready, check your TestEnvironment.IsEnvironmentReady scenario.");
}
}
else
{
await ExtendResourceGroupExpirationAsync();
}
}
private async Task ExtendResourceGroupExpirationAsync()
{
if (Mode is not RecordedTestMode.Live or RecordedTestMode.Record)
{
return;
}
// determine whether it is even possible to talk to the management endpoint
string resourceGroup = GetOptionalVariable("RESOURCE_GROUP");
if (resourceGroup == null)
{
return;
}
string subscription = GetOptionalVariable("SUBSCRIPTION_ID");
if (subscription == null)
{
return;
}
string tenantId = GetOptionalVariable("TENANT_ID");
string clientId = GetOptionalVariable("CLIENT_ID");
string clientSecret = GetOptionalVariable("CLIENT_SECRET");
string authorityHost = GetOptionalVariable("AZURE_AUTHORITY_HOST");
if (tenantId == null || clientId == null || clientSecret == null || authorityHost == null)
{
return;
}
// intentionally not using the Credential property as we don't want to throw if the env vars are not available, and we want to allow this to vary per environment.
var credential = new ClientSecretCredential(
tenantId,
clientId,
clientSecret,
new ClientSecretCredentialOptions()
{
AuthorityHost = new Uri(authorityHost)
});
HttpPipeline pipeline = HttpPipelineBuilder.Build(ClientOptions.Default, new BearerTokenAuthenticationPolicy(credential, "https://management.azure.com/.default"));
// create the GET request for the resource group information
Request request = pipeline.CreateRequest();
Uri uri = new Uri($"{ResourceManagerUrl}/subscriptions/{subscription}/resourcegroups/{resourceGroup}?api-version=2021-04-01");
request.Uri.Reset(uri);
request.Method = RequestMethod.Get;
// send the GET request
Response response = await pipeline.SendRequestAsync(request, CancellationToken.None);
// resource group not found - nothing we can do here
if (response.Status == 404)
{
return;
}
// unexpected response => throw an exception
if (response.Status != 200)
{
throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(response);
}
// parse the response
JsonElement json = JsonDocument.Parse(response.Content).RootElement;
if (json.TryGetProperty("tags", out JsonElement tags) && tags.TryGetProperty("DeleteAfter", out JsonElement deleteAfter))
{
DateTimeOffset deleteDto = DateTimeOffset.Parse(deleteAfter.GetString());
if (deleteDto.Subtract(DateTimeOffset.Now) < TimeSpan.FromDays(5))
{
// construct the JSON to send for PATCH request
using var stream = new MemoryStream();
var writer = new Utf8JsonWriter(stream);
writer.WriteStartObject();
writer.WritePropertyName("tags");
writer.WriteStartObject();
// even though this is a PATCH operation, we still need to include all other tags
// otherwise they will be deleted.
foreach (JsonProperty property in tags.EnumerateObject())
{
if (property.NameEquals("DeleteAfter"))
{
DateTimeOffset newTime = deleteDto.AddDays(5);
writer.WriteString("DeleteAfter", newTime);
}
else
{
property.WriteTo(writer);
}
}
writer.WriteEndObject();
writer.WriteEndObject();
writer.Flush();
// create the PATCH request
request = pipeline.CreateRequest();
request.Uri.Reset(uri);
request.Method = RequestMethod.Patch;
request.Headers.SetValue("Content-Type", "application/json");
stream.Position = 0;
request.Content = RequestContent.Create(stream);
// send the PATCH request
response = await pipeline.SendRequestAsync(request, CancellationToken.None);
if (response.Status != 200)
{
throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(response);
}
}
}
}
/// <summary>
/// Returns and records an environment variable value when running live or recorded value during playback.
/// </summary>
protected string GetRecordedOptionalVariable(string name)
{
return GetRecordedOptionalVariable(name, _ => { });
}
/// <summary>
/// Returns and records an environment variable value when running live or recorded value during playback.
/// </summary>
protected string GetRecordedOptionalVariable(string name, Action<RecordedVariableOptions> options)
{
if (Mode == RecordedTestMode.Playback)
{
return GetRecordedValue(name);
}
string value = GetOptionalVariable(name);
if (Mode is null or RecordedTestMode.Live)
{
return value;
}
if (_recording == null)
{
throw new InvalidOperationException("Recorded value should not be set outside the test method invocation");
}
// If the value was populated, sanitize before recording it.
string sanitizedValue = value;
if (!string.IsNullOrEmpty(value))
{
var optionsInstance = new RecordedVariableOptions();
options?.Invoke(optionsInstance);
sanitizedValue = optionsInstance.Apply(sanitizedValue);
}
_recording?.SetVariable(name, sanitizedValue);
return value;
}
/// <summary>
/// Returns and records an environment variable value when running live or recorded value during playback.
/// Throws when variable is not found.
/// </summary>
protected string GetRecordedVariable(string name)
{
return GetRecordedVariable(name, null);
}
/// <summary>
/// Returns and records an environment variable value when running live or recorded value during playback.
/// Throws when variable is not found.
/// </summary>
protected string GetRecordedVariable(string name, Action<RecordedVariableOptions> options)
{
var value = GetRecordedOptionalVariable(name, options);
if (value == null)
{
BootStrapTestResources();
value = GetRecordedOptionalVariable(name, options);
}
EnsureValue(name, value);
return value;
}
/// <summary>
/// Returns an environment variable value or null when variable is not found.
/// </summary>
protected string GetOptionalVariable(string name)
{
var prefixedName = _prefix + name;
// Prefixed name overrides non-prefixed
var value = Environment.GetEnvironmentVariable(prefixedName);
if (value == null)
{
_environmentFile.TryGetValue(prefixedName, out value);
}
if (value == null)
{
value = Environment.GetEnvironmentVariable(name);
}
if (value == null)
{
value = Environment.GetEnvironmentVariable($"AZURE_{name}");
}
if (value == null)
{
_environmentFile.TryGetValue(name, out value);
}
return value;
}
/// <summary>
/// Returns an environment variable value.
/// Throws when variable is not found.
/// </summary>
protected string GetVariable(string name)
{
var value = GetOptionalVariable(name);
if (value == null)
{
BootStrapTestResources();
value = GetOptionalVariable(name);
}
EnsureValue(name, value);
return value;
}
private void EnsureValue(string name, string value)
{
if (value == null)
{
string prefixedName = _prefix + name;
string message = $"Unable to find environment variable {prefixedName} or {name} required by test." + Environment.NewLine +
"Make sure the test environment was initialized using the eng/common/TestResources/New-TestResources.ps1 script.";
if (_bootstrappingException != null)
{
message += Environment.NewLine + "Resource creation failed during the test run. Make sure PowerShell version 6 or higher is installed.";
throw new InvalidOperationException(
message,
_bootstrappingException);
}
throw new InvalidOperationException(message);
}
}
public void SetRecording(TestRecording recording)
{
_credential = null;
_recording = recording;
}
private string GetRecordedValue(string name)
{
if (_recording == null)
{
throw new InvalidOperationException("Recorded value should not be retrieved outside the test method invocation");
}
return _recording.GetVariable(name, null);
}
internal static string GetSourcePath(Assembly assembly)
{
if (assembly == null)
throw new ArgumentNullException(nameof(assembly));
var testProject = assembly.GetCustomAttributes<AssemblyMetadataAttribute>().Single(a => a.Key == "SourcePath").Value;
if (string.IsNullOrEmpty(testProject))
{
throw new InvalidOperationException($"Unable to determine the test directory for {assembly}");
}
return testProject;
}
/// <summary>
/// Determines if the current environment is Azure DevOps.
/// </summary>
public static bool GlobalIsRunningInCI => Environment.GetEnvironmentVariable("TF_BUILD") != null;
/// <summary>
/// Determines if the current global test mode.
/// </summary>
internal static RecordedTestMode GlobalTestMode
{
get
{
string modeString = TestContext.Parameters["TestMode"] ?? Environment.GetEnvironmentVariable("AZURE_TEST_MODE");
RecordedTestMode mode = RecordedTestMode.Playback;
if (!string.IsNullOrEmpty(modeString))
{
mode = (RecordedTestMode)Enum.Parse(typeof(RecordedTestMode), modeString, true);
}
return mode;
}
}
/// <summary>
/// Determines if tests that use <see cref="ClientTestFixtureAttribute"/> should only test the latest version.
/// </summary>
internal static bool GlobalTestOnlyLatestVersion
{
get
{
string switchString = TestContext.Parameters["OnlyLiveTestLatestServiceVersion"] ?? Environment.GetEnvironmentVariable("AZURE_ONLY_TEST_LATEST_SERVICE_VERSION");
bool.TryParse(switchString, out bool onlyTestLatestServiceVersion);
return onlyTestLatestServiceVersion;
}
}
/// <summary>
/// Determines service versions that would be tested in tests that use <see cref="ClientTestFixtureAttribute"/>.
/// NOTE: this variable only narrows the set of versions defined in the attribute
/// </summary>
internal static string[] GlobalTestServiceVersions
{
get
{
string switchString = TestContext.Parameters["LiveTestServiceVersions"] ?? Environment.GetEnvironmentVariable("AZURE_LIVE_TEST_SERVICE_VERSIONS") ?? string.Empty;
return switchString.Split(new char[] {',', ';'}, StringSplitOptions.RemoveEmptyEntries);
}
}
/// <summary>
/// Determines if tests that use <see cref="RecordedTestAttribute"/> should try to re-record on failure.
/// </summary>
internal static bool GlobalDisableAutoRecording
{
get
{
string switchString = TestContext.Parameters["DisableAutoRecording"] ?? Environment.GetEnvironmentVariable("AZURE_DISABLE_AUTO_RECORDING");
bool.TryParse(switchString, out bool disableAutoRecording);
return disableAutoRecording || GlobalIsRunningInCI;
}
}
/// <summary>
/// Determines whether to enable the test framework to proxy traffic through fiddler.
/// </summary>
internal static bool EnableFiddler
{
get
{
string switchString = TestContext.Parameters["EnableFiddler"] ??
Environment.GetEnvironmentVariable("AZURE_ENABLE_FIDDLER");
bool.TryParse(switchString, out bool enableFiddler);
return enableFiddler;
}
}
private void BootStrapTestResources()
{
lock (s_syncLock)
{
try
{
if (!s_isWindows ||
s_bootstrappingAttemptedTypes.Contains(_type) ||
Mode == RecordedTestMode.Playback ||
GlobalIsRunningInCI)
{
return;
}
string path = Path.Combine(
RepositoryRoot,
"eng",
"scripts",
$"New-TestResources-Bootstrapper.ps1 {_serviceName}");
var processInfo = new ProcessStartInfo(
@"pwsh.exe",
path)
{
UseShellExecute = true
};
Process process = null;
try
{
process = Process.Start(processInfo);
}
catch (Exception ex)
{
_bootstrappingException = ex;
}
if (process != null)
{
process.WaitForExit();
ParseEnvironmentFile();
}
}
finally
{
s_bootstrappingAttemptedTypes.Add(_type);
}
}
}
}
}
| |
// 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.Linq;
using System.Net.Test.Common;
using System.Security.Principal;
using System.Text;
using System.Threading.Tasks;
using Xunit;
namespace System.Net.Security.Tests
{
[PlatformSpecific(TestPlatforms.Windows)] // NegotiateStream only supports client-side functionality on Unix
public abstract class NegotiateStreamStreamToStreamTest
{
private readonly byte[] _sampleMsg = Encoding.UTF8.GetBytes("Sample Test Message");
protected abstract Task AuthenticateAsClientAsync(NegotiateStream client, NetworkCredential credential, string targetName);
protected abstract Task AuthenticateAsServerAsync(NegotiateStream server);
[Fact]
public void NegotiateStream_StreamToStream_Authentication_Success()
{
VirtualNetwork network = new VirtualNetwork();
using (var clientStream = new VirtualNetworkStream(network, isServer: false))
using (var serverStream = new VirtualNetworkStream(network, isServer: true))
using (var client = new NegotiateStream(clientStream))
using (var server = new NegotiateStream(serverStream))
{
Assert.False(client.IsAuthenticated);
Assert.False(server.IsAuthenticated);
Task[] auth = new Task[2];
auth[0] = AuthenticateAsClientAsync(client, CredentialCache.DefaultNetworkCredentials, string.Empty);
auth[1] = AuthenticateAsServerAsync(server);
bool finished = Task.WaitAll(auth, TestConfiguration.PassingTestTimeoutMilliseconds);
Assert.True(finished, "Handshake completed in the allotted time");
// Expected Client property values:
Assert.True(client.IsAuthenticated);
Assert.Equal(TokenImpersonationLevel.Identification, client.ImpersonationLevel);
Assert.Equal(true, client.IsEncrypted);
Assert.Equal(false, client.IsMutuallyAuthenticated);
Assert.Equal(false, client.IsServer);
Assert.Equal(true, client.IsSigned);
Assert.Equal(false, client.LeaveInnerStreamOpen);
IIdentity serverIdentity = client.RemoteIdentity;
Assert.Equal("NTLM", serverIdentity.AuthenticationType);
Assert.Equal(false, serverIdentity.IsAuthenticated);
Assert.Equal("", serverIdentity.Name);
// Expected Server property values:
Assert.True(server.IsAuthenticated);
Assert.Equal(TokenImpersonationLevel.Identification, server.ImpersonationLevel);
Assert.Equal(true, server.IsEncrypted);
Assert.Equal(false, server.IsMutuallyAuthenticated);
Assert.Equal(true, server.IsServer);
Assert.Equal(true, server.IsSigned);
Assert.Equal(false, server.LeaveInnerStreamOpen);
IIdentity clientIdentity = server.RemoteIdentity;
Assert.Equal("NTLM", clientIdentity.AuthenticationType);
Assert.Equal(true, clientIdentity.IsAuthenticated);
IdentityValidator.AssertIsCurrentIdentity(clientIdentity);
}
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "https://github.com/dotnet/corefx/issues/19379")]
public void NegotiateStream_StreamToStream_Authentication_TargetName_Success()
{
string targetName = "testTargetName";
VirtualNetwork network = new VirtualNetwork();
using (var clientStream = new VirtualNetworkStream(network, isServer: false))
using (var serverStream = new VirtualNetworkStream(network, isServer: true))
using (var client = new NegotiateStream(clientStream))
using (var server = new NegotiateStream(serverStream))
{
Assert.False(client.IsAuthenticated);
Assert.False(server.IsAuthenticated);
Task[] auth = new Task[2];
auth[0] = AuthenticateAsClientAsync(client, CredentialCache.DefaultNetworkCredentials, targetName);
auth[1] = AuthenticateAsServerAsync(server);
bool finished = Task.WaitAll(auth, TestConfiguration.PassingTestTimeoutMilliseconds);
Assert.True(finished, "Handshake completed in the allotted time");
// Expected Client property values:
Assert.True(client.IsAuthenticated);
Assert.Equal(TokenImpersonationLevel.Identification, client.ImpersonationLevel);
Assert.Equal(true, client.IsEncrypted);
Assert.Equal(false, client.IsMutuallyAuthenticated);
Assert.Equal(false, client.IsServer);
Assert.Equal(true, client.IsSigned);
Assert.Equal(false, client.LeaveInnerStreamOpen);
IIdentity serverIdentity = client.RemoteIdentity;
Assert.Equal("NTLM", serverIdentity.AuthenticationType);
Assert.Equal(true, serverIdentity.IsAuthenticated);
Assert.Equal(targetName, serverIdentity.Name);
// Expected Server property values:
Assert.True(server.IsAuthenticated);
Assert.Equal(TokenImpersonationLevel.Identification, server.ImpersonationLevel);
Assert.Equal(true, server.IsEncrypted);
Assert.Equal(false, server.IsMutuallyAuthenticated);
Assert.Equal(true, server.IsServer);
Assert.Equal(true, server.IsSigned);
Assert.Equal(false, server.LeaveInnerStreamOpen);
IIdentity clientIdentity = server.RemoteIdentity;
Assert.Equal("NTLM", clientIdentity.AuthenticationType);
Assert.Equal(true, clientIdentity.IsAuthenticated);
IdentityValidator.AssertIsCurrentIdentity(clientIdentity);
}
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, ".NET Core difference in behavior: https://github.com/dotnet/corefx/issues/5241")]
public void NegotiateStream_StreamToStream_Authentication_EmptyCredentials_Fails()
{
string targetName = "testTargetName";
// Ensure there is no confusion between DefaultCredentials / DefaultNetworkCredentials and a
// NetworkCredential object with empty user, password and domain.
NetworkCredential emptyNetworkCredential = new NetworkCredential("", "", "");
Assert.NotEqual(emptyNetworkCredential, CredentialCache.DefaultCredentials);
Assert.NotEqual(emptyNetworkCredential, CredentialCache.DefaultNetworkCredentials);
VirtualNetwork network = new VirtualNetwork();
using (var clientStream = new VirtualNetworkStream(network, isServer: false))
using (var serverStream = new VirtualNetworkStream(network, isServer: true))
using (var client = new NegotiateStream(clientStream))
using (var server = new NegotiateStream(serverStream))
{
Assert.False(client.IsAuthenticated);
Assert.False(server.IsAuthenticated);
Task[] auth = new Task[2];
auth[0] = AuthenticateAsClientAsync(client, emptyNetworkCredential, targetName);
auth[1] = AuthenticateAsServerAsync(server);
bool finished = Task.WaitAll(auth, TestConfiguration.PassingTestTimeoutMilliseconds);
Assert.True(finished, "Handshake completed in the allotted time");
// Expected Client property values:
Assert.True(client.IsAuthenticated);
Assert.Equal(TokenImpersonationLevel.Identification, client.ImpersonationLevel);
Assert.Equal(true, client.IsEncrypted);
Assert.Equal(false, client.IsMutuallyAuthenticated);
Assert.Equal(false, client.IsServer);
Assert.Equal(true, client.IsSigned);
Assert.Equal(false, client.LeaveInnerStreamOpen);
IIdentity serverIdentity = client.RemoteIdentity;
Assert.Equal("NTLM", serverIdentity.AuthenticationType);
Assert.Equal(true, serverIdentity.IsAuthenticated);
Assert.Equal(targetName, serverIdentity.Name);
// Expected Server property values:
Assert.True(server.IsAuthenticated);
Assert.Equal(TokenImpersonationLevel.Identification, server.ImpersonationLevel);
Assert.Equal(true, server.IsEncrypted);
Assert.Equal(false, server.IsMutuallyAuthenticated);
Assert.Equal(true, server.IsServer);
Assert.Equal(true, server.IsSigned);
Assert.Equal(false, server.LeaveInnerStreamOpen);
IIdentity clientIdentity = server.RemoteIdentity;
Assert.Equal("NTLM", clientIdentity.AuthenticationType);
// TODO #5241: Behavior difference:
Assert.Equal(false, clientIdentity.IsAuthenticated);
// On .Net Desktop: Assert.Equal(true, clientIdentity.IsAuthenticated);
IdentityValidator.AssertHasName(clientIdentity, @"NT AUTHORITY\ANONYMOUS LOGON");
}
}
[Fact]
public void NegotiateStream_StreamToStream_Successive_ClientWrite_Sync_Success()
{
byte[] recvBuf = new byte[_sampleMsg.Length];
VirtualNetwork network = new VirtualNetwork();
using (var clientStream = new VirtualNetworkStream(network, isServer: false))
using (var serverStream = new VirtualNetworkStream(network, isServer: true))
using (var client = new NegotiateStream(clientStream))
using (var server = new NegotiateStream(serverStream))
{
Assert.False(client.IsAuthenticated);
Assert.False(server.IsAuthenticated);
Task[] auth = new Task[2];
auth[0] = AuthenticateAsClientAsync(client, CredentialCache.DefaultNetworkCredentials, string.Empty);
auth[1] = AuthenticateAsServerAsync(server);
bool finished = Task.WaitAll(auth, TestConfiguration.PassingTestTimeoutMilliseconds);
Assert.True(finished, "Handshake completed in the allotted time");
client.Write(_sampleMsg, 0, _sampleMsg.Length);
server.Read(recvBuf, 0, _sampleMsg.Length);
Assert.True(_sampleMsg.SequenceEqual(recvBuf));
client.Write(_sampleMsg, 0, _sampleMsg.Length);
server.Read(recvBuf, 0, _sampleMsg.Length);
Assert.True(_sampleMsg.SequenceEqual(recvBuf));
}
}
[Fact]
public void NegotiateStream_StreamToStream_Successive_ClientWrite_Async_Success()
{
byte[] recvBuf = new byte[_sampleMsg.Length];
VirtualNetwork network = new VirtualNetwork();
using (var clientStream = new VirtualNetworkStream(network, isServer: false))
using (var serverStream = new VirtualNetworkStream(network, isServer: true))
using (var client = new NegotiateStream(clientStream))
using (var server = new NegotiateStream(serverStream))
{
Assert.False(client.IsAuthenticated);
Assert.False(server.IsAuthenticated);
Task[] auth = new Task[2];
auth[0] = AuthenticateAsClientAsync(client, CredentialCache.DefaultNetworkCredentials, string.Empty);
auth[1] = AuthenticateAsServerAsync(server);
bool finished = Task.WaitAll(auth, TestConfiguration.PassingTestTimeoutMilliseconds);
Assert.True(finished, "Handshake completed in the allotted time");
auth[0] = client.WriteAsync(_sampleMsg, 0, _sampleMsg.Length);
auth[1] = server.ReadAsync(recvBuf, 0, _sampleMsg.Length);
finished = Task.WaitAll(auth, TestConfiguration.PassingTestTimeoutMilliseconds);
Assert.True(finished, "Send/receive completed in the allotted time");
Assert.True(_sampleMsg.SequenceEqual(recvBuf));
auth[0] = client.WriteAsync(_sampleMsg, 0, _sampleMsg.Length);
auth[1] = server.ReadAsync(recvBuf, 0, _sampleMsg.Length);
finished = Task.WaitAll(auth, TestConfiguration.PassingTestTimeoutMilliseconds);
Assert.True(finished, "Send/receive completed in the allotted time");
Assert.True(_sampleMsg.SequenceEqual(recvBuf));
}
}
[Fact]
public void NegotiateStream_StreamToStream_Flush_Propagated()
{
VirtualNetwork network = new VirtualNetwork();
using (var stream = new VirtualNetworkStream(network, isServer: false))
using (var negotiateStream = new NegotiateStream(stream))
{
Assert.False(stream.HasBeenSyncFlushed);
negotiateStream.Flush();
Assert.True(stream.HasBeenSyncFlushed);
}
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Relies on FlushAsync override not available in desktop")]
public void NegotiateStream_StreamToStream_FlushAsync_Propagated()
{
VirtualNetwork network = new VirtualNetwork();
using (var stream = new VirtualNetworkStream(network, isServer: false))
using (var negotiateStream = new NegotiateStream(stream))
{
Task task = negotiateStream.FlushAsync();
Assert.False(task.IsCompleted);
stream.CompleteAsyncFlush();
Assert.True(task.IsCompleted);
}
}
}
public sealed class NegotiateStreamStreamToStreamTest_Async : NegotiateStreamStreamToStreamTest
{
protected override Task AuthenticateAsClientAsync(NegotiateStream client, NetworkCredential credential, string targetName) =>
client.AuthenticateAsClientAsync(credential, targetName);
protected override Task AuthenticateAsServerAsync(NegotiateStream server) =>
server.AuthenticateAsServerAsync();
}
public sealed class NegotiateStreamStreamToStreamTest_BeginEnd : NegotiateStreamStreamToStreamTest
{
protected override Task AuthenticateAsClientAsync(NegotiateStream client, NetworkCredential credential, string targetName) =>
Task.Factory.FromAsync(client.BeginAuthenticateAsClient, client.EndAuthenticateAsClient, credential, targetName, null);
protected override Task AuthenticateAsServerAsync(NegotiateStream server) =>
Task.Factory.FromAsync(server.BeginAuthenticateAsServer, server.EndAuthenticateAsServer, null);
}
public sealed class NegotiateStreamStreamToStreamTest_Sync : NegotiateStreamStreamToStreamTest
{
protected override Task AuthenticateAsClientAsync(NegotiateStream client, NetworkCredential credential, string targetName) =>
Task.Run(() => client.AuthenticateAsClient(credential, targetName));
protected override Task AuthenticateAsServerAsync(NegotiateStream server) =>
Task.Run(() => server.AuthenticateAsServer());
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using StardewValley;
using StardewValley.Menus;
namespace Pathoschild.Stardew.Common.UI
{
/// <summary>A dropdown UI component which lets the player choose from a list of values.</summary>
/// <typeparam name="TValue">The item value type.</typeparam>
internal class DropdownList<TValue> : ClickableComponent
{
/*********
** Fields
*********/
/****
** Constants
****/
/// <summary>The padding applied to dropdown lists.</summary>
private const int DropdownPadding = 5;
/****
** Items
****/
/// <summary>The selected option.</summary>
private DropListOption SelectedOption;
/// <summary>The options in the list.</summary>
private readonly DropListOption[] Options;
/// <summary>The item index shown at the top of the list.</summary>
private int FirstVisibleIndex;
/// <summary>The maximum items to display.</summary>
private int MaxItems;
/// <summary>The item index shown at the bottom of the list.</summary>
private int LastVisibleIndex => this.FirstVisibleIndex + this.MaxItems - 1;
/// <summary>The maximum index that can be shown at the top of the list.</summary>
private int MaxFirstVisibleIndex => this.Options.Length - this.MaxItems;
/// <summary>Whether the player can scroll up in the list.</summary>
private bool CanScrollUp => this.FirstVisibleIndex > 0;
/// <summary>Whether the player can scroll down in the list.</summary>
private bool CanScrollDown => this.FirstVisibleIndex < this.MaxFirstVisibleIndex;
/****
** Rendering
****/
/// <summary>The font with which to render text.</summary>
private readonly SpriteFont Font;
/// <summary>The up arrow to scroll results.</summary>
private ClickableTextureComponent UpArrow;
/// <summary>The bottom arrow to scroll results.</summary>
private ClickableTextureComponent DownArrow;
/*********
** Accessors
*********/
/// <summary>The selected value.</summary>
public TValue SelectedValue => this.SelectedOption.Value;
/// <summary>The display label for the selected value.</summary>
public string SelectedLabel => this.SelectedOption.label;
/// <summary>The maximum height for the possible labels.</summary>
public int MaxLabelHeight { get; }
/// <summary>The maximum width for the possible labels.</summary>
public int MaxLabelWidth { get; private set; }
/// <summary>The <see cref="ClickableComponent.myID"/> value for the top entry in the dropdown.</summary>
public int TopComponentId => this.Options.First(p => p.visible).myID;
/*********
** Public methods
*********/
/// <summary>Construct an instance.</summary>
/// <param name="selectedValue">The selected value.</param>
/// <param name="items">The items in the list.</param>
/// <param name="getLabel">Get the display label for an item.</param>
/// <param name="x">The X-position from which to render the list.</param>
/// <param name="y">The Y-position from which to render the list.</param>
/// <param name="font">The font with which to render text.</param>
public DropdownList(TValue selectedValue, TValue[] items, Func<TValue, string> getLabel, int x, int y, SpriteFont font)
: base(new Rectangle(), nameof(DropdownList<TValue>))
{
// save values
this.Options = items
.Select((item, index) => new DropListOption(Rectangle.Empty, index, getLabel(item), item, font))
.ToArray();
this.Font = font;
this.MaxLabelHeight = this.Options.Max(p => p.LabelHeight);
// set initial selection
int selectedIndex = Array.IndexOf(items, selectedValue);
this.SelectedOption = selectedIndex >= 0
? this.Options[selectedIndex]
: this.Options.First();
// initialize UI
this.bounds.X = x;
this.bounds.Y = y;
this.ReinitializeComponents();
}
/// <summary>A method invoked when the player scrolls the dropdown using the mouse wheel.</summary>
/// <param name="direction">The scroll direction.</param>
public void ReceiveScrollWheelAction(int direction)
{
this.Scroll(direction > 0 ? -1 : 1); // scrolling down moves first item up
}
/// <summary>Handle a click at the given position, if applicable.</summary>
/// <param name="x">The X-position that was clicked.</param>
/// <param name="y">The Y-position that was clicked.</param>
/// <param name="itemClicked">Whether a dropdown item was clicked.</param>
/// <returns>Returns whether the click was handled.</returns>
public bool TryClick(int x, int y, out bool itemClicked)
{
// dropdown value
var option = this.Options.FirstOrDefault(p => p.visible && p.containsPoint(x, y));
if (option != null)
{
this.SelectedOption = option;
itemClicked = true;
return true;
}
itemClicked = false;
// arrows
if (this.UpArrow.containsPoint(x, y))
{
this.Scroll(-1);
return true;
}
if (this.DownArrow.containsPoint(x, y))
{
this.Scroll(1);
return true;
}
return false;
}
/// <summary>Select an item in the list matching the given value.</summary>
/// <param name="value">The value to search.</param>
/// <returns>Returns whether an item was selected.</returns>
public bool TrySelect(TValue value)
{
var entry = this.Options.FirstOrDefault(p =>
(p.Value == null && value == null)
|| p.Value?.Equals(value) == true
);
if (entry == null)
return false;
this.SelectedOption = entry;
return true;
}
/// <summary>Get whether the dropdown list contains the given UI pixel position.</summary>
/// <param name="x">The UI X position.</param>
/// <param name="y">The UI Y position.</param>
public override bool containsPoint(int x, int y)
{
return
base.containsPoint(x, y)
|| this.UpArrow.containsPoint(x, y)
|| this.DownArrow.containsPoint(x, y);
}
/// <summary>Render the UI.</summary>
/// <param name="sprites">The sprites to render.</param>
/// <param name="opacity">The opacity at which to draw.</param>
public void Draw(SpriteBatch sprites, float opacity = 1)
{
// draw dropdown items
foreach (DropListOption option in this.Options)
{
if (!option.visible)
continue;
// draw background
if (option.containsPoint(Game1.getMouseX(), Game1.getMouseY()))
sprites.Draw(CommonSprites.DropDown.Sheet, option.bounds, CommonSprites.DropDown.HoverBackground, Color.White * opacity);
else if (option.Index == this.SelectedOption.Index)
sprites.Draw(CommonSprites.DropDown.Sheet, option.bounds, CommonSprites.DropDown.ActiveBackground, Color.White * opacity);
else
sprites.Draw(CommonSprites.DropDown.Sheet, option.bounds, CommonSprites.DropDown.InactiveBackground, Color.White * opacity);
// draw text
Vector2 position = new Vector2(option.bounds.X + DropdownList<TValue>.DropdownPadding, option.bounds.Y + Game1.tileSize / 16);
sprites.DrawString(this.Font, option.label, position, Color.Black * opacity);
}
// draw up/down arrows
if (this.CanScrollUp)
this.UpArrow.draw(sprites, Color.White * opacity, 1);
if (this.CanScrollDown)
this.DownArrow.draw(sprites, Color.White * opacity, 1);
}
/// <summary>Recalculate dimensions and components for rendering.</summary>
public void ReinitializeComponents()
{
int x = this.bounds.X;
int y = this.bounds.Y;
// get item size
int itemWidth = this.MaxLabelWidth = Math.Max(this.Options.Max(p => p.LabelWidth), Game1.tileSize * 2) + DropdownList<TValue>.DropdownPadding * 2;
int itemHeight = this.MaxLabelHeight;
// get pagination
this.MaxItems = Math.Min((Game1.uiViewport.Height - y) / itemHeight, this.Options.Length);
this.FirstVisibleIndex = this.GetValidFirstItem(this.FirstVisibleIndex, this.MaxFirstVisibleIndex);
// get dropdown size
this.bounds.Width = itemWidth;
this.bounds.Height = itemHeight * this.MaxItems;
// update components
{
int itemY = y;
foreach (var option in this.Options)
{
option.visible = option.Index >= this.FirstVisibleIndex && option.Index <= this.LastVisibleIndex;
if (option.visible)
{
option.bounds = new Rectangle(x, itemY, itemWidth, itemHeight);
itemY += itemHeight;
}
}
}
// add arrows
{
Rectangle upSource = CommonSprites.Icons.UpArrow;
Rectangle downSource = CommonSprites.Icons.DownArrow;
this.UpArrow = new ClickableTextureComponent("up-arrow", new Rectangle(x - upSource.Width, y, upSource.Width, upSource.Height), "", "", CommonSprites.Icons.Sheet, upSource, 1);
this.DownArrow = new ClickableTextureComponent("down-arrow", new Rectangle(x - downSource.Width, y + this.bounds.Height - downSource.Height, downSource.Width, downSource.Height), "", "", CommonSprites.Icons.Sheet, downSource, 1);
}
// update controller flow
this.ReinitializeControllerFlow();
}
/// <summary>Set the fields to support controller snapping.</summary>
public void ReinitializeControllerFlow()
{
int firstIndex = this.FirstVisibleIndex;
int lastIndex = this.LastVisibleIndex;
int initialId = 1_100_000;
foreach (var option in this.Options)
{
int index = option.Index;
int id = initialId + index;
option.myID = id;
option.upNeighborID = index > firstIndex
? id - 1
: -99999;
option.downNeighborID = index < lastIndex
? id + 1
: -1;
}
}
/// <summary>Get the nested components for controller snapping.</summary>
public IEnumerable<ClickableComponent> GetChildComponents()
{
return this.Options;
}
/*********
** Private methods
*********/
/// <summary>Scroll the dropdown by the specified amount.</summary>
/// <param name="amount">The number of items to scroll.</param>
private void Scroll(int amount)
{
// recalculate first item
int firstItem = this.GetValidFirstItem(this.FirstVisibleIndex + amount, this.MaxFirstVisibleIndex);
if (firstItem == this.FirstVisibleIndex)
return;
this.FirstVisibleIndex = firstItem;
// update displayed items
this.ReinitializeComponents();
}
/// <summary>Calculate a valid index for the first displayed item in the list.</summary>
/// <param name="value">The initial value, which may not be valid.</param>
/// <param name="maxIndex">The maximum first index.</param>
private int GetValidFirstItem(int value, int maxIndex)
{
return Math.Max(Math.Min(value, maxIndex), 0);
}
/*********
** Private models
*********/
/// <summary>A clickable option in the dropdown.</summary>
private class DropListOption : ClickableComponent
{
/*********
** Accessors
*********/
/// <summary>The option's index in the list.</summary>
public int Index { get; }
/// <summary>The option value.</summary>
public TValue Value { get; }
/// <summary>The label text width in pixels.</summary>
public int LabelWidth { get; }
/// <summary>The label text height in pixels.</summary>
public int LabelHeight { get; }
/*********
** Public methods
*********/
/// <summary>Construct an instance.</summary>
/// <param name="bounds">The pixel bounds on screen.</param>
/// <param name="index">The option's index in the list.</param>
/// <param name="label">The display text.</param>
/// <param name="value">The option value.</param>
/// <param name="font">The font with which to measure the label.</param>
public DropListOption(Rectangle bounds, int index, string label, TValue value, SpriteFont font)
: base(bounds: bounds, name: index.ToString(), label: label)
{
this.Index = index;
this.Value = value;
Vector2 labelSize = font.MeasureString(label);
this.LabelWidth = (int)labelSize.X;
this.LabelHeight = (int)labelSize.Y;
}
}
}
}
| |
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
using Microsoft.Azure.Commands.Common.Authentication.Abstractions;
using Microsoft.Azure.Commands.Common.Authentication.Models;
using Microsoft.Azure.Commands.Management.Storage.Models;
using Microsoft.Azure.Management.Compute.Models;
using Microsoft.Azure.Management.Storage;
using Microsoft.Azure.Management.Storage.Models;
using Microsoft.WindowsAzure.Commands.Common.Storage;
using Microsoft.WindowsAzure.Commands.Storage.Adapters;
using Microsoft.WindowsAzure.Commands.Utilities.Common;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Auth;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Management.Automation;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.Xml.Serialization;
namespace Microsoft.Azure.Commands.Compute.Common
{
public static class DiagnosticsHelper
{
private static string EncodedXmlCfg = "xmlCfg";
private static string WadCfg = "WadCfg";
private static string WadCfgBlob = "WadCfgBlob";
private static string StorageType = "StorageType";
private static string StorageAccount = "storageAccount";
private static string Path = "path";
private static string ExpandResourceDirectory = "expandResourceDirectory";
private static string LocalResourceDirectory = "localResourceDirectory";
private static string StorageAccountNameTag = "storageAccountName";
private static string StorageAccountKeyTag = "storageAccountKey";
private static string StorageAccountEndPointTag = "storageAccountEndPoint";
private static string StorageAccountSASTokenTag = "storageAccountSasToken";
public static string XmlNamespace = "http://schemas.microsoft.com/ServiceHosting/2010/10/DiagnosticsConfiguration";
public static string DiagnosticsConfigurationElemStr = "DiagnosticsConfiguration";
public static string DiagnosticMonitorConfigurationElemStr = "DiagnosticMonitorConfiguration";
public static string PublicConfigElemStr = "PublicConfig";
public static string PrivateConfigElemStr = "PrivateConfig";
public static string StorageAccountElemStr = "StorageAccount";
public static string PrivConfNameAttr = "name";
public static string PrivConfKeyAttr = "key";
public static string PrivConfEndpointAttr = "endpoint";
public static string PrivConfSasKeyAttr = "sasToken";
public static string MetricsElemStr = "Metrics";
public static string MetricsResourceIdAttr = "resourceId";
public static string EventHubElemStr = "EventHub";
public static string EventHubUrlAttr = "Url";
public static string EventHubSharedAccessKeyNameAttr = "SharedAccessKeyName";
public static string EventHubSharedAccessKeyAttr = "SharedAccessKey";
private enum WadStorageType
{
Table,
Blob,
TableAndBlob
}
public enum ConfigFileType
{
Unknown,
Json,
Xml
}
public static ConfigFileType GetConfigFileType(string configurationPath)
{
if (!string.IsNullOrEmpty(configurationPath))
{
try
{
XmlDocument doc = new XmlDocument();
doc.Load(configurationPath);
return ConfigFileType.Xml;
}
catch (XmlException)
{ }
try
{
JsonConvert.DeserializeObject(File.ReadAllText(configurationPath));
return ConfigFileType.Json;
}
catch (JsonReaderException)
{ }
}
return ConfigFileType.Unknown;
}
public static Hashtable GetPublicDiagnosticsConfigurationFromFile(string configurationPath,
string storageAccountName, string resourceId, Cmdlet cmdlet)
{
switch (GetConfigFileType(configurationPath))
{
case ConfigFileType.Xml:
return GetPublicConfigFromXmlFile(configurationPath, storageAccountName, resourceId, cmdlet);
case ConfigFileType.Json:
return GetPublicConfigFromJsonFile(configurationPath, storageAccountName, resourceId, cmdlet);
default:
throw new ArgumentException(Properties.Resources.DiagnosticsExtensionInvalidConfigFileFormat);
}
}
private static Hashtable GetPublicConfigFromXmlFile(string configurationPath, string storageAccountName, string resourceId, Cmdlet cmdlet)
{
var doc = XDocument.Load(configurationPath);
var wadCfgElement = doc.Descendants().FirstOrDefault(d => d.Name.LocalName == WadCfg);
var wadCfgBlobElement = doc.Descendants().FirstOrDefault(d => d.Name.LocalName == WadCfgBlob);
if (wadCfgElement == null && wadCfgBlobElement == null)
{
throw new ArgumentException(Properties.Resources.DiagnosticsExtensionIaaSConfigElementNotDefinedInXml);
}
if (wadCfgElement != null)
{
AutoFillMetricsConfig(wadCfgElement, resourceId, cmdlet);
}
string originalConfiguration = wadCfgElement != null ? wadCfgElement.ToString() : wadCfgBlobElement.ToString();
string encodedConfiguration = Convert.ToBase64String(Encoding.UTF8.GetBytes(wadCfgElement.ToString().ToCharArray()));
// Now extract the local resource directory element
var node = doc.Descendants().FirstOrDefault(e => e.Name.LocalName == "LocalResourceDirectory");
string localDirectory = (node != null && node.Attribute(Path) != null) ? node.Attribute(Path).Value : null;
string localDirectoryExpand = (node != null && node.Attribute("expandEnvironment") != null)
? node.Attribute("expandEnvironment").Value
: null;
if (localDirectoryExpand == "0")
{
localDirectoryExpand = "false";
}
if (localDirectoryExpand == "1")
{
localDirectoryExpand = "true";
}
var hashTable = new Hashtable();
hashTable.Add(EncodedXmlCfg, encodedConfiguration);
hashTable.Add(StorageAccount, storageAccountName);
if (!string.IsNullOrEmpty(localDirectory))
{
var localDirectoryHashTable = new Hashtable();
localDirectoryHashTable.Add(Path, localDirectory);
localDirectoryHashTable.Add(ExpandResourceDirectory, localDirectoryExpand);
hashTable.Add(LocalResourceDirectory, localDirectoryHashTable);
}
var storageTypeElement = doc.Descendants().FirstOrDefault(d => d.Name.LocalName == StorageType);
if (storageTypeElement != null)
{
string storageType = storageTypeElement.Value;
WadStorageType wadStorageType;
if (!Enum.TryParse<WadStorageType>(storageType, out wadStorageType))
{
throw new ArgumentException(StorageType);
}
hashTable.Add(StorageType, storageTypeElement.Value);
}
return hashTable;
}
private static void AutoFillMetricsConfig(XElement wadCfgElement, string resourceId, Cmdlet cmdlet)
{
if (string.IsNullOrEmpty(resourceId))
{
return;
}
var configurationElem = wadCfgElement.Elements().FirstOrDefault(d => d.Name.LocalName == DiagnosticMonitorConfigurationElemStr);
if (configurationElem == null)
{
throw new ArgumentException(Properties.Resources.DiagnosticsExtensionDiagnosticMonitorConfigurationElementNotDefined);
}
var metricsElement = configurationElem.Elements().FirstOrDefault(d => d.Name.LocalName == MetricsElemStr);
if (metricsElement == null)
{
XNamespace ns = XmlNamespace;
metricsElement = new XElement(ns + MetricsElemStr,
new XAttribute(MetricsResourceIdAttr, resourceId));
configurationElem.Add(metricsElement);
}
else
{
var resourceIdAttr = metricsElement.Attribute(MetricsResourceIdAttr);
if (resourceIdAttr != null && !resourceIdAttr.Value.Equals(resourceId))
{
cmdlet.WriteWarning(Properties.Resources.DiagnosticsExtensionMetricsResourceIdNotMatch);
}
metricsElement.SetAttributeValue(MetricsResourceIdAttr, resourceId);
}
}
private static Hashtable GetPublicConfigFromJsonFile(string configurationPath, string storageAccountName, string resourceId, Cmdlet cmdlet)
{
var publicConfig = GetPublicConfigJObjectFromJsonFile(configurationPath);
var properties = publicConfig.Properties().Select(p => p.Name);
var wadCfgProperty = properties.FirstOrDefault(p => p.Equals(WadCfg, StringComparison.OrdinalIgnoreCase));
var wadCfgBlobProperty = properties.FirstOrDefault(p => p.Equals(WadCfgBlob, StringComparison.OrdinalIgnoreCase));
var xmlCfgProperty = properties.FirstOrDefault(p => p.Equals(EncodedXmlCfg, StringComparison.OrdinalIgnoreCase));
var storageAccountProperty = properties.FirstOrDefault(p => p.Equals(StorageAccount, StringComparison.OrdinalIgnoreCase));
var storageTypeProperty = properties.FirstOrDefault(p => p.Equals(StorageType, StringComparison.OrdinalIgnoreCase));
var hashTable = new Hashtable();
if (string.IsNullOrEmpty(storageAccountName) && storageAccountProperty != null)
{
storageAccountName = (string)publicConfig[storageAccountProperty];
}
hashTable.Add(StorageAccount, storageAccountName);
if (wadCfgProperty != null && publicConfig[wadCfgProperty] is JObject)
{
var wadCfgObject = (JObject)publicConfig[wadCfgProperty];
AutoFillMetricsConfig(wadCfgObject, resourceId, cmdlet);
hashTable.Add(wadCfgProperty, wadCfgObject);
}
else if (wadCfgBlobProperty != null)
{
hashTable.Add(wadCfgBlobProperty, publicConfig[wadCfgBlobProperty]);
}
else if (xmlCfgProperty != null)
{
hashTable.Add(xmlCfgProperty, publicConfig[xmlCfgProperty]);
}
else
{
throw new ArgumentException(Properties.Resources.DiagnosticsExtensionIaaSConfigElementNotDefinedInJson);
}
if (storageTypeProperty != null)
{
string storageType = (string)publicConfig[storageTypeProperty];
WadStorageType wadStorageType;
if (!Enum.TryParse<WadStorageType>(storageType, out wadStorageType))
{
throw new ArgumentException(StorageType);
}
hashTable.Add(StorageType, storageType);
}
return hashTable;
}
private static void AutoFillMetricsConfig(JObject wadCfgObject, string resourceId, Cmdlet cmdlet)
{
if (string.IsNullOrEmpty(resourceId))
{
return;
}
var configObject = wadCfgObject[DiagnosticMonitorConfigurationElemStr] as JObject;
if (configObject == null)
{
throw new ArgumentException(Properties.Resources.DiagnosticsExtensionDiagnosticMonitorConfigurationElementNotDefined);
}
var metricsObject = configObject[MetricsElemStr] as JObject;
if (metricsObject == null)
{
configObject.Add(new JProperty(MetricsElemStr,
new JObject(
new JProperty(MetricsResourceIdAttr, resourceId))));
}
else
{
var resourceIdValue = metricsObject[MetricsResourceIdAttr] as JValue;
if (resourceIdValue != null && !resourceIdValue.Value.Equals(resourceId))
{
cmdlet.WriteWarning(Properties.Resources.DiagnosticsExtensionMetricsResourceIdNotMatch);
}
metricsObject[MetricsResourceIdAttr] = resourceId;
}
}
public static Hashtable GetPrivateDiagnosticsConfiguration(string configurationPath,
string overrideStorageAccountName, string overrideStorageKey, string overrideEndpoint)
{
var privateConfig = new Hashtable();
var configFileType = GetConfigFileType(configurationPath);
if (configFileType == ConfigFileType.Xml)
{
var doc = XDocument.Load(configurationPath);
var privateConfigElement = doc.Descendants().FirstOrDefault(d => d.Name.LocalName == PrivateConfigElemStr);
if (privateConfigElement != null)
{
// Unfortunately, there is no easy way to convert the xml config to json config without involving a schema file.
// We take the schema file generated by the .xsd file, and let the serializer doing the conversion work for us.
// NOTE: this file need to be updated whenever the private schema is changed.
XmlSerializer serializer = new XmlSerializer(typeof(Cis.Monitoring.Wad.PrivateConfigConverter.PrivateConfig));
using (StringReader sr = new StringReader(privateConfigElement.ToString()))
{
var config = (Cis.Monitoring.Wad.PrivateConfigConverter.PrivateConfig)serializer.Deserialize(sr);
var storageAccount = config.StorageAccount;
// Set the StorageAccount element as null, so it won't appear after serialize to json
config.StorageAccount = null;
var privateConfigInJson = JsonConvert.SerializeObject(config,
new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore
});
privateConfig = JsonConvert.DeserializeObject<Hashtable>(privateConfigInJson);
if (!string.IsNullOrEmpty(storageAccount.name))
{
privateConfig[StorageAccountNameTag] = storageAccount.name;
}
if (!string.IsNullOrEmpty(storageAccount.key))
{
privateConfig[StorageAccountKeyTag] = storageAccount.key;
}
if (!string.IsNullOrEmpty(storageAccount.endpoint))
{
privateConfig[StorageAccountEndPointTag] = storageAccount.endpoint;
}
if (!string.IsNullOrEmpty(storageAccount.sasToken))
{
privateConfig[StorageAccountSASTokenTag] = storageAccount.sasToken;
}
}
}
}
else if (configFileType == ConfigFileType.Json)
{
// Find the PrivateConfig
var jsonConfig = JsonConvert.DeserializeObject<JObject>(File.ReadAllText(configurationPath));
var hasPrivateConfig = jsonConfig.Properties().Any(p => p.Name.Equals(PrivateConfigElemStr));
if (hasPrivateConfig)
{
privateConfig = JsonConvert.DeserializeObject<Hashtable>(jsonConfig[PrivateConfigElemStr].ToString());
}
}
string storageAccountNameInPrivateConfig = privateConfig[StorageAccountNameTag] as string;
if (!string.IsNullOrEmpty(storageAccountNameInPrivateConfig) &&
!string.Equals(storageAccountNameInPrivateConfig, overrideStorageAccountName, StringComparison.OrdinalIgnoreCase))
{
throw new ArgumentException(Properties.Resources.DiagnosticsExtensionMismatchStorageAccountName, StorageAccountNameTag);
}
privateConfig[StorageAccountNameTag] = overrideStorageAccountName;
// Only overwrite storage key if no sas token is provided.
if (string.IsNullOrEmpty(privateConfig[StorageAccountSASTokenTag] as string))
{
privateConfig[StorageAccountKeyTag] = overrideStorageKey;
privateConfig[StorageAccountEndPointTag] = overrideEndpoint;
}
return privateConfig;
}
private static void AddEventHubPrivateConfig(Hashtable privateConfig, string configurationPath)
{
var eventHubUrl = GetConfigValueFromPrivateConfig(configurationPath, EventHubElemStr, EventHubUrlAttr);
var eventHubSharedAccessKeyName = GetConfigValueFromPrivateConfig(configurationPath, EventHubElemStr, EventHubSharedAccessKeyNameAttr);
var eventHubSharedAccessKey = GetConfigValueFromPrivateConfig(configurationPath, EventHubElemStr, EventHubSharedAccessKeyAttr);
if (!string.IsNullOrEmpty(eventHubUrl) || !string.IsNullOrEmpty(eventHubSharedAccessKeyName) || !string.IsNullOrEmpty(eventHubSharedAccessKey))
{
var eventHubConfig = new Hashtable();
eventHubConfig.Add(EventHubUrlAttr, eventHubUrl);
eventHubConfig.Add(EventHubSharedAccessKeyNameAttr, eventHubSharedAccessKeyName);
eventHubConfig.Add(EventHubSharedAccessKeyAttr, eventHubSharedAccessKey);
privateConfig.Add(EventHubElemStr, eventHubConfig);
}
}
private static XElement GetPublicConfigXElementFromXmlFile(string configurationPath)
{
XElement publicConfig = null;
if (!string.IsNullOrEmpty(configurationPath))
{
var xmlConfig = XElement.Load(configurationPath);
if (xmlConfig.Name.LocalName == PublicConfigElemStr)
{
// The passed in config file is public config
publicConfig = xmlConfig;
}
else if (xmlConfig.Name.LocalName == DiagnosticsConfigurationElemStr)
{
// The passed in config file is .wadcfgx file
publicConfig = xmlConfig.Elements().FirstOrDefault(ele => ele.Name.LocalName == PublicConfigElemStr);
}
}
return publicConfig;
}
private static JObject GetPublicConfigJObjectFromJsonFile(string configurationPath)
{
var config = JsonConvert.DeserializeObject<JObject>(File.ReadAllText(configurationPath));
var properties = config.Properties().Select(p => p.Name);
// If the json config has the public config as a property, we extract it. Otherwise, the root object is the public config.
var publicConfigProperty = properties.FirstOrDefault(p => p.Equals(PublicConfigElemStr, StringComparison.OrdinalIgnoreCase));
var publicConfig = publicConfigProperty == null ? config : config[publicConfigProperty] as JObject;
return publicConfig;
}
/// <summary>
/// Get the private config value for a specific attribute.
/// The private config looks like this:
/// XML:
/// <PrivateConfig xmlns="namespace">
/// <StorageAccount name = "name" key="key" endpoint="endpoint" />
/// <EventHub Url = "url" SharedAccessKeyName="sasKeyName" SharedAccessKey="sasKey"/>
/// </PrivateConfig>
///
/// JSON:
/// "PrivateConfig":{
/// "storageAccountName":"name",
/// "storageAccountKey":"key",
/// "storageAccountEndPoint":"endpoint",
/// "EventHub":{
/// "Url":"url",
/// "SharedAccessKeyName":"sasKeyName",
/// "SharedAccessKey":"sasKey"
/// }
/// }
/// </summary>
/// <param name="configurationPath">The path to the configuration file</param>
/// <param name="elementName">The element name of the private config. e.g., StorageAccount, EventHub</param>
/// <param name="attributeName">The attribute name of the element</param>
/// <returns></returns>
public static string GetConfigValueFromPrivateConfig(string configurationPath, string elementName, string attributeName)
{
string value = string.Empty;
var configFileType = GetConfigFileType(configurationPath);
if (configFileType == ConfigFileType.Xml)
{
var xmlConfig = XElement.Load(configurationPath);
if (xmlConfig.Name.LocalName == DiagnosticsConfigurationElemStr)
{
var privateConfigElem = xmlConfig.Elements().FirstOrDefault(ele => ele.Name.LocalName == PrivateConfigElemStr);
var configElem = privateConfigElem == null ? null : privateConfigElem.Elements().FirstOrDefault(ele => ele.Name.LocalName == elementName);
var attribute = configElem == null ? null : configElem.Attributes().FirstOrDefault(a => string.Equals(a.Name.LocalName, attributeName));
value = attribute == null ? null : attribute.Value;
}
}
else if (configFileType == ConfigFileType.Json)
{
// Find the PrivateConfig
var jsonConfig = JsonConvert.DeserializeObject<JObject>(File.ReadAllText(configurationPath));
var properties = jsonConfig.Properties().Select(p => p.Name);
var privateConfigProperty = properties.FirstOrDefault(p => p.Equals(PrivateConfigElemStr));
if (privateConfigProperty == null)
{
return value;
}
var privateConfig = jsonConfig[privateConfigProperty] as JObject;
// Find the target config object corresponding to elementName
JObject targetConfig = null;
if (elementName == StorageAccountElemStr)
{
// Special handling as private storage config is flattened
targetConfig = privateConfig;
var attributeNameMapping = new Dictionary<string, string>()
{
{ PrivConfNameAttr, "storageAccountName" },
{ PrivConfKeyAttr, "storageAccountKey" },
{ PrivConfEndpointAttr, "storageAccountEndPoint" }
};
attributeName = attributeNameMapping.FirstOrDefault(m => m.Key == attributeName).Value;
}
else
{
properties = privateConfig.Properties().Select(p => p.Name);
var configProperty = properties.FirstOrDefault(p => p.Equals(elementName));
targetConfig = configProperty == null ? null : privateConfig[configProperty] as JObject;
}
if (targetConfig == null || attributeName == null)
{
return value;
}
// Find the config value corresponding to attributeName
properties = targetConfig.Properties().Select(p => p.Name);
var attributeProperty = properties.FirstOrDefault(p => p.Equals(attributeName));
value = attributeProperty == null ? null : targetConfig[attributeProperty].Value<string>();
}
return value;
}
/// <summary>
/// Initialize the storage account name if it's not specified.
/// It can be defined in multiple places, we only take the one with higher precedence. And the precedence is:
/// 1. The one get from StorageContext parameter
/// 2. The one parsed from the diagnostics configuration file
/// </summary>
public static string InitializeStorageAccountName(AzureStorageContext storageContext = null, string configurationPath = null)
{
string storageAccountName = null;
var configFileType = GetConfigFileType(configurationPath);
if (storageContext != null)
{
storageAccountName = storageContext.StorageAccountName;
}
else if (configFileType == ConfigFileType.Xml)
{
var publicConfig = GetPublicConfigXElementFromXmlFile(configurationPath);
var storageNode = publicConfig == null ? null : publicConfig.Elements().FirstOrDefault(ele => ele.Name.LocalName == StorageAccountElemStr);
storageAccountName = storageNode == null ? null : storageNode.Value;
}
else if (configFileType == ConfigFileType.Json)
{
var publicConfig = GetPublicConfigJObjectFromJsonFile(configurationPath);
var properties = publicConfig.Properties().Select(p => p.Name);
var storageAccountProperty = properties.FirstOrDefault(p => p.Equals(StorageAccount, StringComparison.OrdinalIgnoreCase));
storageAccountName = storageAccountProperty == null ? null : publicConfig[storageAccountProperty].Value<string>();
}
return storageAccountName;
}
/// <summary>
/// Initialize the storage account key if it's not specified.
/// It can be defined in multiple places, we only take the one with higher precedence. And the precedence is:
/// 1. The one we try to resolve within current subscription
/// 2. The one defined in PrivateConfig in the configuration file
/// </summary>
public static string InitializeStorageAccountKey(IStorageManagementClient storageClient, string storageAccountName = null, string configurationPath = null)
{
string storageAccountKey = null;
StorageAccount storageAccount = null;
if (TryGetStorageAccount(storageClient, storageAccountName, out storageAccount))
{
var account = new ARMStorageProvider(storageClient).GetCloudStorageAccount(storageAccount.Name, ARMStorageService.ParseResourceGroupFromId(storageAccount.Id));
// Help user retrieve the storage account key
var credentials = account.Credentials;
storageAccountKey = credentials.ExportBase64EncodedKey();
}
else
{
// Use the one defined in PrivateConfig
storageAccountKey = GetConfigValueFromPrivateConfig(configurationPath, StorageAccountElemStr, PrivConfKeyAttr);
}
return storageAccountKey;
}
/// <summary>
/// Initialize the storage account endpoint if it's not specified.
/// We can get the value from multiple places, we only take the one with higher precedence. And the precedence is:
/// 1. The one get from StorageContext parameter
/// 2. The one get from the storage account
/// 3. The one get from PrivateConfig element in config file
/// 4. The one get from current Azure Environment
/// </summary>
public static string InitializeStorageAccountEndpoint(string storageAccountName, string storageAccountKey, IStorageManagementClient storageClient,
AzureStorageContext storageContext = null, string configurationPath = null, IAzureContext defaultContext = null)
{
string storageAccountEndpoint = null;
StorageAccount storageAccount = null;
if (storageContext != null)
{
// Get value from StorageContext
storageAccountEndpoint = GetEndpointFromStorageContext(storageContext);
}
else if (TryGetStorageAccount(storageClient, storageAccountName, out storageAccount))
{
// Get value from StorageAccount
var endpoints = storageAccount.PrimaryEndpoints;
var context = CreateStorageContext(new Uri(endpoints.Blob), new Uri(endpoints.Queue), new Uri(endpoints.Table), new Uri(endpoints.File), storageAccountName, storageAccountKey);
storageAccountEndpoint = GetEndpointFromStorageContext(context);
}
else if (!string.IsNullOrEmpty(
storageAccountEndpoint = GetConfigValueFromPrivateConfig(configurationPath, StorageAccountElemStr, PrivConfEndpointAttr)))
{
// We can get the value from PrivateConfig
}
else if (defaultContext != null && defaultContext.Environment != null)
{
// Get value from default azure environment. Default to use https
Uri blobEndpoint = defaultContext.Environment.GetStorageBlobEndpoint(storageAccountName);
Uri queueEndpoint = defaultContext.Environment.GetStorageQueueEndpoint(storageAccountName);
Uri tableEndpoint = defaultContext.Environment.GetStorageTableEndpoint(storageAccountName);
Uri fileEndpoint = defaultContext.Environment.GetStorageFileEndpoint(storageAccountName);
var context = CreateStorageContext(blobEndpoint, queueEndpoint, tableEndpoint, fileEndpoint, storageAccountName, storageAccountKey);
storageAccountEndpoint = GetEndpointFromStorageContext(context);
}
return storageAccountEndpoint;
}
private static bool TryGetStorageAccount(IStorageManagementClient storageClient, string storageAccountName, out StorageAccount storageAccount)
{
try
{
var storageAccounts = storageClient.StorageAccounts.List();
storageAccount = storageAccounts == null ? null : storageAccounts.FirstOrDefault(account => account.Name.Equals(storageAccountName));
}
catch
{
storageAccount = null;
}
return storageAccount != null;
}
private static AzureStorageContext CreateStorageContext(Uri blobEndpoint, Uri queueEndpoint, Uri tableEndpoint, Uri fileEndpoint,
string storageAccountName, string storageAccountKey)
{
var credentials = new StorageCredentials(storageAccountName, storageAccountKey);
var cloudStorageAccount = new CloudStorageAccount(credentials, blobEndpoint, queueEndpoint, tableEndpoint, fileEndpoint);
return new AzureStorageContext(cloudStorageAccount);
}
private static string GetEndpointFromStorageContext(AzureStorageContext context)
{
var scheme = context.BlobEndPoint.StartsWith("https://", StringComparison.OrdinalIgnoreCase) ? "https://" : "http://";
return scheme + context.EndPointSuffix;
}
/// <summary>
/// Parse public and private configurations, and automatically resolve storage key for private configuration.
/// </summary>
/// <param name="publicConfigPath">Public configuration file path</param>
/// <param name="privateConfigPath">Private configuration file path, can be empty</param>
/// <param name="storageClient">Storage client</param>
/// <returns>A tuple with public configuration as first element and private configuration as second element</returns>
public static Tuple<Hashtable, Hashtable> GetConfigurationsFromFiles(string publicConfigPath, string privateConfigPath, string resourceId, Cmdlet cmdlet, IStorageManagementClient storageClient)
{
var publicConfig = GetPublicConfigFromJsonFile(publicConfigPath, null, resourceId, cmdlet);
var privateConfig = string.IsNullOrEmpty(privateConfigPath) ? new Hashtable() :
JsonConvert.DeserializeObject<Hashtable>(File.ReadAllText(privateConfigPath));
// Resolve storage account name
// Storage account name must be provided in public config
var storageAccountNameInPublicConfig = publicConfig[StorageAccount] as string;
if (string.IsNullOrEmpty(storageAccountNameInPublicConfig))
{
throw new ArgumentException(Properties.Resources.DiagnosticsExtensionNullStorageAccountName);
}
string storageAccountNameInPrivateConfig = privateConfig[StorageAccountNameTag] as string;
if (!string.IsNullOrEmpty(storageAccountNameInPrivateConfig) &&
!string.Equals(storageAccountNameInPrivateConfig, storageAccountNameInPublicConfig, StringComparison.OrdinalIgnoreCase))
{
throw new ArgumentException(Properties.Resources.DiagnosticsExtensionMismatchStorageAccountName, StorageAccountNameTag);
}
privateConfig[StorageAccountNameTag] = storageAccountNameInPublicConfig;
string storageAccountKey = null;
// If sas token is provided, just use it.
// Otherwise, try to resolve storage key.
if (string.IsNullOrEmpty(privateConfig[StorageAccountSASTokenTag] as string))
{
// Resolve storage account key
storageAccountKey = InitializeStorageAccountKey(storageClient, storageAccountNameInPublicConfig, privateConfigPath);
if (string.IsNullOrEmpty(storageAccountKey))
{
storageAccountKey = privateConfig[StorageAccountKeyTag] as string;
if (string.IsNullOrEmpty(storageAccountKey))
{
// Throw exception if no storage key provided in private config and cannot retrieve it from server
throw new ArgumentException(Properties.Resources.DiagnosticsExtensionNullStorageAccountKey);
}
}
else
{
// If storage key can be retrieved, use that one.
privateConfig[StorageAccountKeyTag] = storageAccountKey;
}
}
// Resolve storage account endpoint
var storageAccountEndpoint = storageAccountKey == null? null: InitializeStorageAccountEndpoint(storageAccountNameInPublicConfig, storageAccountKey, storageClient);
if (string.IsNullOrEmpty(storageAccountEndpoint))
{
storageAccountEndpoint = privateConfig[StorageAccountEndPointTag] as string;
if (string.IsNullOrEmpty(storageAccountEndpoint))
{
// Throw exception if no storage endpoint provided in private config and cannot retrieve it from server
throw new ArgumentNullException(Properties.Resources.DiagnosticsExtensionNullStorageAccountEndpoint);
}
}
else
{
// If storage account endpoint can be retrieved, use that one.
privateConfig[StorageAccountEndPointTag] = storageAccountEndpoint;
}
return new Tuple<Hashtable, Hashtable>(publicConfig, privateConfig);
}
/// <summary>
/// Check if a VMSS extension is diagnostics extension.
/// </summary>
/// <param name="extension">VMSS extension</param>
/// <returns>Whether the VMSS extension is diagnostics extension</returns>
public static bool IsDiagnosticsExtension(VirtualMachineScaleSetExtension extension)
{
return extension.Publisher.Equals(DiagnosticsExtensionConstants.ExtensionPublisher, StringComparison.InvariantCultureIgnoreCase) &&
extension.Type.Equals(DiagnosticsExtensionConstants.ExtensionType, StringComparison.InvariantCultureIgnoreCase);
}
}
}
| |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for details.
using System;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using OpenLiveWriter.Localization.Bidi;
namespace OpenLiveWriter.CoreServices
{
/// <summary>
/// Graphics helper class.
/// </summary>
public sealed class GraphicsHelper
{
/// <summary>
/// Initializes a new instance of the GraphicsHelper class.
/// </summary>
private GraphicsHelper()
{
}
/// <summary>
/// Helper to tile fill an unscaled image vertically.
/// </summary>
/// <param name="graphics">Graphics context in which the image is to be tiled.</param>
/// <param name="image">The image to tile.</param>
/// <param name="rectangle">The rectangle to fill.</param>
public static void TileFillUnscaledImageVertically(Graphics graphics, Image image, Rectangle rectangle)
{
// Tile while there is height left to fill.
int fillWidth = Math.Min(image.Width, rectangle.Width);
Rectangle imageRectangle = new Rectangle(Point.Empty, image.Size);
for (int y = rectangle.Y; y < rectangle.Bottom; )
{
// Calculate the fill height for this iteration.
int fillHeight = Math.Min(image.Height, rectangle.Bottom-y);
// Fill the fill height with the image.
graphics.DrawImage( image,
new Rectangle(rectangle.X, y, fillWidth, fillHeight),
new Rectangle(0, 0, fillWidth, fillHeight),
GraphicsUnit.Pixel);
// Adjust the y position for the next loop iteration.
y += fillHeight;
}
}
/// <summary>
/// Helper to tile fill an unscaled image vertically.
/// </summary>
/// <param name="graphics">Graphics context in which the image is to be tiled.</param>
/// <param name="image">The image to tile.</param>
/// <param name="srcRectangle">The source rectangle in the image.</param>
/// <param name="srcRectangle">The destination rectangle to fill.</param>
[Obsolete("Slow. Use OpenLiveWriter.CoreServices.UI.BorderPaint instead", false)]
public static void TileFillUnscaledImageVertically(Graphics graphics, Image image, Rectangle srcRectangle, Rectangle destRectangle)
{
// Tile while there is height left to fill.
int fillWidth = Math.Min(srcRectangle.Width, destRectangle.Width);
for (int y = destRectangle.Y; y < destRectangle.Bottom; )
{
// Calculate the fill height for this iteration.
int fillHeight = Math.Min(srcRectangle.Height, destRectangle.Bottom-y);
// Fill the fill height with the image.
graphics.DrawImage( image,
new Rectangle(destRectangle.X, y, fillWidth, fillHeight),
new Rectangle(srcRectangle.X, srcRectangle.Y, fillWidth, fillHeight),
GraphicsUnit.Pixel);
// Adjust the y position for the next loop iteration.
y += fillHeight;
}
}
/// <summary>
/// Helper to tile fill an unscaled image horizontally.
/// </summary>
/// <param name="graphics">Graphics context in which the image is to be tiled.</param>
/// <param name="image">The image to tile.</param>
/// <param name="rectangle">The rectangle to fill.</param>
public static void TileFillUnscaledImageHorizontally(Graphics graphics, Image image, Rectangle rectangle)
{
// Tile while there is width left to fill.
int fillHeight = Math.Min(image.Height, rectangle.Height);
for (int x = rectangle.X; x < rectangle.Right; )
{
// Calculate the fill width for this iteration.
int fillWidth = Math.Min(image.Width, rectangle.Right-x);
// Fill the fill width with the image.
graphics.DrawImage( image,
new Rectangle(x, rectangle.Y, fillWidth, fillHeight),
new Rectangle(0, 0, fillWidth, fillHeight),
GraphicsUnit.Pixel);
// Adjust the x position for the next loop iteration.
x += fillWidth;
}
}
/// <summary>
/// Helper to tile fill an unscaled image horizontally.
/// </summary>
/// <param name="graphics">Graphics context in which the image is to be tiled.</param>
/// <param name="image">The image to tile.</param>
/// <param name="srcRectangle">The source rectangle in the image.</param>
/// <param name="srcRectangle">The destination rectangle to fill.</param>
[Obsolete("Slow. Use OpenLiveWriter.CoreServices.UI.BorderPaint instead", false)]
public static void TileFillUnscaledImageHorizontally(Graphics graphics, Image image, Rectangle srcRectangle, Rectangle destRectangle)
{
// Tile while there is width left to fill.
int fillHeight = Math.Min(srcRectangle.Height, destRectangle.Height);
for (int x = destRectangle.X; x < destRectangle.Right; )
{
// Calculate the fill width for this iteration.
int fillWidth = Math.Min(srcRectangle.Width, destRectangle.Right-x);
// Fill the fill width with the image.
graphics.DrawImage( image,
new Rectangle(x, destRectangle.Y, fillWidth, fillHeight),
new Rectangle(srcRectangle.X, srcRectangle.Y, fillWidth, fillHeight),
GraphicsUnit.Pixel);
// Adjust the x position for the next loop iteration.
x += fillWidth;
}
}
/// <summary>
///
/// </summary>
/// <param name="graphics"></param>
/// <param name="image"></param>
/// <param name="rectangle"></param>
public static void TileFillScaledImageHorizontally(BidiGraphics graphics, Image image, Rectangle rectangle)
{
Rectangle imageRectangle = new Rectangle(Point.Empty, image.Size);
TileFillScaledImageHorizontally(graphics, image, rectangle, imageRectangle);
}
private static void TileFillScaledImageHorizontally(BidiGraphics graphics, Image image, Rectangle rectangle, Rectangle srcRectangle)
{
for (int x = rectangle.X; x < rectangle.Right; x += srcRectangle.Width)
graphics.DrawImage( true,
image,
new Rectangle(x, rectangle.Y, Math.Min(srcRectangle.Width, rectangle.Right-x), rectangle.Height),
srcRectangle,
GraphicsUnit.Pixel);
}
public static Rectangle[] SliceCompositedImageBorder(Size imgSize, int vert1, int vert2, int horiz1, int horiz2)
{
int left = 0, center = vert1, right = vert2, x4 = imgSize.Width;
int top = 0, middle = horiz1, bottom = horiz2, y4 = imgSize.Height;
int leftWidth = center, centerWidth = right - center, rightWidth = x4 - right;
int topHeight = middle, middleHeight = bottom - middle, bottomHeight = y4 - bottom;
return new Rectangle[]
{
// top left
new Rectangle(left, top, leftWidth, topHeight),
// top center
new Rectangle(center, top, centerWidth, topHeight),
// top right
new Rectangle(right, top, rightWidth, topHeight),
// left
new Rectangle(left, middle, leftWidth, middleHeight),
// middle
new Rectangle(center, middle, centerWidth, middleHeight),
// right
new Rectangle(right, middle, rightWidth, middleHeight),
// bottom left
new Rectangle(left, bottom, leftWidth, bottomHeight),
// bottom center
new Rectangle(center, bottom, centerWidth, bottomHeight),
// bottom right
new Rectangle(right, bottom, rightWidth, bottomHeight)
};
}
// Slow. Use OpenLiveWriter.CoreServices.UI.BorderPaint if performance matters
public static void DrawLeftCenterRightImageBorder(
BidiGraphics graphics,
Rectangle rectangle,
Image image,
Rectangle leftSlice,
Rectangle centerSlice,
Rectangle rightSlice)
{
GraphicsContainer graphicsContainer = graphics.Graphics.BeginContainer();
// Have to remove this line because it messes with mirrored images.
// Specifically, right-to-left drawing of the hover effect for the context menu dongle
// hanging off "Save Draft" doesn't happen at all. Seems like a short-circuit happens
// in Graphics when the image's location is outside the clipping area.
//graphics.Graphics.SetClip(rectangle);
graphics.Graphics.CompositingMode = CompositingMode.SourceOver;
graphics.Graphics.CompositingQuality = CompositingQuality.HighQuality;
graphics.DrawImage(
true,
image,
new Rectangle(rectangle.Left, rectangle.Top, leftSlice.Width, rectangle.Height),
leftSlice.Left, leftSlice.Top, leftSlice.Width, leftSlice.Height,
GraphicsUnit.Pixel
);
TileFillScaledImageHorizontally(
graphics,
image,
new Rectangle(rectangle.Left + leftSlice.Width, rectangle.Top, Math.Max(0, rectangle.Width - leftSlice.Width - rightSlice.Width), rectangle.Height),
centerSlice);
graphics.DrawImage(
true,
image,
new Rectangle(rectangle.Right - rightSlice.Width, rectangle.Top, rightSlice.Width, rectangle.Height),
rightSlice.Left, rightSlice.Top, rightSlice.Width, rightSlice.Height,
GraphicsUnit.Pixel
);
graphics.Graphics.EndContainer(graphicsContainer);
}
[Obsolete("Slow. Use OpenLiveWriter.CoreServices.UI.BorderPaint instead", false)]
public static void DrawCompositedImageBorder(
Graphics graphics,
Rectangle rectangle,
Image image,
Rectangle[] slices)
{
DrawCompositedImageBorder(graphics, rectangle, image,
slices[0],
slices[1],
slices[2],
slices[3],
slices[4],
slices[5],
slices[6],
slices[7]);
}
/// <summary>
/// Draws a composited image border.
/// </summary>
/// <remarks>
/// Note that because it would be too computationally expensive, it is assumed that images
/// will fit into the specified rectangle.
/// </remarks>
/// <param name="graphics">A graphics context into which the image-based border is to be drawn.</param>
/// <param name="rectangle">The rectangle into which the image-based border is to be drawn.</param>
/// <param name="topLeftRectangle">The top left rectangle.</param>
/// <param name="topCenterRectangle">The top center (fill) rectangle.</param>
/// <param name="topRightRectangle">The top right rectangle.</param>
/// <param name="leftCenterRectangle">The left center (fill) rectangle.</param>
/// <param name="rightCenterRectangle">The right center (fill) rectangle.</param>
/// <param name="bottomLeftRectangle">The bottom left rectangle.</param>
/// <param name="bottomCenterRectangle">The bottom center (fill) rectangle.</param>
/// <param name="bottomRightRectangle">The bottom right rectangle.</param>
[Obsolete("Slow. Use OpenLiveWriter.CoreServices.UI.BorderPaint instead", false)]
public static void DrawCompositedImageBorder
(
Graphics graphics,
Rectangle rectangle,
Image image,
Rectangle topLeftRectangle,
Rectangle topCenterRectangle,
Rectangle topRightRectangle,
Rectangle leftCenterRectangle,
Rectangle rightCenterRectangle,
Rectangle bottomLeftRectangle,
Rectangle bottomCenterRectangle,
Rectangle bottomRightRectangle
)
{
Rectangle fillRectangle;
// Save a graphics container with the current state of the graphics object and open
// and use a new, clipped graphics container.
GraphicsContainer graphicsContainer = graphics.BeginContainer();
graphics.SetClip(rectangle);
graphics.CompositingMode = CompositingMode.SourceOver;
graphics.CompositingQuality = CompositingQuality.HighQuality;
if (HasArea(topLeftRectangle))
{
// Top left.
graphics.DrawImage( image,
new Rectangle(rectangle.X, rectangle.Y, topLeftRectangle.Width, topLeftRectangle.Height),
topLeftRectangle,
GraphicsUnit.Pixel);
}
if (HasArea(topCenterRectangle))
{
// Top center.
fillRectangle = new Rectangle( rectangle.X+topLeftRectangle.Width,
rectangle.Y,
rectangle.Width-(topLeftRectangle.Width+topRightRectangle.Width),
topCenterRectangle.Height);
TileFillUnscaledImageHorizontally(graphics, image, topCenterRectangle, fillRectangle);
}
if (HasArea(topRightRectangle))
{
// Top right.
graphics.DrawImage( image,
new Rectangle(rectangle.Right-topRightRectangle.Width, rectangle.Y, topRightRectangle.Width, topRightRectangle.Height),
topRightRectangle,
GraphicsUnit.Pixel);
}
if (HasArea(leftCenterRectangle))
{
// Left center.
fillRectangle = new Rectangle( rectangle.X,
rectangle.Y+topLeftRectangle.Height,
leftCenterRectangle.Width,
rectangle.Height-(topLeftRectangle.Height+bottomLeftRectangle.Height));
TileFillUnscaledImageVertically(graphics, image, leftCenterRectangle, fillRectangle);
}
if (HasArea(rightCenterRectangle))
{
// Right center.
fillRectangle = new Rectangle( rectangle.Right-rightCenterRectangle.Width,
rectangle.Y+topRightRectangle.Height,
rightCenterRectangle.Width,
rectangle.Height-(topRightRectangle.Height+bottomRightRectangle.Height));
TileFillUnscaledImageVertically(graphics, image, rightCenterRectangle, fillRectangle);
}
if (HasArea(bottomLeftRectangle))
{
// Bottom left.
graphics.DrawImage( image,
new Rectangle(rectangle.X, rectangle.Bottom-bottomLeftRectangle.Height, bottomLeftRectangle.Width, bottomLeftRectangle.Height),
bottomLeftRectangle,
GraphicsUnit.Pixel);
}
if (HasArea(bottomCenterRectangle))
{
// Bottom center.
fillRectangle = new Rectangle( rectangle.X+bottomLeftRectangle.Width,
rectangle.Bottom-bottomCenterRectangle.Height,
rectangle.Width-(bottomLeftRectangle.Width+bottomRightRectangle.Width),
bottomCenterRectangle.Height);
TileFillUnscaledImageHorizontally(graphics, image, bottomCenterRectangle, fillRectangle);
}
if (HasArea(bottomRightRectangle))
{
// Botom right.
graphics.DrawImage( image,
new Rectangle(rectangle.Right-bottomRightRectangle.Width, rectangle.Bottom-bottomRightRectangle.Height, bottomRightRectangle.Width, bottomRightRectangle.Height),
bottomRightRectangle,
GraphicsUnit.Pixel);
}
// End the graphics container.
graphics.EndContainer(graphicsContainer);
}
private static bool HasArea(Rectangle rectangle)
{
return rectangle.Height > 0 && rectangle.Width > 0;
}
/// <summary>
/// Draws a composited image border. Note that because it would be too computationally
/// expensive, it is ASSUMED that the rectangle supplied is large enough to draw the border
/// witout
/// </summary>
/// <remarks>
/// Note that because it would be too computationally expensive, it is assumed that images
/// will fit into the specified rectangle.
/// </remarks>
/// <param name="graphics">A graphics context into which the image-based border is to be drawn.</param>
/// <param name="rectangle">The rectangle into which the image-based border is to be drawn.</param>
/// <param name="topLeftImage">The top left image.</param>
/// <param name="topCenterImage">The top center (fill) image.</param>
/// <param name="topRightImage">The top right image.</param>
/// <param name="leftCenterImage">The left center (fill) image.</param>
/// <param name="rightCenterImage">The right center (fill) image.</param>
/// <param name="bottomLeftImage">The bottom left image.</param>
/// <param name="bottomCenterImage">The bottom center (fill) image.</param>
/// <param name="bottomRightImage">The bottom right image.</param>
public static void DrawCompositedImageBorder
(
Graphics graphics,
Rectangle rectangle,
Image topLeftImage,
Image topCenterImage,
Image topRightImage,
Image leftCenterImage,
Image rightCenterImage,
Image bottomLeftImage,
Image bottomCenterImage,
Image bottomRightImage
)
{
Rectangle fillRectangle;
// Save a graphics container with the current state of the graphics object and open
// and use a new, clipped graphics container.
GraphicsContainer graphicsContainer = graphics.BeginContainer();
graphics.SetClip(rectangle);
// Top left.
graphics.DrawImageUnscaled(topLeftImage, rectangle.X, rectangle.Y);
// Top center.
fillRectangle = new Rectangle( rectangle.X+topLeftImage.Width,
rectangle.Y,
rectangle.Width-(topLeftImage.Width+topRightImage.Width),
topCenterImage.Height);
TileFillUnscaledImageHorizontally(graphics, topCenterImage, fillRectangle);
// Top right.
graphics.DrawImageUnscaled(topRightImage, rectangle.Right-topRightImage.Width, rectangle.Y);
// Left center.
fillRectangle = new Rectangle( rectangle.X,
rectangle.Y+topLeftImage.Height,
leftCenterImage.Width,
rectangle.Height-(topLeftImage.Height+bottomLeftImage.Height));
TileFillUnscaledImageVertically(graphics, leftCenterImage, fillRectangle);
// Right center.
fillRectangle = new Rectangle( rectangle.Right-rightCenterImage.Width,
rectangle.Y+topRightImage.Height,
rightCenterImage.Width,
rectangle.Height-(topRightImage.Height+bottomRightImage.Height));
TileFillUnscaledImageVertically(graphics, rightCenterImage, fillRectangle);
// Bottom left.
graphics.DrawImageUnscaled(bottomLeftImage, rectangle.X, rectangle.Bottom-bottomLeftImage.Height);
// Bottom center.
fillRectangle = new Rectangle( rectangle.X+bottomLeftImage.Width,
rectangle.Bottom-bottomCenterImage.Height,
rectangle.Width-(bottomLeftImage.Width+bottomRightImage.Width),
bottomCenterImage.Height);
TileFillUnscaledImageHorizontally(graphics, bottomCenterImage, fillRectangle);
// Bottom right.
graphics.DrawImageUnscaled(bottomRightImage, rectangle.Right-bottomRightImage.Width, rectangle.Bottom-bottomRightImage.Height);
// End the graphics container.
graphics.EndContainer(graphicsContainer);
}
/// <summary>
/// Converts an opacity percent between 0.0 and 100.0, inclusive, into an alpha component
/// value between 0 and 255.
/// </summary>
/// <param name="opacity">Opacity percent between 0.0 and 100.0.</param>
/// <returns>Alpha component value between 0 and 255</returns>
public static int Opacity(double opacity)
{
Debug.Assert(opacity >= 0.0 && opacity <= 100.0, "Invalid opacity specified", "Specify opacity as a value between 0.0 and 100.0, inclusive.");
if (opacity >= 0.0 && opacity <= 100.0)
return Convert.ToInt32((255.0*opacity)/100.0);
else
return 255;
}
public static IDisposable Offset(Graphics g, Rectangle dest, Rectangle src)
{
Debug.Assert(dest.Size.Equals(src.Size), "Can't offset with rectangles of unequal sizes");
return Offset(g, dest.Location.X - src.Location.X, dest.Location.Y - src.Location.Y);
}
public static IDisposable Offset(Graphics g, int x, int y)
{
GraphicsState graphicsState = g.Save();
g.TranslateTransform(x, y);
return new GraphicsStateRestorer(g, graphicsState);
}
private class GraphicsStateRestorer : IDisposable
{
private readonly Graphics graphics;
private readonly GraphicsState graphicsState;
private bool disposed = false;
public GraphicsStateRestorer(Graphics graphics, GraphicsState graphicsState)
{
this.graphics = graphics;
this.graphicsState = graphicsState;
}
public void Dispose()
{
if (!disposed)
{
disposed = true;
graphics.Restore(graphicsState);
}
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing.Imaging;
using System.Drawing.Internal;
using System.Globalization;
using System.IO;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
namespace System.Drawing
{
/// <summary>
/// An abstract base class that provides functionality for 'Bitmap', 'Icon', 'Cursor', and 'Metafile' descended classes.
/// </summary>
[ImmutableObject(true)]
[ComVisible(true)]
public abstract partial class Image : MarshalByRefObject, ICloneable, IDisposable, ISerializable
{
#if FINALIZATION_WATCH
private string allocationSite = Graphics.GetAllocationStack();
#endif
// The signature of this delegate is incorrect. The signature of the corresponding
// native callback function is:
// extern "C" {
// typedef BOOL (CALLBACK * ImageAbort)(VOID *);
// typedef ImageAbort DrawImageAbort;
// typedef ImageAbort GetThumbnailImageAbort;
// }
// However, as this delegate is not used in both GDI 1.0 and 1.1, we choose not
// to modify it, in order to preserve compatibility.
public delegate bool GetThumbnailImageAbort();
internal IntPtr nativeImage;
// used to work around lack of animated gif encoder... rarely set...
private byte[] _rawData;
//userData : so that user can use TAGS with IMAGES..
private object _userData;
internal Image()
{
}
[
Localizable(false),
DefaultValue(null),
]
public object Tag
{
get
{
return _userData;
}
set
{
_userData = value;
}
}
/// <summary>
/// Creates an <see cref='Image'/> from the specified file.
/// </summary>
public static Image FromFile(string filename) => FromFile(filename, false);
public static Image FromFile(string filename, bool useEmbeddedColorManagement)
{
if (!File.Exists(filename))
{
// Throw a more specific exception for invalid paths that are null or empty,
// contain invalid characters or are too long.
filename = Path.GetFullPath(filename);
throw new FileNotFoundException(filename);
}
// GDI+ will read this file multiple times. Get the fully qualified path
// so if our app changes default directory we won't get an error
filename = Path.GetFullPath(filename);
IntPtr image = IntPtr.Zero;
int status;
if (useEmbeddedColorManagement)
{
status = SafeNativeMethods.Gdip.GdipLoadImageFromFileICM(filename, out image);
}
else
{
status = SafeNativeMethods.Gdip.GdipLoadImageFromFile(filename, out image);
}
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
status = SafeNativeMethods.Gdip.GdipImageForceValidation(new HandleRef(null, image));
if (status != SafeNativeMethods.Gdip.Ok)
{
SafeNativeMethods.Gdip.GdipDisposeImage(new HandleRef(null, image));
throw SafeNativeMethods.Gdip.StatusException(status);
}
Image img = CreateImageObject(image);
EnsureSave(img, filename, null);
return img;
}
/// <summary>
/// Creates an <see cref='Image'/> from the specified data stream.
/// </summary>
public static Image FromStream(Stream stream)
{
return Image.FromStream(stream, false);
}
public static Image FromStream(Stream stream,
bool useEmbeddedColorManagement)
{
return FromStream(stream, useEmbeddedColorManagement, true);
}
public static Image FromStream(Stream stream, bool useEmbeddedColorManagement, bool validateImageData)
{
if (stream == null)
{
throw new ArgumentNullException(nameof(stream));
}
IntPtr image = IntPtr.Zero;
int status;
if (useEmbeddedColorManagement)
{
status = SafeNativeMethods.Gdip.GdipLoadImageFromStreamICM(new GPStream(stream), out image);
}
else
{
status = SafeNativeMethods.Gdip.GdipLoadImageFromStream(new GPStream(stream), out image);
}
if (status != SafeNativeMethods.Gdip.Ok)
{
throw SafeNativeMethods.Gdip.StatusException(status);
}
if (validateImageData)
{
status = SafeNativeMethods.Gdip.GdipImageForceValidation(new HandleRef(null, image));
if (status != SafeNativeMethods.Gdip.Ok)
{
SafeNativeMethods.Gdip.GdipDisposeImage(new HandleRef(null, image));
throw SafeNativeMethods.Gdip.StatusException(status);
}
}
Image img = CreateImageObject(image);
EnsureSave(img, null, stream);
return img;
}
// Used for serialization
private void InitializeFromStream(Stream stream)
{
IntPtr image = IntPtr.Zero;
int status = SafeNativeMethods.Gdip.GdipLoadImageFromStream(new GPStream(stream), out image);
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
status = SafeNativeMethods.Gdip.GdipImageForceValidation(new HandleRef(null, image));
if (status != SafeNativeMethods.Gdip.Ok)
{
SafeNativeMethods.Gdip.GdipDisposeImage(new HandleRef(null, image));
throw SafeNativeMethods.Gdip.StatusException(status);
}
nativeImage = image;
int type = -1;
status = SafeNativeMethods.Gdip.GdipGetImageType(new HandleRef(this, nativeImage), out type);
EnsureSave(this, null, stream);
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
}
internal Image(IntPtr nativeImage)
{
SetNativeImage(nativeImage);
}
/// <summary>
/// Creates an exact copy of this <see cref='Image'/>.
/// </summary>
public object Clone()
{
IntPtr cloneImage = IntPtr.Zero;
int status = SafeNativeMethods.Gdip.GdipCloneImage(new HandleRef(this, nativeImage), out cloneImage);
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
status = SafeNativeMethods.Gdip.GdipImageForceValidation(new HandleRef(null, cloneImage));
if (status != SafeNativeMethods.Gdip.Ok)
{
SafeNativeMethods.Gdip.GdipDisposeImage(new HandleRef(null, cloneImage));
throw SafeNativeMethods.Gdip.StatusException(status);
}
return CreateImageObject(cloneImage);
}
/// <summary>
/// Cleans up Windows resources for this <see cref='Image'/>.
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
#if FINALIZATION_WATCH
if (!disposing && nativeImage != IntPtr.Zero)
Debug.WriteLine("**********************\nDisposed through finalization:\n" + allocationSite);
#endif
if (nativeImage != IntPtr.Zero)
{
try
{
#if DEBUG
int status =
#endif
SafeNativeMethods.Gdip.GdipDisposeImage(new HandleRef(this, nativeImage));
#if DEBUG
Debug.Assert(status == SafeNativeMethods.Gdip.Ok, "GDI+ returned an error status: " + status.ToString(CultureInfo.InvariantCulture));
#endif
}
catch (Exception ex)
{
if (ClientUtils.IsSecurityOrCriticalException(ex))
{
throw;
}
Debug.Fail("Exception thrown during Dispose: " + ex.ToString());
}
finally
{
nativeImage = IntPtr.Zero;
}
}
}
/// <summary>
/// Cleans up Windows resources for this <see cref='Image'/>.
/// </summary>
~Image()
{
Dispose(false);
}
internal static void EnsureSave(Image image, string filename, Stream dataStream)
{
if (image.RawFormat.Equals(ImageFormat.Gif))
{
bool animatedGif = false;
Guid[] dimensions = image.FrameDimensionsList;
foreach (Guid guid in dimensions)
{
FrameDimension dimension = new FrameDimension(guid);
if (dimension.Equals(FrameDimension.Time))
{
animatedGif = image.GetFrameCount(FrameDimension.Time) > 1;
break;
}
}
if (animatedGif)
{
try
{
Stream created = null;
long lastPos = 0;
if (dataStream != null)
{
lastPos = dataStream.Position;
dataStream.Position = 0;
}
try
{
if (dataStream == null)
{
created = dataStream = File.OpenRead(filename);
}
image._rawData = new byte[(int)dataStream.Length];
dataStream.Read(image._rawData, 0, (int)dataStream.Length);
}
finally
{
if (created != null)
{
created.Close();
}
else
{
dataStream.Position = lastPos;
}
}
}
// possible exceptions for reading the filename
catch (UnauthorizedAccessException)
{
}
catch (DirectoryNotFoundException)
{
}
catch (IOException)
{
}
// possible exceptions for setting/getting the position inside dataStream
catch (NotSupportedException)
{
}
catch (ObjectDisposedException)
{
}
// possible exception when reading stuff into dataStream
catch (ArgumentException)
{
}
}
}
}
internal static Image CreateImageObject(IntPtr nativeImage)
{
Image image;
int type = -1;
int status = SafeNativeMethods.Gdip.GdipGetImageType(new HandleRef(null, nativeImage), out type);
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
switch ((ImageType)type)
{
case ImageType.Bitmap:
image = Bitmap.FromGDIplus(nativeImage);
break;
case ImageType.Metafile:
image = Metafile.FromGDIplus(nativeImage);
break;
default:
throw new ArgumentException(SR.Format(SR.InvalidImage));
}
return image;
}
/// <summary>
/// Returns information about the codecs used for this <see cref='Image'/>.
/// </summary>
public EncoderParameters GetEncoderParameterList(Guid encoder)
{
EncoderParameters p;
int size;
int status = SafeNativeMethods.Gdip.GdipGetEncoderParameterListSize(new HandleRef(this, nativeImage),
ref encoder,
out size);
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
if (size <= 0)
return null;
IntPtr buffer = Marshal.AllocHGlobal(size);
try
{
status = SafeNativeMethods.Gdip.GdipGetEncoderParameterList(new HandleRef(this, nativeImage),
ref encoder,
size,
buffer);
if (status != SafeNativeMethods.Gdip.Ok)
{
throw SafeNativeMethods.Gdip.StatusException(status);
}
p = EncoderParameters.ConvertFromMemory(buffer);
}
finally
{
Marshal.FreeHGlobal(buffer);
}
return p;
}
/// <summary>
/// Saves this <see cref='Image'/> to the specified file.
/// </summary>
public void Save(string filename)
{
Save(filename, RawFormat);
}
/// <summary>
/// Saves this <see cref='Image'/> to the specified file in the specified format.
/// </summary>
public void Save(string filename, ImageFormat format)
{
if (format == null)
throw new ArgumentNullException("format");
ImageCodecInfo codec = format.FindEncoder();
if (codec == null)
codec = ImageFormat.Png.FindEncoder();
Save(filename, codec, null);
}
/// <summary>
/// Saves this <see cref='Image'/> to the specified file in the specified format and with the specified encoder parameters.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
public void Save(string filename, ImageCodecInfo encoder, EncoderParameters encoderParams)
{
if (filename == null)
throw new ArgumentNullException("filename");
if (encoder == null)
throw new ArgumentNullException("encoder");
IntPtr encoderParamsMemory = IntPtr.Zero;
if (encoderParams != null)
{
_rawData = null;
encoderParamsMemory = encoderParams.ConvertToMemory();
}
int status = SafeNativeMethods.Gdip.Ok;
try
{
Guid g = encoder.Clsid;
bool saved = false;
if (_rawData != null)
{
ImageCodecInfo rawEncoder = RawFormat.FindEncoder();
if (rawEncoder != null && rawEncoder.Clsid == g)
{
using (FileStream fs = File.OpenWrite(filename))
{
fs.Write(_rawData, 0, _rawData.Length);
saved = true;
}
}
}
if (!saved)
{
status = SafeNativeMethods.Gdip.GdipSaveImageToFile(new HandleRef(this, nativeImage),
filename,
ref g,
new HandleRef(encoderParams, encoderParamsMemory));
}
}
finally
{
if (encoderParamsMemory != IntPtr.Zero)
{
Marshal.FreeHGlobal(encoderParamsMemory);
}
}
if (status != SafeNativeMethods.Gdip.Ok)
{
throw SafeNativeMethods.Gdip.StatusException(status);
}
}
internal void Save(MemoryStream stream)
{
// Jpeg loses data, so we don't want to use it to serialize...
ImageFormat dest = RawFormat;
if (dest == ImageFormat.Jpeg)
{
dest = ImageFormat.Png;
}
ImageCodecInfo codec = dest.FindEncoder();
// If we don't find an Encoder (for things like Icon), we
// just switch back to PNG...
if (codec == null)
{
codec = ImageFormat.Png.FindEncoder();
}
Save(stream, codec, null);
}
/// <summary>
/// Saves this <see cref='Image'/> to the specified stream in the specified format.
/// </summary>
public void Save(Stream stream, ImageFormat format)
{
if (format == null)
throw new ArgumentNullException("format");
ImageCodecInfo codec = format.FindEncoder();
Save(stream, codec, null);
}
/// <summary>
/// Saves this <see cref='Image'/> to the specified stream in the specified format.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
public void Save(Stream stream, ImageCodecInfo encoder, EncoderParameters encoderParams)
{
if (stream == null)
{
throw new ArgumentNullException("stream");
}
if (encoder == null)
{
throw new ArgumentNullException("encoder");
}
IntPtr encoderParamsMemory = IntPtr.Zero;
if (encoderParams != null)
{
_rawData = null;
encoderParamsMemory = encoderParams.ConvertToMemory();
}
int status = SafeNativeMethods.Gdip.Ok;
try
{
Guid g = encoder.Clsid;
bool saved = false;
if (_rawData != null)
{
ImageCodecInfo rawEncoder = RawFormat.FindEncoder();
if (rawEncoder != null && rawEncoder.Clsid == g)
{
stream.Write(_rawData, 0, _rawData.Length);
saved = true;
}
}
if (!saved)
{
status = SafeNativeMethods.Gdip.GdipSaveImageToStream(new HandleRef(this, nativeImage),
new UnsafeNativeMethods.ComStreamFromDataStream(stream),
ref g,
new HandleRef(encoderParams, encoderParamsMemory));
}
}
finally
{
if (encoderParamsMemory != IntPtr.Zero)
{
Marshal.FreeHGlobal(encoderParamsMemory);
}
}
if (status != SafeNativeMethods.Gdip.Ok)
{
throw SafeNativeMethods.Gdip.StatusException(status);
}
}
/// <summary>
/// Adds an <see cref='EncoderParameters'/> to this <see cref='Image'/>.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
public void SaveAdd(EncoderParameters encoderParams)
{
IntPtr encoder = IntPtr.Zero;
if (encoderParams != null)
{
encoder = encoderParams.ConvertToMemory();
}
_rawData = null;
int status = SafeNativeMethods.Gdip.GdipSaveAdd(new HandleRef(this, nativeImage), new HandleRef(encoderParams, encoder));
if (encoder != IntPtr.Zero)
{
Marshal.FreeHGlobal(encoder);
}
if (status != SafeNativeMethods.Gdip.Ok)
{
throw SafeNativeMethods.Gdip.StatusException(status);
}
}
/// <summary>
/// Adds an <see cref='EncoderParameters'/> to the specified <see cref='Image'/>.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")]
public void SaveAdd(Image image, EncoderParameters encoderParams)
{
IntPtr encoder = IntPtr.Zero;
if (image == null)
{
throw new ArgumentNullException("image");
}
if (encoderParams != null)
{
encoder = encoderParams.ConvertToMemory();
}
_rawData = null;
int status = SafeNativeMethods.Gdip.GdipSaveAddImage(new HandleRef(this, nativeImage), new HandleRef(image, image.nativeImage), new HandleRef(encoderParams, encoder));
if (encoder != IntPtr.Zero)
{
Marshal.FreeHGlobal(encoder);
}
if (status != SafeNativeMethods.Gdip.Ok)
{
throw SafeNativeMethods.Gdip.StatusException(status);
}
}
private SizeF _GetPhysicalDimension()
{
float width;
float height;
int status = SafeNativeMethods.Gdip.GdipGetImageDimension(new HandleRef(this, nativeImage), out width, out height);
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
return new SizeF(width, height);
}
/// <summary>
/// Gets the width and height of this <see cref='Image'/>.
/// </summary>
public SizeF PhysicalDimension
{
get { return _GetPhysicalDimension(); }
}
/// <summary>
/// Gets the width and height of this <see cref='Image'/>.
/// </summary>
public Size Size
{
get
{
return new Size(Width, Height);
}
}
/// <summary>
/// Gets the width of this <see cref='Image'/>.
/// </summary>
[
DefaultValue(false),
Browsable(false),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
]
public int Width
{
get
{
int width;
int status = SafeNativeMethods.Gdip.GdipGetImageWidth(new HandleRef(this, nativeImage), out width);
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
return width;
}
}
/// <summary>
/// Gets the height of this <see cref='Image'/>.
/// </summary>
[
DefaultValue(false),
Browsable(false),
DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)
]
public int Height
{
get
{
int height;
int status = SafeNativeMethods.Gdip.GdipGetImageHeight(new HandleRef(this, nativeImage), out height);
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
return height;
}
}
/// <summary>
/// Gets the horizontal resolution, in pixels-per-inch, of this <see cref='Image'/>.
/// </summary>
public float HorizontalResolution
{
get
{
float horzRes;
int status = SafeNativeMethods.Gdip.GdipGetImageHorizontalResolution(new HandleRef(this, nativeImage), out horzRes);
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
return horzRes;
}
}
/// <summary>
/// Gets the vertical resolution, in pixels-per-inch, of this <see cref='Image'/>.
/// </summary>
public float VerticalResolution
{
get
{
float vertRes;
int status = SafeNativeMethods.Gdip.GdipGetImageVerticalResolution(new HandleRef(this, nativeImage), out vertRes);
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
return vertRes;
}
}
/// <summary>
/// Gets attribute flags for this <see cref='Image'/>.
/// </summary>
[Browsable(false)]
public int Flags
{
get
{
int flags;
int status = SafeNativeMethods.Gdip.GdipGetImageFlags(new HandleRef(this, nativeImage), out flags);
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
return flags;
}
}
/// <summary>
/// Gets the format of this <see cref='Image'/>.
/// </summary>
public ImageFormat RawFormat
{
get
{
Guid guid = new Guid();
int status = SafeNativeMethods.Gdip.GdipGetImageRawFormat(new HandleRef(this, nativeImage), ref guid);
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
return new ImageFormat(guid);
}
}
/// <summary>
/// Gets the pixel format for this <see cref='Image'/>.
/// </summary>
public PixelFormat PixelFormat
{
get
{
int format;
int status = SafeNativeMethods.Gdip.GdipGetImagePixelFormat(new HandleRef(this, nativeImage), out format);
if (status != SafeNativeMethods.Gdip.Ok)
return PixelFormat.Undefined;
else
return (PixelFormat)format;
}
}
/// <summary>
/// Gets a bounding rectangle in the specified units for this <see cref='Image'/>.
/// </summary>
public RectangleF GetBounds(ref GraphicsUnit pageUnit)
{
GPRECTF gprectf = new GPRECTF();
int status = SafeNativeMethods.Gdip.GdipGetImageBounds(new HandleRef(this, nativeImage), ref gprectf, out pageUnit);
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
return gprectf.ToRectangleF();
}
private ColorPalette _GetColorPalette()
{
int size = -1;
int status = SafeNativeMethods.Gdip.GdipGetImagePaletteSize(new HandleRef(this, nativeImage), out size);
// "size" is total byte size:
// sizeof(ColorPalette) + (pal->Count-1)*sizeof(ARGB)
if (status != SafeNativeMethods.Gdip.Ok)
{
throw SafeNativeMethods.Gdip.StatusException(status);
}
ColorPalette palette = new ColorPalette(size);
// Memory layout is:
// UINT Flags
// UINT Count
// ARGB Entries[size]
IntPtr memory = Marshal.AllocHGlobal(size);
try
{
status = SafeNativeMethods.Gdip.GdipGetImagePalette(new HandleRef(this, nativeImage), memory, size);
if (status != SafeNativeMethods.Gdip.Ok)
{
throw SafeNativeMethods.Gdip.StatusException(status);
}
palette.ConvertFromMemory(memory);
}
finally
{
Marshal.FreeHGlobal(memory);
}
return palette;
}
private void _SetColorPalette(ColorPalette palette)
{
IntPtr memory = palette.ConvertToMemory();
int status = SafeNativeMethods.Gdip.GdipSetImagePalette(new HandleRef(this, nativeImage), memory);
if (memory != IntPtr.Zero)
{
Marshal.FreeHGlobal(memory);
}
if (status != SafeNativeMethods.Gdip.Ok)
{
throw SafeNativeMethods.Gdip.StatusException(status);
}
}
/// <summary>
/// Gets or sets the color palette used for this <see cref='Image'/>.
/// </summary>
[Browsable(false)]
public ColorPalette Palette
{
get
{
return _GetColorPalette();
}
set
{
_SetColorPalette(value);
}
}
// Thumbnail support
/// <summary>
/// Returns the thumbnail for this <see cref='Image'/>.
/// </summary>
public Image GetThumbnailImage(int thumbWidth, int thumbHeight,
GetThumbnailImageAbort callback, IntPtr callbackData)
{
IntPtr thumbImage = IntPtr.Zero;
int status = SafeNativeMethods.Gdip.GdipGetImageThumbnail(new HandleRef(this, nativeImage), thumbWidth, thumbHeight, out thumbImage,
callback, callbackData);
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
return CreateImageObject(thumbImage);
}
// Multi-frame support
/// <summary>
/// Gets an array of GUIDs that represent the dimensions of frames within this <see cref='Image'/>.
/// </summary>
[Browsable(false)]
public Guid[] FrameDimensionsList
{
get
{
int count;
int status = SafeNativeMethods.Gdip.GdipImageGetFrameDimensionsCount(new HandleRef(this, nativeImage), out count);
if (status != SafeNativeMethods.Gdip.Ok)
{
throw SafeNativeMethods.Gdip.StatusException(status);
}
Debug.Assert(count >= 0, "FrameDimensionsList returns bad count");
if (count <= 0)
{
return new Guid[0];
}
int size = (int)Marshal.SizeOf(typeof(Guid));
IntPtr buffer = Marshal.AllocHGlobal(checked(size * count));
if (buffer == IntPtr.Zero)
{
throw SafeNativeMethods.Gdip.StatusException(SafeNativeMethods.Gdip.OutOfMemory);
}
status = SafeNativeMethods.Gdip.GdipImageGetFrameDimensionsList(new HandleRef(this, nativeImage), buffer, count);
if (status != SafeNativeMethods.Gdip.Ok)
{
Marshal.FreeHGlobal(buffer);
throw SafeNativeMethods.Gdip.StatusException(status);
}
Guid[] guids = new Guid[count];
try
{
for (int i = 0; i < count; i++)
{
guids[i] = (Guid)Marshal.PtrToStructure((IntPtr)((long)buffer + size * i), typeof(Guid));
}
}
finally
{
Marshal.FreeHGlobal(buffer);
}
return guids;
}
}
/// <summary>
/// Returns the number of frames of the given dimension.
/// </summary>
public int GetFrameCount(FrameDimension dimension)
{
int[] count = new int[] { 0 };
Guid dimensionID = dimension.Guid;
int status = SafeNativeMethods.Gdip.GdipImageGetFrameCount(new HandleRef(this, nativeImage), ref dimensionID, count);
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
return count[0];
}
/// <summary>
/// Selects the frame specified by the given dimension and index.
/// </summary>
public int SelectActiveFrame(FrameDimension dimension, int frameIndex)
{
int[] count = new int[] { 0 };
Guid dimensionID = dimension.Guid;
int status = SafeNativeMethods.Gdip.GdipImageSelectActiveFrame(new HandleRef(this, nativeImage), ref dimensionID, frameIndex);
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
return count[0];
}
public void RotateFlip(RotateFlipType rotateFlipType)
{
int status = SafeNativeMethods.Gdip.GdipImageRotateFlip(new HandleRef(this, nativeImage), unchecked((int)rotateFlipType));
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
}
/// <summary>
/// Gets an array of the property IDs stored in this <see cref='Image'/>.
/// </summary>
[Browsable(false)]
public int[] PropertyIdList
{
get
{
int count;
int status = SafeNativeMethods.Gdip.GdipGetPropertyCount(new HandleRef(this, nativeImage), out count);
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
int[] propid = new int[count];
//if we have a 0 count, just return our empty array
if (count == 0)
return propid;
status = SafeNativeMethods.Gdip.GdipGetPropertyIdList(new HandleRef(this, nativeImage), count, propid);
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
return propid;
}
}
/// <summary>
/// Gets the specified property item from this <see cref='Image'/>.
/// </summary>
public PropertyItem GetPropertyItem(int propid)
{
PropertyItem propitem;
int size;
int status = SafeNativeMethods.Gdip.GdipGetPropertyItemSize(new HandleRef(this, nativeImage), propid, out size);
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
if (size == 0)
return null;
IntPtr propdata = Marshal.AllocHGlobal(size);
if (propdata == IntPtr.Zero)
throw SafeNativeMethods.Gdip.StatusException(SafeNativeMethods.Gdip.OutOfMemory);
try
{
status = SafeNativeMethods.Gdip.GdipGetPropertyItem(new HandleRef(this, nativeImage), propid, size, propdata);
if (status != SafeNativeMethods.Gdip.Ok)
{
throw SafeNativeMethods.Gdip.StatusException(status);
}
propitem = PropertyItemInternal.ConvertFromMemory(propdata, 1)[0];
}
finally
{
Marshal.FreeHGlobal(propdata);
}
return propitem;
}
/// <summary>
/// Removes the specified property item from this <see cref='Image'/>.
/// </summary>
public void RemovePropertyItem(int propid)
{
int status = SafeNativeMethods.Gdip.GdipRemovePropertyItem(new HandleRef(this, nativeImage), propid);
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
}
/// <summary>
/// Sets the specified property item to the specified value.
/// </summary>
public void SetPropertyItem(PropertyItem propitem)
{
PropertyItemInternal propItemInternal = PropertyItemInternal.ConvertFromPropertyItem(propitem);
using (propItemInternal)
{
int status = SafeNativeMethods.Gdip.GdipSetPropertyItem(new HandleRef(this, nativeImage), propItemInternal);
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
}
}
/// <summary>
/// Gets an array of <see cref='PropertyItem'/> objects that describe this <see cref='Image'/>.
/// </summary>
[Browsable(false)]
public PropertyItem[] PropertyItems
{
get
{
int size;
int count;
int status = SafeNativeMethods.Gdip.GdipGetPropertyCount(new HandleRef(this, nativeImage), out count);
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
status = SafeNativeMethods.Gdip.GdipGetPropertySize(new HandleRef(this, nativeImage), out size, ref count);
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
if (size == 0 || count == 0)
return new PropertyItem[0];
IntPtr propdata = Marshal.AllocHGlobal(size);
try
{
status = SafeNativeMethods.Gdip.GdipGetAllPropertyItems(new HandleRef(this, nativeImage), size, count, propdata);
if (status != SafeNativeMethods.Gdip.Ok)
{
throw SafeNativeMethods.Gdip.StatusException(status);
}
return PropertyItemInternal.ConvertFromMemory(propdata, count);
}
finally
{
Marshal.FreeHGlobal(propdata);
}
}
}
internal void SetNativeImage(IntPtr handle)
{
if (handle == IntPtr.Zero)
throw new ArgumentException(SR.Format(SR.NativeHandle0), "handle");
nativeImage = handle;
}
/// <summary>
/// Creates a <see cref='Bitmap'/> from a Windows handle.
/// </summary>
public static Bitmap FromHbitmap(IntPtr hbitmap)
{
return FromHbitmap(hbitmap, IntPtr.Zero);
}
/// <summary>
/// Creates a <see cref='Bitmap'/> from the specified Windows handle with the specified color palette.
/// </summary>
public static Bitmap FromHbitmap(IntPtr hbitmap, IntPtr hpalette)
{
IntPtr bitmap = IntPtr.Zero;
int status = SafeNativeMethods.Gdip.GdipCreateBitmapFromHBITMAP(new HandleRef(null, hbitmap), new HandleRef(null, hpalette), out bitmap);
if (status != SafeNativeMethods.Gdip.Ok)
throw SafeNativeMethods.Gdip.StatusException(status);
return Bitmap.FromGDIplus(bitmap);
}
/// <summary>
/// Returns the size of the specified pixel format.
/// </summary>
public static int GetPixelFormatSize(PixelFormat pixfmt)
{
return (unchecked((int)pixfmt) >> 8) & 0xFF;
}
/// <summary>
/// Returns a value indicating whether the pixel format contains alpha information.
/// </summary>
public static bool IsAlphaPixelFormat(PixelFormat pixfmt)
{
return (pixfmt & PixelFormat.Alpha) != 0;
}
/// <summary>
/// Returns a value indicating whether the pixel format is extended.
/// </summary>
public static bool IsExtendedPixelFormat(PixelFormat pixfmt)
{
return (pixfmt & PixelFormat.Extended) != 0;
}
/*
* Determine if the pixel format is canonical format:
* PixelFormat32bppARGB
* PixelFormat32bppPARGB
* PixelFormat64bppARGB
* PixelFormat64bppPARGB
*/
/// <summary>
/// Returns a value indicating whether the pixel format is canonical.
/// </summary>
public static bool IsCanonicalPixelFormat(PixelFormat pixfmt)
{
return (pixfmt & PixelFormat.Canonical) != 0;
}
}
}
| |
//----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//----------------------------------------------------------------------------
namespace System.ServiceModel.Channels
{
using System.Runtime;
using System.ServiceModel.Dispatcher;
using System.Threading;
sealed class InternalDuplexChannelFactory : LayeredChannelFactory<IDuplexChannel>
{
static long channelCount = 0;
InputChannelDemuxer channelDemuxer;
IChannelFactory<IOutputChannel> innerChannelFactory;
IChannelListener<IInputChannel> innerChannelListener;
LocalAddressProvider localAddressProvider;
bool providesCorrelation;
internal InternalDuplexChannelFactory(InternalDuplexBindingElement bindingElement, BindingContext context,
InputChannelDemuxer channelDemuxer,
IChannelFactory<IOutputChannel> innerChannelFactory, LocalAddressProvider localAddressProvider)
: base(context.Binding, innerChannelFactory)
{
this.channelDemuxer = channelDemuxer;
this.innerChannelFactory = innerChannelFactory;
ChannelDemuxerFilter demuxFilter = new ChannelDemuxerFilter(new MatchNoneMessageFilter(), int.MinValue);
this.innerChannelListener = this.channelDemuxer.BuildChannelListener<IInputChannel>(demuxFilter);
this.localAddressProvider = localAddressProvider;
this.providesCorrelation = bindingElement.ProvidesCorrelation;
}
bool CreateUniqueLocalAddress(out EndpointAddress address, out int priority)
{
long tempChannelCount = Interlocked.Increment(ref channelCount);
if (tempChannelCount > 1)
{
AddressHeader uniqueEndpointHeader = AddressHeader.CreateAddressHeader(XD.UtilityDictionary.UniqueEndpointHeaderName,
XD.UtilityDictionary.UniqueEndpointHeaderNamespace, tempChannelCount);
address = new EndpointAddress(this.innerChannelListener.Uri, uniqueEndpointHeader);
priority = 1;
return true;
}
else
{
address = new EndpointAddress(this.innerChannelListener.Uri);
priority = 0;
return false;
}
}
protected override IDuplexChannel OnCreateChannel(EndpointAddress address, Uri via)
{
EndpointAddress localAddress;
int priority;
MessageFilter filter;
// determines whether the CompositeDuplex channels created from this factory expect the UniqueEndpoint (ChannelInstance) header in its messages
bool useUniqueHeader = false;
if (localAddressProvider != null)
{
localAddress = localAddressProvider.LocalAddress;
filter = localAddressProvider.Filter;
priority = localAddressProvider.Priority;
}
else
{
useUniqueHeader = CreateUniqueLocalAddress(out localAddress, out priority);
filter = new MatchAllMessageFilter();
}
return this.CreateChannel(address, via, localAddress, filter, priority, useUniqueHeader);
}
public IDuplexChannel CreateChannel(EndpointAddress address, Uri via, MessageFilter filter, int priority, bool usesUniqueHeader)
{
return this.CreateChannel(address, via, new EndpointAddress(this.innerChannelListener.Uri), filter, priority, usesUniqueHeader);
}
public IDuplexChannel CreateChannel(EndpointAddress remoteAddress, Uri via, EndpointAddress localAddress, MessageFilter filter, int priority, bool usesUniqueHeader)
{
ChannelDemuxerFilter demuxFilter = new ChannelDemuxerFilter(new AndMessageFilter(new EndpointAddressMessageFilter(localAddress, true), filter), priority);
IDuplexChannel newChannel = null;
IOutputChannel innerOutputChannel = null;
IChannelListener<IInputChannel> innerInputListener = null;
IInputChannel innerInputChannel = null;
try
{
innerOutputChannel = this.innerChannelFactory.CreateChannel(remoteAddress, via);
innerInputListener = this.channelDemuxer.BuildChannelListener<IInputChannel>(demuxFilter);
innerInputListener.Open();
innerInputChannel = innerInputListener.AcceptChannel();
newChannel = new ClientCompositeDuplexChannel(this, innerInputChannel, innerInputListener, localAddress, innerOutputChannel, usesUniqueHeader);
}
finally
{
if (newChannel == null) // need to cleanup
{
if (innerOutputChannel != null)
{
innerOutputChannel.Close();
}
if (innerInputListener != null)
{
innerInputListener.Close();
}
if (innerInputChannel != null)
{
innerInputChannel.Close();
}
}
}
return newChannel;
}
protected override void OnAbort()
{
base.OnAbort();
this.innerChannelListener.Abort();
}
protected override void OnOpen(TimeSpan timeout)
{
TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
base.OnOpen(timeoutHelper.RemainingTime());
this.innerChannelListener.Open(timeoutHelper.RemainingTime());
}
protected override IAsyncResult OnBeginOpen(TimeSpan timeout, AsyncCallback callback, object state)
{
return new ChainedOpenAsyncResult(timeout, callback, state, base.OnBeginOpen, base.OnEndOpen, this.innerChannelListener);
}
protected override void OnEndOpen(IAsyncResult result)
{
ChainedOpenAsyncResult.End(result);
}
protected override void OnClose(TimeSpan timeout)
{
TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
base.OnClose(timeoutHelper.RemainingTime());
this.innerChannelListener.Close(timeoutHelper.RemainingTime());
}
protected override IAsyncResult OnBeginClose(TimeSpan timeout, AsyncCallback callback, object state)
{
return new ChainedCloseAsyncResult(timeout, callback, state, base.OnBeginClose, base.OnEndClose, this.innerChannelListener);
}
protected override void OnEndClose(IAsyncResult result)
{
ChainedCloseAsyncResult.End(result);
}
public override T GetProperty<T>()
{
if (typeof(T) == typeof(IChannelListener))
{
return (T)(object)innerChannelListener;
}
if (typeof(T) == typeof(ISecurityCapabilities) && !this.providesCorrelation)
{
return InternalDuplexBindingElement.GetSecurityCapabilities<T>(base.GetProperty<ISecurityCapabilities>());
}
T baseProperty = base.GetProperty<T>();
if (baseProperty != null)
{
return baseProperty;
}
IChannelListener channelListener = innerChannelListener;
if (channelListener != null)
{
return channelListener.GetProperty<T>();
}
else
{
return default(T);
}
}
class ClientCompositeDuplexChannel : LayeredDuplexChannel
{
IChannelListener<IInputChannel> innerInputListener;
bool usesUniqueHeader; // Perf optimization - don't check message headers if we know there's only one CompositeDuplexChannel created
public ClientCompositeDuplexChannel(ChannelManagerBase channelManager, IInputChannel innerInputChannel, IChannelListener<IInputChannel> innerInputListener, EndpointAddress localAddress, IOutputChannel innerOutputChannel, bool usesUniqueHeader)
: base(channelManager, innerInputChannel, localAddress, innerOutputChannel)
{
this.innerInputListener = innerInputListener;
this.usesUniqueHeader = usesUniqueHeader;
}
protected override void OnAbort()
{
base.OnAbort();
this.innerInputListener.Abort();
}
protected override IAsyncResult OnBeginClose(TimeSpan timeout, AsyncCallback callback, object state)
{
return new ChainedAsyncResult(timeout, callback, state, base.OnBeginClose, base.OnEndClose, this.innerInputListener.BeginClose, this.innerInputListener.EndClose);
}
protected override void OnClose(TimeSpan timeout)
{
TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
base.OnClose(timeoutHelper.RemainingTime());
this.innerInputListener.Close(timeoutHelper.RemainingTime());
}
protected override void OnEndClose(IAsyncResult result)
{
ChainedAsyncResult.End(result);
}
protected override void OnReceive(Message message)
{
// Mark ChannelInstance header ref params as Understood on message
// MessageFilters will take care of proper routing of the message, but we need to mark it as understood here.
if (usesUniqueHeader)
{
// 3.0 allows for messages to be received with duplicate message headers; we cannot
// use MessageHeaders.FindHeader() to find the header because it will throw an exception
// if it encounters duplicate headers. We instead have to look through all headers.
for (int i = 0; i < message.Headers.Count; i++)
{
if (message.Headers[i].Name == XD.UtilityDictionary.UniqueEndpointHeaderName.Value &&
message.Headers[i].Namespace == XD.UtilityDictionary.UniqueEndpointHeaderNamespace.Value)
{
message.Headers.AddUnderstood(i);
}
}
}
}
}
}
}
| |
// Copyright 2015 Coinprism, 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.
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: schema.proto
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace Openchain.Messages {
/// <summary>Holder for reflection information generated from schema.proto</summary>
internal static partial class SchemaReflection {
#region Descriptor
/// <summary>File descriptor for schema.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static SchemaReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"CgxzY2hlbWEucHJvdG8SCU9wZW5jaGFpbiIbCgtSZWNvcmRWYWx1ZRIMCgRk",
"YXRhGAEgASgMIk0KBlJlY29yZBILCgNrZXkYASABKAwSJQoFdmFsdWUYAiAB",
"KAsyFi5PcGVuY2hhaW4uUmVjb3JkVmFsdWUSDwoHdmVyc2lvbhgDIAEoDCJT",
"CghNdXRhdGlvbhIRCgluYW1lc3BhY2UYASABKAwSIgoHcmVjb3JkcxgCIAMo",
"CzIRLk9wZW5jaGFpbi5SZWNvcmQSEAoIbWV0YWRhdGEYAyABKAwiUAoLVHJh",
"bnNhY3Rpb24SEAoIbXV0YXRpb24YASABKAwSEQoJdGltZXN0YW1wGAIgASgD",
"EhwKFHRyYW5zYWN0aW9uX21ldGFkYXRhGAMgASgMYgZwcm90bzM="));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::Openchain.Messages.RecordValue), global::Openchain.Messages.RecordValue.Parser, new[]{ "Data" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Openchain.Messages.Record), global::Openchain.Messages.Record.Parser, new[]{ "Key", "Value", "Version" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Openchain.Messages.Mutation), global::Openchain.Messages.Mutation.Parser, new[]{ "Namespace", "Records", "Metadata" }, null, null, null),
new pbr::GeneratedClrTypeInfo(typeof(global::Openchain.Messages.Transaction), global::Openchain.Messages.Transaction.Parser, new[]{ "Mutation", "Timestamp", "TransactionMetadata" }, null, null, null)
}));
}
#endregion
}
#region Messages
internal sealed partial class RecordValue : pb::IMessage<RecordValue> {
private static readonly pb::MessageParser<RecordValue> _parser = new pb::MessageParser<RecordValue>(() => new RecordValue());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<RecordValue> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Openchain.Messages.SchemaReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public RecordValue() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public RecordValue(RecordValue other) : this() {
data_ = other.data_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public RecordValue Clone() {
return new RecordValue(this);
}
/// <summary>Field number for the "data" field.</summary>
public const int DataFieldNumber = 1;
private pb::ByteString data_ = pb::ByteString.Empty;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pb::ByteString Data {
get { return data_; }
set {
data_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as RecordValue);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(RecordValue other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Data != other.Data) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (Data.Length != 0) hash ^= Data.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (Data.Length != 0) {
output.WriteRawTag(10);
output.WriteBytes(Data);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (Data.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeBytesSize(Data);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(RecordValue other) {
if (other == null) {
return;
}
if (other.Data.Length != 0) {
Data = other.Data;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
Data = input.ReadBytes();
break;
}
}
}
}
}
internal sealed partial class Record : pb::IMessage<Record> {
private static readonly pb::MessageParser<Record> _parser = new pb::MessageParser<Record>(() => new Record());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<Record> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Openchain.Messages.SchemaReflection.Descriptor.MessageTypes[1]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Record() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Record(Record other) : this() {
key_ = other.key_;
Value = other.value_ != null ? other.Value.Clone() : null;
version_ = other.version_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Record Clone() {
return new Record(this);
}
/// <summary>Field number for the "key" field.</summary>
public const int KeyFieldNumber = 1;
private pb::ByteString key_ = pb::ByteString.Empty;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pb::ByteString Key {
get { return key_; }
set {
key_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "value" field.</summary>
public const int ValueFieldNumber = 2;
private global::Openchain.Messages.RecordValue value_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::Openchain.Messages.RecordValue Value {
get { return value_; }
set {
value_ = value;
}
}
/// <summary>Field number for the "version" field.</summary>
public const int VersionFieldNumber = 3;
private pb::ByteString version_ = pb::ByteString.Empty;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pb::ByteString Version {
get { return version_; }
set {
version_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as Record);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(Record other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Key != other.Key) return false;
if (!object.Equals(Value, other.Value)) return false;
if (Version != other.Version) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (Key.Length != 0) hash ^= Key.GetHashCode();
if (value_ != null) hash ^= Value.GetHashCode();
if (Version.Length != 0) hash ^= Version.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (Key.Length != 0) {
output.WriteRawTag(10);
output.WriteBytes(Key);
}
if (value_ != null) {
output.WriteRawTag(18);
output.WriteMessage(Value);
}
if (Version.Length != 0) {
output.WriteRawTag(26);
output.WriteBytes(Version);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (Key.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeBytesSize(Key);
}
if (value_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(Value);
}
if (Version.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeBytesSize(Version);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(Record other) {
if (other == null) {
return;
}
if (other.Key.Length != 0) {
Key = other.Key;
}
if (other.value_ != null) {
if (value_ == null) {
value_ = new global::Openchain.Messages.RecordValue();
}
Value.MergeFrom(other.Value);
}
if (other.Version.Length != 0) {
Version = other.Version;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
Key = input.ReadBytes();
break;
}
case 18: {
if (value_ == null) {
value_ = new global::Openchain.Messages.RecordValue();
}
input.ReadMessage(value_);
break;
}
case 26: {
Version = input.ReadBytes();
break;
}
}
}
}
}
internal sealed partial class Mutation : pb::IMessage<Mutation> {
private static readonly pb::MessageParser<Mutation> _parser = new pb::MessageParser<Mutation>(() => new Mutation());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<Mutation> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Openchain.Messages.SchemaReflection.Descriptor.MessageTypes[2]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Mutation() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Mutation(Mutation other) : this() {
namespace_ = other.namespace_;
records_ = other.records_.Clone();
metadata_ = other.metadata_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Mutation Clone() {
return new Mutation(this);
}
/// <summary>Field number for the "namespace" field.</summary>
public const int NamespaceFieldNumber = 1;
private pb::ByteString namespace_ = pb::ByteString.Empty;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pb::ByteString Namespace {
get { return namespace_; }
set {
namespace_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "records" field.</summary>
public const int RecordsFieldNumber = 2;
private static readonly pb::FieldCodec<global::Openchain.Messages.Record> _repeated_records_codec
= pb::FieldCodec.ForMessage(18, global::Openchain.Messages.Record.Parser);
private readonly pbc::RepeatedField<global::Openchain.Messages.Record> records_ = new pbc::RepeatedField<global::Openchain.Messages.Record>();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pbc::RepeatedField<global::Openchain.Messages.Record> Records {
get { return records_; }
}
/// <summary>Field number for the "metadata" field.</summary>
public const int MetadataFieldNumber = 3;
private pb::ByteString metadata_ = pb::ByteString.Empty;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pb::ByteString Metadata {
get { return metadata_; }
set {
metadata_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as Mutation);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(Mutation other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Namespace != other.Namespace) return false;
if(!records_.Equals(other.records_)) return false;
if (Metadata != other.Metadata) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (Namespace.Length != 0) hash ^= Namespace.GetHashCode();
hash ^= records_.GetHashCode();
if (Metadata.Length != 0) hash ^= Metadata.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (Namespace.Length != 0) {
output.WriteRawTag(10);
output.WriteBytes(Namespace);
}
records_.WriteTo(output, _repeated_records_codec);
if (Metadata.Length != 0) {
output.WriteRawTag(26);
output.WriteBytes(Metadata);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (Namespace.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeBytesSize(Namespace);
}
size += records_.CalculateSize(_repeated_records_codec);
if (Metadata.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeBytesSize(Metadata);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(Mutation other) {
if (other == null) {
return;
}
if (other.Namespace.Length != 0) {
Namespace = other.Namespace;
}
records_.Add(other.records_);
if (other.Metadata.Length != 0) {
Metadata = other.Metadata;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
Namespace = input.ReadBytes();
break;
}
case 18: {
records_.AddEntriesFrom(input, _repeated_records_codec);
break;
}
case 26: {
Metadata = input.ReadBytes();
break;
}
}
}
}
}
internal sealed partial class Transaction : pb::IMessage<Transaction> {
private static readonly pb::MessageParser<Transaction> _parser = new pb::MessageParser<Transaction>(() => new Transaction());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<Transaction> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Openchain.Messages.SchemaReflection.Descriptor.MessageTypes[3]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Transaction() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Transaction(Transaction other) : this() {
mutation_ = other.mutation_;
timestamp_ = other.timestamp_;
transactionMetadata_ = other.transactionMetadata_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Transaction Clone() {
return new Transaction(this);
}
/// <summary>Field number for the "mutation" field.</summary>
public const int MutationFieldNumber = 1;
private pb::ByteString mutation_ = pb::ByteString.Empty;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pb::ByteString Mutation {
get { return mutation_; }
set {
mutation_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "timestamp" field.</summary>
public const int TimestampFieldNumber = 2;
private long timestamp_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public long Timestamp {
get { return timestamp_; }
set {
timestamp_ = value;
}
}
/// <summary>Field number for the "transaction_metadata" field.</summary>
public const int TransactionMetadataFieldNumber = 3;
private pb::ByteString transactionMetadata_ = pb::ByteString.Empty;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public pb::ByteString TransactionMetadata {
get { return transactionMetadata_; }
set {
transactionMetadata_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as Transaction);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(Transaction other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Mutation != other.Mutation) return false;
if (Timestamp != other.Timestamp) return false;
if (TransactionMetadata != other.TransactionMetadata) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (Mutation.Length != 0) hash ^= Mutation.GetHashCode();
if (Timestamp != 0L) hash ^= Timestamp.GetHashCode();
if (TransactionMetadata.Length != 0) hash ^= TransactionMetadata.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (Mutation.Length != 0) {
output.WriteRawTag(10);
output.WriteBytes(Mutation);
}
if (Timestamp != 0L) {
output.WriteRawTag(16);
output.WriteInt64(Timestamp);
}
if (TransactionMetadata.Length != 0) {
output.WriteRawTag(26);
output.WriteBytes(TransactionMetadata);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (Mutation.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeBytesSize(Mutation);
}
if (Timestamp != 0L) {
size += 1 + pb::CodedOutputStream.ComputeInt64Size(Timestamp);
}
if (TransactionMetadata.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeBytesSize(TransactionMetadata);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(Transaction other) {
if (other == null) {
return;
}
if (other.Mutation.Length != 0) {
Mutation = other.Mutation;
}
if (other.Timestamp != 0L) {
Timestamp = other.Timestamp;
}
if (other.TransactionMetadata.Length != 0) {
TransactionMetadata = other.TransactionMetadata;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
Mutation = input.ReadBytes();
break;
}
case 16: {
Timestamp = input.ReadInt64();
break;
}
case 26: {
TransactionMetadata = input.ReadBytes();
break;
}
}
}
}
}
#endregion
}
#endregion Designer generated code
| |
// ------------------------------------------------------------------------------
// 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 InferenceClassificationOverridesCollectionRequest.
/// </summary>
public partial class InferenceClassificationOverridesCollectionRequest : BaseRequest, IInferenceClassificationOverridesCollectionRequest
{
/// <summary>
/// Constructs a new InferenceClassificationOverridesCollectionRequest.
/// </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 InferenceClassificationOverridesCollectionRequest(
string requestUrl,
IBaseClient client,
IEnumerable<Option> options)
: base(requestUrl, client, options)
{
}
/// <summary>
/// Adds the specified InferenceClassificationOverride to the collection via POST.
/// </summary>
/// <param name="inferenceClassificationOverride">The InferenceClassificationOverride to add.</param>
/// <returns>The created InferenceClassificationOverride.</returns>
public System.Threading.Tasks.Task<InferenceClassificationOverride> AddAsync(InferenceClassificationOverride inferenceClassificationOverride)
{
return this.AddAsync(inferenceClassificationOverride, CancellationToken.None);
}
/// <summary>
/// Adds the specified InferenceClassificationOverride to the collection via POST.
/// </summary>
/// <param name="inferenceClassificationOverride">The InferenceClassificationOverride to add.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The created InferenceClassificationOverride.</returns>
public System.Threading.Tasks.Task<InferenceClassificationOverride> AddAsync(InferenceClassificationOverride inferenceClassificationOverride, CancellationToken cancellationToken)
{
this.ContentType = "application/json";
this.Method = "POST";
return this.SendAsync<InferenceClassificationOverride>(inferenceClassificationOverride, cancellationToken);
}
/// <summary>
/// Gets the collection page.
/// </summary>
/// <returns>The collection page.</returns>
public System.Threading.Tasks.Task<IInferenceClassificationOverridesCollectionPage> 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<IInferenceClassificationOverridesCollectionPage> GetAsync(CancellationToken cancellationToken)
{
this.Method = "GET";
var response = await this.SendAsync<InferenceClassificationOverridesCollectionResponse>(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 IInferenceClassificationOverridesCollectionRequest 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 IInferenceClassificationOverridesCollectionRequest Expand(Expression<Func<InferenceClassificationOverride, 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 IInferenceClassificationOverridesCollectionRequest 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 IInferenceClassificationOverridesCollectionRequest Select(Expression<Func<InferenceClassificationOverride, 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 IInferenceClassificationOverridesCollectionRequest 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 IInferenceClassificationOverridesCollectionRequest 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 IInferenceClassificationOverridesCollectionRequest 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 IInferenceClassificationOverridesCollectionRequest OrderBy(string value)
{
this.QueryOptions.Add(new QueryOption("$orderby", value));
return this;
}
}
}
| |
/*
* Copyright (c) 2009, openmetaverse.org
* All rights reserved.
*
* - Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* - Neither the name of the openmetaverse.org nor the names
* of its contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Net;
using System.Net.Security;
using System.IO;
using System.Text;
using System.Threading;
using System.Security.Cryptography.X509Certificates;
namespace OpenMetaverse.Http
{
public class TrustAllCertificatePolicy : ICertificatePolicy
{
public bool CheckValidationResult(ServicePoint sp, X509Certificate cert, WebRequest req, int problem)
{
return true;
}
public static bool TrustAllCertificateHandler(Object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
return true;
}
}
public static class CapsBase
{
public delegate void OpenWriteEventHandler(HttpWebRequest request);
public delegate void DownloadProgressEventHandler(HttpWebRequest request, HttpWebResponse response, int bytesReceived, int totalBytesToReceive);
public delegate void RequestCompletedEventHandler(HttpWebRequest request, HttpWebResponse response, byte[] responseData, Exception error);
static CapsBase()
{
ServicePointManager.CertificatePolicy = new TrustAllCertificatePolicy();
// Even though this will compile on Mono 2.4, it throws a runtime exception
//ServicePointManager.ServerCertificateValidationCallback = TrustAllCertificatePolicy.TrustAllCertificateHandler;
}
private class RequestState
{
public HttpWebRequest Request;
public byte[] UploadData;
public int MillisecondsTimeout;
public OpenWriteEventHandler OpenWriteCallback;
public DownloadProgressEventHandler DownloadProgressCallback;
public RequestCompletedEventHandler CompletedCallback;
public RequestState(HttpWebRequest request, byte[] uploadData, int millisecondsTimeout, OpenWriteEventHandler openWriteCallback,
DownloadProgressEventHandler downloadProgressCallback, RequestCompletedEventHandler completedCallback)
{
Request = request;
UploadData = uploadData;
MillisecondsTimeout = millisecondsTimeout;
OpenWriteCallback = openWriteCallback;
DownloadProgressCallback = downloadProgressCallback;
CompletedCallback = completedCallback;
}
}
public static HttpWebRequest UploadDataAsync(Uri address, X509Certificate2 clientCert, string contentType, byte[] data,
int millisecondsTimeout, OpenWriteEventHandler openWriteCallback, DownloadProgressEventHandler downloadProgressCallback,
RequestCompletedEventHandler completedCallback)
{
// Create the request
HttpWebRequest request = SetupRequest(address, clientCert);
request.ContentLength = data.Length;
if (!String.IsNullOrEmpty(contentType))
request.ContentType = contentType;
request.Method = "POST";
// Create an object to hold all of the state for this request
RequestState state = new RequestState(request, data, millisecondsTimeout, openWriteCallback,
downloadProgressCallback, completedCallback);
// Start the request for a stream to upload to
IAsyncResult result = request.BeginGetRequestStream(OpenWrite, state);
// Register a timeout for the request
ThreadPool.RegisterWaitForSingleObject(result.AsyncWaitHandle, TimeoutCallback, state, millisecondsTimeout, true);
return request;
}
public static HttpWebRequest DownloadStringAsync(Uri address, X509Certificate2 clientCert, int millisecondsTimeout,
DownloadProgressEventHandler downloadProgressCallback, RequestCompletedEventHandler completedCallback)
{
// Create the request
HttpWebRequest request = SetupRequest(address, clientCert);
request.Method = "GET";
DownloadDataAsync(request, millisecondsTimeout, downloadProgressCallback, completedCallback);
return request;
}
public static void DownloadDataAsync(HttpWebRequest request, int millisecondsTimeout,
DownloadProgressEventHandler downloadProgressCallback, RequestCompletedEventHandler completedCallback)
{
// Create an object to hold all of the state for this request
RequestState state = new RequestState(request, null, millisecondsTimeout, null, downloadProgressCallback,
completedCallback);
// Start the request for the remote server response
IAsyncResult result = request.BeginGetResponse(GetResponse, state);
// Register a timeout for the request
ThreadPool.RegisterWaitForSingleObject(result.AsyncWaitHandle, TimeoutCallback, state, millisecondsTimeout, true);
}
static HttpWebRequest SetupRequest(Uri address, X509Certificate2 clientCert)
{
if (address == null)
throw new ArgumentNullException("address");
// Create the request
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(address);
// Add the client certificate to the request if one was given
if (clientCert != null)
request.ClientCertificates.Add(clientCert);
// Leave idle connections to this endpoint open for up to 60 seconds
request.ServicePoint.MaxIdleTime = 1000 * 60;
// Disable stupid Expect-100: Continue header
request.ServicePoint.Expect100Continue = false;
// Crank up the max number of connections per endpoint (default is 2!)
request.ServicePoint.ConnectionLimit = Math.Max(request.ServicePoint.ConnectionLimit, 32);
// Caps requests are never sent as trickles of data, so Nagle's
// coalescing algorithm won't help us
request.ServicePoint.UseNagleAlgorithm = false;
// If not on mono, set accept-encoding header that allows response compression
if (Type.GetType("Mono.Runtime") == null)
{
request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
}
return request;
}
static void OpenWrite(IAsyncResult ar)
{
RequestState state = (RequestState)ar.AsyncState;
try
{
// Get the stream to write our upload to
using (Stream uploadStream = state.Request.EndGetRequestStream(ar))
{
// Fire the callback for successfully opening the stream
if (state.OpenWriteCallback != null)
state.OpenWriteCallback(state.Request);
// Write our data to the upload stream
uploadStream.Write(state.UploadData, 0, state.UploadData.Length);
}
// Start the request for the remote server response
IAsyncResult result = state.Request.BeginGetResponse(GetResponse, state);
// Register a timeout for the request
ThreadPool.RegisterWaitForSingleObject(result.AsyncWaitHandle, TimeoutCallback, state,
state.MillisecondsTimeout, true);
}
catch (Exception ex)
{
//Logger.Log.Debug("CapsBase.OpenWrite(): " + ex.Message);
if (state.CompletedCallback != null)
state.CompletedCallback(state.Request, null, null, ex);
}
}
static void GetResponse(IAsyncResult ar)
{
RequestState state = (RequestState)ar.AsyncState;
HttpWebResponse response = null;
byte[] responseData = null;
Exception error = null;
try
{
response = (HttpWebResponse)state.Request.EndGetResponse(ar);
// Get the stream for downloading the response
using (Stream responseStream = response.GetResponseStream())
{
#region Read the response
// If Content-Length is set we create a buffer of the exact size, otherwise
// a MemoryStream is used to receive the response
bool nolength = (response.ContentLength <= 0);
int size = (nolength) ? 8192 : (int)response.ContentLength;
MemoryStream ms = (nolength) ? new MemoryStream() : null;
byte[] buffer = new byte[size];
int bytesRead = 0;
int offset = 0;
int totalBytesRead = 0;
int totalSize = nolength ? 0 : size;
while ((bytesRead = responseStream.Read(buffer, offset, size)) != 0)
{
totalBytesRead += bytesRead;
if (nolength)
{
totalSize += (size - bytesRead);
ms.Write(buffer, 0, bytesRead);
}
else
{
offset += bytesRead;
size -= bytesRead;
}
// Fire the download progress callback for each chunk of received data
if (state.DownloadProgressCallback != null)
state.DownloadProgressCallback(state.Request, response, totalBytesRead, totalSize);
}
if (nolength)
{
responseData = ms.ToArray();
ms.Close();
ms.Dispose();
}
else
{
responseData = buffer;
}
#endregion Read the response
responseStream.Close();
}
}
catch (Exception ex)
{
// Logger.DebugLog("CapsBase.GetResponse(): " + ex.Message);
error = ex;
}
if (state.CompletedCallback != null)
state.CompletedCallback(state.Request, response, responseData, error);
}
static void TimeoutCallback(object state, bool timedOut)
{
if (timedOut)
{
RequestState requestState = state as RequestState;
//Logger.Log.Debug("CapsBase.TimeoutCallback(): Request to " + requestState.Request.RequestUri +
// " timed out after " + requestState.MillisecondsTimeout + " milliseconds");
if (requestState != null && requestState.Request != null)
requestState.Request.Abort();
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Dynamic;
using System.Linq;
using Microsoft.AspNetCore.Html;
using Microsoft.AspNetCore.Mvc.Rendering;
using Newtonsoft.Json;
using OrchardCore.DisplayManagement.Zones;
namespace OrchardCore.DisplayManagement.Shapes
{
[DebuggerTypeProxy(typeof(ShapeDebugView))]
public class Shape : Composite, IShape, IPositioned, IEnumerable<object>
{
private List<string> _classes;
private Dictionary<string, string> _attributes;
private List<IPositioned> _items = new List<IPositioned>();
private bool _sorted = false;
public ShapeMetadata Metadata { get; } = new ShapeMetadata();
public string Id { get; set; }
public string TagName { get; set; }
public IList<string> Classes => _classes ??= new List<string>();
public IDictionary<string, string> Attributes => _attributes ??= new Dictionary<string, string>();
public IEnumerable<dynamic> Items
{
get
{
if (!_sorted)
{
_items = _items.OrderBy(x => x, FlatPositionComparer.Instance).ToList();
_sorted = true;
}
return _items;
}
}
public bool HasItems => _items.Count > 0;
public string Position
{
get { return Metadata.Position; }
set { Metadata.Position = value; }
}
public virtual Shape Add(object item, string position = null)
{
if (item == null)
{
return this;
}
if (position == null)
{
position = "";
}
_sorted = false;
if (item is IHtmlContent)
{
_items.Add(new PositionWrapper((IHtmlContent)item, position));
}
else if (item is string)
{
_items.Add(new PositionWrapper((string)item, position));
}
else
{
var shape = item as IPositioned;
if (shape != null)
{
if (position != null)
{
shape.Position = position;
}
_items.Add(shape);
}
}
return this;
}
public Shape AddRange(IEnumerable<object> items, string position = null)
{
foreach (var item in items)
{
Add(item, position);
}
return this;
}
public void Remove(string shapeName)
{
for (var i = _items.Count - 1; i >= 0; i--)
{
if (_items[i] is IShape shape && shape.Metadata.Name == shapeName)
{
_items.RemoveAt(i);
return;
}
}
}
public IShape Named(string shapeName)
{
for (var i = 0; i < _items.Count; i++)
{
if (_items[i] is IShape shape && shape.Metadata.Name == shapeName)
{
return shape;
}
}
return null;
}
public IShape NormalizedNamed(string shapeName)
{
for (var i = 0; i < _items.Count; i++)
{
if (_items[i] is IShape shape && shape.Metadata.Name?.Replace("__", "-") == shapeName)
{
return shape;
}
}
return null;
}
IEnumerator<object> IEnumerable<object>.GetEnumerator()
{
if (!_sorted)
{
_items = _items.OrderBy(x => x, FlatPositionComparer.Instance).ToList();
_sorted = true;
}
return _items.GetEnumerator();
}
public IEnumerator GetEnumerator()
{
if (!_sorted)
{
_items = _items.OrderBy(x => x, FlatPositionComparer.Instance).ToList();
_sorted = true;
}
return _items.GetEnumerator();
}
public override bool TryConvert(ConvertBinder binder, out object result)
{
result = Items;
if (binder.ReturnType == typeof(IEnumerable<object>) ||
binder.ReturnType == typeof(IEnumerable<dynamic>))
{
return true;
}
return base.TryConvert(binder, out result);
}
public static TagBuilder GetTagBuilder(Shape shape, string defaultTagName = "span")
{
var tagName = defaultTagName;
// We keep this for backward compatibility
if (shape.Properties.TryGetValue("Tag", out var value) && value is string valueString)
{
tagName = valueString;
}
if (!String.IsNullOrEmpty(shape.TagName))
{
tagName = shape.TagName;
}
return GetTagBuilder(tagName, shape.Id, shape.Classes, shape.Attributes);
}
public static TagBuilder GetTagBuilder(string tagName, string id, IEnumerable<string> classes, IDictionary<string, string> attributes)
{
var tagBuilder = new TagBuilder(tagName);
if (attributes != null)
{
tagBuilder.MergeAttributes(attributes, false);
}
foreach (var cssClass in classes ?? Enumerable.Empty<string>())
{
tagBuilder.AddCssClass(cssClass);
}
if (!String.IsNullOrWhiteSpace(id))
{
tagBuilder.Attributes["id"] = id;
}
return tagBuilder;
}
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
var name = binder.Name;
if (!base.TryGetMember(binder, out result) || (null == result))
{
// Try to get a Named shape
result = Named(name);
if (result == null)
{
result = NormalizedNamed(name.Replace("__", "-"));
}
}
return true;
}
protected override bool TrySetMemberImpl(string name, object value)
{
// We set the Shape real properties for Razor
if (name == "Id")
{
Id = value as string;
return true;
}
if (name == "TagName")
{
TagName = value as string;
return true;
}
if (name == "Attributes")
{
if (value is Dictionary<string, string> attributes)
{
foreach (var attribute in attributes)
{
Attributes.TryAdd(attribute.Key, attribute.Value);
}
}
if (value is string stringValue)
{
attributes = JsonConvert.DeserializeObject<Dictionary<string, string>>(stringValue);
foreach (var attribute in attributes)
{
Attributes.TryAdd(attribute.Key, attribute.Value);
}
}
}
if (name == "Classes")
{
if (value is List<string> classes)
{
foreach (var item in classes)
{
Classes.Add(item);
}
}
if (value is string stringValue)
{
var values = stringValue.Split(' ', StringSplitOptions.RemoveEmptyEntries);
foreach (var item in values)
{
Classes.Add(item);
}
}
}
base.TrySetMemberImpl(name, value);
return true;
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using Microsoft.Azure.Commands.Compute.Automation.Models;
using Microsoft.Azure.Management.Compute.Models;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation;
namespace Microsoft.Azure.Commands.Compute.Automation
{
[Cmdlet(VerbsCommon.Set, ResourceManager.Common.AzureRMConstants.AzureRMPrefix + "VmssOsProfile", SupportsShouldProcess = true)]
[OutputType(typeof(PSVirtualMachineScaleSet))]
public partial class SetAzureRmVmssOsProfileCommand : Microsoft.Azure.Commands.ResourceManager.Common.AzureRMCmdlet
{
[Parameter(
Mandatory = true,
Position = 0,
ValueFromPipeline = true,
ValueFromPipelineByPropertyName = true)]
public PSVirtualMachineScaleSet VirtualMachineScaleSet { get; set; }
[Parameter(
Mandatory = false,
Position = 1,
ValueFromPipelineByPropertyName = true)]
public string ComputerNamePrefix { get; set; }
[Parameter(
Mandatory = false,
Position = 2,
ValueFromPipelineByPropertyName = true)]
public string AdminUsername { get; set; }
[Parameter(
Mandatory = false,
Position = 3,
ValueFromPipelineByPropertyName = true)]
public string AdminPassword { get; set; }
[Parameter(
Mandatory = false,
Position = 4,
ValueFromPipelineByPropertyName = true)]
public string CustomData { get; set; }
[Parameter(
Mandatory = false,
Position = 5,
ValueFromPipelineByPropertyName = true)]
public bool? WindowsConfigurationProvisionVMAgent { get; set; }
[Parameter(
Mandatory = false,
Position = 6,
ValueFromPipelineByPropertyName = true)]
public bool? WindowsConfigurationEnableAutomaticUpdate { get; set; }
[Parameter(
Mandatory = false,
Position = 7,
ValueFromPipelineByPropertyName = true)]
public string TimeZone { get; set; }
[Parameter(
Mandatory = false,
Position = 8,
ValueFromPipelineByPropertyName = true)]
public AdditionalUnattendContent[] AdditionalUnattendContent { get; set; }
[Parameter(
Mandatory = false,
Position = 9,
ValueFromPipelineByPropertyName = true)]
public WinRMListener[] Listener { get; set; }
[Parameter(
Mandatory = false,
Position = 10,
ValueFromPipelineByPropertyName = true)]
public bool? LinuxConfigurationDisablePasswordAuthentication { get; set; }
[Parameter(
Mandatory = false,
Position = 11,
ValueFromPipelineByPropertyName = true)]
public SshPublicKey[] PublicKey { get; set; }
[Parameter(
Mandatory = false,
Position = 12,
ValueFromPipelineByPropertyName = true)]
public VaultSecretGroup[] Secret { get; set; }
protected override void ProcessRecord()
{
if (ShouldProcess("VirtualMachineScaleSet", "Set"))
{
Run();
}
}
private void Run()
{
if (this.MyInvocation.BoundParameters.ContainsKey("ComputerNamePrefix"))
{
// VirtualMachineProfile
if (this.VirtualMachineScaleSet.VirtualMachineProfile == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetVMProfile();
}
// OsProfile
if (this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetOSProfile();
}
this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile.ComputerNamePrefix = this.ComputerNamePrefix;
}
if (this.MyInvocation.BoundParameters.ContainsKey("AdminUsername"))
{
// VirtualMachineProfile
if (this.VirtualMachineScaleSet.VirtualMachineProfile == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetVMProfile();
}
// OsProfile
if (this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetOSProfile();
}
this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile.AdminUsername = this.AdminUsername;
}
if (this.MyInvocation.BoundParameters.ContainsKey("AdminPassword"))
{
// VirtualMachineProfile
if (this.VirtualMachineScaleSet.VirtualMachineProfile == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetVMProfile();
}
// OsProfile
if (this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetOSProfile();
}
this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile.AdminPassword = this.AdminPassword;
}
if (this.MyInvocation.BoundParameters.ContainsKey("CustomData"))
{
// VirtualMachineProfile
if (this.VirtualMachineScaleSet.VirtualMachineProfile == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetVMProfile();
}
// OsProfile
if (this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetOSProfile();
}
this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile.CustomData = this.CustomData;
}
if (this.MyInvocation.BoundParameters.ContainsKey("WindowsConfigurationProvisionVMAgent"))
{
// VirtualMachineProfile
if (this.VirtualMachineScaleSet.VirtualMachineProfile == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetVMProfile();
}
// OsProfile
if (this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetOSProfile();
}
// WindowsConfiguration
if (this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile.WindowsConfiguration == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile.WindowsConfiguration = new Microsoft.Azure.Management.Compute.Models.WindowsConfiguration();
}
this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile.WindowsConfiguration.ProvisionVMAgent = this.WindowsConfigurationProvisionVMAgent;
}
if (this.MyInvocation.BoundParameters.ContainsKey("WindowsConfigurationEnableAutomaticUpdate"))
{
// VirtualMachineProfile
if (this.VirtualMachineScaleSet.VirtualMachineProfile == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetVMProfile();
}
// OsProfile
if (this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetOSProfile();
}
// WindowsConfiguration
if (this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile.WindowsConfiguration == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile.WindowsConfiguration = new Microsoft.Azure.Management.Compute.Models.WindowsConfiguration();
}
this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile.WindowsConfiguration.EnableAutomaticUpdates = this.WindowsConfigurationEnableAutomaticUpdate;
}
if (this.MyInvocation.BoundParameters.ContainsKey("TimeZone"))
{
// VirtualMachineProfile
if (this.VirtualMachineScaleSet.VirtualMachineProfile == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetVMProfile();
}
// OsProfile
if (this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetOSProfile();
}
// WindowsConfiguration
if (this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile.WindowsConfiguration == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile.WindowsConfiguration = new Microsoft.Azure.Management.Compute.Models.WindowsConfiguration();
}
this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile.WindowsConfiguration.TimeZone = this.TimeZone;
}
if (this.MyInvocation.BoundParameters.ContainsKey("AdditionalUnattendContent"))
{
// VirtualMachineProfile
if (this.VirtualMachineScaleSet.VirtualMachineProfile == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetVMProfile();
}
// OsProfile
if (this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetOSProfile();
}
// WindowsConfiguration
if (this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile.WindowsConfiguration == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile.WindowsConfiguration = new Microsoft.Azure.Management.Compute.Models.WindowsConfiguration();
}
this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile.WindowsConfiguration.AdditionalUnattendContent = this.AdditionalUnattendContent;
}
if (this.MyInvocation.BoundParameters.ContainsKey("Listener"))
{
// VirtualMachineProfile
if (this.VirtualMachineScaleSet.VirtualMachineProfile == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetVMProfile();
}
// OsProfile
if (this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetOSProfile();
}
// WindowsConfiguration
if (this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile.WindowsConfiguration == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile.WindowsConfiguration = new Microsoft.Azure.Management.Compute.Models.WindowsConfiguration();
}
// WinRM
if (this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile.WindowsConfiguration.WinRM == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile.WindowsConfiguration.WinRM = new Microsoft.Azure.Management.Compute.Models.WinRMConfiguration();
}
this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile.WindowsConfiguration.WinRM.Listeners = this.Listener;
}
if (this.MyInvocation.BoundParameters.ContainsKey("LinuxConfigurationDisablePasswordAuthentication"))
{
// VirtualMachineProfile
if (this.VirtualMachineScaleSet.VirtualMachineProfile == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetVMProfile();
}
// OsProfile
if (this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetOSProfile();
}
// LinuxConfiguration
if (this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile.LinuxConfiguration == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile.LinuxConfiguration = new Microsoft.Azure.Management.Compute.Models.LinuxConfiguration();
}
this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile.LinuxConfiguration.DisablePasswordAuthentication = this.LinuxConfigurationDisablePasswordAuthentication;
}
if (this.MyInvocation.BoundParameters.ContainsKey("PublicKey"))
{
// VirtualMachineProfile
if (this.VirtualMachineScaleSet.VirtualMachineProfile == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetVMProfile();
}
// OsProfile
if (this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetOSProfile();
}
// LinuxConfiguration
if (this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile.LinuxConfiguration == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile.LinuxConfiguration = new Microsoft.Azure.Management.Compute.Models.LinuxConfiguration();
}
// Ssh
if (this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile.LinuxConfiguration.Ssh == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile.LinuxConfiguration.Ssh = new Microsoft.Azure.Management.Compute.Models.SshConfiguration();
}
this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile.LinuxConfiguration.Ssh.PublicKeys = this.PublicKey;
}
if (this.MyInvocation.BoundParameters.ContainsKey("Secret"))
{
// VirtualMachineProfile
if (this.VirtualMachineScaleSet.VirtualMachineProfile == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetVMProfile();
}
// OsProfile
if (this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile == null)
{
this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile = new Microsoft.Azure.Management.Compute.Models.VirtualMachineScaleSetOSProfile();
}
this.VirtualMachineScaleSet.VirtualMachineProfile.OsProfile.Secrets = this.Secret;
}
WriteObject(this.VirtualMachineScaleSet);
}
}
}
| |
// 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 Xunit;
namespace System.Linq.Expressions.Tests
{
public class PreDecrementAssignTests : IncDecAssignTests
{
[Theory]
[PerCompilationType(nameof(Int16sAndDecrements))]
[PerCompilationType(nameof(NullableInt16sAndDecrements))]
[PerCompilationType(nameof(UInt16sAndDecrements))]
[PerCompilationType(nameof(NullableUInt16sAndDecrements))]
[PerCompilationType(nameof(Int32sAndDecrements))]
[PerCompilationType(nameof(NullableInt32sAndDecrements))]
[PerCompilationType(nameof(UInt32sAndDecrements))]
[PerCompilationType(nameof(NullableUInt32sAndDecrements))]
[PerCompilationType(nameof(Int64sAndDecrements))]
[PerCompilationType(nameof(NullableInt64sAndDecrements))]
[PerCompilationType(nameof(UInt64sAndDecrements))]
[PerCompilationType(nameof(NullableUInt64sAndDecrements))]
[PerCompilationType(nameof(DecimalsAndDecrements))]
[PerCompilationType(nameof(NullableDecimalsAndDecrements))]
[PerCompilationType(nameof(SinglesAndDecrements))]
[PerCompilationType(nameof(NullableSinglesAndDecrements))]
[PerCompilationType(nameof(DoublesAndDecrements))]
[PerCompilationType(nameof(NullableDoublesAndDecrements))]
public void ReturnsCorrectValues(Type type, object value, object result, bool useInterpreter)
{
ParameterExpression variable = Expression.Variable(type);
BlockExpression block = Expression.Block(
new[] { variable },
Expression.Assign(variable, Expression.Constant(value, type)),
Expression.PreDecrementAssign(variable)
);
Assert.True(Expression.Lambda<Func<bool>>(Expression.Equal(Expression.Constant(result, type), block)).Compile(useInterpreter)());
}
[Theory]
[PerCompilationType(nameof(Int16sAndDecrements))]
[PerCompilationType(nameof(NullableInt16sAndDecrements))]
[PerCompilationType(nameof(UInt16sAndDecrements))]
[PerCompilationType(nameof(NullableUInt16sAndDecrements))]
[PerCompilationType(nameof(Int32sAndDecrements))]
[PerCompilationType(nameof(NullableInt32sAndDecrements))]
[PerCompilationType(nameof(UInt32sAndDecrements))]
[PerCompilationType(nameof(NullableUInt32sAndDecrements))]
[PerCompilationType(nameof(Int64sAndDecrements))]
[PerCompilationType(nameof(NullableInt64sAndDecrements))]
[PerCompilationType(nameof(UInt64sAndDecrements))]
[PerCompilationType(nameof(NullableUInt64sAndDecrements))]
[PerCompilationType(nameof(DecimalsAndDecrements))]
[PerCompilationType(nameof(NullableDecimalsAndDecrements))]
[PerCompilationType(nameof(SinglesAndDecrements))]
[PerCompilationType(nameof(NullableSinglesAndDecrements))]
[PerCompilationType(nameof(DoublesAndDecrements))]
[PerCompilationType(nameof(NullableDoublesAndDecrements))]
public void AssignsCorrectValues(Type type, object value, object result, bool useInterpreter)
{
ParameterExpression variable = Expression.Variable(type);
LabelTarget target = Expression.Label(type);
BlockExpression block = Expression.Block(
new[] { variable },
Expression.Assign(variable, Expression.Constant(value, type)),
Expression.PreDecrementAssign(variable),
Expression.Return(target, variable),
Expression.Label(target, Expression.Default(type))
);
Assert.True(Expression.Lambda<Func<bool>>(Expression.Equal(Expression.Constant(result, type), block)).Compile(useInterpreter)());
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public void SingleNanToNan(bool useInterpreter)
{
TestPropertyClass<float> instance = new TestPropertyClass<float>();
instance.TestInstance = float.NaN;
Assert.True(float.IsNaN(
Expression.Lambda<Func<float>>(
Expression.PreDecrementAssign(
Expression.Property(
Expression.Constant(instance),
typeof(TestPropertyClass<float>),
"TestInstance"
)
)
).Compile(useInterpreter)()
));
Assert.True(float.IsNaN(instance.TestInstance));
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public void DoubleNanToNan(bool useInterpreter)
{
TestPropertyClass<double> instance = new TestPropertyClass<double>();
instance.TestInstance = double.NaN;
Assert.True(double.IsNaN(
Expression.Lambda<Func<double>>(
Expression.PreDecrementAssign(
Expression.Property(
Expression.Constant(instance),
typeof(TestPropertyClass<double>),
"TestInstance"
)
)
).Compile(useInterpreter)()
));
Assert.True(double.IsNaN(instance.TestInstance));
}
[Theory]
[PerCompilationType(nameof(DecrementOverflowingValues))]
public void OverflowingValuesThrow(object value, bool useInterpreter)
{
ParameterExpression variable = Expression.Variable(value.GetType());
Action overflow = Expression.Lambda<Action>(
Expression.Block(
typeof(void),
new[] { variable },
Expression.Assign(variable, Expression.Constant(value)),
Expression.PreDecrementAssign(variable)
)
).Compile(useInterpreter);
Assert.Throws<OverflowException>(overflow);
}
[Theory]
[MemberData(nameof(UnincrementableAndUndecrementableTypes))]
public void InvalidOperandType(Type type)
{
ParameterExpression variable = Expression.Variable(type);
Assert.Throws<InvalidOperationException>(() => Expression.PreDecrementAssign(variable));
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public void MethodCorrectResult(bool useInterpreter)
{
ParameterExpression variable = Expression.Variable(typeof(string));
BlockExpression block = Expression.Block(
new[] { variable },
Expression.Assign(variable, Expression.Constant("hello")),
Expression.PreDecrementAssign(variable, typeof(IncDecAssignTests).GetTypeInfo().GetDeclaredMethod("SillyMethod"))
);
Assert.Equal("Eggplant", Expression.Lambda<Func<string>>(block).Compile(useInterpreter)());
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public void MethodCorrectAssign(bool useInterpreter)
{
ParameterExpression variable = Expression.Variable(typeof(string));
LabelTarget target = Expression.Label(typeof(string));
BlockExpression block = Expression.Block(
new[] { variable },
Expression.Assign(variable, Expression.Constant("hello")),
Expression.PreDecrementAssign(variable, typeof(IncDecAssignTests).GetTypeInfo().GetDeclaredMethod("SillyMethod")),
Expression.Return(target, variable),
Expression.Label(target, Expression.Default(typeof(string)))
);
Assert.Equal("Eggplant", Expression.Lambda<Func<string>>(block).Compile(useInterpreter)());
}
[Fact]
public void IncorrectMethodType()
{
Expression variable = Expression.Variable(typeof(int));
MethodInfo method = typeof(IncDecAssignTests).GetTypeInfo().GetDeclaredMethod("SillyMethod");
Assert.Throws<InvalidOperationException>(() => Expression.PreDecrementAssign(variable, method));
}
[Fact]
public void IncorrectMethodParameterCount()
{
Expression variable = Expression.Variable(typeof(string));
MethodInfo method = typeof(object).GetTypeInfo().GetDeclaredMethod("ReferenceEquals");
Assert.Throws<ArgumentException>("method", () => Expression.PreDecrementAssign(variable, method));
}
[Fact]
public void IncorrectMethodReturnType()
{
Expression variable = Expression.Variable(typeof(int));
MethodInfo method = typeof(IncDecAssignTests).GetTypeInfo().GetDeclaredMethod("GetString");
Assert.Throws<ArgumentException>(null, () => Expression.PreDecrementAssign(variable, method));
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public void StaticMemberAccessCorrect(bool useInterpreter)
{
TestPropertyClass<int>.TestStatic = 2;
Assert.Equal(
1,
Expression.Lambda<Func<int>>(
Expression.PreDecrementAssign(
Expression.Property(null, typeof(TestPropertyClass<int>), "TestStatic")
)
).Compile(useInterpreter)()
);
Assert.Equal(1, TestPropertyClass<int>.TestStatic);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public void InstanceMemberAccessCorrect(bool useInterpreter)
{
TestPropertyClass<int> instance = new TestPropertyClass<int>();
instance.TestInstance = 2;
Assert.Equal(
1,
Expression.Lambda<Func<int>>(
Expression.PreDecrementAssign(
Expression.Property(
Expression.Constant(instance),
typeof(TestPropertyClass<int>),
"TestInstance"
)
)
).Compile(useInterpreter)()
);
Assert.Equal(1, instance.TestInstance);
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public void ArrayAccessCorrect(bool useInterpreter)
{
int[] array = new int[1];
array[0] = 2;
Assert.Equal(
1,
Expression.Lambda<Func<int>>(
Expression.PreDecrementAssign(
Expression.ArrayAccess(Expression.Constant(array), Expression.Constant(0))
)
).Compile(useInterpreter)()
);
Assert.Equal(1, array[0]);
}
[Fact]
public void CanReduce()
{
ParameterExpression variable = Expression.Variable(typeof(int));
UnaryExpression op = Expression.PreDecrementAssign(variable);
Assert.True(op.CanReduce);
Assert.NotSame(op, op.ReduceAndCheck());
}
[Fact]
public void NullOperand()
{
Assert.Throws<ArgumentNullException>("expression", () => Expression.PreDecrementAssign(null));
}
[Fact]
public void UnwritableOperand()
{
Assert.Throws<ArgumentException>("expression", () => Expression.PreDecrementAssign(Expression.Constant(1)));
}
[Fact]
public void UnreadableOperand()
{
Expression value = Expression.Property(null, typeof(Unreadable<int>), "WriteOnly");
Assert.Throws<ArgumentException>("expression", () => Expression.PreDecrementAssign(value));
}
[Fact]
public void UpdateSameOperandSameNode()
{
UnaryExpression op = Expression.PreDecrementAssign(Expression.Variable(typeof(int)));
Assert.Same(op, op.Update(op.Operand));
Assert.Same(op, NoOpVisitor.Instance.Visit(op));
}
[Fact]
public void UpdateDiffOperandDiffNode()
{
UnaryExpression op = Expression.PreDecrementAssign(Expression.Variable(typeof(int)));
Assert.NotSame(op, op.Update(Expression.Variable(typeof(int))));
}
[Fact]
public void ToStringTest()
{
var e = Expression.PreDecrementAssign(Expression.Parameter(typeof(int), "x"));
Assert.Equal("--x", e.ToString());
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Reflection;
using Autofac;
using NUnit.Framework;
using Orchard.Caching;
using Orchard.Environment.Extensions;
using Orchard.Environment.Extensions.Folders;
using Orchard.Environment.Extensions.Loaders;
using Orchard.Environment.Extensions.Models;
using Orchard.FileSystems.Dependencies;
using Orchard.Tests.Extensions.ExtensionTypes;
using Orchard.Tests.Stubs;
namespace Orchard.Tests.Environment.Extensions {
[TestFixture]
public class ExtensionManagerTests {
private IContainer _container;
private IExtensionManager _manager;
private StubFolders _folders;
[SetUp]
public void Init() {
var builder = new ContainerBuilder();
_folders = new StubFolders();
builder.RegisterInstance(_folders).As<IExtensionFolders>();
builder.RegisterType<ExtensionManager>().As<IExtensionManager>();
builder.RegisterType<StubCacheManager>().As<ICacheManager>();
builder.RegisterType<StubParallelCacheContext>().As<IParallelCacheContext>();
builder.RegisterType<StubAsyncTokenProvider>().As<IAsyncTokenProvider>();
_container = builder.Build();
_manager = _container.Resolve<IExtensionManager>();
}
public class StubFolders : IExtensionFolders {
private readonly string _extensionType;
public StubFolders(string extensionType) {
Manifests = new Dictionary<string, string>();
_extensionType = extensionType;
}
public StubFolders()
: this(DefaultExtensionTypes.Module) {
}
public IDictionary<string, string> Manifests { get; set; }
public IEnumerable<ExtensionDescriptor> AvailableExtensions() {
foreach (var e in Manifests) {
string name = e.Key;
yield return ExtensionHarvester.GetDescriptorForExtension("~/", name, _extensionType, Manifests[name]);
}
}
}
public class StubLoaders : IExtensionLoader {
#region Implementation of IExtensionLoader
public int Order {
get { return 1; }
}
public string Name {
get { throw new NotImplementedException(); }
}
public Assembly LoadReference(DependencyReferenceDescriptor reference) {
throw new NotImplementedException();
}
public void ReferenceActivated(ExtensionLoadingContext context, ExtensionReferenceProbeEntry referenceEntry) {
throw new NotImplementedException();
}
public void ReferenceDeactivated(ExtensionLoadingContext context, ExtensionReferenceProbeEntry referenceEntry) {
throw new NotImplementedException();
}
public bool IsCompatibleWithModuleReferences(ExtensionDescriptor extension, IEnumerable<ExtensionProbeEntry> references) {
throw new NotImplementedException();
}
public ExtensionProbeEntry Probe(ExtensionDescriptor descriptor) {
return new ExtensionProbeEntry { Descriptor = descriptor, Loader = this };
}
public IEnumerable<ExtensionReferenceProbeEntry> ProbeReferences(ExtensionDescriptor extensionDescriptor) {
throw new NotImplementedException();
}
public ExtensionEntry Load(ExtensionDescriptor descriptor) {
return new ExtensionEntry { Descriptor = descriptor, ExportedTypes = new[] { typeof(Alpha), typeof(Beta), typeof(Phi) } };
}
public void ExtensionActivated(ExtensionLoadingContext ctx, ExtensionDescriptor extension) {
throw new NotImplementedException();
}
public void ExtensionDeactivated(ExtensionLoadingContext ctx, ExtensionDescriptor extension) {
throw new NotImplementedException();
}
public void ExtensionRemoved(ExtensionLoadingContext ctx, DependencyDescriptor dependency) {
throw new NotImplementedException();
}
public void Monitor(ExtensionDescriptor extension, Action<IVolatileToken> monitor) {
}
public IEnumerable<ExtensionCompilationReference> GetCompilationReferences(DependencyDescriptor dependency) {
throw new NotImplementedException();
}
public IEnumerable<string> GetVirtualPathDependencies(DependencyDescriptor dependency) {
throw new NotImplementedException();
}
#endregion
}
[Test]
public void AvailableExtensionsShouldFollowCatalogLocations() {
_folders.Manifests.Add("foo", "Name: Foo");
_folders.Manifests.Add("bar", "Name: Bar");
_folders.Manifests.Add("frap", "Name: Frap");
_folders.Manifests.Add("quad", "Name: Quad");
var available = _manager.AvailableExtensions();
Assert.That(available.Count(), Is.EqualTo(4));
Assert.That(available, Has.Some.Property("Id").EqualTo("foo"));
}
[Test]
public void ExtensionDescriptorKeywordsAreCaseInsensitive() {
_folders.Manifests.Add("Sample", @"
NaMe: Sample Extension
version: 2.x
DESCRIPTION: HELLO
");
var descriptor = _manager.AvailableExtensions().Single();
Assert.That(descriptor.Id, Is.EqualTo("Sample"));
Assert.That(descriptor.Name, Is.EqualTo("Sample Extension"));
Assert.That(descriptor.Version, Is.EqualTo("2.x"));
Assert.That(descriptor.Description, Is.EqualTo("HELLO"));
}
[Test]
public void ExtensionDescriptorsShouldHaveNameAndVersion() {
_folders.Manifests.Add("Sample", @"
Name: Sample Extension
Version: 2.x
");
var descriptor = _manager.AvailableExtensions().Single();
Assert.That(descriptor.Id, Is.EqualTo("Sample"));
Assert.That(descriptor.Name, Is.EqualTo("Sample Extension"));
Assert.That(descriptor.Version, Is.EqualTo("2.x"));
}
[Test]
public void ExtensionDescriptorsShouldBeParsedForMinimalModuleTxt() {
_folders.Manifests.Add("SuperWiki", @"
Name: SuperWiki
Version: 1.0.3
OrchardVersion: 1
Features:
SuperWiki:
Description: My super wiki module for Orchard.
");
var descriptor = _manager.AvailableExtensions().Single();
Assert.That(descriptor.Id, Is.EqualTo("SuperWiki"));
Assert.That(descriptor.Version, Is.EqualTo("1.0.3"));
Assert.That(descriptor.OrchardVersion, Is.EqualTo("1"));
Assert.That(descriptor.Features.Count(), Is.EqualTo(1));
Assert.That(descriptor.Features.First().Id, Is.EqualTo("SuperWiki"));
Assert.That(descriptor.Features.First().Extension.Id, Is.EqualTo("SuperWiki"));
Assert.That(descriptor.Features.First().Description, Is.EqualTo("My super wiki module for Orchard."));
}
[Test]
public void ExtensionDescriptorsShouldBeParsedForCompleteModuleTxt() {
_folders.Manifests.Add("MyCompany.AnotherWiki", @"
Name: AnotherWiki
Author: Coder Notaprogrammer
Website: http://anotherwiki.codeplex.com
Version: 1.2.3
OrchardVersion: 1
Features:
AnotherWiki:
Description: My super wiki module for Orchard.
Dependencies: Versioning, Search
Category: Content types
AnotherWiki Editor:
Description: A rich editor for wiki contents.
Dependencies: TinyMCE, AnotherWiki
Category: Input methods
AnotherWiki DistributionList:
Description: Sends e-mail alerts when wiki contents gets published.
Dependencies: AnotherWiki, Email Subscriptions
Category: Email
AnotherWiki Captcha:
Description: Kills spam. Or makes it zombie-like.
Dependencies: AnotherWiki, reCaptcha
Category: Spam
");
var descriptor = _manager.AvailableExtensions().Single();
Assert.That(descriptor.Id, Is.EqualTo("MyCompany.AnotherWiki"));
Assert.That(descriptor.Name, Is.EqualTo("AnotherWiki"));
Assert.That(descriptor.Author, Is.EqualTo("Coder Notaprogrammer"));
Assert.That(descriptor.WebSite, Is.EqualTo("http://anotherwiki.codeplex.com"));
Assert.That(descriptor.Version, Is.EqualTo("1.2.3"));
Assert.That(descriptor.OrchardVersion, Is.EqualTo("1"));
Assert.That(descriptor.Features.Count(), Is.EqualTo(5));
foreach (var featureDescriptor in descriptor.Features) {
switch (featureDescriptor.Id) {
case "AnotherWiki":
Assert.That(featureDescriptor.Extension, Is.SameAs(descriptor));
Assert.That(featureDescriptor.Description, Is.EqualTo("My super wiki module for Orchard."));
Assert.That(featureDescriptor.Category, Is.EqualTo("Content types"));
Assert.That(featureDescriptor.Dependencies.Count(), Is.EqualTo(2));
Assert.That(featureDescriptor.Dependencies.Contains("Versioning"));
Assert.That(featureDescriptor.Dependencies.Contains("Search"));
break;
case "AnotherWiki Editor":
Assert.That(featureDescriptor.Extension, Is.SameAs(descriptor));
Assert.That(featureDescriptor.Description, Is.EqualTo("A rich editor for wiki contents."));
Assert.That(featureDescriptor.Category, Is.EqualTo("Input methods"));
Assert.That(featureDescriptor.Dependencies.Count(), Is.EqualTo(2));
Assert.That(featureDescriptor.Dependencies.Contains("TinyMCE"));
Assert.That(featureDescriptor.Dependencies.Contains("AnotherWiki"));
break;
case "AnotherWiki DistributionList":
Assert.That(featureDescriptor.Extension, Is.SameAs(descriptor));
Assert.That(featureDescriptor.Description, Is.EqualTo("Sends e-mail alerts when wiki contents gets published."));
Assert.That(featureDescriptor.Category, Is.EqualTo("Email"));
Assert.That(featureDescriptor.Dependencies.Count(), Is.EqualTo(2));
Assert.That(featureDescriptor.Dependencies.Contains("AnotherWiki"));
Assert.That(featureDescriptor.Dependencies.Contains("Email Subscriptions"));
break;
case "AnotherWiki Captcha":
Assert.That(featureDescriptor.Extension, Is.SameAs(descriptor));
Assert.That(featureDescriptor.Description, Is.EqualTo("Kills spam. Or makes it zombie-like."));
Assert.That(featureDescriptor.Category, Is.EqualTo("Spam"));
Assert.That(featureDescriptor.Dependencies.Count(), Is.EqualTo(2));
Assert.That(featureDescriptor.Dependencies.Contains("AnotherWiki"));
Assert.That(featureDescriptor.Dependencies.Contains("reCaptcha"));
break;
// default feature.
case "MyCompany.AnotherWiki":
Assert.That(featureDescriptor.Extension, Is.SameAs(descriptor));
break;
default:
Assert.Fail("Features not parsed correctly");
break;
}
}
}
[Test]
public void ExtensionManagerShouldLoadFeatures() {
var extensionLoader = new StubLoaders();
var extensionFolder = new StubFolders();
extensionFolder.Manifests.Add("TestModule", @"
Name: TestModule
Version: 1.0.3
OrchardVersion: 1
Features:
TestModule:
Description: My test module for Orchard.
TestFeature:
Description: Contains the Phi type.
");
IExtensionManager extensionManager = CreateExtensionManager(extensionFolder, extensionLoader);
var testFeature = extensionManager.AvailableExtensions()
.SelectMany(x => x.Features);
var features = extensionManager.LoadFeatures(testFeature);
var types = features.SelectMany(x => x.ExportedTypes);
Assert.That(types.Count(), Is.Not.EqualTo(0));
}
[Test]
public void ExtensionManagerFeaturesContainNonAbstractClasses() {
var extensionLoader = new StubLoaders();
var extensionFolder = new StubFolders();
extensionFolder.Manifests.Add("TestModule", @"
Name: TestModule
Version: 1.0.3
OrchardVersion: 1
Features:
TestModule:
Description: My test module for Orchard.
TestFeature:
Description: Contains the Phi type.
");
IExtensionManager extensionManager = CreateExtensionManager(extensionFolder, extensionLoader);
var testFeature = extensionManager.AvailableExtensions()
.SelectMany(x => x.Features);
var features = extensionManager.LoadFeatures(testFeature);
var types = features.SelectMany(x => x.ExportedTypes);
foreach (var type in types) {
Assert.That(type.IsClass);
Assert.That(!type.IsAbstract);
}
}
private static ExtensionManager CreateExtensionManager(StubFolders extensionFolder, StubLoaders extensionLoader) {
return CreateExtensionManager(new[] { extensionFolder }, new[] { extensionLoader });
}
private static ExtensionManager CreateExtensionManager(IEnumerable<StubFolders> extensionFolder, IEnumerable<StubLoaders> extensionLoader) {
return new ExtensionManager(extensionFolder, extensionLoader, new StubCacheManager(), new StubParallelCacheContext(), new StubAsyncTokenProvider());
}
[Test]
public void ExtensionManagerShouldReturnEmptyFeatureIfFeatureDoesNotExist() {
var featureDescriptor = new FeatureDescriptor { Id = "NoSuchFeature", Extension = new ExtensionDescriptor { Id = "NoSuchFeature" } };
Feature feature = _manager.LoadFeatures(new[] { featureDescriptor }).First();
Assert.AreEqual(featureDescriptor, feature.Descriptor);
Assert.AreEqual(0, feature.ExportedTypes.Count());
}
[Test]
public void ExtensionManagerTestFeatureAttribute() {
var extensionLoader = new StubLoaders();
var extensionFolder = new StubFolders();
extensionFolder.Manifests.Add("TestModule", @"
Name: TestModule
Version: 1.0.3
OrchardVersion: 1
Features:
TestModule:
Description: My test module for Orchard.
TestFeature:
Description: Contains the Phi type.
");
IExtensionManager extensionManager = CreateExtensionManager(extensionFolder, extensionLoader);
var testFeature = extensionManager.AvailableExtensions()
.SelectMany(x => x.Features)
.Single(x => x.Id == "TestFeature");
foreach (var feature in extensionManager.LoadFeatures(new[] { testFeature })) {
foreach (var type in feature.ExportedTypes) {
foreach (OrchardFeatureAttribute featureAttribute in type.GetCustomAttributes(typeof(OrchardFeatureAttribute), false)) {
Assert.That(featureAttribute.FeatureName, Is.EqualTo("TestFeature"));
}
}
}
}
[Test]
public void ExtensionManagerLoadFeatureReturnsTypesFromSpecificFeaturesWithFeatureAttribute() {
var extensionLoader = new StubLoaders();
var extensionFolder = new StubFolders();
extensionFolder.Manifests.Add("TestModule", @"
Name: TestModule
Version: 1.0.3
OrchardVersion: 1
Features:
TestModule:
Description: My test module for Orchard.
TestFeature:
Description: Contains the Phi type.
");
IExtensionManager extensionManager = CreateExtensionManager(extensionFolder, extensionLoader);
var testFeature = extensionManager.AvailableExtensions()
.SelectMany(x => x.Features)
.Single(x => x.Id == "TestFeature");
foreach (var feature in extensionManager.LoadFeatures(new[] { testFeature })) {
foreach (var type in feature.ExportedTypes) {
Assert.That(type == typeof(Phi));
}
}
}
[Test]
public void ExtensionManagerLoadFeatureDoesNotReturnTypesFromNonMatchingFeatures() {
var extensionLoader = new StubLoaders();
var extensionFolder = new StubFolders();
extensionFolder.Manifests.Add("TestModule", @"
Name: TestModule
Version: 1.0.3
OrchardVersion: 1
Features:
TestModule:
Description: My test module for Orchard.
TestFeature:
Description: Contains the Phi type.
");
IExtensionManager extensionManager = CreateExtensionManager(extensionFolder, extensionLoader);
var testModule = extensionManager.AvailableExtensions()
.SelectMany(x => x.Features)
.Single(x => x.Id == "TestModule");
foreach (var feature in extensionManager.LoadFeatures(new[] { testModule })) {
foreach (var type in feature.ExportedTypes) {
Assert.That(type != typeof(Phi));
Assert.That((type == typeof(Alpha) || (type == typeof(Beta))));
}
}
}
[Test]
public void ModuleNameIsIntroducedAsFeatureImplicitly() {
var extensionLoader = new StubLoaders();
var extensionFolder = new StubFolders();
extensionFolder.Manifests.Add("Minimalistic", @"
Name: Minimalistic
Version: 1.0.3
OrchardVersion: 1
");
IExtensionManager extensionManager = CreateExtensionManager(extensionFolder, extensionLoader);
var minimalisticModule = extensionManager.AvailableExtensions().Single(x => x.Id == "Minimalistic");
Assert.That(minimalisticModule.Features.Count(), Is.EqualTo(1));
Assert.That(minimalisticModule.Features.Single().Id, Is.EqualTo("Minimalistic"));
}
[Test]
public void FeatureDescriptorsAreInDependencyOrder() {
var extensionLoader = new StubLoaders();
var extensionFolder = new StubFolders();
extensionFolder.Manifests.Add("Alpha", @"
Name: Alpha
Version: 1.0.3
OrchardVersion: 1
Features:
Alpha:
Dependencies: Gamma
");
extensionFolder.Manifests.Add("Beta", @"
Name: Beta
Version: 1.0.3
OrchardVersion: 1
");
extensionFolder.Manifests.Add("Gamma", @"
Name: Gamma
Version: 1.0.3
OrchardVersion: 1
Features:
Gamma:
Dependencies: Beta
");
IExtensionManager extensionManager = CreateExtensionManager(extensionFolder, extensionLoader);
var features = extensionManager.AvailableFeatures();
Assert.That(features.Aggregate("<", (a, b) => a + b.Id + "<"), Is.EqualTo("<Beta<Gamma<Alpha<"));
}
[Test]
public void FeatureDescriptorsShouldBeLoadedInThemes() {
var extensionLoader = new StubLoaders();
var moduleExtensionFolder = new StubFolders();
var themeExtensionFolder = new StubFolders(DefaultExtensionTypes.Theme);
moduleExtensionFolder.Manifests.Add("Alpha", @"
Name: Alpha
Version: 1.0.3
OrchardVersion: 1
Features:
Alpha:
Dependencies: Gamma
");
moduleExtensionFolder.Manifests.Add("Beta", @"
Name: Beta
Version: 1.0.3
OrchardVersion: 1
");
moduleExtensionFolder.Manifests.Add("Gamma", @"
Name: Gamma
Version: 1.0.3
OrchardVersion: 1
Features:
Gamma:
Dependencies: Beta
");
moduleExtensionFolder.Manifests.Add("Classic", @"
Name: Classic
Version: 1.0.3
OrchardVersion: 1
");
IExtensionManager extensionManager = CreateExtensionManager(new[] { moduleExtensionFolder, themeExtensionFolder }, new[] { extensionLoader });
var features = extensionManager.AvailableFeatures();
Assert.That(features.Count(), Is.EqualTo(4));
}
[Test]
public void ThemeFeatureDescriptorsShouldBeAbleToDependOnModules() {
var extensionLoader = new StubLoaders();
var moduleExtensionFolder = new StubFolders();
var themeExtensionFolder = new StubFolders(DefaultExtensionTypes.Theme);
moduleExtensionFolder.Manifests.Add("Alpha", CreateManifest("Alpha", null, "Gamma"));
moduleExtensionFolder.Manifests.Add("Beta", CreateManifest("Beta"));
moduleExtensionFolder.Manifests.Add("Gamma", CreateManifest("Gamma", null, "Beta"));
moduleExtensionFolder.Manifests.Add("Classic", CreateManifest("Classic", null, "Alpha"));
AssertFeaturesAreInOrder(new[] { moduleExtensionFolder, themeExtensionFolder }, extensionLoader, "<Beta<Gamma<Alpha<Classic<");
}
private static string CreateManifest(string name, string priority = null, string dependencies = null) {
return string.Format(CultureInfo.InvariantCulture, @"
Name: {0}
Version: 1.0.3
OrchardVersion: 1{1}{2}",
name,
(dependencies == null ? null : "\nDependencies: " + dependencies),
(priority == null ? null : "\nPriority:" + priority));
}
private static void AssertFeaturesAreInOrder(StubFolders folder, StubLoaders loader, string expectedOrder) {
AssertFeaturesAreInOrder(new StubFolders[] { folder }, loader, expectedOrder);
}
private static void AssertFeaturesAreInOrder(IEnumerable<StubFolders> folders, StubLoaders loader, string expectedOrder) {
var extensionManager = CreateExtensionManager(folders, new[] { loader });
var features = extensionManager.AvailableFeatures();
Assert.That(features.Aggregate("<", (a, b) => a + b.Id + "<"), Is.EqualTo(expectedOrder));
}
[Test]
public void FeatureDescriptorsAreInDependencyAndPriorityOrder() {
var extensionLoader = new StubLoaders();
var extensionFolder = new StubFolders();
// Check that priorities apply correctly on items on the same level of dependencies and are overwritten by dependencies
extensionFolder.Manifests.Add("Alpha", CreateManifest("Alpha", "2", "Gamma")); // More important than Gamma but will get overwritten by the dependency
extensionFolder.Manifests.Add("Beta", CreateManifest("Beta", "2"));
extensionFolder.Manifests.Add("Foo", CreateManifest("Foo", "1"));
extensionFolder.Manifests.Add("Gamma", CreateManifest("Gamma", "3", "Beta, Foo"));
AssertFeaturesAreInOrder(extensionFolder, extensionLoader, "<Foo<Beta<Gamma<Alpha<");
// Change priorities and see that it reflects properly
// Gamma comes after Foo (same priority) because their order in the Manifests is preserved
extensionFolder.Manifests["Foo"] = CreateManifest("Foo", "3");
AssertFeaturesAreInOrder(extensionFolder, extensionLoader, "<Beta<Foo<Gamma<Alpha<");
// Remove dependency on Foo and see that it moves down the list since no one depends on it anymore
extensionFolder.Manifests["Gamma"] = CreateManifest("Gamma", "3", "Beta");
AssertFeaturesAreInOrder(extensionFolder, extensionLoader, "<Beta<Gamma<Alpha<Foo<");
// Change Foo to depend on Gamma and see that it says in its position (same dependencies as alpha but lower priority)
extensionFolder.Manifests["Foo"] = CreateManifest("Foo", "3", "Gamma");
AssertFeaturesAreInOrder(extensionFolder, extensionLoader, "<Beta<Gamma<Alpha<Foo<");
// Update Foo to a higher priority than alpha and see that it moves before alpha
extensionFolder.Manifests["Foo"] = CreateManifest("Foo", "1", "Gamma");
AssertFeaturesAreInOrder(extensionFolder, extensionLoader, "<Beta<Gamma<Foo<Alpha<");
}
[Test]
public void FeatureDescriptorsAreInPriorityOrder() {
var extensionLoader = new StubLoaders();
var extensionFolder = new StubFolders();
// Check that priorities apply correctly on items on the same level of dependencies and are overwritten by dependencies
extensionFolder.Manifests.Add("Alpha", CreateManifest("Alpha", "4")); // More important than Gamma but will get overwritten by the dependency
extensionFolder.Manifests.Add("Beta", CreateManifest("Beta", "3"));
extensionFolder.Manifests.Add("Foo", CreateManifest("Foo", "1"));
extensionFolder.Manifests.Add("Gamma", CreateManifest("Gamma", "2"));
AssertFeaturesAreInOrder(extensionFolder, extensionLoader, "<Foo<Gamma<Beta<Alpha<");
}
[Test]
public void FeatureDescriptorsAreInManifestOrderWhenTheyHaveEqualPriority() {
var extensionLoader = new StubLoaders();
var extensionFolder = new StubFolders();
extensionFolder.Manifests.Add("Alpha", CreateManifest("Alpha", "4"));
extensionFolder.Manifests.Add("Beta", CreateManifest("Beta", "4"));
extensionFolder.Manifests.Add("Gamma", CreateManifest("Gamma", "4"));
extensionFolder.Manifests.Add("Foo", CreateManifest("Foo", "3"));
extensionFolder.Manifests.Add("Bar", CreateManifest("Bar", "3"));
extensionFolder.Manifests.Add("Baz", CreateManifest("Baz", "3"));
AssertFeaturesAreInOrder(extensionFolder, extensionLoader, "<Foo<Bar<Baz<Alpha<Beta<Gamma<");
}
}
}
| |
// 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
//
// 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 Google.Api.Ads.AdWords.Lib;
using Google.Api.Ads.AdWords.v201809;
using System;
using System.Collections.Generic;
namespace Google.Api.Ads.AdWords.Examples.CSharp.v201809
{
/// <summary>
/// This code example adds various types of targeting criteria to a campaign.
/// To get a list of campaigns, run GetCampaigns.cs.
/// </summary>
public class AddCampaignTargetingCriteria : ExampleBase
{
/// <summary>
/// Main method, to run this code example as a standalone application.
/// </summary>
/// <param name="args">The command line arguments.</param>
public static void Main(string[] args)
{
AddCampaignTargetingCriteria codeExample = new AddCampaignTargetingCriteria();
Console.WriteLine(codeExample.Description);
try
{
long campaignId = long.Parse("INSERT_CAMPAIGN_ID_HERE");
string feedIdText = "INSERT_LOCATION_FEED_ID_HERE";
long? feedId = null;
long temp;
if (long.TryParse(feedIdText, out temp))
{
feedId = temp;
}
codeExample.Run(new AdWordsUser(), campaignId, feedId);
}
catch (Exception e)
{
Console.WriteLine("An exception occurred while running this code example. {0}",
ExampleUtilities.FormatException(e));
}
}
/// <summary>
/// Returns a description about the code example.
/// </summary>
public override string Description
{
get
{
return "This code example adds various types of targeting criteria to a " +
"campaign. To get a list of campaigns, run GetCampaigns.cs.";
}
}
/// <summary>
/// Runs the code example.
/// </summary>
/// <param name="user">The AdWords user.</param>
/// <param name="campaignId">Id of the campaign to which targeting criteria
/// are added.</param>
/// <param name="feedId">ID of a feed that has been configured for location
/// targeting, meaning it has an ENABLED FeedMapping with criterionType of
/// 77. Feeds linked to a GMB account automatically have this FeedMapping.
/// If you don't have such a feed, set this value to null.</param>
public void Run(AdWordsUser user, long campaignId, long? feedId)
{
using (CampaignCriterionService campaignCriterionService =
(CampaignCriterionService) user.GetService(AdWordsService.v201809
.CampaignCriterionService))
{
// Create locations. The IDs can be found in the documentation or
// retrieved with the LocationCriterionService.
Location california = new Location()
{
id = 21137L
};
Location mexico = new Location()
{
id = 2484L
};
// Create languages. The IDs can be found in the documentation or
// retrieved with the ConstantDataService.
Language english = new Language()
{
id = 1000L
};
Language spanish = new Language()
{
id = 1003L
};
List<Criterion> criteria = new List<Criterion>()
{
california,
mexico,
english,
spanish
};
// Distance targeting. Area of 10 miles around the locations in the location feed.
if (feedId != null)
{
LocationGroups radiusLocationGroup = new LocationGroups()
{
feedId = feedId.Value,
matchingFunction = new Function()
{
@operator = FunctionOperator.IDENTITY,
lhsOperand = new FunctionArgumentOperand[]
{
new LocationExtensionOperand()
{
radius = new ConstantOperand()
{
type = ConstantOperandConstantType.DOUBLE,
unit = ConstantOperandUnit.MILES,
doubleValue = 10
}
}
}
}
};
criteria.Add(radiusLocationGroup);
}
// Create operations to add each of the criteria above.
List<CampaignCriterionOperation>
operations = new List<CampaignCriterionOperation>();
foreach (Criterion criterion in criteria)
{
CampaignCriterionOperation operation = new CampaignCriterionOperation()
{
operand = new CampaignCriterion()
{
campaignId = campaignId,
criterion = criterion
},
@operator = Operator.ADD
};
operations.Add(operation);
}
// Add a negative campaign criterion.
CampaignCriterion negativeCriterion = new NegativeCampaignCriterion()
{
campaignId = campaignId,
criterion = new Keyword()
{
text = "jupiter cruise",
matchType = KeywordMatchType.BROAD
}
};
CampaignCriterionOperation negativeCriterionOperation =
new CampaignCriterionOperation()
{
operand = negativeCriterion,
@operator = Operator.ADD
};
operations.Add(negativeCriterionOperation);
try
{
// Set the campaign targets.
CampaignCriterionReturnValue retVal =
campaignCriterionService.mutate(operations.ToArray());
if (retVal != null && retVal.value != null)
{
// Display campaign targets.
foreach (CampaignCriterion criterion in retVal.value)
{
Console.WriteLine(
"Campaign criteria of type '{0}' was set to campaign with" +
" id = '{1}'.", criterion.criterion.CriterionType,
criterion.campaignId);
}
}
}
catch (Exception e)
{
throw new System.ApplicationException("Failed to set Campaign criteria.", e);
}
}
}
}
}
| |
using System.Collections.Generic;
using System;
using System.Threading.Tasks;
using Ceen;
using Ceen.Mvc;
using Ceen.Database;
using System.Linq;
namespace Ceen.PaaS.AdminHandlers
{
/// <summary>
/// Handler for the dashboard stats
/// </summary>
[RequireHandler(typeof(Ceen.PaaS.Services.AdminRequiredHandler))]
public class DashboardStatsHandler : API.ControllerBase, IAdminAPIv1
{
/// <summary>
/// The UNIX Epoch value
/// </summary>
public static readonly DateTime UnixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
/// <summary>
/// The log module instance
/// </summary>
private Ceen.Extras.LogModule _logModule;
/// <summary>
/// Lazy-loaded cached reference to the log module
/// </summary>
protected Ceen.Extras.LogModule HttpLogModule
{
get
{
if (_logModule == null)
_logModule = Ceen.Context.Current.GetItemsOfType<Ceen.Extras.LogModule>().First();
return _logModule;
}
}
[HttpPost]
public virtual async Task<IResult> Index()
{
return Json(await IndexResultsAsync(DateTime.Now.AddDays(-7)));
}
/// <summary>
/// Overrideable result generator for the index handler, providing the dashboard overview results
/// </summary>
/// <param name="timelimit">The time to display events for in the dashboard</param>
/// <returns>An an object prepared for JSON handling</returns>
protected virtual async Task<Dictionary<string, object>> IndexResultsAsync(DateTime timelimit)
{
var httpstats = await HttpLogModule?.RunInTransactionAsync(db => new {
OK = db.SelectCount<Ceen.Extras.LogModule.HttpLogEntry>(x => x.Started > timelimit && x.ResponseStatusCode <= 399),
ClientError = db.SelectCount<Ceen.Extras.LogModule.HttpLogEntry>(x => x.Started > timelimit && x.ResponseStatusCode >= 400 && x.ResponseStatusCode <= 499),
ServerError = db.SelectCount<Ceen.Extras.LogModule.HttpLogEntry>(x => x.Started > timelimit && x.ResponseStatusCode >= 500),
LandingPage = db.SelectCount<Ceen.Extras.LogModule.HttpLogEntry>(x => x.Started > timelimit && x.RequestUrl == "/"),
});
return await DB.RunInTransactionAsync(db =>
new Dictionary<string, object>() {
{
"Signup", new {
WaitListSize = db.SelectCount<Database.Signup.SignupEntry>(x => x.Status == Database.Signup.SignupStatus.Confirmed),
ActivatedUsers = db.SelectCount<Database.Signup.SignupEntry>(x => x.Status == Database.Signup.SignupStatus.Activated),
NewConfirmedSignups = db.SelectCount<Database.Signup.SignupEntry>(x => x.LastAttempt > timelimit && x.Status == Database.Signup.SignupStatus.Confirmed),
NonConfirmedSignups = db.SelectCount<Database.Signup.SignupEntry>(x => x.LastAttempt > timelimit && (x.Status == Database.Signup.SignupStatus.Created || x.Status == Database.Signup.SignupStatus.Failed)),
}
},
{
"Email", new {
EmailsSent = db.SelectCount<Database.SentEmailLog>(x => x.When > timelimit),
}
},
{
"Http", httpstats
}
}
);
}
/// <summary>
/// The request for graph data
/// </summary>
public class GraphQuery
{
public int From;
public int To;
public int Buckets;
public string Type;
}
/// <summary>
/// Time range for graph queries
/// </summary>
public struct TimeRange
{
public DateTime From;
public DateTime To;
}
/// <summary>
/// Builds a graph for a particular feature
/// </summary>
/// <param name="start">The unix epoch based start of the range</param>
/// <param name="end">The unix epoch based end of the range</param>
/// <param name="type">The query type</param>
/// <returns></returns>
[HttpPost]
public virtual async Task<IResult> Graph(GraphQuery req)
{
if (req == null || string.IsNullOrWhiteSpace(req.Type))
return BadRequest;
if (req.To - req.From < 100)
return Status(BadRequest, "End must be larger than start by at least 100 seconds");
if (req.Buckets < 3 || req.Buckets > 100)
return Status(BadRequest, "The buckets must be [3-365]");
var from = UnixEpoch.AddSeconds(req.From);
var to = UnixEpoch.AddSeconds(req.To);
var bucketsize = TimeSpan.FromSeconds((req.To - req.From) / req.Buckets);
// Compute to and from ranges
var fromtimes = new DateTime[req.Buckets];
var totimes = new DateTime[req.Buckets];
var prev = from;
for(var i = 0; i < req.Buckets; i++)
prev = totimes[i] = (fromtimes[i] = prev) + bucketsize;
// Make sure we cover the full range
totimes[req.Buckets - 1] = to;
// Make it as an array
var dt = fromtimes.Zip(totimes, (x, y) => new TimeRange { From = x, To = y }).ToArray();
// Compute the response in an overideable manner
return await CreateGraphResponse(req, dt);
}
/// <summary>
/// Creates the actual response from the request and a computed set of intervals
/// </summary>
/// <param name="req">The request to service</param>
/// <param name="ranges">The computed range buckets</param>
/// <returns>A JSON result</returns>
protected virtual async Task<IResult> CreateGraphResponse(GraphQuery req, TimeRange[] ranges)
{
switch (req.Type.ToLowerInvariant())
{
case "signup":
return Json(await DB.RunInTransactionAsync(db =>
new {
WaitListSize =
ranges.Select(t =>
db.SelectCount<Database.Signup.SignupEntry>(x => x.Status == Database.Signup.SignupStatus.Confirmed && x.When > t.From && x.When <= t.To)
).ToArray(),
ActivatedUsers =
ranges.Select(t =>
db.SelectCount<Database.Signup.SignupEntry>(x => x.Status == Database.Signup.SignupStatus.Activated && x.WhenActivated > t.From && x.WhenActivated <= t.To)
).ToArray(),
ConfirmedSignups =
ranges.Select(t =>
db.SelectCount<Database.Signup.SignupEntry>(x => x.LastAttempt > t.From && x.LastAttempt <= t.To && x.Status == Database.Signup.SignupStatus.Confirmed)
).ToArray(),
NonConfirmedSignups =
ranges.Select(t =>
db.SelectCount<Database.Signup.SignupEntry>(x => x.LastAttempt > t.From && x.LastAttempt <= t.To && (x.Status == Database.Signup.SignupStatus.Created || x.Status == Database.Signup.SignupStatus.Failed))
).ToArray()
}));
case "email":
return Json(await DB.RunInTransactionAsync(db =>
new {
Sent =
ranges.Select(t =>
db.SelectCount<Database.SentEmailLog>(x => x.When > t.From && x.When <= t.To)
).ToArray()
}
));
case "http":
return Json(await HttpLogModule.RunInTransactionAsync(db =>
new
{
OK =
ranges.Select(t =>
db.SelectCount<Ceen.Extras.LogModule.HttpLogEntry>(x => x.Started > t.From && x.Started <= t.To && x.ResponseStatusCode <= 399)
).ToArray(),
ClientError =
ranges.Select(t =>
db.SelectCount<Ceen.Extras.LogModule.HttpLogEntry>(x => x.Started > t.From && x.Started <= t.To && x.ResponseStatusCode > 399 && x.ResponseStatusCode <= 499)
).ToArray(),
ServerError =
ranges.Select(t =>
db.SelectCount<Ceen.Extras.LogModule.HttpLogEntry>(x => x.Started > t.From && x.Started <= t.To && x.ResponseStatusCode >= 500)
).ToArray()
}
));
default:
return Status(BadRequest, "No such query type");
}
}
}
}
| |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="Win32Methods.cs" company="Jan-Cornelius Molnar">
// The MIT License (MIT)
//
// Copyright (c) 2015 Jan-Cornelius Molnar
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
using System;
using System.Runtime.InteropServices;
namespace Jcq.Wpf.CommonExtenders
{
internal class Win32Methods
{
[DllImport("user32.dll", CharSet = CharSet.Auto)]
internal static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);
}
[StructLayout(LayoutKind.Sequential)]
internal class MinMaxInfo
{
internal Win32Point ptMaxPosition;
internal Win32Point ptMaxSize;
internal Win32Point ptMaxTrackSize;
internal Win32Point ptMinTrackSize;
internal Win32Point ptReserved;
}
[StructLayout(LayoutKind.Sequential)]
internal class Win32Point
{
// Fields
internal int x;
internal int y;
internal Win32Point()
{
}
internal Win32Point(int xval, int yval)
{
x = xval;
y = yval;
}
}
[StructLayout(LayoutKind.Sequential)]
internal class Win32Rect
{
internal int bottom;
// Fields
internal int left;
internal int right;
internal int top;
}
internal enum WindowMessage : uint
{
WM_NULL = 0x0,
WM_CREATE = 0x1,
WM_DESTROY = 0x2,
WM_MOVE = 0x3,
WM_SIZE = 0x5,
WM_ACTIVATE = 0x6,
WM_SETFOCUS = 0x7,
WM_KILLFOCUS = 0x8,
WM_ENABLE = 0xa,
WM_SETREDRAW = 0xb,
WM_SETTEXT = 0xc,
WM_GETTEXT = 0xd,
WM_GETTEXTLENGTH = 0xe,
WM_PAINT = 0xf,
WM_CLOSE = 0x10,
WM_QUERYENDSESSION = 0x11,
WM_QUERYOPEN = 0x13,
WM_ENDSESSION = 0x16,
WM_QUIT = 0x12,
WM_ERASEBKGND = 0x14,
WM_SYSCOLORCHANGE = 0x15,
WM_SHOWWINDOW = 0x18,
WM_WININICHANGE = 0x1a,
WM_DEVMODECHANGE = 0x1b,
WM_ACTIVATEAPP = 0x1c,
WM_FONTCHANGE = 0x1d,
WM_TIMECHANGE = 0x1e,
WM_CANCELMODE = 0x1f,
WM_SETCURSOR = 0x20,
WM_MOUSEACTIVATE = 0x21,
WM_CHILDACTIVATE = 0x22,
WM_QUEUESYNC = 0x23,
WM_GETMINMAXINFO = 0x24,
WM_PAINTICON = 0x26,
WM_ICONERASEBKGND = 0x27,
WM_NEXTDLGCTL = 0x28,
WM_SPOOLERSTATUS = 0x2a,
WM_DRAWITEM = 0x2b,
WM_MEASUREITEM = 0x2c,
WM_DELETEITEM = 0x2d,
WM_VKEYTOITEM = 0x2e,
WM_CHARTOITEM = 0x2f,
WM_SETFONT = 0x30,
WM_GETFONT = 0x31,
WM_SETHOTKEY = 0x32,
WM_GETHOTKEY = 0x33,
WM_QUERYDRAGICON = 0x37,
WM_COMPAREITEM = 0x39,
WM_GETOBJECT = 0x3d,
WM_COMPACTING = 0x41,
WM_COMMNOTIFY = 0x44,
WM_WINDOWPOSCHANGING = 0x46,
WM_WINDOWPOSCHANGED = 0x47,
WM_POWER = 0x48,
WM_COPYDATA = 0x4a,
WM_CANCELJOURNAL = 0x4b,
WM_NOTIFY = 0x4e,
WM_INPUTLANGCHANGEREQUEST = 0x50,
WM_INPUTLANGCHANGE = 0x51,
WM_TCARD = 0x52,
WM_HELP = 0x53,
WM_USERCHANGED = 0x54,
WM_NOTIFYFORMAT = 0x55,
WM_CONTEXTMENU = 0x7b,
WM_STYLECHANGING = 0x7c,
WM_STYLECHANGED = 0x7d,
WM_DISPLAYCHANGE = 0x7e,
WM_GETICON = 0x7f,
WM_SETICON = 0x80,
WM_NCCREATE = 0x81,
WM_NCDESTROY = 0x82,
WM_NCCALCSIZE = 0x83,
WM_NCHITTEST = 0x84,
WM_NCPAINT = 0x85,
WM_NCACTIVATE = 0x86,
WM_GETDLGCODE = 0x87,
WM_SYNCPAINT = 0x88,
WM_NCMOUSEMOVE = 0xa0,
WM_NCLBUTTONDOWN = 0xa1,
WM_NCLBUTTONUP = 0xa2,
WM_NCLBUTTONDBLCLK = 0xa3,
WM_NCRBUTTONDOWN = 0xa4,
WM_NCRBUTTONUP = 0xa5,
WM_NCRBUTTONDBLCLK = 0xa6,
WM_NCMBUTTONDOWN = 0xa7,
WM_NCMBUTTONUP = 0xa8,
WM_NCMBUTTONDBLCLK = 0xa9,
WM_NCXBUTTONDOWN = 0xab,
WM_NCXBUTTONUP = 0xac,
WM_NCXBUTTONDBLCLK = 0xad,
WM_INPUT_DEVICE_CHANGE = 0xfe,
WM_INPUT = 0xff,
WM_KEYFIRST = 0x100,
WM_KEYDOWN = 0x100,
WM_KEYUP = 0x101,
WM_CHAR = 0x102,
WM_DEADCHAR = 0x103,
WM_SYSKEYDOWN = 0x104,
WM_SYSKEYUP = 0x105,
WM_SYSCHAR = 0x106,
WM_SYSDEADCHAR = 0x107,
WM_UNICHAR = 0x109,
WM_KEYLAST = 0x109,
WM_IME_STARTCOMPOSITION = 0x10d,
WM_IME_ENDCOMPOSITION = 0x10e,
WM_IME_COMPOSITION = 0x10f,
WM_IME_KEYLAST = 0x10f,
WM_INITDIALOG = 0x110,
WM_COMMAND = 0x111,
WM_SYSCOMMAND = 0x112,
WM_TIMER = 0x113,
WM_HSCROLL = 0x114,
WM_VSCROLL = 0x115,
WM_INITMENU = 0x116,
WM_INITMENUPOPUP = 0x117,
WM_MENUSELECT = 0x11f,
WM_MENUCHAR = 0x120,
WM_ENTERIDLE = 0x121,
WM_MENURBUTTONUP = 0x122,
WM_MENUDRAG = 0x123,
WM_MENUGETOBJECT = 0x124,
WM_UNINITMENUPOPUP = 0x125,
WM_MENUCOMMAND = 0x126,
WM_CHANGEUISTATE = 0x127,
WM_UPDATEUISTATE = 0x128,
WM_QUERYUISTATE = 0x129,
WM_CTLCOLORMSGBOX = 0x132,
WM_CTLCOLOREDIT = 0x133,
WM_CTLCOLORLISTBOX = 0x134,
WM_CTLCOLORBTN = 0x135,
WM_CTLCOLORDLG = 0x136,
WM_CTLCOLORSCROLLBAR = 0x137,
WM_CTLCOLORSTATIC = 0x138,
MN_GETHMENU = 0x1e1,
WM_MOUSEFIRST = 0x200,
WM_MOUSEMOVE = 0x200,
WM_LBUTTONDOWN = 0x201,
WM_LBUTTONUP = 0x202,
WM_LBUTTONDBLCLK = 0x203,
WM_RBUTTONDOWN = 0x204,
WM_RBUTTONUP = 0x205,
WM_RBUTTONDBLCLK = 0x206,
WM_MBUTTONDOWN = 0x207,
WM_MBUTTONUP = 0x208,
WM_MBUTTONDBLCLK = 0x209,
WM_MOUSEWHEEL = 0x20a,
WM_XBUTTONDOWN = 0x20b,
WM_XBUTTONUP = 0x20c,
WM_XBUTTONDBLCLK = 0x20d,
WM_MOUSELAST = 0x20d,
WM_PARENTNOTIFY = 0x210,
WM_ENTERMENULOOP = 0x211,
WM_EXITMENULOOP = 0x212,
WM_NEXTMENU = 0x213,
WM_SIZING = 0x214,
WM_CAPTURECHANGED = 0x215,
WM_MOVING = 0x216,
WM_POWERBROADCAST = 0x218,
WM_DEVICECHANGE = 0x219,
WM_MDICREATE = 0x220,
WM_MDIDESTROY = 0x221,
WM_MDIACTIVATE = 0x222,
WM_MDIRESTORE = 0x223,
WM_MDINEXT = 0x224,
WM_MDIMAXIMIZE = 0x225,
WM_MDITILE = 0x226,
WM_MDICASCADE = 0x227,
WM_MDIICONARRANGE = 0x228,
WM_MDIGETACTIVE = 0x229,
WM_MDISETMENU = 0x230,
WM_ENTERSIZEMOVE = 0x231,
WM_EXITSIZEMOVE = 0x232,
WM_DROPFILES = 0x233,
WM_MDIREFRESHMENU = 0x234,
WM_IME_SETCONTEXT = 0x281,
WM_IME_NOTIFY = 0x282,
WM_IME_CONTROL = 0x283,
WM_IME_COMPOSITIONFULL = 0x284,
WM_IME_SELECT = 0x285,
WM_IME_CHAR = 0x286,
WM_IME_REQUEST = 0x288,
WM_IME_KEYDOWN = 0x290,
WM_IME_KEYUP = 0x291,
WM_MOUSEHOVER = 0x2a1,
WM_MOUSELEAVE = 0x2a3,
WM_NCMOUSEHOVER = 0x2a0,
WM_NCMOUSELEAVE = 0x2a2,
WM_WTSSESSION_CHANGE = 0x2b1,
WM_TABLET_FIRST = 0x2c0,
WM_TABLET_LAST = 0x2df,
WM_CUT = 0x300,
WM_COPY = 0x301,
WM_PASTE = 0x302,
WM_CLEAR = 0x303,
WM_UNDO = 0x304,
WM_RENDERFORMAT = 0x305,
WM_RENDERALLFORMATS = 0x306,
WM_DESTROYCLIPBOARD = 0x307,
WM_DRAWCLIPBOARD = 0x308,
WM_PAINTCLIPBOARD = 0x309,
WM_VSCROLLCLIPBOARD = 0x30a,
WM_SIZECLIPBOARD = 0x30b,
WM_ASKCBFORMATNAME = 0x30c,
WM_CHANGECBCHAIN = 0x30d,
WM_HSCROLLCLIPBOARD = 0x30e,
WM_QUERYNEWPALETTE = 0x30f,
WM_PALETTEISCHANGING = 0x310,
WM_PALETTECHANGED = 0x311,
WM_HOTKEY = 0x312,
WM_PRINT = 0x317,
WM_PRINTCLIENT = 0x318,
WM_APPCOMMAND = 0x319,
WM_THEMECHANGED = 0x31a,
WM_CLIPBOARDUPDATE = 0x31d,
WM_DWMCOMPOSITIONCHANGED = 0x31e,
WM_DWMNCRENDERINGCHANGED = 0x31f,
WM_DWMCOLORIZATIONCOLORCHANGED = 0x320,
WM_DWMWINDOWMAXIMIZEDCHANGE = 0x321,
WM_HANDHELDFIRST = 0x358,
WM_HANDHELDLAST = 0x35f,
WM_AFXFIRST = 0x360,
WM_AFXLAST = 0x37f,
WM_PENWINFIRST = 0x380,
WM_PENWINLAST = 0x38f,
WM_APP = 0x8000
}
internal enum SysCommand : uint
{
SC_SIZE = 0xf000,
SC_MOVE = 0xf010,
SC_MINIMIZE = 0xf020,
SC_MAXIMIZE = 0xf030,
SC_NEXTWINDOW = 0xf040,
SC_PREVWINDOW = 0xf050,
SC_CLOSE = 0xf060,
SC_VSCROLL = 0xf070,
SC_HSCROLL = 0xf080,
SC_MOUSEMENU = 0xf090,
SC_KEYMENU = 0xf100,
SC_ARRANGE = 0xf110,
SC_RESTORE = 0xf120,
SC_TASKLIST = 0xf130,
SC_SCREENSAVE = 0xf140,
SC_HOTKEY = 0xf150,
SC_DEFAULT = 0xf160,
SC_MONITORPOWER = 0xf170,
SC_CONTEXTHELP = 0xf180,
SC_SEPARATOR = 0xf00f
}
internal enum Win32WindowStyle : uint
{
WS_POPUP = 0x80000000,
WS_CLIPCHILDREN = 0x2000000,
WS_OVERLAPPED = 0x0,
WS_CHILD = 0x40000000,
WS_MINIMIZE = 0x20000000,
WS_VISIBLE = 0x10000000,
WS_DISABLED = 0x8000000,
WS_CLIPSIBLINGS = 0x4000000,
WS_MAXIMIZE = 0x1000000,
WS_CAPTION = 0x0,
WS_BORDER = 0x800000,
WS_DLGFRAME = 0x400000,
WS_VSCROLL = 0x200000,
WS_HSCROLL = 0x100000,
WS_SYSMENU = 0x80000,
WS_THICKFRAME = 0x40000,
WS_GROUP = 0x20000,
WS_TABSTOP = 0x10000,
WS_MINIMIZEBOX = 0x20000,
WS_MAXIMIZEBOX = 0x10000
}
}
| |
//#define USE_SharpZipLib
#if !UNITY_WEBPLAYER
#define USE_FileIO
#endif
/* * * * *
* A simple JSON Parser / builder
* ------------------------------
*
* It mainly has been written as a simple JSON parser. It can build a JSON string
* from the node-tree, or generate a node tree from any valid JSON string.
*
* If you want to use compression when saving to file / stream / B64 you have to include
* SharpZipLib ( http://www.icsharpcode.net/opensource/sharpziplib/ ) in your project and
* define "USE_SharpZipLib" at the top of the file
*
* Written by Bunny83
* 2012-06-09
*
* Features / attributes:
* - provides strongly typed node classes and lists / dictionaries
* - provides easy access to class members / array items / data values
* - the parser ignores data types. Each value is a string.
* - only double quotes (") are used for quoting strings.
* - values and names are not restricted to quoted strings. They simply add up and are trimmed.
* - There are only 3 types: arrays(JSONArray), objects(JSONClass) and values(JSONData)
* - provides "casting" properties to easily convert to / from those types:
* int / float / double / bool
* - provides a common interface for each node so no explicit casting is required.
* - the parser try to avoid errors, but if malformed JSON is parsed the result is undefined
*
*
* 2012-12-17 Update:
* - Added internal JSONLazyCreator class which simplifies the construction of a JSON tree
* Now you can simple reference any item that doesn't exist yet and it will return a JSONLazyCreator
* The class determines the required type by it's further use, creates the type and removes itself.
* - Added binary serialization / deserialization.
* - Added support for BZip2 zipped binary format. Requires the SharpZipLib ( http://www.icsharpcode.net/opensource/sharpziplib/ )
* The usage of the SharpZipLib library can be disabled by removing or commenting out the USE_SharpZipLib define at the top
* - The serializer uses different types when it comes to store the values. Since my data values
* are all of type string, the serializer will "try" which format fits best. The order is: int, float, double, bool, string.
* It's not the most efficient way but for a moderate amount of data it should work on all platforms.
*
* * * * */
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace FuelSDKSimpleJSON
{
public enum JSONBinaryTag
{
Array = 1,
Class = 2,
Value = 3,
IntValue = 4,
DoubleValue = 5,
BoolValue = 6,
FloatValue = 7,
}
public class JSONNode
{
#region common interface
public virtual void Add (string aKey, JSONNode aItem)
{
}
public virtual JSONNode this [int aIndex] { get { return null; } set { }
}
public virtual JSONNode this [string aKey] { get { return null; } set { }
}
public virtual string Value {
get { return ""; }
set { }
}
public virtual int Count { get { return 0; } }
public virtual void Add (JSONNode aItem)
{
Add ("", aItem);
}
public virtual JSONNode Remove (string aKey)
{
return null;
}
public virtual JSONNode Remove (int aIndex)
{
return null;
}
public virtual JSONNode Remove (JSONNode aNode)
{
return aNode;
}
public virtual IEnumerable<JSONNode> Childs { get { yield break; } }
public IEnumerable<JSONNode> DeepChilds {
get {
foreach (var C in Childs)
foreach (var D in C.DeepChilds)
yield return D;
}
}
public override string ToString ()
{
return "JSONNode";
}
public virtual string ToString (string aPrefix)
{
return "JSONNode";
}
#endregion common interface
#region typecasting properties
public virtual int AsInt {
get {
int v = 0;
if (int.TryParse (Value, out v))
return v;
return 0;
}
set {
Value = value.ToString ();
}
}
public virtual float AsFloat {
get {
float v = 0.0f;
if (float.TryParse (Value, out v))
return v;
return 0.0f;
}
set {
Value = value.ToString ();
}
}
public virtual double AsDouble {
get {
double v = 0.0;
if (double.TryParse (Value, out v))
return v;
return 0.0;
}
set {
Value = value.ToString ();
}
}
public virtual bool AsBool {
get {
bool v = false;
if (bool.TryParse (Value, out v))
return v;
return !string.IsNullOrEmpty (Value);
}
set {
Value = (value) ? "true" : "false";
}
}
public virtual JSONArray AsArray {
get {
return this as JSONArray;
}
}
public virtual JSONClass AsObject {
get {
return this as JSONClass;
}
}
#endregion typecasting properties
#region operators
public static implicit operator JSONNode (string s)
{
return new JSONData (s);
}
public static implicit operator string (JSONNode d)
{
return (d == null) ? null : d.Value;
}
public static bool operator == (JSONNode a, object b)
{
if (b == null && a is JSONLazyCreator)
return true;
return System.Object.ReferenceEquals (a, b);
}
public static bool operator != (JSONNode a, object b)
{
return !(a == b);
}
public override bool Equals (object obj)
{
return System.Object.ReferenceEquals (this, obj);
}
public override int GetHashCode ()
{
return base.GetHashCode ();
}
#endregion operators
internal static string Escape (string aText)
{
string result = "";
foreach (char c in aText) {
switch (c) {
case '\\':
result += "\\\\";
break;
case '\"':
result += "\\\"";
break;
case '\n':
result += "\\n";
break;
case '\r':
result += "\\r";
break;
case '\t':
result += "\\t";
break;
case '\b':
result += "\\b";
break;
case '\f':
result += "\\f";
break;
default :
result += c;
break;
}
}
return result;
}
public static JSONNode Parse (string aJSON)
{
Stack<JSONNode> stack = new Stack<JSONNode> ();
JSONNode ctx = null;
int i = 0;
string Token = "";
string TokenName = "";
bool QuoteMode = false;
while (i < aJSON.Length) {
switch (aJSON [i]) {
case '{':
if (QuoteMode) {
Token += aJSON [i];
break;
}
stack.Push (new JSONClass ());
if (ctx != null) {
TokenName = TokenName.Trim ();
if (ctx is JSONArray)
ctx.Add (stack.Peek ());
else if (TokenName != "")
ctx.Add (TokenName, stack.Peek ());
}
TokenName = "";
Token = "";
ctx = stack.Peek ();
break;
case '[':
if (QuoteMode) {
Token += aJSON [i];
break;
}
stack.Push (new JSONArray ());
if (ctx != null) {
TokenName = TokenName.Trim ();
if (ctx is JSONArray)
ctx.Add (stack.Peek ());
else if (TokenName != "")
ctx.Add (TokenName, stack.Peek ());
}
TokenName = "";
Token = "";
ctx = stack.Peek ();
break;
case '}':
case ']':
if (QuoteMode) {
Token += aJSON [i];
break;
}
if (stack.Count == 0)
throw new Exception ("JSON Parse: Too many closing brackets");
stack.Pop ();
if (Token != "") {
TokenName = TokenName.Trim ();
if (ctx is JSONArray)
ctx.Add (Token);
else if (TokenName != "")
ctx.Add (TokenName, Token);
}
TokenName = "";
Token = "";
if (stack.Count > 0)
ctx = stack.Peek ();
break;
case ':':
if (QuoteMode) {
Token += aJSON [i];
break;
}
TokenName = Token;
Token = "";
break;
case '"':
QuoteMode ^= true;
break;
case ',':
if (QuoteMode) {
Token += aJSON [i];
break;
}
if (Token != "") {
if (ctx is JSONArray)
ctx.Add (Token);
else if (TokenName != "")
ctx.Add (TokenName, Token);
}
TokenName = "";
Token = "";
break;
case '\r':
case '\n':
break;
case ' ':
case '\t':
if (QuoteMode)
Token += aJSON [i];
break;
case '\\':
++i;
if (QuoteMode) {
char C = aJSON [i];
switch (C) {
case 't':
Token += '\t';
break;
case 'r':
Token += '\r';
break;
case 'n':
Token += '\n';
break;
case 'b':
Token += '\b';
break;
case 'f':
Token += '\f';
break;
case 'u':
{
string s = aJSON.Substring (i + 1, 4);
Token += (char)int.Parse (s, System.Globalization.NumberStyles.AllowHexSpecifier);
i += 4;
break;
}
default :
Token += C;
break;
}
}
break;
default:
Token += aJSON [i];
break;
}
++i;
}
if (QuoteMode) {
throw new Exception ("JSON Parse: Quotation marks seems to be messed up.");
}
return ctx;
}
public virtual void Serialize (System.IO.BinaryWriter aWriter)
{
}
public void SaveToStream (System.IO.Stream aData)
{
var W = new System.IO.BinaryWriter (aData);
Serialize (W);
}
#if USE_SharpZipLib
public void SaveToCompressedStream(System.IO.Stream aData)
{
using (var gzipOut = new ICSharpCode.SharpZipLib.BZip2.BZip2OutputStream(aData))
{
gzipOut.IsStreamOwner = false;
SaveToStream(gzipOut);
gzipOut.Close();
}
}
public void SaveToCompressedFile(string aFileName)
{
#if USE_FileIO
System.IO.Directory.CreateDirectory((new System.IO.FileInfo(aFileName)).Directory.FullName);
using(var F = System.IO.File.OpenWrite(aFileName))
{
SaveToCompressedStream(F);
}
#else
throw new Exception("Can't use File IO stuff in webplayer");
#endif
}
public string SaveToCompressedBase64()
{
using (var stream = new System.IO.MemoryStream())
{
SaveToCompressedStream(stream);
stream.Position = 0;
return System.Convert.ToBase64String(stream.ToArray());
}
}
#else
public void SaveToCompressedStream (System.IO.Stream aData)
{
throw new Exception ("Can't use compressed functions. You need include the SharpZipLib and uncomment the define at the top of SimpleJSON");
}
public void SaveToCompressedFile (string aFileName)
{
throw new Exception ("Can't use compressed functions. You need include the SharpZipLib and uncomment the define at the top of SimpleJSON");
}
public string SaveToCompressedBase64 ()
{
throw new Exception ("Can't use compressed functions. You need include the SharpZipLib and uncomment the define at the top of SimpleJSON");
}
#endif
public void SaveToFile (string aFileName)
{
#if USE_FileIO
System.IO.Directory.CreateDirectory ((new System.IO.FileInfo (aFileName)).Directory.FullName);
using (var F = System.IO.File.OpenWrite(aFileName)) {
SaveToStream (F);
}
#else
throw new Exception("Can't use File IO stuff in webplayer");
#endif
}
public string SaveToBase64 ()
{
using (var stream = new System.IO.MemoryStream()) {
SaveToStream (stream);
stream.Position = 0;
return System.Convert.ToBase64String (stream.ToArray ());
}
}
public static JSONNode Deserialize (System.IO.BinaryReader aReader)
{
JSONBinaryTag type = (JSONBinaryTag)aReader.ReadByte ();
switch (type) {
case JSONBinaryTag.Array:
{
int count = aReader.ReadInt32 ();
JSONArray tmp = new JSONArray ();
for (int i = 0; i < count; i++)
tmp.Add (Deserialize (aReader));
return tmp;
}
case JSONBinaryTag.Class:
{
int count = aReader.ReadInt32 ();
JSONClass tmp = new JSONClass ();
for (int i = 0; i < count; i++) {
string key = aReader.ReadString ();
var val = Deserialize (aReader);
tmp.Add (key, val);
}
return tmp;
}
case JSONBinaryTag.Value:
{
return new JSONData (aReader.ReadString ());
}
case JSONBinaryTag.IntValue:
{
return new JSONData (aReader.ReadInt32 ());
}
case JSONBinaryTag.DoubleValue:
{
return new JSONData (aReader.ReadDouble ());
}
case JSONBinaryTag.BoolValue:
{
return new JSONData (aReader.ReadBoolean ());
}
case JSONBinaryTag.FloatValue:
{
return new JSONData (aReader.ReadSingle ());
}
default:
{
throw new Exception ("Error deserializing JSON. Unknown tag: " + type);
}
}
}
#if USE_SharpZipLib
public static JSONNode LoadFromCompressedStream(System.IO.Stream aData)
{
var zin = new ICSharpCode.SharpZipLib.BZip2.BZip2InputStream(aData);
return LoadFromStream(zin);
}
public static JSONNode LoadFromCompressedFile(string aFileName)
{
#if USE_FileIO
using(var F = System.IO.File.OpenRead(aFileName))
{
return LoadFromCompressedStream(F);
}
#else
throw new Exception("Can't use File IO stuff in webplayer");
#endif
}
public static JSONNode LoadFromCompressedBase64(string aBase64)
{
var tmp = System.Convert.FromBase64String(aBase64);
var stream = new System.IO.MemoryStream(tmp);
stream.Position = 0;
return LoadFromCompressedStream(stream);
}
#else
public static JSONNode LoadFromCompressedFile (string aFileName)
{
throw new Exception ("Can't use compressed functions. You need include the SharpZipLib and uncomment the define at the top of SimpleJSON");
}
public static JSONNode LoadFromCompressedStream (System.IO.Stream aData)
{
throw new Exception ("Can't use compressed functions. You need include the SharpZipLib and uncomment the define at the top of SimpleJSON");
}
public static JSONNode LoadFromCompressedBase64 (string aBase64)
{
throw new Exception ("Can't use compressed functions. You need include the SharpZipLib and uncomment the define at the top of SimpleJSON");
}
#endif
public static JSONNode LoadFromStream (System.IO.Stream aData)
{
using (var R = new System.IO.BinaryReader(aData)) {
return Deserialize (R);
}
}
public static JSONNode LoadFromFile (string aFileName)
{
#if USE_FileIO
using (var F = System.IO.File.OpenRead(aFileName)) {
return LoadFromStream (F);
}
#else
throw new Exception("Can't use File IO stuff in webplayer");
#endif
}
public static JSONNode LoadFromBase64 (string aBase64)
{
var tmp = System.Convert.FromBase64String (aBase64);
var stream = new System.IO.MemoryStream (tmp);
stream.Position = 0;
return LoadFromStream (stream);
}
} // End of JSONNode
public class JSONArray : JSONNode, IEnumerable
{
private List<JSONNode> m_List = new List<JSONNode> ();
public override JSONNode this [int aIndex] {
get {
if (aIndex < 0 || aIndex >= m_List.Count)
return new JSONLazyCreator (this);
return m_List [aIndex];
}
set {
if (aIndex < 0 || aIndex >= m_List.Count)
m_List.Add (value);
else
m_List [aIndex] = value;
}
}
public override JSONNode this [string aKey] {
get{ return new JSONLazyCreator (this);}
set{ m_List.Add (value); }
}
public override int Count {
get { return m_List.Count; }
}
public override void Add (string aKey, JSONNode aItem)
{
m_List.Add (aItem);
}
public override JSONNode Remove (int aIndex)
{
if (aIndex < 0 || aIndex >= m_List.Count)
return null;
JSONNode tmp = m_List [aIndex];
m_List.RemoveAt (aIndex);
return tmp;
}
public override JSONNode Remove (JSONNode aNode)
{
m_List.Remove (aNode);
return aNode;
}
public override IEnumerable<JSONNode> Childs {
get {
foreach (JSONNode N in m_List)
yield return N;
}
}
public IEnumerator GetEnumerator ()
{
foreach (JSONNode N in m_List)
yield return N;
}
public override string ToString ()
{
string result = "[ ";
foreach (JSONNode N in m_List) {
if (result.Length > 2)
result += ", ";
result += N.ToString ();
}
result += " ]";
return result;
}
public override string ToString (string aPrefix)
{
string result = "[ ";
foreach (JSONNode N in m_List) {
if (result.Length > 3)
result += ", ";
result += "\n" + aPrefix + " ";
result += N.ToString (aPrefix + " ");
}
result += "\n" + aPrefix + "]";
return result;
}
public override void Serialize (System.IO.BinaryWriter aWriter)
{
aWriter.Write ((byte)JSONBinaryTag.Array);
aWriter.Write (m_List.Count);
for (int i = 0; i < m_List.Count; i++) {
m_List [i].Serialize (aWriter);
}
}
} // End of JSONArray
public class JSONClass : JSONNode, IEnumerable
{
private Dictionary<string,JSONNode> m_Dict = new Dictionary<string,JSONNode> ();
public override JSONNode this [string aKey] {
get {
if (m_Dict.ContainsKey (aKey))
return m_Dict [aKey];
else
return new JSONLazyCreator (this, aKey);
}
set {
if (m_Dict.ContainsKey (aKey))
m_Dict [aKey] = value;
else
m_Dict.Add (aKey, value);
}
}
public override JSONNode this [int aIndex] {
get {
if (aIndex < 0 || aIndex >= m_Dict.Count)
return null;
return m_Dict.ElementAt (aIndex).Value;
}
set {
if (aIndex < 0 || aIndex >= m_Dict.Count)
return;
string key = m_Dict.ElementAt (aIndex).Key;
m_Dict [key] = value;
}
}
public override int Count {
get { return m_Dict.Count; }
}
public override void Add (string aKey, JSONNode aItem)
{
if (!string.IsNullOrEmpty (aKey)) {
if (m_Dict.ContainsKey (aKey))
m_Dict [aKey] = aItem;
else
m_Dict.Add (aKey, aItem);
} else
m_Dict.Add (Guid.NewGuid ().ToString (), aItem);
}
public override JSONNode Remove (string aKey)
{
if (!m_Dict.ContainsKey (aKey))
return null;
JSONNode tmp = m_Dict [aKey];
m_Dict.Remove (aKey);
return tmp;
}
public override JSONNode Remove (int aIndex)
{
if (aIndex < 0 || aIndex >= m_Dict.Count)
return null;
var item = m_Dict.ElementAt (aIndex);
m_Dict.Remove (item.Key);
return item.Value;
}
public override JSONNode Remove (JSONNode aNode)
{
try {
var item = m_Dict.Where (k => k.Value == aNode).First ();
m_Dict.Remove (item.Key);
return aNode;
} catch {
return null;
}
}
public override IEnumerable<JSONNode> Childs {
get {
foreach (KeyValuePair<string,JSONNode> N in m_Dict)
yield return N.Value;
}
}
public IEnumerator GetEnumerator ()
{
foreach (KeyValuePair<string, JSONNode> N in m_Dict)
yield return N;
}
public override string ToString ()
{
string result = "{";
foreach (KeyValuePair<string, JSONNode> N in m_Dict) {
if (result.Length > 2)
result += ", ";
result += "\"" + Escape (N.Key) + "\":" + N.Value.ToString ();
}
result += "}";
return result;
}
public override string ToString (string aPrefix)
{
string result = "{ ";
foreach (KeyValuePair<string, JSONNode> N in m_Dict) {
if (result.Length > 3)
result += ", ";
result += "\n" + aPrefix + " ";
result += "\"" + Escape (N.Key) + "\" : " + N.Value.ToString (aPrefix + " ");
}
result += "\n" + aPrefix + "}";
return result;
}
public override void Serialize (System.IO.BinaryWriter aWriter)
{
aWriter.Write ((byte)JSONBinaryTag.Class);
aWriter.Write (m_Dict.Count);
foreach (string K in m_Dict.Keys) {
aWriter.Write (K);
m_Dict [K].Serialize (aWriter);
}
}
} // End of JSONClass
public class JSONData : JSONNode
{
private string m_Data;
public override string Value {
get { return m_Data; }
set { m_Data = value; }
}
public JSONData (string aData)
{
m_Data = aData;
}
public JSONData (float aData)
{
AsFloat = aData;
}
public JSONData (double aData)
{
AsDouble = aData;
}
public JSONData (bool aData)
{
AsBool = aData;
}
public JSONData (int aData)
{
AsInt = aData;
}
public override string ToString ()
{
return "\"" + Escape (m_Data) + "\"";
}
public override string ToString (string aPrefix)
{
return "\"" + Escape (m_Data) + "\"";
}
public override void Serialize (System.IO.BinaryWriter aWriter)
{
var tmp = new JSONData ("");
tmp.AsInt = AsInt;
if (tmp.m_Data == this.m_Data) {
aWriter.Write ((byte)JSONBinaryTag.IntValue);
aWriter.Write (AsInt);
return;
}
tmp.AsFloat = AsFloat;
if (tmp.m_Data == this.m_Data) {
aWriter.Write ((byte)JSONBinaryTag.FloatValue);
aWriter.Write (AsFloat);
return;
}
tmp.AsDouble = AsDouble;
if (tmp.m_Data == this.m_Data) {
aWriter.Write ((byte)JSONBinaryTag.DoubleValue);
aWriter.Write (AsDouble);
return;
}
tmp.AsBool = AsBool;
if (tmp.m_Data == this.m_Data) {
aWriter.Write ((byte)JSONBinaryTag.BoolValue);
aWriter.Write (AsBool);
return;
}
aWriter.Write ((byte)JSONBinaryTag.Value);
aWriter.Write (m_Data);
}
} // End of JSONData
internal class JSONLazyCreator : JSONNode
{
private JSONNode m_Node = null;
private string m_Key = null;
public JSONLazyCreator (JSONNode aNode)
{
m_Node = aNode;
m_Key = null;
}
public JSONLazyCreator (JSONNode aNode, string aKey)
{
m_Node = aNode;
m_Key = aKey;
}
private void Set (JSONNode aVal)
{
if (m_Key == null) {
m_Node.Add (aVal);
} else {
m_Node.Add (m_Key, aVal);
}
m_Node = null; // Be GC friendly.
}
public override JSONNode this [int aIndex] {
get {
return new JSONLazyCreator (this);
}
set {
var tmp = new JSONArray ();
tmp.Add (value);
Set (tmp);
}
}
public override JSONNode this [string aKey] {
get {
return new JSONLazyCreator (this, aKey);
}
set {
var tmp = new JSONClass ();
tmp.Add (aKey, value);
Set (tmp);
}
}
public override void Add (JSONNode aItem)
{
var tmp = new JSONArray ();
tmp.Add (aItem);
Set (tmp);
}
public override void Add (string aKey, JSONNode aItem)
{
var tmp = new JSONClass ();
tmp.Add (aKey, aItem);
Set (tmp);
}
public static bool operator == (JSONLazyCreator a, object b)
{
if (b == null)
return true;
return System.Object.ReferenceEquals (a, b);
}
public static bool operator != (JSONLazyCreator a, object b)
{
return !(a == b);
}
public override bool Equals (object obj)
{
if (obj == null)
return true;
return System.Object.ReferenceEquals (this, obj);
}
public override int GetHashCode ()
{
return base.GetHashCode ();
}
public override string ToString ()
{
return "";
}
public override string ToString (string aPrefix)
{
return "";
}
public override int AsInt {
get {
JSONData tmp = new JSONData (0);
Set (tmp);
return 0;
}
set {
JSONData tmp = new JSONData (value);
Set (tmp);
}
}
public override float AsFloat {
get {
JSONData tmp = new JSONData (0.0f);
Set (tmp);
return 0.0f;
}
set {
JSONData tmp = new JSONData (value);
Set (tmp);
}
}
public override double AsDouble {
get {
JSONData tmp = new JSONData (0.0);
Set (tmp);
return 0.0;
}
set {
JSONData tmp = new JSONData (value);
Set (tmp);
}
}
public override bool AsBool {
get {
JSONData tmp = new JSONData (false);
Set (tmp);
return false;
}
set {
JSONData tmp = new JSONData (value);
Set (tmp);
}
}
public override JSONArray AsArray {
get {
JSONArray tmp = new JSONArray ();
Set (tmp);
return tmp;
}
}
public override JSONClass AsObject {
get {
JSONClass tmp = new JSONClass ();
Set (tmp);
return tmp;
}
}
} // End of JSONLazyCreator
public static class JSON
{
public static JSONNode Parse (string aJSON)
{
return JSONNode.Parse (aJSON);
}
}
}
| |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Management.Automation;
namespace Microsoft.PowerShell.ScheduledJob
{
/// <summary>
/// This cmdlet sets properties on a trigger for a ScheduledJobDefinition.
/// </summary>
[Cmdlet(VerbsCommon.Set, "JobTrigger", DefaultParameterSetName = SetJobTriggerCommand.DefaultParameterSet,
HelpUri = "https://go.microsoft.com/fwlink/?LinkID=223916")]
[OutputType(typeof(ScheduledJobTrigger))]
public sealed class SetJobTriggerCommand : ScheduleJobCmdletBase
{
#region Parameters
private const string DefaultParameterSet = "DefaultParams";
/// <summary>
/// ScheduledJobTrigger objects to set properties on.
/// </summary>
[Parameter(Position = 0, Mandatory = true, ValueFromPipeline = true,
ParameterSetName = SetJobTriggerCommand.DefaultParameterSet)]
[ValidateNotNullOrEmpty]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public ScheduledJobTrigger[] InputObject
{
get { return _triggers; }
set { _triggers = value; }
}
private ScheduledJobTrigger[] _triggers;
/// <summary>
/// Daily interval for trigger.
/// </summary>
[Parameter(ParameterSetName = SetJobTriggerCommand.DefaultParameterSet)]
public Int32 DaysInterval
{
get { return _daysInterval; }
set { _daysInterval = value; }
}
private Int32 _daysInterval = 1;
/// <summary>
/// Weekly interval for trigger.
/// </summary>
[Parameter(ParameterSetName = SetJobTriggerCommand.DefaultParameterSet)]
public Int32 WeeksInterval
{
get { return _weeksInterval; }
set { _weeksInterval = value; }
}
private Int32 _weeksInterval = 1;
/// <summary>
/// Random delay for trigger.
/// </summary>
[Parameter(ParameterSetName = SetJobTriggerCommand.DefaultParameterSet)]
public TimeSpan RandomDelay
{
get { return _randomDelay; }
set { _randomDelay = value; }
}
private TimeSpan _randomDelay;
/// <summary>
/// Job start date/time for trigger.
/// </summary>
[Parameter(ParameterSetName = SetJobTriggerCommand.DefaultParameterSet)]
public DateTime At
{
get { return _atTime; }
set { _atTime = value; }
}
private DateTime _atTime;
/// <summary>
/// User name for AtLogon trigger. The AtLogon parameter set will create a trigger
/// that activates after log on for the provided user name.
/// </summary>
[Parameter(ParameterSetName = SetJobTriggerCommand.DefaultParameterSet)]
[ValidateNotNullOrEmpty]
public string User
{
get { return _user; }
set { _user = value; }
}
private string _user;
/// <summary>
/// Days of week for trigger.
/// </summary>
[Parameter(ParameterSetName = SetJobTriggerCommand.DefaultParameterSet)]
[ValidateNotNullOrEmpty]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public DayOfWeek[] DaysOfWeek
{
get { return _daysOfWeek; }
set { _daysOfWeek = value; }
}
private DayOfWeek[] _daysOfWeek;
/// <summary>
/// Switch to specify an AtStartup trigger.
/// </summary>
[Parameter(ParameterSetName = SetJobTriggerCommand.DefaultParameterSet)]
public SwitchParameter AtStartup
{
get { return _atStartup; }
set { _atStartup = value; }
}
private SwitchParameter _atStartup;
/// <summary>
/// Switch to specify an AtLogon trigger.
/// </summary>
[Parameter(ParameterSetName = SetJobTriggerCommand.DefaultParameterSet)]
public SwitchParameter AtLogOn
{
get { return _atLogon; }
set { _atLogon = value; }
}
private SwitchParameter _atLogon;
/// <summary>
/// Switch to specify an Once trigger.
/// </summary>
[Parameter(ParameterSetName = SetJobTriggerCommand.DefaultParameterSet)]
public SwitchParameter Once
{
get { return _once; }
set { _once = value; }
}
private SwitchParameter _once;
/// <summary>
/// Repetition interval of a one time trigger.
/// </summary>
[Parameter(ParameterSetName = SetJobTriggerCommand.DefaultParameterSet)]
public TimeSpan RepetitionInterval
{
get { return _repInterval; }
set { _repInterval = value; }
}
private TimeSpan _repInterval;
/// <summary>
/// Repetition duration of a one time trigger.
/// </summary>
[Parameter(ParameterSetName = SetJobTriggerCommand.DefaultParameterSet)]
public TimeSpan RepetitionDuration
{
get { return _repDuration; }
set { _repDuration = value; }
}
private TimeSpan _repDuration;
/// <summary>
/// Repetition interval repeats indefinitely.
/// </summary>
[Parameter(ParameterSetName = SetJobTriggerCommand.DefaultParameterSet)]
public SwitchParameter RepeatIndefinitely
{
get { return _repRepeatIndefinitely; }
set { _repRepeatIndefinitely = value; }
}
private SwitchParameter _repRepeatIndefinitely;
/// <summary>
/// Switch to specify an Daily trigger.
/// </summary>
[Parameter(ParameterSetName = SetJobTriggerCommand.DefaultParameterSet)]
public SwitchParameter Daily
{
get { return _daily; }
set { _daily = value; }
}
private SwitchParameter _daily;
/// <summary>
/// Switch to specify an Weekly trigger.
/// </summary>
[Parameter(ParameterSetName = SetJobTriggerCommand.DefaultParameterSet)]
public SwitchParameter Weekly
{
get { return _weekly; }
set { _weekly = value; }
}
private SwitchParameter _weekly;
/// <summary>
/// Pass through job trigger object.
/// </summary>
[Parameter(ParameterSetName = SetJobTriggerCommand.DefaultParameterSet)]
public SwitchParameter PassThru
{
get { return _passThru; }
set { _passThru = value; }
}
private SwitchParameter _passThru;
#endregion
#region Cmdlet Overrides
/// <summary>
/// Process input.
/// </summary>
protected override void ProcessRecord()
{
// Validate the parameter set and write any errors.
TriggerFrequency newTriggerFrequency = TriggerFrequency.None;
if (!ValidateParameterSet(ref newTriggerFrequency))
{
return;
}
// Update each trigger object with the current parameter set.
// The associated scheduled job definition will also be updated.
foreach (ScheduledJobTrigger trigger in _triggers)
{
ScheduledJobTrigger originalTrigger = new ScheduledJobTrigger(trigger);
if (!UpdateTrigger(trigger, newTriggerFrequency))
{
continue;
}
ScheduledJobDefinition definition = trigger.JobDefinition;
if (definition != null)
{
bool jobUpdateFailed = false;
try
{
trigger.UpdateJobDefinition();
}
catch (ScheduledJobException e)
{
jobUpdateFailed = true;
string msg = StringUtil.Format(ScheduledJobErrorStrings.CantUpdateTriggerOnJobDef, definition.Name, trigger.Id);
Exception reason = new RuntimeException(msg, e);
ErrorRecord errorRecord = new ErrorRecord(reason, "CantSetPropertiesOnJobTrigger", ErrorCategory.InvalidOperation, trigger);
WriteError(errorRecord);
}
if (jobUpdateFailed)
{
// Restore trigger to original configuration.
originalTrigger.CopyTo(trigger);
}
}
if (_passThru)
{
WriteObject(trigger);
}
}
}
#endregion
#region Private Methods
private bool ValidateParameterSet(ref TriggerFrequency newTriggerFrequency)
{
// First see if a switch parameter was set.
List<TriggerFrequency> switchParamList = new List<TriggerFrequency>();
if (MyInvocation.BoundParameters.ContainsKey(nameof(AtStartup)))
{
switchParamList.Add(TriggerFrequency.AtStartup);
}
if (MyInvocation.BoundParameters.ContainsKey(nameof(AtLogon)))
{
switchParamList.Add(TriggerFrequency.AtLogon);
}
if (MyInvocation.BoundParameters.ContainsKey(nameof(Once)))
{
switchParamList.Add(TriggerFrequency.Once);
}
if (MyInvocation.BoundParameters.ContainsKey(nameof(Daily)))
{
switchParamList.Add(TriggerFrequency.Daily);
}
if (MyInvocation.BoundParameters.ContainsKey(nameof(Weekly)))
{
switchParamList.Add(TriggerFrequency.Weekly);
}
if (switchParamList.Count > 1)
{
WriteValidationError(ScheduledJobErrorStrings.ConflictingTypeParams);
return false;
}
newTriggerFrequency = (switchParamList.Count == 1) ? switchParamList[0] : TriggerFrequency.None;
// Validate parameters against the new trigger frequency value.
bool rtnValue = false;
switch (newTriggerFrequency)
{
case TriggerFrequency.None:
rtnValue = true;
break;
case TriggerFrequency.AtStartup:
rtnValue = ValidateStartupParams();
break;
case TriggerFrequency.AtLogon:
rtnValue = ValidateLogonParams();
break;
case TriggerFrequency.Once:
rtnValue = ValidateOnceParams();
break;
case TriggerFrequency.Daily:
rtnValue = ValidateDailyParams();
break;
case TriggerFrequency.Weekly:
rtnValue = ValidateWeeklyParams();
break;
default:
Debug.Assert(false, "Invalid trigger frequency value.");
rtnValue = false;
break;
}
return rtnValue;
}
private bool ValidateStartupParams()
{
if (MyInvocation.BoundParameters.ContainsKey(nameof(DaysInterval)))
{
string msg = StringUtil.Format(ScheduledJobErrorStrings.InvalidDaysInterval, ScheduledJobErrorStrings.TriggerStartUpType);
WriteValidationError(msg);
return false;
}
if (MyInvocation.BoundParameters.ContainsKey(nameof(WeeksInterval)))
{
string msg = StringUtil.Format(ScheduledJobErrorStrings.InvalidWeeksInterval, ScheduledJobErrorStrings.TriggerStartUpType);
WriteValidationError(msg);
return false;
}
if (MyInvocation.BoundParameters.ContainsKey(nameof(At)))
{
string msg = StringUtil.Format(ScheduledJobErrorStrings.InvalidAtTime, ScheduledJobErrorStrings.TriggerStartUpType);
WriteValidationError(msg);
return false;
}
if (MyInvocation.BoundParameters.ContainsKey(nameof(User)))
{
string msg = StringUtil.Format(ScheduledJobErrorStrings.InvalidUser, ScheduledJobErrorStrings.TriggerStartUpType);
WriteValidationError(msg);
return false;
}
if (MyInvocation.BoundParameters.ContainsKey(nameof(DaysOfWeek)))
{
string msg = StringUtil.Format(ScheduledJobErrorStrings.InvalidDaysOfWeek, ScheduledJobErrorStrings.TriggerStartUpType);
WriteValidationError(msg);
return false;
}
if (MyInvocation.BoundParameters.ContainsKey(nameof(RepetitionInterval)) || MyInvocation.BoundParameters.ContainsKey(nameof(RepetitionDuration)) ||
MyInvocation.BoundParameters.ContainsKey(nameof(RepetitionInfiniteDuration)))
{
string msg = StringUtil.Format(ScheduledJobErrorStrings.InvalidSetTriggerRepetition, ScheduledJobErrorStrings.TriggerStartUpType);
WriteValidationError(msg);
return false;
}
return true;
}
private bool ValidateLogonParams()
{
if (MyInvocation.BoundParameters.ContainsKey(nameof(DaysInterval)))
{
string msg = StringUtil.Format(ScheduledJobErrorStrings.InvalidDaysInterval, ScheduledJobErrorStrings.TriggerLogonType);
WriteValidationError(msg);
return false;
}
if (MyInvocation.BoundParameters.ContainsKey(nameof(WeeksInterval)))
{
string msg = StringUtil.Format(ScheduledJobErrorStrings.InvalidWeeksInterval, ScheduledJobErrorStrings.TriggerLogonType);
WriteValidationError(msg);
return false;
}
if (MyInvocation.BoundParameters.ContainsKey(nameof(At)))
{
string msg = StringUtil.Format(ScheduledJobErrorStrings.InvalidAtTime, ScheduledJobErrorStrings.TriggerLogonType);
WriteValidationError(msg);
return false;
}
if (MyInvocation.BoundParameters.ContainsKey(nameof(DaysOfWeek)))
{
string msg = StringUtil.Format(ScheduledJobErrorStrings.InvalidDaysOfWeek, ScheduledJobErrorStrings.TriggerLogonType);
WriteValidationError(msg);
return false;
}
if (MyInvocation.BoundParameters.ContainsKey(nameof(RepetitionInterval)) || MyInvocation.BoundParameters.ContainsKey(nameof(RepetitionDuration)) ||
MyInvocation.BoundParameters.ContainsKey(nameof(RepetitionInfiniteDuration)))
{
string msg = StringUtil.Format(ScheduledJobErrorStrings.InvalidSetTriggerRepetition, ScheduledJobErrorStrings.TriggerLogonType);
WriteValidationError(msg);
return false;
}
return true;
}
private bool ValidateOnceParams(ScheduledJobTrigger trigger = null)
{
if (MyInvocation.BoundParameters.ContainsKey(nameof(DaysInterval)))
{
string msg = StringUtil.Format(ScheduledJobErrorStrings.InvalidDaysInterval, ScheduledJobErrorStrings.TriggerOnceType);
WriteValidationError(msg);
return false;
}
if (MyInvocation.BoundParameters.ContainsKey(nameof(WeeksInterval)))
{
string msg = StringUtil.Format(ScheduledJobErrorStrings.InvalidWeeksInterval, ScheduledJobErrorStrings.TriggerOnceType);
WriteValidationError(msg);
return false;
}
if (MyInvocation.BoundParameters.ContainsKey(nameof(User)))
{
string msg = StringUtil.Format(ScheduledJobErrorStrings.InvalidUser, ScheduledJobErrorStrings.TriggerOnceType);
WriteValidationError(msg);
return false;
}
if (MyInvocation.BoundParameters.ContainsKey(nameof(DaysOfWeek)))
{
string msg = StringUtil.Format(ScheduledJobErrorStrings.InvalidDaysOfWeek, ScheduledJobErrorStrings.TriggerOnceType);
WriteValidationError(msg);
return false;
}
if (MyInvocation.BoundParameters.ContainsKey(nameof(RepetitionInfiniteDuration)))
{
_repDuration = TimeSpan.MaxValue;
}
if (MyInvocation.BoundParameters.ContainsKey(nameof(RepetitionInterval)) || MyInvocation.BoundParameters.ContainsKey(nameof(RepetitionDuration)) ||
MyInvocation.BoundParameters.ContainsKey(nameof(RepetitionInfiniteDuration)))
{
// Validate Once trigger repetition parameters.
try
{
ScheduledJobTrigger.ValidateOnceRepetitionParams(_repInterval, _repDuration);
}
catch (PSArgumentException e)
{
WriteValidationError(e.Message);
return false;
}
}
if (trigger != null)
{
if (trigger.At == null && !MyInvocation.BoundParameters.ContainsKey(nameof(At)))
{
string msg = StringUtil.Format(ScheduledJobErrorStrings.MissingAtTime, ScheduledJobErrorStrings.TriggerOnceType);
WriteValidationError(msg);
return false;
}
}
return true;
}
private bool ValidateDailyParams(ScheduledJobTrigger trigger = null)
{
if (MyInvocation.BoundParameters.ContainsKey(nameof(DaysInterval)) &&
_daysInterval < 1)
{
WriteValidationError(ScheduledJobErrorStrings.InvalidDaysIntervalParam);
return false;
}
if (MyInvocation.BoundParameters.ContainsKey(nameof(WeeksInterval)))
{
string msg = StringUtil.Format(ScheduledJobErrorStrings.InvalidWeeksInterval, ScheduledJobErrorStrings.TriggerDailyType);
WriteValidationError(msg);
return false;
}
if (MyInvocation.BoundParameters.ContainsKey(nameof(User)))
{
string msg = StringUtil.Format(ScheduledJobErrorStrings.InvalidUser, ScheduledJobErrorStrings.TriggerDailyType);
WriteValidationError(msg);
return false;
}
if (MyInvocation.BoundParameters.ContainsKey(nameof(DaysOfWeek)))
{
string msg = StringUtil.Format(ScheduledJobErrorStrings.InvalidDaysOfWeek, ScheduledJobErrorStrings.TriggerDailyType);
WriteValidationError(msg);
return false;
}
if (MyInvocation.BoundParameters.ContainsKey(nameof(RepetitionInterval)) || MyInvocation.BoundParameters.ContainsKey(nameof(RepetitionDuration)) ||
MyInvocation.BoundParameters.ContainsKey(nameof(RepetitionInfiniteDuration)))
{
string msg = StringUtil.Format(ScheduledJobErrorStrings.InvalidSetTriggerRepetition, ScheduledJobErrorStrings.TriggerDailyType);
WriteValidationError(msg);
return false;
}
if (trigger != null)
{
if (trigger.At == null && !MyInvocation.BoundParameters.ContainsKey(nameof(At)))
{
string msg = StringUtil.Format(ScheduledJobErrorStrings.MissingAtTime, ScheduledJobErrorStrings.TriggerDailyType);
WriteValidationError(msg);
return false;
}
}
return true;
}
private bool ValidateWeeklyParams(ScheduledJobTrigger trigger = null)
{
if (MyInvocation.BoundParameters.ContainsKey(nameof(DaysInterval)))
{
string msg = StringUtil.Format(ScheduledJobErrorStrings.InvalidDaysInterval, ScheduledJobErrorStrings.TriggerWeeklyType);
WriteValidationError(msg);
return false;
}
if (MyInvocation.BoundParameters.ContainsKey(nameof(WeeksInterval)) &&
_weeksInterval < 1)
{
WriteValidationError(ScheduledJobErrorStrings.InvalidWeeksIntervalParam);
return false;
}
if (MyInvocation.BoundParameters.ContainsKey(nameof(User)))
{
string msg = StringUtil.Format(ScheduledJobErrorStrings.InvalidUser, ScheduledJobErrorStrings.TriggerWeeklyType);
WriteValidationError(msg);
return false;
}
if (MyInvocation.BoundParameters.ContainsKey(nameof(RepetitionInterval)) || MyInvocation.BoundParameters.ContainsKey(nameof(RepetitionDuration)) ||
MyInvocation.BoundParameters.ContainsKey(nameof(RepetitionInfiniteDuration)))
{
string msg = StringUtil.Format(ScheduledJobErrorStrings.InvalidSetTriggerRepetition, ScheduledJobErrorStrings.TriggerWeeklyType);
WriteValidationError(msg);
return false;
}
if (trigger != null)
{
if (trigger.At == null && !MyInvocation.BoundParameters.ContainsKey(nameof(At)))
{
string msg = StringUtil.Format(ScheduledJobErrorStrings.MissingAtTime, ScheduledJobErrorStrings.TriggerDailyType);
WriteValidationError(msg);
return false;
}
if ((trigger.DaysOfWeek == null || trigger.DaysOfWeek.Count == 0) &&
!MyInvocation.BoundParameters.ContainsKey(nameof(DaysOfWeek)))
{
string msg = StringUtil.Format(ScheduledJobErrorStrings.MissingDaysOfWeek, ScheduledJobErrorStrings.TriggerDailyType);
WriteValidationError(msg);
return false;
}
}
return true;
}
private bool UpdateTrigger(ScheduledJobTrigger trigger, TriggerFrequency triggerFrequency)
{
if (triggerFrequency != TriggerFrequency.None)
{
//
// User has specified a specific trigger type.
// Parameters have been validated for this trigger type.
//
if (triggerFrequency != trigger.Frequency)
{
// Changing to a new trigger type.
return CreateTrigger(trigger, triggerFrequency);
}
else
{
// Modifying existing trigger type.
return ModifyTrigger(trigger, triggerFrequency);
}
}
else
{
// We are updating an existing trigger. Need to validate params
// against each trigger type we are updating.
return ModifyTrigger(trigger, trigger.Frequency, true);
}
}
private bool CreateTrigger(ScheduledJobTrigger trigger, TriggerFrequency triggerFrequency)
{
switch (triggerFrequency)
{
case TriggerFrequency.AtStartup:
CreateAtStartupTrigger(trigger);
break;
case TriggerFrequency.AtLogon:
CreateAtLogonTrigger(trigger);
break;
case TriggerFrequency.Once:
if (trigger.Frequency != triggerFrequency &&
!ValidateOnceParams(trigger))
{
return false;
}
CreateOnceTrigger(trigger);
break;
case TriggerFrequency.Daily:
if (trigger.Frequency != triggerFrequency &&
!ValidateDailyParams(trigger))
{
return false;
}
CreateDailyTrigger(trigger);
break;
case TriggerFrequency.Weekly:
if (trigger.Frequency != triggerFrequency &&
!ValidateWeeklyParams(trigger))
{
return false;
}
CreateWeeklyTrigger(trigger);
break;
}
return true;
}
private bool ModifyTrigger(ScheduledJobTrigger trigger, TriggerFrequency triggerFrequency, bool validate = false)
{
switch (triggerFrequency)
{
case TriggerFrequency.AtStartup:
if (validate &&
!ValidateStartupParams())
{
return false;
}
ModifyStartupTrigger(trigger);
break;
case TriggerFrequency.AtLogon:
if (validate &&
!ValidateLogonParams())
{
return false;
}
ModifyLogonTrigger(trigger);
break;
case TriggerFrequency.Once:
if (validate &&
!ValidateOnceParams())
{
return false;
}
ModifyOnceTrigger(trigger);
break;
case TriggerFrequency.Daily:
if (validate &&
!ValidateDailyParams())
{
return false;
}
ModifyDailyTrigger(trigger);
break;
case TriggerFrequency.Weekly:
if (validate &&
!ValidateWeeklyParams())
{
return false;
}
ModifyWeeklyTrigger(trigger);
break;
}
return true;
}
private void ModifyStartupTrigger(ScheduledJobTrigger trigger)
{
if (MyInvocation.BoundParameters.ContainsKey(nameof(RandomDelay)))
{
trigger.RandomDelay = _randomDelay;
}
}
private void ModifyLogonTrigger(ScheduledJobTrigger trigger)
{
if (MyInvocation.BoundParameters.ContainsKey(nameof(RandomDelay)))
{
trigger.RandomDelay = _randomDelay;
}
if (MyInvocation.BoundParameters.ContainsKey(nameof(User)))
{
trigger.User = string.IsNullOrEmpty(_user) ? ScheduledJobTrigger.AllUsers : _user;
}
}
private void ModifyOnceTrigger(ScheduledJobTrigger trigger)
{
if (MyInvocation.BoundParameters.ContainsKey(nameof(RandomDelay)))
{
trigger.RandomDelay = _randomDelay;
}
if (MyInvocation.BoundParameters.ContainsKey(nameof(RepetitionInterval)))
{
trigger.RepetitionInterval = _repInterval;
}
if (MyInvocation.BoundParameters.ContainsKey(nameof(RepetitionDuration)))
{
trigger.RepetitionDuration = _repDuration;
}
if (MyInvocation.BoundParameters.ContainsKey(nameof(At)))
{
trigger.At = _atTime;
}
}
private void ModifyDailyTrigger(ScheduledJobTrigger trigger)
{
if (MyInvocation.BoundParameters.ContainsKey(nameof(RandomDelay)))
{
trigger.RandomDelay = _randomDelay;
}
if (MyInvocation.BoundParameters.ContainsKey(nameof(At)))
{
trigger.At = _atTime;
}
if (MyInvocation.BoundParameters.ContainsKey(nameof(DaysInterval)))
{
trigger.Interval = _daysInterval;
}
}
private void ModifyWeeklyTrigger(ScheduledJobTrigger trigger)
{
if (MyInvocation.BoundParameters.ContainsKey(nameof(RandomDelay)))
{
trigger.RandomDelay = _randomDelay;
}
if (MyInvocation.BoundParameters.ContainsKey(nameof(At)))
{
trigger.At = _atTime;
}
if (MyInvocation.BoundParameters.ContainsKey(nameof(WeeksInterval)))
{
trigger.Interval = _weeksInterval;
}
if (MyInvocation.BoundParameters.ContainsKey(nameof(DaysOfWeek)))
{
trigger.DaysOfWeek = new List<DayOfWeek>(_daysOfWeek);
}
}
private void CreateAtLogonTrigger(ScheduledJobTrigger trigger)
{
bool enabled = trigger.Enabled;
int id = trigger.Id;
TimeSpan randomDelay = trigger.RandomDelay;
string user = string.IsNullOrEmpty(trigger.User) ? ScheduledJobTrigger.AllUsers : trigger.User;
trigger.ClearProperties();
trigger.Frequency = TriggerFrequency.AtLogon;
trigger.Enabled = enabled;
trigger.Id = id;
trigger.RandomDelay = MyInvocation.BoundParameters.ContainsKey(nameof(RandomDelay)) ? _randomDelay : randomDelay;
trigger.User = MyInvocation.BoundParameters.ContainsKey(nameof(User)) ? _user : user;
}
private void CreateAtStartupTrigger(ScheduledJobTrigger trigger)
{
bool enabled = trigger.Enabled;
int id = trigger.Id;
TimeSpan randomDelay = trigger.RandomDelay;
trigger.ClearProperties();
trigger.Frequency = TriggerFrequency.AtStartup;
trigger.Enabled = enabled;
trigger.Id = id;
trigger.RandomDelay = MyInvocation.BoundParameters.ContainsKey(nameof(RandomDelay)) ? _randomDelay : randomDelay;
}
private void CreateOnceTrigger(ScheduledJobTrigger trigger)
{
bool enabled = trigger.Enabled;
int id = trigger.Id;
TimeSpan randomDelay = trigger.RandomDelay;
DateTime? atTime = trigger.At;
TimeSpan? repInterval = trigger.RepetitionInterval;
TimeSpan? repDuration = trigger.RepetitionDuration;
trigger.ClearProperties();
trigger.Frequency = TriggerFrequency.Once;
trigger.Enabled = enabled;
trigger.Id = id;
trigger.RandomDelay = MyInvocation.BoundParameters.ContainsKey(nameof(RandomDelay)) ? _randomDelay : randomDelay;
trigger.At = MyInvocation.BoundParameters.ContainsKey(nameof(At)) ? _atTime : atTime;
trigger.RepetitionInterval = MyInvocation.BoundParameters.ContainsKey(nameof(RepetitionInterval)) ? _repInterval : repInterval;
trigger.RepetitionDuration = MyInvocation.BoundParameters.ContainsKey(nameof(RepetitionDuration)) ? _repDuration : repDuration;
}
private void CreateDailyTrigger(ScheduledJobTrigger trigger)
{
bool enabled = trigger.Enabled;
int id = trigger.Id;
TimeSpan randomDelay = trigger.RandomDelay;
DateTime? atTime = trigger.At;
int interval = trigger.Interval;
trigger.ClearProperties();
trigger.Frequency = TriggerFrequency.Daily;
trigger.Enabled = enabled;
trigger.Id = id;
trigger.RandomDelay = MyInvocation.BoundParameters.ContainsKey(nameof(RandomDelay)) ? _randomDelay : randomDelay;
trigger.At = MyInvocation.BoundParameters.ContainsKey(nameof(At)) ? _atTime : atTime;
trigger.Interval = MyInvocation.BoundParameters.ContainsKey(nameof(DaysInterval)) ? _daysInterval : interval;
}
private void CreateWeeklyTrigger(ScheduledJobTrigger trigger)
{
bool enabled = trigger.Enabled;
int id = trigger.Id;
TimeSpan randomDelay = trigger.RandomDelay;
DateTime? atTime = trigger.At;
int interval = trigger.Interval;
List<DayOfWeek> daysOfWeek = trigger.DaysOfWeek;
trigger.ClearProperties();
trigger.Frequency = TriggerFrequency.Weekly;
trigger.Enabled = enabled;
trigger.Id = id;
trigger.RandomDelay = MyInvocation.BoundParameters.ContainsKey(nameof(RandomDelay)) ? _randomDelay : randomDelay;
trigger.At = MyInvocation.BoundParameters.ContainsKey(nameof(At)) ? _atTime : atTime;
trigger.Interval = MyInvocation.BoundParameters.ContainsKey(nameof(WeeksInterval)) ? _weeksInterval : interval;
trigger.DaysOfWeek = MyInvocation.BoundParameters.ContainsKey(nameof(DaysOfWeek)) ? new List<DayOfWeek>(_daysOfWeek) : daysOfWeek;
}
private void WriteValidationError(string msg)
{
Exception reason = new RuntimeException(msg);
ErrorRecord errorRecord = new ErrorRecord(reason, "SetJobTriggerParameterValidationError", ErrorCategory.InvalidArgument, null);
WriteError(errorRecord);
}
#endregion
}
}
| |
/*
Copyright(c) Microsoft Open Technologies, Inc. All rights reserved.
The MIT License(MIT)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files(the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions :
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Networking;
using Windows.System.Display;
using Windows.UI.Core;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Navigation;
using Newtonsoft.Json;
using Shield.Communication;
using Shield.Communication.Destinations;
using Shield.Communication.Services;
using Shield.Core;
using Shield.Core.Models;
using Shield.Services;
using Shield.ViewModels;
using Windows.UI.ViewManagement;
using Microsoft.ApplicationInsights;
namespace Shield
{
public sealed partial class MainPage : Page
{
private const long pingCheck = 60*10000000; //1min
internal readonly CoreDispatcher dispatcher;
private readonly MainViewModel model;
internal readonly Dictionary<string, int> sensors = new Dictionary<string, int>();
private Audio audio;
private Camera camera;
public Connection currentConnection;
private List<IDestination> destinations;
private bool isCameraInitialized;
private DisplayRequest keepScreenOnRequest;
private Manager manager;
private long nextPingCheck = DateTime.UtcNow.Ticks;
private long recentStringReceivedTick;
// Setup for ServerClient Connection
public string remoteHost = "SERVER_IP_OR_ADDRESS";
public string remoteService = "SERVER_PORT";
private long sentPingTick;
public ServiceBase service;
public bool IsInSettings = false;
private AppSettings appSettings = null;
public static MainPage Instance = null;
private TelemetryClient telemetry = new TelemetryClient();
private Screen screen;
private Web web;
public MainPage()
{
Instance = this;
appSettings = (AppSettings)App.Current.Resources["appSettings"];
InitializeComponent();
model = new MainViewModel();
dispatcher = CoreWindow.GetForCurrentThread().Dispatcher;
Initialize();
if (Windows.Foundation.Metadata.ApiInformation.IsTypePresent("Windows.Phone.UI.ViewManagement.StatusBar"))
{
if (StatusBar.GetForCurrentView() != null)
{
StatusBar.GetForCurrentView().BackgroundOpacity = 0.50;
}
}
}
public Sensors Sensors { get; set; }
private bool isRunning = false;
private Dictionary<string, ServiceBase> services = new Dictionary<string, ServiceBase>();
public void SetService()
{
if (appSettings.ConnectionIndex < 0)
{
return;
}
ServiceBase.OnConnectHandler OnConnection = async connection =>
{
await SendResult(new SystemResultMessage("CONNECT"), "!!");
};
ServiceBase.OnConnectHandler OnDisconnected = connection =>
{
this.Disconnect();
};
if (service != null)
{
service.OnConnect -= OnConnection;
service.OnDisconnected -= OnDisconnected;
}
if (appSettings.ConnectionIndex == 0)
{
service = services.ContainsKey("Bluetooth") ? services["Bluetooth"] : new Bluetooth();
services["Bluetooth"] = service;
}
else
{
service = services.ContainsKey("Wifi") ? services["Wifi"] : new Wifi();
services["Wifi"] = service;
if (appSettings.ConnectionIndex == 2 && !string.IsNullOrWhiteSpace(appSettings.Hostname))
{
service.SetClient("added",
new Connection("added",
new RemotePeer(null, new HostName(appSettings.Hostname), "1235")));
}
}
service.OnConnect += OnConnection;
service.OnDisconnected += OnDisconnected;
service.Initialize(!appSettings.MissingBackButton);
service.ListenForBeacons();
RefreshConnections();
}
private void Initialize()
{
destinations = new List<IDestination>();
DataContext = model;
model.Sensors = new Sensors(dispatcher);
MessageFactory.LoadClasses();
Sensors = model.Sensors;
// the Azure BLOB storage helper is handed to both Camera and audio for stream options
// if it is not used, no upload will to Azure BLOB will be done
camera = new Camera();
audio = new Audio();
Sensors.OnSensorUpdated += Sensors_OnSensorUpdated;
Sensors.Start();
NavigationCacheMode = NavigationCacheMode.Required;
canvas.PointerPressed += async (s, a) => await SendEvent(s, a, "pressed");
canvas.PointerReleased += async (s, a) => await SendEvent(s, a, "released");
Display.PointerPressed += async (s, a) => await SendEvent(s, a, "pressed");
Display.PointerReleased += async (s, a) => await SendEvent(s, a, "released");
screen = new Screen(this);
web = new Web(this);
CheckAlwaysRunning();
isRunning = true;
#pragma warning disable 4014
Task.Run(() =>
{
SetService();
AutoReconnect();
});
Task.Run(() => { ProcessMessages(); });
#pragma warning restore 4014
}
public void CheckAlwaysRunning(bool? force = null)
{
if ((force.HasValue && force.Value) || appSettings.AlwaysRunning)
{
keepScreenOnRequest = new DisplayRequest();
keepScreenOnRequest.RequestActive();
}
else if (keepScreenOnRequest != null)
{
keepScreenOnRequest.RequestRelease();
keepScreenOnRequest = null;
}
}
private async void AutoReconnect()
{
var isConnecting = false;
while (isRunning)
{
if (!isConnecting && this.currentConnection == null && !IsInSettings)
{
var previousConnection = appSettings.PreviousConnectionName;
if (!string.IsNullOrWhiteSpace(previousConnection) && appSettings.ConnectionList.Count > 0)
{
var item = appSettings.ConnectionList.FirstOrDefault(c => c.DisplayName == previousConnection);
if (item != null)
{
isConnecting = true;
await Connect(item);
await Task.Delay(30000);
isConnecting = false;
}
}
}
}
}
public async Task SendResult(ResultMessage resultMessage, string key = null)
{
key = key ?? resultMessage.Type.ToString();
var priority = GetPriorityOnKey(key);
var json = JsonConvert.SerializeObject(resultMessage,
new JsonSerializerSettings {NullValueHandling = NullValueHandling.Ignore});
await service.SendMessage(json, key, priority);
Log("S: " + json + "\r\n");
}
private int GetPriorityOnKey(string key)
{
return "AGMLQP".Contains(key) ? 20 : 10;
}
private async void Sensors_OnSensorUpdated(XYZ data)
{
var builder = new StringBuilder();
builder.Append("{\"Service\":\"SENSOR\", \"Type\":\"" + data.Tag + "\",\"Id\":");
builder.AppendFormat("{0}", data.Id);
foreach (var t in data.Data)
{
builder.AppendFormat(",\"{0}\":{1:0.0###}", t.Name, t.Value);
}
builder.Append("}");
await service.SendMessage(builder.ToString(), data.Tag, 20);
}
private void InitializeManager()
{
manager = new Manager();
manager.StringReceived += StringReceived;
manager.MessageReceived += QueueMessage;
}
private async Task InitializeCamera()
{
try
{
if (!isCameraInitialized && !isCameraInitializing)
{
await
dispatcher.RunAsync(CoreDispatcherPriority.Normal,
async () =>
{
await camera.InitializePreview(canvasBackground);
isCameraInitialized = true;
isCameraInitializing = false;
});
}
}
catch (Exception)
{
//camera not available
isCameraInitialized = false;
isCameraInitializing = false;
}
}
private async void StringReceived(string message)
{
recentStringReceivedTick = DateTime.UtcNow.Ticks;
if (message.Equals("{}"))
{
//indicates ready for messages
service.IsClearToSend = true;
var ticks = DateTime.UtcNow.Ticks;
if (ticks > nextPingCheck)
{
nextPingCheck = long.MaxValue - pingCheck < ticks ? 0 : ticks + pingCheck;
sentPingTick = DateTime.UtcNow.Ticks;
await SendResult(new SystemResultMessage("PING"));
}
}
}
private async void PopulateList()
{
Connections list;
if (service == null)
{
return;
}
try
{
list = await service.GetConnections();
if (list == null || list.Count == 0)
{
appSettings.ConnectionList.Clear();
return;
}
}
catch (Exception ex)
{
telemetry.TrackException(ex);
return;
}
if (!list.Any())
{
await dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
telemetry.TrackEvent("VirtualShieldConnectionEnumerationFail");
});
return;
}
var connections = new Connections();
foreach (var item in list)
{
connections.Add(item);
}
await dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
appSettings.ConnectionList = connections;
telemetry.TrackEvent("VirtualShieldConnectionEnumerationSuccess");
});
}
public async void Disconnect()
{
if (currentConnection != null)
{
await dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
appSettings.CurrentConnectionState = (int)ConnectionState.Disconnecting;
});
service.Disconnect(currentConnection);
currentConnection = null;
await dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
appSettings.CurrentConnectionState = (int)ConnectionState.NotConnected;
});
telemetry.TrackEvent("VirtualShieldDisconnect");
}
}
public async Task<bool> Connect(Connection selectedConnection)
{
bool result = false;
if (currentConnection != null)
{
service.Disconnect(currentConnection);
await Task.Delay(1000);
}
try
{
bool worked = false;
await dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
appSettings.CurrentConnectionState = (int)ConnectionState.Connecting;
});
await dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () =>
{
worked = await service.Connect(selectedConnection);
if (!worked)
{
appSettings.CurrentConnectionState = (int)ConnectionState.CouldNotConnect;
telemetry.TrackEvent("VirtualShieldConnectionFail");
}
else
{
appSettings.CurrentConnectionState = (int)ConnectionState.Connected;
currentConnection = selectedConnection;
appSettings.PreviousConnectionName = currentConnection.DisplayName;
telemetry.TrackEvent("VirtualShieldConnectionSuccess");
result = true;
}
});
if (service.CharEventHandlerCount == 0)
{
service.CharReceived += c => manager.OnCharsReceived(c.ToString());
service.CharEventHandlerCount++;
}
}
catch (Exception e)
{
this.Log("!:error connecting:" + e.Message);
await dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
appSettings.CurrentConnectionState = (int)ConnectionState.CouldNotConnect;
});
telemetry.TrackException(e);
}
return result;
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
InitializeManager();
if ((!appSettings.AutoConnect || string.IsNullOrWhiteSpace(appSettings.PreviousConnectionName))
&& this.currentConnection == null)
{
this.Frame.Navigate(typeof(SettingsPage));
}
if (!string.IsNullOrWhiteSpace(e.Parameter?.ToString()))
{
this.OnLaunchWhileActive(e.Parameter.ToString());
}
}
private async void ButtonBase_OnClick(object sender, RoutedEventArgs e)
{
await SendResult(new ScreenResultMessage
{
Service = "LCDG",
Type = 'S',
Action = "clicked",
Result = ((sender as Button).Tag).ToString(),
Area = "CONTROL"
});
}
private async void UIElement_OnHolding(object sender, HoldingRoutedEventArgs e)
{
await SendResult(new ScreenResultMessage
{
Service = "LCDG",
Type = 'S',
Action = "holding",
Result = ((sender as Button).Tag).ToString(),
Area = "CONTROL"
});
}
private void ToggleSwitch_Toggled(object sender, RoutedEventArgs e)
{
var swi = sender as ToggleSwitch;
manager.OnStringReceived("{ 'Service': 'SENSORS', 'Sensors': [ {'" + swi.Tag + "' : " +
(swi.IsOn ? "true" : "false") + "} ] }");
}
public void RefreshConnections()
{
PopulateList();
}
private void AppButtons_OnClick(object sender, RoutedEventArgs e)
{
var appbutton = sender as AppBarButton;
if (appbutton.Tag.Equals("Settings"))
{
this.Frame.Navigate(typeof(SettingsPage));
}
else if (appbutton.Tag.Equals("Control"))
{
appSettings.IsControlscreen = true;
}
else if (appbutton.Tag.Equals("Display")) // to full screen
{
appSettings.IsFullscreen = true;
}
else if (appbutton.Tag.Equals("Refresh"))
{
SendResult(new SystemResultMessage("REFRESH"), "!R").Wait();
}
else if (appbutton.Tag.Equals("CloseApp"))
{
CheckAlwaysRunning(false);
isRunning = false;
if (this.currentConnection != null)
{
this.service.Disconnect(this.currentConnection);
}
Application.Current.Exit();
}
commandBar.IsOpen = false;
}
public void UpdateDestinations()
{
// As of right now we only support one destination
destinations.Clear();
// Add the AzureBlob Destination Endpoint
var blobDestination = new AzureBlob(appSettings.BlobAccountName, appSettings.BlobAccountKey);
destinations.Add(blobDestination);
}
public async void OnLaunchWhileActive(string arguments)
{
try
{
var notify = JsonConvert.DeserializeObject<NotificationLaunch>(arguments);
if (notify != null)
{
await dispatcher.RunAsync(CoreDispatcherPriority.Normal,
async () =>
{
await
SendResult(new NotifyResultMessage()
{
Id = int.Parse(notify.Id),
Service = "NOTIFY",
Type = 'N',
Tag = notify.Tag
});
});
}
}
catch (Exception e)
{
this.Log("Toast:" + e.Message);
}
}
}
public class NotificationLaunch
{
public string Type { get; set; }
public string Id { get; set; }
public string Tag { get; set; }
}
}
| |
using Elizabeth;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;
using System.Collections.Generic;
using System.Linq;
namespace mogate
{
public enum PlayerState
{
Idle,
Moving,
Attacking,
};
public class PlayerLayer : Layer
{
Point m_toMove;
bool m_isLevelCompleted = false;
public PlayerLayer(Game game, string name, Scene scene, int z) : base(game, name, scene, z)
{
}
public override void OnActivated ()
{
var res = (IGameResources)Game.Services.GetService (typeof(IGameResources));
var world = (IWorld)Game.Services.GetService (typeof(IWorld));
var gameState = (IGameState)Game.Services.GetService (typeof(IGameState));
var mapGrid = world.GetLevel(gameState.Level);
var player = CreateEntity ("player");
player.Register (new State<PlayerState> (PlayerState.Idle));
player.Register (new Health (gameState.PlayerHealth, gameState.PlayerHealthMax,
() => OnHealthChanged(player)));
player.Register (new Attack (Archetypes.Weapons[gameState.PlayerWeaponID]["attack"], Archetypes.Weapons[gameState.PlayerWeaponID]["attack_distance"], gameState.PlayerWeaponID));
player.Register (new PointLight ((PointLight.DistanceType)gameState.PlayerViewDistanceType, Color.White));
player.Register (new MoveSpeed (gameState.PlayerMoveSpeed));
player.Register (new IFFSystem (Globals.IFF_PLAYER_ID, 2));
player.Register (new Attackable (OnAttacked));
player.Register (new Position (mapGrid.StairDown.X, mapGrid.StairDown.Y));
player.Register (new Execute ());
player.Register (new Poisonable (OnPoisoned));
player.Register (new Sprite (res.GetSprite (string.Format("player_{0:D2}", gameState.PlayerSpriteID))));
player.Register (new Drawable (new Vector2(mapGrid.StairDown.X * Globals.CELL_WIDTH, mapGrid.StairDown.Y * Globals.CELL_HEIGHT)));
player.Register (new Clickable (new Rectangle (0, 0, Globals.CELL_WIDTH * Globals.WORLD_WIDTH, Globals.CELL_HEIGHT * Globals.WORLD_HEIGHT), player));
player.Register (new Consumable<ConsumableTypes> ());
player.Register (new CriticalHit ());
player.Register (new MoneyMultiplier (gameState.PlayerMoneyMultiplier));
player.Register (new AttackMultiplier (gameState.PlayerAttackMultiplier));
player.Register (new PoisonChanceMultiplier (gameState.PlayerPoisonChanceMultiplier));
player.Register (new AttackDistanceMultiplier (gameState.PlayerAttackDistanceMultiplier));
player.Register (new AttackSpeed (gameState.PlayerAttackSpeed));
if (gameState.PlayerArmorID >= 0) {
player.Register (new Armor (Archetypes.Armors [gameState.PlayerArmorID] ["defence"], gameState.PlayerArmorID));
}
player.Get<Consumable<ConsumableTypes>> ().Refill (ConsumableTypes.Money, gameState.PlayerMoney);
player.Get<Consumable<ConsumableTypes>> ().Refill (ConsumableTypes.Antitod, gameState.PlayerAntitodPotions);
player.Get<Clickable> ().OnTouched += OnAction;
player.Get<Clickable>().OnKeyHold += OnKeyHold;
player.Get<Clickable>().OnKeyPressed += OnKeyPressed;
var seq = new Sequence ();
seq.Add (new ActionEntity (player, OnEnterToLevel));
var blink = new Loop(new ActionEntity(player, (_) => {
if (player.Get<Drawable>().DrawAlpha == 0.0f) {
player.Get<Drawable>().DrawAlpha = 1.0f;
} else {
player.Get<Drawable>().DrawAlpha = 0.0f;
}
}), 250);
seq.Add (new Timeline (blink, Globals.PLAYER_SPAWN_SEC * 1000));
seq.Add (new ActionEntity (player, (_AppDomain) => {
player.Get<Drawable>().DrawAlpha = 1.0f;
}));
seq.Add (new Loop (new ActionEntity (player, (_) => {
UpdatePlayer (player);
})));
player.Get<Execute>().Add(seq, "player_update_loop");
m_toMove = mapGrid.StairDown;
StartIdle (player);
}
public override void OnDeactivated ()
{
var gameState = (IGameState)Game.Services.GetService (typeof(IGameState));
var player = GetEntityByTag("player");
gameState.PlayerHealth = player.Get<Health> ().HP;
gameState.PlayerMoney = player.Get<Consumable<ConsumableTypes>> ().Amount (ConsumableTypes.Money);
gameState.PlayerAntitodPotions = player.Get<Consumable<ConsumableTypes>> ().Amount (ConsumableTypes.Antitod);
}
private void UpdatePlayer (Entity player)
{
var world = (IWorld)Game.Services.GetService (typeof(IWorld));
var gameState = (IGameState)Game.Services.GetService (typeof(IGameState));
var director = (IDirector)Game.Services.GetService (typeof(IDirector));
if (m_isLevelCompleted) {
gameState.NextLevel ();
director.ActivateScene ("inter");
return;
}
var mapGrid = world.GetLevel(gameState.Level);
var mapPos = player.Get<Position>().MapPos;
if (player.Get<State<PlayerState>>().EState == PlayerState.Idle) {
if (mapPos.X < m_toMove.X && mapGrid.GetID (mapPos.X + 1, mapPos.Y) != MapGridTypes.ID.Blocked)
mapPos.X++;
if (mapPos.X > m_toMove.X && mapGrid.GetID (mapPos.X - 1, mapPos.Y) != MapGridTypes.ID.Blocked)
mapPos.X--;
if (mapPos.Y < m_toMove.Y && mapGrid.GetID (mapPos.X, mapPos.Y + 1) != MapGridTypes.ID.Blocked)
mapPos.Y++;
if (mapPos.Y > m_toMove.Y && mapGrid.GetID (mapPos.X, mapPos.Y - 1) != MapGridTypes.ID.Blocked)
mapPos.Y--;
if (mapGrid.GetID (mapPos.X, mapPos.Y) != MapGridTypes.ID.Blocked && mapPos != player.Get<Position> ().MapPos) {
var seq = new Sequence ();
seq.Add (new MoveSpriteTo (player, new Vector2 (mapPos.X * Globals.CELL_WIDTH, mapPos.Y * Globals.CELL_HEIGHT), player.Get<MoveSpeed>().Speed));
seq.Add (new ActionEntity (player, (_) => {
player.Get<Position> ().MapPos = mapPos;
}));
seq.Add (new ActionEntity (player, OnEndMove));
player.Get<Execute> ().AddNew (seq, "movement");
player.Get<State<PlayerState>> ().EState = PlayerState.Moving;
}
}
}
private void OnKeyPressed(Keys key, Entity player)
{
if (key == Keys.Q)
m_isLevelCompleted = true;
else if (key == Keys.M)
{
player.Get<Consumable<ConsumableTypes>>().Refill(ConsumableTypes.Money, 100);
}
else if (key == Keys.S)
{
var stats = (IStatistics)Game.Services.GetService(typeof(IStatistics));
stats.Dump();
}
}
private void OnKeyHold(Keys key, Entity player)
{
var world = (IWorld)Game.Services.GetService(typeof(IWorld));
var gameState = (IGameState)Game.Services.GetService(typeof(IGameState));
var mapGrid = world.GetLevel(gameState.Level);
var mapPos = player.Get<Position>().MapPos;
if (key == Keys.Left)
--mapPos.X;
else if (key == Keys.Right)
++mapPos.X;
else if (key == Keys.Up)
--mapPos.Y;
else if (key == Keys.Down)
++mapPos.Y;
if (mapGrid.GetID(mapPos.X, mapPos.Y) != MapGridTypes.ID.Blocked
&& m_toMove != mapPos)
{
m_toMove = mapPos;
}
}
private void OnAction(Point clickPos, Entity _)
{
var world = (IWorld)Game.Services.GetService (typeof(IWorld));
var gameState = (IGameState)Game.Services.GetService (typeof(IGameState));
var mapGrid = world.GetLevel(gameState.Level);
var actionPos = mapGrid.ScreenToWorld (clickPos.X, clickPos.Y);
var player = GetEntityByTag("player");
var mapPos = player.Get<Position>().MapPos;
var actionPosID = mapGrid.GetID (actionPos.X, actionPos.Y);
var playerPosID = mapGrid.GetID (mapPos.X, mapPos.Y);
var state = player.Get<State<PlayerState>> ().EState;
if (state != PlayerState.Idle ||
actionPosID == MapGridTypes.ID.Blocked ||
actionPosID != playerPosID ||
actionPos == mapPos)
return;
var effects = (EffectsLayer)Scene.GetLayer ("effects");
var items = (ItemsLayer)Scene.GetLayer ("items");
var monsters = (MonstersLayer)Scene.GetLayer ("monsters");
float distMult = player.Get<AttackDistanceMultiplier> ().Multiplier;
if (Utils.Dist(mapPos, actionPos) <= (int)(player.Get<Attack>().Distance * distMult)) {
var mapLine = mapGrid.GetLine (mapPos, actionPos);
if (mapLine.Any() && !mapLine.Any (e => e.Type == MapGridTypes.ID.Blocked)) {
var seq = new Sequence ();
int weaponId = player.Get<Attack> ().ArchetypeID;
string weaponSpriteName = string.Format ("weapon_{0:D2}", Archetypes.Weapons [weaponId] ["sprite_index"]);
effects.SpawnEffect (actionPos, weaponSpriteName, player.Get<AttackSpeed> ().Speed);
var actionTargets = items.GetAllEntities ().Where (e => e.Has<Position> ()).ToList ();
actionTargets.AddRange (monsters.GetAllEntities ().Where (e => e.Has<Position> ()));
var target = actionTargets.FirstOrDefault (m => m.Get<Position> ().MapPos == actionPos);
if (target != default(Entity)) {
if (target.Has<IFFSystem> ()) {
if (player.Get<IFFSystem> ().IsFoe (target)) {
seq.Add (new AttackEntity (player, target));
}
}
}
seq.Add (new Delay (player.Get<AttackSpeed> ().Speed));
seq.Add (new ActionEntity (player, StartIdle));
player.Get<Execute> ().Add (seq, "attack");
player.Get<State<PlayerState>> ().EState = PlayerState.Attacking;
}
}
}
private void OnEnterToLevel(Entity player)
{
var gameState = (IGameState)Game.Services.GetService (typeof(IGameState));
var hud = (HUDLayer)Scene.GetLayer ("hud");
var msgs = new List<string> () { "He is scary", "He is sad", "He is happy",
"Monsters ahead", "He is a champ", "He wants eat"};
string feedbackMsg = string.Format ("{0} is here. {2}",
gameState.PlayerName, gameState.Level + 1, msgs[Utils.ThrowDice(msgs.Count)]);
hud.FeedbackMessage (feedbackMsg, Color.Yellow, (Globals.PLAYER_SPAWN_SEC + 2) * 1000);
}
private void OnEndMove(Entity player)
{
var items = (ItemsLayer)Scene.GetLayer ("items");
var maps = (MapGridLayer)Scene.GetLayer ("map");
var toTrigger = items.GetAllEntities ().Where (m => m.Has<Triggerable>()).ToList();
toTrigger.AddRange(maps.GetAllEntities ().Where (m => m.Has<Triggerable>()));
foreach (var item in toTrigger) {
player.Get<Execute> ().Add (new TriggerEntity (player, item));
}
StartIdle (player);
}
private void OnAttacked(Entity attacker, int damage, int critical)
{
var effects = (EffectsLayer)Scene.GetLayer ("effects");
var hud = (HUDLayer)Scene.GetLayer ("hud");
var player = GetEntityByTag("player");
effects.AttachEffect (player, "damage_01", 400);
string feedbackMsg = string.Format ("Damage {0} Critical {1}", damage, critical);
hud.FeedbackMessage (feedbackMsg, Color.Red);
}
private void OnHealthChanged(Entity player)
{
var director = (IDirector)Game.Services.GetService (typeof(IDirector));
var state = (IGameState)Game.Services.GetService (typeof(IGameState));
if (player.Get<Health> ().HP == 0) {
state.GameProgress = GameProgressState.Death;
director.ActivateScene ("inter");
}
}
private void OnPoisoned(Entity player, int damage)
{
var effects = (EffectsLayer)Scene.GetLayer ("effects");
var hud = (HUDLayer)Scene.GetLayer ("hud");
if (player.Get<Consumable<ConsumableTypes>> ().TryConsume (ConsumableTypes.Antitod, 1)) {
hud.FeedbackMessage ("Cured", Color.Yellow);
player.Get<Poisonable> ().CancelPoison (player);
} else {
effects.AttachEffect (player, "damage_01", 400);
string feedbackMsg = string.Format ("Poison {0}", damage);
hud.FeedbackMessage (feedbackMsg, Color.Red);
}
}
private void StartIdle(Entity player)
{
player.Get<State<PlayerState>>().EState = PlayerState.Idle;
}
}
}
| |
namespace GitVersion
{
using System;
using System.IO;
using System.Linq;
using GitTools.Git;
using LibGit2Sharp;
public class GitPreparer
{
string targetUrl;
string dynamicRepositoryLocation;
AuthenticationInfo authentication;
bool noFetch;
string targetPath;
public GitPreparer(string targetPath) : this(null, null, null, false, targetPath) { }
public GitPreparer(string targetUrl, string dynamicRepositoryLocation, Authentication authentication, bool noFetch, string targetPath)
{
this.targetUrl = targetUrl;
this.dynamicRepositoryLocation = dynamicRepositoryLocation;
this.authentication = authentication == null ?
null :
new AuthenticationInfo
{
Username = authentication.Username,
Password = authentication.Password
};
this.noFetch = noFetch;
this.targetPath = targetPath.TrimEnd('/', '\\');
}
public string WorkingDirectory
{
get { return targetPath; }
}
public bool IsDynamicGitRepository
{
get { return !string.IsNullOrWhiteSpace(DynamicGitRepositoryPath); }
}
public string DynamicGitRepositoryPath { get; private set; }
public void Initialise(bool normaliseGitDirectory, string currentBranch)
{
if (string.IsNullOrWhiteSpace(targetUrl))
{
if (normaliseGitDirectory)
{
GitRepositoryHelper.NormalizeGitDirectory(GetDotGitDirectory(), authentication, noFetch, currentBranch);
}
return;
}
var tempRepositoryPath = CalculateTemporaryRepositoryPath(targetUrl, dynamicRepositoryLocation);
DynamicGitRepositoryPath = CreateDynamicRepository(tempRepositoryPath, authentication, targetUrl, currentBranch, noFetch);
}
public TResult WithRepository<TResult>(Func<IRepository, TResult> action)
{
using (IRepository repo = new Repository(GetDotGitDirectory()))
{
return action(repo);
}
}
static string CalculateTemporaryRepositoryPath(string targetUrl, string dynamicRepositoryLocation)
{
var userTemp = dynamicRepositoryLocation ?? Path.GetTempPath();
var repositoryName = targetUrl.Split('/', '\\').Last().Replace(".git", string.Empty);
var possiblePath = Path.Combine(userTemp, repositoryName);
// Verify that the existing directory is ok for us to use
if (Directory.Exists(possiblePath))
{
if (!GitRepoHasMatchingRemote(possiblePath, targetUrl))
{
var i = 1;
var originalPath = possiblePath;
bool possiblePathExists;
do
{
possiblePath = string.Concat(originalPath, "_", i++.ToString());
possiblePathExists = Directory.Exists(possiblePath);
} while (possiblePathExists && !GitRepoHasMatchingRemote(possiblePath, targetUrl));
}
}
return possiblePath;
}
static bool GitRepoHasMatchingRemote(string possiblePath, string targetUrl)
{
try
{
using (var repository = new Repository(possiblePath))
{
return repository.Network.Remotes.Any(r => r.Url == targetUrl);
}
}
catch (Exception)
{
return false;
}
}
public string GetDotGitDirectory()
{
if (IsDynamicGitRepository)
return DynamicGitRepositoryPath;
var dotGitDirectory = Repository.Discover(targetPath);
if (String.IsNullOrEmpty(dotGitDirectory))
throw new DirectoryNotFoundException("Can't find the .git directory in " + targetPath);
dotGitDirectory = dotGitDirectory.TrimEnd('/', '\\');
if (string.IsNullOrEmpty(dotGitDirectory))
throw new DirectoryNotFoundException("Can't find the .git directory in " + targetPath);
return dotGitDirectory;
}
public string GetProjectRootDirectory()
{
Logger.WriteInfo(string.Format("IsDynamicGitRepository: {0}", IsDynamicGitRepository));
if (IsDynamicGitRepository)
{
Logger.WriteInfo(string.Format("Returning Project Root as {0}", targetPath));
return targetPath;
}
var dotGetGitDirectory = GetDotGitDirectory();
var result = Directory.GetParent(dotGetGitDirectory).FullName;
Logger.WriteInfo(string.Format("Returning Project Root from DotGitDirectory: {0} - {1}", dotGetGitDirectory, result));
return result;
}
static string CreateDynamicRepository(string targetPath, AuthenticationInfo authentication, string repositoryUrl, string targetBranch, bool noFetch)
{
if (string.IsNullOrWhiteSpace(targetBranch))
{
throw new Exception("Dynamic Git repositories must have a target branch (/b)");
}
Logger.WriteInfo(string.Format("Creating dynamic repository at '{0}'", targetPath));
var gitDirectory = Path.Combine(targetPath, ".git");
if (Directory.Exists(targetPath))
{
Logger.WriteInfo("Git repository already exists");
GitRepositoryHelper.NormalizeGitDirectory(gitDirectory, authentication, noFetch, targetBranch);
return gitDirectory;
}
CloneRepository(repositoryUrl, gitDirectory, authentication);
// Normalize (download branches) before using the branch
GitRepositoryHelper.NormalizeGitDirectory(gitDirectory, authentication, noFetch, targetBranch);
return gitDirectory;
}
static void CloneRepository(string repositoryUrl, string gitDirectory, AuthenticationInfo authentication)
{
Credentials credentials = null;
if (!string.IsNullOrWhiteSpace(authentication.Username) && !string.IsNullOrWhiteSpace(authentication.Password))
{
Logger.WriteInfo(string.Format("Setting up credentials using name '{0}'", authentication.Username));
credentials = new UsernamePasswordCredentials
{
Username = authentication.Username,
Password = authentication.Password
};
}
Logger.WriteInfo(string.Format("Retrieving git info from url '{0}'", repositoryUrl));
try
{
var cloneOptions = new CloneOptions
{
Checkout = false,
CredentialsProvider = (url, usernameFromUrl, types) => credentials
};
var returnedPath = Repository.Clone(repositoryUrl, gitDirectory, cloneOptions);
Logger.WriteInfo(string.Format("Returned path after repository clone: {0}", returnedPath));
}
catch (LibGit2SharpException ex)
{
var message = ex.Message;
if (message.Contains("401"))
{
throw new Exception("Unauthorised: Incorrect username/password");
}
if (message.Contains("403"))
{
throw new Exception("Forbidden: Possbily Incorrect username/password");
}
if (message.Contains("404"))
{
throw new Exception("Not found: The repository was not found");
}
throw new Exception("There was an unknown problem with the Git repository you provided", ex);
}
}
}
}
| |
#region License
/* Copyright (c) 2003-2015 Llewellyn Pritchard
* All rights reserved.
* This source code is subject to terms and conditions of the BSD License.
* See license.txt. */
#endregion
#region Includes
using System;
using System.Collections;
using System.IO;
using System.Drawing;
using IronScheme.Editor.ComponentModel;
using System.Windows.Forms;
using Microsoft.Build.BuildEngine;
using Project = IronScheme.Editor.Build.Project;
#endregion
namespace IronScheme.Editor.Controls
{
sealed class OutlineView : TreeView
{
public OutlineView()
{
Dock = DockStyle.Fill;
Sorted = true;
PathSeparator = Path.DirectorySeparatorChar.ToString();
Font = SystemInformation.MenuFont;
TreeViewNodeSorter = new TreeViewComparer();
}
class TreeViewComparer : IComparer
{
public int Compare(object x, object y)
{
TreeNode a = x as TreeNode;
TreeNode b = y as TreeNode;
if (a == null)
{
return 1;
}
if (b == null)
{
return -1;
}
BuildItem locabi = a.Tag as BuildItem;
BuildItem locbbi = b.Tag as BuildItem;
string loca = locabi != null ? locabi.Include : null;
string locb = locbbi != null ? locbbi.Include : null;
if (a.Text == "Properties")
{
return -1;
}
if (b.Text == "Properties")
{
return 1;
}
if (a.Text == "References")
{
return -1;
}
if (b.Text == "References")
{
return 1;
}
if (loca == null)
{
if (locb == null)
{
return a.Text.CompareTo(b.Text);
}
return -1;
}
if (locb == null)
{
return 1;
}
if (Directory.Exists(loca))
{
if (Directory.Exists(locb))
{
return loca.CompareTo(locb);
}
else
{
return -1;
}
}
else
{
if (Directory.Exists(locb))
{
return -1;
}
else
{
return loca.CompareTo(locb);
}
}
}
}
protected override void OnBeforeExpand(TreeViewCancelEventArgs e)
{
if (e.Node.ImageIndex == 1)
{
e.Node.ImageIndex = e.Node.SelectedImageIndex = 2;
}
base.OnBeforeExpand (e);
}
protected override void OnBeforeCollapse(TreeViewCancelEventArgs e)
{
if (e.Node.ImageIndex == 2)
{
e.Node.ImageIndex = e.Node.SelectedImageIndex = 1;
}
base.OnBeforeCollapse (e);
}
protected override void Dispose(bool disposing)
{
base.Dispose (disposing);
}
protected override void OnMouseDown(MouseEventArgs e)
{
base.OnMouseDown (e);
TreeNode r = SelectedNode;
if (r != null)
{
while (r.Parent != null)
{
r = r.Parent;
}
ServiceHost.Project.Current = r.Tag as Project;
}
}
protected override void OnMouseUp(MouseEventArgs e)
{
if (e.Button == MouseButtons.Right)
{
if (SelectedNode == null)
{
return;
}
ContextMenuStrip cm = new ContextMenuStrip();
object tag = SelectedNode.Tag;
if (tag is Project)
{
Project p = tag as Project;
IMenuService ms = ServiceHost.Menu;
ToolStripMenuItem pm = ms["Project"];
foreach (ToolStripItem mi in pm.DropDownItems)
{
if (mi is ToolStripSeparator)
{
cm.Items.Add(new ToolStripSeparator());
}
else
{
cm.Items.Add(((ToolStripMenuItem)mi).Clone());
}
}
}
else if (tag is BuildItem)
{
ToolStripMenuItem pmi = new ToolStripMenuItem("Remove", null,
new EventHandler(RemoveFile));
IImageListProviderService ims = ServiceHost.ImageListProvider;
cm.ImageList = ims.ImageList;
_RemoveFile rf = new _RemoveFile();
rf.value = tag;
pmi.ImageIndex = ims[rf];
cm.Items.Add(pmi);
cm.Items.Add(new ToolStripSeparator());
pmi = new ToolStripMenuItem("Action");
cm.Items.Add(pmi);
Project proj = ServiceHost.Project.Current;
foreach (string action in proj.Actions)
{
ToolStripMenuItem am = new ToolStripMenuItem(action, null, new EventHandler(ChangeAction));
pmi.DropDownItems.Add(am);
string dd = (tag as BuildItem).Name;
if (dd == action)
{
am.Checked = true;
}
}
}
cm.Show(this, new Point(e.X, e.Y));
}
base.OnMouseUp (e);
}
[Name("Remove"), Image("File.Close.png")]
class _RemoveFile
{
public object value;
}
void ChangeAction(object sender, EventArgs e)
{
BuildItem file = SelectedNode.Tag as BuildItem;
string action = (sender as ToolStripMenuItem).Text as string;
Project proj = ServiceHost.Project.Current;
proj.RemoveFile(file.Include);
if (SelectedNode.Nodes.Count == 0)
{
SelectedNode.Remove();
}
proj.AddFile(file.Include, action, true);
}
void RemoveFile(object sender, EventArgs e)
{
BuildItem file = (SelectedNode.Tag) as BuildItem;
if (file != null)
{
if (DialogResult.OK == MessageBox.Show(this, "Remove '" + file + "' from project?",
"Confirmation", MessageBoxButtons.OKCancel))
{
Project proj = ServiceHost.Project.Current;
SelectedNode.Remove();
proj.RemoveFile(file.Include);
}
}
}
}
}
| |
// ------------------------------------------------------------------------------
// 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\EntityRequest.cs.tt
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Threading;
using System.Linq.Expressions;
/// <summary>
/// The type ConversationThreadRequest.
/// </summary>
public partial class ConversationThreadRequest : BaseRequest, IConversationThreadRequest
{
/// <summary>
/// Constructs a new ConversationThreadRequest.
/// </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 ConversationThreadRequest(
string requestUrl,
IBaseClient client,
IEnumerable<Option> options)
: base(requestUrl, client, options)
{
}
/// <summary>
/// Creates the specified ConversationThread using POST.
/// </summary>
/// <param name="conversationThreadToCreate">The ConversationThread to create.</param>
/// <returns>The created ConversationThread.</returns>
public System.Threading.Tasks.Task<ConversationThread> CreateAsync(ConversationThread conversationThreadToCreate)
{
return this.CreateAsync(conversationThreadToCreate, CancellationToken.None);
}
/// <summary>
/// Creates the specified ConversationThread using POST.
/// </summary>
/// <param name="conversationThreadToCreate">The ConversationThread to create.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The created ConversationThread.</returns>
public async System.Threading.Tasks.Task<ConversationThread> CreateAsync(ConversationThread conversationThreadToCreate, CancellationToken cancellationToken)
{
this.ContentType = "application/json";
this.Method = "POST";
var newEntity = await this.SendAsync<ConversationThread>(conversationThreadToCreate, cancellationToken).ConfigureAwait(false);
this.InitializeCollectionProperties(newEntity);
return newEntity;
}
/// <summary>
/// Deletes the specified ConversationThread.
/// </summary>
/// <returns>The task to await.</returns>
public System.Threading.Tasks.Task DeleteAsync()
{
return this.DeleteAsync(CancellationToken.None);
}
/// <summary>
/// Deletes the specified ConversationThread.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The task to await.</returns>
public async System.Threading.Tasks.Task DeleteAsync(CancellationToken cancellationToken)
{
this.Method = "DELETE";
await this.SendAsync<ConversationThread>(null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets the specified ConversationThread.
/// </summary>
/// <returns>The ConversationThread.</returns>
public System.Threading.Tasks.Task<ConversationThread> GetAsync()
{
return this.GetAsync(CancellationToken.None);
}
/// <summary>
/// Gets the specified ConversationThread.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The ConversationThread.</returns>
public async System.Threading.Tasks.Task<ConversationThread> GetAsync(CancellationToken cancellationToken)
{
this.Method = "GET";
var retrievedEntity = await this.SendAsync<ConversationThread>(null, cancellationToken).ConfigureAwait(false);
this.InitializeCollectionProperties(retrievedEntity);
return retrievedEntity;
}
/// <summary>
/// Updates the specified ConversationThread using PATCH.
/// </summary>
/// <param name="conversationThreadToUpdate">The ConversationThread to update.</param>
/// <returns>The updated ConversationThread.</returns>
public System.Threading.Tasks.Task<ConversationThread> UpdateAsync(ConversationThread conversationThreadToUpdate)
{
return this.UpdateAsync(conversationThreadToUpdate, CancellationToken.None);
}
/// <summary>
/// Updates the specified ConversationThread using PATCH.
/// </summary>
/// <param name="conversationThreadToUpdate">The ConversationThread to update.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The updated ConversationThread.</returns>
public async System.Threading.Tasks.Task<ConversationThread> UpdateAsync(ConversationThread conversationThreadToUpdate, CancellationToken cancellationToken)
{
this.ContentType = "application/json";
this.Method = "PATCH";
var updatedEntity = await this.SendAsync<ConversationThread>(conversationThreadToUpdate, cancellationToken).ConfigureAwait(false);
this.InitializeCollectionProperties(updatedEntity);
return updatedEntity;
}
/// <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 IConversationThreadRequest 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 IConversationThreadRequest Expand(Expression<Func<ConversationThread, 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 IConversationThreadRequest 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 IConversationThreadRequest Select(Expression<Func<ConversationThread, 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>
/// Initializes any collection properties after deserialization, like next requests for paging.
/// </summary>
/// <param name="conversationThreadToInitialize">The <see cref="ConversationThread"/> with the collection properties to initialize.</param>
private void InitializeCollectionProperties(ConversationThread conversationThreadToInitialize)
{
if (conversationThreadToInitialize != null && conversationThreadToInitialize.AdditionalData != null)
{
if (conversationThreadToInitialize.Posts != null && conversationThreadToInitialize.Posts.CurrentPage != null)
{
conversationThreadToInitialize.Posts.AdditionalData = conversationThreadToInitialize.AdditionalData;
object nextPageLink;
conversationThreadToInitialize.AdditionalData.TryGetValue("posts@odata.nextLink", out nextPageLink);
var nextPageLinkString = nextPageLink as string;
if (!string.IsNullOrEmpty(nextPageLinkString))
{
conversationThreadToInitialize.Posts.InitializeNextPageRequest(
this.Client,
nextPageLinkString);
}
}
}
}
}
}
| |
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 Service.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>>
{
DefaultSampleObjectFactory,
};
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order,
/// stopping when the factory successfully returns a non-<see langref="null"/> object.
/// </summary>
/// <remarks>
/// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use
/// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and
/// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",
Justification = "This is an appropriate nesting of generic types")]
public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames.
// If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames.
// If still not found, try to get the sample provided for the specified mediaType and type.
// Finally, try to get the sample provided for the specified mediaType.
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create
/// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other
/// factories in <see cref="SampleObjectFactories"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")]
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// No specific object available, try our factories.
foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories)
{
if (factory == null)
{
continue;
}
try
{
sampleObject = factory(this, type);
if (sampleObject != null)
{
break;
}
}
catch
{
// Ignore any problems encountered in the factory; go on to the next one (if any).
}
}
}
return sampleObject;
}
/// <summary>
/// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The type.</returns>
public virtual Type ResolveHttpRequestMessageType(ApiDescription api)
{
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters);
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
UnwrapException(e).Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
internal static Exception UnwrapException(Exception exception)
{
AggregateException aggregateException = exception as AggregateException;
if (aggregateException != null)
{
return aggregateException.Flatten().InnerException;
}
return exception;
}
// Default factory for sample objects
private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type)
{
// Try to create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
using System;
using System.Collections;
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 XamarinAzure.Backend.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;
}
}
}
| |
/* VRManagerScript
* MiddleVR
* (c) MiddleVR
*/
using UnityEngine;
using MiddleVR_Unity3D;
[AddComponentMenu("")]
public class VRManagerScript : MonoBehaviour
{
public enum ENavigation{
None,
Joystick,
Elastic,
GrabWorld
}
public enum EVirtualHandMapping{
Direct,
Gogo
}
public enum EManipulation{
None,
Ray,
Homer
}
// Public readable parameters
[HideInInspector]
public float WandAxisHorizontal = 0.0f;
[HideInInspector]
public float WandAxisVertical = 0.0f;
[HideInInspector]
public bool WandButton0 = false;
[HideInInspector]
public bool WandButton1 = false;
[HideInInspector]
public bool WandButton2 = false;
[HideInInspector]
public bool WandButton3 = false;
[HideInInspector]
public bool WandButton4 = false;
[HideInInspector]
public bool WandButton5 = false;
[HideInInspector]
public double DeltaTime = 0.0f;
private vrCommand m_startParticlesCommand = null;
// Exposed parameters:
public string ConfigFile = "c:\\config.vrx";
public GameObject VRSystemCenterNode = null;
public GameObject TemplateCamera = null;
public bool ShowWand = true;
[SerializeField]
private bool m_UseVRMenu = false;
public bool UseVRMenu
{
get
{
return m_UseVRMenu;
}
set
{
_EnableVRMenu(value);
}
}
public ENavigation Navigation = ENavigation.Joystick;
public EManipulation Manipulation = EManipulation.Ray;
public EVirtualHandMapping VirtualHandMapping = EVirtualHandMapping.Direct;
[SerializeField]
private bool m_ShowScreenProximityWarnings = false;
public bool ShowScreenProximityWarnings
{
get
{
return m_ShowScreenProximityWarnings;
}
set
{
_EnableProximityWarning(value);
}
}
[SerializeField]
private bool m_Fly = false;
public bool Fly
{
get
{
return m_Fly;
}
set
{
_EnableNavigationFly(value);
}
}
[SerializeField]
private bool m_NavigationCollisions = false;
public bool NavigationCollisions
{
get
{
return m_NavigationCollisions;
}
set
{
_EnableNavigationCollision(value);
}
}
[SerializeField]
private bool m_ManipulationReturnObjects = false;
public bool ManipulationReturnObjects
{
get
{
return m_ManipulationReturnObjects;
}
set
{
_EnableManipulationReturnObjects(value);
}
}
[SerializeField]
private bool m_ShowFPS = true;
public bool ShowFPS
{
get
{
return m_ShowFPS;
}
set
{
_EnableFPSDisplay(value);
}
}
public bool DisableExistingCameras = true;
public bool GrabExistingNodes = false;
public bool DebugNodes = false;
public bool DebugScreens = false;
public bool QuitOnEsc = true;
public bool DontChangeWindowGeometry = false;
public bool SimpleCluster = true;
public bool SimpleClusterParticles = true;
public bool ForceQuality = false;
public int ForceQualityIndex = 3;
public bool CustomLicense = false;
public string CustomLicenseName;
public string CustomLicenseCode;
// Private members
private vrKernel m_Kernel = null;
private vrDeviceManager m_DeviceMgr = null;
private vrDisplayManager m_DisplayMgr = null;
private vrClusterManager m_ClusterMgr = null;
private GameObject m_Wand = null;
private GameObject m_VRMenu = null;
private bool m_isInit = false;
private bool m_isGeometrySet = false;
private bool m_displayLog = false;
private int m_AntiAliasingLevel = 0;
private bool m_NeedDelayedRenderingReset = false;
private int m_RenderingResetDelay = 1;
private GUIText m_GUI = null;
private bool[] mouseButtons = new bool[3];
private bool m_AllowRenderTargetAA = false;
private uint m_FirstFrameAfterReset = 0;
private bool m_InteractionsInitialized = false;
private vrCommand m_QuitCommand = null;
// Public methods
public void Log(string text)
{
MVRTools.Log(text);
}
public bool IsKeyPressed(uint iKey)
{
return m_DeviceMgr.IsKeyPressed(iKey);
}
public bool IsMouseButtonPressed(uint iButtonIndex)
{
return m_DeviceMgr.IsMouseButtonPressed(iButtonIndex);
}
public float GetMouseAxisValue(uint iAxisIndex)
{
return m_DeviceMgr.GetMouseAxisValue(iAxisIndex);
}
// Private methods
void InitializeVR()
{
mouseButtons[0] = mouseButtons[1] = mouseButtons[2] = false;
if (m_displayLog)
{
GameObject gui = new GameObject();
m_GUI = gui.AddComponent<GUIText>() as GUIText;
gui.transform.localPosition = new UnityEngine.Vector3(0.5f, 0.0f, 0.0f);
m_GUI.pixelOffset = new UnityEngine.Vector2(15, 0);
m_GUI.anchor = TextAnchor.LowerCenter;
}
MVRTools.IsEditor = Application.isEditor;
if( MiddleVR.VRKernel != null )
{
MVRTools.Log(3, "[ ] VRKernel already alive, reset Unity Manager.");
MVRTools.VRReset();
m_isInit = true;
// Not needed because this is the first execution of this script instance
// m_isGeometrySet = false;
m_FirstFrameAfterReset = MiddleVR.VRKernel.GetFrame();
}
else
{
if( CustomLicense )
{
MVRTools.CustomLicense = true;
MVRTools.CustomLicenseName = CustomLicenseName;
MVRTools.CustomLicenseCode = CustomLicenseCode;
}
m_isInit = MVRTools.VRInitialize(ConfigFile);
}
if (SimpleClusterParticles)
{
_SetParticlesSeeds();
}
// Get AA from vrx configuration file
m_AntiAliasingLevel = (int)MiddleVR.VRDisplayMgr.GetAntiAliasing();
DumpOptions();
if (!m_isInit)
{
GameObject gui = new GameObject();
m_GUI = gui.AddComponent<GUIText>() as GUIText;
gui.transform.localPosition = new UnityEngine.Vector3(0.2f, 0.0f, 0.0f);
m_GUI.pixelOffset = new UnityEngine.Vector2(0, 0);
m_GUI.anchor = TextAnchor.LowerLeft;
string txt = m_Kernel.GetLogString(true);
print(txt);
m_GUI.text = txt;
return;
}
m_Kernel = MiddleVR.VRKernel;
m_DeviceMgr = MiddleVR.VRDeviceMgr;
m_DisplayMgr = MiddleVR.VRDisplayMgr;
m_ClusterMgr = MiddleVR.VRClusterMgr;
if (SimpleCluster)
{
SetupSimpleCluster();
}
if (DisableExistingCameras)
{
Camera[] cameras = GameObject.FindObjectsOfType(typeof(Camera)) as Camera[];
foreach (Camera cam in cameras)
{
if (cam.targetTexture == null)
{
cam.enabled = false;
}
}
}
MVRNodesCreator.Instance.CreateNodes(VRSystemCenterNode, DebugNodes, DebugScreens, GrabExistingNodes, TemplateCamera);
MVRTools.CreateViewportsAndCameras(DontChangeWindowGeometry, m_AllowRenderTargetAA);
//AttachCameraCB();
MVRTools.Log(4, "[<] End of VR initialization script");
}
void AttachCameraCB()
{
Camera[] cameras = GameObject.FindObjectsOfType(typeof(Camera)) as Camera[];
foreach (Camera cam in cameras)
{
if (cam.targetTexture != null)
{
cam.gameObject.AddComponent<VRCameraCB>();
}
}
}
protected void Awake()
{
MVRNodesMapper.CreateInstance();
MVRNodesCreator.CreateInstance();
InitializeVR();
}
protected void Start ()
{
MVRTools.Log(4, "[>] VR Manager Start.");
m_Kernel.DeleteLateObjects();
#if !UNITY_3_4 && !UNITY_3_5 && !UNITY_4_0 && !UNITY_4_0_1 && !UNITY_4_1
m_AllowRenderTargetAA = true;
#endif
// Reset Manager's position so text display is correct.
transform.position = new UnityEngine.Vector3(0, 0, 0);
transform.rotation = new Quaternion();
transform.localScale = new UnityEngine.Vector3(1, 1, 1);
m_Wand = GameObject.Find("VRWand");
m_VRMenu = GameObject.Find("VRMenu");
ShowWandGeometry(ShowWand);
_EnableProximityWarning(m_ShowScreenProximityWarnings);
_EnableFPSDisplay(m_ShowFPS);
_EnableNavigationCollision(m_NavigationCollisions);
_EnableManipulationReturnObjects(m_ManipulationReturnObjects);
_EnableVRMenu(m_UseVRMenu);
if (ForceQuality)
{
QualitySettings.SetQualityLevel(ForceQualityIndex);
}
// Manage VSync after the quality settings
MVRTools.ManageVSync();
// Set AA from vrx configuration file
QualitySettings.antiAliasing = m_AntiAliasingLevel;
// Check if MiddleVR Reset is needed
if (!Application.isEditor && (ForceQuality || QualitySettings.antiAliasing > 1))
{
bool useOpenGLQuadbuffer = m_DisplayMgr.GetActiveViewport(0).GetStereo() && (m_DisplayMgr.GetActiveViewport(0).GetStereoMode() == 0); //VRStereoMode_QuadBuffer = 0
if (useOpenGLQuadbuffer || m_ClusterMgr.GetForceOpenGLConversion())
{
m_NeedDelayedRenderingReset = true;
m_RenderingResetDelay = 1;
}
}
m_QuitCommand = new vrCommand("VRManager.QuitApplicationCommand", _QuitApplicationCommandHandler);
MVRTools.Log(4, "[<] End of VR Manager Start.");
}
private vrValue StartParticlesCommandHandler(vrValue iValue)
{
// We get all the randomSeed / playOnAwake of the master's particle systems
// to sync the slaves.
ParticleSystem[] particles = GameObject.FindObjectsOfType(typeof(ParticleSystem)) as ParticleSystem[];
for (uint i = 0, iEnd = iValue.GetListItemsNb(), particlesCnt = (uint)particles.GetLength(0); i < iEnd && i < particlesCnt; ++i)
{
particles[i].randomSeed = (uint)iValue.GetListItem(i).GetListItem(0).GetInt();
if (iValue.GetListItem(i).GetListItem(1).GetBool())
{
particles[i].Play();
}
}
return null;
}
private void _SetParticlesSeeds()
{
if (MiddleVR.VRClusterMgr.IsCluster())
{
// Creating the list of randomSeed / is playOnAwake to sync the seeds
// of each particle systems to the master
vrValue particlesDataList = vrValue.CreateList();
foreach (ParticleSystem particle in GameObject.FindObjectsOfType(typeof(ParticleSystem)) as ParticleSystem[])
{
if (MiddleVR.VRClusterMgr.IsServer())
{
vrValue particleData = vrValue.CreateList();
particleData.AddListItem((int)particle.randomSeed);
particleData.AddListItem(particle.playOnAwake);
particlesDataList.AddListItem(particleData);
}
// We reset the particle systems to sync them in every nodes of the cluster
particle.Clear();
particle.Stop();
particle.time = .0f;
}
m_startParticlesCommand = new vrCommand("startParticleCommand", StartParticlesCommandHandler);
if (MiddleVR.VRClusterMgr.IsServer())
{
m_startParticlesCommand.Do(particlesDataList);
}
}
}
private void _SetNavigation(ENavigation iNavigation)
{
Navigation = iNavigation;
VRInteractionNavigationWandJoystick navigationWandJoystick = m_Wand.GetComponent<VRInteractionNavigationWandJoystick>();
VRInteractionNavigationElastic navigationElastic = m_Wand.GetComponent<VRInteractionNavigationElastic>();
VRInteractionNavigationGrabWorld navigationGrabWorld = m_Wand.GetComponent<VRInteractionNavigationGrabWorld>();
if (navigationWandJoystick == null || navigationElastic == null || navigationGrabWorld == null)
{
MVRTools.Log(2, "[~] Some navigation scripts are missing on the Wand.");
return;
}
if (navigationWandJoystick.GetInteraction() == null || navigationElastic.GetInteraction() == null || navigationGrabWorld.GetInteraction() == null)
{
MVRTools.Log(2, "[~] Some navigation interactions are not initialized.");
return;
}
switch (Navigation)
{
case ENavigation.None:
MiddleVR.VRInteractionMgr.Deactivate(navigationWandJoystick.GetInteraction());
MiddleVR.VRInteractionMgr.Deactivate(navigationElastic.GetInteraction());
MiddleVR.VRInteractionMgr.Deactivate(navigationGrabWorld.GetInteraction());
break;
case ENavigation.Joystick:
MiddleVR.VRInteractionMgr.Activate(navigationWandJoystick.GetInteraction());
break;
case ENavigation.Elastic:
MiddleVR.VRInteractionMgr.Activate(navigationElastic.GetInteraction());
break;
case ENavigation.GrabWorld:
MiddleVR.VRInteractionMgr.Activate(navigationGrabWorld.GetInteraction());
break;
default:
break;
}
}
private void _SetManipulation(EManipulation iManpulation)
{
Manipulation = iManpulation;
VRInteractionManipulationRay manipulationRay = m_Wand.GetComponent<VRInteractionManipulationRay>();
VRInteractionManipulationHomer manipulationHomer = m_Wand.GetComponent<VRInteractionManipulationHomer>();
if (manipulationRay == null || manipulationHomer == null)
{
MVRTools.Log(2, "[~] Some manipulation scripts are missing on the Wand.");
return;
}
switch (Manipulation)
{
case EManipulation.None:
MiddleVR.VRInteractionMgr.Deactivate(manipulationRay.GetInteraction());
MiddleVR.VRInteractionMgr.Deactivate(manipulationHomer.GetInteraction());
break;
case EManipulation.Ray:
MiddleVR.VRInteractionMgr.Activate(manipulationRay.GetInteraction());
break;
case EManipulation.Homer:
MiddleVR.VRInteractionMgr.Activate(manipulationHomer.GetInteraction());
break;
default:
break;
}
}
private void _SetVirtualHandMapping(EVirtualHandMapping iVirtualHandMapping)
{
VirtualHandMapping = iVirtualHandMapping;
VRInteractionVirtualHandGogo virtualHandGogo = m_Wand.GetComponent<VRInteractionVirtualHandGogo>();
if (virtualHandGogo == null)
{
MVRTools.Log(2, "[~] The virtual hand Gogo script is missing on the Wand.");
return;
}
switch (VirtualHandMapping)
{
case EVirtualHandMapping.Direct:
MiddleVR.VRInteractionMgr.Deactivate(virtualHandGogo.GetInteraction());
break;
case EVirtualHandMapping.Gogo:
MiddleVR.VRInteractionMgr.Activate(virtualHandGogo.GetInteraction());
break;
default:
break;
}
}
private void _EnableProximityWarning(bool iShow)
{
m_ShowScreenProximityWarnings = iShow;
VRInteractionScreenProximityWarning proximityWarning = m_Wand.GetComponent<VRInteractionScreenProximityWarning>();
if (proximityWarning != null)
{
proximityWarning.enabled = m_ShowScreenProximityWarnings;
}
}
private void _EnableFPSDisplay(bool iEnable)
{
m_ShowFPS = iEnable;
this.GetComponent<GUIText>().enabled = m_ShowFPS;
}
private void _EnableVRMenu(bool iEnable)
{
m_UseVRMenu = iEnable;
if (m_VRMenu != null)
{
m_VRMenu.GetComponent<VRMenuManager>().UseVRMenu(m_UseVRMenu);
}
}
private void _EnableNavigationFly(bool iEnable)
{
m_Fly = iEnable;
vrInteractionManager interactionMgr = vrInteractionManager.GetInstance();
for (uint i = 0, iEnd = interactionMgr.GetInteractionsNb(); i < iEnd; ++i)
{
vrProperty flyProp = interactionMgr.GetInteractionByIndex(i).GetProperty("Fly");
if (flyProp != null)
{
flyProp.SetBool(m_Fly);
}
}
}
private void _EnableNavigationCollision(bool iEnable)
{
m_NavigationCollisions = iEnable;
VRNavigationCollision navigationCollision = m_Wand.GetComponent<VRNavigationCollision>();
if (navigationCollision != null)
{
navigationCollision.enabled = m_NavigationCollisions;
}
}
private void _EnableManipulationReturnObjects(bool iEnable)
{
m_ManipulationReturnObjects = iEnable;
VRInteractionManipulationReturnObjects returnObjects = m_Wand.GetComponent<VRInteractionManipulationReturnObjects>();
if (returnObjects != null)
{
returnObjects.enabled = m_ManipulationReturnObjects;
}
}
public void ShowWandGeometry(bool iShow)
{
if (m_Wand != null)
{
m_Wand.GetComponent<VRWand>().Show(iShow);
}
}
void UpdateInput()
{
vrButtons wandButtons = m_DeviceMgr.GetWandButtons();
if (wandButtons != null)
{
uint buttonNb = wandButtons.GetButtonsNb();
if (buttonNb > 0)
{
WandButton0 = wandButtons.IsPressed(m_DeviceMgr.GetWandButton0());
}
if (buttonNb > 1)
{
WandButton1 = wandButtons.IsPressed(m_DeviceMgr.GetWandButton1());
}
if (buttonNb > 2)
{
WandButton2 = wandButtons.IsPressed(m_DeviceMgr.GetWandButton2());
}
if (buttonNb > 3)
{
WandButton3 = wandButtons.IsPressed(m_DeviceMgr.GetWandButton3());
}
if (buttonNb > 4)
{
WandButton4 = wandButtons.IsPressed(m_DeviceMgr.GetWandButton4());
}
if (buttonNb > 5)
{
WandButton5 = wandButtons.IsPressed(m_DeviceMgr.GetWandButton5());
}
}
WandAxisHorizontal = m_DeviceMgr.GetWandHorizontalAxisValue();
WandAxisVertical = m_DeviceMgr.GetWandVerticalAxisValue();
}
// Update is called once per frame
void Update ()
{
//MVRTools.Log("VRManagerUpdate");
// Initialize interactions
if( !m_InteractionsInitialized )
{
_SetNavigation(Navigation);
_SetManipulation(Manipulation);
_SetVirtualHandMapping(VirtualHandMapping);
m_InteractionsInitialized = true;
}
MVRNodesMapper nodesMapper = MVRNodesMapper.Instance;
nodesMapper.UpdateNodesUnityToMiddleVR();
if (m_isInit)
{
MVRTools.Log(4, "[>] Unity Update - Start");
if (m_Kernel.GetFrame() >= m_FirstFrameAfterReset+1 && !m_isGeometrySet && !Application.isEditor)
{
if (!DontChangeWindowGeometry)
{
m_DisplayMgr.SetUnityWindowGeometry();
}
m_isGeometrySet = true;
}
if (m_Kernel.GetFrame() == 0)
{
// Set the random seed in kernel for dispatching only during start-up.
// With clustering, a client will be set by a call to kernel.Update().
if (!m_ClusterMgr.IsCluster() ||
(m_ClusterMgr.IsCluster() && m_ClusterMgr.IsServer()))
{
// The cast is safe because the seed is always positive.
uint seed = (uint) UnityEngine.Random.seed;
m_Kernel._SetRandomSeed(seed);
}
}
m_Kernel.Update();
if (m_Kernel.GetFrame() == 0)
{
// Set the random seed in a client only during start-up.
if (m_ClusterMgr.IsCluster() && m_ClusterMgr.IsClient())
{
// The cast is safe because the seed comes from
// a previous value of Unity.
int seed = (int) m_Kernel.GetRandomSeed();
UnityEngine.Random.seed = seed;
}
}
UpdateInput();
if (ShowFPS)
{
this.GetComponent<GUIText>().text = m_Kernel.GetFPS().ToString("f2");
}
nodesMapper.UpdateNodesMiddleVRToUnity(false);
MVRTools.UpdateCameraProperties();
if (m_displayLog)
{
string txt = m_Kernel.GetLogString(true);
print(txt);
m_GUI.text = txt;
}
vrKeyboard keyb = m_DeviceMgr.GetKeyboard();
if (keyb != null)
{
if (keyb.IsKeyPressed(MiddleVR.VRK_LSHIFT) || keyb.IsKeyPressed(MiddleVR.VRK_RSHIFT))
{
if (keyb.IsKeyToggled(MiddleVR.VRK_D))
{
ShowFPS = !ShowFPS;
}
if (keyb.IsKeyToggled(MiddleVR.VRK_W) || keyb.IsKeyToggled(MiddleVR.VRK_Z))
{
ShowWand = !ShowWand;
ShowWandGeometry(ShowWand);
}
// Toggle Fly mode on interactions
if (keyb.IsKeyToggled(MiddleVR.VRK_F))
{
Fly = !Fly;
}
// Navigation mode switch
if (keyb.IsKeyToggled(MiddleVR.VRK_N))
{
vrInteraction navigation = _GetNextInteraction("ContinuousNavigation");
if (navigation != null)
{
MiddleVR.VRInteractionMgr.Activate(navigation);
}
}
}
}
DeltaTime = m_Kernel.GetDeltaTime();
MVRTools.Log(4, "[<] Unity Update - End");
}
else
{
//Debug.LogWarning("[ ] If you have an error mentioning 'DLLNotFoundException: MiddleVR_CSharp', please restart Unity. If this does not fix the problem, please make sure MiddleVR is in the PATH environment variable.");
}
// If QualityLevel changed, we have to reset the Unity Manager
if( m_NeedDelayedRenderingReset )
{
if( m_RenderingResetDelay == 0 )
{
MVRTools.Log(3,"[ ] Graphic quality forced, reset Unity Manager.");
MVRTools.VRReset();
MVRTools.CreateViewportsAndCameras(DontChangeWindowGeometry, m_AllowRenderTargetAA);
m_isGeometrySet = false;
m_NeedDelayedRenderingReset = false;
}
else
{
--m_RenderingResetDelay;
}
}
}
void AddClusterScripts(GameObject iObject)
{
MVRTools.Log(2, "[ ] Adding cluster sharing scripts to " + iObject.name);
if (iObject.GetComponent<VRShareTransform>() == null)
{
iObject.AddComponent<VRShareTransform>();
}
}
void SetupSimpleCluster()
{
if (m_ClusterMgr.IsCluster())
{
// Rigid bodies
Rigidbody[] bodies = FindObjectsOfType(typeof(Rigidbody)) as Rigidbody[];
foreach (Rigidbody body in bodies)
{
if (!body.isKinematic)
{
GameObject iObject = body.gameObject;
AddClusterScripts(iObject);
}
}
// Character controller
CharacterController[] ctrls = FindObjectsOfType(typeof(CharacterController)) as CharacterController[];
foreach (CharacterController ctrl in ctrls)
{
GameObject iObject = ctrl.gameObject;
AddClusterScripts(iObject);
}
}
}
void DumpOptions()
{
MVRTools.Log(3, "[ ] Dumping VRManager's options:");
MVRTools.Log(3, "[ ] - Config File : " + ConfigFile);
MVRTools.Log(3, "[ ] - System Center Node : " + VRSystemCenterNode);
MVRTools.Log(3, "[ ] - Template Camera : " + TemplateCamera);
MVRTools.Log(3, "[ ] - Show Wand : " + ShowWand);
MVRTools.Log(3, "[ ] - Show FPS : " + ShowFPS);
MVRTools.Log(3, "[ ] - Disable Existing Cameras : " + DisableExistingCameras);
MVRTools.Log(3, "[ ] - Grab Existing Nodes : " + GrabExistingNodes);
MVRTools.Log(3, "[ ] - Debug Nodes : " + DebugNodes);
MVRTools.Log(3, "[ ] - Debug Screens : " + DebugScreens);
MVRTools.Log(3, "[ ] - Quit On Esc : " + QuitOnEsc);
MVRTools.Log(3, "[ ] - Don't Change Window Geometry : " + DontChangeWindowGeometry);
MVRTools.Log(3, "[ ] - Simple Cluster : " + SimpleCluster);
MVRTools.Log(3, "[ ] - Simple Cluster Particles : " + SimpleClusterParticles );
MVRTools.Log(3, "[ ] - Force Quality : " + ForceQuality );
MVRTools.Log(3, "[ ] - Force QualityIndex : " + ForceQualityIndex );
MVRTools.Log(3, "[ ] - Anti-Aliasing Level : " + m_AntiAliasingLevel );
MVRTools.Log(3, "[ ] - Custom License : " + CustomLicense );
MVRTools.Log(3, "[ ] - Custom License Name : " + CustomLicenseName );
MVRTools.Log(3, "[ ] - Custom License Code : " + CustomLicenseCode );
}
private vrInteraction _GetNextInteraction(string iTag)
{
vrInteraction nextInteraction = null;
vrInteraction activeInteraction = MiddleVR.VRInteractionMgr.GetActiveInteractionByTag("ContinuousNavigation");
if (activeInteraction != null)
{
// Found active interaction, search for the next one
uint interactionsNb = MiddleVR.VRInteractionMgr.GetInteractionsNb();
uint index = MiddleVR.VRInteractionMgr.GetInteractionIndex(activeInteraction);
for (uint i = 0; i < interactionsNb - 1; ++i)
{
// We loop in the interactions list to find the next interaction with the right tag
uint nextIndex = (index + 1 + i) % interactionsNb;
vrInteraction interaction = MiddleVR.VRInteractionMgr.GetInteractionByIndex(nextIndex);
if (interaction != null && interaction.TagsContain("ContinuousNavigation"))
{
nextInteraction = interaction;
break;
}
}
}
else
{
// No active interaction, try to activate the first if existing
nextInteraction = MiddleVR.VRInteractionMgr.GetInteractionByTag("ContinuousNavigation", 0);
}
return nextInteraction;
}
public void QuitApplication()
{
MVRTools.Log(3,"[ ] Execute QuitCommand.");
// Call cluster command so that all cluster nodes quit
m_QuitCommand.Do(new vrValue());
}
private vrValue _QuitApplicationCommandHandler(vrValue iValue)
{
MVRTools.Log(3, "[ ] Received QuitApplicationCommand");
MVRTools.Log("[ ] Unity says we're quitting.");
MiddleVR.VRKernel.SetQuitting();
Application.Quit();
return null;
}
void OnApplicationQuit()
{
MVRNodesCreator.DestroyInstance();
MVRNodesMapper.DestroyInstance();
MVRTools.VRDestroy(Application.isEditor);
}
void OnDestroy()
{
if (m_startParticlesCommand != null)
{
m_startParticlesCommand.Dispose();
m_startParticlesCommand = null;
}
}
}
| |
namespace iControl {
using System.Xml.Serialization;
using System.Web.Services;
using System.ComponentModel;
using System.Web.Services.Protocols;
using System;
using System.Diagnostics;
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Web.Services.WebServiceBindingAttribute(Name="Management.RADIUSConfigurationBinding", Namespace="urn:iControl")]
public partial class ManagementRADIUSConfiguration : iControlInterface {
public ManagementRADIUSConfiguration() {
this.Url = "https://url_to_service";
}
//=======================================================================
// Operations
//=======================================================================
//-----------------------------------------------------------------------
// add_server
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/RADIUSConfiguration",
RequestNamespace="urn:iControl:Management/RADIUSConfiguration", ResponseNamespace="urn:iControl:Management/RADIUSConfiguration")]
public void add_server(
string [] config_names,
string [] [] servers
) {
this.Invoke("add_server", new object [] {
config_names,
servers});
}
public System.IAsyncResult Beginadd_server(string [] config_names,string [] [] servers, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("add_server", new object[] {
config_names,
servers}, callback, asyncState);
}
public void Endadd_server(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// create
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/RADIUSConfiguration",
RequestNamespace="urn:iControl:Management/RADIUSConfiguration", ResponseNamespace="urn:iControl:Management/RADIUSConfiguration")]
public void create(
string [] config_names,
string [] [] servers
) {
this.Invoke("create", new object [] {
config_names,
servers});
}
public System.IAsyncResult Begincreate(string [] config_names,string [] [] servers, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("create", new object[] {
config_names,
servers}, callback, asyncState);
}
public void Endcreate(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// create_default_authentication_radius_configuration
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/RADIUSConfiguration",
RequestNamespace="urn:iControl:Management/RADIUSConfiguration", ResponseNamespace="urn:iControl:Management/RADIUSConfiguration")]
public void create_default_authentication_radius_configuration(
string [] servers
) {
this.Invoke("create_default_authentication_radius_configuration", new object [] {
servers});
}
public System.IAsyncResult Begincreate_default_authentication_radius_configuration(string [] servers, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("create_default_authentication_radius_configuration", new object[] {
servers}, callback, asyncState);
}
public void Endcreate_default_authentication_radius_configuration(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// delete_all_configurations
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/RADIUSConfiguration",
RequestNamespace="urn:iControl:Management/RADIUSConfiguration", ResponseNamespace="urn:iControl:Management/RADIUSConfiguration")]
public void delete_all_configurations(
) {
this.Invoke("delete_all_configurations", new object [0]);
}
public System.IAsyncResult Begindelete_all_configurations(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("delete_all_configurations", new object[0], callback, asyncState);
}
public void Enddelete_all_configurations(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// delete_configuration
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/RADIUSConfiguration",
RequestNamespace="urn:iControl:Management/RADIUSConfiguration", ResponseNamespace="urn:iControl:Management/RADIUSConfiguration")]
public void delete_configuration(
string [] config_names
) {
this.Invoke("delete_configuration", new object [] {
config_names});
}
public System.IAsyncResult Begindelete_configuration(string [] config_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("delete_configuration", new object[] {
config_names}, callback, asyncState);
}
public void Enddelete_configuration(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// get_accounting_validation_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/RADIUSConfiguration",
RequestNamespace="urn:iControl:Management/RADIUSConfiguration", ResponseNamespace="urn:iControl:Management/RADIUSConfiguration")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public CommonEnabledState [] get_accounting_validation_state(
string [] config_names
) {
object [] results = this.Invoke("get_accounting_validation_state", new object [] {
config_names});
return ((CommonEnabledState [])(results[0]));
}
public System.IAsyncResult Beginget_accounting_validation_state(string [] config_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_accounting_validation_state", new object[] {
config_names}, callback, asyncState);
}
public CommonEnabledState [] Endget_accounting_validation_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((CommonEnabledState [])(results[0]));
}
//-----------------------------------------------------------------------
// get_client_id
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/RADIUSConfiguration",
RequestNamespace="urn:iControl:Management/RADIUSConfiguration", ResponseNamespace="urn:iControl:Management/RADIUSConfiguration")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_client_id(
string [] config_names
) {
object [] results = this.Invoke("get_client_id", new object [] {
config_names});
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_client_id(string [] config_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_client_id", new object[] {
config_names}, callback, asyncState);
}
public string [] Endget_client_id(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_debug_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/RADIUSConfiguration",
RequestNamespace="urn:iControl:Management/RADIUSConfiguration", ResponseNamespace="urn:iControl:Management/RADIUSConfiguration")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public CommonEnabledState [] get_debug_state(
string [] config_names
) {
object [] results = this.Invoke("get_debug_state", new object [] {
config_names});
return ((CommonEnabledState [])(results[0]));
}
public System.IAsyncResult Beginget_debug_state(string [] config_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_debug_state", new object[] {
config_names}, callback, asyncState);
}
public CommonEnabledState [] Endget_debug_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((CommonEnabledState [])(results[0]));
}
//-----------------------------------------------------------------------
// get_description
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/RADIUSConfiguration",
RequestNamespace="urn:iControl:Management/RADIUSConfiguration", ResponseNamespace="urn:iControl:Management/RADIUSConfiguration")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_description(
string [] config_names
) {
object [] results = this.Invoke("get_description", new object [] {
config_names});
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_description(string [] config_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_description", new object[] {
config_names}, callback, asyncState);
}
public string [] Endget_description(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_list
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/RADIUSConfiguration",
RequestNamespace="urn:iControl:Management/RADIUSConfiguration", ResponseNamespace="urn:iControl:Management/RADIUSConfiguration")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_list(
) {
object [] results = this.Invoke("get_list", new object [0]);
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_list(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_list", new object[0], callback, asyncState);
}
public string [] Endget_list(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_retry
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/RADIUSConfiguration",
RequestNamespace="urn:iControl:Management/RADIUSConfiguration", ResponseNamespace="urn:iControl:Management/RADIUSConfiguration")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public long [] get_retry(
string [] config_names
) {
object [] results = this.Invoke("get_retry", new object [] {
config_names});
return ((long [])(results[0]));
}
public System.IAsyncResult Beginget_retry(string [] config_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_retry", new object[] {
config_names}, callback, asyncState);
}
public long [] Endget_retry(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((long [])(results[0]));
}
//-----------------------------------------------------------------------
// get_server
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/RADIUSConfiguration",
RequestNamespace="urn:iControl:Management/RADIUSConfiguration", ResponseNamespace="urn:iControl:Management/RADIUSConfiguration")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] [] get_server(
string [] config_names
) {
object [] results = this.Invoke("get_server", new object [] {
config_names});
return ((string [] [])(results[0]));
}
public System.IAsyncResult Beginget_server(string [] config_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_server", new object[] {
config_names}, callback, asyncState);
}
public string [] [] Endget_server(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [] [])(results[0]));
}
//-----------------------------------------------------------------------
// get_service_type
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/RADIUSConfiguration",
RequestNamespace="urn:iControl:Management/RADIUSConfiguration", ResponseNamespace="urn:iControl:Management/RADIUSConfiguration")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public ManagementRadiusServiceType [] get_service_type(
string [] config_names
) {
object [] results = this.Invoke("get_service_type", new object [] {
config_names});
return ((ManagementRadiusServiceType [])(results[0]));
}
public System.IAsyncResult Beginget_service_type(string [] config_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_service_type", new object[] {
config_names}, callback, asyncState);
}
public ManagementRadiusServiceType [] Endget_service_type(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((ManagementRadiusServiceType [])(results[0]));
}
//-----------------------------------------------------------------------
// get_version
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/RADIUSConfiguration",
RequestNamespace="urn:iControl:Management/RADIUSConfiguration", ResponseNamespace="urn:iControl:Management/RADIUSConfiguration")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string get_version(
) {
object [] results = this.Invoke("get_version", new object [] {
});
return ((string)(results[0]));
}
public System.IAsyncResult Beginget_version(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_version", new object[] {
}, callback, asyncState);
}
public string Endget_version(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string)(results[0]));
}
//-----------------------------------------------------------------------
// remove_all_servers
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/RADIUSConfiguration",
RequestNamespace="urn:iControl:Management/RADIUSConfiguration", ResponseNamespace="urn:iControl:Management/RADIUSConfiguration")]
public void remove_all_servers(
string [] config_names
) {
this.Invoke("remove_all_servers", new object [] {
config_names});
}
public System.IAsyncResult Beginremove_all_servers(string [] config_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("remove_all_servers", new object[] {
config_names}, callback, asyncState);
}
public void Endremove_all_servers(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// remove_server
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/RADIUSConfiguration",
RequestNamespace="urn:iControl:Management/RADIUSConfiguration", ResponseNamespace="urn:iControl:Management/RADIUSConfiguration")]
public void remove_server(
string [] config_names,
string [] [] servers
) {
this.Invoke("remove_server", new object [] {
config_names,
servers});
}
public System.IAsyncResult Beginremove_server(string [] config_names,string [] [] servers, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("remove_server", new object[] {
config_names,
servers}, callback, asyncState);
}
public void Endremove_server(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_accounting_validation_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/RADIUSConfiguration",
RequestNamespace="urn:iControl:Management/RADIUSConfiguration", ResponseNamespace="urn:iControl:Management/RADIUSConfiguration")]
public void set_accounting_validation_state(
string [] config_names,
CommonEnabledState [] states
) {
this.Invoke("set_accounting_validation_state", new object [] {
config_names,
states});
}
public System.IAsyncResult Beginset_accounting_validation_state(string [] config_names,CommonEnabledState [] states, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_accounting_validation_state", new object[] {
config_names,
states}, callback, asyncState);
}
public void Endset_accounting_validation_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_client_id
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/RADIUSConfiguration",
RequestNamespace="urn:iControl:Management/RADIUSConfiguration", ResponseNamespace="urn:iControl:Management/RADIUSConfiguration")]
public void set_client_id(
string [] config_names,
string [] client_ids
) {
this.Invoke("set_client_id", new object [] {
config_names,
client_ids});
}
public System.IAsyncResult Beginset_client_id(string [] config_names,string [] client_ids, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_client_id", new object[] {
config_names,
client_ids}, callback, asyncState);
}
public void Endset_client_id(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_debug_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/RADIUSConfiguration",
RequestNamespace="urn:iControl:Management/RADIUSConfiguration", ResponseNamespace="urn:iControl:Management/RADIUSConfiguration")]
public void set_debug_state(
string [] config_names,
CommonEnabledState [] states
) {
this.Invoke("set_debug_state", new object [] {
config_names,
states});
}
public System.IAsyncResult Beginset_debug_state(string [] config_names,CommonEnabledState [] states, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_debug_state", new object[] {
config_names,
states}, callback, asyncState);
}
public void Endset_debug_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_description
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/RADIUSConfiguration",
RequestNamespace="urn:iControl:Management/RADIUSConfiguration", ResponseNamespace="urn:iControl:Management/RADIUSConfiguration")]
public void set_description(
string [] config_names,
string [] descriptions
) {
this.Invoke("set_description", new object [] {
config_names,
descriptions});
}
public System.IAsyncResult Beginset_description(string [] config_names,string [] descriptions, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_description", new object[] {
config_names,
descriptions}, callback, asyncState);
}
public void Endset_description(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_retry
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/RADIUSConfiguration",
RequestNamespace="urn:iControl:Management/RADIUSConfiguration", ResponseNamespace="urn:iControl:Management/RADIUSConfiguration")]
public void set_retry(
string [] config_names,
long [] retries
) {
this.Invoke("set_retry", new object [] {
config_names,
retries});
}
public System.IAsyncResult Beginset_retry(string [] config_names,long [] retries, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_retry", new object[] {
config_names,
retries}, callback, asyncState);
}
public void Endset_retry(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_service_type
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:Management/RADIUSConfiguration",
RequestNamespace="urn:iControl:Management/RADIUSConfiguration", ResponseNamespace="urn:iControl:Management/RADIUSConfiguration")]
public void set_service_type(
string [] config_names,
ManagementRadiusServiceType [] service_types
) {
this.Invoke("set_service_type", new object [] {
config_names,
service_types});
}
public System.IAsyncResult Beginset_service_type(string [] config_names,ManagementRadiusServiceType [] service_types, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_service_type", new object[] {
config_names,
service_types}, callback, asyncState);
}
public void Endset_service_type(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
}
//=======================================================================
// Enums
//=======================================================================
//=======================================================================
// Structs
//=======================================================================
}
| |
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 WebServiceMarvel.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;
}
}
}
| |
//---------------------------------------------------------------------------
//
// File: XamlWriter.cs
//
// Description:
// base Parser class that parses XML markup into an Avalon Element Tree
//
//
// History:
// 6/06/01: rogerg Created as Parser.cs
// 5/29/03: peterost Ported to wcp as Parser.cs
// 8/04/05: a-neabbu Split Parser into XamlReader and XamlWriter
//
// Copyright (C) 2003 by Microsoft Corporation. All rights reserved.
//
//---------------------------------------------------------------------------
using System;
using System.Xml;
using System.IO;
using System.IO.Packaging;
using System.Windows;
using System.Collections;
using System.Diagnostics;
using System.Reflection;
using System.Windows.Threading;
using MS.Utility;
using System.Security;
using System.Security.Permissions;
using System.Security.Policy;
using System.Text;
using System.ComponentModel.Design.Serialization;
using System.Globalization;
using System.Windows.Markup.Primitives;
using MS.Internal.IO.Packaging;
using MS.Internal.PresentationFramework;
namespace System.Windows.Markup
{
/// <summary>
/// Parsing class used to create an Windows Presentation Platform Tree
/// </summary>
public static class XamlWriter
{
#region Public Methods
/// <summary>
/// Save gets the xml respresentation
/// for the given object instance
/// </summary>
/// <param name="obj">
/// Object instance
/// </param>
/// <returns>
/// XAML string representing object instance
/// </returns>
/// <SecurityNote>
/// Critcal: We only allow Serialization in partial trust. Although we would throw an exception later anyways,
/// we throw one here so we know where to expect the exception. (
[SecuritySafeCritical]
public static string Save(object obj)
{
// Must be in full trust
SecurityHelper.DemandUnmanagedCode();
// Validate input arguments
if (obj == null)
{
throw new ArgumentNullException("obj");
}
// Create TextWriter
StringBuilder sb = new StringBuilder();
TextWriter writer = new StringWriter(sb, TypeConverterHelper.InvariantEnglishUS);
try
{
Save(obj, writer);
}
finally
{
// Close writer
writer.Close();
}
return sb.ToString();
}
/// <summary>
/// Save writes the xml respresentation
/// for the given object instance using the given writer
/// </summary>
/// <param name="obj">
/// Object instance
/// </param>
/// <param name="writer">
/// Text Writer
/// </param>
/// <SecurityNote>
/// Critcal: We only allow Serialization in full trust. Although we would throw an exception later anyways,
/// we throw one here so we know where to expect the exception. (
[SecuritySafeCritical]
public static void Save(object obj, TextWriter writer)
{
// Must be in full trust
SecurityHelper.DemandUnmanagedCode();
// Validate input arguments
if (obj == null)
{
throw new ArgumentNullException("obj");
}
if (writer == null)
{
throw new ArgumentNullException("writer");
}
// Create XmlTextWriter
XmlTextWriter xmlWriter = new XmlTextWriter(writer);
MarkupWriter.SaveAsXml(xmlWriter, obj);
}
/// <summary>
/// Save writes the xml respresentation
/// for the given object instance to the given stream
/// </summary>
/// <param name="obj">
/// Object instance
/// </param>
/// <param name="stream">
/// Stream
/// </param>
/// <SecurityNote>
/// Critcal: We only allow Serialization in full trust. Although we would throw an exception later anyways,
/// we throw one here so we know where to expect the exception. (
[SecuritySafeCritical]
public static void Save(object obj, Stream stream)
{
// Must be in full trust
SecurityHelper.DemandUnmanagedCode();
// Validate input arguments
if (obj == null)
{
throw new ArgumentNullException("obj");
}
if (stream == null)
{
throw new ArgumentNullException("stream");
}
// Create XmlTextWriter
XmlTextWriter xmlWriter = new XmlTextWriter(stream, null);
MarkupWriter.SaveAsXml(xmlWriter, obj);
}
/// <summary>
/// Save writes the xml respresentation
/// for the given object instance using the given
/// writer. In addition it also allows the designer
/// to participate in this conversion.
/// </summary>
/// <param name="obj">
/// Object instance
/// </param>
/// <param name="xmlWriter">
/// XmlWriter
/// </param>
/// <SecurityNote>
/// Critcal: We only allow Serialization in full trust. Although we would throw an exception later anyways,
/// we throw one here so we know where to expect the exception. (
[SecuritySafeCritical]
public static void Save(object obj, XmlWriter xmlWriter)
{
// Must be in full trust
SecurityHelper.DemandUnmanagedCode();
// Validate input arguments
if (obj == null)
{
throw new ArgumentNullException("obj");
}
if (xmlWriter == null)
{
throw new ArgumentNullException("xmlWriter");
}
try
{
MarkupWriter.SaveAsXml(xmlWriter, obj);
}
finally
{
xmlWriter.Flush();
}
}
/// <summary>
/// Save writes the xml respresentation
/// for the given object instance using the
/// given XmlTextWriter embedded in the manager.
/// </summary>
/// <param name="obj">
/// Object instance
/// </param>
/// <param name="manager">
/// Serialization Manager
/// </param>
/// <SecurityNote>
/// Critcal: We only allow Serialization in full trust. Although we would throw an exception later anyways,
/// we throw one here so we know where to expect the exception. (
[SecuritySafeCritical]
public static void Save(object obj, XamlDesignerSerializationManager manager)
{
// Must be in full trust
SecurityHelper.DemandUnmanagedCode();
// Validate input arguments
if (obj == null)
{
throw new ArgumentNullException("obj");
}
if (manager == null)
{
throw new ArgumentNullException("manager");
}
MarkupWriter.SaveAsXml(manager.XmlWriter, obj, manager);
}
#endregion Public Methods
}
}
| |
// 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 gcav = Google.Cloud.AIPlatform.V1;
using sys = System;
namespace Google.Cloud.AIPlatform.V1
{
/// <summary>Resource name for the <c>ModelEvaluation</c> resource.</summary>
public sealed partial class ModelEvaluationName : gax::IResourceName, sys::IEquatable<ModelEvaluationName>
{
/// <summary>The possible contents of <see cref="ModelEvaluationName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern
/// <c>projects/{project}/locations/{location}/models/{model}/evaluations/{evaluation}</c>.
/// </summary>
ProjectLocationModelEvaluation = 1,
}
private static gax::PathTemplate s_projectLocationModelEvaluation = new gax::PathTemplate("projects/{project}/locations/{location}/models/{model}/evaluations/{evaluation}");
/// <summary>Creates a <see cref="ModelEvaluationName"/> 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="ModelEvaluationName"/> containing the provided
/// <paramref name="unparsedResourceName"/>.
/// </returns>
public static ModelEvaluationName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new ModelEvaluationName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="ModelEvaluationName"/> with the pattern
/// <c>projects/{project}/locations/{location}/models/{model}/evaluations/{evaluation}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="modelId">The <c>Model</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="evaluationId">The <c>Evaluation</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="ModelEvaluationName"/> constructed from the provided ids.</returns>
public static ModelEvaluationName FromProjectLocationModelEvaluation(string projectId, string locationId, string modelId, string evaluationId) =>
new ModelEvaluationName(ResourceNameType.ProjectLocationModelEvaluation, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), modelId: gax::GaxPreconditions.CheckNotNullOrEmpty(modelId, nameof(modelId)), evaluationId: gax::GaxPreconditions.CheckNotNullOrEmpty(evaluationId, nameof(evaluationId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="ModelEvaluationName"/> with pattern
/// <c>projects/{project}/locations/{location}/models/{model}/evaluations/{evaluation}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="modelId">The <c>Model</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="evaluationId">The <c>Evaluation</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="ModelEvaluationName"/> with pattern
/// <c>projects/{project}/locations/{location}/models/{model}/evaluations/{evaluation}</c>.
/// </returns>
public static string Format(string projectId, string locationId, string modelId, string evaluationId) =>
FormatProjectLocationModelEvaluation(projectId, locationId, modelId, evaluationId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="ModelEvaluationName"/> with pattern
/// <c>projects/{project}/locations/{location}/models/{model}/evaluations/{evaluation}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="modelId">The <c>Model</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="evaluationId">The <c>Evaluation</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="ModelEvaluationName"/> with pattern
/// <c>projects/{project}/locations/{location}/models/{model}/evaluations/{evaluation}</c>.
/// </returns>
public static string FormatProjectLocationModelEvaluation(string projectId, string locationId, string modelId, string evaluationId) =>
s_projectLocationModelEvaluation.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(modelId, nameof(modelId)), gax::GaxPreconditions.CheckNotNullOrEmpty(evaluationId, nameof(evaluationId)));
/// <summary>
/// Parses the given resource name string into a new <see cref="ModelEvaluationName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>projects/{project}/locations/{location}/models/{model}/evaluations/{evaluation}</c>
/// </description>
/// </item>
/// </list>
/// </remarks>
/// <param name="modelEvaluationName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="ModelEvaluationName"/> if successful.</returns>
public static ModelEvaluationName Parse(string modelEvaluationName) => Parse(modelEvaluationName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="ModelEvaluationName"/> 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>projects/{project}/locations/{location}/models/{model}/evaluations/{evaluation}</c>
/// </description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="modelEvaluationName">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="ModelEvaluationName"/> if successful.</returns>
public static ModelEvaluationName Parse(string modelEvaluationName, bool allowUnparsed) =>
TryParse(modelEvaluationName, allowUnparsed, out ModelEvaluationName 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="ModelEvaluationName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description>
/// <c>projects/{project}/locations/{location}/models/{model}/evaluations/{evaluation}</c>
/// </description>
/// </item>
/// </list>
/// </remarks>
/// <param name="modelEvaluationName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="ModelEvaluationName"/>, 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 modelEvaluationName, out ModelEvaluationName result) =>
TryParse(modelEvaluationName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="ModelEvaluationName"/> 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>projects/{project}/locations/{location}/models/{model}/evaluations/{evaluation}</c>
/// </description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="modelEvaluationName">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="ModelEvaluationName"/>, 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 modelEvaluationName, bool allowUnparsed, out ModelEvaluationName result)
{
gax::GaxPreconditions.CheckNotNull(modelEvaluationName, nameof(modelEvaluationName));
gax::TemplatedResourceName resourceName;
if (s_projectLocationModelEvaluation.TryParseName(modelEvaluationName, out resourceName))
{
result = FromProjectLocationModelEvaluation(resourceName[0], resourceName[1], resourceName[2], resourceName[3]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(modelEvaluationName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private ModelEvaluationName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string evaluationId = null, string locationId = null, string modelId = null, string projectId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
EvaluationId = evaluationId;
LocationId = locationId;
ModelId = modelId;
ProjectId = projectId;
}
/// <summary>
/// Constructs a new instance of a <see cref="ModelEvaluationName"/> class from the component parts of pattern
/// <c>projects/{project}/locations/{location}/models/{model}/evaluations/{evaluation}</c>
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="modelId">The <c>Model</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="evaluationId">The <c>Evaluation</c> ID. Must not be <c>null</c> or empty.</param>
public ModelEvaluationName(string projectId, string locationId, string modelId, string evaluationId) : this(ResourceNameType.ProjectLocationModelEvaluation, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), modelId: gax::GaxPreconditions.CheckNotNullOrEmpty(modelId, nameof(modelId)), evaluationId: gax::GaxPreconditions.CheckNotNullOrEmpty(evaluationId, nameof(evaluationId)))
{
}
/// <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>Evaluation</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string EvaluationId { get; }
/// <summary>
/// The <c>Location</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string LocationId { get; }
/// <summary>
/// The <c>Model</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string ModelId { get; }
/// <summary>
/// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string ProjectId { 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.ProjectLocationModelEvaluation: return s_projectLocationModelEvaluation.Expand(ProjectId, LocationId, ModelId, EvaluationId);
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 ModelEvaluationName);
/// <inheritdoc/>
public bool Equals(ModelEvaluationName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(ModelEvaluationName a, ModelEvaluationName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(ModelEvaluationName a, ModelEvaluationName b) => !(a == b);
}
public partial class ModelEvaluation
{
/// <summary>
/// <see cref="gcav::ModelEvaluationName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcav::ModelEvaluationName ModelEvaluationName
{
get => string.IsNullOrEmpty(Name) ? null : gcav::ModelEvaluationName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
}
| |
// 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 Test.Utilities;
using Xunit;
namespace Microsoft.NetFramework.Analyzers.UnitTests
{
public partial class DoNotUseInsecureDtdProcessingAnalyzerTests : DiagnosticAnalyzerTestBase
{
private static readonly string s_CA3075XmlTextReaderSetInsecureResolutionMessage = MicrosoftNetFrameworkAnalyzersResources.XmlTextReaderSetInsecureResolutionMessage;
private DiagnosticResult GetCA3075XmlTextReaderSetInsecureResolutionCSharpResultAt(int line, int column)
{
return GetCSharpResultAt(line, column, CA3075RuleId, s_CA3075XmlTextReaderSetInsecureResolutionMessage);
}
private DiagnosticResult GetCA3075XmlTextReaderSetInsecureResolutionBasicResultAt(int line, int column)
{
return GetBasicResultAt(line, column, CA3075RuleId, s_CA3075XmlTextReaderSetInsecureResolutionMessage);
}
[Fact]
public void UseXmlTextReaderNoCtorShouldNotGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Xml;
namespace TestNamespace
{
class TestClass
{
private static void TestMethod(XmlTextReader reader)
{
var count = reader.AttributeCount;
}
}
}"
);
VerifyBasic(@"
Imports System.Xml
Namespace TestNamespace
Class TestClass
Private Shared Sub TestMethod(reader As XmlTextReader)
Dim count = reader.AttributeCount
End Sub
End Class
End Namespace");
}
[Fact]
public void XmlTextReaderNoCtorSetResolverToNullShouldGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Xml;
namespace TestNamespace
{
class TestClass
{
private static void TestMethod(XmlTextReader reader)
{
reader.XmlResolver = new XmlUrlResolver();
}
}
}",
GetCA3075XmlTextReaderSetInsecureResolutionCSharpResultAt(10, 13)
);
VerifyBasic(@"
Imports System.Xml
Namespace TestNamespace
Class TestClass
Private Shared Sub TestMethod(reader As XmlTextReader)
reader.XmlResolver = New XmlUrlResolver()
End Sub
End Class
End Namespace",
GetCA3075XmlTextReaderSetInsecureResolutionBasicResultAt(7, 13)
);
}
[Fact]
public void XmlTextReaderNoCtorSetDtdProcessingToParseShouldGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Xml;
namespace TestNamespace
{
class TestClass
{
private static void TestMethod(XmlTextReader reader)
{
reader.DtdProcessing = DtdProcessing.Parse;
}
}
}",
GetCA3075XmlTextReaderSetInsecureResolutionCSharpResultAt(10, 13)
);
VerifyBasic(@"
Imports System.Xml
Namespace TestNamespace
Class TestClass
Private Shared Sub TestMethod(reader As XmlTextReader)
reader.DtdProcessing = DtdProcessing.Parse
End Sub
End Class
End Namespace",
GetCA3075XmlTextReaderSetInsecureResolutionBasicResultAt(7, 13)
);
}
[Fact]
public void XmlTextReaderNoCtorSetBothToInsecureValuesShouldGenerateDiagnostics()
{
VerifyCSharp(@"
using System.Xml;
namespace TestNamespace
{
class TestClass
{
private static void TestMethod(XmlTextReader reader, XmlUrlResolver resolver)
{
reader.XmlResolver = resolver;
reader.DtdProcessing = DtdProcessing.Parse;
}
}
}",
GetCA3075XmlTextReaderSetInsecureResolutionCSharpResultAt(10, 13),
GetCA3075XmlTextReaderSetInsecureResolutionCSharpResultAt(11, 13)
);
VerifyBasic(@"
Imports System.Xml
Namespace TestNamespace
Class TestClass
Private Shared Sub TestMethod(reader As XmlTextReader, resolver As XmlUrlResolver)
reader.XmlResolver = resolver
reader.DtdProcessing = DtdProcessing.Parse
End Sub
End Class
End Namespace",
GetCA3075XmlTextReaderSetInsecureResolutionBasicResultAt(7, 13),
GetCA3075XmlTextReaderSetInsecureResolutionBasicResultAt(8, 13)
);
}
[Fact]
public void XmlTextReaderNoCtorSetInSecureResolverInTryClauseShouldGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Xml;
namespace TestNamespace
{
class TestClass
{
private static void TestMethod(XmlTextReader reader)
{
try
{
reader.XmlResolver = new XmlUrlResolver();
}
catch { throw; }
}
}
}",
GetCA3075XmlTextReaderSetInsecureResolutionCSharpResultAt(12, 17)
);
VerifyBasic(@"
Imports System.Xml
Namespace TestNamespace
Class TestClass
Private Shared Sub TestMethod(reader As XmlTextReader)
Try
reader.XmlResolver = New XmlUrlResolver()
Catch
Throw
End Try
End Sub
End Class
End Namespace",
GetCA3075XmlTextReaderSetInsecureResolutionBasicResultAt(8, 17)
);
}
[Fact]
public void XmlTextReaderNoCtorSetInSecureResolverInCatchBlockShouldGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Xml;
namespace TestNamespace
{
class TestClass
{
private static void TestMethod(XmlTextReader reader)
{
try { }
catch { reader.XmlResolver = new XmlUrlResolver(); }
finally {}
}
}
}",
GetCA3075XmlTextReaderSetInsecureResolutionCSharpResultAt(11, 21)
);
VerifyBasic(@"
Imports System.Xml
Namespace TestNamespace
Class TestClass
Private Shared Sub TestMethod(reader As XmlTextReader)
Try
Catch
reader.XmlResolver = New XmlUrlResolver()
Finally
End Try
End Sub
End Class
End Namespace",
GetCA3075XmlTextReaderSetInsecureResolutionBasicResultAt(9, 17)
);
}
[Fact]
public void XmlTextReaderNoCtorSetInSecureResolverInFinallyBlockShouldGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Xml;
namespace TestNamespace
{
class TestClass
{
private static void TestMethod(XmlTextReader reader)
{
try { }
catch { throw; }
finally { reader.XmlResolver = new XmlUrlResolver(); }
}
}
}",
GetCA3075XmlTextReaderSetInsecureResolutionCSharpResultAt(12, 23)
);
VerifyBasic(@"
Imports System.Xml
Namespace TestNamespace
Class TestClass
Private Shared Sub TestMethod(reader As XmlTextReader)
Try
Catch
Throw
Finally
reader.XmlResolver = New XmlUrlResolver()
End Try
End Sub
End Class
End Namespace",
GetCA3075XmlTextReaderSetInsecureResolutionBasicResultAt(11, 17)
);
}
[Fact]
public void XmlTextReaderNoCtorSetDtdprocessingToParseInTryClauseShouldGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Xml;
namespace TestNamespace
{
class TestClass
{
private static void TestMethod(XmlTextReader reader)
{
try
{
reader.DtdProcessing = DtdProcessing.Parse;
}
catch { throw; }
}
}
}",
GetCA3075XmlTextReaderSetInsecureResolutionCSharpResultAt(12, 17)
);
VerifyBasic(@"
Imports System.Xml
Namespace TestNamespace
Class TestClass
Private Shared Sub TestMethod(reader As XmlTextReader)
Try
reader.DtdProcessing = DtdProcessing.Parse
Catch
Throw
End Try
End Sub
End Class
End Namespace",
GetCA3075XmlTextReaderSetInsecureResolutionBasicResultAt(8, 17)
);
}
[Fact]
public void XmlTextReaderNoCtorSetDtdprocessingToParseInCatchBlockShouldGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Xml;
namespace TestNamespace
{
class TestClass
{
private static void TestMethod(XmlTextReader reader)
{
try { }
catch { reader.DtdProcessing = DtdProcessing.Parse; }
finally { }
}
}
}",
GetCA3075XmlTextReaderSetInsecureResolutionCSharpResultAt(11, 21)
);
VerifyBasic(@"
Imports System.Xml
Namespace TestNamespace
Class TestClass
Private Shared Sub TestMethod(reader As XmlTextReader)
Try
Catch
reader.DtdProcessing = DtdProcessing.Parse
Finally
End Try
End Sub
End Class
End Namespace",
GetCA3075XmlTextReaderSetInsecureResolutionBasicResultAt(9, 17)
);
}
[Fact]
public void XmlTextReaderNoCtorSetDtdprocessingToParseInFinallyBlockShouldGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Xml;
namespace TestNamespace
{
class TestClass
{
private static void TestMethod(XmlTextReader reader)
{
try { }
catch { throw; }
finally { reader.DtdProcessing = DtdProcessing.Parse; }
}
}
}",
GetCA3075XmlTextReaderSetInsecureResolutionCSharpResultAt(12, 23)
);
VerifyBasic(@"
Imports System.Xml
Namespace TestNamespace
Class TestClass
Private Shared Sub TestMethod(reader As XmlTextReader)
Try
Catch
Throw
Finally
reader.DtdProcessing = DtdProcessing.Parse
End Try
End Sub
End Class
End Namespace",
GetCA3075XmlTextReaderSetInsecureResolutionBasicResultAt(11, 17)
);
}
[Fact(Skip = "https://github.com/dotnet/roslyn-analyzers/issues/1202")]
public void ConstructXmlTextReaderSetInsecureResolverInInitializerShouldGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Xml;
namespace TestNamespace
{
class TestClass
{
private static void TestMethod(string path)
{
XmlTextReader doc = new XmlTextReader(path)
{
XmlResolver = new XmlUrlResolver()
};
}
}
}",
GetCA3075XmlTextReaderSetInsecureResolutionCSharpResultAt(10, 33)
);
VerifyBasic(@"
Imports System.Xml
Namespace TestNamespace
Class TestClass
Private Shared Sub TestMethod(path As String)
Dim doc As New XmlTextReader(path) With { _
.XmlResolver = New XmlUrlResolver() _
}
End Sub
End Class
End Namespace",
GetCA3075XmlTextReaderSetInsecureResolutionBasicResultAt(7, 24)
);
}
[Fact(Skip = "https://github.com/dotnet/roslyn-analyzers/issues/1202")]
public void ConstructXmlTextReaderSetDtdProcessingParseInInitializerShouldGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Xml;
namespace TestNamespace
{
class TestClass
{
private static void TestMethod(string path)
{
XmlTextReader doc = new XmlTextReader(path)
{
DtdProcessing = DtdProcessing.Parse
};
}
}
}",
GetCA3075XmlTextReaderSetInsecureResolutionCSharpResultAt(10, 33)
);
VerifyBasic(@"
Imports System.Xml
Namespace TestNamespace
Class TestClass
Private Shared Sub TestMethod(path As String)
Dim doc As New XmlTextReader(path) With { _
.DtdProcessing = DtdProcessing.Parse _
}
End Sub
End Class
End Namespace",
GetCA3075XmlTextReaderSetInsecureResolutionBasicResultAt(7, 24)
);
}
[Fact(Skip = "https://github.com/dotnet/roslyn-analyzers/issues/1202")]
public void ConstructXmlTextReaderSetBothToInsecureValuesInInitializerShouldGenerateDiagnostic()
{
VerifyCSharp(@"
using System.Xml;
namespace TestNamespace
{
class TestClass
{
private static void TestMethod(string path)
{
XmlTextReader doc = new XmlTextReader(path)
{
DtdProcessing = DtdProcessing.Parse,
XmlResolver = new XmlUrlResolver()
};
}
}
}",
GetCA3075XmlTextReaderSetInsecureResolutionCSharpResultAt(10, 33)
);
VerifyBasic(@"
Imports System.Xml
Namespace TestNamespace
Class TestClass
Private Shared Sub TestMethod(path As String)
Dim doc As New XmlTextReader(path) With { _
.DtdProcessing = DtdProcessing.Parse, _
.XmlResolver = New XmlUrlResolver() _
}
End Sub
End Class
End Namespace",
GetCA3075XmlTextReaderSetInsecureResolutionBasicResultAt(7, 24)
);
}
[Fact(Skip = "https://github.com/dotnet/roslyn-analyzers/issues/1202")]
public void XmlTextReaderDerivedTypeSetInsecureResolverShouldGenerateDiagnostic()
{
VerifyCSharp(@"
using System;
using System.Xml;
namespace TestNamespace
{
class DerivedType : XmlTextReader {}
class TestClass
{
void TestMethod()
{
var c = new DerivedType(){ XmlResolver = new XmlUrlResolver() };
}
}
}",
GetCA3075XmlTextReaderSetInsecureResolutionCSharpResultAt(13, 21)
);
VerifyBasic(@"
Imports System.Xml
Namespace TestNamespace
Class DerivedType
Inherits XmlTextReader
End Class
Class TestClass
Private Sub TestMethod()
Dim c = New DerivedType() With { _
.XmlResolver = New XmlUrlResolver() _
}
End Sub
End Class
End Namespace",
GetCA3075XmlTextReaderSetInsecureResolutionBasicResultAt(11, 21)
);
}
[Fact(Skip = "https://github.com/dotnet/roslyn-analyzers/issues/1202")]
public void XmlTextReaderDerivedTypeSetDtdProcessingParseShouldGenerateDiagnostic()
{
VerifyCSharp(@"
using System;
using System.Xml;
namespace TestNamespace
{
class DerivedType : XmlTextReader {}
class TestClass
{
void TestMethod()
{
var c = new DerivedType(){ DtdProcessing = DtdProcessing.Parse };
}
}
}",
GetCA3075XmlTextReaderSetInsecureResolutionCSharpResultAt(13, 21)
);
VerifyBasic(@"
Imports System.Xml
Namespace TestNamespace
Class DerivedType
Inherits XmlTextReader
End Class
Class TestClass
Private Sub TestMethod()
Dim c = New DerivedType() With { _
.DtdProcessing = DtdProcessing.Parse _
}
End Sub
End Class
End Namespace",
GetCA3075XmlTextReaderSetInsecureResolutionBasicResultAt(11, 21)
);
}
[Fact]
public void XmlTextReaderCreatedAsTempSetSecureSettingsShouldNotGenerateDiagnostics()
{
VerifyCSharp(@"
using System.Xml;
namespace TestNamespace
{
class TestClass
{
public void Method1(string path)
{
Method2(new XmlTextReader(path){ XmlResolver = null, DtdProcessing = DtdProcessing.Prohibit });
}
public void Method2(XmlTextReader reader){}
}
}"
);
VerifyBasic(@"
Imports System.Xml
Namespace TestNamespace
Class TestClass
Public Sub Method1(path As String)
Method2(New XmlTextReader(path) With { _
.XmlResolver = Nothing, _
.DtdProcessing = DtdProcessing.Prohibit _
})
End Sub
Public Sub Method2(reader As XmlTextReader)
End Sub
End Class
End Namespace");
}
[Fact(Skip = "https://github.com/dotnet/roslyn-analyzers/issues/1202")]
public void XmlTextReaderCreatedAsTempSetInsecureResolverShouldGenerateDiagnostics()
{
VerifyCSharp(@"
using System.Xml;
namespace TestNamespace
{
class TestClass
{
public void Method1(string path)
{
Method2(new XmlTextReader(path){ XmlResolver = new XmlUrlResolver(), DtdProcessing = DtdProcessing.Prohibit });
}
public void Method2(XmlTextReader reader){}
}
}",
GetCA3075XmlTextReaderSetInsecureResolutionCSharpResultAt(11, 21)
);
VerifyBasic(@"
Imports System.Xml
Namespace TestNamespace
Class TestClass
Public Sub Method1(path As String)
Method2(New XmlTextReader(path) With { _
.XmlResolver = New XmlUrlResolver(), _
.DtdProcessing = DtdProcessing.Prohibit _
})
End Sub
Public Sub Method2(reader As XmlTextReader)
End Sub
End Class
End Namespace
",
GetCA3075XmlTextReaderSetInsecureResolutionBasicResultAt(8, 21)
);
}
[Fact(Skip = "https://github.com/dotnet/roslyn-analyzers/issues/1202")]
public void XmlTextReaderCreatedAsTempSetDtdProcessingParseShouldGenerateDiagnostics()
{
VerifyCSharp(@"
using System.Xml;
namespace TestNamespace
{
class TestClass
{
public void Method1(string path)
{
Method2(new XmlTextReader(path){ XmlResolver = null, DtdProcessing = DtdProcessing.Parse });
}
public void Method2(XmlTextReader reader){}
}
}",
GetCA3075XmlTextReaderSetInsecureResolutionCSharpResultAt(11, 21)
);
VerifyBasic(@"
Imports System.Xml
Namespace TestNamespace
Class TestClass
Public Sub Method1(path As String)
Method2(New XmlTextReader(path) With { _
.XmlResolver = Nothing, _
.DtdProcessing = DtdProcessing.Parse _
})
End Sub
Public Sub Method2(reader As XmlTextReader)
End Sub
End Class
End Namespace",
GetCA3075XmlTextReaderSetInsecureResolutionBasicResultAt(8, 21)
);
}
}
}
| |
#region License
/*
* All content copyright Terracotta, Inc., unless otherwise indicated. 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.
*
*/
#endregion
using System;
namespace Quartz.Impl.Triggers
{
/// <summary>
/// A concrete <see cref="ITrigger" /> that is used to fire a <see cref="IJobDetail" />
/// at a given moment in time, and optionally repeated at a specified interval.
/// </summary>
/// <seealso cref="ITrigger" />
/// <seealso cref="ICronTrigger" />
/// <author>James House</author>
/// <author>Contributions by Lieven Govaerts of Ebitec Nv, Belgium.</author>
/// <author>Marko Lahma (.NET)</author>
[Serializable]
public class SimpleTriggerImpl : AbstractTrigger, ISimpleTrigger
{
/// <summary>
/// Used to indicate the 'repeat count' of the trigger is indefinite. Or in
/// other words, the trigger should repeat continually until the trigger's
/// ending timestamp.
/// </summary>
public const int RepeatIndefinitely = -1;
private const int YearToGiveupSchedulingAt = 2299;
private DateTimeOffset? nextFireTimeUtc;
private DateTimeOffset? previousFireTimeUtc;
private int repeatCount;
private TimeSpan repeatInterval = TimeSpan.Zero;
private int timesTriggered;
/// <summary>
/// Create a <see cref="SimpleTriggerImpl" /> with no settings.
/// </summary>
public SimpleTriggerImpl()
{
}
/// <summary>
/// Create a <see cref="SimpleTriggerImpl" /> that will occur immediately, and
/// not repeat.
/// </summary>
public SimpleTriggerImpl(string name) : this(name, null)
{
}
/// <summary>
/// Create a <see cref="SimpleTriggerImpl" /> that will occur immediately, and
/// not repeat.
/// </summary>
public SimpleTriggerImpl(string name, string group)
: this(name, group, SystemTime.UtcNow(), null, 0, TimeSpan.Zero)
{
}
/// <summary>
/// Create a <see cref="SimpleTriggerImpl" /> that will occur immediately, and
/// repeat at the given interval the given number of times.
/// </summary>
public SimpleTriggerImpl(string name, int repeatCount, TimeSpan repeatInterval)
: this(name, null, repeatCount, repeatInterval)
{
}
/// <summary>
/// Create a <see cref="SimpleTriggerImpl" /> that will occur immediately, and
/// repeat at the given interval the given number of times.
/// </summary>
public SimpleTriggerImpl(string name, string group, int repeatCount, TimeSpan repeatInterval)
: this(name, group, SystemTime.UtcNow(), null, repeatCount, repeatInterval)
{
}
/// <summary>
/// Create a <see cref="SimpleTriggerImpl" /> that will occur at the given time,
/// and not repeat.
/// </summary>
public SimpleTriggerImpl(string name, DateTimeOffset startTimeUtc)
: this(name, null, startTimeUtc)
{
}
/// <summary>
/// Create a <see cref="SimpleTriggerImpl" /> that will occur at the given time,
/// and not repeat.
/// </summary>
public SimpleTriggerImpl(string name, string group, DateTimeOffset startTimeUtc)
: this(name, group, startTimeUtc, null, 0, TimeSpan.Zero)
{
}
/// <summary>
/// Create a <see cref="SimpleTriggerImpl" /> that will occur at the given time,
/// and repeat at the given interval the given number of times, or until
/// the given end time.
/// </summary>
/// <param name="name">The name.</param>
/// <param name="startTimeUtc">A UTC <see cref="DateTimeOffset" /> set to the time for the <see cref="ITrigger" /> to fire.</param>
/// <param name="endTimeUtc">A UTC <see cref="DateTimeOffset" /> set to the time for the <see cref="ITrigger" />
/// to quit repeat firing.</param>
/// <param name="repeatCount">The number of times for the <see cref="ITrigger" /> to repeat
/// firing, use <see cref="RepeatIndefinitely "/> for unlimited times.</param>
/// <param name="repeatInterval">The time span to pause between the repeat firing.</param>
public SimpleTriggerImpl(string name, DateTimeOffset startTimeUtc,
DateTimeOffset? endTimeUtc, int repeatCount, TimeSpan repeatInterval)
: this(name, null, startTimeUtc, endTimeUtc, repeatCount, repeatInterval)
{
}
/// <summary>
/// Create a <see cref="SimpleTriggerImpl" /> that will occur at the given time,
/// and repeat at the given interval the given number of times, or until
/// the given end time.
/// </summary>
/// <param name="name">The name.</param>
/// <param name="group">The group.</param>
/// <param name="startTimeUtc">A UTC <see cref="DateTimeOffset" /> set to the time for the <see cref="ITrigger" /> to fire.</param>
/// <param name="endTimeUtc">A UTC <see cref="DateTimeOffset" /> set to the time for the <see cref="ITrigger" />
/// to quit repeat firing.</param>
/// <param name="repeatCount">The number of times for the <see cref="ITrigger" /> to repeat
/// firing, use <see cref="RepeatIndefinitely "/> for unlimited times.</param>
/// <param name="repeatInterval">The time span to pause between the repeat firing.</param>
public SimpleTriggerImpl(string name, string group, DateTimeOffset startTimeUtc,
DateTimeOffset? endTimeUtc, int repeatCount, TimeSpan repeatInterval)
: base(name, group)
{
StartTimeUtc = startTimeUtc;
EndTimeUtc = endTimeUtc;
RepeatCount = repeatCount;
RepeatInterval = repeatInterval;
}
/// <summary>
/// Create a <see cref="SimpleTriggerImpl" /> that will occur at the given time,
/// fire the identified <see cref="IJob" /> and repeat at the given
/// interval the given number of times, or until the given end time.
/// </summary>
/// <param name="name">The name.</param>
/// <param name="group">The group.</param>
/// <param name="jobName">Name of the job.</param>
/// <param name="jobGroup">The job group.</param>
/// <param name="startTimeUtc">A <see cref="DateTimeOffset" /> set to the time for the <see cref="ITrigger" />
/// to fire.</param>
/// <param name="endTimeUtc">A <see cref="DateTimeOffset" /> set to the time for the <see cref="ITrigger" />
/// to quit repeat firing.</param>
/// <param name="repeatCount">The number of times for the <see cref="ITrigger" /> to repeat
/// firing, use RepeatIndefinitely for unlimited times.</param>
/// <param name="repeatInterval">The time span to pause between the repeat firing.</param>
public SimpleTriggerImpl(string name, string group, string jobName, string jobGroup, DateTimeOffset startTimeUtc,
DateTimeOffset? endTimeUtc,
int repeatCount, TimeSpan repeatInterval)
: base(name, group, jobName, jobGroup)
{
StartTimeUtc = startTimeUtc;
EndTimeUtc = endTimeUtc;
RepeatCount = repeatCount;
RepeatInterval = repeatInterval;
}
/// <summary>
/// Get or set the number of times the <see cref="SimpleTriggerImpl" /> should
/// repeat, after which it will be automatically deleted.
/// </summary>
/// <seealso cref="RepeatIndefinitely" />
public int RepeatCount
{
get { return repeatCount; }
set
{
if (value < 0 && value != RepeatIndefinitely)
{
throw new ArgumentException("Repeat count must be >= 0, use the constant RepeatIndefinitely for infinite.");
}
repeatCount = value;
}
}
/// <summary>
/// Get or set the time interval at which the <see cref="ISimpleTrigger" /> should repeat.
/// </summary>
public TimeSpan RepeatInterval
{
get { return repeatInterval; }
set
{
if (value < TimeSpan.Zero)
{
throw new ArgumentException("Repeat interval must be >= 0");
}
repeatInterval = value;
}
}
/// <summary>
/// Get or set the number of times the <see cref="ISimpleTrigger" /> has already
/// fired.
/// </summary>
public virtual int TimesTriggered
{
get { return timesTriggered; }
set { timesTriggered = value; }
}
public override IScheduleBuilder GetScheduleBuilder()
{
SimpleScheduleBuilder sb = SimpleScheduleBuilder.Create()
.WithInterval(RepeatInterval)
.WithRepeatCount(RepeatCount);
switch (MisfireInstruction)
{
case Quartz.MisfireInstruction.SimpleTrigger.FireNow: sb.WithMisfireHandlingInstructionFireNow();
break;
case Quartz.MisfireInstruction.SimpleTrigger.RescheduleNextWithExistingCount: sb.WithMisfireHandlingInstructionNextWithExistingCount();
break;
case Quartz.MisfireInstruction.SimpleTrigger.RescheduleNextWithRemainingCount : sb.WithMisfireHandlingInstructionNextWithRemainingCount();
break;
case Quartz.MisfireInstruction.SimpleTrigger.RescheduleNowWithExistingRepeatCount : sb.WithMisfireHandlingInstructionNowWithExistingCount();
break;
case Quartz.MisfireInstruction.SimpleTrigger.RescheduleNowWithRemainingRepeatCount: sb.WithMisfireHandlingInstructionNowWithRemainingCount();
break;
}
return sb;
}
/// <summary>
/// Returns the final UTC time at which the <see cref="ISimpleTrigger" /> will
/// fire, if repeatCount is RepeatIndefinitely, null will be returned.
/// <para>
/// Note that the return time may be in the past.
/// </para>
/// </summary>
public override DateTimeOffset? FinalFireTimeUtc
{
get
{
if (repeatCount == 0)
{
return StartTimeUtc;
}
if (repeatCount == RepeatIndefinitely && !EndTimeUtc.HasValue)
{
return null;
}
if (repeatCount == RepeatIndefinitely && !EndTimeUtc.HasValue)
{
return null;
}
else if (repeatCount == RepeatIndefinitely)
{
return GetFireTimeBefore(EndTimeUtc);
}
DateTimeOffset lastTrigger = StartTimeUtc.AddMilliseconds(repeatCount * repeatInterval.TotalMilliseconds);
if (!EndTimeUtc.HasValue || lastTrigger < EndTimeUtc.Value)
{
return lastTrigger;
}
else
{
return GetFireTimeBefore(EndTimeUtc);
}
}
}
/// <summary>
/// Tells whether this Trigger instance can handle events
/// in millisecond precision.
/// </summary>
/// <value></value>
public override bool HasMillisecondPrecision
{
get { return true; }
}
/// <summary>
/// Validates the misfire instruction.
/// </summary>
/// <param name="misfireInstruction">The misfire instruction.</param>
/// <returns></returns>
protected override bool ValidateMisfireInstruction(int misfireInstruction)
{
if (misfireInstruction < Quartz.MisfireInstruction.IgnoreMisfirePolicy)
{
return false;
}
if (misfireInstruction > Quartz.MisfireInstruction.SimpleTrigger.RescheduleNextWithExistingCount)
{
return false;
}
return true;
}
/// <summary>
/// Updates the <see cref="ISimpleTrigger" />'s state based on the
/// MisfireInstruction value that was selected when the <see cref="ISimpleTrigger" />
/// was created.
/// </summary>
/// <remarks>
/// If MisfireSmartPolicyEnabled is set to true,
/// then the following scheme will be used: <br />
/// <ul>
/// <li>If the Repeat Count is 0, then the instruction will
/// be interpreted as <see cref="MisfireInstruction.SimpleTrigger.FireNow" />.</li>
/// <li>If the Repeat Count is <see cref="RepeatIndefinitely" />, then
/// the instruction will be interpreted as <see cref="MisfireInstruction.SimpleTrigger.RescheduleNowWithRemainingRepeatCount" />.
/// <b>WARNING:</b> using MisfirePolicy.SimpleTrigger.RescheduleNowWithRemainingRepeatCount
/// with a trigger that has a non-null end-time may cause the trigger to
/// never fire again if the end-time arrived during the misfire time span.
/// </li>
/// <li>If the Repeat Count is > 0, then the instruction
/// will be interpreted as <see cref="MisfireInstruction.SimpleTrigger.RescheduleNowWithExistingRepeatCount" />.
/// </li>
/// </ul>
/// </remarks>
public override void UpdateAfterMisfire(ICalendar cal)
{
int instr = MisfireInstruction;
if (instr == Quartz.MisfireInstruction.SmartPolicy)
{
if (RepeatCount == 0)
{
instr = Quartz.MisfireInstruction.SimpleTrigger.FireNow;
}
else if (RepeatCount == RepeatIndefinitely)
{
instr = Quartz.MisfireInstruction.SimpleTrigger.RescheduleNextWithRemainingCount;
}
else
{
instr = Quartz.MisfireInstruction.SimpleTrigger.RescheduleNowWithExistingRepeatCount;
}
}
else if (instr == Quartz.MisfireInstruction.SimpleTrigger.FireNow && RepeatCount != 0)
{
instr = Quartz.MisfireInstruction.SimpleTrigger.RescheduleNowWithRemainingRepeatCount;
}
if (instr == Quartz.MisfireInstruction.SimpleTrigger.FireNow)
{
nextFireTimeUtc = SystemTime.UtcNow();
}
else if (instr == Quartz.MisfireInstruction.SimpleTrigger.RescheduleNextWithExistingCount)
{
DateTimeOffset? newFireTime = GetFireTimeAfter(SystemTime.UtcNow());
while (newFireTime.HasValue && cal != null && !cal.IsTimeIncluded(newFireTime.Value))
{
newFireTime = GetFireTimeAfter(newFireTime);
if (!newFireTime.HasValue)
{
break;
}
//avoid infinite loop
if (newFireTime.Value.Year > YearToGiveupSchedulingAt)
{
newFireTime = null;
}
}
nextFireTimeUtc = newFireTime;
}
else if (instr == Quartz.MisfireInstruction.SimpleTrigger.RescheduleNextWithRemainingCount)
{
DateTimeOffset? newFireTime = GetFireTimeAfter(SystemTime.UtcNow());
while (newFireTime.HasValue && cal != null && !cal.IsTimeIncluded(newFireTime.Value))
{
newFireTime = GetFireTimeAfter(newFireTime);
if (!newFireTime.HasValue)
{
break;
}
//avoid infinite loop
if (newFireTime.Value.Year > YearToGiveupSchedulingAt)
{
newFireTime = null;
}
}
if (newFireTime.HasValue)
{
int timesMissed = ComputeNumTimesFiredBetween(nextFireTimeUtc, newFireTime);
TimesTriggered = TimesTriggered + timesMissed;
}
nextFireTimeUtc = newFireTime;
}
else if (instr == Quartz.MisfireInstruction.SimpleTrigger.RescheduleNowWithExistingRepeatCount)
{
DateTimeOffset newFireTime = SystemTime.UtcNow();
if (repeatCount != 0 && repeatCount != RepeatIndefinitely)
{
RepeatCount = RepeatCount - TimesTriggered;
TimesTriggered = 0;
}
if (EndTimeUtc.HasValue && EndTimeUtc.Value < newFireTime)
{
nextFireTimeUtc = null; // We are past the end time
}
else
{
StartTimeUtc = newFireTime;
nextFireTimeUtc = newFireTime;
}
}
else if (instr == Quartz.MisfireInstruction.SimpleTrigger.RescheduleNowWithRemainingRepeatCount)
{
DateTimeOffset newFireTime = SystemTime.UtcNow();
int timesMissed = ComputeNumTimesFiredBetween(nextFireTimeUtc, newFireTime);
if (repeatCount != 0 && repeatCount != RepeatIndefinitely)
{
int remainingCount = RepeatCount - (TimesTriggered + timesMissed);
if (remainingCount <= 0)
{
remainingCount = 0;
}
RepeatCount = remainingCount;
TimesTriggered = 0;
}
if (EndTimeUtc.HasValue && EndTimeUtc.Value < newFireTime)
{
nextFireTimeUtc = null; // We are past the end time
}
else
{
StartTimeUtc = newFireTime;
nextFireTimeUtc = newFireTime;
}
}
}
/// <summary>
/// Called when the <see cref="IScheduler" /> has decided to 'fire'
/// the trigger (Execute the associated <see cref="IJob" />), in order to
/// give the <see cref="ITrigger" /> a chance to update itself for its next
/// triggering (if any).
/// </summary>
/// <seealso cref="JobExecutionException" />
public override void Triggered(ICalendar cal)
{
timesTriggered++;
previousFireTimeUtc = nextFireTimeUtc;
nextFireTimeUtc = GetFireTimeAfter(nextFireTimeUtc);
while (nextFireTimeUtc.HasValue && cal != null && !cal.IsTimeIncluded(nextFireTimeUtc.Value))
{
nextFireTimeUtc = GetFireTimeAfter(nextFireTimeUtc);
if (!nextFireTimeUtc.HasValue)
{
break;
}
//avoid infinite loop
if (nextFireTimeUtc.Value.Year > YearToGiveupSchedulingAt)
{
nextFireTimeUtc = null;
}
}
}
/// <summary>
/// Updates the instance with new calendar.
/// </summary>
/// <param name="calendar">The calendar.</param>
/// <param name="misfireThreshold">The misfire threshold.</param>
public override void UpdateWithNewCalendar(ICalendar calendar, TimeSpan misfireThreshold)
{
nextFireTimeUtc = GetFireTimeAfter(previousFireTimeUtc);
if (nextFireTimeUtc == null || calendar == null)
{
return;
}
DateTimeOffset now = SystemTime.UtcNow();
while (nextFireTimeUtc.HasValue && !calendar.IsTimeIncluded(nextFireTimeUtc.Value))
{
nextFireTimeUtc = GetFireTimeAfter(nextFireTimeUtc);
if (!nextFireTimeUtc.HasValue)
{
break;
}
//avoid infinite loop
if (nextFireTimeUtc.Value.Year > YearToGiveupSchedulingAt)
{
nextFireTimeUtc = null;
}
if (nextFireTimeUtc != null && nextFireTimeUtc.Value < now)
{
TimeSpan diff = now - nextFireTimeUtc.Value;
if (diff >= misfireThreshold)
{
nextFireTimeUtc = GetFireTimeAfter(nextFireTimeUtc);
}
}
}
}
/// <summary>
/// Called by the scheduler at the time a <see cref="ITrigger" /> is first
/// added to the scheduler, in order to have the <see cref="ITrigger" />
/// compute its first fire time, based on any associated calendar.
/// <para>
/// After this method has been called, <see cref="GetNextFireTimeUtc" />
/// should return a valid answer.
/// </para>
/// </summary>
/// <returns>
/// The first time at which the <see cref="ITrigger" /> will be fired
/// by the scheduler, which is also the same value <see cref="GetNextFireTimeUtc" />
/// will return (until after the first firing of the <see cref="ITrigger" />).
/// </returns>
public override DateTimeOffset? ComputeFirstFireTimeUtc(ICalendar cal)
{
nextFireTimeUtc = StartTimeUtc;
while (cal != null && !cal.IsTimeIncluded(nextFireTimeUtc.Value))
{
nextFireTimeUtc = GetFireTimeAfter(nextFireTimeUtc);
if (!nextFireTimeUtc.HasValue)
{
break;
}
//avoid infinite loop
if (nextFireTimeUtc.Value.Year > YearToGiveupSchedulingAt)
{
return null;
}
}
return nextFireTimeUtc;
}
/// <summary>
/// Returns the next time at which the <see cref="ISimpleTrigger" /> will
/// fire. If the trigger will not fire again, <see langword="null" /> will be
/// returned. The value returned is not guaranteed to be valid until after
/// the <see cref="ITrigger" /> has been added to the scheduler.
/// </summary>
public override DateTimeOffset? GetNextFireTimeUtc()
{
return nextFireTimeUtc;
}
public override void SetNextFireTimeUtc(DateTimeOffset? nextFireTime)
{
nextFireTimeUtc = nextFireTime;
}
public override void SetPreviousFireTimeUtc(DateTimeOffset? previousFireTime)
{
previousFireTimeUtc = previousFireTime;
}
/// <summary>
/// Returns the previous time at which the <see cref="ISimpleTrigger" /> fired.
/// If the trigger has not yet fired, <see langword="null" /> will be
/// returned.
/// </summary>
public override DateTimeOffset? GetPreviousFireTimeUtc()
{
return previousFireTimeUtc;
}
/// <summary>
/// Returns the next UTC time at which the <see cref="ISimpleTrigger" /> will
/// fire, after the given UTC time. If the trigger will not fire after the given
/// time, <see langword="null" /> will be returned.
/// </summary>
public override DateTimeOffset? GetFireTimeAfter(DateTimeOffset? afterTimeUtc)
{
if ((timesTriggered > repeatCount) && (repeatCount != RepeatIndefinitely))
{
return null;
}
if (!afterTimeUtc.HasValue)
{
afterTimeUtc = SystemTime.UtcNow();
}
if (repeatCount == 0 && afterTimeUtc.Value.CompareTo(StartTimeUtc) >= 0)
{
return null;
}
DateTimeOffset startMillis = StartTimeUtc;
DateTimeOffset afterMillis = afterTimeUtc.Value;
DateTimeOffset endMillis = !EndTimeUtc.HasValue ? DateTimeOffset.MaxValue : EndTimeUtc.Value;
if (endMillis <= afterMillis)
{
return null;
}
if (afterMillis < startMillis)
{
return startMillis;
}
long numberOfTimesExecuted = (long) (((long) (afterMillis - startMillis).TotalMilliseconds / repeatInterval.TotalMilliseconds) + 1);
if ((numberOfTimesExecuted > repeatCount) &&
(repeatCount != RepeatIndefinitely))
{
return null;
}
DateTimeOffset time = startMillis.AddMilliseconds(numberOfTimesExecuted * repeatInterval.TotalMilliseconds);
if (endMillis <= time)
{
return null;
}
return time;
}
/// <summary>
/// Returns the last UTC time at which the <see cref="ISimpleTrigger" /> will
/// fire, before the given time. If the trigger will not fire before the
/// given time, <see langword="null" /> will be returned.
/// </summary>
public virtual DateTimeOffset? GetFireTimeBefore(DateTimeOffset? endUtc)
{
if (endUtc.Value < StartTimeUtc)
{
return null;
}
int numFires = ComputeNumTimesFiredBetween(StartTimeUtc, endUtc);
return StartTimeUtc.AddMilliseconds(numFires*repeatInterval.TotalMilliseconds);
}
/// <summary>
/// Computes the number of times fired between the two UTC date times.
/// </summary>
/// <param name="startTimeUtc">The UTC start date and time.</param>
/// <param name="endTimeUtc">The UTC end date and time.</param>
/// <returns></returns>
public virtual int ComputeNumTimesFiredBetween(DateTimeOffset? startTimeUtc, DateTimeOffset? endTimeUtc)
{
long time = (long) (endTimeUtc.Value - startTimeUtc.Value).TotalMilliseconds;
return (int) (time/repeatInterval.TotalMilliseconds);
}
/// <summary>
/// Determines whether or not the <see cref="ISimpleTrigger" /> will occur
/// again.
/// </summary>
public override bool GetMayFireAgain()
{
return GetNextFireTimeUtc().HasValue;
}
/// <summary>
/// Validates whether the properties of the <see cref="IJobDetail" /> are
/// valid for submission into a <see cref="IScheduler" />.
/// </summary>
public override void Validate()
{
base.Validate();
if (repeatCount != 0 && repeatInterval.TotalMilliseconds < 1)
{
throw new SchedulerException("Repeat Interval cannot be zero.");
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Reflection;
using Xunit;
namespace System.Linq.Expressions.Tests
{
public class PreIncrementAssignTests : IncDecAssignTests
{
[Theory]
[MemberData(nameof(Int16sAndIncrements))]
[MemberData(nameof(NullableInt16sAndIncrements))]
[MemberData(nameof(UInt16sAndIncrements))]
[MemberData(nameof(NullableUInt16sAndIncrements))]
[MemberData(nameof(Int32sAndIncrements))]
[MemberData(nameof(NullableInt32sAndIncrements))]
[MemberData(nameof(UInt32sAndIncrements))]
[MemberData(nameof(NullableUInt32sAndIncrements))]
[MemberData(nameof(Int64sAndIncrements))]
[MemberData(nameof(NullableInt64sAndIncrements))]
[MemberData(nameof(UInt64sAndIncrements))]
[MemberData(nameof(NullableUInt64sAndIncrements))]
[MemberData(nameof(DecimalsAndIncrements))]
[MemberData(nameof(NullableDecimalsAndIncrements))]
[MemberData(nameof(SinglesAndIncrements))]
[MemberData(nameof(NullableSinglesAndIncrements))]
[MemberData(nameof(DoublesAndIncrements))]
[MemberData(nameof(NullableDoublesAndIncrements))]
public void ReturnsCorrectValues(Type type, object value, object result)
{
ParameterExpression variable = Expression.Variable(type);
BlockExpression block = Expression.Block(
new[] { variable },
Expression.Assign(variable, Expression.Constant(value, type)),
Expression.PreIncrementAssign(variable)
);
Assert.True(Expression.Lambda<Func<bool>>(Expression.Equal(Expression.Constant(result, type), block)).Compile()());
}
[Theory]
[MemberData(nameof(Int16sAndIncrements))]
[MemberData(nameof(NullableInt16sAndIncrements))]
[MemberData(nameof(UInt16sAndIncrements))]
[MemberData(nameof(NullableUInt16sAndIncrements))]
[MemberData(nameof(Int32sAndIncrements))]
[MemberData(nameof(NullableInt32sAndIncrements))]
[MemberData(nameof(UInt32sAndIncrements))]
[MemberData(nameof(NullableUInt32sAndIncrements))]
[MemberData(nameof(Int64sAndIncrements))]
[MemberData(nameof(NullableInt64sAndIncrements))]
[MemberData(nameof(UInt64sAndIncrements))]
[MemberData(nameof(NullableUInt64sAndIncrements))]
[MemberData(nameof(DecimalsAndIncrements))]
[MemberData(nameof(NullableDecimalsAndIncrements))]
[MemberData(nameof(SinglesAndIncrements))]
[MemberData(nameof(NullableSinglesAndIncrements))]
[MemberData(nameof(DoublesAndIncrements))]
[MemberData(nameof(NullableDoublesAndIncrements))]
public void AssignsCorrectValues(Type type, object value, object result)
{
ParameterExpression variable = Expression.Variable(type);
LabelTarget target = Expression.Label(type);
BlockExpression block = Expression.Block(
new[] { variable },
Expression.Assign(variable, Expression.Constant(value, type)),
Expression.PreIncrementAssign(variable),
Expression.Return(target, variable),
Expression.Label(target, Expression.Default(type))
);
Assert.True(Expression.Lambda<Func<bool>>(Expression.Equal(Expression.Constant(result, type), block)).Compile()());
}
[Fact]
public void SingleNanToNan()
{
TestPropertyClass<float> instance = new TestPropertyClass<float>();
instance.TestInstance = float.NaN;
Assert.True(float.IsNaN(
Expression.Lambda<Func<float>>(
Expression.PreIncrementAssign(
Expression.Property(
Expression.Constant(instance),
typeof(TestPropertyClass<float>),
"TestInstance"
)
)
).Compile()()
));
Assert.True(float.IsNaN(instance.TestInstance));
}
[Fact]
public void DoubleNanToNan()
{
TestPropertyClass<double> instance = new TestPropertyClass<double>();
instance.TestInstance = double.NaN;
Assert.True(double.IsNaN(
Expression.Lambda<Func<double>>(
Expression.PreIncrementAssign(
Expression.Property(
Expression.Constant(instance),
typeof(TestPropertyClass<double>),
"TestInstance"
)
)
).Compile()()
));
Assert.True(double.IsNaN(instance.TestInstance));
}
[Theory]
[MemberData(nameof(IncrementOverflowingValues))]
public void OverflowingValuesThrow(object value)
{
ParameterExpression variable = Expression.Variable(value.GetType());
Action overflow = Expression.Lambda<Action>(
Expression.Block(
typeof(void),
new[] { variable },
Expression.Assign(variable, Expression.Constant(value)),
Expression.PreIncrementAssign(variable)
)
).Compile();
Assert.Throws<OverflowException>(overflow);
}
[Theory]
[MemberData(nameof(UnincrementableAndUndecrementableTypes))]
public void InvalidOperandType(Type type)
{
ParameterExpression variable = Expression.Variable(type);
Assert.Throws<InvalidOperationException>(() => Expression.PreIncrementAssign(variable));
}
[Fact]
public void MethodCorrectResult()
{
ParameterExpression variable = Expression.Variable(typeof(string));
BlockExpression block = Expression.Block(
new[] { variable },
Expression.Assign(variable, Expression.Constant("hello")),
Expression.PreIncrementAssign(variable, typeof(IncDecAssignTests).GetTypeInfo().GetDeclaredMethod("SillyMethod"))
);
Assert.Equal("Eggplant", Expression.Lambda<Func<string>>(block).Compile()());
}
[Fact]
public void MethodCorrectAssign()
{
ParameterExpression variable = Expression.Variable(typeof(string));
LabelTarget target = Expression.Label(typeof(string));
BlockExpression block = Expression.Block(
new[] { variable },
Expression.Assign(variable, Expression.Constant("hello")),
Expression.PreIncrementAssign(variable, typeof(IncDecAssignTests).GetTypeInfo().GetDeclaredMethod("SillyMethod")),
Expression.Return(target, variable),
Expression.Label(target, Expression.Default(typeof(string)))
);
Assert.Equal("Eggplant", Expression.Lambda<Func<string>>(block).Compile()());
}
[Fact]
public void IncorrectMethodType()
{
Expression variable = Expression.Variable(typeof(int));
MethodInfo method = typeof(IncDecAssignTests).GetTypeInfo().GetDeclaredMethod("SillyMethod");
Assert.Throws<InvalidOperationException>(() => Expression.PreIncrementAssign(variable, method));
}
[Fact]
public void IncorrectMethodParameterCount()
{
Expression variable = Expression.Variable(typeof(string));
MethodInfo method = typeof(object).GetTypeInfo().GetDeclaredMethod("ReferenceEquals");
Assert.Throws<ArgumentException>(() => Expression.PreIncrementAssign(variable, method));
}
[Fact]
public void IncorrectMethodReturnType()
{
Expression variable = Expression.Variable(typeof(int));
MethodInfo method = typeof(IncDecAssignTests).GetTypeInfo().GetDeclaredMethod("GetString");
Assert.Throws<ArgumentException>(() => Expression.PreIncrementAssign(variable, method));
}
[Fact]
public void StaticMemberAccessCorrect()
{
TestPropertyClass<uint>.TestStatic = 2U;
Assert.Equal(
3U,
Expression.Lambda<Func<uint>>(
Expression.PreIncrementAssign(
Expression.Property(null, typeof(TestPropertyClass<uint>), "TestStatic")
)
).Compile()()
);
Assert.Equal(3U, TestPropertyClass<uint>.TestStatic);
}
[Fact]
public void InstanceMemberAccessCorrect()
{
TestPropertyClass<int> instance = new TestPropertyClass<int>();
instance.TestInstance = 2;
Assert.Equal(
3,
Expression.Lambda<Func<int>>(
Expression.PreIncrementAssign(
Expression.Property(
Expression.Constant(instance),
typeof(TestPropertyClass<int>),
"TestInstance"
)
)
).Compile()()
);
Assert.Equal(3, instance.TestInstance);
}
[Fact]
public void ArrayAccessCorrect()
{
int[] array = new int[1];
array[0] = 2;
Assert.Equal(
3,
Expression.Lambda<Func<int>>(
Expression.PreIncrementAssign(
Expression.ArrayAccess(Expression.Constant(array), Expression.Constant(0))
)
).Compile()()
);
Assert.Equal(3, array[0]);
}
[Fact]
public void CanReduce()
{
ParameterExpression variable = Expression.Variable(typeof(int));
UnaryExpression op = Expression.PreIncrementAssign(variable);
Assert.True(op.CanReduce);
Assert.NotSame(op, op.ReduceAndCheck());
}
[Fact]
public void NullOperand()
{
Assert.Throws<ArgumentNullException>("expression", () => Expression.PreIncrementAssign(null));
}
[Fact]
public void UnwritableOperand()
{
Assert.Throws<ArgumentException>("expression", () => Expression.PreIncrementAssign(Expression.Constant(1)));
}
[Fact]
public void UnreadableOperand()
{
Expression value = Expression.Property(null, typeof(Unreadable<int>), "WriteOnly");
Assert.Throws<ArgumentException>("expression", () => Expression.PreIncrementAssign(value));
}
[Fact]
public void UpdateSameOperandSameNode()
{
UnaryExpression op = Expression.PreIncrementAssign(Expression.Variable(typeof(int)));
Assert.Same(op, op.Update(op.Operand));
}
[Fact]
public void UpdateDiffOperandDiffNode()
{
UnaryExpression op = Expression.PreIncrementAssign(Expression.Variable(typeof(int)));
Assert.NotSame(op, op.Update(Expression.Variable(typeof(int))));
}
}
}
| |
/* ====================================================================
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 TestCases.XWPF.UserModel
{
using NPOI.OpenXmlFormats.Wordprocessing;
using NPOI.Util;
using NPOI.XWPF.Model;
using NPOI.XWPF.UserModel;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.IO;
/**
* Tests for XWPF Run
*/
[TestFixture]
public class TestXWPFRun
{
public CT_R ctRun;
public XWPFParagraph p;
[SetUp]
public void SetUp()
{
XWPFDocument doc = new XWPFDocument();
p = doc.CreateParagraph();
this.ctRun = new CT_R();
}
[Test]
public void TestSetGetText()
{
ctRun.AddNewT().Value = ("TEST STRING");
ctRun.AddNewT().Value = ("TEST2 STRING");
ctRun.AddNewT().Value = ("TEST3 STRING");
Assert.AreEqual(3, ctRun.SizeOfTArray());
XWPFRun run = new XWPFRun(ctRun, p);
Assert.AreEqual("TEST2 STRING", run.GetText(1));
run.SetText("NEW STRING", 0);
Assert.AreEqual("NEW STRING", run.GetText(0));
//Run.Text=("xxx",14);
//Assert.Fail("Position wrong");
}
/*
* bug 59208
* Purpose: test all valid boolean-like values
* exercise isCTOnOff(CTOnOff) through all valid permutations
*/
[Ignore("stub testCTOnOff")]
public void TestCTOnOff()
{
//CTRPr rpr = ctRun.addNewRPr();
//CTOnOff bold = rpr.addNewB();
//XWPFRun run = new XWPFRun(ctRun, p);
//// True values: "true", "1", "on"
//bold.setVal(STOnOff.TRUE);
//assertEquals(true, run.isBold());
//bold.setVal(STOnOff.X_1);
//assertEquals(true, run.isBold());
//bold.setVal(STOnOff.ON);
//assertEquals(true, run.isBold());
//// False values: "false", "0", "off"
//bold.setVal(STOnOff.FALSE);
//assertEquals(false, run.isBold());
//bold.setVal(STOnOff.X_0);
//assertEquals(false, run.isBold());
//bold.setVal(STOnOff.OFF);
//assertEquals(false, run.isBold());
}
[Test]
public void TestSetGetBold()
{
CT_RPr rpr = ctRun.AddNewRPr();
rpr.AddNewB().val = true;
XWPFRun run = new XWPFRun(ctRun, p);
Assert.AreEqual(true, run.IsBold);
run.IsBold = (false);
// Implementation detail: POI natively prefers <w:b w:val="false"/>,
// but should correctly read val="0" and val="off"
Assert.AreEqual(false, run.IsBold);
Assert.AreEqual(false, rpr.b.val);
}
[Test]
public void TestSetGetItalic()
{
CT_RPr rpr = ctRun.AddNewRPr();
rpr.AddNewI().val = true;
XWPFRun run = new XWPFRun(ctRun, p);
Assert.AreEqual(true, run.IsItalic);
run.IsItalic = false;
Assert.AreEqual(false, rpr.i.val);
}
[Test]
public void TestSetGetStrike()
{
CT_RPr rpr = ctRun.AddNewRPr();
rpr.AddNewStrike().val = true;
XWPFRun run = new XWPFRun(ctRun, p);
Assert.AreEqual(true, run.IsStrike);
run.SetStrike(false);
Assert.AreEqual(false, rpr.strike.val);
}
[Test]
public void TestSetGetUnderline()
{
CT_RPr rpr = ctRun.AddNewRPr();
rpr.AddNewU().val = (ST_Underline.dash);
XWPFRun run = new XWPFRun(ctRun, p);
Assert.AreEqual(UnderlinePatterns.Dash, run.Underline);
run.SetUnderline(UnderlinePatterns.None);
Assert.AreEqual(ST_Underline.none, rpr.u.val);
}
[Test]
public void TestSetGetVAlign()
{
CT_RPr rpr = ctRun.AddNewRPr();
rpr.AddNewVertAlign().val = (ST_VerticalAlignRun.subscript);
XWPFRun run = new XWPFRun(ctRun, p);
Assert.AreEqual(VerticalAlign.SUBSCRIPT, run.Subscript);
run.Subscript = (VerticalAlign.BASELINE);
Assert.AreEqual(ST_VerticalAlignRun.baseline, rpr.vertAlign.val);
}
[Test]
public void TestSetGetFontFamily()
{
CT_RPr rpr = ctRun.AddNewRPr();
rpr.AddNewRFonts().ascii = ("Times New Roman");
XWPFRun run = new XWPFRun(ctRun, p);
Assert.AreEqual("Times New Roman", run.FontFamily);
run.FontFamily = ("Verdana");
Assert.AreEqual("Verdana", rpr.rFonts.ascii);
}
[Test]
public void TestSetGetFontSize()
{
CT_RPr rpr = ctRun.AddNewRPr();
rpr.AddNewSz().val = 14;
XWPFRun run = new XWPFRun(ctRun, p);
Assert.AreEqual(7.0, run.FontSize);
run.FontSize = 24;
Assert.AreEqual(48, (int)rpr.sz.val);
run.FontSize = 24.5;
Assert.AreEqual(24.5, run.FontSize);
}
[Test]
public void TestSetGetTextForegroundBackground()
{
CT_RPr rpr = ctRun.AddNewRPr();
rpr.AddNewPosition().val = "4000";
XWPFRun run = new XWPFRun(ctRun, p);
Assert.AreEqual(4000, run.TextPosition);
run.TextPosition = (2400);
Assert.AreEqual(2400, int.Parse(rpr.position.val));
}
[Test]
public void TestSetGetColor()
{
XWPFRun run = new XWPFRun(ctRun, p);
run.SetColor("0F0F0F");
String clr = run.GetColor();
Assert.AreEqual("0F0F0F", clr);
}
[Test]
public void TestAddCarriageReturn()
{
ctRun.AddNewT().Value = ("TEST STRING");
ctRun.AddNewCr();
ctRun.AddNewT().Value = ("TEST2 STRING");
ctRun.AddNewCr();
ctRun.AddNewT().Value = ("TEST3 STRING");
Assert.AreEqual(2, ctRun.SizeOfCrArray());
XWPFRun run = new XWPFRun(new CT_R(), p);
run.AppendText("T1");
run.AddCarriageReturn();
run.AddCarriageReturn();
run.AppendText("T2");
run.AddCarriageReturn();
Assert.AreEqual(3, run.GetCTR().GetCrList().Count);
Assert.AreEqual("T1\n\nT2\n", run.ToString());
}
[Test]
public void TestAddTabsAndLineBreaks()
{
ctRun.AddNewT().Value = "TEST STRING";
ctRun.AddNewCr();
ctRun.AddNewT().Value = "TEST2 STRING";
ctRun.AddNewTab();
ctRun.AddNewT().Value = "TEST3 STRING";
Assert.AreEqual(1, ctRun.SizeOfCrArray());
Assert.AreEqual(1, ctRun.SizeOfTabArray());
XWPFRun run = new XWPFRun(new CT_R(), p);
run.AppendText("T1");
run.AddCarriageReturn();
run.AppendText("T2");
run.AddTab();
run.AppendText("T3");
Assert.AreEqual(1, run.GetCTR().GetCrList().Count);
Assert.AreEqual(1, run.GetCTR().GetTabList().Count);
Assert.AreEqual("T1\nT2\tT3", run.ToString());
}
[Test]
public void TestAddPageBreak()
{
ctRun.AddNewT().Value = "TEST STRING";
ctRun.AddNewBr();
ctRun.AddNewT().Value = "TEST2 STRING";
CT_Br breac = ctRun.AddNewBr();
breac.clear = ST_BrClear.left;
ctRun.AddNewT().Value = "TEST3 STRING";
Assert.AreEqual(2, ctRun.SizeOfBrArray());
XWPFRun run = new XWPFRun(new CT_R(), p);
run.SetText("TEXT1");
run.AddBreak();
run.SetText("TEXT2");
run.AddBreak(BreakType.TEXTWRAPPING);
Assert.AreEqual(2, run.GetCTR().SizeOfBrArray());
}
/**
* Test that on an existing document, we do the
* right thing with it
* @throws IOException
*/
[Test]
public void TestExisting()
{
XWPFDocument doc = XWPFTestDataSamples.OpenSampleDocument("TestDocument.docx");
XWPFParagraph p;
XWPFRun run;
// First paragraph is simple
p = doc.GetParagraphArray(0);
Assert.AreEqual("This is a test document.", p.Text);
Assert.AreEqual(2, p.Runs.Count);
run = p.Runs[0];
Assert.AreEqual("This is a test document", run.ToString());
Assert.AreEqual(false, run.IsBold);
Assert.AreEqual(false, run.IsItalic);
Assert.AreEqual(false, run.IsStrike);
Assert.AreEqual(null, run.GetCTR().rPr);
run = p.Runs[1];
Assert.AreEqual(".", run.ToString());
Assert.AreEqual(false, run.IsBold);
Assert.AreEqual(false, run.IsItalic);
Assert.AreEqual(false, run.IsStrike);
Assert.AreEqual(null, run.GetCTR().rPr);
// Next paragraph is all in one style, but a different one
p = doc.GetParagraphArray(1);
Assert.AreEqual("This bit is in bold and italic", p.Text);
Assert.AreEqual(1, p.Runs.Count);
run = p.Runs[0];
Assert.AreEqual("This bit is in bold and italic", run.ToString());
Assert.AreEqual(true, run.IsBold);
Assert.AreEqual(true, run.IsItalic);
Assert.AreEqual(false, run.IsStrike);
Assert.AreEqual(true, run.GetCTR().rPr.IsSetB());
Assert.AreEqual(false, run.GetCTR().rPr.b.IsSetVal());
// Back to normal
p = doc.GetParagraphArray(2);
Assert.AreEqual("Back to normal", p.Text);
Assert.AreEqual(1, p.Runs.Count);
run = p.Runs[(0)];
Assert.AreEqual("Back to normal", run.ToString());
Assert.AreEqual(false, run.IsBold);
Assert.AreEqual(false, run.IsItalic);
Assert.AreEqual(false, run.IsStrike);
Assert.AreEqual(null, run.GetCTR().rPr);
// Different styles in one paragraph
p = doc.GetParagraphArray(3);
Assert.AreEqual("This contains BOLD, ITALIC and BOTH, as well as RED and YELLOW text.", p.Text);
Assert.AreEqual(11, p.Runs.Count);
run = p.Runs[(0)];
Assert.AreEqual("This contains ", run.ToString());
Assert.AreEqual(false, run.IsBold);
Assert.AreEqual(false, run.IsItalic);
Assert.AreEqual(false, run.IsStrike);
Assert.AreEqual(null, run.GetCTR().rPr);
run = p.Runs[(1)];
Assert.AreEqual("BOLD", run.ToString());
Assert.AreEqual(true, run.IsBold);
Assert.AreEqual(false, run.IsItalic);
Assert.AreEqual(false, run.IsStrike);
run = p.Runs[2];
Assert.AreEqual(", ", run.ToString());
Assert.AreEqual(false, run.IsBold);
Assert.AreEqual(false, run.IsItalic);
Assert.AreEqual(false, run.IsStrike);
Assert.AreEqual(null, run.GetCTR().rPr);
run = p.Runs[(3)];
Assert.AreEqual("ITALIC", run.ToString());
Assert.AreEqual(false, run.IsBold);
Assert.AreEqual(true, run.IsItalic);
Assert.AreEqual(false, run.IsStrike);
run = p.Runs[(4)];
Assert.AreEqual(" and ", run.ToString());
Assert.AreEqual(false, run.IsBold);
Assert.AreEqual(false, run.IsItalic);
Assert.AreEqual(false, run.IsStrike);
Assert.AreEqual(null, run.GetCTR().rPr);
run = p.Runs[(5)];
Assert.AreEqual("BOTH", run.ToString());
Assert.AreEqual(true, run.IsBold);
Assert.AreEqual(true, run.IsItalic);
Assert.AreEqual(false, run.IsStrike);
run = p.Runs[(6)];
Assert.AreEqual(", as well as ", run.ToString());
Assert.AreEqual(false, run.IsBold);
Assert.AreEqual(false, run.IsItalic);
Assert.AreEqual(false, run.IsStrike);
Assert.AreEqual(null, run.GetCTR().rPr);
run = p.Runs[(7)];
Assert.AreEqual("RED", run.ToString());
Assert.AreEqual(false, run.IsBold);
Assert.AreEqual(false, run.IsItalic);
Assert.AreEqual(false, run.IsStrike);
run = p.Runs[(8)];
Assert.AreEqual(" and ", run.ToString());
Assert.AreEqual(false, run.IsBold);
Assert.AreEqual(false, run.IsItalic);
Assert.AreEqual(false, run.IsStrike);
Assert.AreEqual(null, run.GetCTR().rPr);
run = p.Runs[(9)];
Assert.AreEqual("YELLOW", run.ToString());
Assert.AreEqual(false, run.IsBold);
Assert.AreEqual(false, run.IsItalic);
Assert.AreEqual(false, run.IsStrike);
run = p.Runs[(10)];
Assert.AreEqual(" text.", run.ToString());
Assert.AreEqual(false, run.IsBold);
Assert.AreEqual(false, run.IsItalic);
Assert.AreEqual(false, run.IsStrike);
Assert.AreEqual(null, run.GetCTR().rPr);
}
[Test]
public void TestPictureInHeader()
{
XWPFDocument sampleDoc = XWPFTestDataSamples.OpenSampleDocument("headerPic.docx");
XWPFHeaderFooterPolicy policy = sampleDoc.GetHeaderFooterPolicy();
XWPFHeader header = policy.GetDefaultHeader();
int count = 0;
foreach (XWPFParagraph p in header.Paragraphs)
{
foreach (XWPFRun r in p.Runs)
{
List<XWPFPicture> pictures = r.GetEmbeddedPictures();
foreach (XWPFPicture pic in pictures)
{
Assert.IsNotNull(pic.GetPictureData());
Assert.AreEqual("DOZOR", pic.GetDescription());
}
count += pictures.Count;
}
}
Assert.AreEqual(1, count);
}
[Test]
public void testSetGetHighlight()
{
XWPFRun run = p.CreateRun();
Assert.AreEqual(false, run.IsHighlighted);
// TODO Do this using XWPFRun methods
run.GetCTR().AddNewRPr().AddNewHighlight().val = (ST_HighlightColor.none);
Assert.AreEqual(false, run.IsHighlighted);
run.GetCTR().rPr.highlight.val = (ST_HighlightColor.cyan);
Assert.AreEqual(true, run.IsHighlighted);
run.GetCTR().rPr.highlight.val = (ST_HighlightColor.none);
Assert.AreEqual(false, run.IsHighlighted);
}
[Test]
public void TestAddPicture()
{
XWPFDocument doc = XWPFTestDataSamples.OpenSampleDocument("TestDocument.docx");
XWPFParagraph p = doc.GetParagraphArray(2);
XWPFRun r = p.Runs[0];
Assert.AreEqual(0, doc.AllPictures.Count);
Assert.AreEqual(0, r.GetEmbeddedPictures().Count);
r.AddPicture(new MemoryStream(new byte[0]), (int)PictureType.JPEG, "test.jpg", 21, 32);
Assert.AreEqual(1, doc.AllPictures.Count);
Assert.AreEqual(1, r.GetEmbeddedPictures().Count);
}
/**
* Bugzilla #52288 - setting the font family on the
* run mustn't NPE
*/
[Test]
public void TestSetFontFamily_52288()
{
XWPFDocument doc = XWPFTestDataSamples.OpenSampleDocument("52288.docx");
IEnumerator<XWPFParagraph> paragraphs = doc.Paragraphs.GetEnumerator();
while (paragraphs.MoveNext())
{
XWPFParagraph paragraph = paragraphs.Current;
foreach (XWPFRun run in paragraph.Runs)
{
if (run != null)
{
String text = run.GetText(0);
if (text != null)
{
run.FontFamily = ("Times New Roman");
}
}
}
}
}
[Test]
public void TestBug55476()
{
byte[] image = XWPFTestDataSamples.GetImage("abstract1.jpg");
XWPFDocument document = new XWPFDocument();
document.CreateParagraph().CreateRun().AddPicture(
new MemoryStream(image), (int)PictureType.JPEG, "test.jpg", Units.ToEMU(300), Units.ToEMU(100));
XWPFDocument docBack = XWPFTestDataSamples.WriteOutAndReadBack(document);
List<XWPFPicture> pictures = docBack.GetParagraphArray(0).Runs[0].GetEmbeddedPictures();
Assert.AreEqual(1, pictures.Count);
docBack.Close();
/*OutputStream stream = new FileOutputStream("c:\\temp\\55476.docx");
try {
document.write(stream);
} finally {
stream.close();
}*/
document.Close();
}
[Test]
public void TestBug58922()
{
XWPFDocument document = new XWPFDocument();
XWPFRun run = document.CreateParagraph().CreateRun();
Assert.AreEqual(-1, run.FontSize);
run.FontSize = 10;
Assert.AreEqual(10, run.FontSize);
run.FontSize = short.MaxValue - 1;
Assert.AreEqual(short.MaxValue - 1, run.FontSize);
run.FontSize = short.MaxValue;
Assert.AreEqual(short.MaxValue, run.FontSize);
run.FontSize = short.MaxValue + 1;
Assert.AreEqual(short.MaxValue + 1, run.FontSize);
run.FontSize = int.MaxValue - 1;
Assert.AreEqual(int.MaxValue - 1, run.FontSize);
run.FontSize = int.MaxValue;
Assert.AreEqual(int.MaxValue, run.FontSize);
run.FontSize = -1;
Assert.AreEqual(-1, run.FontSize);
Assert.AreEqual(-1, run.TextPosition);
run.TextPosition = 10;
Assert.AreEqual(10, run.TextPosition);
run.TextPosition = short.MaxValue - 1;
Assert.AreEqual(short.MaxValue - 1, run.TextPosition);
run.TextPosition = short.MaxValue;
Assert.AreEqual(short.MaxValue, run.TextPosition);
run.TextPosition = short.MaxValue + 1;
Assert.AreEqual(short.MaxValue + 1, run.TextPosition);
run.TextPosition = short.MaxValue + 1;
Assert.AreEqual(short.MaxValue + 1, run.TextPosition);
run.TextPosition = int.MaxValue - 1;
Assert.AreEqual(int.MaxValue - 1, run.TextPosition);
run.TextPosition = int.MaxValue;
Assert.AreEqual(int.MaxValue, run.TextPosition);
run.TextPosition = -1;
Assert.AreEqual(-1, run.TextPosition);
}
[Test]
public void TestWhitespace()
{
String[]
text = new String[] {
" The quick brown fox",
"\t\tjumped over the lazy dog"
};
MemoryStream bos = new MemoryStream();
XWPFDocument doc = new XWPFDocument();
foreach (String s in text) {
XWPFParagraph p1 = doc.CreateParagraph();
XWPFRun r1 = p1.CreateRun();
r1.SetText(s);
}
doc.Write(bos);
MemoryStream bis = new MemoryStream(bos.ToArray());
var doc2 = new XWPFDocument(bis);
var paragraphs = doc2.Paragraphs;
Assert.AreEqual(2, paragraphs.Count);
for (int i = 0; i < text.Length; i++)
{
XWPFParagraph p1 = paragraphs[i];
String expected = text[i];
Assert.AreEqual(expected, p1.Text);
CT_P ctp = p1.GetCTP();
CT_R ctr = ctp.GetRArray(0);
CT_Text ctText = ctr.GetTArray(0);
// if text has leading whitespace then expect xml-fragment to have xml:space="preserve" set
// <xml-fragment xml:space="preserve" xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
bool isWhitespace = Character.isWhitespace(expected[0]);
Assert.AreEqual(isWhitespace, ctText.space == "preserve");
}
}
[Test]
public void TestSetStyleId()
{
XWPFDocument document = XWPFTestDataSamples.OpenSampleDocument("SampleDoc.docx");
XWPFRun run = document.CreateParagraph().CreateRun();
String styleId = "bolditalic";
run.SetStyle(styleId);
String candStyleId = run.GetCTR().rPr.rStyle.val;
Assert.IsNotNull(candStyleId, "Expected to find a run style ID");
Assert.AreEqual(styleId, candStyleId);
Assert.AreEqual(styleId, run.GetStyle());
document.Close();
}
}
}
| |
// Python Tools for Visual Studio
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABILITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using Microsoft.PythonTools.Infrastructure;
using Microsoft.PythonTools.Interpreter;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TestUtilities;
namespace PythonToolsTests {
[TestClass]
public class WorkspaceInterpreterFactoryTests {
[ClassInitialize]
public static void DoDeployment(TestContext context) {
AssertListener.Initialize();
}
[TestMethod, Priority(UnitTestPriority.P1)]
public void WatchWorkspaceFolderChanged() {
var workspaceFolder1 = TestData.GetTempPath();
Directory.CreateDirectory(workspaceFolder1);
File.WriteAllText(Path.Combine(workspaceFolder1, "app1.py"), string.Empty);
var workspaceFolder2 = TestData.GetTempPath();
Directory.CreateDirectory(workspaceFolder2);
File.WriteAllText(Path.Combine(workspaceFolder2, "app2.py"), string.Empty);
var workspace1 = new WorkspaceTestHelper.MockWorkspace(workspaceFolder1);
var workspace2 = new WorkspaceTestHelper.MockWorkspace(workspaceFolder2);
var workspaceContext1 = new WorkspaceTestHelper.MockWorkspaceContext(workspace1);
var workspaceContext2 = new WorkspaceTestHelper.MockWorkspaceContext(workspace2);
var workspaceContextProvider = new WorkspaceTestHelper.MockWorkspaceContextProvider(workspaceContext1);
using (var factoryProvider = new WorkspaceInterpreterFactoryProvider(workspaceContextProvider)) {
// Load a different workspace
Action triggerDiscovery = () => {
workspaceContextProvider.SimulateChangeWorkspace(workspaceContext2);
};
TestTriggerDiscovery(workspaceContext1, triggerDiscovery, workspaceContextProvider, true);
}
}
[TestMethod, Priority(UnitTestPriority.P1)]
public void WatchWorkspaceSettingsChanged() {
var workspaceFolder = TestData.GetTempPath();
Directory.CreateDirectory(workspaceFolder);
File.WriteAllText(Path.Combine(workspaceFolder, "app.py"), string.Empty);
var workspace = new WorkspaceTestHelper.MockWorkspace(workspaceFolder);
var workspaceContext = new WorkspaceTestHelper.MockWorkspaceContext(workspace);
// Modify settings
Action triggerDiscovery = () => {
workspaceContext.SimulateChangeInterpreterSetting("Global|PythonCore|3.7");
};
TestTriggerDiscovery(workspaceContext, triggerDiscovery, null, true);
}
[TestMethod, Priority(UnitTestPriority.P0)]
public void WatchWorkspaceVirtualEnvCreated() {
var python = PythonPaths.LatestVersion;
var workspaceFolder = TestData.GetTempPath("workspace");
Directory.CreateDirectory(workspaceFolder);
File.WriteAllText(Path.Combine(workspaceFolder, "app.py"), string.Empty);
string envFolder = Path.Combine(workspaceFolder, "env");
var workspace = new WorkspaceTestHelper.MockWorkspace(workspaceFolder);
var workspaceContext = new WorkspaceTestHelper.MockWorkspaceContext(workspace);
// Create virtual env inside the workspace folder (one level from root)
var configs = TestTriggerDiscovery(
workspaceContext,
() => python.CreateVirtualEnv(VirtualEnvName.First, Path.Combine(workspaceFolder, "env"))
).ToArray();
Assert.AreEqual(1, configs.Length);
Assert.IsTrue(PathUtils.IsSamePath(
Path.Combine(envFolder, "scripts", "python.exe"),
configs[0].InterpreterPath
));
Assert.AreEqual("Workspace|Workspace|env", configs[0].Id);
}
[TestMethod, Priority(UnitTestPriority.P0)]
public void DetectLocalEnvOutsideWorkspace() {
var python = PythonPaths.LatestVersion;
var tempFolder = TestData.GetTempPath();
var workspaceFolder = Path.Combine(tempFolder, "workspace");
var envFolder = Path.Combine(tempFolder, "outside");
Directory.CreateDirectory(workspaceFolder);
File.WriteAllText(Path.Combine(workspaceFolder, "app.py"), string.Empty);
// Create virtual env outside the workspace folder
using (var p = ProcessOutput.RunHiddenAndCapture(python.InterpreterPath, "-m", "venv", envFolder)) {
Console.WriteLine(p.Arguments);
p.Wait();
Console.WriteLine(string.Join(Environment.NewLine, p.StandardOutputLines.Concat(p.StandardErrorLines)));
Assert.AreEqual(0, p.ExitCode);
}
// Normally a local virtual environment outside the workspace
// wouldn't be detected, but it is when it's referenced from
// the workspace python settings.
var workspace = new WorkspaceTestHelper.MockWorkspace(workspaceFolder);
var workspaceContext = new WorkspaceTestHelper.MockWorkspaceContext(workspace, @"..\outside\scripts\python.exe");
var workspaceContextProvider = new WorkspaceTestHelper.MockWorkspaceContextProvider(workspaceContext);
using (var factoryProvider = new WorkspaceInterpreterFactoryProvider(workspaceContextProvider)) {
workspaceContextProvider.SimulateChangeWorkspace(workspaceContext);
var configs = factoryProvider.GetInterpreterConfigurations().ToArray();
Assert.AreEqual(1, configs.Length);
Assert.IsTrue(PathUtils.IsSamePath(
Path.Combine(envFolder, "scripts", "python.exe"),
configs[0].InterpreterPath
));
Assert.AreEqual("Workspace|Workspace|outside", configs[0].Id);
}
}
[TestMethod, Priority(UnitTestPriority.P1_FAILING)]
public void WatchWorkspaceVirtualEnvRenamed() {
const string ENV_NAME = "env";
var workspaceContext = CreateEnvAndGetWorkspaceService(ENV_NAME);
string envPath = Path.Combine(workspaceContext.Location, ENV_NAME);
string renamedEnvPath = Path.Combine(workspaceContext.Location, string.Concat(ENV_NAME, "1"));
var configs = TestTriggerDiscovery(workspaceContext, () => Directory.Move(envPath, renamedEnvPath)).ToArray();
Assert.AreEqual(1, configs.Length);
Assert.IsTrue(PathUtils.IsSamePath(Path.Combine(renamedEnvPath, "scripts", "python.exe"), configs[0].InterpreterPath));
Assert.AreEqual("Workspace|Workspace|env1", configs[0].Id);
}
[TestMethod, Priority(UnitTestPriority.P1)]
public void WatchWorkspaceVirtualEnvDeleted() {
const string ENV_NAME = "env";
var workspaceContext = CreateEnvAndGetWorkspaceService(ENV_NAME);
string envPath = Path.Combine(workspaceContext.Location, ENV_NAME);
var configs = TestTriggerDiscovery(workspaceContext, () => Directory.Delete(envPath, true)).ToArray();
Assert.AreEqual(0, configs.Length);
}
private static IEnumerable<InterpreterConfiguration> TestTriggerDiscovery(
IPythonWorkspaceContext workspaceContext,
Action triggerDiscovery,
IPythonWorkspaceContextProvider workspaceContextProvider = null,
bool useDiscoveryStartedEvent = false
) {
workspaceContextProvider = workspaceContextProvider
?? new WorkspaceTestHelper.MockWorkspaceContextProvider(workspaceContext);
using (var provider = new WorkspaceInterpreterFactoryProvider(workspaceContextProvider))
using (var evt = new AutoResetEvent(false)) {
// This initializes the provider, discovers the initial set
// of factories and starts watching the filesystem.
provider.GetInterpreterFactories();
if (useDiscoveryStartedEvent) {
provider.DiscoveryStarted += (sender, e) => {
evt.Set();
};
} else {
provider.InterpreterFactoriesChanged += (sender, e) => {
evt.Set();
};
}
triggerDiscovery();
Assert.IsTrue(evt.WaitOne(5000), "Failed to trigger discovery.");
return provider.GetInterpreterConfigurations();
}
}
private WorkspaceTestHelper.MockWorkspaceContext CreateEnvAndGetWorkspaceService(string envName) {
var python = PythonPaths.LatestVersion;
var workspacePath = TestData.GetTempPath();
Directory.CreateDirectory(workspacePath);
File.WriteAllText(Path.Combine(workspacePath, "app.py"), string.Empty);
python.CreateVirtualEnv(VirtualEnvName.First, Path.Combine(workspacePath, envName));
return new WorkspaceTestHelper.MockWorkspaceContext(new WorkspaceTestHelper.MockWorkspace(workspacePath));
}
}
}
| |
// Copyright (c) 2017 Trevor Redfern
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
namespace SilverNeedle.Serialization
{
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using SilverNeedle.Characters;
using SilverNeedle.Dice;
using SilverNeedle.Utility;
public static class ObjectStoreSerializer
{
public const string SERIALIZED_TYPE_KEY = "serialized-type";
public static T Deserialize<T>(this IObjectStore data, T result)
{
var typeInfo = typeof(T);
var properties = typeInfo.GetProperties();
foreach(var prop in properties)
{
var attribute = prop.GetCustomAttribute<ObjectStoreAttribute>();
if(attribute == null)
continue;
var propType = prop.PropertyType.Name.ToLower();
object propertyValue = null;
object defaultValue = attribute.DefaultValue;
bool useDefault = defaultValue != null;
string keyName = attribute.PropertyName;
switch(propType)
{
case "single":
if(attribute.Optional)
if(useDefault)
propertyValue = data.GetFloatOptional(keyName, (float)defaultValue);
else
propertyValue = data.GetFloatOptional(keyName);
else
propertyValue = data.GetFloat(keyName);
break;
case "int32":
if(attribute.Optional)
if(useDefault)
propertyValue = data.GetIntegerOptional(keyName, (int)defaultValue);
else
propertyValue = data.GetIntegerOptional(keyName);
else
propertyValue = data.GetInteger(keyName);
break;
case "string":
if(attribute.Optional)
if(useDefault)
propertyValue = data.GetStringOptional(keyName, defaultValue.ToString());
else
propertyValue = data.GetStringOptional(keyName);
else
propertyValue = data.GetString(keyName);
break;
case "string[]":
if(attribute.Optional)
propertyValue = data.GetListOptional(keyName);
else
propertyValue = data.GetList(keyName);
break;
case "boolean":
if(attribute.Optional)
if(useDefault)
propertyValue = data.GetBoolOptional(keyName, (bool)defaultValue);
else
propertyValue = data.GetBoolOptional(keyName);
else
propertyValue = data.GetBool(keyName);
break;
case "movementtype":
//TODO: Cannot just keep adding types here, but let's see how common it is first
propertyValue = data.GetEnum<MovementType>(keyName);
break;
case "cup":
propertyValue = DiceStrings.ParseDice(data.GetString(keyName));
break;
case "spelltype":
propertyValue = data.GetEnum<Spells.SpellType>(keyName);
break;
case "object[]":
var objectList = data.GetObjectList(keyName);
var newList = new List<object>();
foreach(var o in objectList)
{
var instance = o.GetString(SERIALIZED_TYPE_KEY).Instantiate<object>(o);
newList.Add(instance);
}
propertyValue = newList.ToArray();
break;
default:
ShortLog.DebugFormat("Attempting to deserialize: {0}", propType);
if(prop.PropertyType.IsEnum)
{
propertyValue = System.Enum.Parse(prop.PropertyType, data.GetString(keyName), true);
}
else
{
propertyValue = DeserializeObject(data, keyName, attribute.Optional, prop.PropertyType);
}
break;
}
prop.SetValue(result, propertyValue);
}
return result;
}
private static object DeserializeObject(IObjectStore configuration, string keyName, bool optional, System.Type objectType)
{
if(optional)
{
var objInfo = configuration.GetObjectOptional(keyName);
if(objInfo != null)
return objectType.Instantiate<object>(objInfo);
}
else
{
return objectType.Instantiate<object>(configuration.GetObject(keyName));
}
return null;
}
public static void Serialize(this IObjectStore storage, object val)
{
var yamlStore = storage as YamlObjectStore;
if(yamlStore == null)
throw new System.NotImplementedException("Only YamlStore supported for serializing");
var typeInfo = val.GetType();
var properties = typeInfo.GetProperties();
yamlStore.SetValue(SERIALIZED_TYPE_KEY, typeInfo.FullName);
foreach(var prop in properties)
{
var attribute = prop.GetCustomAttribute<ObjectStoreAttribute>();
if(attribute == null)
continue;
var propType = prop.PropertyType.Name.ToLower();
var propertyValue = prop.GetValue(val);
if(propertyValue == null)
continue;
switch(propType)
{
case "boolean":
yamlStore.SetValue(attribute.PropertyName, (bool)propertyValue);
break;
case "int32":
yamlStore.SetValue(attribute.PropertyName, (int)propertyValue);
break;
case "single":
yamlStore.SetValue(attribute.PropertyName, (float)propertyValue);
break;
case "string":
yamlStore.SetValue(attribute.PropertyName, propertyValue.ToString());
break;
case "string[]":
yamlStore.SetValue(attribute.PropertyName, (string[])propertyValue);
break;
case "object[]":
var objectArray = (object[])propertyValue;
var store = new List<YamlObjectStore>();
foreach(var o in objectArray)
{
var s = new YamlObjectStore();
s.Serialize(o);
store.Add(s);
}
yamlStore.SetValue(attribute.PropertyName, store);
break;
case "cup":
default:
if(prop.PropertyType.IsEnum)
{
yamlStore.SetValue(attribute.PropertyName, propertyValue.ToString());
}
else
{
ShortLog.DebugFormat("Attempting to serialize: {0} {1}", attribute.PropertyName, prop.PropertyType);
var newStore = new YamlObjectStore();
newStore.Serialize(propertyValue);
yamlStore.SetValue(attribute.PropertyName, newStore);
}
break;
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using FlatRedBall;
using FlatRedBall.Input;
using FlatRedBall.AI.Pathfinding;
using FlatRedBall.Graphics.Animation;
using FlatRedBall.Graphics.Particle;
using FlatRedBall.Math.Geometry;
using FlatRedBall.Math.Splines;
using BitmapFont = FlatRedBall.Graphics.BitmapFont;
using Cursor = FlatRedBall.Gui.Cursor;
using GuiManager = FlatRedBall.Gui.GuiManager;
using DemoProject.DataTypes;
#if FRB_XNA || SILVERLIGHT
using Keys = Microsoft.Xna.Framework.Input.Keys;
using Vector3 = Microsoft.Xna.Framework.Vector3;
using Texture2D = Microsoft.Xna.Framework.Graphics.Texture2D;
using FlatRedBall.Screens;
#elif FRB_MDX
using Keys = Microsoft.DirectX.DirectInput.Key;
#endif
namespace DemoProject.Entities
{
public enum MovementType
{
Ground,
Air,
AfterDoubleJump
}
public partial class PlatformerCharacterBase
{
#region Fields
bool mIsOnGround = false;
bool mHitHead = false;
bool mHasDoubleJumped = false;
double mTimeJumpPushed = double.NegativeInfinity;
MovementValues mValuesJumpedWith;
MovementValues mCurrentMovement;
MovementType mMovementType;
#endregion
#region Properties
public Xbox360GamePad GamePad
{
get;
set;
}
double CurrentTime
{
get
{
if (ScreenManager.CurrentScreen != null)
{
return ScreenManager.CurrentScreen.PauseAdjustedCurrentTime;
}
else
{
return TimeManager.CurrentTime;
}
}
}
MovementValues CurrentMovement
{
get
{
return mCurrentMovement;
}
}
protected virtual bool JumpDown
{
get
{
if (GamePad != null && GamePad.IsConnected)
{
return GamePad.ButtonDown(Xbox360GamePad.Button.A);
}
else
{
return InputManager.Keyboard.KeyDown(Keys.Space);
}
}
}
protected virtual bool JumpPushed
{
get
{
if (GamePad != null && GamePad.IsConnected)
{
return GamePad.ButtonPushed(Xbox360GamePad.Button.A);
}
else
{
return InputManager.Keyboard.KeyPushed(Keys.Space);
}
}
}
protected virtual float HorizontalRatio
{
get
{
if (GamePad != null && GamePad.IsConnected)
{
return GamePad.LeftStick.Position.X;
}
else
{
if (InputManager.Keyboard.KeyDown(Keys.Left))
{
return -1;
}
else if (InputManager.Keyboard.KeyDown(Keys.Right))
{
return 1;
}
else
{
return 0;
}
}
}
}
public bool IsOnGround
{
get
{
return mIsOnGround;
}
}
public MovementType CurrentMovementType
{
get
{
return mMovementType;
}
set
{
mMovementType = value;
switch (mMovementType)
{
case MovementType.Ground:
mCurrentMovement = GroundMovement;
break;
case MovementType.Air:
mCurrentMovement = AirMovement;
break;
case MovementType.AfterDoubleJump:
mCurrentMovement = AfterDoubleJump;
break;
}
}
}
#endregion
private void CustomInitialize()
{
CurrentMovementType = MovementType.Ground;
YAcceleration = this.CurrentMovement.Gravity;
}
private void CustomActivity()
{
InputActivity();
}
private void InputActivity()
{
HorizontalMovementActivity();
JumpVelocity();
}
private void JumpVelocity()
{
if (JumpPushed &&
CurrentMovement.JumpVelocity > 0 &&
(mIsOnGround || AfterDoubleJump == null || (AfterDoubleJump != null && mHasDoubleJumped == false))
)
{
mTimeJumpPushed = CurrentTime;
this.YVelocity = CurrentMovement.JumpVelocity;
mValuesJumpedWith = CurrentMovement;
if (CurrentMovementType == MovementType.Air)
{
mHasDoubleJumped = true ;
}
}
double secondsSincePush = CurrentTime - mTimeJumpPushed;
if (mValuesJumpedWith != null &&
secondsSincePush < mValuesJumpedWith.JumpApplyLength &&
(mValuesJumpedWith.JumpApplyByButtonHold == false || JumpDown)
)
{
this.YVelocity = mValuesJumpedWith.JumpVelocity;
}
if (mValuesJumpedWith != null && mValuesJumpedWith.JumpApplyByButtonHold &&
(!JumpDown || mHitHead)
)
{
mValuesJumpedWith = null;
}
this.YVelocity = Math.Max(-CurrentMovement.MaxFallSpeed, this.YVelocity);
}
private void HorizontalMovementActivity()
{
if (this.CurrentMovement.AccelerationTimeX <= 0)
{
this.XVelocity = HorizontalRatio * CurrentMovement.MaxSpeedX;
}
else
{
float acceleration = CurrentMovement.MaxSpeedX / CurrentMovement.AccelerationTimeX;
float sign = Math.Sign(HorizontalRatio);
float magnitude = Math.Abs(HorizontalRatio);
if(sign == 0)
{
sign = -Math.Sign(XVelocity);
magnitude = 1;
}
if (XVelocity == 0 || sign == Math.Sign(XVelocity))
{
this.XAcceleration = sign * magnitude * CurrentMovement.MaxSpeedX / CurrentMovement.AccelerationTimeX;
}
else
{
float accelerationValue = magnitude * CurrentMovement.MaxSpeedX / CurrentMovement.DecelerationTimeX;
if (Math.Abs(XVelocity) < accelerationValue * TimeManager.SecondDifference)
{
this.XAcceleration = 0;
this.XVelocity = 0;
}
else
{
// slowing down
this.XAcceleration = sign * accelerationValue;
}
}
XVelocity = Math.Min(XVelocity, CurrentMovement.MaxSpeedX);
XVelocity = Math.Max(XVelocity, -CurrentMovement.MaxSpeedX);
}
}
private void CustomDestroy()
{
}
private static void CustomLoadStaticContent(string contentManagerName)
{
}
public void CollideAgainst(ShapeCollection shapeCollection)
{
CollideAgainst(shapeCollection, false);
}
public void CollideAgainst(ShapeCollection shapeCollection, bool isCloudCollision)
{
CollideAgainst(() => shapeCollection.CollideAgainstBounceWithoutSnag(this.Collision, 0), isCloudCollision);
}
public void CollideAgainst(Func<bool> collisionFunction, bool isCloudCollision)
{
Vector3 positionBeforeCollision = this.Position;
Vector3 velocityBeforeCollision = this.Velocity;
float lastY = this.Y;
mIsOnGround = false;
mHitHead = false;
if(isCloudCollision == false || velocityBeforeCollision.Y < 0)
{
if (collisionFunction())
{
// make sure that we've been moved up, and that we're falling
bool shouldApplyCollision = true;
if (isCloudCollision)
{
if (this.Y <= positionBeforeCollision.Y)
{
shouldApplyCollision = false;
}
}
if (shouldApplyCollision)
{
if (this.Y > lastY)
{
mIsOnGround = true;
}
if (this.Y < lastY)
{
mHitHead = true;
}
}
else
{
Position = positionBeforeCollision;
Velocity = velocityBeforeCollision;
}
}
}
}
public void DetermineMovementValues()
{
if (mIsOnGround)
{
mHasDoubleJumped = false;
if (CurrentMovementType == MovementType.Air ||
CurrentMovementType == MovementType.AfterDoubleJump)
{
CurrentMovementType = MovementType.Ground;
}
}
else
{
if (CurrentMovementType == MovementType.Ground)
{
CurrentMovementType = MovementType.Air;
}
}
if (CurrentMovementType == MovementType.Air && mHasDoubleJumped)
{
CurrentMovementType = MovementType.AfterDoubleJump;
}
}
}
}
| |
#region References
/// @cond hide_from_doxygen
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using MiniJSON.Teak;
#if UNITY_EDITOR
using System.IO;
using System.Net;
using System.Text;
#endif
/// @endcond
#endregion
/// <summary>
/// Interface for manipulating notifications from Teak.
/// </summary>
public partial class TeakNotification {
public bool Incentivized { get; set; }
public string ScheduleName { get; set; }
public ulong ScheduleId { get; set; }
public string CreativeName { get; set; }
public ulong CreativeId { get; set; }
public string ChannelName { get; set; }
public string RewardId { get; set; }
public string DeepLink { get; set; }
public TeakNotification(Dictionary<string, object> json) {
this.ScheduleName = json["teakScheduleName"] as string;
this.CreativeName = json["teakCreativeName"] as string;
this.ChannelName = json.ContainsKey("teakChannelName") ? json["teakChannelName"] as string : null;
this.RewardId = json.ContainsKey("teakRewardId") ? json["teakRewardId"] as string : null;
this.DeepLink = json.ContainsKey("teakDeepLink") ? json["teakDeepLink"] as string : null;
this.Incentivized = (this.RewardId != null);
ulong temp = 0;
if (json.ContainsKey("teakScheduleId")) {
UInt64.TryParse(json["teakScheduleId"] as string, out temp);
this.ScheduleId = temp;
}
if (json.ContainsKey("teakCreativeId")) {
temp = 0;
UInt64.TryParse(json["teakCreativeId"] as string, out temp);
this.CreativeId = temp;
}
}
public override string ToString() {
string formatString = "{{ Incentivized = '{0}', ScheduleName = '{1}', ScheduleId = '{2}', CreativeName = '{3}', CreativeId = '{4}', ChannelName = '{5}', RewardId = '{6}', DeepLink = '{7}' }}";
return string.Format(formatString,
this.Incentivized,
this.ScheduleName,
this.ScheduleId,
this.CreativeName,
this.CreativeId,
this.ChannelName,
this.RewardId,
this.DeepLink);
}
public partial class Reply {
public enum ReplyStatus {
/// <summary>
/// The call was successful, and the notification has been scheduled for delivery.
/// </summary>
Ok,
/// <summary>
/// The call could not be completed because Teak is unable to send a notification to the device.
/// </summary>
/// <remarks>
/// This can either be that the user has not granted push permissions on iOS, or that the
/// Teak Dashboard does not have sending credentials suitable for the current device
/// (i.e. Teak has not been provided with an FCM Sender ID/API Key, APNS certificate,
/// or ADM Client ID/Client Secret).
/// </remarks>
UnconfiguredKey,
/// <summary>
/// The call could not be completed because Teak is not aware of the device scheduling
/// the notification.
/// </summary>
/// <remarks>
/// This can happen if Teak was completely unable to get a push token for the device,
/// which can occur due to intermittent failures in APNS/FCM/ADM,
/// intermittent networking failures between the device and those services,
/// or system modifications made on rooted devices.
/// </remarks>
InvalidDevice,
/// <summary>
/// An unknown error occured, and the call should be retried.
/// </summary>
InternalError
}
public struct Notification {
public string ScheduleId;
public string CreativeId;
public override string ToString() {
string formatString = "{{ ScheduleId = '{0}', CreativeId = '{1}' }}";
return string.Format(formatString,
this.ScheduleId,
this.CreativeId);
}
}
public ReplyStatus Status { get; set; }
public List<Notification> Notifications { get; set; }
}
// Returns an id that can be used to cancel a scheduled notification
public static IEnumerator ScheduleNotification(string scheduleName, string defaultMessage, long delayInSeconds, System.Action<Reply> callback) {
if (Teak.Instance.Trace) {
Debug.Log("[TeakNotification] ScheduleNotification(" + scheduleName + ", " + defaultMessage + ", " + delayInSeconds + ")");
}
#if UNITY_EDITOR
yield return null;
#elif UNITY_ANDROID
string data = null;
string status = null;
AndroidJavaClass teakNotification = new AndroidJavaClass("io.teak.sdk.TeakNotification");
AndroidJavaObject future = teakNotification.CallStatic<AndroidJavaObject>("scheduleNotification", scheduleName, defaultMessage, delayInSeconds);
if (future != null) {
while (!future.Call<bool>("isDone")) { yield return null; }
try {
Dictionary<string, object> json = Json.TryDeserialize(future.Call<string>("get")) as Dictionary<string, object>;
data = json["data"] as string;
status = json["status"] as string;
} catch {
status = "error.internal";
data = null;
}
}
SafePerformCallback("schedule_notification.local", callback, data, status, scheduleName);
#elif UNITY_IPHONE
string data = null;
string status = null;
IntPtr notif = TeakNotificationSchedule_Retained(scheduleName, defaultMessage, delayInSeconds);
if (notif != IntPtr.Zero) {
while (!TeakNotificationIsCompleted(notif)) { yield return null; }
data = Marshal.PtrToStringAnsi(TeakNotificationGetTeakNotifId(notif));
status = Marshal.PtrToStringAnsi(TeakNotificationGetStatus(notif));
TeakRelease(notif);
}
SafePerformCallback("schedule_notification.local", callback, data, status, scheduleName);
#elif UNITY_WEBGL
string callbackId = DateTime.Now.Ticks.ToString();
webGlCallbackMap.Add(callbackId, callback);
TeakNotificationSchedule(callbackId, scheduleName, defaultMessage, delayInSeconds);
yield return null;
#endif
}
public static IEnumerator ScheduleNotification(string scheduleName, long delayInSeconds, string[] userIds, System.Action<Reply> callback) {
if (Teak.Instance.Trace) {
Debug.Log("[TeakNotification] ScheduleNotification(" + scheduleName + ", " + delayInSeconds + ", " + userIds + ")");
}
#if UNITY_EDITOR
yield return null;
#elif UNITY_ANDROID
string data = null;
string status = null;
AndroidJavaClass teakNotification = new AndroidJavaClass("io.teak.sdk.TeakNotification");
AndroidJavaObject future = teakNotification.CallStatic<AndroidJavaObject>("scheduleNotification", scheduleName, delayInSeconds, userIds);
if (future != null) {
while (!future.Call<bool>("isDone")) { yield return null; }
try {
Dictionary<string, object> json = Json.TryDeserialize(future.Call<string>("get")) as Dictionary<string, object>;
data = json["data"] as string;
status = json["status"] as string;
} catch {
status = "error.internal";
data = null;
}
}
SafePerformCallback("schedule_notification.long_distance", callback, data, status, scheduleName);
#elif UNITY_IPHONE
string data = null;
string status = null;
IntPtr notif = TeakNotificationScheduleLongDistance_Retained(scheduleName, delayInSeconds, userIds, userIds.Length);
if (notif != IntPtr.Zero) {
while (!TeakNotificationIsCompleted(notif)) { yield return null; }
data = Marshal.PtrToStringAnsi(TeakNotificationGetTeakNotifId(notif));
status = Marshal.PtrToStringAnsi(TeakNotificationGetStatus(notif));
TeakRelease(notif);
}
SafePerformCallback("schedule_notification.long_distance", callback, data, status, scheduleName);
#elif UNITY_WEBGL
string callbackId = DateTime.Now.Ticks.ToString();
webGlCallbackMap.Add(callbackId, callback);
TeakNotificationScheduleLongDistance(callbackId, scheduleName, Json.Serialize(userIds), delayInSeconds);
yield return null;
#endif
}
// Cancel an existing notification
public static IEnumerator CancelScheduledNotification(string scheduleId, System.Action<Reply> callback) {
if (Teak.Instance.Trace) {
Debug.Log("[TeakNotification] CancelScheduledNotification(" + scheduleId + ")");
}
#if UNITY_EDITOR
yield return null;
#elif UNITY_ANDROID
string data = null;
string status = null;
AndroidJavaClass teakNotification = new AndroidJavaClass("io.teak.sdk.TeakNotification");
AndroidJavaObject future = teakNotification.CallStatic<AndroidJavaObject>("cancelNotification", scheduleId);
if (future != null) {
while (!future.Call<bool>("isDone")) { yield return null; }
try {
Dictionary<string, object> json = Json.TryDeserialize(future.Call<string>("get")) as Dictionary<string, object>;
data = json["data"] as string;
status = json["status"] as string;
} catch {
status = "error.internal";
data = null;
}
}
SafePerformCallback("cancel_notification", callback, data, status, null);
#elif UNITY_IPHONE
string data = null;
string status = null;
IntPtr notif = TeakNotificationCancel_Retained(scheduleId);
if (notif != IntPtr.Zero) {
while (!TeakNotificationIsCompleted(notif)) { yield return null; }
data = Marshal.PtrToStringAnsi(TeakNotificationGetTeakNotifId(notif));
status = Marshal.PtrToStringAnsi(TeakNotificationGetStatus(notif));
TeakRelease(notif);
}
SafePerformCallback("cancel_notification", callback, data, status, null);
#elif UNITY_WEBGL
string callbackId = DateTime.Now.Ticks.ToString();
webGlCallbackMap.Add(callbackId, callback);
TeakNotificationCancel(callbackId, scheduleId);
yield return null;
#endif
}
// Cancel all scheduled notifications
public static IEnumerator CancelAllScheduledNotifications(System.Action<Reply> callback) {
if (Teak.Instance.Trace) {
Debug.Log("[TeakNotification] CancelAllScheduledNotifications()");
}
#if UNITY_EDITOR
yield return null;
#elif UNITY_ANDROID
string data = null;
string status = null;
AndroidJavaClass teakNotification = new AndroidJavaClass("io.teak.sdk.TeakNotification");
AndroidJavaObject future = teakNotification.CallStatic<AndroidJavaObject>("cancelAll");
if (future != null) {
while (!future.Call<bool>("isDone")) { yield return null; }
try {
Dictionary<string, object> json = Json.TryDeserialize(future.Call<string>("get")) as Dictionary<string, object>;
data = Json.Serialize(json["data"]);
status = json["status"] as string;
} catch {
status = "error.internal";
data = null;
}
}
SafePerformCallback("cancel_all_notifications", callback, data, status, null);
#elif UNITY_IPHONE
string data = null;
string status = null;
IntPtr notif = TeakNotificationCancelAll_Retained();
if (notif != IntPtr.Zero) {
while (!TeakNotificationIsCompleted(notif)) { yield return null; }
data = Marshal.PtrToStringAnsi(TeakNotificationGetTeakNotifId(notif));
status = Marshal.PtrToStringAnsi(TeakNotificationGetStatus(notif));
TeakRelease(notif);
}
SafePerformCallback("cancel_all_notifications", callback, data, status, null);
#elif UNITY_WEBGL
string callbackId = DateTime.Now.Ticks.ToString();
webGlCallbackMap.Add(callbackId, callback);
TeakNotificationCancelAll(callbackId);
yield return null;
#endif
}
/// @cond hide_from_doxygen
private static void SafePerformCallback(string method, System.Action<Reply> callback, string data, string status, string scheduleName) {
try {
callback(new Reply(status, data, scheduleName));
} catch (Exception e) {
Dictionary<string, object> extras = new Dictionary<string, object>();
extras["data"] = data;
extras["status"] = status;
if (scheduleName != null) {
extras["creative_id"] = scheduleName;
}
Teak.Instance.ReportCallbackError(method, e, extras);
}
}
#if UNITY_IOS
[DllImport ("__Internal")]
private static extern IntPtr TeakNotificationSchedule_Retained(string scheduleName, string message, long delay);
[DllImport ("__Internal")]
private static extern IntPtr TeakNotificationScheduleLongDistance_Retained(string scheduleName, long delayInSeconds, string[] userIds, int lenUserIds);
[DllImport ("__Internal")]
private static extern IntPtr TeakNotificationCancel_Retained(string scheduleId);
[DllImport ("__Internal")]
private static extern IntPtr TeakNotificationCancelAll_Retained();
[DllImport ("__Internal")]
private static extern void TeakRelease(IntPtr obj);
[DllImport ("__Internal")]
private static extern bool TeakNotificationIsCompleted(IntPtr notif);
[DllImport ("__Internal")]
private static extern IntPtr TeakNotificationGetTeakNotifId(IntPtr notif);
[DllImport ("__Internal")]
private static extern IntPtr TeakNotificationGetStatus(IntPtr notif);
#elif UNITY_WEBGL
[DllImport ("__Internal")]
private static extern void TeakNotificationSchedule(string callbackId, string scheduleName, string message, long delay);
[DllImport ("__Internal")]
private static extern IntPtr TeakNotificationScheduleLongDistance(string callbackId, string scheduleName, string jsonUserIds, long delay);
[DllImport ("__Internal")]
private static extern void TeakNotificationCancel(string callbackId, string scheduleId);
[DllImport ("__Internal")]
private static extern void TeakNotificationCancelAll(string callbackId);
private static Dictionary<string, System.Action<Reply>> webGlCallbackMap = new Dictionary<string, System.Action<Reply>>();
public static void WebGLCallback(string callbackId, string status, string data, string scheduleName) {
if (webGlCallbackMap.ContainsKey(callbackId)) {
System.Action<Reply> callback = webGlCallbackMap[callbackId];
webGlCallbackMap.Remove(callbackId);
callback(new Reply(status, data, scheduleName));
}
}
#endif
/// @endcond
/// @cond hide_from_doxygen
public partial class Reply {
public Reply(string status, string data, string creativeId = null) {
this.Status = ReplyStatus.InternalError;
switch (status) {
case "ok":
this.Status = ReplyStatus.Ok;
break;
case "unconfigured_key":
this.Status = ReplyStatus.UnconfiguredKey;
break;
case "invalid_device":
this.Status = ReplyStatus.InvalidDevice;
break;
}
if (this.Status == ReplyStatus.Ok) {
List<object> replyList = Json.TryDeserialize(data) as List<object>;
if (replyList != null) {
// Data contains array of pairs
this.Notifications = new List<Notification>();
foreach (object e in replyList) {
Dictionary<string, object> entry = e as Dictionary<string, object>;
if (entry != null) {
this.Notifications.Add(new Notification { ScheduleId = entry["schedule_id"].ToString(), CreativeId = entry["creative_id"] as string });
} else {
this.Notifications.Add(new Notification { ScheduleId = e as string, CreativeId = creativeId });
}
}
} else {
this.Notifications = new List<Notification> {
new Notification { ScheduleId = data, CreativeId = creativeId }
};
}
}
}
}
/// @endcond
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
namespace Phonix.TestE2E
{
using NUnit.Framework;
[TestFixture]
public class ParserTest
{
[Test]
public void RuleWithVariable()
{
var phono = new PhonixWrapper().StdImports().Append("rule voice-assimilate [] => [$vc] / _ [$vc]");
phono.Start().ValidateInOut("sz", "zz");
phono.End();
}
[Test]
public void RuleDirectionRightward()
{
// default direction should be rightward
var phono = new PhonixWrapper().StdImports().Append("rule rightward a => b / a _");
phono.Start().ValidateInOut("aaa", "aba");
phono.End();
var phono2 = new PhonixWrapper().StdImports().Append("rule rightward (direction=left-to-right) a => b / a _");
phono2.Start().ValidateInOut("aaa", "aba");
phono2.End();
}
[Test]
public void RuleDirectionLeftward()
{
var phono = new PhonixWrapper().StdImports().Append("rule leftward (direction=right-to-left) a => b / a _");
phono.Start().ValidateInOut("aaa", "abb");
phono.End();
}
[Test]
public void NodeExistsInRule()
{
var phono = new PhonixWrapper().StdImports().Append(
@"rule coronal-test [Coronal] => [+vc]");
phono.Start().ValidateInOut("ptk", "pdk");
phono.End();
}
[Test]
public void NodeVariableInRule()
{
var phono = new PhonixWrapper().StdImports().Append(
@"rule coronal-test [] => [$Coronal] / _ [$Coronal -vc]");
phono.Start().ValidateInOut("TCg", "CCg");
phono.End();
}
[Test]
public void NodeNullInRule()
{
var phono = new PhonixWrapper().StdImports().Append(
@"rule coronal-null [Coronal] => [*Place] / _ ");
phono.Start().ValidateInOut("fTx", "fhx");
phono.End();
}
[Test]
public void LeftwardInsert()
{
var phono = new PhonixWrapper().StdImports().Append("rule leftward-insert (direction=right-to-left) * => c / b _ b");
phono.Start().ValidateInOut("abba", "abcba");
phono.End();
}
[Test]
public void RightwardInsert()
{
var phono = new PhonixWrapper().StdImports().Append("rule rightward-insert (direction=left-to-right) * => c / b _ b");
phono.Start().ValidateInOut("abba", "abcba");
phono.End();
}
[Test]
public void BasicExclude()
{
var phono = new PhonixWrapper().StdImports().Append("rule ex a => b / _ c // _ cc");
phono.Start()
.ValidateInOut("ac", "bc")
.ValidateInOut("acc", "acc")
.End();
}
[Test]
public void ExcludeContextLonger()
{
var phono = new PhonixWrapper().StdImports().Append("rule ex a => b / c[-vc] _ // c _");
phono.Start()
.ValidateInOut("csa", "csb")
.ValidateInOut("cca", "cca")
.End();
}
[Test]
public void ExcludeContextShorter()
{
var phono = new PhonixWrapper().StdImports().Append("rule ex a => b / k _ // sk _");
phono.Start()
.ValidateInOut("ka", "kb")
.ValidateInOut("ska", "ska")
.End();
}
[Test]
public void ExcludeNoContext()
{
var phono = new PhonixWrapper().StdImports().Append("rule ex a => b // c _");
phono.Start()
.ValidateInOut("ka", "kb")
.ValidateInOut("ca", "ca")
.End();
}
[Test]
public void ContextTrailingSlash()
{
var phono = new PhonixWrapper().StdImports().Append("rule ex a => b / _ c / ");
phono.Start().ValidateInOut("aac", "abc");
phono.End();
}
[Test]
public void ExcludeSingleSlash()
{
var phono = new PhonixWrapper().StdImports().Append("rule ex a => b / _ c / a _ ");
phono.Start().ValidateInOut("aac", "aac");
phono.End();
}
[Test]
public void Insert()
{
// middle
var phono = new PhonixWrapper().StdImports().Append("rule insert * => a / b _ b");
phono.Start().ValidateInOut("bb", "bab");
phono.End();
// beginning
phono = new PhonixWrapper().StdImports().Append("rule insert * => a / _ bb");
phono.Start().ValidateInOut("bb", "abb");
phono.End();
// end
phono = new PhonixWrapper().StdImports().Append("rule insert * => a / bb _");
phono.Start().ValidateInOut("bb", "bba");
phono.End();
}
[Test]
public void Delete()
{
// middle
var phono = new PhonixWrapper().StdImports().Append("rule delete-middle a => * / b _ b");
phono.Start().ValidateInOut("bab", "bb");
phono.End();
// beginning
phono = new PhonixWrapper().StdImports().Append("rule delete-beginning a => * / _ bb");
phono.Start().ValidateInOut("abb", "bb");
phono.End();
// end
phono = new PhonixWrapper().StdImports().Append("rule delete-end a => * / bb _");
phono.Start().ValidateInOut("bba", "bb");
phono.End();
// two
phono = new PhonixWrapper().StdImports().Append("rule delete-double aa => **");
phono.Start().ValidateInOut("baab", "bb");
phono.End();
}
[Test]
public void RulePersist()
{
var phono = new PhonixWrapper().StdImports().Append("rule persist-b-a (persist) b => a rule a-b a => b");
phono.Start().ValidateInOut("baa", "aaa");
phono.End();
}
[Test]
public void SegmentRepeatZeroOrMore()
{
var phono = new PhonixWrapper().StdImports().Append("rule matchany a => c / _ (b)*$ ");
phono.Start()
.ValidateInOut("a", "c")
.ValidateInOut("ab", "cb")
.ValidateInOut("abb", "cbb")
.ValidateInOut("ac", "ac")
.End();
}
[Test]
public void SegmentRepeatOneOrMore()
{
var phono = new PhonixWrapper().StdImports().Append("rule matchany a => c / _ (b)+$ ");
phono.Start().ValidateInOut("a", "a");
phono.ValidateInOut("ab", "cb");
phono.ValidateInOut("abb", "cbb");
phono.ValidateInOut("ac", "ac");
phono.End();
}
[Test]
public void SegmentRepeatZeroOrOne()
{
var phono = new PhonixWrapper().StdImports().Append("rule matchany a => c / _ (b)$ ");
phono.Start().ValidateInOut("a", "c");
phono.ValidateInOut("ab", "cb");
phono.ValidateInOut("abb", "abb");
phono.ValidateInOut("ac", "ac");
phono.End();
}
[Test]
public void MultipleSegmentOptional()
{
var phono = new PhonixWrapper().StdImports().Append("rule matchany a => c / _ (bc)c$ ");
phono.Start();
phono.ValidateInOut("a", "a");
phono.ValidateInOut("ac", "cc");
phono.ValidateInOut("abc", "abc");
phono.ValidateInOut("abcc", "cbcc");
phono.End();
}
[Test]
public void SegmentOptional()
{
var phono = new PhonixWrapper().StdImports().Append("rule matchany a => c / _ (b)+c$ ");
phono.Start().ValidateInOut("a", "a");
phono.ValidateInOut("ac", "ac");
phono.ValidateInOut("abc", "cbc");
phono.ValidateInOut("abbc", "cbbc");
phono.End();
}
[Test]
public void MultipleSegmentOptionalBacktrack()
{
var phono = new PhonixWrapper().StdImports().Append("rule matchany a => c / _ (bc)+b$ ");
phono.Start().ValidateInOut("abc", "abc");
phono.ValidateInOut("abcb", "cbcb");
phono.ValidateInOut("abcbc", "abcbc");
phono.ValidateInOut("abcbcb", "cbcbcb");
phono.End();
}
[Test]
public void SegmentRepeatZeroOrOnePre()
{
var phono = new PhonixWrapper().StdImports().Append("rule matchany a => x / (c)b _ $ ");
phono.Start().ValidateInOut("cba", "cbx");
phono.ValidateInOut("ba", "bx");
phono.ValidateInOut("ca", "ca");
phono.End();
}
[Test]
public void SegmentRepeatZeroOnMorePre()
{
var phono = new PhonixWrapper().StdImports().Append("rule matchany a => x / (c)*b _ $ ");
phono.Start().ValidateInOut("cba", "cbx");
phono.ValidateInOut("ccba", "ccbx");
phono.ValidateInOut("cccba", "cccbx");
phono.ValidateInOut("ba", "bx");
phono.ValidateInOut("ca", "ca");
phono.End();
}
[Test]
public void SegmentRepeatOneOrMorePre()
{
var phono = new PhonixWrapper().StdImports().Append("rule matchany a => x / (c)+b _ $ ");
phono.Start().ValidateInOut("cba", "cbx");
phono.ValidateInOut("ccba", "ccbx");
phono.ValidateInOut("cccba", "cccbx");
phono.ValidateInOut("ba", "ba");
phono.ValidateInOut("ca", "ca");
phono.End();
}
private string scalarDefs =
"feature sc (type=scalar min=0 max=3) " +
"symbol scX [*sc] " +
"symbol sc0 [sc=0] " +
"symbol sc1 [sc=1] " +
"symbol sc2 [sc=2] " +
"symbol sc3 [sc=3] ";
[Test]
public void ScalarNotEq()
{
var phono = new PhonixWrapper().Append(scalarDefs).Append("rule neq [sc<>0] => sc2");
phono.Start().ValidateInOut("sc0", "sc0");
phono.ValidateInOut("sc1", "sc2");
phono.ValidateInOut("sc2", "sc2");
phono.ValidateInOut("sc3", "sc2");
phono.ValidateInOut("scX", "sc2");
phono.End();
}
[Test]
public void ScalarGT()
{
var phono = new PhonixWrapper().Append(scalarDefs).Append("rule gt [sc>1] => sc0");
phono.Start().ValidateInOut("sc0", "sc0");
phono.ValidateInOut("sc1", "sc1");
phono.ValidateInOut("sc2", "sc0");
phono.ValidateInOut("sc3", "sc0");
phono.ValidateInOut("scX", "scX");
phono.End();
}
[Test]
public void ScalarGTOrEq()
{
var phono = new PhonixWrapper().Append(scalarDefs + "rule gte [sc>=2] => sc0");
phono.Start().ValidateInOut("sc0", "sc0");
phono.ValidateInOut("sc1", "sc1");
phono.ValidateInOut("sc2", "sc0");
phono.ValidateInOut("sc3", "sc0");
phono.ValidateInOut("scX", "scX");
phono.End();
}
[Test]
public void ScalarLT()
{
var phono = new PhonixWrapper().Append(scalarDefs + "rule lt [sc<2] => sc3");
phono.Start().ValidateInOut("sc0", "sc3");
phono.ValidateInOut("sc1", "sc3");
phono.ValidateInOut("sc2", "sc2");
phono.ValidateInOut("sc3", "sc3");
phono.ValidateInOut("scX", "scX");
phono.End();
}
[Test]
public void ScalarLTOrEq()
{
var phono = new PhonixWrapper().Append(scalarDefs + "rule lte [sc<=1] => sc3");
phono.Start().ValidateInOut("sc0", "sc3");
phono.ValidateInOut("sc1", "sc3");
phono.ValidateInOut("sc2", "sc2");
phono.ValidateInOut("sc3", "sc3");
phono.ValidateInOut("scX", "scX");
phono.End();
}
[Test]
public void ScalarAdd()
{
var phono = new PhonixWrapper().Append(scalarDefs + "rule add [sc<3] => [sc=+1]");
phono.Start().ValidateInOut("sc0", "sc1");
phono.ValidateInOut("sc1", "sc2");
phono.ValidateInOut("sc2", "sc3");
phono.ValidateInOut("sc3", "sc3");
phono.ValidateInOut("scX", "scX");
phono.End();
}
[Test]
public void ScalarSubtract()
{
var phono = new PhonixWrapper().Append(scalarDefs + "rule subtract [sc>0] => [sc=-1]");
phono.Start().ValidateInOut("sc0", "sc0");
phono.ValidateInOut("sc1", "sc0");
phono.ValidateInOut("sc2", "sc1");
phono.ValidateInOut("sc3", "sc2");
phono.ValidateInOut("scX", "scX");
phono.End();
}
[Test]
public void MatchOnset()
{
var phono = new PhonixWrapper().StdImports().Append(
"syllable onset [+cons]([+cons]) nucleus [-cons +son] coda [+cons] " +
"rule markOnset [<onset>] => x / _ [<*onset>]");
phono.Start().ValidateInOut("basiho", "xaxixo");
phono.ValidateInOut("brastihno", "bxasxihxo");
phono.ValidateInOut("aszihgon", "asxihxon");
phono.ValidateInOut("barsih", "xarxih");
phono.End();
}
[Test]
public void MatchCoda()
{
var phono = new PhonixWrapper().StdImports().Append(
"syllable onset [+cons] nucleus [-cons +son] coda [+cons] " +
"rule markCoda [<coda>] => x / [<*coda>] _ ");
phono.Start();
phono.ValidateInOut("basiho", "basiho");
phono.ValidateInOut("brastihno", "braxtixno");
phono.ValidateInOut("aszihgon", "axzixgox");
phono.ValidateInOut("barsih", "baxsix");
phono.End();
}
[Test]
public void MatchNucleus()
{
var phono = new PhonixWrapper().StdImports().Append(
"syllable onset [+cons] nucleus [-cons +son] coda [+cons] " +
"rule markCoda [<nucleus>] => x ");
phono.Start().ValidateInOut("basiho", "bxsxhx");
phono.ValidateInOut("brastihno", "brxstxhnx");
phono.ValidateInOut("aszihgon", "xszxhgxn");
phono.ValidateInOut("barsih", "bxrsxh");
phono.End();
}
[Test]
public void MatchSyllable()
{
var phono = new PhonixWrapper().StdImports().Append(
"syllable (onsetRequired codaRequired) onset [+cons] nucleus [-cons +son] coda [+cons] " +
"rule markSyllable [<syllable>] => x ");
phono.Start().ValidateInOut("basiho", "xxxiho");
phono.ValidateInOut("brastihno", "bxxxxxxno");
phono.ValidateInOut("aszihgon", "asxxxxxx");
phono.ValidateInOut("barsih", "xxxxxx");
phono.End();
}
[Test]
public void MatchNoSyllable()
{
var phono = new PhonixWrapper().StdImports().Append(
"syllable (onsetRequired codaRequired) onset [+cons] nucleus [-cons +son] coda [+cons] " +
"rule markNoSyllable [<*syllable>] => x ");
phono.Start().ValidateInOut("basiho", "basxxx");
phono.ValidateInOut("brastihno", "xrastihxx");
phono.ValidateInOut("aszihgon", "xxzihgon");
phono.ValidateInOut("barsih", "barsih");
phono.End();
}
[Test]
public void FeatureGroupDeclaration()
{
new PhonixWrapper().StdImports().Append("feature [V] [+syll +son +vc]");
}
[Test]
public void SymbolContainsFeatureGroup()
{
new PhonixWrapper().StdImports().Append("feature [V] [+syll +son +vc] symbol ! [[V] -hi]");
}
[Test]
public void RuleMatchContainsFeatureGroup()
{
var phono = new PhonixWrapper().StdImports().Append("feature [V] [+syll +son]\n" +
"rule match-group [[V]] => i");
phono.Start().ValidateInOut("bomo", "bimi");
phono.End();
}
[Test]
public void RuleActionContainsFeatureGroup()
{
var phono = new PhonixWrapper().StdImports().Append("feature [V] [+syll +son]\n" +
"rule match-group [+syll -hi] => [[V] +hi -lo +fr -bk]");
phono.Start().ValidateInOut("bomo", "bymy");
phono.End();
}
[Test]
public void SymbolContainsSymbolRef()
{
new PhonixWrapper().StdImports().Append("symbol s! [(s) -cons]");
}
[Test]
public void RuleMatchContainsSymbolRef()
{
var phono = new PhonixWrapper().StdImports().Append("import std.symbols.diacritics\nrule match-sym [(a)] => i");
phono.Start().ValidateInOut("ba~ma_0", "bimi");
phono.End();
}
[Test]
public void RuleMatchAndActionContainSymbolRef()
{
var phono = new PhonixWrapper().StdImports().Append("import std.symbols.diacritics\nrule match-sym [(a)] => [(i)]");
phono.Start().ValidateInOut("ba~ma_0", "bi~mi_0");
phono.End();
}
[Test]
public void StringQuoting()
{
var phono = new PhonixWrapper().StdImports().Append(
"symbol \"quote\" [-cons -ro]" +
"symbol \"quote with space\" [+cons -ro]" +
"symbol \"quote +(with) -<bad> $[chars]\" [+cons +ro]" +
"symbol \"quote isn't awesome\" [-cons +ro]" +
"symbol 'squote' [-cons -str]" +
"symbol 'squote with space' [+cons -str]" +
"symbol 'squote +(with) -<bad> $[chars]' [+cons +str]" +
"symbol 'squote has \" in it' [-cons +str]"
);
phono.Start().End();
}
}
}
| |
using System;
using System.Runtime.Serialization;
namespace Python.Runtime
{
/// <summary>
/// Represents a Python integer object. See the documentation at
/// PY2: https://docs.python.org/2/c-api/int.html
/// PY3: No equivalent
/// for details.
/// </summary>
public class PyInt : PyNumber
{
internal PyInt(in StolenReference ptr) : base(ptr)
{
}
internal PyInt(BorrowedReference reference): base(reference)
{
if (!Runtime.PyInt_Check(reference)) throw new ArgumentException("object is not an int");
}
/// <summary>
/// PyInt Constructor
/// </summary>
/// <remarks>
/// Copy constructor - obtain a PyInt from a generic PyObject. An
/// ArgumentException will be thrown if the given object is not a
/// Python int object.
/// </remarks>
public PyInt(PyObject o) : base(FromObject(o))
{
}
private static BorrowedReference FromObject(PyObject o)
{
if (o is null) throw new ArgumentNullException(nameof(o));
if (!IsIntType(o))
{
throw new ArgumentException("object is not an int");
}
return o.Reference;
}
/// <summary>
/// PyInt Constructor
/// </summary>
/// <remarks>
/// Creates a new Python int from an int32 value.
/// </remarks>
public PyInt(int value) : base(Runtime.PyInt_FromInt32(value).StealOrThrow())
{
}
/// <summary>
/// PyInt Constructor
/// </summary>
/// <remarks>
/// Creates a new Python int from a uint32 value.
/// </remarks>
public PyInt(uint value) : this((long)value)
{
}
/// <summary>
/// PyInt Constructor
/// </summary>
/// <remarks>
/// Creates a new Python int from an int64 value.
/// </remarks>
public PyInt(long value) : base(Runtime.PyInt_FromInt64(value).StealOrThrow())
{
}
/// <summary>
/// Creates a new Python int from a <see cref="UInt64"/> value.
/// </summary>
public PyInt(ulong value) : base(Runtime.PyLong_FromUnsignedLongLong(value).StealOrThrow())
{
}
/// <summary>
/// PyInt Constructor
/// </summary>
/// <remarks>
/// Creates a new Python int from an int16 value.
/// </remarks>
public PyInt(short value) : this((int)value)
{
}
/// <summary>
/// PyInt Constructor
/// </summary>
/// <remarks>
/// Creates a new Python int from a uint16 value.
/// </remarks>
public PyInt(ushort value) : this((int)value)
{
}
/// <summary>
/// PyInt Constructor
/// </summary>
/// <remarks>
/// Creates a new Python int from a byte value.
/// </remarks>
public PyInt(byte value) : this((int)value)
{
}
/// <summary>
/// PyInt Constructor
/// </summary>
/// <remarks>
/// Creates a new Python int from an sbyte value.
/// </remarks>
public PyInt(sbyte value) : this((int)value)
{
}
/// <summary>
/// PyInt Constructor
/// </summary>
/// <remarks>
/// Creates a new Python int from a string value.
/// </remarks>
public PyInt(string value) : base(Runtime.PyLong_FromString(value, 0).StealOrThrow())
{
}
protected PyInt(SerializationInfo info, StreamingContext context)
: base(info, context) { }
/// <summary>
/// IsIntType Method
/// </summary>
/// <remarks>
/// Returns true if the given object is a Python int.
/// </remarks>
public static bool IsIntType(PyObject value)
{
if (value is null) throw new ArgumentNullException(nameof(value));
return Runtime.PyInt_Check(value.obj);
}
/// <summary>
/// Convert a Python object to a Python int if possible, raising
/// a PythonException if the conversion is not possible. This is
/// equivalent to the Python expression "int(object)".
/// </summary>
public static PyInt AsInt(PyObject value)
{
if (value is null) throw new ArgumentNullException(nameof(value));
var op = Runtime.PyNumber_Long(value.Reference);
PythonException.ThrowIfIsNull(op);
return new PyInt(op.Steal());
}
/// <summary>
/// ToInt16 Method
/// </summary>
/// <remarks>
/// Return the value of the Python int object as an int16.
/// </remarks>
public short ToInt16()
{
return Convert.ToInt16(ToInt32());
}
/// <summary>
/// Return the value of the Python int object as an <see cref="Int32"/>.
/// </summary>
public int ToInt32() => Converter.ToInt32(Reference);
/// <summary>
/// ToInt64 Method
/// </summary>
/// <remarks>
/// Return the value of the Python int object as an int64.
/// </remarks>
public long ToInt64()
{
long? val = Runtime.PyLong_AsLongLong(obj);
if (val is null)
{
throw PythonException.ThrowLastAsClrException();
}
return val.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.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization.Formatters.Tests;
using Xunit;
namespace System.Tests
{
public static class TestExtensionMethod
{
public static DelegateTests.TestStruct TestFunc(this DelegateTests.TestClass testparam)
{
return testparam.structField;
}
public static void IncrementX(this DelegateTests.TestSerializableClass t)
{
t.x++;
}
}
public static unsafe class DelegateTests
{
public struct TestStruct
{
public object o1;
public object o2;
}
public class TestClass
{
public TestStruct structField;
}
[Serializable]
public class TestSerializableClass
{
public int x = 1;
}
private static void EmptyFunc() { }
public delegate TestStruct StructReturningDelegate();
[Fact]
public static void ClosedStaticDelegate()
{
TestClass foo = new TestClass();
foo.structField.o1 = new object();
foo.structField.o2 = new object();
StructReturningDelegate testDelegate = foo.TestFunc;
TestStruct returnedStruct = testDelegate();
Assert.Same(foo.structField.o1, returnedStruct.o1);
Assert.Same(foo.structField.o2, returnedStruct.o2);
}
public class A { }
public class B : A { }
public delegate A DynamicInvokeDelegate(A nonRefParam1, B nonRefParam2, ref A refParam, out B outParam);
public static A DynamicInvokeTestFunction(A nonRefParam1, B nonRefParam2, ref A refParam, out B outParam)
{
outParam = (B)refParam;
refParam = nonRefParam2;
return nonRefParam1;
}
[Fact]
public static void DynamicInvoke()
{
A a1 = new A();
A a2 = new A();
B b1 = new B();
B b2 = new B();
DynamicInvokeDelegate testDelegate = DynamicInvokeTestFunction;
// Check that the delegate behaves as expected
A refParam = b2;
B outParam = null;
A returnValue = testDelegate(a1, b1, ref refParam, out outParam);
Assert.Same(returnValue, a1);
Assert.Same(refParam, b1);
Assert.Same(outParam, b2);
// Check dynamic invoke behavior
object[] parameters = new object[] { a1, b1, b2, null };
object retVal = testDelegate.DynamicInvoke(parameters);
Assert.Same(retVal, a1);
Assert.Same(parameters[2], b1);
Assert.Same(parameters[3], b2);
// Check invoke on a delegate that takes no parameters.
Action emptyDelegate = EmptyFunc;
emptyDelegate.DynamicInvoke(new object[] { });
emptyDelegate.DynamicInvoke(null);
}
[Fact]
public static void DynamicInvoke_MissingTypeForDefaultParameter_Succeeds()
{
// Passing Type.Missing with default.
Delegate d = new IntIntDelegateWithDefault(IntIntMethod);
d.DynamicInvoke(7, Type.Missing);
}
[Fact]
public static void DynamicInvoke_MissingTypeForNonDefaultParameter_ThrowsArgumentException()
{
Delegate d = new IntIntDelegate(IntIntMethod);
AssertExtensions.Throws<ArgumentException>("parameters", () => d.DynamicInvoke(7, Type.Missing));
}
[Theory]
[InlineData(new object[] { 7 }, new object[] { 8 })]
[InlineData(new object[] { null }, new object[] { 1 })]
public static void DynamicInvoke_RefValueTypeParameter(object[] args, object[] expected)
{
Delegate d = new RefIntDelegate(RefIntMethod);
d.DynamicInvoke(args);
Assert.Equal(expected, args);
}
[Fact]
public static void DynamicInvoke_NullRefValueTypeParameter_ReturnsValueTypeDefault()
{
Delegate d = new RefValueTypeDelegate(RefValueTypeMethod);
object[] args = new object[] { null };
d.DynamicInvoke(args);
MyStruct s = (MyStruct)(args[0]);
Assert.Equal(s.X, 7);
Assert.Equal(s.Y, 8);
}
[Fact]
public static void DynamicInvoke_TypeDoesntExactlyMatchRefValueType_ThrowsArgumentException()
{
Delegate d = new RefIntDelegate(RefIntMethod);
AssertExtensions.Throws<ArgumentException>(null, () => d.DynamicInvoke((uint)7));
AssertExtensions.Throws<ArgumentException>(null, () => d.DynamicInvoke(IntEnum.One));
}
[Theory]
[InlineData(7, (short)7)] // uint -> int
[InlineData(7, IntEnum.Seven)] // Enum (int) -> int
[InlineData(7, ShortEnum.Seven)] // Enum (short) -> int
public static void DynamicInvoke_ValuePreservingPrimitiveWidening_Succeeds(object o1, object o2)
{
Delegate d = new IntIntDelegate(IntIntMethod);
d.DynamicInvoke(o1, o2);
}
[Theory]
[InlineData(IntEnum.Seven, 7)]
[InlineData(IntEnum.Seven, (short)7)]
public static void DynamicInvoke_ValuePreservingWideningToEnum_Succeeds(object o1, object o2)
{
Delegate d = new EnumEnumDelegate(EnumEnumMethod);
d.DynamicInvoke(o1, o2);
}
[Fact]
public static void DynamicInvoke_SizePreservingNonVauePreservingConversion_ThrowsArgumentException()
{
Delegate d = new IntIntDelegate(IntIntMethod);
AssertExtensions.Throws<ArgumentException>(null, () => d.DynamicInvoke(7, (uint)7));
AssertExtensions.Throws<ArgumentException>(null, () => d.DynamicInvoke(7, U4.Seven));
}
[Fact]
public static void DynamicInvoke_NullValueType_Succeeds()
{
Delegate d = new ValueTypeDelegate(ValueTypeMethod);
d.DynamicInvoke(new object[] { null });
}
[Fact]
public static void DynamicInvoke_ConvertMatchingTToNullable_Succeeds()
{
Delegate d = new NullableDelegate(NullableMethod);
d.DynamicInvoke(7);
}
[Fact]
public static void DynamicInvoke_ConvertNonMatchingTToNullable_ThrowsArgumentException()
{
Delegate d = new NullableDelegate(NullableMethod);
AssertExtensions.Throws<ArgumentException>(null, () => d.DynamicInvoke((short)7));
AssertExtensions.Throws<ArgumentException>(null, () => d.DynamicInvoke(IntEnum.Seven));
}
[Fact]
public static void DynamicInvoke_DefaultParameter_AllPrimitiveParametersWithMissingValues()
{
object[] parameters = new object[13];
for (int i = 0; i < parameters.Length; i++) { parameters[i] = Type.Missing; }
Assert.Equal(
"True, test, c, 2, -1, -3, 4, -5, 6, -7, 8, 9.1, 11.12",
(string)(new AllPrimitivesWithDefaultValues(AllPrimitivesMethod)).DynamicInvoke(parameters));
}
[Fact]
public static void DynamicInvoke_DefaultParameter_AllPrimitiveParametersWithAllExplicitValues()
{
Assert.Equal(
"False, value, d, 102, -101, -103, 104, -105, 106, -107, 108, 109.1, 111.12",
(string)(new AllPrimitivesWithDefaultValues(AllPrimitivesMethod)).DynamicInvoke(
new object[13]
{
false,
"value",
'd',
(byte)102,
(sbyte)-101,
(short)-103,
(UInt16)104,
(int)-105,
(UInt32)106,
(long)-107,
(UInt64)108,
(Single)109.1,
(Double)111.12
}
));
}
[Fact]
public static void DynamicInvoke_DefaultParameter_AllPrimitiveParametersWithSomeExplicitValues()
{
Assert.Equal(
"False, test, d, 2, -101, -3, 104, -5, 106, -7, 108, 9.1, 111.12",
(string)(new AllPrimitivesWithDefaultValues(AllPrimitivesMethod)).DynamicInvoke(
new object[13]
{
false,
Type.Missing,
'd',
Type.Missing,
(sbyte)-101,
Type.Missing,
(UInt16)104,
Type.Missing,
(UInt32)106,
Type.Missing,
(UInt64)108,
Type.Missing,
(Double)111.12
}
));
}
[Fact]
public static void DynamicInvoke_DefaultParameter_StringParameterWithMissingValue()
{
Assert.Equal
("test",
(string)(new StringWithDefaultValue(StringMethod)).DynamicInvoke(new object[] { Type.Missing }));
}
[Fact]
public static void DynamicInvoke_DefaultParameter_StringParameterWithExplicitValue()
{
Assert.Equal(
"value",
(string)(new StringWithDefaultValue(StringMethod)).DynamicInvoke(new object[] { "value" }));
}
[Fact]
public static void DynamicInvoke_DefaultParameter_ReferenceTypeParameterWithMissingValue()
{
Assert.Null((new ReferenceWithDefaultValue(ReferenceMethod)).DynamicInvoke(new object[] { Type.Missing }));
}
[Fact]
public static void DynamicInvoke_DefaultParameter_ReferenceTypeParameterWithExplicitValue()
{
CustomReferenceType referenceInstance = new CustomReferenceType();
Assert.Same(
referenceInstance,
(new ReferenceWithDefaultValue(ReferenceMethod)).DynamicInvoke(new object[] { referenceInstance }));
}
[Fact]
public static void DynamicInvoke_DefaultParameter_ValueTypeParameterWithMissingValue()
{
Assert.Equal(
0,
((CustomValueType)(new ValueTypeWithDefaultValue(ValueTypeMethod)).DynamicInvoke(new object[] { Type.Missing })).Id);
}
[Fact]
public static void DynamicInvoke_DefaultParameter_ValueTypeParameterWithExplicitValue()
{
Assert.Equal(
1,
((CustomValueType)(new ValueTypeWithDefaultValue(ValueTypeMethod)).DynamicInvoke(new object[] { new CustomValueType { Id = 1 } })).Id);
}
[Fact]
public static void DynamicInvoke_DefaultParameter_DateTimeParameterWithMissingValue()
{
Assert.Equal(
new DateTime(42),
(DateTime)(new DateTimeWithDefaultValueAttribute(DateTimeMethod)).DynamicInvoke(new object[] { Type.Missing }));
}
[Fact]
public static void DynamicInvoke_DefaultParameter_DateTimeParameterWithExplicitValue()
{
Assert.Equal(
new DateTime(43),
(DateTime)(new DateTimeWithDefaultValueAttribute(DateTimeMethod)).DynamicInvoke(new object[] { new DateTime(43) }));
}
[Fact]
public static void DynamicInvoke_DefaultParameter_DecimalParameterWithAttributeAndMissingValue()
{
Assert.Equal(
new decimal(4, 3, 2, true, 1),
(decimal)(new DecimalWithDefaultValueAttribute(DecimalMethod)).DynamicInvoke(new object[] { Type.Missing }));
}
[Fact]
public static void DynamicInvoke_DefaultParameter_DecimalParameterWithAttributeAndExplicitValue()
{
Assert.Equal(
new decimal(12, 13, 14, true, 1),
(decimal)(new DecimalWithDefaultValueAttribute(DecimalMethod)).DynamicInvoke(new object[] { new decimal(12, 13, 14, true, 1) }));
}
[Fact]
public static void DynamicInvoke_DefaultParameter_DecimalParameterWithMissingValue()
{
Assert.Equal(
3.14m,
(decimal)(new DecimalWithDefaultValue(DecimalMethod)).DynamicInvoke(new object[] { Type.Missing }));
}
[Fact]
public static void DynamicInvoke_DefaultParameter_DecimalParameterWithExplicitValue()
{
Assert.Equal(
103.14m,
(decimal)(new DecimalWithDefaultValue(DecimalMethod)).DynamicInvoke(new object[] { 103.14m }));
}
[Fact]
public static void DynamicInvoke_DefaultParameter_NullableIntWithMissingValue()
{
Assert.Null((int?)(new NullableIntWithDefaultValue(NullableIntMethod)).DynamicInvoke(new object[] { Type.Missing }));
}
[Fact]
public static void DynamicInvoke_DefaultParameter_NullableIntWithExplicitValue()
{
Assert.Equal(
(int?)42,
(int?)(new NullableIntWithDefaultValue(NullableIntMethod)).DynamicInvoke(new object[] { (int?)42 }));
}
[Fact]
public static void DynamicInvoke_DefaultParameter_EnumParameterWithMissingValue()
{
Assert.Equal(
IntEnum.Seven,
(IntEnum)(new EnumWithDefaultValue(EnumMethod)).DynamicInvoke(new object[] { Type.Missing }));
}
[Fact]
public static void DynamicInvoke_OptionalParameter_WithExplicitValue()
{
Assert.Equal(
"value",
(new OptionalObjectParameter(ObjectMethod)).DynamicInvoke(new object[] { "value" }));
}
[Fact]
public static void DynamicInvoke_OptionalParameter_WithMissingValue()
{
Assert.Equal(
Type.Missing,
(new OptionalObjectParameter(ObjectMethod)).DynamicInvoke(new object[] { Type.Missing }));
}
[Fact]
public static void DynamicInvoke_OptionalParameterUnassingableFromMissing_WithMissingValue()
{
AssertExtensions.Throws<ArgumentException>(null, () => (new OptionalStringParameter(StringMethod)).DynamicInvoke(new object[] { Type.Missing }));
}
[Fact]
public static void DynamicInvoke_ParameterSpecification_ArrayOfStrings()
{
Assert.Equal(
"value",
(new StringParameter(StringMethod)).DynamicInvoke(new string[] { "value" }));
}
[Fact]
public static void DynamicInvoke_ParameterSpecification_ArrayOfMissing()
{
Assert.Same(
Missing.Value,
(new OptionalObjectParameter(ObjectMethod)).DynamicInvoke(new Missing[] { Missing.Value }));
}
private static void IntIntMethod(int expected, int actual)
{
Assert.Equal(expected, actual);
}
private delegate void IntIntDelegate(int expected, int actual);
private delegate void IntIntDelegateWithDefault(int expected, int actual = 7);
private static void RefIntMethod(ref int i) => i++;
private delegate void RefIntDelegate(ref int i);
private struct MyStruct
{
public int X;
public int Y;
}
private static void RefValueTypeMethod(ref MyStruct s)
{
s.X += 7;
s.Y += 8;
}
private delegate void RefValueTypeDelegate(ref MyStruct s);
private static void EnumEnumMethod(IntEnum expected, IntEnum actual)
{
Assert.Equal(expected, actual);
}
private delegate void EnumEnumDelegate(IntEnum expected, IntEnum actual);
private static void ValueTypeMethod(MyStruct s)
{
Assert.Equal(s.X, 0);
Assert.Equal(s.Y, 0);
}
private delegate void ValueTypeDelegate(MyStruct s);
private static void NullableMethod(int? n)
{
Assert.True(n.HasValue);
Assert.Equal(n.Value, 7);
}
private delegate void NullableDelegate(int? s);
private enum ShortEnum : short
{
One = 1,
Seven = 7,
}
private enum IntEnum : int
{
One = 1,
Seven = 7,
}
private enum U4 : uint
{
One = 1,
Seven = 7,
}
private delegate string AllPrimitivesWithDefaultValues(
bool boolean = true,
string str = "test",
char character = 'c',
byte unsignedbyte = 2,
sbyte signedbyte = -1,
Int16 int16 = -3,
UInt16 uint16 = 4,
Int32 int32 = -5,
UInt32 uint32 = 6,
Int64 int64 = -7,
UInt64 uint64 = 8,
Single single = (Single)9.1,
Double dbl = 11.12);
private static string AllPrimitivesMethod(
bool boolean,
string str,
char character,
byte unsignedbyte,
sbyte signedbyte,
Int16 int16,
UInt16 uint16,
Int32 int32,
UInt32 uint32,
Int64 int64,
UInt64 uint64,
Single single,
Double dbl)
{
return FormattableString.Invariant($"{boolean}, {str}, {character}, {unsignedbyte}, {signedbyte}, {int16}, {uint16}, {int32}, {uint32}, {int64}, {uint64}, {single}, {dbl}");
}
private delegate string StringParameter(string parameter);
private delegate string StringWithDefaultValue(string parameter = "test");
private static string StringMethod(string parameter)
{
return parameter;
}
private class CustomReferenceType { };
private delegate CustomReferenceType ReferenceWithDefaultValue(CustomReferenceType parameter = null);
private static CustomReferenceType ReferenceMethod(CustomReferenceType parameter)
{
return parameter;
}
private struct CustomValueType { public int Id; };
private delegate CustomValueType ValueTypeWithDefaultValue(CustomValueType parameter = default(CustomValueType));
private static CustomValueType ValueTypeMethod(CustomValueType parameter)
{
return parameter;
}
private delegate DateTime DateTimeWithDefaultValueAttribute([DateTimeConstant(42)] DateTime parameter);
private static DateTime DateTimeMethod(DateTime parameter)
{
return parameter;
}
private delegate decimal DecimalWithDefaultValueAttribute([DecimalConstant(1, 1, 2, 3, 4)] decimal parameter);
private delegate decimal DecimalWithDefaultValue(decimal parameter = 3.14m);
private static decimal DecimalMethod(decimal parameter)
{
return parameter;
}
private delegate int? NullableIntWithDefaultValue(int? parameter = null);
private static int? NullableIntMethod(int? parameter)
{
return parameter;
}
private delegate IntEnum EnumWithDefaultValue(IntEnum parameter = IntEnum.Seven);
private static IntEnum EnumMethod(IntEnum parameter = IntEnum.Seven)
{
return parameter;
}
private delegate object OptionalObjectParameter([Optional] object parameter);
private static object ObjectMethod(object parameter)
{
return parameter;
}
private delegate string OptionalStringParameter([Optional] string parameter);
}
public static class CreateDelegateTests
{
#region Tests
[Fact]
public static void CreateDelegate1_Method_Static()
{
C c = new C();
MethodInfo mi = typeof(C).GetMethod("S");
Delegate dg = Delegate.CreateDelegate(typeof(D), mi);
Assert.Equal(mi, dg.Method);
Assert.Null(dg.Target);
D d = (D)dg;
d(c);
}
[Fact]
public static void CreateDelegate1_Method_Null()
{
ArgumentNullException ex = AssertExtensions.Throws<ArgumentNullException>("method", () => Delegate.CreateDelegate(typeof(D), (MethodInfo)null));
Assert.Null(ex.InnerException);
Assert.NotNull(ex.Message);
}
[Fact]
public static void CreateDelegate1_Type_Null()
{
MethodInfo mi = typeof(C).GetMethod("S");
ArgumentNullException ex = AssertExtensions.Throws<ArgumentNullException>("type", () => Delegate.CreateDelegate((Type)null, mi));
Assert.Null(ex.InnerException);
Assert.NotNull(ex.Message);
}
[Fact]
public static void CreateDelegate2()
{
E e;
e = (E)Delegate.CreateDelegate(typeof(E), new B(), "Execute");
Assert.NotNull(e);
Assert.Equal(4, e(new C()));
e = (E)Delegate.CreateDelegate(typeof(E), new C(), "Execute");
Assert.NotNull(e);
Assert.Equal(4, e(new C()));
e = (E)Delegate.CreateDelegate(typeof(E), new C(), "DoExecute");
Assert.NotNull(e);
Assert.Equal(102, e(new C()));
}
[Fact]
public static void CreateDelegate2_Method_ArgumentsMismatch()
{
ArgumentException ex = AssertExtensions.Throws<ArgumentException>(null, () => Delegate.CreateDelegate(typeof(E), new B(), "StartExecute"));
// Error binding to target method
Assert.Null(ex.InnerException);
Assert.NotNull(ex.Message);
}
[Fact]
public static void CreateDelegate2_Method_CaseMismatch()
{
ArgumentException ex = AssertExtensions.Throws<ArgumentException>(null, () => Delegate.CreateDelegate(typeof(E), new B(), "ExecutE"));
// Error binding to target method
Assert.Null(ex.InnerException);
Assert.NotNull(ex.Message);
}
[Fact]
public static void CreateDelegate2_Method_DoesNotExist()
{
ArgumentException ex = AssertExtensions.Throws<ArgumentException>(null, () => Delegate.CreateDelegate(typeof(E), new B(), "DoesNotExist"));
// Error binding to target method
Assert.Null(ex.InnerException);
Assert.NotNull(ex.Message);
}
[Fact]
public static void CreateDelegate2_Method_Null()
{
C c = new C();
ArgumentNullException ex = AssertExtensions.Throws<ArgumentNullException>("method", () => Delegate.CreateDelegate(typeof(D), c, (string)null));
Assert.Null(ex.InnerException);
Assert.NotNull(ex.Message);
}
[Fact]
public static void CreateDelegate2_Method_ReturnTypeMismatch()
{
ArgumentException ex = AssertExtensions.Throws<ArgumentException>(null, () => Delegate.CreateDelegate(typeof(E), new B(), "DoExecute"));
// Error binding to target method
Assert.Null(ex.InnerException);
Assert.NotNull(ex.Message);
}
[Fact]
public static void CreateDelegate2_Method_Static()
{
ArgumentException ex = AssertExtensions.Throws<ArgumentException>(null, () => Delegate.CreateDelegate(typeof(E), new B(), "Run"));
// Error binding to target method
Assert.Null(ex.InnerException);
Assert.NotNull(ex.Message);
}
[Fact]
public static void CreateDelegate2_Target_Null()
{
ArgumentNullException ex = AssertExtensions.Throws<ArgumentNullException>("target", () => Delegate.CreateDelegate(typeof(D), null, "N"));
Assert.Null(ex.InnerException);
Assert.NotNull(ex.Message);
}
[Fact]
public static void CreateDelegate2_Type_Null()
{
C c = new C();
ArgumentNullException ex = AssertExtensions.Throws<ArgumentNullException>("type", () => Delegate.CreateDelegate((Type)null, c, "N"));
Assert.Null(ex.InnerException);
Assert.NotNull(ex.Message);
}
[Fact]
public static void CreateDelegate3()
{
E e;
// matching static method
e = (E)Delegate.CreateDelegate(typeof(E), typeof(B), "Run");
Assert.NotNull(e);
Assert.Equal(5, e(new C()));
// matching static method
e = (E)Delegate.CreateDelegate(typeof(E), typeof(C), "Run");
Assert.NotNull(e);
Assert.Equal(5, e(new C()));
// matching static method
e = (E)Delegate.CreateDelegate(typeof(E), typeof(C), "DoRun");
Assert.NotNull(e);
Assert.Equal(107, e(new C()));
}
[Fact]
public static void CreateDelegate3_Method_ArgumentsMismatch()
{
ArgumentException ex = AssertExtensions.Throws<ArgumentException>(null, () => Delegate.CreateDelegate(typeof(E), typeof(B), "StartRun"));
// Error binding to target method
Assert.Null(ex.InnerException);
Assert.NotNull(ex.Message);
}
[Fact]
public static void CreateDelegate3_Method_CaseMismatch()
{
ArgumentException ex = AssertExtensions.Throws<ArgumentException>(null, () => Delegate.CreateDelegate(typeof(E), typeof(B), "RuN"));
// Error binding to target method
Assert.Null(ex.InnerException);
Assert.NotNull(ex.Message);
}
[Fact]
public static void CreateDelegate3_Method_DoesNotExist()
{
ArgumentException ex = AssertExtensions.Throws<ArgumentException>(null, () => Delegate.CreateDelegate(typeof(E), typeof(B), "DoesNotExist"));
// Error binding to target method
Assert.Null(ex.InnerException);
Assert.NotNull(ex.Message);
}
[Fact]
public static void CreateDelegate3_Method_Instance()
{
ArgumentException ex = AssertExtensions.Throws<ArgumentException>(null, () => Delegate.CreateDelegate(typeof(E), typeof(B), "Execute"));
// Error binding to target method
Assert.Null(ex.InnerException);
Assert.NotNull(ex.Message);
}
[Fact]
public static void CreateDelegate3_Method_Null()
{
ArgumentNullException ex = AssertExtensions.Throws<ArgumentNullException>("method", () => Delegate.CreateDelegate(typeof(D), typeof(C), (string)null));
Assert.Null(ex.InnerException);
Assert.NotNull(ex.Message);
}
[Fact]
public static void CreateDelegate3_Method_ReturnTypeMismatch()
{
ArgumentException ex = AssertExtensions.Throws<ArgumentException>(null, () => Delegate.CreateDelegate(typeof(E), typeof(B), "DoRun"));
// Error binding to target method
Assert.Null(ex.InnerException);
Assert.NotNull(ex.Message);
}
[Fact]
public static void CreateDelegate3_Target_Null()
{
ArgumentNullException ex = AssertExtensions.Throws<ArgumentNullException>("target", () => Delegate.CreateDelegate(typeof(D), (Type)null, "S"));
Assert.Null(ex.InnerException);
Assert.NotNull(ex.Message);
}
[Fact]
public static void CreateDelegate3_Type_Null()
{
ArgumentNullException ex = AssertExtensions.Throws<ArgumentNullException>("type", () => Delegate.CreateDelegate((Type)null, typeof(C), "S"));
Assert.Null(ex.InnerException);
Assert.NotNull(ex.Message);
}
[Fact]
public static void CreateDelegate4()
{
E e;
B b = new B();
// instance method, exact case, ignore case
e = (E)Delegate.CreateDelegate(typeof(E), b, "Execute", true);
Assert.NotNull(e);
Assert.Equal(4, e(new C()));
// instance method, exact case, do not ignore case
e = (E)Delegate.CreateDelegate(typeof(E), b, "Execute", false);
Assert.NotNull(e);
Assert.Equal(4, e(new C()));
// instance method, case mismatch, ignore case
e = (E)Delegate.CreateDelegate(typeof(E), b, "ExecutE", true);
Assert.NotNull(e);
Assert.Equal(4, e(new C()));
C c = new C();
// instance method, exact case, ignore case
e = (E)Delegate.CreateDelegate(typeof(E), c, "Execute", true);
Assert.NotNull(e);
Assert.Equal(4, e(new C()));
// instance method, exact case, ignore case
e = (E)Delegate.CreateDelegate(typeof(E), c, "DoExecute", true);
Assert.NotNull(e);
Assert.Equal(102, e(new C()));
// instance method, exact case, do not ignore case
e = (E)Delegate.CreateDelegate(typeof(E), c, "Execute", false);
Assert.NotNull(e);
Assert.Equal(4, e(new C()));
// instance method, case mismatch, ignore case
e = (E)Delegate.CreateDelegate(typeof(E), c, "ExecutE", true);
Assert.NotNull(e);
Assert.Equal(4, e(new C()));
}
[Fact]
public static void CreateDelegate4_Method_ArgumentsMismatch()
{
ArgumentException ex = AssertExtensions.Throws<ArgumentException>(null, () => Delegate.CreateDelegate(typeof(E), new B(), "StartExecute", false));
// Error binding to target method
Assert.Null(ex.InnerException);
Assert.NotNull(ex.Message);
}
[Fact]
public static void CreateDelegate4_Method_CaseMismatch()
{
// instance method, case mismatch, do not igore case
ArgumentException ex = AssertExtensions.Throws<ArgumentException>(null, () => Delegate.CreateDelegate(typeof(E), new B(), "ExecutE", false));
// Error binding to target method
Assert.Null(ex.InnerException);
Assert.NotNull(ex.Message);
}
[Fact]
public static void CreateDelegate4_Method_DoesNotExist()
{
ArgumentException ex = AssertExtensions.Throws<ArgumentException>(null, () => Delegate.CreateDelegate(typeof(E), new B(), "DoesNotExist", false));
// Error binding to target method
Assert.Null(ex.InnerException);
Assert.NotNull(ex.Message);
}
[Fact]
public static void CreateDelegate4_Method_Null()
{
ArgumentNullException ex = AssertExtensions.Throws<ArgumentNullException>("method", () => Delegate.CreateDelegate(typeof(D), new C(), (string)null, true));
Assert.Null(ex.InnerException);
Assert.NotNull(ex.Message);
}
[Fact]
public static void CreateDelegate4_Method_ReturnTypeMismatch()
{
ArgumentException ex = AssertExtensions.Throws<ArgumentException>(null, () => Delegate.CreateDelegate(typeof(E), new B(), "DoExecute", false));
// Error binding to target method
Assert.Null(ex.InnerException);
Assert.NotNull(ex.Message);
}
[Fact]
public static void CreateDelegate4_Method_Static()
{
ArgumentException ex = AssertExtensions.Throws<ArgumentException>(null, () => Delegate.CreateDelegate(typeof(E), new B(), "Run", true));
// Error binding to target method
Assert.Null(ex.InnerException);
Assert.NotNull(ex.Message);
}
[Fact]
public static void CreateDelegate4_Target_Null()
{
ArgumentNullException ex = AssertExtensions.Throws<ArgumentNullException>("target", () => Delegate.CreateDelegate(typeof(D), null, "N", true));
Assert.Null(ex.InnerException);
Assert.NotNull(ex.Message);
}
[Fact]
public static void CreateDelegate4_Type_Null()
{
C c = new C();
ArgumentNullException ex = AssertExtensions.Throws<ArgumentNullException>("type", () => Delegate.CreateDelegate((Type)null, c, "N", true));
Assert.Null(ex.InnerException);
Assert.NotNull(ex.Message);
}
[Fact]
public static void CreateDelegate9()
{
E e;
// do not ignore case, do not throw bind failure
e = (E)Delegate.CreateDelegate(typeof(E), new B(),
"Execute", false, false);
Assert.NotNull(e);
Assert.Equal(4, e(new C()));
// do not ignore case, throw bind failure
e = (E)Delegate.CreateDelegate(typeof(E), new B(),
"Execute", false, true);
Assert.NotNull(e);
Assert.Equal(4, e(new C()));
// ignore case, do not throw bind failure
e = (E)Delegate.CreateDelegate(typeof(E), new B(),
"Execute", true, false);
Assert.NotNull(e);
Assert.Equal(4, e(new C()));
// ignore case, throw bind failure
e = (E)Delegate.CreateDelegate(typeof(E), new B(),
"Execute", true, true);
Assert.NotNull(e);
Assert.Equal(4, e(new C()));
// do not ignore case, do not throw bind failure
e = (E)Delegate.CreateDelegate(typeof(E), new C(),
"Execute", false, false);
Assert.NotNull(e);
Assert.Equal(4, e(new C()));
// do not ignore case, throw bind failure
e = (E)Delegate.CreateDelegate(typeof(E), new C(),
"Execute", false, true);
Assert.NotNull(e);
Assert.Equal(4, e(new C()));
// ignore case, do not throw bind failure
e = (E)Delegate.CreateDelegate(typeof(E), new C(),
"Execute", true, false);
Assert.NotNull(e);
Assert.Equal(4, e(new C()));
// ignore case, throw bind failure
e = (E)Delegate.CreateDelegate(typeof(E), new C(),
"Execute", true, true);
Assert.NotNull(e);
Assert.Equal(4, e(new C()));
// do not ignore case, do not throw bind failure
e = (E)Delegate.CreateDelegate(typeof(E), new C(),
"DoExecute", false, false);
Assert.NotNull(e);
Assert.Equal(102, e(new C()));
// do not ignore case, throw bind failure
e = (E)Delegate.CreateDelegate(typeof(E), new C(),
"DoExecute", false, true);
Assert.NotNull(e);
Assert.Equal(102, e(new C()));
// ignore case, do not throw bind failure
e = (E)Delegate.CreateDelegate(typeof(E), new C(),
"DoExecute", true, false);
Assert.NotNull(e);
Assert.Equal(102, e(new C()));
// ignore case, throw bind failure
e = (E)Delegate.CreateDelegate(typeof(E), new C(),
"DoExecute", true, true);
Assert.NotNull(e);
Assert.Equal(102, e(new C()));
}
[Fact]
public static void CreateDelegate9_Method_ArgumentsMismatch()
{
// throw bind failure
ArgumentException ex = AssertExtensions.Throws<ArgumentException>(null, () => Delegate.CreateDelegate(typeof(E), new B(), "StartExecute", false, true));
// Error binding to target method
Assert.Null(ex.InnerException);
Assert.NotNull(ex.Message);
// do not throw on bind failure
E e = (E)Delegate.CreateDelegate(typeof(E), new B(),
"StartExecute", false, false);
Assert.Null(e);
}
[Fact]
public static void CreateDelegate9_Method_CaseMismatch()
{
E e;
// do not ignore case, throw bind failure
ArgumentException ex = AssertExtensions.Throws<ArgumentException>(null, () => Delegate.CreateDelegate(typeof(E), new B(), "ExecutE", false, true));
// Error binding to target method
Assert.Null(ex.InnerException);
Assert.NotNull(ex.Message);
// do not ignore case, do not throw bind failure
e = (E)Delegate.CreateDelegate(typeof(E), new B(),
"ExecutE", false, false);
Assert.Null(e);
// ignore case, throw bind failure
e = (E)Delegate.CreateDelegate(typeof(E), new B(),
"ExecutE", true, true);
Assert.NotNull(e);
Assert.Equal(4, e(new C()));
// ignore case, do not throw bind failure
e = (E)Delegate.CreateDelegate(typeof(E), new B(),
"ExecutE", true, false);
Assert.NotNull(e);
Assert.Equal(4, e(new C()));
}
[Fact]
public static void CreateDelegate9_Method_DoesNotExist()
{
// throw bind failure
ArgumentException ex = AssertExtensions.Throws<ArgumentException>(null, () => Delegate.CreateDelegate(typeof(E), new B(), "DoesNotExist", false, true));
// Error binding to target method
Assert.Null(ex.InnerException);
Assert.NotNull(ex.Message);
// do not throw on bind failure
E e = (E)Delegate.CreateDelegate(typeof(E), new B(),
"DoesNotExist", false, false);
Assert.Null(e);
}
[Fact]
public static void CreateDelegate9_Method_Null()
{
ArgumentNullException ex = AssertExtensions.Throws<ArgumentNullException>("method", () => Delegate.CreateDelegate(typeof(E), new B(), (string)null, false, false));
Assert.Null(ex.InnerException);
Assert.NotNull(ex.Message);
}
[Fact]
public static void CreateDelegate9_Method_ReturnTypeMismatch()
{
// throw bind failure
ArgumentException ex = AssertExtensions.Throws<ArgumentException>(null, () => Delegate.CreateDelegate(typeof(E), new B(), "DoExecute", false, true));
// Error binding to target method
Assert.Null(ex.InnerException);
Assert.NotNull(ex.Message);
// do not throw on bind failure
E e = (E)Delegate.CreateDelegate(typeof(E), new B(),
"DoExecute", false, false);
Assert.Null(e);
}
[Fact]
public static void CreateDelegate9_Method_Static()
{
// throw bind failure
ArgumentException ex = AssertExtensions.Throws<ArgumentException>(null, () => Delegate.CreateDelegate(typeof(E), new B(), "Run", true, true));
// Error binding to target method
Assert.Null(ex.InnerException);
Assert.NotNull(ex.Message);
// do not throw on bind failure
E e = (E)Delegate.CreateDelegate(typeof(E), new B(),
"Run", true, false);
Assert.Null(e);
}
[Fact]
public static void CreateDelegate9_Target_Null()
{
ArgumentNullException ex = AssertExtensions.Throws<ArgumentNullException>("target", () => Delegate.CreateDelegate(typeof(E), (object)null, "Execute", true, false));
Assert.Null(ex.InnerException);
Assert.NotNull(ex.Message);
}
[Fact]
public static void CreateDelegate9_Type_Null()
{
ArgumentNullException ex = AssertExtensions.Throws<ArgumentNullException>("type", () => Delegate.CreateDelegate((Type)null, new B(), "Execute", true, false));
Assert.Null(ex.InnerException);
Assert.NotNull(ex.Message);
}
#endregion Tests
#region Test Setup
public class B
{
public virtual string retarg3(string s)
{
return s;
}
static int Run(C x)
{
return 5;
}
public static void DoRun(C x)
{
}
public static int StartRun(C x, B b)
{
return 6;
}
int Execute(C c)
{
return 4;
}
public static void DoExecute(C c)
{
}
public int StartExecute(C c, B b)
{
return 3;
}
}
public class C : B, Iface
{
public string retarg(string s)
{
return s;
}
public string retarg2(Iface iface, string s)
{
return s + "2";
}
public override string retarg3(string s)
{
return s + "2";
}
static void Run(C x)
{
}
public new static int DoRun(C x)
{
return 107;
}
void Execute(C c)
{
}
public new int DoExecute(C c)
{
return 102;
}
public static void M()
{
}
public static void N(C c)
{
}
public static void S(C c)
{
}
private void PrivateInstance()
{
}
}
public interface Iface
{
string retarg(string s);
}
public delegate void D(C c);
public delegate int E(C c);
#endregion Test Setup
}
}
| |
using System;
using System.Linq;
using NetGore.Audio;
using SFML.Graphics;
namespace NetGore.Graphics.GUI
{
/// <summary>
/// Base of a game screen for the <see cref="ScreenManager"/>. Each screen should ideally be independent of
/// one another.
/// </summary>
public abstract class GameScreen : IGameScreen
{
readonly IGUIManager _guiManager;
readonly string _name;
readonly IScreenManager _screenManager;
bool _playMusic = true;
IMusicInfo _screenMusic;
/// <summary>
/// Initializes a new instance of the <see cref="GameScreen"/> class.
/// </summary>
/// <param name="screenManager">The <see cref="IScreenManager"/> to add this <see cref="GameScreen"/> to.</param>
/// <param name="name">Unique name of the screen that can be used to identify and
/// call it from other screens</param>
/// <exception cref="ArgumentNullException"><paramref name="screenManager"/> is null.</exception>
/// <exception cref="ArgumentNullException"><paramref name="name"/> is null or empty.</exception>
protected GameScreen(IScreenManager screenManager, string name)
{
if (screenManager == null)
throw new ArgumentNullException("screenManager");
if (string.IsNullOrEmpty(name))
throw new ArgumentNullException("name");
_screenManager = screenManager;
_name = name;
var font = GetScreenManagerFont(ScreenManager) ?? screenManager.DefaultFont;
_guiManager = ScreenManager.CreateGUIManager(font);
screenManager.Add(this);
}
/// <summary>
/// Gets the <see cref="Font"/> to use as the default font for the <see cref="IGUIManager"/> for this
/// <see cref="GameScreen"/>.
/// </summary>
/// <param name="screenManager">The <see cref="IScreenManager"/> for this screen.</param>
/// <returns>The <see cref="Font"/> to use for this <see cref="GameScreen"/>. If null, the
/// <see cref="IScreenManager.DefaultFont"/> for this <see cref="GameScreen"/> will be used instead.</returns>
protected virtual Font GetScreenManagerFont(IScreenManager screenManager)
{
return screenManager.DefaultFont;
}
/// <summary>
/// Updates the currently playing music based off the values defined by <see cref="GameScreen.PlayMusic"/>
/// and <see cref="GameScreen.ScreenMusic"/>.
/// </summary>
void UpdateMusic()
{
// Make sure we have the screen enabled
if (ScreenManager == null || ScreenManager.ActiveNonConsoleScreen != this)
return;
// Turn off music
if (!PlayMusic)
{
MusicManager.Stop();
return;
}
// Change track
if (ScreenMusic != null)
ScreenManager.AudioManager.MusicManager.Play(ScreenMusic);
}
#region IGameScreen Members
/// <summary>
/// Gets the <see cref="IDrawingManager"/> that is used to help draw on this screen.
/// </summary>
public IDrawingManager DrawingManager
{
get { return ScreenManager.DrawingManager; }
}
/// <summary>
/// Gets the <see cref="IGUIManager"/> that is used for the GUI of this <see cref="IGameScreen"/>.
/// </summary>
public IGUIManager GUIManager
{
get { return _guiManager; }
}
/// <summary>
/// Gets the <see cref="IMusicManager"/> to use for the music to play on this <see cref="IGameScreen"/>.
/// </summary>
public IMusicManager MusicManager
{
get { return ScreenManager.AudioManager.MusicManager; }
}
/// <summary>
/// Gets the unique name of this screen.
/// </summary>
public string Name
{
get { return _name; }
}
/// <summary>
/// Gets or sets if music is to be played during this screen. If true, the <see cref="IMusicInfo"/> specified
/// in <see cref="IGameScreen.ScreenMusic"/> will be played. If false, any music will be turned off while this
/// screen is active.
/// </summary>
public bool PlayMusic
{
get { return _playMusic; }
set
{
// Value changed?
if (_playMusic == value)
return;
// Update value and update music
_playMusic = value;
UpdateMusic();
}
}
/// <summary>
/// Gets the <see cref="IScreenManager"/> that manages this <see cref="IGameScreen"/>.
/// </summary>
public IScreenManager ScreenManager
{
get { return _screenManager; }
}
/// <summary>
/// Gets or sets the <see cref="IMusicInfo"/> of the music to play while this screen is active. Only valid if
/// <see cref="IGameScreen.PlayMusic"/> is set. If null, the track will not be changed, preserving the music
/// currently playing.
/// </summary>
public IMusicInfo ScreenMusic
{
get { return _screenMusic; }
set
{
// Value changed?
if (_screenMusic == value)
return;
// Update value and update music
_screenMusic = value;
UpdateMusic();
}
}
/// <summary>
/// Gets the <see cref="ISoundManager"/> to use for the sound to play on this <see cref="IGameScreen"/>.
/// </summary>
public ISoundManager SoundManager
{
get { return ScreenManager.AudioManager.SoundManager; }
}
/// <summary>
/// Handles screen activation, which occurs every time the screen becomes the current
/// active screen. Objects in here often will want to be destroyed on <see cref="GameScreen.Deactivate"/>().
/// </summary>
public virtual void Activate()
{
UpdateMusic();
GUIManager.IsEnabled = true;
}
/// <summary>
/// Handles screen deactivation, which occurs every time the screen changes from being
/// the current active screen. Good place to clean up any objects created in <see cref="GameScreen.Activate"/>().
/// </summary>
public virtual void Deactivate()
{
GUIManager.IsEnabled = false;
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
public virtual void Dispose()
{
}
/// <summary>
/// Handles drawing of the screen. The ScreenManager already provides a GraphicsDevice.Clear() so
/// there is often no need to clear the screen. This will only be called while the screen is the
/// active screen.
/// </summary>
/// <param name="gameTime">The current game time.</param>
public virtual void Draw(TickCount gameTime)
{
var spriteBatch = DrawingManager.BeginDrawGUI();
if (spriteBatch == null)
return;
GUIManager.Draw(spriteBatch);
DrawingManager.EndDrawGUI();
}
/// <summary>
/// Handles initialization of the GameScreen. This will be invoked after the GameScreen has been
/// completely and successfully added to the ScreenManager. It is highly recommended that you
/// use this instead of the constructor. This is invoked only once.
/// </summary>
public virtual void Initialize()
{
}
/// <summary>
/// Handles the loading of game content. Any content that is loaded should be placed in here.
/// This will be invoked once (right after Initialize()), along with any time the content needs
/// to be reloaded for whatever reason.
/// </summary>
public virtual void LoadContent()
{
}
/// <summary>
/// Handles the unloading of game content. This is raised whenever the content for this screen
/// needs to be unloaded. All content loaded in <see cref="IGameScreen.LoadContent"/> should
/// be unloaded here to ensure complete and proper disposal.
/// </summary>
public virtual void UnloadContent()
{
}
/// <summary>
/// Updates the screen if it is currently the active screen.
/// </summary>
/// <param name="gameTime">The current game time.</param>
public virtual void Update(TickCount gameTime)
{
GUIManager.Update(gameTime);
}
#endregion
}
}
| |
/*
* 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
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Security;
using System.Text.RegularExpressions;
using System.Threading;
using Apache.Ignite.Core.Binary;
using Apache.Ignite.Core.Cache;
using Apache.Ignite.Core.Cache.Store;
using Apache.Ignite.Core.Cluster;
using Apache.Ignite.Core.Common;
using Apache.Ignite.Core.Compute;
using Apache.Ignite.Core.Impl.Binary;
using Apache.Ignite.Core.Services;
using Apache.Ignite.Core.Transactions;
/// <summary>
/// Managed environment. Acts as a gateway for native code.
/// </summary>
internal static class ExceptionUtils
{
/** NoClassDefFoundError fully-qualified class name which is important during startup phase. */
private const string ClsNoClsDefFoundErr = "java.lang.NoClassDefFoundError";
/** NoSuchMethodError fully-qualified class name which is important during startup phase. */
private const string ClsNoSuchMthdErr = "java.lang.NoSuchMethodError";
/** InteropCachePartialUpdateException. */
private const string ClsCachePartialUpdateErr = "org.apache.ignite.internal.processors.platform.cache.PlatformCachePartialUpdateException";
/** Map with predefined exceptions. */
private static readonly IDictionary<string, ExceptionFactory> Exs = new Dictionary<string, ExceptionFactory>();
/** Inner class regex. */
private static readonly Regex InnerClassRegex = new Regex(@"class ([^\s]+): (.*)", RegexOptions.Compiled);
/// <summary>
/// Static initializer.
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1810:InitializeReferenceTypeStaticFieldsInline",
Justification = "Readability")]
static ExceptionUtils()
{
// Common Java exceptions mapped to common .NET exceptions.
Exs["java.lang.IllegalArgumentException"] = (c, m, e, i) => new ArgumentException(m, e);
Exs["java.lang.IllegalStateException"] = (c, m, e, i) => new InvalidOperationException(m, e);
Exs["java.lang.UnsupportedOperationException"] = (c, m, e, i) => new NotSupportedException(m, e);
Exs["java.lang.InterruptedException"] = (c, m, e, i) => new ThreadInterruptedException(m, e);
// Generic Ignite exceptions.
Exs["org.apache.ignite.IgniteException"] = (c, m, e, i) => new IgniteException(m, e);
Exs["org.apache.ignite.IgniteCheckedException"] = (c, m, e, i) => new IgniteException(m, e);
Exs["org.apache.ignite.IgniteClientDisconnectedException"] = (c, m, e, i) => new ClientDisconnectedException(m, e, i.GetCluster().ClientReconnectTask);
Exs["org.apache.ignite.internal.IgniteClientDisconnectedCheckedException"] = (c, m, e, i) => new ClientDisconnectedException(m, e, i.GetCluster().ClientReconnectTask);
Exs["org.apache.ignite.binary.BinaryObjectException"] = (c, m, e, i) => new BinaryObjectException(m, e);
// Cluster exceptions.
Exs["org.apache.ignite.cluster.ClusterGroupEmptyException"] = (c, m, e, i) => new ClusterGroupEmptyException(m, e);
Exs["org.apache.ignite.internal.cluster.ClusterGroupEmptyCheckedException"] = (c, m, e, i) => new ClusterGroupEmptyException(m, e);
Exs["org.apache.ignite.cluster.ClusterTopologyException"] = (c, m, e, i) => new ClusterTopologyException(m, e);
// Compute exceptions.
Exs["org.apache.ignite.compute.ComputeExecutionRejectedException"] = (c, m, e, i) => new ComputeExecutionRejectedException(m, e);
Exs["org.apache.ignite.compute.ComputeJobFailoverException"] = (c, m, e, i) => new ComputeJobFailoverException(m, e);
Exs["org.apache.ignite.compute.ComputeTaskCancelledException"] = (c, m, e, i) => new ComputeTaskCancelledException(m, e);
Exs["org.apache.ignite.compute.ComputeTaskTimeoutException"] = (c, m, e, i) => new ComputeTaskTimeoutException(m, e);
Exs["org.apache.ignite.compute.ComputeUserUndeclaredException"] = (c, m, e, i) => new ComputeUserUndeclaredException(m, e);
// Cache exceptions.
Exs["javax.cache.CacheException"] = (c, m, e, i) => new CacheException(m, e);
Exs["javax.cache.integration.CacheLoaderException"] = (c, m, e, i) => new CacheStoreException(m, e);
Exs["javax.cache.integration.CacheWriterException"] = (c, m, e, i) => new CacheStoreException(m, e);
Exs["javax.cache.processor.EntryProcessorException"] = (c, m, e, i) => new CacheEntryProcessorException(m, e);
Exs["org.apache.ignite.cache.CacheAtomicUpdateTimeoutException"] = (c, m, e, i) => new CacheAtomicUpdateTimeoutException(m, e);
// Transaction exceptions.
Exs["org.apache.ignite.transactions.TransactionOptimisticException"] = (c, m, e, i) => new TransactionOptimisticException(m, e);
Exs["org.apache.ignite.transactions.TransactionTimeoutException"] = (c, m, e, i) => new TransactionTimeoutException(m, e);
Exs["org.apache.ignite.transactions.TransactionRollbackException"] = (c, m, e, i) => new TransactionRollbackException(m, e);
Exs["org.apache.ignite.transactions.TransactionHeuristicException"] = (c, m, e, i) => new TransactionHeuristicException(m, e);
Exs["org.apache.ignite.transactions.TransactionDeadlockException"] = (c, m, e, i) => new TransactionDeadlockException(m, e);
// Security exceptions.
Exs["org.apache.ignite.IgniteAuthenticationException"] = (c, m, e, i) => new SecurityException(m, e);
Exs["org.apache.ignite.plugin.security.GridSecurityException"] = (c, m, e, i) => new SecurityException(m, e);
// Future exceptions.
Exs["org.apache.ignite.lang.IgniteFutureCancelledException"] = (c, m, e, i) => new IgniteFutureCancelledException(m, e);
Exs["org.apache.ignite.internal.IgniteFutureCancelledCheckedException"] = (c, m, e, i) => new IgniteFutureCancelledException(m, e);
// Service exceptions.
Exs["org.apache.ignite.services.ServiceDeploymentException"] = (c, m, e, i) => new ServiceDeploymentException(m, e);
}
/// <summary>
/// Creates exception according to native code class and message.
/// </summary>
/// <param name="igniteInt">The ignite.</param>
/// <param name="clsName">Exception class name.</param>
/// <param name="msg">Exception message.</param>
/// <param name="stackTrace">Native stack trace.</param>
/// <param name="reader">Error data reader.</param>
/// <param name="innerException">Inner exception.</param>
/// <returns>Exception.</returns>
public static Exception GetException(IIgniteInternal igniteInt, string clsName, string msg, string stackTrace,
BinaryReader reader = null, Exception innerException = null)
{
// Set JavaException as immediate inner.
innerException = new JavaException(clsName, msg, stackTrace, innerException);
var ignite = igniteInt == null ? null : igniteInt.GetIgnite();
ExceptionFactory ctor;
if (Exs.TryGetValue(clsName, out ctor))
{
var match = InnerClassRegex.Match(msg ?? string.Empty);
ExceptionFactory innerCtor;
if (match.Success && Exs.TryGetValue(match.Groups[1].Value, out innerCtor))
{
return ctor(clsName, msg,
innerCtor(match.Groups[1].Value, match.Groups[2].Value, innerException, ignite),
ignite);
}
return ctor(clsName, msg, innerException, ignite);
}
if (ClsNoClsDefFoundErr.Equals(clsName, StringComparison.OrdinalIgnoreCase))
return new IgniteException("Java class is not found (did you set IGNITE_HOME environment " +
"variable?): " + msg, innerException);
if (ClsNoSuchMthdErr.Equals(clsName, StringComparison.OrdinalIgnoreCase))
return new IgniteException("Java class method is not found (did you set IGNITE_HOME environment " +
"variable?): " + msg, innerException);
if (ClsCachePartialUpdateErr.Equals(clsName, StringComparison.OrdinalIgnoreCase))
return ProcessCachePartialUpdateException(igniteInt, msg, stackTrace, reader);
// Predefined mapping not found - check plugins.
if (igniteInt != null && igniteInt.PluginProcessor != null)
{
ctor = igniteInt.PluginProcessor.GetExceptionMapping(clsName);
if (ctor != null)
{
return ctor(clsName, msg, innerException, ignite);
}
}
// Return default exception.
return new IgniteException(string.Format("Java exception occurred [class={0}, message={1}]", clsName, msg),
innerException);
}
/// <summary>
/// Process cache partial update exception.
/// </summary>
/// <param name="ignite">The ignite.</param>
/// <param name="msg">Message.</param>
/// <param name="stackTrace">Stack trace.</param>
/// <param name="reader">Reader.</param>
/// <returns>CachePartialUpdateException.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
private static Exception ProcessCachePartialUpdateException(IIgniteInternal ignite, string msg,
string stackTrace, BinaryReader reader)
{
if (reader == null)
return new CachePartialUpdateException(msg, new IgniteException("Failed keys are not available."));
bool dataExists = reader.ReadBoolean();
Debug.Assert(dataExists);
if (reader.ReadBoolean())
{
bool keepBinary = reader.ReadBoolean();
BinaryReader keysReader = reader.Marshaller.StartUnmarshal(reader.Stream, keepBinary);
try
{
return new CachePartialUpdateException(msg, ReadNullableList(keysReader));
}
catch (Exception e)
{
// Failed to deserialize data.
return new CachePartialUpdateException(msg, e);
}
}
// Was not able to write keys.
string innerErrCls = reader.ReadString();
string innerErrMsg = reader.ReadString();
Exception innerErr = GetException(ignite, innerErrCls, innerErrMsg, stackTrace);
return new CachePartialUpdateException(msg, innerErr);
}
/// <summary>
/// Create JVM initialization exception.
/// </summary>
/// <param name="clsName">Class name.</param>
/// <param name="msg">Message.</param>
/// <param name="stackTrace">Stack trace.</param>
/// <returns>Exception.</returns>
[ExcludeFromCodeCoverage] // Covered by a test in a separate process.
public static Exception GetJvmInitializeException(string clsName, string msg, string stackTrace)
{
if (clsName != null)
return new IgniteException("Failed to initialize JVM.", GetException(null, clsName, msg, stackTrace));
if (msg != null)
return new IgniteException("Failed to initialize JVM: " + msg + "\n" + stackTrace);
return new IgniteException("Failed to initialize JVM.");
}
/// <summary>
/// Reads nullable list.
/// </summary>
/// <param name="reader">Reader.</param>
/// <returns>List.</returns>
private static List<object> ReadNullableList(BinaryReader reader)
{
if (!reader.ReadBoolean())
return null;
var size = reader.ReadInt();
var list = new List<object>(size);
for (int i = 0; i < size; i++)
list.Add(reader.ReadObject<object>());
return list;
}
}
}
| |
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 SocialNetwork.Services.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 UnityEngine;
using UnityEngine.Serialization;
using System.Collections.Generic;
#if UNITY_EDITOR
using UnityEditor;
public class SgtPointStarfield_Editor<T> : SgtQuads_Editor<T>
where T : SgtPointStarfield
{
protected void DrawPointMaterial(ref bool updateMaterial)
{
DrawDefault("Softness", ref updateMaterial);
if (Any(t => t.Softness > 0.0f))
{
foreach (var camera in Camera.allCameras)
{
if (SgtHelper.Enabled(camera) == true && camera.depthTextureMode == DepthTextureMode.None)
{
if ((camera.cullingMask & (1 << Target.gameObject.layer)) != 0)
{
if (HelpButton("You have enabled soft particles, but the '" + camera.name + "' camera does not write depth textures.", MessageType.Error, "Fix", 50.0f) == true)
{
var dtm = SgtHelper.GetOrAddComponent<SgtDepthTextureMode>(camera.gameObject);
dtm.DepthMode = DepthTextureMode.Depth;
dtm.UpdateDepthMode();
Selection.activeObject = dtm;
}
}
}
}
}
Separator();
DrawDefault("FollowCameras", ref updateMaterial);
if (Any(t => t.FollowCameras == true && t.Wrap == true))
{
EditorGUILayout.HelpBox("This setting shouldn't be used with 'Wrap'", MessageType.Warning);
}
DrawDefault("Wrap", ref updateMaterial);
if (Any(t => t.Wrap == true))
{
BeginIndent();
BeginError(Any(t => t.WrapSize.x == 0.0f || t.WrapSize.y == 0.0f || t.WrapSize.z == 0.0f));
DrawDefault("WrapSize", ref updateMaterial);
EndError();
EndIndent();
}
DrawDefault("FadeNear", ref updateMaterial);
if (Any(t => t.FadeNear == true))
{
BeginIndent();
BeginError(Any(t => t.FadeNearTex == null));
DrawDefault("FadeNearTex", ref updateMaterial);
EndError();
BeginError(Any(t => t.FadeNearRadius < 0.0f));
DrawDefault("FadeNearRadius", ref updateMaterial);
EndError();
BeginError(Any(t => t.FadeNearThickness <= 0.0f));
DrawDefault("FadeNearThickness", ref updateMaterial);
EndError();
EndIndent();
}
DrawDefault("FadeFar", ref updateMaterial);
if (Any(t => t.FadeFar == true))
{
BeginIndent();
BeginError(Any(t => t.FadeFarTex == null));
DrawDefault("FadeFarTex", ref updateMaterial);
EndError();
BeginError(Any(t => t.FadeFarRadius < 0.0f));
DrawDefault("FadeFarRadius", ref updateMaterial);
EndError();
BeginError(Any(t => t.FadeFarThickness <= 0.0f));
DrawDefault("FadeFarThickness", ref updateMaterial);
EndError();
EndIndent();
}
DrawDefault("Stretch", ref updateMaterial);
if (Any(t => t.Stretch == true))
{
BeginIndent();
DrawDefault("StretchVector", ref updateMaterial);
BeginError(Any(t => t.StretchScale < 0.0f));
DrawDefault("StretchScale", ref updateMaterial);
EndError();
EndIndent();
}
DrawDefault("Pulse", ref updateMaterial);
if (Any(t => t.Pulse == true))
{
BeginIndent();
DrawDefault("PulseOffset");
BeginError(Any(t => t.PulseSpeed == 0.0f));
DrawDefault("PulseSpeed");
EndError();
EndIndent();
}
if (Any(t => t.FadeNear == true && t.FadeNearTex == null && t.GetComponent<SgtStarfieldFadeNear>() == null))
{
Separator();
if (Button("Add Fade Near") == true)
{
Each(t => SgtHelper.GetOrAddComponent<SgtStarfieldFadeNear>(t.gameObject));
}
}
if (Any(t => t.FadeFar == true && t.FadeFarTex == null && t.GetComponent<SgtStarfieldFadeFar>() == null))
{
Separator();
if (Button("Add Fade Far") == true)
{
Each(t => SgtHelper.GetOrAddComponent<SgtStarfieldFadeFar>(t.gameObject));
}
}
}
}
#endif
// This is the base class for all starfields that store star corner vertices the same point/location
// and are stretched out in the vertex shader, allowing billboarding in view space, and dynamic resizing
public abstract class SgtPointStarfield : SgtQuads
{
[Tooltip("Should the stars automatically be placed on top of the currently rendering camera?")]
[FormerlySerializedAs("FollowObservers")]
public bool FollowCameras;
[Tooltip("Should the stars fade out if they're intersecting solid geometry?")]
[Range(0.0f, 1000.0f)]
public float Softness;
[Tooltip("Should the stars wrap around the camera if they get too far away?")]
public bool Wrap;
[Tooltip("The size of the wrapped area")]
public Vector3 WrapSize = Vector3.one;
[Tooltip("Should the stars stretch if an observer moves?")]
[FormerlySerializedAs("StretchToObservers")]
public bool Stretch;
[Tooltip("The vector of the stretching")]
public Vector3 StretchVector;
[Tooltip("The scale of the stretching relative to the velocity")]
public float StretchScale = 1.0f;
[Tooltip("Should the stars fade out when the camera gets near?")]
public bool FadeNear;
[Tooltip("The lookup table used to calculate the fading amount based on the distance")]
public Texture FadeNearTex;
[Tooltip("The radius of the fading effect in world coordinates")]
public float FadeNearRadius = 2.0f;
[Tooltip("The thickness of the fading effect in local coordinates")]
public float FadeNearThickness = 2.0f;
[Tooltip("Should the stars fade out when the camera gets too far away?")]
public bool FadeFar;
[Tooltip("The lookup table used to calculate the fading amount based on the distance")]
public Texture FadeFarTex;
[Tooltip("The radius of the fading effect in world coordinates")]
public float FadeFarRadius = 2.0f;
[Tooltip("The thickness of the fading effect in world coordinates")]
public float FadeFarThickness = 2.0f;
[Tooltip("Should the stars pulse in size over time?")]
[FormerlySerializedAs("AllowPulse")]
public bool Pulse;
[Tooltip("The amount of seconds this starfield has been animating")]
[FormerlySerializedAs("Age")]
public float PulseOffset;
[Tooltip("The animation speed of this starfield")]
[FormerlySerializedAs("TimeScale")]
public float PulseSpeed = 1.0f;
protected override string ShaderName
{
get
{
return SgtHelper.ShaderNamePrefix + "PointStarfield";
}
}
public void UpdateFadeFarTex()
{
if (Material != null)
{
Material.SetTexture("_FadeFarTex", FadeFarTex);
}
}
public void UpdateFadeNearTex()
{
if (Material != null)
{
Material.SetTexture("_FadeNearTex", FadeNearTex);
}
}
public SgtCustomStarfield MakeEditableCopy(int layer, Transform parent, Vector3 localPosition, Quaternion localRotation, Vector3 localScale)
{
#if UNITY_EDITOR
SgtHelper.BeginUndo("Create Editable Starfield Copy");
#endif
var gameObject = SgtHelper.CreateGameObject("Editable Starfield Copy", layer, parent, localPosition, localRotation, localScale);
var customStarfield = SgtHelper.AddComponent<SgtCustomStarfield>(gameObject, false);
var quads = new List<SgtPointStar>();
var starCount = BeginQuads();
for (var i = 0; i < starCount; i++)
{
var quad = SgtClassPool<SgtPointStar>.Pop() ?? new SgtPointStar();
NextQuad(ref quad, i);
quads.Add(quad);
}
EndQuads();
// Copy common settings
customStarfield.Color = Color;
customStarfield.Brightness = Brightness;
customStarfield.MainTex = MainTex;
customStarfield.Layout = Layout;
customStarfield.LayoutColumns = LayoutColumns;
customStarfield.LayoutRows = LayoutRows;
customStarfield.RenderQueue = RenderQueue;
customStarfield.RenderQueueOffset = RenderQueueOffset;
customStarfield.FollowCameras = FollowCameras;
customStarfield.Softness = Softness;
customStarfield.Wrap = Wrap;
customStarfield.WrapSize = WrapSize;
customStarfield.Stretch = Stretch;
customStarfield.StretchVector = StretchVector;
customStarfield.StretchScale = StretchScale;
customStarfield.FadeNear = FadeNear;
customStarfield.FadeNearRadius = FadeNearRadius;
customStarfield.FadeNearThickness = FadeNearThickness;
customStarfield.FadeNearTex = FadeNearTex;
customStarfield.FadeFar = FadeFar;
customStarfield.FadeFarRadius = FadeFarRadius;
customStarfield.FadeFarThickness = FadeFarThickness;
customStarfield.FadeFarTex = FadeFarTex;
customStarfield.Pulse = Pulse;
customStarfield.PulseOffset = PulseOffset;
customStarfield.PulseSpeed = PulseSpeed;
// Copy custom settings
customStarfield.Stars = quads;
// Update
customStarfield.UpdateMaterial();
customStarfield.UpdateMeshesAndModels();
return customStarfield;
}
public SgtCustomStarfield MakeEditableCopy(int layer = 0, Transform parent = null)
{
return MakeEditableCopy(layer, parent, Vector3.zero, Quaternion.identity, Vector3.one);
}
#if UNITY_EDITOR
[ContextMenu("Make Editable Copy")]
public void MakeEditableCopyContext()
{
var customStarfield = MakeEditableCopy(gameObject.layer, transform.parent, transform.localPosition, transform.localRotation, transform.localScale);
SgtHelper.SelectAndPing(customStarfield);
}
#endif
protected override void OnEnable()
{
Camera.onPreCull += CameraPreCull;
Camera.onPreRender += CameraPreRender;
Camera.onPostRender += CameraPostRender;
base.OnEnable();
}
protected virtual void LateUpdate()
{
if (Application.isPlaying == true)
{
PulseOffset += Time.deltaTime * PulseSpeed;
}
if (Material != null)
{
if (Pulse == true)
{
Material.SetFloat("_PulseOffset", PulseOffset);
}
}
}
protected override void OnDisable()
{
Camera.onPreCull -= CameraPreCull;
Camera.onPreRender -= CameraPreRender;
Camera.onPostRender -= CameraPostRender;
base.OnDisable();
}
#if UNITY_EDITOR
protected virtual void OnDrawGizmosSelected()
{
if (Wrap == true)
{
Gizmos.matrix = transform.localToWorldMatrix;
Gizmos.DrawWireCube(Vector3.zero, WrapSize);
}
}
#endif
protected override void BuildMaterial()
{
base.BuildMaterial();
if (Wrap == true)
{
SgtHelper.EnableKeyword("SGT_B", Material); // Wrap
Material.SetVector("_WrapSize", WrapSize);
Material.SetVector("_WrapSizeRecip", SgtHelper.Reciprocal3(WrapSize));
}
else
{
SgtHelper.DisableKeyword("SGT_B", Material); // Wrap
}
if (Stretch == true)
{
SgtHelper.EnableKeyword("SGT_C", Material); // Stretch
}
else
{
SgtHelper.DisableKeyword("SGT_C", Material); // Stretch
}
if (FadeNear == true)
{
SgtHelper.EnableKeyword("SGT_D", Material); // Fade near
Material.SetTexture("_FadeNearTex", FadeNearTex);
Material.SetFloat("_FadeNearRadius", FadeNearRadius);
Material.SetFloat("_FadeNearScale", SgtHelper.Reciprocal(FadeNearThickness));
}
else
{
SgtHelper.DisableKeyword("SGT_D", Material); // Fade near
}
if (FadeFar == true)
{
SgtHelper.EnableKeyword("SGT_E", Material); // Fade far
Material.SetTexture("_FadeFarTex", FadeFarTex);
Material.SetFloat("_FadeFarRadius", FadeFarRadius);
Material.SetFloat("_FadeFarScale", SgtHelper.Reciprocal(FadeFarThickness));
}
else
{
SgtHelper.DisableKeyword("SGT_E", Material); // Fade far
}
if (Pulse == true)
{
SgtHelper.EnableKeyword("LIGHT_1", Material); // Pulse
// This is also set in Update
Material.SetFloat("_PulseOffset", PulseOffset);
}
else
{
SgtHelper.DisableKeyword("LIGHT_1", Material); // Pulse
}
if (Softness > 0.0f)
{
SgtHelper.EnableKeyword("LIGHT_2", Material); // Softness
Material.SetFloat("_InvFade", SgtHelper.Reciprocal(Softness));
}
else
{
SgtHelper.DisableKeyword("LIGHT_2", Material); // Softness
}
}
protected abstract void NextQuad(ref SgtPointStar quad, int starIndex);
protected override void BuildMesh(Mesh mesh, int starIndex, int starCount)
{
var positions = new Vector3[starCount * 4];
var colors = new Color[starCount * 4];
var normals = new Vector3[starCount * 4];
var tangents = new Vector4[starCount * 4];
var coords1 = new Vector2[starCount * 4];
var coords2 = new Vector2[starCount * 4];
var indices = new int[starCount * 6];
var minMaxSet = false;
var min = default(Vector3);
var max = default(Vector3);
for (var i = 0; i < starCount; i++)
{
NextQuad(ref SgtPointStar.Temp, starIndex + i);
var offV = i * 4;
var offI = i * 6;
var position = SgtPointStar.Temp.Position;
var radius = SgtPointStar.Temp.Radius;
var angle = Mathf.Repeat(SgtPointStar.Temp.Angle / 180.0f, 2.0f) - 1.0f;
var uv = tempCoords[SgtHelper.Mod(SgtPointStar.Temp.Variant, tempCoords.Count)];
ExpandBounds(ref minMaxSet, ref min, ref max, position, radius);
positions[offV + 0] =
positions[offV + 1] =
positions[offV + 2] =
positions[offV + 3] = position;
colors[offV + 0] =
colors[offV + 1] =
colors[offV + 2] =
colors[offV + 3] = SgtPointStar.Temp.Color;
normals[offV + 0] = new Vector3(-1.0f, 1.0f, angle);
normals[offV + 1] = new Vector3( 1.0f, 1.0f, angle);
normals[offV + 2] = new Vector3(-1.0f, -1.0f, angle);
normals[offV + 3] = new Vector3( 1.0f, -1.0f, angle);
tangents[offV + 0] =
tangents[offV + 1] =
tangents[offV + 2] =
tangents[offV + 3] = new Vector4(SgtPointStar.Temp.PulseOffset, SgtPointStar.Temp.PulseSpeed, SgtPointStar.Temp.PulseRange, 0.0f);
coords1[offV + 0] = new Vector2(uv.x, uv.y);
coords1[offV + 1] = new Vector2(uv.z, uv.y);
coords1[offV + 2] = new Vector2(uv.x, uv.w);
coords1[offV + 3] = new Vector2(uv.z, uv.w);
coords2[offV + 0] = new Vector2(radius, 0.5f);
coords2[offV + 1] = new Vector2(radius, -0.5f);
coords2[offV + 2] = new Vector2(radius, 0.5f);
coords2[offV + 3] = new Vector2(radius, -0.5f);
indices[offI + 0] = offV + 0;
indices[offI + 1] = offV + 1;
indices[offI + 2] = offV + 2;
indices[offI + 3] = offV + 3;
indices[offI + 4] = offV + 2;
indices[offI + 5] = offV + 1;
}
mesh.vertices = positions;
mesh.colors = colors;
mesh.normals = normals;
mesh.tangents = tangents;
mesh.uv = coords1;
mesh.uv2 = coords2;
mesh.triangles = indices;
mesh.bounds = SgtHelper.NewBoundsFromMinMax(min, max);
}
protected virtual void CameraPreCull(Camera camera)
{
if (FollowCameras == true || Wrap == true)
{
if (Models != null)
{
for (var i = Models.Count - 1; i >= 0; i--)
{
var model = Models[i];
if (model != null)
{
model.Revert();
{
if (FollowCameras == true)
{
model.transform.position = camera.transform.position;
}
}
model.Save(camera);
if (Wrap == true)
{
model.transform.position = camera.transform.position;
}
}
}
}
}
}
protected void CameraPreRender(Camera camera)
{
if (Models != null)
{
for (var i = Models.Count - 1; i >= 0; i--)
{
var model = Models[i];
if (model != null)
{
model.Restore(camera);
}
}
}
if (Material != null)
{
var velocity = StretchVector;
var observer = SgtObserver.Find(camera);
if (observer != null)
{
Material.SetFloat("_CameraRollAngle", observer.RollAngle * Mathf.Deg2Rad);
velocity += observer.Velocity * StretchScale;
}
if (Stretch == true)
{
Material.SetVector("_StretchVector", velocity);
Material.SetVector("_StretchDirection", velocity.normalized);
Material.SetFloat("_StretchLength", velocity.magnitude);
}
}
}
protected void CameraPostRender(Camera camera)
{
if (Models != null)
{
for (var i = Models.Count - 1; i >= 0; i--)
{
var model = Models[i];
if (model != null)
{
model.Revert();
}
}
}
if (Material != null)
{
Material.SetFloat("_CameraRollAngle", 0.0f);
Material.SetVector("_StretchVector", Vector3.zero);
Material.SetVector("_StretchDirection", Vector3.zero);
Material.SetFloat("_StretchLength", 0.0f);
}
}
}
| |
namespace PokerTell.Statistics
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Practices.Composite.Events;
using PokerTell.Infrastructure;
using PokerTell.Infrastructure.Enumerations.PokerHand;
using PokerTell.Infrastructure.Events;
using PokerTell.Infrastructure.Interfaces.PokerHand;
using PokerTell.Infrastructure.Interfaces.Repository;
using PokerTell.Infrastructure.Interfaces.Statistics;
using PokerTell.Statistics.Detailed;
using PokerTell.Statistics.Filters;
using PokerTell.Statistics.Interfaces;
using PokerTell.Statistics.Utilities;
using Tools.FunctionalCSharp;
public class PlayerStatistics : IPlayerStatistics, IEnumerable<IActionSequenceStatisticsSet>
{
protected IList<IAnalyzablePokerPlayer> _allAnalyzablePlayers;
protected long _lastQueriedId;
readonly IRepository _repository;
IAnalyzablePokerPlayersFilter _filter;
string _playerName;
string _pokerSite;
public PlayerStatistics(IEventAggregator eventAggregator, IRepository repository)
{
eventAggregator
.GetEvent<DatabaseInUseChangedEvent>()
.Subscribe(dp => Reinitialize());
_repository = repository;
_allAnalyzablePlayers = new List<IAnalyzablePokerPlayer>();
_filter = AnalyzablePokerPlayersFilter.InactiveFilter;
}
public IAnalyzablePokerPlayersFilter Filter
{
get { return _filter; }
set
{
_filter = value;
FilterAnalyzablePlayersAndUpdateStatisticsSetsWithThem();
FilterChanged();
}
}
public IEnumerable<IAnalyzablePokerPlayer> FilteredAnalyzablePokerPlayers { get; protected set; }
public IActionSequenceStatisticsSet[] HeroXOrHeroBInPosition { get; protected set; }
public IActionSequenceStatisticsSet[] HeroXOrHeroBOutOfPosition { get; protected set; }
public IActionSequenceStatisticsSet[] HeroXOutOfPositionOppB { get; protected set; }
public IActionSequenceStatisticsSet[] OppBIntoHeroInPosition { get; protected set; }
public IActionSequenceStatisticsSet[] OppBIntoHeroOutOfPosition { get; protected set; }
public IPlayerIdentity PlayerIdentity { get; protected set; }
public IActionSequenceStatisticsSet PreFlopRaisedPot { get; protected set; }
public IActionSequenceStatisticsSet PreFlopUnraisedPot { get; protected set; }
public int TotalCountPreFlopRaisedPot
{
get { return PreFlopRaisedPot.TotalCounts.Sum(); }
}
public int TotalCountPreFlopUnraisedPot
{
get { return PreFlopUnraisedPot.TotalCounts.Sum(); }
}
/// <summary>
/// Returns an enumerator that iterates through a collection.
/// </summary>
/// <returns>
/// An
/// <see cref="T:System.Collections.IEnumerator" />
/// object that can be used to iterate through the collection.
/// </returns>
/// <filterpriority>2</filterpriority>
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns>
/// <see cref="T:System.Collections.Generic.IEnumerator`1" />
/// that can be used to iterate through the collection.
/// </returns>
/// <filterpriority>1</filterpriority>
public IEnumerator<IActionSequenceStatisticsSet> GetEnumerator()
{
yield return PreFlopUnraisedPot;
yield return PreFlopRaisedPot;
for (Streets street = Streets.Flop; street <= Streets.River; street++)
{
yield return HeroXOrHeroBOutOfPosition[(int)street];
yield return HeroXOrHeroBInPosition[(int)street];
yield return OppBIntoHeroOutOfPosition[(int)street];
yield return OppBIntoHeroInPosition[(int)street];
yield return HeroXOutOfPositionOppB[(int)street];
}
}
public override string ToString()
{
var sb = new StringBuilder(
string.Format(
"PlayerName: {0}, PokerSite: {1}, LastQueriedId: {2}\n",
_playerName,
_pokerSite,
_lastQueriedId));
this.ToList().ForEach(statisticsSet => sb.AppendLine(statisticsSet.ToString()));
sb.AppendLine("Total Counts: ")
.AppendLine("Preflop: ")
.AppendFormat("UnraisedPot: {0} ", TotalCountPreFlopUnraisedPot)
.AppendFormat("RaisedPot: {0}", TotalCountPreFlopRaisedPot);
sb.AppendLine("\nPostFlop:")
.Append("Out of Position: ");
for (Streets street = Streets.Flop; street <= Streets.River; street++)
{
sb.Append(TotalCountsOutOfPosition(street) + ", ");
}
sb.AppendLine()
.Append("In Position: ");
for (Streets street = Streets.Flop; street <= Streets.River; street++)
{
sb.Append(TotalCountsInPosition(street) + ", ");
}
return sb.ToString();
}
public IPlayerStatistics InitializePlayer(string playerName, string pokerSite)
{
_playerName = playerName;
_pokerSite = pokerSite;
InitializeStatistics();
return this;
}
public int TotalCountsInPosition(Streets street)
{
return HeroXOrHeroBInPosition[(int)street].TotalCounts.Sum() +
OppBIntoHeroInPosition[(int)street].TotalCounts.Sum();
}
public int TotalCountsOutOfPosition(Streets street)
{
return HeroXOrHeroBOutOfPosition[(int)street].TotalCounts.Sum() +
OppBIntoHeroOutOfPosition[(int)street].TotalCounts.Sum();
}
public IPlayerStatistics UpdateStatistics()
{
ExtractPlayerIdentityIfItIsNullFrom(_repository);
if (PlayerIdentity != null)
{
ExtractAnalyzablePlayersAndRememberLastQueriedIdFrom(_repository);
FilterAnalyzablePlayersAndUpdateStatisticsSetsWithThem();
}
return this;
}
protected virtual IEnumerable<IAnalyzablePokerPlayer> GetFilteredAnalyzablePlayers()
{
return Filter == null
? _allAnalyzablePlayers
: Filter.Filter(_allAnalyzablePlayers);
}
protected virtual IActionSequenceStatisticsSet NewActionSequenceSetStatistics(
IPercentagesCalculator percentagesCalculator,
IEnumerable<IActionSequenceStatistic> statistics,
string playerName,
Streets street,
ActionSequences actionSequence,
bool inPosition)
{
return new ActionSequenceStatisticsSet(percentagesCalculator, statistics, playerName, street, actionSequence, inPosition);
}
protected virtual IActionSequenceStatisticsSet NewHeroCheckOrBetSetStatistics(
IPercentagesCalculator percentagesCalculator,
IEnumerable<IActionSequenceStatistic> statistics,
string playerName,
Streets street,
bool inPosition)
{
return new HeroCheckOrBetSetStatistics(percentagesCalculator, statistics, playerName, street, inPosition);
}
protected virtual IActionSequenceStatisticsSet NewPreflopActionSequenceSetStatistics(
IPercentagesCalculator percentagesCalculator,
IEnumerable<IActionSequenceStatistic> actionSequenceStatistics,
string playerName,
bool raisedPot)
{
return new ActionSequenceStatisticsSet(
percentagesCalculator,
actionSequenceStatistics,
playerName,
raisedPot ? ActionSequences.PreFlopFrontRaise : ActionSequences.PreFlopNoFrontRaise,
raisedPot);
}
protected virtual void UpdateStatisticsWith(IEnumerable<IAnalyzablePokerPlayer> filteredAnalyzablePlayers)
{
FilteredAnalyzablePokerPlayers = filteredAnalyzablePlayers;
foreach (IActionSequenceStatisticsSet statisticsSet in this)
{
statisticsSet.UpdateWith(filteredAnalyzablePlayers);
}
}
void CreatePostFlopStatistics()
{
HeroXOrHeroBInPosition = new IActionSequenceStatisticsSet[(int)(Streets.River + 1)];
HeroXOrHeroBOutOfPosition = new IActionSequenceStatisticsSet[(int)(Streets.River + 1)];
HeroXOutOfPositionOppB = new IActionSequenceStatisticsSet[(int)(Streets.River + 1)];
OppBIntoHeroInPosition = new IActionSequenceStatisticsSet[(int)(Streets.River + 1)];
OppBIntoHeroOutOfPosition = new IActionSequenceStatisticsSet[(int)(Streets.River + 1)];
}
void ExtractAnalyzablePlayersAndRememberLastQueriedIdFrom(IRepository repository)
{
IEnumerable<IAnalyzablePokerPlayer> newAnalyzablePlayers =
repository.FindAnalyzablePlayersWith(PlayerIdentity.Id, _lastQueriedId);
if (newAnalyzablePlayers.Count() != 0)
{
_lastQueriedId = (from player in newAnalyzablePlayers select player.Id).Max();
foreach (IAnalyzablePokerPlayer analyzablePlayer in newAnalyzablePlayers)
{
_allAnalyzablePlayers.Add(analyzablePlayer);
}
}
}
void ExtractPlayerIdentityIfItIsNullFrom(IRepository repository)
{
if (PlayerIdentity == null)
{
PlayerIdentity = repository.FindPlayerIdentityFor(_playerName, _pokerSite);
}
}
void FilterAnalyzablePlayersAndUpdateStatisticsSetsWithThem()
{
IEnumerable<IAnalyzablePokerPlayer> filteredAnalyzablePlayers = GetFilteredAnalyzablePlayers();
UpdateStatisticsWith(filteredAnalyzablePlayers);
}
void InitializeHeroXorBStatistics(Streets street, int betSizeIndexCount)
{
var heroXOrHeroBOutOfPositionStatistics = new List<IActionSequenceStatistic>
{
new PostFlopHeroXStatistic(street, false),
new PostFlopActionSequenceStatistic(ActionSequences.HeroB, street, false, betSizeIndexCount)
};
var heroXOrHeroBInPositionStatistics = new List<IActionSequenceStatistic>
{
new PostFlopHeroXStatistic(street, true),
new PostFlopActionSequenceStatistic(ActionSequences.HeroB, street, true, betSizeIndexCount)
};
HeroXOrHeroBOutOfPosition[(int)street] =
NewHeroCheckOrBetSetStatistics(new SeparateRowsPercentagesCalculator(),
heroXOrHeroBOutOfPositionStatistics,
_playerName,
street,
false);
HeroXOrHeroBInPosition[(int)street] =
NewHeroCheckOrBetSetStatistics(new SeparateRowsPercentagesCalculator(), heroXOrHeroBInPositionStatistics, _playerName, street, true);
}
public event Action FilterChanged = delegate { };
void InitializeHeroXOutOfPositionOppBStatistics(Streets street, int betSizeIndexCount)
{
var heroXOutOfPositionOppBStatistics = new List<IActionSequenceStatistic>
{
new PostFlopActionSequenceStatistic(ActionSequences.HeroXOppBHeroF, street, false, betSizeIndexCount),
new PostFlopActionSequenceStatistic(ActionSequences.HeroXOppBHeroC, street, false, betSizeIndexCount),
new PostFlopActionSequenceStatistic(ActionSequences.HeroXOppBHeroR, street, false, betSizeIndexCount)
};
HeroXOutOfPositionOppB[(int)street] =
NewActionSequenceSetStatistics(new AcrossRowsPercentagesCalculator(),
heroXOutOfPositionOppBStatistics,
_playerName,
street,
ActionSequences.HeroXOppB,
false);
}
void InitializeOppBIntoHeroStatistics(Streets street, int betSizeIndexCount)
{
var oppBIntoHeroOutOfPositionStatistics = new List<IActionSequenceStatistic>
{
new PostFlopActionSequenceStatistic(ActionSequences.OppBHeroF, street, false, betSizeIndexCount),
new PostFlopActionSequenceStatistic(ActionSequences.OppBHeroC, street, false, betSizeIndexCount),
new PostFlopActionSequenceStatistic(ActionSequences.OppBHeroR, street, false, betSizeIndexCount)
};
var oppBIntoHeroInPositionStatistics = new List<IActionSequenceStatistic>
{
new PostFlopActionSequenceStatistic(ActionSequences.OppBHeroF, street, true, betSizeIndexCount),
new PostFlopActionSequenceStatistic(ActionSequences.OppBHeroC, street, true, betSizeIndexCount),
new PostFlopActionSequenceStatistic(ActionSequences.OppBHeroR, street, true, betSizeIndexCount)
};
OppBIntoHeroOutOfPosition[(int)street] =
NewActionSequenceSetStatistics(new AcrossRowsPercentagesCalculator(),
oppBIntoHeroOutOfPositionStatistics,
_playerName,
street,
ActionSequences.OppB,
false);
OppBIntoHeroInPosition[(int)street] =
NewActionSequenceSetStatistics(new AcrossRowsPercentagesCalculator(),
oppBIntoHeroInPositionStatistics,
_playerName,
street,
ActionSequences.OppB,
true);
}
void InitializePreFlopStatistics()
{
var preFlopUnraisedPotStatistics = new List<IActionSequenceStatistic>
{
new PreFlopActionSequenceStatistic(ActionSequences.HeroF),
new PreFlopActionSequenceStatistic(ActionSequences.HeroC),
new PreFlopActionSequenceStatistic(ActionSequences.HeroR)
};
var preFlopRaisedPotStatistics = new List<IActionSequenceStatistic>
{
new PreFlopActionSequenceStatistic(ActionSequences.OppRHeroF),
new PreFlopActionSequenceStatistic(ActionSequences.OppRHeroC),
new PreFlopActionSequenceStatistic(ActionSequences.OppRHeroR)
};
PreFlopRaisedPot =
NewPreflopActionSequenceSetStatistics(new AcrossRowsPercentagesCalculator(), preFlopRaisedPotStatistics, _playerName, true);
PreFlopUnraisedPot =
NewPreflopActionSequenceSetStatistics(new AcrossRowsPercentagesCalculator(), preFlopUnraisedPotStatistics, _playerName, false);
}
void InitializeStatistics()
{
int betSizeIndexCount = ApplicationProperties.BetSizeKeys.Length;
InitializePreFlopStatistics();
CreatePostFlopStatistics();
for (Streets street = Streets.Flop; street <= Streets.River; street++)
{
InitializeHeroXorBStatistics(street, betSizeIndexCount);
InitializeOppBIntoHeroStatistics(street, betSizeIndexCount);
InitializeHeroXOutOfPositionOppBStatistics(street, betSizeIndexCount);
}
}
void Reinitialize()
{
_lastQueriedId = 0;
_allAnalyzablePlayers = new List<IAnalyzablePokerPlayer>();
PlayerIdentity = null;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using System.Xml.Linq;
using Nuke.Common;
using Nuke.Common.Git;
using Nuke.Common.ProjectModel;
using Nuke.Common.Tooling;
using Nuke.Common.Tools.DotNet;
using Nuke.Common.Tools.MSBuild;
using Nuke.Common.Tools.Npm;
using Nuke.Common.Utilities;
using Nuke.Common.Utilities.Collections;
using Pharmacist.Core;
using static Nuke.Common.EnvironmentInfo;
using static Nuke.Common.IO.FileSystemTasks;
using static Nuke.Common.IO.PathConstruction;
using static Nuke.Common.Tools.MSBuild.MSBuildTasks;
using static Nuke.Common.Tools.DotNet.DotNetTasks;
using static Nuke.Common.Tools.Xunit.XunitTasks;
using static Nuke.Common.Tools.VSWhere.VSWhereTasks;
/*
Before editing this file, install support plugin for your IDE,
running and debugging a particular target (optionally without deps) would be way easier
ReSharper/Rider - https://plugins.jetbrains.com/plugin/10803-nuke-support
VSCode - https://marketplace.visualstudio.com/items?itemName=nuke.support
*/
partial class Build : NukeBuild
{
[Solution("Avalonia.sln")] readonly Solution Solution;
static Lazy<string> MsBuildExe = new Lazy<string>(() =>
{
if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
return null;
var msBuildDirectory = VSWhere("-latest -nologo -property installationPath -format value -prerelease").FirstOrDefault().Text;
if (!string.IsNullOrWhiteSpace(msBuildDirectory))
{
string msBuildExe = Path.Combine(msBuildDirectory, @"MSBuild\Current\Bin\MSBuild.exe");
if (!System.IO.File.Exists(msBuildExe))
msBuildExe = Path.Combine(msBuildDirectory, @"MSBuild\15.0\Bin\MSBuild.exe");
return msBuildExe;
}
return null;
}, false);
BuildParameters Parameters { get; set; }
protected override void OnBuildInitialized()
{
Parameters = new BuildParameters(this);
Information("Building version {0} of Avalonia ({1}) using version {2} of Nuke.",
Parameters.Version,
Parameters.Configuration,
typeof(NukeBuild).Assembly.GetName().Version.ToString());
if (Parameters.IsLocalBuild)
{
Information("Repository Name: " + Parameters.RepositoryName);
Information("Repository Branch: " + Parameters.RepositoryBranch);
}
Information("Configuration: " + Parameters.Configuration);
Information("IsLocalBuild: " + Parameters.IsLocalBuild);
Information("IsRunningOnUnix: " + Parameters.IsRunningOnUnix);
Information("IsRunningOnWindows: " + Parameters.IsRunningOnWindows);
Information("IsRunningOnAzure:" + Parameters.IsRunningOnAzure);
Information("IsPullRequest: " + Parameters.IsPullRequest);
Information("IsMainRepo: " + Parameters.IsMainRepo);
Information("IsMasterBranch: " + Parameters.IsMasterBranch);
Information("IsReleaseBranch: " + Parameters.IsReleaseBranch);
Information("IsReleasable: " + Parameters.IsReleasable);
Information("IsMyGetRelease: " + Parameters.IsMyGetRelease);
Information("IsNuGetRelease: " + Parameters.IsNuGetRelease);
void ExecWait(string preamble, string command, string args)
{
Console.WriteLine(preamble);
Process.Start(new ProcessStartInfo(command, args) {UseShellExecute = false}).WaitForExit();
}
ExecWait("dotnet version:", "dotnet", "--version");
if (Parameters.IsRunningOnUnix)
ExecWait("Mono version:", "mono", "--version");
}
IReadOnlyCollection<Output> MsBuildCommon(
string projectFile,
Configure<MSBuildSettings> configurator = null)
{
return MSBuild(c => c
.SetProjectFile(projectFile)
// This is required for VS2019 image on Azure Pipelines
.When(Parameters.IsRunningOnWindows &&
Parameters.IsRunningOnAzure, _ => _
.AddProperty("JavaSdkDirectory", GetVariable<string>("JAVA_HOME_8_X64")))
.AddProperty("PackageVersion", Parameters.Version)
.AddProperty("iOSRoslynPathHackRequired", true)
.SetToolPath(MsBuildExe.Value)
.SetConfiguration(Parameters.Configuration)
.SetVerbosity(MSBuildVerbosity.Minimal)
.Apply(configurator));
}
Target Clean => _ => _.Executes(() =>
{
Parameters.BuildDirs.ForEach(DeleteDirectory);
Parameters.BuildDirs.ForEach(EnsureCleanDirectory);
EnsureCleanDirectory(Parameters.ArtifactsDir);
EnsureCleanDirectory(Parameters.NugetIntermediateRoot);
EnsureCleanDirectory(Parameters.NugetRoot);
EnsureCleanDirectory(Parameters.ZipRoot);
EnsureCleanDirectory(Parameters.TestResultsRoot);
});
Target CompileHtmlPreviewer => _ => _
.DependsOn(Clean)
.OnlyWhenStatic(() => !Parameters.SkipPreviewer)
.Executes(() =>
{
var webappDir = RootDirectory / "src" / "Avalonia.DesignerSupport" / "Remote" / "HtmlTransport" / "webapp";
NpmTasks.NpmInstall(c => c
.SetWorkingDirectory(webappDir)
.SetArgumentConfigurator(a => a.Add("--silent")));
NpmTasks.NpmRun(c => c
.SetWorkingDirectory(webappDir)
.SetCommand("dist"));
});
Target CompileNative => _ => _
.DependsOn(Clean)
.DependsOn(GenerateCppHeaders)
.OnlyWhenStatic(() => EnvironmentInfo.IsOsx)
.Executes(() =>
{
var project = $"{RootDirectory}/native/Avalonia.Native/src/OSX/Avalonia.Native.OSX.xcodeproj/";
var args = $"-project {project} -configuration {Parameters.Configuration} CONFIGURATION_BUILD_DIR={RootDirectory}/Build/Products/Release";
ProcessTasks.StartProcess("xcodebuild", args).AssertZeroExitCode();
});
Target Compile => _ => _
.DependsOn(Clean, CompileNative)
.DependsOn(CompileHtmlPreviewer)
.Executes(async () =>
{
if (Parameters.IsRunningOnWindows)
MsBuildCommon(Parameters.MSBuildSolution, c => c
.SetArgumentConfigurator(a => a.Add("/r"))
.AddTargets("Build")
);
else
DotNetBuild(c => c
.SetProjectFile(Parameters.MSBuildSolution)
.AddProperty("PackageVersion", Parameters.Version)
.SetConfiguration(Parameters.Configuration)
);
await CompileReactiveEvents();
});
async Task CompileReactiveEvents()
{
var avaloniaBuildOutput = Path.Combine(RootDirectory, "packages", "Avalonia", "bin", Parameters.Configuration);
var avaloniaAssemblies = GlobFiles(avaloniaBuildOutput, "**/Avalonia*.dll")
.Where(file => !file.Contains("Avalonia.Build.Tasks") &&
!file.Contains("Avalonia.Remote.Protocol"));
var eventsDirectory = GlobDirectories($"{RootDirectory}/src/**/Avalonia.ReactiveUI.Events").First();
var eventsBuildFile = Path.Combine(eventsDirectory, "Events_Avalonia.cs");
if (File.Exists(eventsBuildFile))
File.Delete(eventsBuildFile);
using (var stream = File.Create(eventsBuildFile))
using (var writer = new StreamWriter(stream))
{
await ObservablesForEventGenerator.ExtractEventsFromAssemblies(
writer, avaloniaAssemblies, new string[0], "netstandard2.0"
);
}
var eventsProject = Path.Combine(eventsDirectory, "Avalonia.ReactiveUI.Events.csproj");
if (Parameters.IsRunningOnWindows)
MsBuildCommon(eventsProject, c => c
.SetArgumentConfigurator(a => a.Add("/r"))
.AddTargets("Build")
);
else
DotNetBuild(c => c
.SetProjectFile(eventsProject)
.AddProperty("PackageVersion", Parameters.Version)
.SetConfiguration(Parameters.Configuration)
);
}
void RunCoreTest(string projectName)
{
Information($"Running tests from {projectName}");
var project = Solution.GetProject(projectName).NotNull("project != null");
foreach (var fw in project.GetTargetFrameworks())
{
if (fw.StartsWith("net4")
&& RuntimeInformation.IsOSPlatform(OSPlatform.Linux)
&& Environment.GetEnvironmentVariable("FORCE_LINUX_TESTS") != "1")
{
Information($"Skipping {projectName} ({fw}) tests on Linux - https://github.com/mono/mono/issues/13969");
continue;
}
Information($"Running for {projectName} ({fw}) ...");
DotNetTest(c => c
.SetProjectFile(project)
.SetConfiguration(Parameters.Configuration)
.SetFramework(fw)
.EnableNoBuild()
.EnableNoRestore()
.When(Parameters.PublishTestResults, _ => _
.SetLogger("trx")
.SetResultsDirectory(Parameters.TestResultsRoot)));
}
}
Target RunHtmlPreviewerTests => _ => _
.DependsOn(CompileHtmlPreviewer)
.OnlyWhenStatic(() => !(Parameters.SkipPreviewer || Parameters.SkipTests))
.Executes(() =>
{
var webappTestDir = RootDirectory / "tests" / "Avalonia.DesignerSupport.Tests" / "Remote" / "HtmlTransport" / "webapp";
NpmTasks.NpmInstall(c => c
.SetWorkingDirectory(webappTestDir)
.SetArgumentConfigurator(a => a.Add("--silent")));
NpmTasks.NpmRun(c => c
.SetWorkingDirectory(webappTestDir)
.SetCommand("test"));
});
Target RunCoreLibsTests => _ => _
.OnlyWhenStatic(() => !Parameters.SkipTests)
.DependsOn(Compile)
.Executes(() =>
{
RunCoreTest("Avalonia.Animation.UnitTests");
RunCoreTest("Avalonia.Base.UnitTests");
RunCoreTest("Avalonia.Controls.UnitTests");
RunCoreTest("Avalonia.Controls.DataGrid.UnitTests");
RunCoreTest("Avalonia.Input.UnitTests");
RunCoreTest("Avalonia.Interactivity.UnitTests");
RunCoreTest("Avalonia.Layout.UnitTests");
RunCoreTest("Avalonia.Markup.UnitTests");
RunCoreTest("Avalonia.Markup.Xaml.UnitTests");
RunCoreTest("Avalonia.Styling.UnitTests");
RunCoreTest("Avalonia.Visuals.UnitTests");
RunCoreTest("Avalonia.Skia.UnitTests");
RunCoreTest("Avalonia.ReactiveUI.UnitTests");
});
Target RunRenderTests => _ => _
.OnlyWhenStatic(() => !Parameters.SkipTests)
.DependsOn(Compile)
.Executes(() =>
{
RunCoreTest("Avalonia.Skia.RenderTests");
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
RunCoreTest("Avalonia.Direct2D1.RenderTests");
});
Target RunDesignerTests => _ => _
.OnlyWhenStatic(() => !Parameters.SkipTests && Parameters.IsRunningOnWindows)
.DependsOn(Compile)
.Executes(() =>
{
RunCoreTest("Avalonia.DesignerSupport.Tests");
});
[PackageExecutable("JetBrains.dotMemoryUnit", "dotMemoryUnit.exe")] readonly Tool DotMemoryUnit;
Target RunLeakTests => _ => _
.OnlyWhenStatic(() => !Parameters.SkipTests && Parameters.IsRunningOnWindows)
.DependsOn(Compile)
.Executes(() =>
{
var testAssembly = "tests\\Avalonia.LeakTests\\bin\\Release\\net461\\Avalonia.LeakTests.dll";
DotMemoryUnit(
$"{XunitPath.DoubleQuoteIfNeeded()} --propagate-exit-code -- {testAssembly}",
timeout: 120_000);
});
Target ZipFiles => _ => _
.After(CreateNugetPackages, Compile, RunCoreLibsTests, Package)
.Executes(() =>
{
var data = Parameters;
Zip(data.ZipCoreArtifacts, data.BinRoot);
Zip(data.ZipNuGetArtifacts, data.NugetRoot);
Zip(data.ZipTargetControlCatalogDesktopDir,
GlobFiles(data.ZipSourceControlCatalogDesktopDir, "*.dll").Concat(
GlobFiles(data.ZipSourceControlCatalogDesktopDir, "*.config")).Concat(
GlobFiles(data.ZipSourceControlCatalogDesktopDir, "*.so")).Concat(
GlobFiles(data.ZipSourceControlCatalogDesktopDir, "*.dylib")).Concat(
GlobFiles(data.ZipSourceControlCatalogDesktopDir, "*.exe")));
});
Target CreateIntermediateNugetPackages => _ => _
.DependsOn(Compile)
.After(RunTests)
.Executes(() =>
{
if (Parameters.IsRunningOnWindows)
MsBuildCommon(Parameters.MSBuildSolution, c => c
.AddTargets("Pack"));
else
DotNetPack(c => c
.SetProject(Parameters.MSBuildSolution)
.SetConfiguration(Parameters.Configuration)
.AddProperty("PackageVersion", Parameters.Version));
});
Target CreateNugetPackages => _ => _
.DependsOn(CreateIntermediateNugetPackages)
.Executes(() =>
{
BuildTasksPatcher.PatchBuildTasksInPackage(Parameters.NugetIntermediateRoot / "Avalonia.Build.Tasks." +
Parameters.Version + ".nupkg");
var config = Numerge.MergeConfiguration.LoadFile(RootDirectory / "nukebuild" / "numerge.config");
EnsureCleanDirectory(Parameters.NugetRoot);
if(!Numerge.NugetPackageMerger.Merge(Parameters.NugetIntermediateRoot, Parameters.NugetRoot, config,
new NumergeNukeLogger()))
throw new Exception("Package merge failed");
});
Target RunTests => _ => _
.DependsOn(RunCoreLibsTests)
.DependsOn(RunRenderTests)
.DependsOn(RunDesignerTests)
.DependsOn(RunHtmlPreviewerTests)
.DependsOn(RunLeakTests);
Target Package => _ => _
.DependsOn(RunTests)
.DependsOn(CreateNugetPackages);
Target CiAzureLinux => _ => _
.DependsOn(RunTests);
Target CiAzureOSX => _ => _
.DependsOn(Package)
.DependsOn(ZipFiles);
Target CiAzureWindows => _ => _
.DependsOn(Package)
.DependsOn(ZipFiles);
public static int Main() =>
RuntimeInformation.IsOSPlatform(OSPlatform.Windows)
? Execute<Build>(x => x.Package)
: Execute<Build>(x => x.RunTests);
}
public static class ToolSettingsExtensions
{
public static T Apply<T>(this T settings, Configure<T> configurator)
{
return configurator != null ? configurator(settings) : settings;
}
}
| |
using System;
namespace Versioning
{
public class ControlData : Sage_Container, IData
{
/* Autogenerated by sage_wrapper_generator.pl */
SageDataObject110.ControlData cd11;
SageDataObject120.ControlData cd12;
SageDataObject130.ControlData cd13;
SageDataObject140.ControlData cd14;
SageDataObject150.ControlData cd15;
SageDataObject160.ControlData cd16;
SageDataObject170.ControlData cd17;
public ControlData(object inner, int version)
: base(version) {
switch (m_version) {
case 11: {
cd11 = (SageDataObject110.ControlData)inner;
m_fields = new Fields(cd11.Fields,m_version);
return;
}
case 12: {
cd12 = (SageDataObject120.ControlData)inner;
m_fields = new Fields(cd12.Fields,m_version);
return;
}
case 13: {
cd13 = (SageDataObject130.ControlData)inner;
m_fields = new Fields(cd13.Fields,m_version);
return;
}
case 14: {
cd14 = (SageDataObject140.ControlData)inner;
m_fields = new Fields(cd14.Fields,m_version);
return;
}
case 15: {
cd15 = (SageDataObject150.ControlData)inner;
m_fields = new Fields(cd15.Fields,m_version);
return;
}
case 16: {
cd16 = (SageDataObject160.ControlData)inner;
m_fields = new Fields(cd16.Fields,m_version);
return;
}
case 17: {
cd17 = (SageDataObject170.ControlData)inner;
m_fields = new Fields(cd17.Fields,m_version);
return;
}
default: throw new InvalidOperationException("ver");
}
}
/* Autogenerated with data_generator.pl */
const string ACCOUNT_REF = "ACCOUNT_REF";
const string CONTROLDATA = "ControlData";
public bool Open(OpenMode mode) {
bool ret;
switch (m_version) {
case 11: {
ret = cd11.Open((SageDataObject110.OpenMode)mode);
break;
}
case 12: {
ret = cd12.Open((SageDataObject120.OpenMode)mode);
break;
}
case 13: {
ret = cd13.Open((SageDataObject130.OpenMode)mode);
break;
}
case 14: {
ret = cd14.Open((SageDataObject140.OpenMode)mode);
break;
}
case 15: {
ret = cd15.Open((SageDataObject150.OpenMode)mode);
break;
}
case 16: {
ret = cd16.Open((SageDataObject160.OpenMode)mode);
break;
}
case 17: {
ret = cd17.Open((SageDataObject170.OpenMode)mode);
break;
}
default: throw new InvalidOperationException("ver");
}
return ret;
}
public void Close() {
switch (m_version) {
case 11: {
cd11.Close();
break;
}
case 12: {
cd12.Close();
break;
}
case 13: {
cd13.Close();
break;
}
case 14: {
cd14.Close();
break;
}
case 15: {
cd15.Close();
break;
}
case 16: {
cd16.Close();
break;
}
case 17: {
cd17.Close();
break;
}
default: throw new InvalidOperationException("ver");
}
}
public bool Read() {
return Read(1);
}
public bool Read(int IRecNo) {
bool ret;
switch (m_version) {
case 11: {
ret = cd11.Read(IRecNo);
break;
}
case 12: {
ret = cd12.Read(IRecNo);
break;
}
case 13: {
ret = cd13.Read(IRecNo);
break;
}
case 14: {
ret = cd14.Read(IRecNo);
break;
}
case 15: {
ret = cd15.Read(IRecNo);
break;
}
case 16: {
ret = cd16.Read(IRecNo);
break;
}
case 17: {
ret = cd17.Read(IRecNo);
break;
}
default: throw new InvalidOperationException("ver");
}
return ret;
}
public bool Write(int IRecNo) {
bool ret;
switch (m_version) {
case 11: {
ret = cd11.Write(IRecNo);
break;
}
case 12: {
ret = cd12.Write(IRecNo);
break;
}
case 13: {
ret = cd13.Write(IRecNo);
break;
}
case 14: {
ret = cd14.Write(IRecNo);
break;
}
case 15: {
ret = cd15.Write(IRecNo);
break;
}
case 16: {
ret = cd16.Write(IRecNo);
break;
}
case 17: {
ret = cd17.Write(IRecNo);
break;
}
default: throw new InvalidOperationException("ver");
}
return ret;
}
public bool Seek(int IRecNo) {
bool ret;
switch (m_version) {
case 11: {
ret = cd11.Seek(IRecNo);
break;
}
case 12: {
ret = cd12.Seek(IRecNo);
break;
}
case 13: {
ret = cd13.Seek(IRecNo);
break;
}
case 14: {
ret = cd14.Seek(IRecNo);
break;
}
case 15: {
ret = cd15.Seek(IRecNo);
break;
}
case 16: {
ret = cd16.Seek(IRecNo);
break;
}
case 17: {
ret = cd17.Seek(IRecNo);
break;
}
default: throw new InvalidOperationException("ver");
}
return ret;
}
public bool Lock(int IRecNo) {
bool ret;
switch (m_version) {
case 11: {
ret = cd11.Lock(IRecNo);
break;
}
case 12: {
ret = cd12.Lock(IRecNo);
break;
}
case 13: {
ret = cd13.Lock(IRecNo);
break;
}
case 14: {
ret = cd14.Lock(IRecNo);
break;
}
case 15: {
ret = cd15.Lock(IRecNo);
break;
}
case 16: {
ret = cd16.Lock(IRecNo);
break;
}
case 17: {
ret = cd17.Lock(IRecNo);
break;
}
default: throw new InvalidOperationException("ver");
}
return ret;
}
public bool Unlock(int IRecNo) {
bool ret;
switch (m_version) {
case 11: {
ret = cd11.Unlock(IRecNo);
break;
}
case 12: {
ret = cd12.Unlock(IRecNo);
break;
}
case 13: {
ret = cd13.Unlock(IRecNo);
break;
}
case 14: {
ret = cd14.Unlock(IRecNo);
break;
}
case 15: {
ret = cd15.Unlock(IRecNo);
break;
}
case 16: {
ret = cd16.Unlock(IRecNo);
break;
}
case 17: {
ret = cd17.Unlock(IRecNo);
break;
}
default: throw new InvalidOperationException("ver");
}
return ret;
}
//public bool FindFirst(object varField, object varSearch) {
// bool ret;
// switch (m_version) {
// case 11: {
// ret = cd11.FindFirst(varField, varSearch);
// break;
// }
// case 12: {
// ret = cd12.FindFirst(varField, varSearch);
// break;
// }
// case 13: {
// ret = cd13.FindFirst(varField, varSearch);
// break;
// }
// case 14: {
// ret = cd14.FindFirst(varField, varSearch);
// break;
// }
// case 15: {
// ret = cd15.FindFirst(varField, varSearch);
// break;
// }
// case 16: {
// ret = cd16.FindFirst(varField, varSearch);
// break;
// }
// case 17: {
// ret = cd17.FindFirst(varField, varSearch);
// break;
// }
// default: throw new InvalidOperationException("ver");
// }
// return ret;
//}
//public bool FindNext(object varField, object varSearch) {
// bool ret;
// switch (m_version) {
// case 11: {
// ret = cd11.FindNext(varField, varSearch);
// break;
// }
// case 12: {
// ret = cd12.FindNext(varField, varSearch);
// break;
// }
// case 13: {
// ret = cd13.FindNext(varField, varSearch);
// break;
// }
// case 14: {
// ret = cd14.FindNext(varField, varSearch);
// break;
// }
// case 15: {
// ret = cd15.FindNext(varField, varSearch);
// break;
// }
// case 16: {
// ret = cd16.FindNext(varField, varSearch);
// break;
// }
// case 17: {
// ret = cd17.FindNext(varField, varSearch);
// break;
// }
// default: throw new InvalidOperationException("ver");
// }
// return ret;
//}
public int Count{
get {
int ret;
switch (m_version) {
case 11: {
ret = cd11.Count();
break;
}
case 12: {
ret = cd12.Count();
break;
}
case 13: {
ret = cd13.Count();
break;
}
case 14: {
ret = cd14.Count();
break;
}
case 15: {
ret = cd15.Count();
break;
}
case 16: {
ret = cd16.Count();
break;
}
case 17: {
ret = cd17.Count();
break;
}
default: throw new InvalidOperationException("ver");
}
return ret;
}
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Reflection;
using System.Xml;
using log4net;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Communications;
using OpenSim.Region.DataSnapshot.Interfaces;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
namespace OpenSim.Region.DataSnapshot
{
public class DataSnapshotManager : IRegionModule, IDataSnapshot
{
#region Class members
//Information from config
private bool m_enabled = false;
private bool m_configLoaded = false;
private List<string> m_disabledModules = new List<string>();
private Dictionary<string, string> m_gridinfo = new Dictionary<string, string>();
private string m_snapsDir = "DataSnapshot";
private string m_exposure_level = "minimum";
//Lists of stuff we need
private List<Scene> m_scenes = new List<Scene>();
private List<IDataSnapshotProvider> m_dataproviders = new List<IDataSnapshotProvider>();
//Various internal objects
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
internal object m_syncInit = new object();
//DataServices and networking
private string m_dataServices = "noservices";
public string m_listener_port = ConfigSettings.DefaultRegionHttpPort.ToString();
public string m_hostname = "127.0.0.1";
//Update timers
private int m_period = 20; // in seconds
private int m_maxStales = 500;
private int m_stales = 0;
private int m_lastUpdate = 0;
//Program objects
private SnapshotStore m_snapStore = null;
#endregion
#region Properties
public string ExposureLevel
{
get { return m_exposure_level; }
}
#endregion
#region IRegionModule
public void Initialise(Scene scene, IConfigSource config)
{
if (!m_configLoaded)
{
m_configLoaded = true;
m_log.Info("[DATASNAPSHOT]: Loading configuration");
//Read from the config for options
lock (m_syncInit)
{
try
{
m_enabled = config.Configs["DataSnapshot"].GetBoolean("index_sims", m_enabled);
if (config.Configs["Startup"].GetBoolean("gridmode", false))
{
m_gridinfo.Add(
"gridserverURL",
config.Configs["Network"].GetString(
"grid_server_url", "http://127.0.0.1:" + ConfigSettings.DefaultGridServerHttpPort.ToString()));
m_gridinfo.Add(
"userserverURL",
config.Configs["Network"].GetString(
"user_server_url", "http://127.0.0.1:" + ConfigSettings.DefaultUserServerHttpPort.ToString()));
m_gridinfo.Add(
"assetserverURL",
config.Configs["Network"].GetString(
"asset_server_url", "http://127.0.0.1:" + ConfigSettings.DefaultAssetServerHttpPort.ToString()));
}
m_gridinfo.Add(
"Name", config.Configs["DataSnapshot"].GetString("gridname", "the lost continent of hippo"));
m_exposure_level = config.Configs["DataSnapshot"].GetString("data_exposure", m_exposure_level);
m_period = config.Configs["DataSnapshot"].GetInt("default_snapshot_period", m_period);
m_maxStales = config.Configs["DataSnapshot"].GetInt("max_changes_before_update", m_maxStales);
m_snapsDir = config.Configs["DataSnapshot"].GetString("snapshot_cache_directory", m_snapsDir);
m_dataServices = config.Configs["DataSnapshot"].GetString("data_services", m_dataServices);
m_listener_port = config.Configs["Network"].GetString("http_listener_port", m_listener_port);
String[] annoying_string_array = config.Configs["DataSnapshot"].GetString("disable_modules", "").Split(".".ToCharArray());
foreach (String bloody_wanker in annoying_string_array)
{
m_disabledModules.Add(bloody_wanker);
}
m_lastUpdate = Environment.TickCount;
}
catch (Exception)
{
m_log.Info("[DATASNAPSHOT]: Could not load configuration. DataSnapshot will be disabled.");
m_enabled = false;
return;
}
}
if (m_enabled)
{
//Hand it the first scene, assuming that all scenes have the same BaseHTTPServer
new DataRequestHandler(scene, this);
m_hostname = scene.RegionInfo.ExternalHostName;
m_snapStore = new SnapshotStore(m_snapsDir, m_gridinfo, m_listener_port, m_hostname);
MakeEverythingStale();
if (m_dataServices != "" && m_dataServices != "noservices")
NotifyDataServices(m_dataServices, "online");
}
}
if (m_enabled)
{
m_log.Info("[DATASNAPSHOT]: Scene added to module.");
m_snapStore.AddScene(scene);
m_scenes.Add(scene);
Assembly currentasm = Assembly.GetExecutingAssembly();
foreach (Type pluginType in currentasm.GetTypes())
{
if (pluginType.IsPublic)
{
if (!pluginType.IsAbstract)
{
if (pluginType.GetInterface("IDataSnapshotProvider") != null)
{
IDataSnapshotProvider module = (IDataSnapshotProvider)Activator.CreateInstance(pluginType);
module.Initialize(scene, this);
module.OnStale += MarkDataStale;
m_dataproviders.Add(module);
m_snapStore.AddProvider(module);
m_log.Info("[DATASNAPSHOT]: Added new data provider type: " + pluginType.Name);
}
}
}
}
//scene.OnRestart += OnSimRestart;
scene.EventManager.OnShutdown += delegate() { OnSimRestart(scene.RegionInfo); };
}
else
{
m_log.Warn("[DATASNAPSHOT]: Data snapshot disabled, not adding scene to module (or anything else).");
}
}
public void Close()
{
if (m_enabled && m_dataServices != "" && m_dataServices != "noservices")
NotifyDataServices(m_dataServices, "offline");
}
public bool IsSharedModule
{
get { return true; }
}
public string Name
{
get { return "External Data Generator"; }
}
public void PostInitialise()
{
}
#endregion
#region Associated helper functions
public Scene SceneForName(string name)
{
foreach (Scene scene in m_scenes)
if (scene.RegionInfo.RegionName == name)
return scene;
return null;
}
public Scene SceneForUUID(UUID id)
{
foreach (Scene scene in m_scenes)
if (scene.RegionInfo.RegionID == id)
return scene;
return null;
}
#endregion
#region [Public] Snapshot storage functions
/**
* Reply to the http request
*/
public XmlDocument GetSnapshot(string regionName)
{
CheckStale();
XmlDocument requestedSnap = new XmlDocument();
requestedSnap.AppendChild(requestedSnap.CreateXmlDeclaration("1.0", null, null));
requestedSnap.AppendChild(requestedSnap.CreateWhitespace("\r\n"));
XmlNode regiondata = requestedSnap.CreateNode(XmlNodeType.Element, "regiondata", "");
try
{
if (regionName == null || regionName == "")
{
XmlNode timerblock = requestedSnap.CreateNode(XmlNodeType.Element, "expire", "");
timerblock.InnerText = m_period.ToString();
regiondata.AppendChild(timerblock);
regiondata.AppendChild(requestedSnap.CreateWhitespace("\r\n"));
foreach (Scene scene in m_scenes)
{
regiondata.AppendChild(m_snapStore.GetScene(scene, requestedSnap));
}
}
else
{
Scene scene = SceneForName(regionName);
regiondata.AppendChild(m_snapStore.GetScene(scene, requestedSnap));
}
requestedSnap.AppendChild(regiondata);
regiondata.AppendChild(requestedSnap.CreateWhitespace("\r\n"));
}
catch (XmlException e)
{
m_log.Warn("[DATASNAPSHOT]: XmlException while trying to load snapshot: " + e.ToString());
requestedSnap = GetErrorMessage(regionName, e);
}
catch (Exception e)
{
m_log.Warn("[DATASNAPSHOT]: Caught unknown exception while trying to load snapshot: " + e.StackTrace);
requestedSnap = GetErrorMessage(regionName, e);
}
return requestedSnap;
}
private XmlDocument GetErrorMessage(string regionName, Exception e)
{
XmlDocument errorMessage = new XmlDocument();
XmlNode error = errorMessage.CreateNode(XmlNodeType.Element, "error", "");
XmlNode region = errorMessage.CreateNode(XmlNodeType.Element, "region", "");
region.InnerText = regionName;
XmlNode exception = errorMessage.CreateNode(XmlNodeType.Element, "exception", "");
exception.InnerText = e.ToString();
error.AppendChild(region);
error.AppendChild(exception);
errorMessage.AppendChild(error);
return errorMessage;
}
#endregion
#region External data services
private void NotifyDataServices(string servicesStr, string serviceName)
{
Stream reply = null;
string delimStr = ";";
char [] delimiter = delimStr.ToCharArray();
string[] services = servicesStr.Split(delimiter);
for (int i = 0; i < services.Length; i++)
{
string url = services[i].Trim();
RestClient cli = new RestClient(url);
cli.AddQueryParameter("service", serviceName);
cli.AddQueryParameter("host", m_hostname);
cli.AddQueryParameter("port", m_listener_port);
cli.RequestMethod = "GET";
try
{
reply = cli.Request();
}
catch (WebException)
{
m_log.Warn("[DATASNAPSHOT]: Unable to notify " + url);
}
catch (Exception e)
{
m_log.Warn("[DATASNAPSHOT]: Ignoring unknown exception " + e.ToString());
}
byte[] response = new byte[1024];
// int n = 0;
try
{
// n = reply.Read(response, 0, 1024);
reply.Read(response, 0, 1024);
}
catch (Exception e)
{
m_log.WarnFormat("[DATASNAPSHOT]: Unable to decode reply from data service. Ignoring. {0}", e.StackTrace);
}
// This is not quite working, so...
// string responseStr = Encoding.UTF8.GetString(response);
m_log.Info("[DATASNAPSHOT]: data service notified: " + url);
}
}
#endregion
#region Latency-based update functions
public void MarkDataStale(IDataSnapshotProvider provider)
{
//Behavior here: Wait m_period seconds, then update if there has not been a request in m_period seconds
//or m_maxStales has been exceeded
m_stales++;
}
private void CheckStale()
{
// Wrap check
if (Environment.TickCount < m_lastUpdate)
{
m_lastUpdate = Environment.TickCount;
}
if (m_stales >= m_maxStales)
{
if (Environment.TickCount - m_lastUpdate >= 20000)
{
m_stales = 0;
m_lastUpdate = Environment.TickCount;
MakeEverythingStale();
}
}
else
{
if (m_lastUpdate + 1000 * m_period < Environment.TickCount)
{
m_stales = 0;
m_lastUpdate = Environment.TickCount;
MakeEverythingStale();
}
}
}
public void MakeEverythingStale()
{
m_log.Debug("[DATASNAPSHOT]: Marking all scenes as stale.");
foreach (Scene scene in m_scenes)
{
m_snapStore.ForceSceneStale(scene);
}
}
#endregion
public void OnSimRestart(RegionInfo thisRegion)
{
m_log.Info("[DATASNAPSHOT]: Region " + thisRegion.RegionName + " is restarting, removing from indexing");
Scene restartedScene = SceneForUUID(thisRegion.RegionID);
m_scenes.Remove(restartedScene);
m_snapStore.RemoveScene(restartedScene);
//Getting around the fact that we can't remove objects from a collection we are enumerating over
List<IDataSnapshotProvider> providersToRemove = new List<IDataSnapshotProvider>();
foreach (IDataSnapshotProvider provider in m_dataproviders)
{
if (provider.GetParentScene == restartedScene)
{
providersToRemove.Add(provider);
}
}
foreach (IDataSnapshotProvider provider in providersToRemove)
{
m_dataproviders.Remove(provider);
m_snapStore.RemoveProvider(provider);
}
m_snapStore.RemoveScene(restartedScene);
}
}
}
| |
using UnityEngine;
using System.Collections;
[RequireComponent (typeof (Rigidbody))]
public class NPCMove : MonoBehaviour {
public Transform target; //Player
public Transform cam; // Camera
public float moveSpeed = 5.0f;
public float rotSpeed = 2.0f;
public float rayLength = 4.0f;
public float minRange = 3.0f;
public float maxRange = 20.0f;
public float roamMaxTime = 5.0f;
public float roamMaxTimeRange = 1.5f;
public float screenDot = .8f;
public bool isChasing = true;
private Transform myTransform; //NPC
private Rigidbody myRigid;
private Vector3 myVelocity;
private bool isGrounded = false;
private bool isVisible = false;
private float minRangeSqr;
private float maxRangeSqr;
private float distSqr=0.0f;
private float roamTime = 0.0f;
private float roamTimeMaxAjd = 5.0f;
private Vector3 dirCalc;
private PlayerHealth playerHealthScript;
private Vignetting vignetting;
enum NPC{
Idle,
Roaming,
Chasing,
Return
}
NPC myState; //NPC State
void Start () {
minRangeSqr = minRange * minRange;
maxRangeSqr = maxRange * maxRange;
myTransform = transform;
myRigid = rigidbody;
myRigid.freezeRotation = true;
roamTime = 1000.0f;
myState = NPC.Roaming;
//InvokeRepeating("Teleport",10.0f,8.0f);
GameObject targetPlayer = GameObject.Find("Player");
if(targetPlayer){
target = targetPlayer.transform;
playerHealthScript = target.GetComponent<PlayerHealth>();
vignetting = cam.GetComponent<Vignetting>();
}
else
Debug.Log ("No player found");
}
// void Teleport(){
// CheckVisible();
//
// if(!isVisible){
// float distSqr = (target.position - myTransform.position).sqrMagnitude;
//
// if(distSqr > maxRangeSqr + 5.0f){
// float distTeleport = maxRange + 20.0f;
//
// Vector3 terrainPosCheck = target.position + (myTransform.right * distTeleport);
// terrainPosCheck.y = 5000.0f;
//
// RaycastHit hit;
//
// if(Physics.Raycast(terrainPosCheck,-Vector3.up, out hit, Mathf.Infinity)){
// if(hit.collider.gameObject.tag =="Floor")
// myTransform.position = hit.point + new Vector3(0,.25f,0);
// }
// }
// }
// }
void DecisionCall(){
CheckVisible();
distSqr = (target.position - myTransform.position).sqrMagnitude;
if(isVisible){
if(distSqr > maxRangeSqr)
myState=NPC.Roaming;
else{
RaycastHit hit;
if (Physics.Linecast( myTransform.position, target.position, out hit))
{
if (hit.collider.gameObject.name == target.name)
{
myState = NPC.Idle;
playerHealthScript.DecreaseHealth();
vignetting.chromaticAberration -= 0.05f;
vignetting.intensity +=0.02f;
}
else
{
myState = NPC.Roaming;
}
}
}
}
else {
if (distSqr > minRangeSqr)
myState=NPC.Chasing;
else
myState=NPC.Idle;
}
}
void Update () {
DecisionCall();
switch(myState){
case NPC.Idle:
myTransform.LookAt(target);
myVelocity = new Vector3(0,myRigid.velocity.y,0);
break;
case NPC.Roaming:
roamTime += Time.deltaTime;
if(roamTime > roamTimeMaxAjd){
roamTime =0;
roamTimeMaxAjd = roamMaxTime + Random.Range(-roamMaxTimeRange, roamMaxTimeRange);
dirCalc = Random.onUnitSphere;
dirCalc.y = 0;
}
// playerHealthScript.IncreaseHealth();
//
// vignetting.chromaticAberration += 0.1f;
//
// if(vignetting.chromaticAberration >= -3)
// vignetting.chromaticAberration = -3;
Moving(dirCalc);
break;
case NPC.Chasing:
Moving((target.position - myTransform.position).normalized);
break;
case NPC.Return:
Moving((myTransform.position - target.position).normalized);
break;
}
}
void CheckVisible(){
Vector3 fwd = target.forward;
Vector3 other = (myTransform.position - target.position).normalized;
float productDot = Vector3.Dot(fwd,other);
isVisible = false;
if(productDot > screenDot)
isVisible = true;
}
void Moving(Vector3 lookDir){
RaycastHit hit;
float sMultiplier = 0.75f;
Vector3 lRayPos = myTransform.position - (myTransform.right * sMultiplier);
Vector3 rRayPos = myTransform.position + (myTransform.right * sMultiplier);
if(Physics.Raycast(lRayPos, myTransform.forward, out hit, rayLength)){
if(hit.collider.gameObject.tag != "Floor")
lookDir += hit.normal * 20.0f;
}
else if (Physics.Raycast(rRayPos, myTransform.forward, out hit, rayLength)){
if(hit.collider.gameObject.tag != "Floor")
lookDir += hit.normal * 20.0f;
}
Quaternion lookRot = Quaternion.LookRotation(lookDir);
myTransform.rotation = Quaternion.Slerp( myTransform.rotation, lookRot, rotSpeed * Time.deltaTime );
//position
myVelocity = myTransform.forward * moveSpeed;
}
void FixedUpdate(){
if(isGrounded)
myRigid.velocity = myVelocity;
}
void OnCollisionEnter(Collision col){
if(col.collider.gameObject.tag == "Floor")
isGrounded = true;
}
void OnCollisionStay(Collision col){
if(col.collider.gameObject.tag == "Floor")
isGrounded = true;
}
void OnCollisionExit(Collision col){
if(col.collider.gameObject.tag == "Floor")
isGrounded = true;
}
}
| |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the lambda-2015-03-31.normal.json service model.
*/
using System;
using System.IO;
using System.Text;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Amazon.Lambda;
using Amazon.Lambda.Model;
using Amazon.Lambda.Model.Internal.MarshallTransformations;
using Amazon.Runtime.Internal.Transform;
using Amazon.Util;
using ServiceClientGenerator;
using AWSSDK_DotNet35.UnitTests.TestTools;
namespace AWSSDK_DotNet35.UnitTests.Marshalling
{
[TestClass]
public partial class LambdaMarshallingTests
{
static readonly ServiceModel service_model = Utils.LoadServiceModel("lambda-2015-03-31.normal.json", "lambda.customizations.json");
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("Lambda")]
public void AddPermissionMarshallTest()
{
var operation = service_model.FindOperation("AddPermission");
var request = InstantiateClassGenerator.Execute<AddPermissionRequest>();
var marshaller = new AddPermissionRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
RequestValidator.Validate("AddPermission", request, internalRequest, service_model);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString());
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse);
ResponseUnmarshaller unmarshaller = AddPermissionResponseUnmarshaller.Instance;
var response = unmarshaller.Unmarshall(context)
as AddPermissionResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("Lambda")]
public void CreateAliasMarshallTest()
{
var operation = service_model.FindOperation("CreateAlias");
var request = InstantiateClassGenerator.Execute<CreateAliasRequest>();
var marshaller = new CreateAliasRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
RequestValidator.Validate("CreateAlias", request, internalRequest, service_model);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString());
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse);
ResponseUnmarshaller unmarshaller = CreateAliasResponseUnmarshaller.Instance;
var response = unmarshaller.Unmarshall(context)
as CreateAliasResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("Lambda")]
public void CreateEventSourceMappingMarshallTest()
{
var operation = service_model.FindOperation("CreateEventSourceMapping");
var request = InstantiateClassGenerator.Execute<CreateEventSourceMappingRequest>();
var marshaller = new CreateEventSourceMappingRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
RequestValidator.Validate("CreateEventSourceMapping", request, internalRequest, service_model);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString());
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse);
ResponseUnmarshaller unmarshaller = CreateEventSourceMappingResponseUnmarshaller.Instance;
var response = unmarshaller.Unmarshall(context)
as CreateEventSourceMappingResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("Lambda")]
public void CreateFunctionMarshallTest()
{
var operation = service_model.FindOperation("CreateFunction");
var request = InstantiateClassGenerator.Execute<CreateFunctionRequest>();
var marshaller = new CreateFunctionRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
RequestValidator.Validate("CreateFunction", request, internalRequest, service_model);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString());
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse);
ResponseUnmarshaller unmarshaller = CreateFunctionResponseUnmarshaller.Instance;
var response = unmarshaller.Unmarshall(context)
as CreateFunctionResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("Lambda")]
public void DeleteAliasMarshallTest()
{
var operation = service_model.FindOperation("DeleteAlias");
var request = InstantiateClassGenerator.Execute<DeleteAliasRequest>();
var marshaller = new DeleteAliasRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
RequestValidator.Validate("DeleteAlias", request, internalRequest, service_model);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("Lambda")]
public void DeleteEventSourceMappingMarshallTest()
{
var operation = service_model.FindOperation("DeleteEventSourceMapping");
var request = InstantiateClassGenerator.Execute<DeleteEventSourceMappingRequest>();
var marshaller = new DeleteEventSourceMappingRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
RequestValidator.Validate("DeleteEventSourceMapping", request, internalRequest, service_model);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString());
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse);
ResponseUnmarshaller unmarshaller = DeleteEventSourceMappingResponseUnmarshaller.Instance;
var response = unmarshaller.Unmarshall(context)
as DeleteEventSourceMappingResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("Lambda")]
public void DeleteFunctionMarshallTest()
{
var operation = service_model.FindOperation("DeleteFunction");
var request = InstantiateClassGenerator.Execute<DeleteFunctionRequest>();
var marshaller = new DeleteFunctionRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
RequestValidator.Validate("DeleteFunction", request, internalRequest, service_model);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("Lambda")]
public void GetAliasMarshallTest()
{
var operation = service_model.FindOperation("GetAlias");
var request = InstantiateClassGenerator.Execute<GetAliasRequest>();
var marshaller = new GetAliasRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
RequestValidator.Validate("GetAlias", request, internalRequest, service_model);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString());
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse);
ResponseUnmarshaller unmarshaller = GetAliasResponseUnmarshaller.Instance;
var response = unmarshaller.Unmarshall(context)
as GetAliasResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("Lambda")]
public void GetEventSourceMappingMarshallTest()
{
var operation = service_model.FindOperation("GetEventSourceMapping");
var request = InstantiateClassGenerator.Execute<GetEventSourceMappingRequest>();
var marshaller = new GetEventSourceMappingRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
RequestValidator.Validate("GetEventSourceMapping", request, internalRequest, service_model);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString());
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse);
ResponseUnmarshaller unmarshaller = GetEventSourceMappingResponseUnmarshaller.Instance;
var response = unmarshaller.Unmarshall(context)
as GetEventSourceMappingResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("Lambda")]
public void GetFunctionMarshallTest()
{
var operation = service_model.FindOperation("GetFunction");
var request = InstantiateClassGenerator.Execute<GetFunctionRequest>();
var marshaller = new GetFunctionRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
RequestValidator.Validate("GetFunction", request, internalRequest, service_model);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString());
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse);
ResponseUnmarshaller unmarshaller = GetFunctionResponseUnmarshaller.Instance;
var response = unmarshaller.Unmarshall(context)
as GetFunctionResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("Lambda")]
public void GetFunctionConfigurationMarshallTest()
{
var operation = service_model.FindOperation("GetFunctionConfiguration");
var request = InstantiateClassGenerator.Execute<GetFunctionConfigurationRequest>();
var marshaller = new GetFunctionConfigurationRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
RequestValidator.Validate("GetFunctionConfiguration", request, internalRequest, service_model);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString());
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse);
ResponseUnmarshaller unmarshaller = GetFunctionConfigurationResponseUnmarshaller.Instance;
var response = unmarshaller.Unmarshall(context)
as GetFunctionConfigurationResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("Lambda")]
public void GetPolicyMarshallTest()
{
var operation = service_model.FindOperation("GetPolicy");
var request = InstantiateClassGenerator.Execute<GetPolicyRequest>();
var marshaller = new GetPolicyRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
RequestValidator.Validate("GetPolicy", request, internalRequest, service_model);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString());
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse);
ResponseUnmarshaller unmarshaller = GetPolicyResponseUnmarshaller.Instance;
var response = unmarshaller.Unmarshall(context)
as GetPolicyResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("Lambda")]
public void InvokeMarshallTest()
{
var operation = service_model.FindOperation("Invoke");
var request = InstantiateClassGenerator.Execute<InvokeRequest>();
var marshaller = new InvokeRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
RequestValidator.Validate("Invoke", request, internalRequest, service_model);
var webResponse = new WebResponseData
{
Headers = {
{"X-Amz-Function-Error","X-Amz-Function-Error_Value"},
{"X-Amz-Log-Result","X-Amz-Log-Result_Value"},
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString());
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse);
ResponseUnmarshaller unmarshaller = InvokeResponseUnmarshaller.Instance;
var response = unmarshaller.Unmarshall(context)
as InvokeResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("Lambda")]
public void InvokeAsyncMarshallTest()
{
var operation = service_model.FindOperation("InvokeAsync");
var request = InstantiateClassGenerator.Execute<InvokeAsyncRequest>();
var marshaller = new InvokeAsyncRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
RequestValidator.Validate("InvokeAsync", request, internalRequest, service_model);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString());
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse);
ResponseUnmarshaller unmarshaller = InvokeAsyncResponseUnmarshaller.Instance;
var response = unmarshaller.Unmarshall(context)
as InvokeAsyncResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("Lambda")]
public void ListAliasesMarshallTest()
{
var operation = service_model.FindOperation("ListAliases");
var request = InstantiateClassGenerator.Execute<ListAliasesRequest>();
var marshaller = new ListAliasesRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
RequestValidator.Validate("ListAliases", request, internalRequest, service_model);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString());
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse);
ResponseUnmarshaller unmarshaller = ListAliasesResponseUnmarshaller.Instance;
var response = unmarshaller.Unmarshall(context)
as ListAliasesResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("Lambda")]
public void ListEventSourceMappingsMarshallTest()
{
var operation = service_model.FindOperation("ListEventSourceMappings");
var request = InstantiateClassGenerator.Execute<ListEventSourceMappingsRequest>();
var marshaller = new ListEventSourceMappingsRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
RequestValidator.Validate("ListEventSourceMappings", request, internalRequest, service_model);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString());
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse);
ResponseUnmarshaller unmarshaller = ListEventSourceMappingsResponseUnmarshaller.Instance;
var response = unmarshaller.Unmarshall(context)
as ListEventSourceMappingsResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("Lambda")]
public void ListFunctionsMarshallTest()
{
var operation = service_model.FindOperation("ListFunctions");
var request = InstantiateClassGenerator.Execute<ListFunctionsRequest>();
var marshaller = new ListFunctionsRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
RequestValidator.Validate("ListFunctions", request, internalRequest, service_model);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString());
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse);
ResponseUnmarshaller unmarshaller = ListFunctionsResponseUnmarshaller.Instance;
var response = unmarshaller.Unmarshall(context)
as ListFunctionsResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("Lambda")]
public void ListVersionsByFunctionMarshallTest()
{
var operation = service_model.FindOperation("ListVersionsByFunction");
var request = InstantiateClassGenerator.Execute<ListVersionsByFunctionRequest>();
var marshaller = new ListVersionsByFunctionRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
RequestValidator.Validate("ListVersionsByFunction", request, internalRequest, service_model);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString());
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse);
ResponseUnmarshaller unmarshaller = ListVersionsByFunctionResponseUnmarshaller.Instance;
var response = unmarshaller.Unmarshall(context)
as ListVersionsByFunctionResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("Lambda")]
public void PublishVersionMarshallTest()
{
var operation = service_model.FindOperation("PublishVersion");
var request = InstantiateClassGenerator.Execute<PublishVersionRequest>();
var marshaller = new PublishVersionRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
RequestValidator.Validate("PublishVersion", request, internalRequest, service_model);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString());
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse);
ResponseUnmarshaller unmarshaller = PublishVersionResponseUnmarshaller.Instance;
var response = unmarshaller.Unmarshall(context)
as PublishVersionResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("Lambda")]
public void RemovePermissionMarshallTest()
{
var operation = service_model.FindOperation("RemovePermission");
var request = InstantiateClassGenerator.Execute<RemovePermissionRequest>();
var marshaller = new RemovePermissionRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
RequestValidator.Validate("RemovePermission", request, internalRequest, service_model);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("Lambda")]
public void UpdateAliasMarshallTest()
{
var operation = service_model.FindOperation("UpdateAlias");
var request = InstantiateClassGenerator.Execute<UpdateAliasRequest>();
var marshaller = new UpdateAliasRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
RequestValidator.Validate("UpdateAlias", request, internalRequest, service_model);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString());
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse);
ResponseUnmarshaller unmarshaller = UpdateAliasResponseUnmarshaller.Instance;
var response = unmarshaller.Unmarshall(context)
as UpdateAliasResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("Lambda")]
public void UpdateEventSourceMappingMarshallTest()
{
var operation = service_model.FindOperation("UpdateEventSourceMapping");
var request = InstantiateClassGenerator.Execute<UpdateEventSourceMappingRequest>();
var marshaller = new UpdateEventSourceMappingRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
RequestValidator.Validate("UpdateEventSourceMapping", request, internalRequest, service_model);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString());
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse);
ResponseUnmarshaller unmarshaller = UpdateEventSourceMappingResponseUnmarshaller.Instance;
var response = unmarshaller.Unmarshall(context)
as UpdateEventSourceMappingResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("Lambda")]
public void UpdateFunctionCodeMarshallTest()
{
var operation = service_model.FindOperation("UpdateFunctionCode");
var request = InstantiateClassGenerator.Execute<UpdateFunctionCodeRequest>();
var marshaller = new UpdateFunctionCodeRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
RequestValidator.Validate("UpdateFunctionCode", request, internalRequest, service_model);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString());
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse);
ResponseUnmarshaller unmarshaller = UpdateFunctionCodeResponseUnmarshaller.Instance;
var response = unmarshaller.Unmarshall(context)
as UpdateFunctionCodeResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
[TestMethod]
[TestCategory("UnitTest")]
[TestCategory("Rest_Json")]
[TestCategory("Lambda")]
public void UpdateFunctionConfigurationMarshallTest()
{
var operation = service_model.FindOperation("UpdateFunctionConfiguration");
var request = InstantiateClassGenerator.Execute<UpdateFunctionConfigurationRequest>();
var marshaller = new UpdateFunctionConfigurationRequestMarshaller();
var internalRequest = marshaller.Marshall(request);
RequestValidator.Validate("UpdateFunctionConfiguration", request, internalRequest, service_model);
var webResponse = new WebResponseData
{
Headers = {
{"x-amzn-RequestId", Guid.NewGuid().ToString()},
{"x-amz-crc32","0"}
}
};
var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute();
webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString());
var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse);
ResponseUnmarshaller unmarshaller = UpdateFunctionConfigurationResponseUnmarshaller.Instance;
var response = unmarshaller.Unmarshall(context)
as UpdateFunctionConfigurationResponse;
InstantiateClassGenerator.ValidateObjectFullyInstantiated(response);
}
}
}
| |
#if IGOR_RUNTIME || UNITY_EDITOR
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.IO;
using System;
using System.Reflection;
using System.Threading;
using System.Xml.Serialization;
namespace Igor
{
public class IgorCore : IIgorCore, IIgorStepHandler
{
public class JobStep
{
public IIgorModule ModuleInst;
public IgorRuntimeUtils.JobStepFunc StepFunction;
public JobStep(IIgorModule Module, IgorRuntimeUtils.JobStepFunc Function)
{
ModuleInst = Module;
StepFunction = Function;
}
}
public static List<IIgorModule> EnabledModules = new List<IIgorModule>();
public static List<IIgorModule> ActiveModulesForJob = new List<IIgorModule>();
public static Dictionary<StepID, List<JobStep>> JobSteps = new Dictionary<StepID, List<JobStep>>();
public static string NamedJobFlag = "ExecuteJob";
protected static string ProductsFlag = "moduleproducts";
public List<string> GetEnabledModuleNames()
{
return IgorConfig.GetInstance().GetEnabledModuleNames();
}
public static List<string> StaticGetEnabledModuleNames()
{
return IgorConfig.GetInstance().GetEnabledModuleNames();
}
static List<Type> _ModuleTypes;
static List<Type> ModuleTypes
{
get
{
if(_ModuleTypes == null)
_ModuleTypes = IgorRuntimeUtils.GetTypesInheritFrom<IIgorModule>();
return _ModuleTypes;
}
}
public static IIgorCore RuntimeCore = null;
protected static List<string> CurrentModuleProducts = new List<string>();
public static void Initialize()
{
#if !UNITY_EDITOR
IgorConfig.DefaultConfigPath = Path.Combine(Application.streamingAssetsPath, Path.Combine("Igor", IgorConfig.IgorConfigFilename));
#endif // !UNITY_EDITOR
}
public static void InitializeRuntimeCoreIfNeeded()
{
if(RuntimeCore == null)
{
List<Type> RuntimeCoreTypes = IgorRuntimeUtils.GetTypesInheritFrom<IIgorCore>();
if(RuntimeCoreTypes.Count > 0)
{
RuntimeCore = (IIgorCore)Activator.CreateInstance(RuntimeCoreTypes[0]);
}
}
}
public static void SetNewModuleProducts(List<string> NewModuleProducts)
{
CurrentModuleProducts.Clear();
CurrentModuleProducts.AddRange(NewModuleProducts);
string CombinedProducts = "";
foreach(string CurrentProduct in NewModuleProducts)
{
CombinedProducts += (CombinedProducts.Length > 0 ? "," : "") + CurrentProduct;
}
IgorJobConfig.SetStringParam(ProductsFlag, CombinedProducts);
}
public static List<string> GetModuleProducts()
{
if(CurrentModuleProducts.Count == 0)
{
string CombinedProducts = IgorJobConfig.GetStringParam(ProductsFlag);
CurrentModuleProducts.Clear();
CurrentModuleProducts.AddRange(CombinedProducts.Split(','));
}
return CurrentModuleProducts;
}
public virtual void RegisterJobStep(StepID CurrentStep, IIgorModule Module, IgorRuntimeUtils.JobStepFunc StepFunction)
{
StaticRegisterJobStep(CurrentStep, Module, StepFunction);
}
protected static void StaticRegisterJobStep(StepID CurrentStep, IIgorModule Module, IgorRuntimeUtils.JobStepFunc StepFunction)
{
List<JobStep> NewSteps = new List<JobStep>();
StepID Priority = new StepID();
foreach(KeyValuePair<StepID, List<JobStep>> CurrentPriority in JobSteps)
{
if(CurrentPriority.Key.StepPriority == CurrentStep.StepPriority)
{
NewSteps = CurrentPriority.Value;
Priority = CurrentPriority.Key;
break;
}
}
NewSteps.Add(new JobStep(Module, StepFunction));
if(JobSteps.ContainsKey(Priority))
{
JobSteps[Priority] = NewSteps;
}
else
{
JobSteps.Add(CurrentStep, NewSteps);
}
}
public static void RegisterAllModules()
{
foreach(Type CurrentType in ModuleTypes)
{
IIgorModule CurrentModule = (IIgorModule)Activator.CreateInstance(CurrentType);
if(CurrentModule != null)
{
CurrentModule.RegisterModule();
}
}
}
public static void ProcessArgs()
{
InitializeRuntimeCoreIfNeeded();
if(RuntimeCore != null)
{
if(typeof(IgorCore).IsAssignableFrom(RuntimeCore.GetType()))
{
IgorCore CoreInst = (IgorCore)RuntimeCore;
if(CoreInst != null)
{
ActiveModulesForJob.Clear();
foreach(IIgorModule CurrentModule in EnabledModules)
{
CurrentModule.ProcessArgs(CoreInst);
}
}
else
{
IgorDebug.CoreCriticalError("Core could not be case to type IgorCore!");
}
}
else
{
IgorDebug.CoreCriticalError("Core is not of type IgorCore. Did you make your own? You may need to change how this works.");
}
}
else
{
IgorDebug.CoreCriticalError("Core not found so we bailed out of processing arguments!");
}
}
public struct JobReturnStatus
{
public bool bDone;
public bool bFailed;
public bool bWasStartedManually;
}
public static JobReturnStatus RunJob(bool bFromMenu = false)
{
bool bWasStartedManually = false;
bool bThrewException = false;
bool bDone = false;
try
{
if(!IgorJobConfig.GetIsRunning())
{
IgorDebug.CoreLog("Job is starting!");
IgorAssert.StartJob();
CheckForNamedJobFlag();
}
if(IgorJobConfig.GetWasMenuTriggered())
{
bWasStartedManually = true;
}
else
{
bWasStartedManually = bFromMenu;
IgorJobConfig.SetWasMenuTriggered(bWasStartedManually);
}
if(!IgorJobConfig.GetIsRunning() || EnabledModules.Count == 0)
{
RegisterAllModules();
}
if(!IgorJobConfig.GetIsRunning() || ActiveModulesForJob.Count == 0)
{
ProcessArgs();
}
if(ExecuteSteps())
{
IgorJobConfig.SetIsRunning(false);
bDone = true;
}
}
catch(Exception e)
{
IgorDebug.CoreLogError("Caught exception while running the job. Exception is " + (e == null ? "NULL exception!" : e.ToString() +
(e.InnerException == null ? "\n\nNULL inner exception." : ("\n\nInner: " + e.InnerException.ToString()))));
bThrewException = true;
}
finally
{
if(bThrewException || bDone)
{
Cleanup();
}
}
JobReturnStatus NewStatus = new JobReturnStatus();
NewStatus.bDone = bDone;
NewStatus.bFailed = bThrewException || IgorAssert.HasJobFailed();
NewStatus.bWasStartedManually = bWasStartedManually;
return NewStatus;
}
public static void HandleJobStatus(IgorCore.JobReturnStatus Status)
{
if(Status.bDone)
{
if(IgorAssert.HasJobFailed())
{
IgorDebug.CoreLogError("Job failed!");
}
else
{
IgorDebug.CoreLog("Job's done!");
}
}
if(!Status.bWasStartedManually && (Status.bFailed || Status.bDone))
{
if(Status.bFailed)
{
Application.Quit();
}
else
{
Application.Quit();
}
}
}
public static void Cleanup()
{
foreach(IIgorModule module in ActiveModulesForJob)
{
module.PostJobCleanup();
}
ActiveModulesForJob.Clear();
JobSteps.Clear();
IgorJobConfig.Cleanup();
}
public static bool RegisterNewModule(IIgorModule NewModule)
{
if(StaticGetEnabledModuleNames().Contains(NewModule.GetModuleName()))
{
bool bFound = false;
foreach(IIgorModule CurrentModule in EnabledModules)
{
if(CurrentModule.GetModuleName() == NewModule.GetModuleName())
{
bFound = true;
}
}
if(!bFound)
{
EnabledModules.Add(NewModule);
return true;
}
}
return false;
}
public static void SetModuleActiveForJob(IIgorModule NewModule)
{
if(EnabledModules.Contains(NewModule) && !ActiveModulesForJob.Contains(NewModule))
{
bool bFound = false;
foreach(IIgorModule CurrentModule in ActiveModulesForJob)
{
if(CurrentModule.GetModuleName() == NewModule.GetModuleName())
{
bFound = true;
}
}
if(!bFound)
{
ActiveModulesForJob.Add(NewModule);
}
}
}
public static bool ExecuteSteps()
{
if(IgorAssert.HasJobFailed())
{
IgorDebug.CoreLogError("Job failed so we are bailing out early and not finishing the remaining steps!");
return false;
}
List<StepID> SortedSteps = new List<StepID>(JobSteps.Keys);
SortedSteps.Sort();
IgorJobConfig.SetIsRunning(true);
int StartingPriority = IgorJobConfig.GetLastPriority();
int StartingIndexInPriority = IgorJobConfig.GetLastIndexInPriority();
foreach(StepID CurrentStep in SortedSteps)
{
if(CurrentStep.StepPriority > StartingPriority)
{
IgorJobConfig.SetLastPriority(CurrentStep.StepPriority - 1);
int LastIndex = 0;
List<JobStep> CurrentStepFuncs = JobSteps[CurrentStep];
foreach(JobStep CurrentFunction in CurrentStepFuncs)
{
if(LastIndex > StartingIndexInPriority)
{
if(CurrentFunction.StepFunction())
{
IgorJobConfig.SetLastIndexInPriority(LastIndex);
}
return false;
}
++LastIndex;
}
StartingIndexInPriority = -1;
IgorJobConfig.SetLastIndexInPriority(-1);
}
}
return true;
}
public static void CheckForNamedJobFlag()
{
if(IgorJobConfig.IsStringParamSet(NamedJobFlag))
{
string JobToStart = IgorJobConfig.GetStringParam(NamedJobFlag);
foreach(IgorPersistentJobConfig Job in IgorConfig.GetInstance().JobConfigs)
{
if(Job.JobName == JobToStart)
{
IgorJobConfig ConfigInst = IgorJobConfig.GetConfig();
ConfigInst.Persistent = Job;
ConfigInst.Save(IgorJobConfig.IgorJobConfigPath);
IgorDebug.CoreLog("Starting named job " + JobToStart + ".");
return;
}
}
IgorDebug.CoreLogError("Couldn't find named job " + JobToStart + "!");
}
}
public virtual bool IsModuleNeededByOtherModules(IIgorModule Module)
{
return StaticIsModuleNeededByOtherModules(Module);
}
public static bool StaticIsModuleNeededByOtherModules(IIgorModule Module)
{
foreach(IIgorModule CurrentModule in EnabledModules)
{
if(CurrentModule.IsDependentOnModule(Module))
{
return true;
}
}
return false;
}
}
}
#endif // IGOR_RUNTIME || UNITY_EDITOR
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace Api.Web.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
internal const int DefaultCollectionSize = 2;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
// 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 AndNotInt16()
{
var test = new SimpleBinaryOpTest__AndNotInt16();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (Sse2.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (Sse2.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (Sse2.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (Sse2.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (Sse2.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__AndNotInt16
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle2;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Int16[] inArray1, Int16[] inArray2, Int16[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int16>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int16>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int16>();
if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Int16, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int16, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector128<Int16> _fld1;
public Vector128<Int16> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref testStruct._fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref testStruct._fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>());
return testStruct;
}
public void RunStructFldScenario(SimpleBinaryOpTest__AndNotInt16 testClass)
{
var result = Sse2.AndNot(_fld1, _fld2);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleBinaryOpTest__AndNotInt16 testClass)
{
fixed (Vector128<Int16>* pFld1 = &_fld1)
fixed (Vector128<Int16>* pFld2 = &_fld2)
{
var result = Sse2.AndNot(
Sse2.LoadVector128((Int16*)(pFld1)),
Sse2.LoadVector128((Int16*)(pFld2))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Int16>>() / sizeof(Int16);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Int16>>() / sizeof(Int16);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Int16>>() / sizeof(Int16);
private static Int16[] _data1 = new Int16[Op1ElementCount];
private static Int16[] _data2 = new Int16[Op2ElementCount];
private static Vector128<Int16> _clsVar1;
private static Vector128<Int16> _clsVar2;
private Vector128<Int16> _fld1;
private Vector128<Int16> _fld2;
private DataTable _dataTable;
static SimpleBinaryOpTest__AndNotInt16()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _clsVar1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _clsVar2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>());
}
public SimpleBinaryOpTest__AndNotInt16()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); }
_dataTable = new DataTable(_data1, _data2, new Int16[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Sse2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Sse2.AndNot(
Unsafe.Read<Vector128<Int16>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Int16>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Sse2.AndNot(
Sse2.LoadVector128((Int16*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Int16*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Sse2.AndNot(
Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Sse2).GetMethod(nameof(Sse2.AndNot), new Type[] { typeof(Vector128<Int16>), typeof(Vector128<Int16>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Int16>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Int16>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Sse2).GetMethod(nameof(Sse2.AndNot), new Type[] { typeof(Vector128<Int16>), typeof(Vector128<Int16>) })
.Invoke(null, new object[] {
Sse2.LoadVector128((Int16*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Int16*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Sse2).GetMethod(nameof(Sse2.AndNot), new Type[] { typeof(Vector128<Int16>), typeof(Vector128<Int16>) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Sse2.AndNot(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector128<Int16>* pClsVar1 = &_clsVar1)
fixed (Vector128<Int16>* pClsVar2 = &_clsVar2)
{
var result = Sse2.AndNot(
Sse2.LoadVector128((Int16*)(pClsVar1)),
Sse2.LoadVector128((Int16*)(pClsVar2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector128<Int16>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector128<Int16>>(_dataTable.inArray2Ptr);
var result = Sse2.AndNot(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = Sse2.LoadVector128((Int16*)(_dataTable.inArray1Ptr));
var op2 = Sse2.LoadVector128((Int16*)(_dataTable.inArray2Ptr));
var result = Sse2.AndNot(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var op1 = Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArray1Ptr));
var op2 = Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArray2Ptr));
var result = Sse2.AndNot(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleBinaryOpTest__AndNotInt16();
var result = Sse2.AndNot(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new SimpleBinaryOpTest__AndNotInt16();
fixed (Vector128<Int16>* pFld1 = &test._fld1)
fixed (Vector128<Int16>* pFld2 = &test._fld2)
{
var result = Sse2.AndNot(
Sse2.LoadVector128((Int16*)(pFld1)),
Sse2.LoadVector128((Int16*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Sse2.AndNot(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector128<Int16>* pFld1 = &_fld1)
fixed (Vector128<Int16>* pFld2 = &_fld2)
{
var result = Sse2.AndNot(
Sse2.LoadVector128((Int16*)(pFld1)),
Sse2.LoadVector128((Int16*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Sse2.AndNot(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = Sse2.AndNot(
Sse2.LoadVector128((Int16*)(&test._fld1)),
Sse2.LoadVector128((Int16*)(&test._fld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector128<Int16> op1, Vector128<Int16> op2, void* result, [CallerMemberName] string method = "")
{
Int16[] inArray1 = new Int16[Op1ElementCount];
Int16[] inArray2 = new Int16[Op2ElementCount];
Int16[] outArray = new Int16[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), op2);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int16>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "")
{
Int16[] inArray1 = new Int16[Op1ElementCount];
Int16[] inArray2 = new Int16[Op2ElementCount];
Int16[] outArray = new Int16[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Int16>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Int16>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int16>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Int16[] left, Int16[] right, Int16[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if ((short)(~left[0] & right[0]) != result[0])
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if ((short)(~left[i] & right[i]) != result[i])
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Sse2)}.{nameof(Sse2.AndNot)}<Int16>(Vector128<Int16>, Vector128<Int16>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
// 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.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Diagnostics.Contracts;
using Microsoft.Research.DataStructures;
namespace Microsoft.Research.CodeAnalysis
{
using Provenance = IEnumerable<ProofObligation>;
using Microsoft.Research.CodeAnalysis.Inference;
using System.Diagnostics.CodeAnalysis;
public class SimplePostconditionDispatcher
{
public static List<Tuple<Method, BoxedExpression.AssertExpression, Provenance>>
GetCandidatePostconditionsForAutoProperties<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly>
(IEnumerable<BoxedExpression> boxedExpressions, IDecodeMetaData<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly> mdd,
FieldsDB<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly> fieldsDB)
{
var result = new List<Tuple<Method, BoxedExpression.AssertExpression, Provenance>>();
if (boxedExpressions != null)
{
foreach (var post in boxedExpressions.Where(exp => { return exp.IsBinary; }))
{
Contract.Assume(post != null);
BoxedExpression exp;
if (post.IsCheckExpNotNotNull(out exp))
{
var path = exp.AccessPath;
if (path != null)
{
Method m;
if (path[0].ToString() == "this" && path[path.Length - 1].IsMethodCall && path[path.Length - 1].TryMethod(out m) && mdd.IsAutoPropertyMember(m))
{
Method setter;
if (mdd.TryGetSetterFromGetter(m, out setter) && fieldsDB.IsCalledInANonConstructor(setter))
{
#if DEBUG
Console.WriteLine("[INFERENCE] Skipping the inference of the postcondition '{0}' to an autoproperty because found it is set in a non-constructor", post);
#endif
continue;
}
var t = mdd.ReturnType(m);
var neqNull = BoxedExpression.Binary(BinaryOperator.Cne_Un, BoxedExpression.Result(t), BoxedExpression.Const(null, t, mdd));
#if DEBUG
Console.WriteLine("[INFERENCE] Propagating the postcondition '{0}' to the autoproperty", post);
#endif
var p = new BoxedExpression.AssertExpression(neqNull, "ensures", APC.Dummy, null, null);
result.Add(new Tuple<Method, BoxedExpression.AssertExpression, Provenance>(m, p, null));
}
}
}
}
}
return result;
}
}
[ContractVerification(true)]
public class SimplePostconditionDispatcher<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, Expression, Variable, LogOptions>
: IPostconditionDispatcher
where LogOptions : IFrameworkLogOptions
where Variable : IEquatable<Variable>
where Expression : IEquatable<Expression>
where Type : IEquatable<Type>
{
#region Statics
private const string ContractPostconditionTemplate = "Contract.Ensures({0});";
#endregion
#region Object invariant
[ContractInvariantMethod]
private void ObjectInvariant()
{
Contract.Invariant(this.output != null);
Contract.Invariant(this.mDriver != null);
Contract.Invariant(this.globalInfo != null);
Contract.Invariant(this.inferredPostconditions != null);
}
#endregion
#region Private state
readonly private IMethodDriver<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, Expression, Variable, LogOptions> mDriver;
readonly private SharedPostConditionManagerInfo<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly> globalInfo;
readonly private IOutputResults output;
readonly private ClousotSuggestion.Ensures PostconditionSuggestionFilter;
readonly private List<BoxedExpression> inferredPostconditions;
readonly private bool warnAndFilterIfExternallyVisible;
readonly private bool aggressiveInference;
private List<BoxedExpression> filteredPostconditions;
#endregion
#region Constructor
public SimplePostconditionDispatcher(
SharedPostConditionManagerInfo<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly> globalInfo,
IMethodDriver<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, Expression, Variable, LogOptions> mDriver, IOutputResults output, ClousotSuggestion.Ensures suggestionFilter, bool warnAndFilterIfExternallyVisible, bool aggressiveInference)
{
Contract.Requires(globalInfo != null);
Contract.Requires(output != null);
Contract.Requires(mDriver != null);
this.mDriver = mDriver;
this.output = output;
this.inferredPostconditions = new List<BoxedExpression>();
this.filteredPostconditions = null;
this.globalInfo = globalInfo;
this.PostconditionSuggestionFilter = suggestionFilter;
this.warnAndFilterIfExternallyVisible = warnAndFilterIfExternallyVisible;
this.aggressiveInference = aggressiveInference;
}
#endregion
#region Implementation
public void AddPostconditions(IEnumerable<BoxedExpression> postconditions)
{
if (this.filteredPostconditions != null)
{
throw new InvalidOperationException("The object is sealed: cannot add postconditions anymore");
}
this.inferredPostconditions.AddRange(postconditions);
}
public void AddNonNullFields(object method, IEnumerable<object> fields)
{
var m = (Method)method;
var f = fields;
this.globalInfo.AddNonNullFields(m, f);
}
public IEnumerable<object> GetNonNullFields(object method)
{
var m = (Method)method;
IEnumerable<Tuple<Field, BoxedExpression>> result;
if(this.globalInfo.TryNonNullFields(m, out result))
{
return result;
}
else
{
return Enumerable.Empty<object>();
}
}
public List<BoxedExpression> GeneratePostconditions()
{
if (this.filteredPostconditions == null)
{
this.filteredPostconditions = new List<BoxedExpression>();
var db = new Set<string>();
foreach (var p in this.inferredPostconditions)
{
if (p != null)
{
var str = p.ToString();
if (!db.Contains(str))
{
this.filteredPostconditions.Add(p);
db.Add(str);
}
}
}
}
return filteredPostconditions;
}
public int SuggestPostconditions()
{
var md = this.mDriver;
var mdd = md.MetaDataDecoder;
var pc = md.CFG.GetPCForMethodEntry();
var count = 0;
// No suggestions on struct constructors
if(mdd.IsConstructor(md.CurrentMethod) && mdd.IsStruct(mdd.DeclaringType(md.CurrentMethod)))
{
return count;
}
foreach (var p in this.GeneratePostconditions().Where(p => p != null && !p.IsConstantFalse()))
{
Contract.Assume(p != null);
bool containsResult;
if (this.IsAdmissible(p, out containsResult))
{
if (this.warnAndFilterIfExternallyVisible)
{
if(mdd.IsVisibleOutsideAssembly(md.CurrentMethod) && (aggressiveInference || containsResult))
{
var suggestion = string.Format("Consider adding the postcondition {0} to provide extra-documentation to the library clients", MakePostconditionString(p.ToString()));
this.output.Suggestion(ClousotSuggestion.Kind.Ensures, "contract for public surface member", pc, suggestion, null, ClousotSuggestion.ExtraSuggestionInfo.None);
}
#if DEBUG
else
{
this.output.WriteLine("[INFERENCE] Postcondition {0} has been filted because is not considered admissible (the method is not visible or it does not contain a result and the inference is not aggressive)- we are only showing it in debug mode", p.ToString());
}
#endif
}
else
{
this.output.Suggestion(ClousotSuggestion.Kind.Ensures, ClousotSuggestion.Kind.Ensures.Message(), pc, MakePostconditionString(p.ToString()), null, ClousotSuggestion.ExtraSuggestionInfo.None);
count++;
}
}
#if DEBUG
else
{
this.output.WriteLine("[INFERENCE] Postcondition {0} has been filted because is not considered admissible for printing - we are only showing it in debug mode", p.ToString());
}
#endif
}
return count;
}
public int SuggestNonNullFieldsForConstructors()
{
var md = this.mDriver;
var t = md.MetaDataDecoder.DeclaringType(md.CurrentMethod);
if (this.globalInfo.CanSuggestInvariantFor(t))
{
return this.globalInfo.SuggestNonNullFieldsForConstructors(md.CFG.GetPCForMethodEntry(), t, this.output);
}
return 0;
}
public IEnumerable<BoxedExpression> SuggestNonNullObjectInvariantsFromConstructorsForward(bool doNotRecord)
{
var md = this.mDriver;
var mdd = md.MetaDataDecoder;
var type = mdd.DeclaringType(md.CurrentMethod);
return this.globalInfo.SuggestNonNullObjectInvariantsFromConstructorsForward(type, doNotRecord);
}
public int PropagatePostconditions()
{
if (!this.mDriver.CanAddEnsures())
{
return 0;
}
var pc = this.mDriver.CFG.Entry;
var count = 0;
// TODO: We do not propagate quantified expressions
foreach (var post in this.GeneratePostconditions().Where(exp => !exp.IsQuantified))
{
Contract.Assume(post != null);
Provenance provenance = null; // TODO: encode where this contract comes from.
if (CanPropagate(post))
{
this.mDriver.AddPostCondition(post, pc, provenance);
count++;
}
}
#if DEBUG
if(count != this.GeneratePostconditions().Count)
{
Console.WriteLine("[INFERENCE] We did not propagate all the generated postconditions. This is probably because either we had some Forall(...), and CC does not know how to handle inferred ForAll postconditions");
}
#endif
return count;
}
public int PropagatePostconditionsForProperties()
{
// Only for constructors
if (!this.mDriver.MetaDataDecoder.IsConstructor(this.mDriver.CurrentMethod))
{
return 0;
}
this.mDriver.AddPostConditionsForAutoProperties(SimplePostconditionDispatcher.GetCandidatePostconditionsForAutoProperties(this.GeneratePostconditions(), this.mDriver.MetaDataDecoder, this.globalInfo.FieldDB));
return 0;
}
[SuppressMessage("Microsoft.Contracts", "TestAlwaysEvaluatingToAConstant")]
public bool MayReturnNull(IFact facts, TimeOutChecker timeout)
{
var moreRefinedFacts = facts as IFactQuery<BoxedExpression, Variable>;
if (facts != null)
{
bool mayReturnNull;
var search = new PostconditionWitnessSeaker<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, Expression, Variable, LogOptions>(moreRefinedFacts, this.mDriver);
return search.TryGetAWitness(this.mDriver.CFG.NormalExit, timeout, out mayReturnNull) && mayReturnNull;
}
return false;
}
public bool EmitWarningIfFalseIsInferred()
{
var md = this.mDriver;
var cd = md.AnalysisDriver.ContractDecoder;
var currMethod = md.CurrentMethod;
if (this.GeneratePostconditions().Any(exp => exp.IsConstantFalse()))
{
if (md.AdditionalSyntacticInformation.AssertedPostconditions.Any(exp => exp.IsConstantFalse())
||
(md.AdditionalSyntacticInformation.HasThrow && md.BasicFacts.IsUnreachable(md.CFG.NormalExit))
)
{
// If the method has already an ensures "false", then we do nothing.
// HACK: If the method normal exit is unreachable, and the method has a throw instruction, then we do nothing.
// Of course, this does not imply that the throw instruction dominates the normal exit, we only use it as an heuristic
return false;
}
else
{
var witness = new Witness(null /* no proof obligation causes it*/, WarningType.FalseEnsures, ProofOutcome.Top, md.CFG.GetPCForMethodEntry());
var isConstructor = md.MetaDataDecoder.IsConstructor(currMethod);
string outputMessage;
if (cd.HasEnsures(currMethod) || cd.HasInvariant(currMethod))
{
outputMessage = String.Format("{0} ensures (and invariants) are in contradiction with the detected code behavior. If this is wanted, consider adding Contract.Ensures(false) to document that it never returns normally", isConstructor ? "Constructor" : "Method");
}
else
{
outputMessage = String.Format("The normal exit of the method is unreachable. If this is wanted, consider adding Contract.Ensures(false) to document it");
}
this.output.EmitOutcome(witness, outputMessage);
}
return true;
}
return false;
}
#endregion
#region private
[Pure]
private bool CanPropagate(BoxedExpression be)
{
Contract.Requires(be != null);
Contract.Assert(this.mDriver.MetaDataDecoder != null);
var options = this.output.LogOptions;
var md = this.mDriver;
var currMethod = md.CurrentMethod;
if (options.PropagateInferredEnsures(md.MetaDataDecoder.IsPropertyGetterOrSetter(currMethod)))
{
return true;
}
if (options.PropagateInferredNonNullReturn
&& !this.mDriver.AdditionalSyntacticInformation.HasExceptionHandlers) // Avoid inferring a postcondition if we have an exception handler, has Clousot ignores those
{
BinaryOperator bop;
BoxedExpression left, right;
if (be.IsBinaryExpression(out bop, out left, out right) && (bop == BinaryOperator.Ceq || bop == BinaryOperator.Cne_Un)
&& (left.IsNull || right.IsNull))
{
// TODO check the other is the return value
return true;
}
}
if (options.PropagateInferredSymbolicReturn && md.AnalysisDriver.ContractDecoder.IsPure(currMethod))
{
BinaryOperator bop;
BoxedExpression left, right;
if (be.IsBinaryExpression(out bop, out left, out right) && bop == BinaryOperator.Ceq && (left.IsResult || right.IsResult))
{
return true;
}
}
return false;
}
[Pure]
private static string MakePostconditionString(string condition)
{
return string.Format(ContractPostconditionTemplate, condition);
}
[Pure]
private bool IsAdmissible(BoxedExpression p, out bool containsResult)
{
Contract.Requires(p != null);
containsResult = false;
switch (this.PostconditionSuggestionFilter)
{
case ClousotSuggestion.Ensures.NonNull:
case ClousotSuggestion.Ensures.NonNullReturnOnly: // Never used?????
{
BinaryOperator bop;
BoxedExpression left, right;
var isExpBopNull = p.IsBinaryExpression(out bop, out left, out right) && bop.IsEqualityOrDisequality() && (right.IsNull || left.IsNull);
if(!isExpBopNull)
{
return false;
}
Contract.Assert(isExpBopNull);
containsResult = left.IsResult || right.IsResult;
if(this.PostconditionSuggestionFilter == ClousotSuggestion.Ensures.NonNullReturnOnly)
{
return left.IsResult;
}
return isExpBopNull; // which should be true
}
default:
{
containsResult = p.ContainsReturnValue();
return true;
}
}
}
#endregion
}
public class SharedPostConditionManagerInfo<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly>
where Type : IEquatable<Type>
{
#region State
readonly private IDecodeMetaData<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly> metadataDecoder;
public FieldsDB<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly> FieldDB { get; private set; }
readonly private Dictionary<Method, IEnumerable<Tuple<Field, BoxedExpression>>> nnFieldsAtMethodExitPoint;
readonly private Dictionary<Type, Set<Method>> analyzedConstructors;
readonly private Set<Type> completeTypes;
readonly private Set<Type> typesWeSuggestedNonNullFields;
readonly private Set<Type> typesWeSuggestedObjectInvariants;
#endregion
public SharedPostConditionManagerInfo(IDecodeMetaData<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly> metadataDecoder, FieldsDB<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly> fieldDB)
{
Contract.Requires(metadataDecoder != null);
Contract.Requires(fieldDB != null);
this.metadataDecoder = metadataDecoder;
this.FieldDB = fieldDB;
this.nnFieldsAtMethodExitPoint = new Dictionary<Method, IEnumerable<Tuple<Field, BoxedExpression>>>();
this.analyzedConstructors = new Dictionary<Type, Set<Method>>();
this.completeTypes = new Set<Type>();
this.typesWeSuggestedNonNullFields = new Set<Type>();
this.typesWeSuggestedObjectInvariants = new Set<Type>();
}
public void AddNonNullFields(Method method, IEnumerable<object> fields)
{
this.nnFieldsAtMethodExitPoint[method] = fields.OfType<Tuple<Field, BoxedExpression>>();
RecordAnalysisOf(method);
}
public bool TryNonNullFields(Method m, out IEnumerable<Tuple<Field, BoxedExpression>> fields)
{
return this.nnFieldsAtMethodExitPoint.TryGetValue(m, out fields);
}
internal bool CanSuggestInvariantFor(Type t)
{
return this.completeTypes.Contains(t) && !this.typesWeSuggestedNonNullFields.Contains(t);
}
internal int SuggestNonNullFieldsForConstructors(APC pc, Type t, IOutputResults output)
{
Contract.Ensures(Contract.Result<int>() >= 0);
var md = this.metadataDecoder;
var count = 0;
// No suggestions for structs
if(md.IsStruct(t))
{
return count;
}
var result = GenerateObjectInvariantsForType(t);
if (result.Any())
{
foreach (var f in result)
{
var contract = string.Format("Contract.Invariant({0} != null);", md.Name(f.Item1));
var extraInfo = new ClousotSuggestion.ExtraSuggestionInfo() { SuggestedCode = contract, TypeDocumentId = md.DocumentationId(t) };
var str = String.Format("Consider adding an object invariant {0} to the type {1}", contract, md.Name(t));
output.Suggestion(ClousotSuggestion.Kind.ObjectInvariant, ClousotSuggestion.Kind.ObjectInvariant.ToString(), pc, str, null, extraInfo);
count++;
}
}
this.typesWeSuggestedNonNullFields.Add(t);
return count;
}
/// <summary>
/// ** INVARIANT ** We only suggest the invariants once for each typem unless doNotRecord is set
/// </summary>
public IEnumerable<BoxedExpression> SuggestNonNullObjectInvariantsFromConstructorsForward(Type type, bool doNotRecord)
{
Contract.Ensures(Contract.Result<IEnumerable<BoxedExpression>>() != null);
var mdd = this.metadataDecoder;
if (mdd.IsStruct(type))
{
return Enumerable.Empty<BoxedExpression>();
}
if(doNotRecord)
{
return this.GenerateObjectInvariantsForType(type).Select(pair => pair.Item2);
}
if (!this.typesWeSuggestedObjectInvariants.Contains(type))
{
return this.GenerateObjectInvariantsForType(type).Select(pair => pair.Item2);
}
else
{
return Enumerable.Empty<BoxedExpression>();
}
}
#region Private
private IEnumerable<Tuple<Field, BoxedExpression>> GenerateObjectInvariantsForType(Type t)
{
Contract.Requires(!this.typesWeSuggestedObjectInvariants.Contains(t));
if(!HaveSeenAllConstructorsOf(t))
{
return Enumerable.Empty<Tuple<Field, BoxedExpression>>();
}
// We are going to suggest the object invariant
this.typesWeSuggestedObjectInvariants.Add(t);
var md = this.metadataDecoder;
var isFirst = true;
IEnumerable<Tuple<Field, BoxedExpression>> result = /* to please the C# compiler */ new Set<Tuple<Field, BoxedExpression>>();
foreach (var fields in this.nnFieldsAtMethodExitPoint.Where(pair => md.IsConstructor(pair.Key) && md.DeclaringType(pair.Key).Equals(t)).Select(x => x.Value))
{
if (isFirst)
{
result = fields;
isFirst = false;
}
else
{
// Just Intersect seems not to work. So we do the work in the ugly way
var f = fields.Select(pair => pair.Item1).ToSet();
result = result.Where(pair => f.Contains(pair.Item1));
}
if (!result.Any())
{
break;
}
}
return result.Where(pair => (md.IsReadonly(pair.Item1) || this.FieldDB.IsACandidateReadonly(pair.Item1)));
}
private bool HaveSeenAllConstructorsOf(Type t)
{
var md = this.metadataDecoder;
return md.ConstructorsCount(t) == this.nnFieldsAtMethodExitPoint.Where(pair => md.IsConstructor(pair.Key) && md.DeclaringType(pair.Key).Equals(t)).Count();
}
private void RecordAnalysisOf(Method m)
{
var md = this.metadataDecoder;
if (md.IsConstructor(m))
{
var type = md.DeclaringType(m);
Set<Method> constructorsAnalyzedForAType;
if (!this.analyzedConstructors.TryGetValue(type, out constructorsAnalyzedForAType))
{
constructorsAnalyzedForAType = new Set<Method>();
this.analyzedConstructors[type] = constructorsAnalyzedForAType;
}
constructorsAnalyzedForAType.Add(m);
// We saw all the constructors for this type
if (constructorsAnalyzedForAType.Count == md.ConstructorsCount(type))
{
this.completeTypes.Add(type);
}
}
}
#endregion
}
}
| |
// Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.NotificationHubs
{
using System.Threading.Tasks;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// Extension methods for NamespacesOperations.
/// </summary>
public static partial class NamespacesOperationsExtensions
{
/// <summary>
/// Checks the availability of the given service namespace across all Azure
/// subscriptions. This is useful because the domain name is created based on
/// the service namespace name.
/// <see href="http://msdn.microsoft.com/en-us/library/windowsazure/jj870968.aspx" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='parameters'>
/// The namespace name.
/// </param>
public static CheckAvailabilityResult CheckAvailability(this INamespacesOperations operations, CheckAvailabilityParameters parameters)
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((INamespacesOperations)s).CheckAvailabilityAsync(parameters), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Checks the availability of the given service namespace across all Azure
/// subscriptions. This is useful because the domain name is created based on
/// the service namespace name.
/// <see href="http://msdn.microsoft.com/en-us/library/windowsazure/jj870968.aspx" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='parameters'>
/// The namespace name.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<CheckAvailabilityResult> CheckAvailabilityAsync(this INamespacesOperations operations, CheckAvailabilityParameters parameters, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.CheckAvailabilityWithHttpMessagesAsync(parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Creates/Updates a service namespace. Once created, this namespace's
/// resource manifest is immutable. This operation is idempotent.
/// <see href="http://msdn.microsoft.com/en-us/library/windowsazure/jj856303.aspx" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='namespaceName'>
/// The namespace name.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to create a Namespace Resource.
/// </param>
public static NamespaceResource CreateOrUpdate(this INamespacesOperations operations, string resourceGroupName, string namespaceName, NamespaceCreateOrUpdateParameters parameters)
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((INamespacesOperations)s).CreateOrUpdateAsync(resourceGroupName, namespaceName, parameters), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Creates/Updates a service namespace. Once created, this namespace's
/// resource manifest is immutable. This operation is idempotent.
/// <see href="http://msdn.microsoft.com/en-us/library/windowsazure/jj856303.aspx" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='namespaceName'>
/// The namespace name.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to create a Namespace Resource.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<NamespaceResource> CreateOrUpdateAsync(this INamespacesOperations operations, string resourceGroupName, string namespaceName, NamespaceCreateOrUpdateParameters parameters, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, namespaceName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Patches the existing namespace
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='namespaceName'>
/// The namespace name.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to patch a Namespace Resource.
/// </param>
public static NamespaceResource Patch(this INamespacesOperations operations, string resourceGroupName, string namespaceName, NamespacePatchParameters parameters)
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((INamespacesOperations)s).PatchAsync(resourceGroupName, namespaceName, parameters), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Patches the existing namespace
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='namespaceName'>
/// The namespace name.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to patch a Namespace Resource.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<NamespaceResource> PatchAsync(this INamespacesOperations operations, string resourceGroupName, string namespaceName, NamespacePatchParameters parameters, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.PatchWithHttpMessagesAsync(resourceGroupName, namespaceName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Deletes an existing namespace. This operation also removes all associated
/// notificationHubs under the namespace.
/// <see href="http://msdn.microsoft.com/en-us/library/windowsazure/jj856296.aspx" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='namespaceName'>
/// The namespace name.
/// </param>
public static void Delete(this INamespacesOperations operations, string resourceGroupName, string namespaceName)
{
System.Threading.Tasks.Task.Factory.StartNew(s => ((INamespacesOperations)s).DeleteAsync(resourceGroupName, namespaceName), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Deletes an existing namespace. This operation also removes all associated
/// notificationHubs under the namespace.
/// <see href="http://msdn.microsoft.com/en-us/library/windowsazure/jj856296.aspx" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='namespaceName'>
/// The namespace name.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task DeleteAsync(this INamespacesOperations operations, string resourceGroupName, string namespaceName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
await operations.DeleteWithHttpMessagesAsync(resourceGroupName, namespaceName, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Deletes an existing namespace. This operation also removes all associated
/// notificationHubs under the namespace.
/// <see href="http://msdn.microsoft.com/en-us/library/windowsazure/jj856296.aspx" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='namespaceName'>
/// The namespace name.
/// </param>
public static void BeginDelete(this INamespacesOperations operations, string resourceGroupName, string namespaceName)
{
System.Threading.Tasks.Task.Factory.StartNew(s => ((INamespacesOperations)s).BeginDeleteAsync(resourceGroupName, namespaceName), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Deletes an existing namespace. This operation also removes all associated
/// notificationHubs under the namespace.
/// <see href="http://msdn.microsoft.com/en-us/library/windowsazure/jj856296.aspx" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='namespaceName'>
/// The namespace name.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task BeginDeleteAsync(this INamespacesOperations operations, string resourceGroupName, string namespaceName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
await operations.BeginDeleteWithHttpMessagesAsync(resourceGroupName, namespaceName, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Returns the description for the specified namespace.
/// <see href="http://msdn.microsoft.com/library/azure/dn140232.aspx" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='namespaceName'>
/// The namespace name.
/// </param>
public static NamespaceResource Get(this INamespacesOperations operations, string resourceGroupName, string namespaceName)
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((INamespacesOperations)s).GetAsync(resourceGroupName, namespaceName), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Returns the description for the specified namespace.
/// <see href="http://msdn.microsoft.com/library/azure/dn140232.aspx" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='namespaceName'>
/// The namespace name.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<NamespaceResource> GetAsync(this INamespacesOperations operations, string resourceGroupName, string namespaceName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, namespaceName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Creates an authorization rule for a namespace
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='namespaceName'>
/// The namespace name.
/// </param>
/// <param name='authorizationRuleName'>
/// Aauthorization Rule Name.
/// </param>
/// <param name='parameters'>
/// The shared access authorization rule.
/// </param>
public static SharedAccessAuthorizationRuleResource CreateOrUpdateAuthorizationRule(this INamespacesOperations operations, string resourceGroupName, string namespaceName, string authorizationRuleName, SharedAccessAuthorizationRuleCreateOrUpdateParameters parameters)
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((INamespacesOperations)s).CreateOrUpdateAuthorizationRuleAsync(resourceGroupName, namespaceName, authorizationRuleName, parameters), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Creates an authorization rule for a namespace
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='namespaceName'>
/// The namespace name.
/// </param>
/// <param name='authorizationRuleName'>
/// Aauthorization Rule Name.
/// </param>
/// <param name='parameters'>
/// The shared access authorization rule.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<SharedAccessAuthorizationRuleResource> CreateOrUpdateAuthorizationRuleAsync(this INamespacesOperations operations, string resourceGroupName, string namespaceName, string authorizationRuleName, SharedAccessAuthorizationRuleCreateOrUpdateParameters parameters, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.CreateOrUpdateAuthorizationRuleWithHttpMessagesAsync(resourceGroupName, namespaceName, authorizationRuleName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Deletes a namespace authorization rule
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='namespaceName'>
/// The namespace name.
/// </param>
/// <param name='authorizationRuleName'>
/// Authorization Rule Name.
/// </param>
public static void DeleteAuthorizationRule(this INamespacesOperations operations, string resourceGroupName, string namespaceName, string authorizationRuleName)
{
System.Threading.Tasks.Task.Factory.StartNew(s => ((INamespacesOperations)s).DeleteAuthorizationRuleAsync(resourceGroupName, namespaceName, authorizationRuleName), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Deletes a namespace authorization rule
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='namespaceName'>
/// The namespace name.
/// </param>
/// <param name='authorizationRuleName'>
/// Authorization Rule Name.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task DeleteAuthorizationRuleAsync(this INamespacesOperations operations, string resourceGroupName, string namespaceName, string authorizationRuleName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
await operations.DeleteAuthorizationRuleWithHttpMessagesAsync(resourceGroupName, namespaceName, authorizationRuleName, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets an authorization rule for a namespace by name.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='namespaceName'>
/// The namespace name
/// </param>
/// <param name='authorizationRuleName'>
/// Authorization rule name.
/// </param>
public static SharedAccessAuthorizationRuleResource GetAuthorizationRule(this INamespacesOperations operations, string resourceGroupName, string namespaceName, string authorizationRuleName)
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((INamespacesOperations)s).GetAuthorizationRuleAsync(resourceGroupName, namespaceName, authorizationRuleName), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets an authorization rule for a namespace by name.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='namespaceName'>
/// The namespace name
/// </param>
/// <param name='authorizationRuleName'>
/// Authorization rule name.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<SharedAccessAuthorizationRuleResource> GetAuthorizationRuleAsync(this INamespacesOperations operations, string resourceGroupName, string namespaceName, string authorizationRuleName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.GetAuthorizationRuleWithHttpMessagesAsync(resourceGroupName, namespaceName, authorizationRuleName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Lists the available namespaces within a resourceGroup.
/// <see href="http://msdn.microsoft.com/en-us/library/azure/hh780759.aspx" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group. If resourceGroupName value is null the
/// method lists all the namespaces within subscription
/// </param>
public static Microsoft.Rest.Azure.IPage<NamespaceResource> List(this INamespacesOperations operations, string resourceGroupName)
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((INamespacesOperations)s).ListAsync(resourceGroupName), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Lists the available namespaces within a resourceGroup.
/// <see href="http://msdn.microsoft.com/en-us/library/azure/hh780759.aspx" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group. If resourceGroupName value is null the
/// method lists all the namespaces within subscription
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Microsoft.Rest.Azure.IPage<NamespaceResource>> ListAsync(this INamespacesOperations operations, string resourceGroupName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.ListWithHttpMessagesAsync(resourceGroupName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Lists all the available namespaces within the subscription irrespective of
/// the resourceGroups.
/// <see href="http://msdn.microsoft.com/en-us/library/azure/hh780759.aspx" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static Microsoft.Rest.Azure.IPage<NamespaceResource> ListAll(this INamespacesOperations operations)
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((INamespacesOperations)s).ListAllAsync(), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Lists all the available namespaces within the subscription irrespective of
/// the resourceGroups.
/// <see href="http://msdn.microsoft.com/en-us/library/azure/hh780759.aspx" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Microsoft.Rest.Azure.IPage<NamespaceResource>> ListAllAsync(this INamespacesOperations operations, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.ListAllWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets the authorization rules for a namespace.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='namespaceName'>
/// The namespace name
/// </param>
public static Microsoft.Rest.Azure.IPage<SharedAccessAuthorizationRuleResource> ListAuthorizationRules(this INamespacesOperations operations, string resourceGroupName, string namespaceName)
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((INamespacesOperations)s).ListAuthorizationRulesAsync(resourceGroupName, namespaceName), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets the authorization rules for a namespace.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='namespaceName'>
/// The namespace name
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Microsoft.Rest.Azure.IPage<SharedAccessAuthorizationRuleResource>> ListAuthorizationRulesAsync(this INamespacesOperations operations, string resourceGroupName, string namespaceName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.ListAuthorizationRulesWithHttpMessagesAsync(resourceGroupName, namespaceName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets the Primary and Secondary ConnectionStrings to the namespace
/// <see href="http://msdn.microsoft.com/en-us/library/windowsazure/jj873988.aspx" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='namespaceName'>
/// The namespace name.
/// </param>
/// <param name='authorizationRuleName'>
/// The connection string of the namespace for the specified authorizationRule.
/// </param>
public static ResourceListKeys ListKeys(this INamespacesOperations operations, string resourceGroupName, string namespaceName, string authorizationRuleName)
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((INamespacesOperations)s).ListKeysAsync(resourceGroupName, namespaceName, authorizationRuleName), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets the Primary and Secondary ConnectionStrings to the namespace
/// <see href="http://msdn.microsoft.com/en-us/library/windowsazure/jj873988.aspx" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='namespaceName'>
/// The namespace name.
/// </param>
/// <param name='authorizationRuleName'>
/// The connection string of the namespace for the specified authorizationRule.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<ResourceListKeys> ListKeysAsync(this INamespacesOperations operations, string resourceGroupName, string namespaceName, string authorizationRuleName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.ListKeysWithHttpMessagesAsync(resourceGroupName, namespaceName, authorizationRuleName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Regenerates the Primary/Secondary Keys to the Namespace Authorization Rule
/// <see href="http://msdn.microsoft.com/en-us/library/windowsazure/jj873988.aspx" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='namespaceName'>
/// The namespace name.
/// </param>
/// <param name='authorizationRuleName'>
/// The connection string of the namespace for the specified authorizationRule.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to regenerate the Namespace Authorization Rule Key.
/// </param>
public static ResourceListKeys RegenerateKeys(this INamespacesOperations operations, string resourceGroupName, string namespaceName, string authorizationRuleName, PolicykeyResource parameters)
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((INamespacesOperations)s).RegenerateKeysAsync(resourceGroupName, namespaceName, authorizationRuleName, parameters), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Regenerates the Primary/Secondary Keys to the Namespace Authorization Rule
/// <see href="http://msdn.microsoft.com/en-us/library/windowsazure/jj873988.aspx" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='namespaceName'>
/// The namespace name.
/// </param>
/// <param name='authorizationRuleName'>
/// The connection string of the namespace for the specified authorizationRule.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to regenerate the Namespace Authorization Rule Key.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<ResourceListKeys> RegenerateKeysAsync(this INamespacesOperations operations, string resourceGroupName, string namespaceName, string authorizationRuleName, PolicykeyResource parameters, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.RegenerateKeysWithHttpMessagesAsync(resourceGroupName, namespaceName, authorizationRuleName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Lists the available namespaces within a resourceGroup.
/// <see href="http://msdn.microsoft.com/en-us/library/azure/hh780759.aspx" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static Microsoft.Rest.Azure.IPage<NamespaceResource> ListNext(this INamespacesOperations operations, string nextPageLink)
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((INamespacesOperations)s).ListNextAsync(nextPageLink), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Lists the available namespaces within a resourceGroup.
/// <see href="http://msdn.microsoft.com/en-us/library/azure/hh780759.aspx" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Microsoft.Rest.Azure.IPage<NamespaceResource>> ListNextAsync(this INamespacesOperations operations, string nextPageLink, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Lists all the available namespaces within the subscription irrespective of
/// the resourceGroups.
/// <see href="http://msdn.microsoft.com/en-us/library/azure/hh780759.aspx" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static Microsoft.Rest.Azure.IPage<NamespaceResource> ListAllNext(this INamespacesOperations operations, string nextPageLink)
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((INamespacesOperations)s).ListAllNextAsync(nextPageLink), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Lists all the available namespaces within the subscription irrespective of
/// the resourceGroups.
/// <see href="http://msdn.microsoft.com/en-us/library/azure/hh780759.aspx" />
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Microsoft.Rest.Azure.IPage<NamespaceResource>> ListAllNextAsync(this INamespacesOperations operations, string nextPageLink, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.ListAllNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets the authorization rules for a namespace.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static Microsoft.Rest.Azure.IPage<SharedAccessAuthorizationRuleResource> ListAuthorizationRulesNext(this INamespacesOperations operations, string nextPageLink)
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((INamespacesOperations)s).ListAuthorizationRulesNextAsync(nextPageLink), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets the authorization rules for a namespace.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Microsoft.Rest.Azure.IPage<SharedAccessAuthorizationRuleResource>> ListAuthorizationRulesNextAsync(this INamespacesOperations operations, string nextPageLink, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.ListAuthorizationRulesNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
/* ====================================================================
Copyright (C) 2004-2008 fyiReporting Software, LLC
This file is part of the fyiReporting RDL project.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
For additional information, email info@fyireporting.com or visit
the website www.fyiReporting.com.
*/
using System;
using System.Xml;
using System.IO;
using System.Drawing;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
namespace fyiReporting.RDL
{
///<summary>
/// The Textbox definition. Inherits from ReportItem.
///</summary>
[Serializable]
internal class Textbox : ReportItem
{
Expression _Value; // (Variant) An expression, the value of which is
// displayed in the text-box.
// This can be a constant expression for constant labels.
bool _CanGrow; // Indicates the Textbox size can
// increase to accommodate the contents
bool _CanShrink; // Indicates the Textbox size can
// decrease to match the contents
string _HideDuplicates; // Indicates the item should be hidden
//when the value of the expression
//associated with the report item is the
//same as the preceding instance. The
//value of HideDuplicates is the name
//of a grouping or data set over which
//to apply the hiding. Each time a
//new instance of that group is
//encountered, the first instance of
//this report item will not be hidden.
//Rows on a previous page are
//ignored for the purposes of hiding
//duplicates. If the textbox is in a
//table or matrix cell, only the text
//will be hidden. The textbox will
//remain to provide background and
//border for the cell.
//Ignored in matrix subtotals.
ToggleImage _ToggleImage; // Indicates the initial state of a
// toggling image should one be
// displayed as a part of the textbox.
DataElementStyleEnum _DataElementStyle; // Indicates whether textbox value
// should render as an element or attribute: Auto (Default)
// Auto uses the setting on the Report element.
bool _IsToggle; // Textbox is used to toggle a detail row
List<string> _ExprReferences; // array of names of expressions that reference this Textbox;
// only needed for page header/footer references
static readonly Regex HTMLEXPR = new Regex("(<expr>.+</expr>)"); // Split on all expressions.
internal Textbox(ReportDefn r, ReportLink p, XmlNode xNode):base(r,p,xNode)
{
_Value=null;
_CanGrow=false;
_CanShrink=false;
_HideDuplicates=null;
_ToggleImage=null;
_DataElementStyle=DataElementStyleEnum.Auto;
// Loop thru all the child nodes
foreach(XmlNode xNodeLoop in xNode.ChildNodes)
{
if (xNodeLoop.NodeType != XmlNodeType.Element)
continue;
switch (xNodeLoop.Name)
{
case "Value":
_Value = new Expression(r, this, xNodeLoop, ExpressionType.Variant);
break;
case "CanGrow":
_CanGrow = XmlUtil.Boolean(xNodeLoop.InnerText, OwnerReport.rl);
break;
case "CanShrink":
_CanShrink = XmlUtil.Boolean(xNodeLoop.InnerText, OwnerReport.rl);
break;
case "HideDuplicates":
_HideDuplicates = xNodeLoop.InnerText;
break;
case "ToggleImage":
_ToggleImage = new ToggleImage(r, this, xNodeLoop);
break;
case "DataElementStyle":
_DataElementStyle = fyiReporting.RDL.DataElementStyle.GetStyle(xNodeLoop.InnerText, OwnerReport.rl);
break;
default:
if (ReportItemElement(xNodeLoop)) // try at ReportItem level
break;
// don't know this element - log it
OwnerReport.rl.LogError(4, "Unknown Textbox element '" + xNodeLoop.Name + "' ignored.");
break;
}
}
if (_Value == null)
OwnerReport.rl.LogError(8, "Textbox value not specified for " + (this.Name == null? "'name not specified'": this.Name.Nm));
if (this.Name != null)
{
try
{
OwnerReport.LUReportItems.Add(this.Name.Nm, this); // add to referenceable TextBoxes
}
catch // Duplicate name
{
OwnerReport.rl.LogError(4, "Duplicate Textbox name '" + this.Name.Nm + "' ignored.");
}
}
}
// Handle parsing of function in final pass
override internal void FinalPass()
{
base.FinalPass();
_Value.FinalPass();
if (this.DataElementName == null && this.Name == null)
{
// no name or dataelementname; try using expression
FunctionField ff = _Value.Expr as FunctionField;
if (ff != null && ff.Fld != null)
{
this.DataElementName = ff.Fld.DataField;
}
}
if (_ToggleImage != null)
_ToggleImage.FinalPass();
if (_HideDuplicates != null)
{
object o = OwnerReport.LUAggrScope[_HideDuplicates];
if (o == null)
{
OwnerReport.rl.LogError(4, "HideDuplicate '" +_HideDuplicates + "' is not a Group or DataSet name. It will be ignored.");
_HideDuplicates=null;
}
else if (o is Grouping)
{
Grouping g = o as Grouping;
g.AddHideDuplicates(this);
}
else if (o is DataSetDefn)
{
DataSetDefn ds = o as DataSetDefn;
ds.AddHideDuplicates(this);
}
}
return;
}
internal void AddExpressionReference(string name)
{
if (_ExprReferences == null)
_ExprReferences = new List<string>();
_ExprReferences.Add(name);
}
internal void RecordPageReference(Report rpt, Page p, Row r)
{
if (_ExprReferences == null)
return;
foreach (string refr in _ExprReferences)
{
p.AddPageExpressionRow(rpt, refr, r);
}
}
internal void ResetPrevious(Report rpt)
{
TextboxRuntime tbr = TextboxRuntime.GetTextboxRuntime(rpt, this);
ResetPrevious(tbr);
}
void ResetPrevious(TextboxRuntime tbr)
{
tbr.PreviousText=null;
tbr.PreviousPage=null;
}
override internal void Run(IPresent ip, Row row)
{
Report rpt = ip.Report();
base.Run(ip, row);
TextboxRuntime tbr = TextboxRuntime.GetTextboxRuntime(rpt, this);
tbr.RunCount++; // Increment the run count
string t = RunText(rpt, row);
bool bDup = RunTextIsDuplicate(tbr, t, null);
if (bDup)
{
if (!(this.IsTableOrMatrixCell(rpt))) // don't put out anything if not in Table or Matrix
return;
t = ""; // still need to put out the cell
}
ip.Textbox(this, t, row);
if (!bDup)
tbr.PreviousText=t; // set for next time
}
override internal void RunPage(Pages pgs, Row row)
{
Report r = pgs.Report;
TextboxRuntime tbr = TextboxRuntime.GetTextboxRuntime(r, this);
tbr.RunCount++; // Increment the run count
bool bHidden = IsHidden(r, row);
SetPagePositionBegin(pgs);
string t;
if (bHidden)
t = "";
else
t = RunText(r, row); // get the text
bool bDup = RunTextIsDuplicate(tbr, t, pgs.CurrentPage);
if (bDup)
{
if (!(this.IsTableOrMatrixCell(r))) // don't put out anything if not in Table or Matrix
bHidden = true;
t = ""; // still need to put out the cell
}
PageText pt;
PageTextHtml pth=null;
if (IsHtml(r, row))
pt = pth = new PageTextHtml(t);
else
pt = new PageText(t);
SetPagePositionAndStyle(r, pt, row);
if (this.CanGrow && tbr.RunHeight == 0) // when textbox is in a DataRegion this will already be called
{
this.RunTextCalcHeight(r, pgs.G, row, pt is PageTextHtml? pt as PageTextHtml: null);
}
pt.H = Math.Max(pt.H, tbr.RunHeight); // reset height
if (pt.SI.BackgroundImage != null)
pt.SI.BackgroundImage.H = pt.H; // and in the background image
pt.CanGrow = this.CanGrow;
// check TextAlign: if General then correct based on data type
if (pt.SI.TextAlign == TextAlignEnum.General)
{
if (DataType.IsNumeric(this.Value.GetTypeCode() ))
pt.SI.TextAlign = TextAlignEnum.Right;
}
// Hidden objects don't affect the current page?
if (!bHidden)
{
// Force page break if it doesn't fit on a page
if (this.IsInBody && // Only force page when object directly in body
pgs.CurrentPage.YOffset + pt.Y + pt.H >= pgs.BottomOfPage && // running off end of page
!pgs.CurrentPage.IsEmpty()) // if page is already empty don't force new
{ // force page break if it doesn't fit on the page
pgs.NextOrNew();
pgs.CurrentPage.YOffset = OwnerReport.TopOfPage;
if (this.YParents != null)
pt.Y = 0;
}
Page p = pgs.CurrentPage;
RecordPageReference(r, p, row); // save information for late page header/footer references
p.AddObject(pt);
if (!bDup)
{
tbr.PreviousText = t; // previous text displayed
tbr.PreviousPage = p; // page previous text was shown on
}
}
SetPagePositionEnd(pgs, pt.Y+pt.H);
if (pth != null)
pth.Reset();
if (this.CanGrow && !Value.IsConstant())
{
tbr.RunHeight = 0; // need to recalculate
}
}
// routine to determine if text is considered to be a duplicate;
// ie: same as previous text and on same page
private bool RunTextIsDuplicate(TextboxRuntime tbr, string t, Page p)
{
if (this._HideDuplicates == null)
return false;
if (t == tbr.PreviousText && p == tbr.PreviousPage)
return true;
return false;
}
internal string RunText(Report rpt, Row row)
{
object o = _Value.Evaluate(rpt, row);
// AJM 15082008: Suppress NaN from appearing in a textbox
if (o is double)
{
if (Double.IsNaN((double)o))
{
o = null;
}
}
string t = Style.GetFormatedString(rpt, this.Style, row, o, _Value.GetTypeCode());
if (IsHtml(rpt, row) && t != null && t.Contains("<expr>"))
{
string[] parts = HTMLEXPR.Split(t);
StringBuilder sb = new StringBuilder(t.Length);
foreach (string s in parts)
{
if (s.StartsWith("<expr>") && s.EndsWith("</expr>"))
{
string expr = s.Substring(6, s.Length - 13);
DynamicExpression de = new DynamicExpression(rpt, this, expr, row);
sb.Append(de.Evaluate(rpt, row));
}
else
sb.Append(s);
}
t = sb.ToString();
}
return t;
}
internal float RunTextCalcHeight(Report rpt, Graphics g, Row row)
{
return RunTextCalcHeight(rpt, g, row, null);
}
internal float RunTextCalcHeight(Report rpt, Graphics g, Row row, PageTextHtml pth)
{ // normally only called when CanGrow is true
Size s = Size.Empty;
if (IsHidden(rpt, row))
return 0;
object o = _Value.Evaluate(rpt, row);
TypeCode tc = _Value.GetTypeCode();
int width = this.WidthCalc(rpt, g);
if (this.Style != null)
{
width -= (Style.EvalPaddingLeftPx(rpt, row) + Style.EvalPaddingRightPx(rpt, row));
if (this.IsHtml(rpt, row))
{
if (pth == null)
{
pth = new PageTextHtml(o==null? "": o.ToString());
SetPagePositionAndStyle(rpt, pth, row);
}
pth.Build(g);
s.Height = RSize.PixelsFromPoints(pth.TotalHeight);
}
else
s = Style.MeasureString(rpt, g, o, tc, row, width);
}
else // call the class static method
s = Style.MeasureStringDefaults(rpt, g, o, tc, row, width);
TextboxRuntime tbr = TextboxRuntime.GetTextboxRuntime(rpt, this);
tbr.RunHeight = RSize.PointsFromPixels(g, s.Height);
if (Style != null)
tbr.RunHeight += (Style.EvalPaddingBottom(rpt, row) + Style.EvalPaddingTop(rpt, row));
return tbr.RunHeight;
}
internal object Evaluate(Report rpt, Row r)
{
object o = _Value.Evaluate(rpt, r);
return o;
}
internal Expression Value
{
get { return _Value; }
set { _Value = value; }
}
internal bool CanGrow
{
get { return _CanGrow; }
set { _CanGrow = value; }
}
internal bool CanShrink
{
get { return _CanShrink; }
set { _CanShrink = value; }
}
internal string HideDuplicates
{
get { return _HideDuplicates; }
set { _HideDuplicates = value; }
}
internal bool IsHtml(Report rpt, Row row)
{
if (this.Style == null || this.Style.Format == null)
return false;
string format = Style.Format.EvaluateString(rpt, row);
if (format == null)
return false;
return format.ToLower() == "html";
}
internal ToggleImage ToggleImage
{
get { return _ToggleImage; }
set { _ToggleImage = value; }
}
internal bool IsToggle
{
get { return _IsToggle; }
set { _IsToggle = value; }
}
internal int RunCount(Report rpt)
{
TextboxRuntime tbr = TextboxRuntime.GetTextboxRuntime(rpt, this);
return tbr.RunCount;
}
internal DataElementStyleEnum DataElementStyle
{
get
{
if (_DataElementStyle == DataElementStyleEnum.Auto) // auto means use report
return OwnerReport.DataElementStyle;
else
return _DataElementStyle;
}
set { _DataElementStyle = value; }
}
}
class TextboxRuntime
{
internal int RunCount=0; // number of times TextBox is rendered at runtime;
// used to generate unique names for toggling visibility
internal float RunHeight=0; // the runtime height (in points)
internal string PreviousText=null; // previous text displayed
internal Page PreviousPage=null; // page previous text was shown on
internal object LastObject=null; // last object calculated
static internal TextboxRuntime GetTextboxRuntime(Report rpt, Textbox tb)
{
TextboxRuntime tbr = rpt.Cache.Get(tb, "txtbox") as TextboxRuntime;
if (tbr != null)
return tbr;
tbr = new TextboxRuntime();
rpt.Cache.Add(tb, "txtbox", tbr);
return tbr;
}
}
}
| |
// TODO: Add Header
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
/// <summary>
/// This is base class for all GUI elements. You can inherit it to create own GUI elements
/// </summary>
public class blindGUIParentElement : MonoBehaviour {
/// <summary>
/// Delegate to be called at the end of animation
/// </summary>
public delegate void AnimationCompleteDelegate( blindGUIParentElement sender );
/// <summary>
/// Element layout configuration
/// </summary>
protected class _blindGUIElementConfig {
public readonly Vector2 scale;
public readonly Vector2 anchorPoint;
public readonly Vector2 offset;
public readonly Vector2 size;
public readonly float angle;
public _blindGUIElementConfig( Vector2 _scale, Vector2 _anchorPoint, Vector2 _offset, Vector2 _size, float _angle ) {
scale = _scale;
anchorPoint = _anchorPoint;
offset = _offset;
size = _size;
angle = _angle;
}
}
/// <summary>
/// Horizontal alignment of element;
/// </summary>
public enum HALIGN { left, center, right, stretch, free };
public HALIGN m_horizontalAlign = HALIGN.left;
/// <summary>
/// Vertical alignment of element.
/// </summary>
public enum VALIGN { top, center, bottom, stretch, free };
public VALIGN m_verticalAlign = VALIGN.top;
/// <summary>
/// Position of elements anchor point in parent's scale
///
/// For "top" alignment m_offset.y sets anchor point position relative to top of container
/// For "bottom" alignment m_offset.y sets anchor point position relative to bottom of container
///
/// The same effect for left, right alignment and m_offset.x
///
/// For "center" alignment m_offset.x and m_offset.y sets anchor point position relative to center of container.
///
/// </summary>
public Vector2 m_offset = new Vector2(0,0);
/// <summary>
/// Size of control
/// </summary>
public Vector2 m_size = new Vector2(100,100);
/// <summary>
/// Z-order of control in container(not global).
/// </summary>
public int z = 0;
/// <summary>
/// Scale of current element
/// </summary>
public float m_scale = 1;
/// <summary>
/// Angle of rotation
/// </summary>
public float m_angle;
/// <summary>
/// Anchor point for rotation
/// </summary>
public Vector2 m_anchorPoint;
/// <summary>
/// Alpha of current element
/// </summary>
public float m_alpha = 1.0f;
/// <summary>
/// Animation speed
/// </summary>
public float m_animationTime = 1.0f;
/// <summary>
/// If this element is active
/// </summary>
public bool m_enabled = true;
/// <summary>
/// Sorted list of
/// </summary>
private List<blindGUIParentElement> m_elements = new List<blindGUIParentElement>();
/// <summary>
/// Style of element
/// </summary>
protected GUIStyle m_style = new GUIStyle();
/// <summary>
/// Set to true on transform
/// </summary>
protected bool m_transformed;
/// <summary>
/// Original GUI Matrix
/// </summary>
protected Matrix4x4 m_guiMatrix;
protected Vector2 m_CSShift;
/// <summary>
/// Container clipping on/off
/// </summary>
public bool m_clipping = false;
/// <summary>
/// Sets to strue if clip assigned
/// </summary>
private bool m_clipAssigned = false;
/// <summary>
/// Original GUI color
/// </summary>
private Color m_originalGUIColor;
/// <summary>
/// Flag show if color was changed
/// </summary>
private bool m_colorChanged;
/// <summary>
/// State at start of animation
/// </summary>
private blindGUIAnimationState m_startAnimationState;
/// <summary>
/// State at end of animation
/// </summary>
private blindGUIAnimationState m_finishAnimationState;
/// <summary>
/// This function will be called at the end of animation
/// </summary>
private AnimationCompleteDelegate m_animationCompleteDelegate;
private Vector2 acnhorPointOnScreen = new Vector2(0,0);
/// <summary>
/// Initialization
/// </summary>
public virtual void Start () {
UpdateLayout();
}
/// <summary>
/// Draws current element and all children.
/// </summary>
/// <param name="drawRect">
/// Parent region with <see cref="Rect"/> type. Already scaled.
/// </param>
/// <param name="active">
/// Flag for element if it is active of <see cref="System.Boolean"/> type.
/// </param>
public virtual void Draw( blindGUILayout parentLayout, bool active) {
//Debug.Log(this.name+" parent layout: "+parentLayout.ToString());
blindGUILayout currentLayout;
Rect containerRectangle = SetupLayout( parentLayout, out currentLayout );
if (this.GetType() == typeof(blindGUIParentElement)) {
GUI.Box(containerRectangle,this.name);
}
foreach( blindGUIParentElement element in m_elements) {
element.Draw(currentLayout, m_enabled & active);
}
if (m_clipAssigned) {
GUI.EndGroup();
m_clipAssigned = false;
}
if (m_colorChanged) {
GUI.color = m_originalGUIColor;
m_colorChanged = false;
}
}
/// <summary>
/// Returns frame for current element
/// </summary>
/// <param name="parentLayout">
/// Parent layout of <see cref="blindGUILayout"/> type.
/// </param>
/// <returns>
/// Current elements's frame. <see cref="Rect"/> type;
/// </returns>
protected Rect GetFrame( blindGUILayout parentLayout ) {
blindGUILayout temp;
return SetupLayout( parentLayout, out temp );
}
/// <summary>
/// Returns current element configuration
/// </summary>
/// <param name="parentLayout">
/// Layout of parent element of <see cref="blindGUILayout"/> type
/// </param>
/// <returns>
/// Returns configuration for this element of <see cref="blindGUIElementConfig"/> type.
/// </returns>
private blindGUIElementConfig GetElement( blindGUILayout parentLayout ) {
float _angle = m_angle;
Vector2 _anchorPoint = m_anchorPoint;
Vector2 _size = m_size;
Vector2 _offset = m_offset;
float _scale = m_scale;
//-------------------------------------------------
// Fix angle
// Set parameters according to alignment
if ((m_horizontalAlign != blindGUIParentElement.HALIGN.free) || (m_verticalAlign != blindGUIParentElement.VALIGN.free)) {
_angle = 0;
}
//-------------------------------------------------
// Fix anchor point
// Horizontal
if (m_horizontalAlign == blindGUIParentElement.HALIGN.left) {
_anchorPoint.x = 0f;
} else if (m_horizontalAlign == blindGUIParentElement.HALIGN.center) {
_anchorPoint.x = 0;
} else if (m_horizontalAlign == blindGUIParentElement.HALIGN.stretch) {
_anchorPoint.x = 0;
} else if (m_horizontalAlign == blindGUIParentElement.HALIGN.right) {
_anchorPoint.x = 0f;
}
// Vertical
if (m_verticalAlign == blindGUIParentElement.VALIGN.top) {
_anchorPoint.y = 0f;
} else if (m_verticalAlign == blindGUIParentElement.VALIGN.center) {
_anchorPoint.y = 0;
} else if (m_verticalAlign == blindGUIParentElement.VALIGN.stretch) {
_anchorPoint.y = 0;
} else if (m_verticalAlign == blindGUIParentElement.VALIGN.bottom) {
_anchorPoint.y = 0f;
}
//-------------------------------------------------
// Fix size
// Horizontal
if (m_horizontalAlign == blindGUIParentElement.HALIGN.stretch) {
_size.x = parentLayout.size.x / _scale;
}
// Vertical
if (m_verticalAlign == blindGUIParentElement.VALIGN.stretch) {
_size.y = parentLayout.size.y / _scale;
}
//-------------------------------------------------
// Fix offset
// Horizontal
if (m_horizontalAlign == blindGUIParentElement.HALIGN.left) {
_offset.x += -parentLayout.size.x*(0.5f+parentLayout.anchorPoint.x)+_size.x*0.5f*_scale;
} else if (m_horizontalAlign == blindGUIParentElement.HALIGN.center) {
_offset.x += -parentLayout.size.x*(0.5f+parentLayout.anchorPoint.x-0.5f);
} else if (m_horizontalAlign == blindGUIParentElement.HALIGN.right) {
_offset.x = -parentLayout.size.x*(0.5f+parentLayout.anchorPoint.x-1.0f) - _size.x*_scale*0.5f - _offset.x;
} else if (m_horizontalAlign == blindGUIParentElement.HALIGN.stretch) {
_offset.x = -parentLayout.size.x*(0.5f+parentLayout.anchorPoint.x-0.5f);
}
// Vertical
if (m_verticalAlign == blindGUIParentElement.VALIGN.top) {
_offset.y += -parentLayout.size.y*(0.5f+parentLayout.anchorPoint.y)+_size.y*0.5f*_scale;
} else if (m_verticalAlign == blindGUIParentElement.VALIGN.center) {
_offset.y += -parentLayout.size.y*(0.5f+parentLayout.anchorPoint.y-0.5f);
} else if (m_verticalAlign == blindGUIParentElement.VALIGN.bottom) {
_offset.y = -parentLayout.size.y*(0.5f+parentLayout.anchorPoint.y-1.0f) - _size.y*_scale*0.5f - _offset.y;
} else if (m_verticalAlign == blindGUIParentElement.VALIGN.stretch) {
_offset.y = -parentLayout.size.y*(0.5f+parentLayout.anchorPoint.y-0.5f);
}
return new blindGUIElementConfig( new Vector2(_scale,_scale),
_anchorPoint,
_offset,
_size,
_angle);
}
/// <summary>
/// Sets rotation, scale and arranges current element
/// </summary>
/// <param name="parentLayout">
/// Layout of parent element of <see cref="blindGUILayout"/> type
/// </param>
/// <param name="elementConfig">
/// Current element configuration of <see cref="blindGUIElementConfig"/> type
/// </param>
/// <param name="currentLayout">
/// Current element layout for hierarhy. <see cref="blindGUILayout"/> type
/// </param>
/// <returns>
/// Rectaingle of current element. <see cref="Rect"/> type.
/// </returns>
private Rect SetupLayout( blindGUILayout parentLayout, out blindGUILayout currentLayout ) {
if (m_angle != 0) m_clipping = false;
if (m_scale == 0) m_scale = 0.0001f;
blindGUIElementConfig elementConfig = GetElement(parentLayout); //new blindGUIElementConfig( new Vector2(m_scale,m_scale), m_rotationAnchorPoint, m_offset, new Vector2( m_size.x, m_size.y), m_angle);
if (!m_clipAssigned) {
GUI.matrix = Matrix4x4.identity;
}
Vector2 realAnchorPoint = new Vector2( -elementConfig.size.x*(0.5f+elementConfig.anchorPoint.x), -elementConfig.size.y*(0.5f+elementConfig.anchorPoint.y) );
Vector2 currentAnchorPoint = new Vector2( parentLayout.realAnchorPoint.x + elementConfig.offset.x*parentLayout.scale.x*Mathf.Cos(-parentLayout.angle*Mathf.Deg2Rad) +
elementConfig.offset.y*parentLayout.scale.y*Mathf.Sin(-parentLayout.angle*Mathf.Deg2Rad)
, parentLayout.realAnchorPoint.y +elementConfig.offset.y*parentLayout.scale.y*Mathf.Cos(-parentLayout.angle*Mathf.Deg2Rad) -
elementConfig.offset.x*parentLayout.scale.x*Mathf.Sin(-parentLayout.angle*Mathf.Deg2Rad));
acnhorPointOnScreen = currentAnchorPoint+realAnchorPoint;
// Current element scale
Vector2 currentScale = new Vector2(parentLayout.scale.x*elementConfig.scale.x, parentLayout.scale.y*elementConfig.scale.y);
// Current element angle
float currentAngle = parentLayout.angle+elementConfig.angle;
if (!m_clipAssigned) {
GUIUtility.ScaleAroundPivot(currentScale, currentAnchorPoint);
GUIUtility.RotateAroundPivot(currentAngle, currentAnchorPoint);
}
if (m_clipping) {
currentLayout = new blindGUILayout( -realAnchorPoint, m_anchorPoint, currentScale, elementConfig.size, currentAngle );
} else {
currentLayout = new blindGUILayout( currentAnchorPoint, m_anchorPoint, currentScale, elementConfig.size, currentAngle );
}
Rect resultRect = new Rect( currentAnchorPoint.x+realAnchorPoint.x, currentAnchorPoint.y +realAnchorPoint.y, elementConfig.size.x, elementConfig.size.y);
if (m_clipping) {
Rect clipRect = new Rect(currentAnchorPoint.x+realAnchorPoint.x,currentAnchorPoint.y+realAnchorPoint.y, elementConfig.size.x+20, elementConfig.size.y+20);
if (!m_clipAssigned) {
GUI.BeginGroup( clipRect , "", new GUIStyle() );
m_clipAssigned = true;
}
resultRect = new Rect(0,0, elementConfig.size.x, elementConfig.size.y);
}
if (!m_colorChanged) {
m_originalGUIColor = GUI.color;
GUI.color = new Color( m_originalGUIColor.r, m_originalGUIColor.g, m_originalGUIColor.b, m_originalGUIColor.a * m_alpha );
m_colorChanged = true;
}
return resultRect;
}
/// <summary>
/// Searches all included blindGUILayer objects to store them in list.
/// Also used to update list of layers. This method must be called if you create GUI programmatically.
/// </summary>
virtual public void UpdateLayout() {
m_elements.Clear();
/// Look for children of this element and check if them has GUI elements
foreach(Transform transform in this.transform) {
if (transform.gameObject != null && transform.gameObject.active) {
blindGUIParentElement[] elements = transform.gameObject.GetComponents<blindGUIParentElement>();
m_elements.AddRange(elements);
foreach (blindGUIParentElement element in elements) {
element.UpdateLayout();
}
}
}
// Sort elements by Z
m_elements.Sort((a,b) => {return a.z.CompareTo(b.z);} );
}
/// <summary>
/// Starts Animation from objects current state to new
/// </summary>
/// <param name="targetState">
/// Target animation state <see cref="blindGUIAnimationState"/>
/// </param>
/// <param name="animationTime">
/// Duration of animation <see cref="System.Single"/>
public void AnimateTo( blindGUIAnimationState targetState, float animationTime) {
AnimateTo(targetState, animationTime, null, iTweenInBlindGUI.EaseType.linear, 0.0f);
}
/// <summary>
/// Starts Animation from objects current state to new
/// </summary>
/// <param name="targetState">
/// Target animation state <see cref="blindGUIAnimationState"/>
/// </param>
/// <param name="animationTime">
/// Duration of animation <see cref="System.Single"/>
/// <param name="easeType">
/// Animation Ease type <see cref="iTweenInBlindGUI.EaseType"/>
/// </param>
public void AnimateTo( blindGUIAnimationState targetState, float animationTime, iTweenInBlindGUI.EaseType easeType ) {
AnimateTo(targetState, animationTime, null, easeType, 0.0f);
}
/// <summary>
/// Starts Animation from objects current state to new
/// </summary>
/// <param name="targetState">
/// Target animation state <see cref="blindGUIAnimationState"/>
/// </param>
/// <param name="animationTime">
/// Duration of animation <see cref="System.Single"/>
/// </param>
/// <param name="animationCompleteDelegate">
/// This function will be called after animation is finished <see cref="AnimationCompleteDelegate"/>
/// </param>
/// <param name="easeType">
/// Animation Ease type <see cref="iTweenInBlindGUI.EaseType"/>
/// </param>
public void AnimateTo( blindGUIAnimationState targetState, float animationTime, AnimationCompleteDelegate animationCompleteDelegate, iTweenInBlindGUI.EaseType easeType ) {
AnimateTo(targetState, animationTime, animationCompleteDelegate, easeType, 0.0f);
}
/// <summary>
/// Starts Animation from objects current state to new
/// </summary>
/// <param name="targetState">
/// Target animation state <see cref="blindGUIAnimationState"/>
/// </param>
/// <param name="animationTime">
/// Duration of animation <see cref="System.Single"/>
/// </param>
/// <param name="animationCompleteDelegate">
/// This function will be called after animation is finished <see cref="AnimationCompleteDelegate"/>
/// </param>
public void AnimateTo( blindGUIAnimationState targetState, float animationTime, AnimationCompleteDelegate animationCompleteDelegate ) {
AnimateTo(targetState, animationTime, animationCompleteDelegate, iTweenInBlindGUI.EaseType.linear, 0.0f);
}
/// <summary>
/// Starts Animation from objects current state to new
/// </summary>
/// <param name="targetState">
/// Target animation state <see cref="blindGUIAnimationState"/>
/// </param>
/// <param name="animationTime">
/// Duration of animation <see cref="System.Single"/>
/// </param>
/// <param name="animationCompleteDelegate">
/// This function will be called after animation is finished <see cref="AnimationCompleteDelegate"/>
/// </param>
/// <param name="easeType">
/// Animation Ease type <see cref="iTweenInBlindGUI.EaseType"/>
/// </param>
/// <param name="delay">
/// Delay of animation <see cref="System.Single"/>
/// </param>
public void AnimateTo( blindGUIAnimationState targetState, float animationTime, AnimationCompleteDelegate animationCompleteDelegate, iTweenInBlindGUI.EaseType easeType, float delay ) {
m_animationCompleteDelegate = animationCompleteDelegate;
m_animationTime = animationTime;
m_startAnimationState = new blindGUIAnimationState( this );
m_finishAnimationState = targetState;
//iTweenInBlindGUI.StopByName(this.name+"_animation");
iTweenInBlindGUI.ValueTo( this.gameObject, iTweenInBlindGUI.Hash(
"name", this.name+"_animation",
"time", m_animationTime,
"delay", delay,
"from", 0,
"to", 1,
"easetype", easeType,
"onupdate", "AnimationStep",
"oncomplete", "AnimationFinished"));
}
/// <summary>
/// New animation Step
/// </summary>
/// <param name="t">
/// A <see cref="System.Single"/>
/// </param>
private void AnimationStep( float t ) {
if (m_startAnimationState.size != m_finishAnimationState.size) {
this.m_size = m_startAnimationState.size*(1-t)+m_finishAnimationState.size*t;
}
if (m_startAnimationState.angle != m_finishAnimationState.angle) {
this.m_angle = m_startAnimationState.angle*(1-t)+m_finishAnimationState.angle*t;
}
if (m_startAnimationState.offset != m_finishAnimationState.offset) {
this.m_offset = m_startAnimationState.offset*(1-t)+m_finishAnimationState.offset*t;
}
if (m_startAnimationState.anchorPoint != m_finishAnimationState.anchorPoint) {
this.m_anchorPoint = m_startAnimationState.anchorPoint*(1-t)+m_finishAnimationState.anchorPoint*t;
}
if (m_startAnimationState.alpha != m_finishAnimationState.alpha) {
this.m_alpha = m_startAnimationState.alpha*(1-t)+m_finishAnimationState.alpha*t;
}
if (m_startAnimationState.scale != m_finishAnimationState.scale) {
this.m_scale = m_startAnimationState.scale*(1-t)+m_finishAnimationState.scale*t;
}
}
/// <summary>
/// Animation finished. Calling delegate if it is registered
/// </summary>
private void AnimationFinished() {
if (m_animationCompleteDelegate != null) {
m_animationCompleteDelegate( this );
}
}
public Vector2 anchorPointOnScreen() {
return acnhorPointOnScreen;
}
}
| |
// ********************************************************************************************************
// Product Name: DotSpatial.Compatibility.dll
// Description: Supports DotSpatial interfaces organized for a MapWindow 4 plugin context.
// ********************************************************************************************************
// The contents of this file are subject to the MIT License (MIT)
// you may not use this file except in compliance with the License. You may obtain a copy of the License at
// http://dotspatial.codeplex.com/license
//
// Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF
// ANY KIND, either expressed or implied. See the License for the specific language governing rights and
// limitations under the License.
//
// The Original Code is from MapWindow.dll version 6.0
//
// The Initial Developer of this Original Code is Ted Dunsford. Created 1/20/2009 2:00:19 PM
//
// Contributor(s): (Open source contributors should list themselves and their modifications here).
//
// ********************************************************************************************************
using System.Drawing;
using GeoAPI.Geometries;
namespace DotSpatial.Compatibility
{
/// <summary>
/// The View interface is used to manipulate or work with the main DotSpatial display.
/// </summary>
public interface IViewOld
{
/// <summary>
/// Determines whether the preview map panel is visible.
/// </summary>
bool PreviewVisible { get; set; }
/// <summary>
/// Determines whether the legend panel is visible.
/// </summary>
bool LegendVisible { get; set; }
/// <summary>
/// Gets or sets the background color of the map.
/// </summary>
Color BackColor { get; set; }
/// <summary>
/// Gets or sets the current cursor mode. The cursor mode can be any of the following:
/// <list type="bullet">
/// <item>None</item>
/// <item>Pan</item>
/// <item>Selection</item>
/// <item>ZoomIn</item>
/// <item>ZoomOut</item>
/// </list>
/// </summary>
CursorMode CursorMode { get; set; }
/// <summary>
/// Returns a <c>DotSpatial.Interfaces.Draw</c> interface used to add custom drawing to the map.
/// </summary>
IDraw Draw { get; }
/// <summary>
/// Gets or sets the amount to pad around the extents when calling <c>ZoomToMaxExtents</c>,
/// <c>ZoomToLayer</c>, and <c>ZoomToShape</c>.
/// </summary>
double ExtentPad { get; set; }
/// <summary>
/// Gets or sets the map's current extents.
/// </summary>
Envelope Extents { get; set; }
/// <summary>
/// Gets or sets the cursor to use on the map. The enumeration can be any of the following:
/// <list type="bullet">
/// <item>crsrAppStarting</item>
/// <item>crsrArrow</item>
/// <item>crsrCross</item>
/// <item>crsrHelp</item>
/// <item>crsrIBeam</item>
/// <item>crsrMapDefault</item>
/// <item>crsrNo</item>
/// <item>crsrSizeAll</item>
/// <item>crsrSizeNESW</item>
/// <item>crsrSizeNS</item>
/// <item>crsrSizeNWSE</item>
/// <item>crsrSizeWE</item>
/// <item>crsrUpArrow</item>
/// <item>crsrUserDefined</item>
/// <item>crsrWait</item>
/// </list>
/// </summary>
MapCursorMode MapCursor { get; set; }
/// <summary>
/// Indicates that the map should handle file drag-drop events (as opposed to firing a message indicating file(s) were dropped).
/// </summary>
bool HandleFileDrop { get; set; }
/// <summary>
/// Gets or sets the <c>MapState</c> string which describes in a single string the entire
/// map state, including layers and coloring schemes.
/// </summary>
string MapState { get; set; }
/// <summary>
/// Returns a <c>SelectInfo</c> object containing information about all shapes that are currently selected.
/// </summary>
ISelectInfo SelectedShapes { get; }
/// <summary>
/// Determines whether labels are loaded from and saved to a project-specific label file or from a shapefile-specific label file. Using a project-level label file will create a new subdirectory with the project's name.
/// </summary>
bool LabelsUseProjectLevel { get; set; }
/// <summary>
/// Gets or sets whether selection should be persistent. If selection is persistent, previously selected
/// shapes are not cleared before selecting the new shapes. When selection is persistent you must select
/// nothing to clear the selection. The default value for this property is false. When selection is not
/// persistent, all selected shapes are cleared between selection routines unless the user is holding down
/// a control or shift key.
/// </summary>
bool SelectionPersistence { get; set; }
/// <summary>
/// The tolerance, in projected map units, to use for selection.
/// </summary>
double SelectionTolerance { get; set; }
/// <summary>
/// Gets or sets the selection method to use.
/// <list type="bullet">
/// <item>Inclusion</item>
/// <item>Intersection</item>
/// </list>
/// Inclusion means that the entire shape must be within the selection bounds in order to select
/// the shape. Intersection means that only a portion of the shape must be within the selection
/// bounds in order for the shape to be selected.
/// </summary>
SelectMode SelectMethod { get; set; }
/// <summary>
/// Gets or sets the color used to indicate a selected shape.
/// </summary>
Color SelectColor { get; set; }
/// <summary>
/// Gets or sets a tag for the map. The tag is a string variable that can be used by a developer
/// to store any information they desire.
/// </summary>
string Tag { get; set; }
/// <summary>
/// Gets or sets the handle of the cursor to use when the <c>CursorMode</c> is <c>cmUserDefined</c>.
/// </summary>
int UserCursorHandle { get; set; }
/// <summary>
/// Gets or sets the default zoom percentage to use when interacting with the map using a mouse.
/// </summary>
double ZoomPercent { get; set; }
/// <summary>
/// Clears all selected shapes from the DotSpatial, reverting them to their original colors.
/// </summary>
void ClearSelectedShapes();
/// <summary>
/// Queries all of the active shapefile layers for any within the specified tolerance of the given point.
/// </summary>
/// <param name="projX">The x coordinate, in projected map units, of the point to query.</param>
/// <param name="projY">The y coordinate, in projected map units, of the point to query.</param>
/// <param name="tolerance">Tolerance is the distance, in projected map units, around the point to include in the query.</param>
/// <returns>Returns an <c>IdentifiedLayers</c> object containing query results.</returns>
IIdentifiedLayers Identify(double projX, double projY, double tolerance);
/// <summary>
/// Prevents the legend from showing any changes made to it until the <c>UnlockLegend</c> function is called.
/// The legend maintains a count of the number of locks it has, only redrawing if there are no locks.
/// </summary>
void LockLegend();
/// <summary>
/// Unlocking the Legend allows it to redraw and update the view to reflect any changes that were made.
/// The legend maintains a count of the number of locks it has, only redrawing if there are no locks.
/// There can never be a negative number of locks.
/// </summary>
void UnlockLegend();
/// <summary>
/// Prevents the map from updating due to any changes made to the layers that are loaded until the <c>UnlockMap</c> function is called.
/// The map maintains a count of the number of locks it has, only redrawing if there are no locks.
/// </summary>
void LockMap();
/// <summary>
/// Allows the map to redraw entirely when changes are made.
/// The map maintains a count of the number of locks it has, only redrawing if there are no locks.
/// There can never be a negative number of locks.
/// </summary>
void UnlockMap();
/// <summary>
/// Converts a point in pixel coordinates to a point in projected map units.
/// </summary>
/// <param name="pixelX">X coordinate of the original point in pixels.</param>
/// <param name="pixelY">Y coordinate of the original point in pixels.</param>
/// <param name="projX">ByRef. X coordinate of the projected point.</param>
/// <param name="projY">ByRef. Y coordinate of the projected point.</param>
void PixelToProj(double pixelX, double pixelY, ref double projX, ref double projY);
/// <summary>
/// Converts a point in projected map units to a point in screen coordinates.
/// </summary>
/// <param name="projX">X coordinate of the projected map point.</param>
/// <param name="projY">Y coordinate of the projected map point.</param>
/// <param name="pixelX">ByRef. X coordinate of the screen point in pixels.</param>
/// <param name="pixelY">ByRef. Y coordinate of the screen point in pixels.</param>
void ProjToPixel(double projX, double projY, ref double pixelX, ref double pixelY);
/// <summary>
/// Forces the map to redraw. This function has no effect if the map is locked.
/// </summary>
void Redraw();
/// <summary>
/// Shows a tooltip under the cursor on the map.
/// </summary>
/// <param name="text">The text to display in the tooltip.</param>
/// <param name="milliseconds">Number of milliseconds before the tooltip automatically disappears.</param>
void ShowToolTip(string text, int milliseconds);
/// <summary>
/// Zooms the view to the maximum extents of all the loaded and visible layers.
/// </summary>
void ZoomToMaxExtents();
/// <summary>
/// Zooms the display in by the given factor.
/// </summary>
/// <param name="percent">The percentage to zoom by.</param>
void ZoomIn(double percent);
/// <summary>
/// Zooms the display out by the given factor.
/// </summary>
/// <param name="percent">The percentage to zoom by.</param>
void ZoomOut(double percent);
/// <summary>
/// Zooms to the previous extent.
/// </summary>
void ZoomToPrev();
/// <summary>
/// Takes a snapshot of the currently visible layers at the extents specified.
/// </summary>
/// <param name="bounds">The area to take the snapshot of.</param>
Image Snapshot(Envelope bounds);
/// <summary>
/// Triggers reloading of field values for the given layer. No action will occur if the layer handle is invalid, not a shapefile, or has no labels.
/// </summary>
/// <param name="layerHandle"></param>
void LabelsRelabel(int layerHandle);
/// <summary>
/// Displays the label editor form for the specified layer. No action will occur if the layer handle is invalid or not a shapefile.
/// </summary>
/// <param name="layerHandle"></param>
void LabelsEdit(int layerHandle);
/// <summary>
/// Selects shapes in the mapwindow from the specified point. The tolerance used is the global
/// tolerance set through the <c>View.SelectionTolerance</c>. This function uses the same selection
/// routines that are called when a user selects with a mouse.
/// </summary>
/// <param name="screenX">The x coordinate in pixels of the location to select.</param>
/// <param name="screenY">The y coordinate in pixels of the location to select.</param>
/// <param name="clearOldSelection">Specifies whether to clear all previously selected shapes or not.</param>
ISelectInfo Select(int screenX, int screenY, bool clearOldSelection);
/// <summary>
/// Selects shapes in the mapwindow from the specified rectangle. This function uses the
/// same selection routines that are called when a user selects with a mouse.
/// </summary>
/// <param name="screenBounds">The rectangle to select shapes with. This rectangle must be in screen (pixel) coordinates.</param>
/// <param name="clearOldSelection">Specifies whether to clear all previously selected shapes or not.</param>
ISelectInfo Select(Rectangle screenBounds, bool clearOldSelection);
}
}
|