context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.IO.Compression; using System.Net.NetworkInformation; using System.Runtime.InteropServices; using System.Text; using System.Threading; using SafeWinHttpHandle = Interop.WinHttp.SafeWinHttpHandle; namespace System.Net.Http { internal sealed class HttpWindowsProxy : IMultiWebProxy, IDisposable { private readonly MultiProxy _insecureProxy; // URI of the http system proxy if set private readonly MultiProxy _secureProxy; // URI of the https system proxy if set private readonly FailedProxyCache _failedProxies = new FailedProxyCache(); private readonly List<string> _bypass; // list of domains not to proxy private readonly bool _bypassLocal = false; // we should bypass domain considered local private readonly List<IPAddress> _localIp; private ICredentials _credentials; private readonly WinInetProxyHelper _proxyHelper; private SafeWinHttpHandle _sessionHandle; private bool _disposed; public static bool TryCreate(out IWebProxy proxy) { // This will get basic proxy setting from system using existing // WinInetProxyHelper functions. If no proxy is enabled, it will return null. SafeWinHttpHandle sessionHandle = null; proxy = null; WinInetProxyHelper proxyHelper = new WinInetProxyHelper(); if (!proxyHelper.ManualSettingsOnly && !proxyHelper.AutoSettingsUsed) { return false; } if (proxyHelper.AutoSettingsUsed) { if (NetEventSource.IsEnabled) NetEventSource.Info(proxyHelper, $"AutoSettingsUsed, calling {nameof(Interop.WinHttp.WinHttpOpen)}"); sessionHandle = Interop.WinHttp.WinHttpOpen( IntPtr.Zero, Interop.WinHttp.WINHTTP_ACCESS_TYPE_NO_PROXY, Interop.WinHttp.WINHTTP_NO_PROXY_NAME, Interop.WinHttp.WINHTTP_NO_PROXY_BYPASS, (int)Interop.WinHttp.WINHTTP_FLAG_ASYNC); if (sessionHandle.IsInvalid) { // Proxy failures are currently ignored by managed handler. if (NetEventSource.IsEnabled) NetEventSource.Error(proxyHelper, $"{nameof(Interop.WinHttp.WinHttpOpen)} returned invalid handle"); return false; } } proxy = new HttpWindowsProxy(proxyHelper, sessionHandle); return true; } private HttpWindowsProxy(WinInetProxyHelper proxyHelper, SafeWinHttpHandle sessionHandle) { _proxyHelper = proxyHelper; _sessionHandle = sessionHandle; if (proxyHelper.ManualSettingsUsed) { if (NetEventSource.IsEnabled) NetEventSource.Info(proxyHelper, $"ManualSettingsUsed, {proxyHelper.Proxy}"); _secureProxy = MultiProxy.Parse(_failedProxies, proxyHelper.Proxy, true); _insecureProxy = MultiProxy.Parse(_failedProxies, proxyHelper.Proxy, false); if (!string.IsNullOrWhiteSpace(proxyHelper.ProxyBypass)) { int idx = 0; int start = 0; string tmp; // Process bypass list for manual setting. // Initial list size is best guess based on string length assuming each entry is at least 5 characters on average. _bypass = new List<string>(proxyHelper.ProxyBypass.Length / 5); while (idx < proxyHelper.ProxyBypass.Length) { // Strip leading spaces and scheme if any. while (idx < proxyHelper.ProxyBypass.Length && proxyHelper.ProxyBypass[idx] == ' ') { idx += 1; }; if (string.Compare(proxyHelper.ProxyBypass, idx, "http://", 0, 7, StringComparison.OrdinalIgnoreCase) == 0) { idx += 7; } else if (string.Compare(proxyHelper.ProxyBypass, idx, "https://", 0, 8, StringComparison.OrdinalIgnoreCase) == 0) { idx += 8; } if (idx < proxyHelper.ProxyBypass.Length && proxyHelper.ProxyBypass[idx] == '[') { // Strip [] from IPv6 so we can use IdnHost laster for matching. idx += 1; } start = idx; while (idx < proxyHelper.ProxyBypass.Length && proxyHelper.ProxyBypass[idx] != ' ' && proxyHelper.ProxyBypass[idx] != ';' && proxyHelper.ProxyBypass[idx] != ']') { idx += 1; }; if (idx == start) { // Empty string. tmp = null; } else if (string.Compare(proxyHelper.ProxyBypass, start, "<local>", 0, 7, StringComparison.OrdinalIgnoreCase) == 0) { _bypassLocal = true; tmp = null; } else { tmp = proxyHelper.ProxyBypass.Substring(start, idx - start); } // Skip trailing characters if any. if (idx < proxyHelper.ProxyBypass.Length && proxyHelper.ProxyBypass[idx] != ';') { // Got stopped at space or ']'. Strip until next ';' or end. while (idx < proxyHelper.ProxyBypass.Length && proxyHelper.ProxyBypass[idx] != ';') { idx += 1; }; } if (idx < proxyHelper.ProxyBypass.Length && proxyHelper.ProxyBypass[idx] == ';') { idx++; } if (tmp == null) { continue; } _bypass.Add(tmp); } if (_bypass.Count == 0) { // Bypass string only had garbage we did not parse. _bypass = null; } } if (_bypassLocal) { _localIp = new List<IPAddress>(); foreach (NetworkInterface netInterface in NetworkInterface.GetAllNetworkInterfaces()) { IPInterfaceProperties ipProps = netInterface.GetIPProperties(); foreach (UnicastIPAddressInformation addr in ipProps.UnicastAddresses) { _localIp.Add(addr.Address); } } } } } public void Dispose() { if (!_disposed) { _disposed = true; if (_sessionHandle != null && !_sessionHandle.IsInvalid) { SafeWinHttpHandle.DisposeAndClearHandle(ref _sessionHandle); } } } /// <summary> /// Gets the proxy URI. (IWebProxy interface) /// </summary> public Uri GetProxy(Uri uri) { GetMultiProxy(uri).ReadNext(out Uri proxyUri, out _); return proxyUri; } /// <summary> /// Gets the proxy URIs. /// </summary> public MultiProxy GetMultiProxy(Uri uri) { // We need WinHTTP to detect and/or process a PAC (JavaScript) file. This maps to // "Automatically detect settings" and/or "Use automatic configuration script" from IE // settings. But, calling into WinHTTP can be slow especially when it has to call into // the out-of-process service to discover, load, and run the PAC file. So, we skip // calling into WinHTTP if there was a recent failure to detect a PAC file on the network. // This is a common error. The default IE settings on a Windows machine consist of the // single checkbox for "Automatically detect settings" turned on and most networks // won't actually discover a PAC file on the network since WPAD protocol isn't configured. if (_proxyHelper.AutoSettingsUsed && !_proxyHelper.RecentAutoDetectionFailure) { var proxyInfo = new Interop.WinHttp.WINHTTP_PROXY_INFO(); try { if (_proxyHelper.GetProxyForUrl(_sessionHandle, uri, out proxyInfo)) { // If WinHTTP just specified a Proxy with no ProxyBypass list, then // we can return the Proxy uri directly. if (proxyInfo.ProxyBypass == IntPtr.Zero) { if (proxyInfo.Proxy != IntPtr.Zero) { string proxyStr = Marshal.PtrToStringUni(proxyInfo.Proxy); return MultiProxy.CreateLazy(_failedProxies, proxyStr, IsSecureUri(uri)); } else { return MultiProxy.Empty; } } // A bypass list was also specified. This means that WinHTTP has fallen back to // using the manual IE settings specified and there is a ProxyBypass list also. // Since we're not really using the full WinHTTP stack, we need to use HttpSystemProxy // to do the computation of the final proxy uri merging the information from the Proxy // and ProxyBypass strings. } else { return MultiProxy.Empty; } } finally { Marshal.FreeHGlobal(proxyInfo.Proxy); Marshal.FreeHGlobal(proxyInfo.ProxyBypass); } } // Fallback to manual settings if present. if (_proxyHelper.ManualSettingsUsed) { if (_bypassLocal) { IPAddress address = null; if (uri.IsLoopback) { // This is optimization for loopback addresses. // Unfortunately this does not work for all local addresses. return MultiProxy.Empty; } // Pre-Check if host may be IP address to avoid parsing. if (uri.HostNameType == UriHostNameType.IPv6 || uri.HostNameType == UriHostNameType.IPv4) { // RFC1123 allows labels to start with number. // Leading number may or may not be IP address. // IPv6 [::1] notation. '[' is not valid character in names. if (IPAddress.TryParse(uri.IdnHost, out address)) { // Host is valid IP address. // Check if it belongs to local system. foreach (IPAddress a in _localIp) { if (a.Equals(address)) { return MultiProxy.Empty; } } } } if (uri.HostNameType != UriHostNameType.IPv6 && !uri.IdnHost.Contains('.')) { // Not address and does not have a dot. // Hosts without FQDN are considered local. return MultiProxy.Empty; } } // Check if we have other rules for bypass. if (_bypass != null) { foreach (string entry in _bypass) { // IdnHost does not have []. if (SimpleRegex.IsMatchWithStarWildcard(uri.IdnHost, entry)) { return MultiProxy.Empty; } } } // We did not find match on bypass list. return IsSecureUri(uri) ? _secureProxy : _insecureProxy; } return MultiProxy.Empty; } private static bool IsSecureUri(Uri uri) { return uri.Scheme == UriScheme.Https || uri.Scheme == UriScheme.Wss; } /// <summary> /// Checks if URI is subject to proxy or not. /// </summary> public bool IsBypassed(Uri uri) { // This HttpSystemProxy class is only consumed by SocketsHttpHandler and is not exposed outside of // SocketsHttpHandler. The current pattern for consumption of IWebProxy is to call IsBypassed first. // If it returns false, then the caller will call GetProxy. For this proxy implementation, computing // the return value for IsBypassed is as costly as calling GetProxy. We want to avoid doing extra // work. So, this proxy implementation for the IsBypassed method can always return false. Then the // GetProxy method will return non-null for a proxy, or null if no proxy should be used. return false; } public ICredentials Credentials { get { return _credentials; } set { _credentials = value; } } // Access function for unit tests. internal List<string> BypassList => _bypass; } }
using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; namespace PCSMaterials.ActualCost { /// <summary> /// Summary description for StandardCostToActualCost. /// </summary> public class StandardCostToActualCost : System.Windows.Forms.Form { private C1.Win.C1Input.C1DateEdit c1DateEdit1; private System.Windows.Forms.Label label1; private C1.Win.C1List.C1Combo cboCCN; private System.Windows.Forms.Label lblCCN; private System.Windows.Forms.Button btnHelp; private System.Windows.Forms.Button btnClose; private System.Windows.Forms.TextBox txtWorkOrder; private System.Windows.Forms.Label lblWorkOrder; private System.Windows.Forms.Button btnRollUp; /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; public StandardCostToActualCost() { // // Required for Windows Form Designer support // InitializeComponent(); // // TODO: Add any constructor code after InitializeComponent call // } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if(components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.c1DateEdit1 = new C1.Win.C1Input.C1DateEdit(); this.label1 = new System.Windows.Forms.Label(); this.cboCCN = new C1.Win.C1List.C1Combo(); this.lblCCN = new System.Windows.Forms.Label(); this.btnHelp = new System.Windows.Forms.Button(); this.btnClose = new System.Windows.Forms.Button(); this.txtWorkOrder = new System.Windows.Forms.TextBox(); this.lblWorkOrder = new System.Windows.Forms.Label(); this.btnRollUp = new System.Windows.Forms.Button(); ((System.ComponentModel.ISupportInitialize)(this.c1DateEdit1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.cboCCN)).BeginInit(); this.SuspendLayout(); // // c1DateEdit1 // this.c1DateEdit1.AccessibleDescription = ""; this.c1DateEdit1.AccessibleName = ""; // // c1DateEdit1.Calendar // this.c1DateEdit1.Calendar.AccessibleDescription = ""; this.c1DateEdit1.Calendar.AccessibleName = ""; this.c1DateEdit1.Calendar.ImeMode = System.Windows.Forms.ImeMode.NoControl; this.c1DateEdit1.CustomFormat = "dd-MM-yyyy"; this.c1DateEdit1.EmptyAsNull = true; this.c1DateEdit1.FormatType = C1.Win.C1Input.FormatTypeEnum.CustomFormat; this.c1DateEdit1.Location = new System.Drawing.Point(74, 30); this.c1DateEdit1.Name = "c1DateEdit1"; this.c1DateEdit1.Size = new System.Drawing.Size(87, 20); this.c1DateEdit1.TabIndex = 53; this.c1DateEdit1.Tag = null; this.c1DateEdit1.TextAlign = System.Windows.Forms.HorizontalAlignment.Center; this.c1DateEdit1.VisibleButtons = C1.Win.C1Input.DropDownControlButtonFlags.DropDown; // // label1 // this.label1.AccessibleDescription = ""; this.label1.AccessibleName = ""; this.label1.ForeColor = System.Drawing.Color.Maroon; this.label1.ImeMode = System.Windows.Forms.ImeMode.NoControl; this.label1.Location = new System.Drawing.Point(5, 30); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(71, 20); this.label1.TabIndex = 54; this.label1.Text = "Rollup Date"; this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // cboCCN // this.cboCCN.AccessibleDescription = ""; this.cboCCN.AccessibleName = ""; this.cboCCN.AddItemSeparator = ';'; this.cboCCN.Caption = ""; this.cboCCN.CaptionHeight = 17; this.cboCCN.CharacterCasing = System.Windows.Forms.CharacterCasing.Normal; this.cboCCN.ColumnCaptionHeight = 17; this.cboCCN.ColumnFooterHeight = 17; this.cboCCN.ComboStyle = C1.Win.C1List.ComboStyleEnum.DropdownList; this.cboCCN.ContentHeight = 15; this.cboCCN.DeadAreaBackColor = System.Drawing.Color.Empty; this.cboCCN.EditorBackColor = System.Drawing.SystemColors.Window; this.cboCCN.EditorFont = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.cboCCN.EditorForeColor = System.Drawing.SystemColors.WindowText; this.cboCCN.EditorHeight = 15; this.cboCCN.GapHeight = 2; this.cboCCN.ItemHeight = 15; this.cboCCN.Location = new System.Drawing.Point(74, 6); this.cboCCN.MatchEntryTimeout = ((long)(2000)); this.cboCCN.MaxDropDownItems = ((short)(5)); this.cboCCN.MaxLength = 32767; this.cboCCN.MouseCursor = System.Windows.Forms.Cursors.Default; this.cboCCN.Name = "cboCCN"; this.cboCCN.RowDivider.Color = System.Drawing.Color.DarkGray; this.cboCCN.RowDivider.Style = C1.Win.C1List.LineStyleEnum.None; this.cboCCN.RowSubDividerColor = System.Drawing.Color.DarkGray; this.cboCCN.Size = new System.Drawing.Size(87, 21); this.cboCCN.TabIndex = 46; this.cboCCN.PropBag = "<?xml version=\"1.0\"?><Blob><Styles type=\"C1.Win.C1List.Design.ContextWrapper\"><Da" + "ta>Group{AlignVert:Center;Border:None,,0, 0, 0, 0;BackColor:ControlDark;}Style2{" + "}Style5{}Style4{}Style7{}Style6{}EvenRow{BackColor:Aqua;}Selected{ForeColor:High" + "lightText;BackColor:Highlight;}Style3{}Inactive{ForeColor:InactiveCaptionText;Ba" + "ckColor:InactiveCaption;}Footer{}Caption{AlignHorz:Center;}Normal{BackColor:Wind" + "ow;}HighlightRow{ForeColor:HighlightText;BackColor:Highlight;}Style1{}OddRow{}Re" + "cordSelector{AlignImage:Center;}Heading{Wrap:True;BackColor:Control;Border:Raise" + "d,,1, 1, 1, 1;ForeColor:ControlText;AlignVert:Center;}Style8{}Style10{}Style11{}" + "Style9{AlignHorz:Near;}</Data></Styles><Splits><C1.Win.C1List.ListBoxView AllowC" + "olSelect=\"False\" Name=\"\" CaptionHeight=\"17\" ColumnCaptionHeight=\"17\" ColumnFoote" + "rHeight=\"17\" VerticalScrollGroup=\"1\" HorizontalScrollGroup=\"1\"><ClientRect>0, 0," + " 116, 156</ClientRect><VScrollBar><Width>16</Width></VScrollBar><HScrollBar><Hei" + "ght>16</Height></HScrollBar><CaptionStyle parent=\"Style2\" me=\"Style9\" /><EvenRow" + "Style parent=\"EvenRow\" me=\"Style7\" /><FooterStyle parent=\"Footer\" me=\"Style3\" />" + "<GroupStyle parent=\"Group\" me=\"Style11\" /><HeadingStyle parent=\"Heading\" me=\"Sty" + "le2\" /><HighLightRowStyle parent=\"HighlightRow\" me=\"Style6\" /><InactiveStyle par" + "ent=\"Inactive\" me=\"Style4\" /><OddRowStyle parent=\"OddRow\" me=\"Style8\" /><RecordS" + "electorStyle parent=\"RecordSelector\" me=\"Style10\" /><SelectedStyle parent=\"Selec" + "ted\" me=\"Style5\" /><Style parent=\"Normal\" me=\"Style1\" /></C1.Win.C1List.ListBoxV" + "iew></Splits><NamedStyles><Style parent=\"\" me=\"Normal\" /><Style parent=\"Normal\" " + "me=\"Heading\" /><Style parent=\"Heading\" me=\"Footer\" /><Style parent=\"Heading\" me=" + "\"Caption\" /><Style parent=\"Heading\" me=\"Inactive\" /><Style parent=\"Normal\" me=\"S" + "elected\" /><Style parent=\"Normal\" me=\"HighlightRow\" /><Style parent=\"Normal\" me=" + "\"EvenRow\" /><Style parent=\"Normal\" me=\"OddRow\" /><Style parent=\"Heading\" me=\"Rec" + "ordSelector\" /><Style parent=\"Caption\" me=\"Group\" /></NamedStyles><vertSplits>1<" + "/vertSplits><horzSplits>1</horzSplits><Layout>Modified</Layout><DefaultRecSelWid" + "th>16</DefaultRecSelWidth></Blob>"; // // lblCCN // this.lblCCN.AccessibleDescription = ""; this.lblCCN.AccessibleName = ""; this.lblCCN.ForeColor = System.Drawing.Color.Maroon; this.lblCCN.ImeMode = System.Windows.Forms.ImeMode.NoControl; this.lblCCN.Location = new System.Drawing.Point(5, 8); this.lblCCN.Name = "lblCCN"; this.lblCCN.Size = new System.Drawing.Size(71, 20); this.lblCCN.TabIndex = 51; this.lblCCN.Text = "CCN"; this.lblCCN.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // btnHelp // this.btnHelp.FlatStyle = System.Windows.Forms.FlatStyle.System; this.btnHelp.ImeMode = System.Windows.Forms.ImeMode.NoControl; this.btnHelp.Location = new System.Drawing.Point(224, 112); this.btnHelp.Name = "btnHelp"; this.btnHelp.Size = new System.Drawing.Size(60, 23); this.btnHelp.TabIndex = 49; this.btnHelp.Text = "&Help"; // // btnClose // this.btnClose.FlatStyle = System.Windows.Forms.FlatStyle.System; this.btnClose.ImeMode = System.Windows.Forms.ImeMode.NoControl; this.btnClose.Location = new System.Drawing.Point(286, 112); this.btnClose.Name = "btnClose"; this.btnClose.Size = new System.Drawing.Size(60, 23); this.btnClose.TabIndex = 50; this.btnClose.Text = "&Close"; // // txtWorkOrder // this.txtWorkOrder.AccessibleDescription = ""; this.txtWorkOrder.AccessibleName = ""; this.txtWorkOrder.Location = new System.Drawing.Point(74, 53); this.txtWorkOrder.Name = "txtWorkOrder"; this.txtWorkOrder.Size = new System.Drawing.Size(87, 20); this.txtWorkOrder.TabIndex = 47; this.txtWorkOrder.Text = ""; // // lblWorkOrder // this.lblWorkOrder.AccessibleDescription = ""; this.lblWorkOrder.AccessibleName = ""; this.lblWorkOrder.ForeColor = System.Drawing.Color.Maroon; this.lblWorkOrder.ImeMode = System.Windows.Forms.ImeMode.NoControl; this.lblWorkOrder.Location = new System.Drawing.Point(5, 53); this.lblWorkOrder.Name = "lblWorkOrder"; this.lblWorkOrder.Size = new System.Drawing.Size(71, 20); this.lblWorkOrder.TabIndex = 52; this.lblWorkOrder.Text = "From Year"; this.lblWorkOrder.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // btnRollUp // this.btnRollUp.FlatStyle = System.Windows.Forms.FlatStyle.System; this.btnRollUp.ImeMode = System.Windows.Forms.ImeMode.NoControl; this.btnRollUp.Location = new System.Drawing.Point(8, 114); this.btnRollUp.Name = "btnRollUp"; this.btnRollUp.Size = new System.Drawing.Size(73, 23); this.btnRollUp.TabIndex = 48; this.btnRollUp.Text = "Rollup"; // // StandardCostToActualCost // this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(350, 143); this.Controls.Add(this.c1DateEdit1); this.Controls.Add(this.label1); this.Controls.Add(this.cboCCN); this.Controls.Add(this.lblCCN); this.Controls.Add(this.btnHelp); this.Controls.Add(this.btnClose); this.Controls.Add(this.txtWorkOrder); this.Controls.Add(this.lblWorkOrder); this.Controls.Add(this.btnRollUp); this.Name = "StandardCostToActualCost"; this.Text = "Standard Cost Rollup From Actual Cost"; ((System.ComponentModel.ISupportInitialize)(this.c1DateEdit1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.cboCCN)).EndInit(); this.ResumeLayout(false); } #endregion } }
/****************************************************************************** * Copyright (C) Leap Motion, Inc. 2011-2017. * * Leap Motion proprietary and confidential. * * * * Use subject to the terms of the Leap Motion SDK Agreement available at * * https://developer.leapmotion.com/sdk_agreement, or another agreement * * between Leap Motion and you, your company or other organization. * ******************************************************************************/ using UnityEngine; #if UNITY_EDITOR using UnityEditor; #endif using System; using System.Collections; using Leap.Unity.Attributes; //using Leap.Unity.Graphing; namespace Leap.Unity { /**LeapServiceProvider creates a Controller and supplies Leap Hands and images */ public class LeapServiceProvider : LeapProvider { /** Conversion factor for nanoseconds to seconds. */ protected const float NS_TO_S = 1e-6f; /** Conversion factor for seconds to nanoseconds. */ protected const float S_TO_NS = 1e6f; /** Transform Array for Precull Latching **/ protected const string HAND_ARRAY = "_LeapHandTransforms"; public enum FrameOptimizationMode { None, ReuseUpdateForPhysics, ReusePhysicsForUpdate, } [Tooltip("Set true if the Leap Motion hardware is mounted on an HMD; otherwise, leave false.")] [SerializeField] protected bool _isHeadMounted = false; [SerializeField] protected LeapVRTemporalWarping _temporalWarping; [Tooltip("When enabled, the provider will only calculate one leap frame instead of two.")] [SerializeField] protected FrameOptimizationMode _frameOptimization = FrameOptimizationMode.None; [Header("[Experimental]")] [Tooltip("Pass updated transform matrices to objects with materials using the VertexOffsetShader.")] [SerializeField] protected bool _updateHandInPrecull = false; protected bool _useInterpolation = true; //Extrapolate on Android to compensate for the latency introduced by its graphics pipeline #if UNITY_ANDROID protected int ExtrapolationAmount = 15; protected int BounceAmount = 70; #else protected int ExtrapolationAmount = 0; protected int BounceAmount = 0; #endif protected Controller leap_controller_; protected bool manualUpdateHasBeenCalledSinceUpdate; protected Vector3 warpedPosition; protected Quaternion warpedRotation; protected SmoothedFloat _fixedOffset = new SmoothedFloat(); protected SmoothedFloat _smoothedTrackingLatency = new SmoothedFloat(); protected Frame _untransformedUpdateFrame; protected Frame _transformedUpdateFrame; protected Frame _untransformedFixedFrame; protected Frame _transformedFixedFrame; protected Matrix4x4[] _transformArray = new Matrix4x4[2]; [NonSerialized] public long imageTimeStamp = 0; public override Frame CurrentFrame { get { if (_frameOptimization == FrameOptimizationMode.ReusePhysicsForUpdate) { return _transformedFixedFrame; } else { return _transformedUpdateFrame; } } } public override Frame CurrentFixedFrame { get { if (_frameOptimization == FrameOptimizationMode.ReuseUpdateForPhysics) { return _transformedUpdateFrame; } else { return _transformedFixedFrame; } } } protected bool UseInterpolation { get { return _useInterpolation; } set { _useInterpolation = value; } } public bool UpdateHandInPrecull { get { return _updateHandInPrecull; } set { resetTransforms(); _updateHandInPrecull = value; } } /** Returns the Leap Controller instance. */ public Controller GetLeapController() { #if UNITY_EDITOR //Null check to deal with hot reloading if (leap_controller_ == null) { createController(); } #endif return leap_controller_; } /** True, if the Leap Motion hardware is plugged in and this application is connected to the Leap Motion service. */ public bool IsConnected() { return GetLeapController().IsConnected; } /** Returns information describing the device hardware. */ public LeapDeviceInfo GetDeviceInfo() { return LeapDeviceInfo.GetLeapDeviceInfo(); } public void ReTransformFrames() { transformFrame(_untransformedUpdateFrame, _transformedUpdateFrame); transformFrame(_untransformedFixedFrame, _transformedFixedFrame); } protected virtual void Reset() { if (checkShouldEnableHeadMounted()) { _isHeadMounted = true; } _temporalWarping = GetComponentInParent<LeapVRTemporalWarping>(); _frameOptimization = FrameOptimizationMode.None; _updateHandInPrecull = false; } protected virtual void Awake() { _fixedOffset.delay = 0.4f; _smoothedTrackingLatency.SetBlend(0.99f, 0.0111f); } protected virtual void Start() { checkShouldEnableHeadMounted(); createController(); _transformedUpdateFrame = new Frame(); _transformedFixedFrame = new Frame(); _untransformedUpdateFrame = new Frame(); _untransformedFixedFrame = new Frame(); } protected virtual void Update() { #if UNITY_EDITOR if (EditorApplication.isCompiling) { EditorApplication.isPlaying = false; Debug.LogWarning("Unity hot reloading not currently supported. Stopping Editor Playback."); return; } #endif manualUpdateHasBeenCalledSinceUpdate = false; _fixedOffset.Update(Time.time - Time.fixedTime, Time.deltaTime); if (_frameOptimization == FrameOptimizationMode.ReusePhysicsForUpdate) { DispatchUpdateFrameEvent(_transformedFixedFrame); return; } if (_useInterpolation) { #if !UNITY_ANDROID _smoothedTrackingLatency.value = Mathf.Min(_smoothedTrackingLatency.value, 30000f); _smoothedTrackingLatency.Update((float)(leap_controller_.Now() - leap_controller_.FrameTimestamp()), Time.deltaTime); #endif leap_controller_.GetInterpolatedFrameFromTime(_untransformedUpdateFrame, CalculateInterpolationTime() + (ExtrapolationAmount * 1000), CalculateInterpolationTime() - (BounceAmount * 1000)); } else { leap_controller_.Frame(_untransformedUpdateFrame); } imageTimeStamp = leap_controller_.FrameTimestamp(); if (_untransformedUpdateFrame != null) { transformFrame(_untransformedUpdateFrame, _transformedUpdateFrame); DispatchUpdateFrameEvent(_transformedUpdateFrame); } } protected virtual void FixedUpdate() { if (_frameOptimization == FrameOptimizationMode.ReuseUpdateForPhysics) { DispatchFixedFrameEvent(_transformedUpdateFrame); return; } if (_useInterpolation) { leap_controller_.GetInterpolatedFrame(_untransformedFixedFrame, CalculateInterpolationTime()); } else { leap_controller_.Frame(_untransformedFixedFrame); } if (_untransformedFixedFrame != null) { transformFrame(_untransformedFixedFrame, _transformedFixedFrame); DispatchFixedFrameEvent(_transformedFixedFrame); } } long CalculateInterpolationTime(bool endOfFrame = false) { #if UNITY_ANDROID return leap_controller_.Now() - 16000; #else if (leap_controller_ != null) { return leap_controller_.Now() - (long)_smoothedTrackingLatency.value + (_updateHandInPrecull && !endOfFrame ? (long)(Time.smoothDeltaTime * S_TO_NS / Time.timeScale) : 0); } else { return 0; } #endif } protected virtual void OnDestroy() { destroyController(); } protected virtual void OnApplicationPause(bool isPaused) { if (leap_controller_ != null) { if (isPaused) { leap_controller_.StopConnection(); } else { leap_controller_.StartConnection(); } } } protected virtual void OnApplicationQuit() { destroyController(); } protected virtual void OnEnable() { Camera.onPreCull -= LateUpdateHandTransforms; Camera.onPreCull += LateUpdateHandTransforms; resetTransforms(); } protected virtual void OnDisable() { Camera.onPreCull -= LateUpdateHandTransforms; resetTransforms(); } private bool checkShouldEnableHeadMounted() { if (UnityEngine.VR.VRSettings.enabled) { var parentCamera = GetComponentInParent<Camera>(); if (parentCamera != null && parentCamera.stereoTargetEye != StereoTargetEyeMask.None) { if (!_isHeadMounted) { if (Application.isPlaying) { Debug.LogError("VR is enabled and the LeapServiceProvider is the child of a " + "camera targeting one or both stereo eyes; You should " + "check the isHeadMounted option on the LeapServiceProvider " + "if the Leap is mounted or attached to your VR headset!", this); } return true; } } } return false; } /* * Resets the Global Hand Transform Shader Matrices */ protected void resetTransforms() { _transformArray[0] = Matrix4x4.identity; _transformArray[1] = Matrix4x4.identity; Shader.SetGlobalMatrixArray(HAND_ARRAY, _transformArray); } /* * Initializes the Leap Motion policy flags. * The POLICY_OPTIMIZE_HMD flag improves tracking for head-mounted devices. */ protected void initializeFlags() { if (leap_controller_ == null) { return; } //Optimize for top-down tracking if on head mounted display. if (_isHeadMounted) { leap_controller_.SetPolicy(Controller.PolicyFlag.POLICY_OPTIMIZE_HMD); } else { leap_controller_.ClearPolicy(Controller.PolicyFlag.POLICY_OPTIMIZE_HMD); } } /** Create an instance of a Controller, initialize its policy flags * and subscribe to connection event */ protected void createController() { if (leap_controller_ != null) { destroyController(); } leap_controller_ = new Controller(); if (leap_controller_.IsConnected) { initializeFlags(); } else { leap_controller_.Device += onHandControllerConnect; } } /** Calling this method stop the connection for the existing instance of a Controller, * clears old policy flags and resets to null */ protected void destroyController() { if (leap_controller_ != null) { if (leap_controller_.IsConnected) { leap_controller_.ClearPolicy(Controller.PolicyFlag.POLICY_OPTIMIZE_HMD); } leap_controller_.StopConnection(); leap_controller_ = null; } } protected void onHandControllerConnect(object sender, LeapEventArgs args) { initializeFlags(); leap_controller_.Device -= onHandControllerConnect; } protected void transformFrame(Frame source, Frame dest, bool resampleTemporalWarping = true) { LeapTransform leapTransform; if (_temporalWarping != null) { if (resampleTemporalWarping) { _temporalWarping.TryGetWarpedTransform(LeapVRTemporalWarping.WarpedAnchor.CENTER, out warpedPosition, out warpedRotation, source.Timestamp); warpedRotation = warpedRotation * transform.localRotation; } leapTransform = new LeapTransform(warpedPosition.ToVector(), warpedRotation.ToLeapQuaternion(), transform.lossyScale.ToVector() * 1e-3f); leapTransform.MirrorZ(); } else { leapTransform = transform.GetLeapMatrix(); } dest.CopyFrom(source).Transform(leapTransform); } protected void transformHands(ref LeapTransform LeftHand, ref LeapTransform RightHand) { LeapTransform leapTransform; if (_temporalWarping != null) { leapTransform = new LeapTransform(warpedPosition.ToVector(), warpedRotation.ToLeapQuaternion(), transform.lossyScale.ToVector() * 1e-3f); leapTransform.MirrorZ(); } else { leapTransform = transform.GetLeapMatrix(); } LeftHand = new LeapTransform(leapTransform.TransformPoint(LeftHand.translation), leapTransform.TransformQuaternion(LeftHand.rotation)); RightHand = new LeapTransform(leapTransform.TransformPoint(RightHand.translation), leapTransform.TransformQuaternion(RightHand.rotation)); } public void LateUpdateHandTransforms(Camera camera) { if (_updateHandInPrecull) { #if UNITY_EDITOR //Hard-coded name of the camera used to generate the pre-render view if (camera.gameObject.name == "PreRenderCamera") { return; } bool isScenePreviewCamera = camera.gameObject.hideFlags == HideFlags.HideAndDontSave; if (isScenePreviewCamera) { return; } #endif if (Application.isPlaying && !manualUpdateHasBeenCalledSinceUpdate && leap_controller_ != null) { manualUpdateHasBeenCalledSinceUpdate = true; //Find the Left and/or Right Hand(s) to Latch Hand leftHand = null, rightHand = null; LeapTransform PrecullLeftHand = LeapTransform.Identity, PrecullRightHand = LeapTransform.Identity; for (int i = 0; i < CurrentFrame.Hands.Count; i++) { Hand updateHand = CurrentFrame.Hands[i]; if (updateHand.IsLeft && leftHand == null) { leftHand = updateHand; } else if (updateHand.IsRight && rightHand == null) { rightHand = updateHand; } } //Determine their new Transforms leap_controller_.GetInterpolatedLeftRightTransform(CalculateInterpolationTime() + (ExtrapolationAmount * 1000), CalculateInterpolationTime() - (BounceAmount * 1000), (leftHand != null ? leftHand.Id : 0), (rightHand != null ? rightHand.Id : 0), out PrecullLeftHand, out PrecullRightHand); bool LeftValid = PrecullLeftHand.translation != Vector.Zero; bool RightValid = PrecullRightHand.translation != Vector.Zero; transformHands(ref PrecullLeftHand, ref PrecullRightHand); //Calculate the Delta Transforms if (rightHand != null && RightValid) { _transformArray[0] = Matrix4x4.TRS(PrecullRightHand.translation.ToVector3(), PrecullRightHand.rotation.ToQuaternion(), Vector3.one) * Matrix4x4.Inverse(Matrix4x4.TRS(rightHand.PalmPosition.ToVector3(), rightHand.Rotation.ToQuaternion(), Vector3.one)); } if (leftHand != null && LeftValid) { _transformArray[1] = Matrix4x4.TRS(PrecullLeftHand.translation.ToVector3(), PrecullLeftHand.rotation.ToQuaternion(), Vector3.one) * Matrix4x4.Inverse(Matrix4x4.TRS(leftHand.PalmPosition.ToVector3(), leftHand.Rotation.ToQuaternion(), Vector3.one)); } //Apply inside of the vertex shader Shader.SetGlobalMatrixArray(HAND_ARRAY, _transformArray); } } } } }
// SPDX-License-Identifier: MIT // Copyright wtfsckgh@gmail.com // Copyright iced contributors #if GAS || INTEL || MASM || NASM using System; using System.Collections.Generic; using Iced.Intel; using Xunit; namespace Iced.UnitTests.Intel.FormatterTests { public sealed class MiscTests { [Fact] void Test_FormatterOperandOptions_properties() { FormatterOperandOptions options = default; options.MemorySizeOptions = MemorySizeOptions.Always; Assert.Equal(MemorySizeOptions.Always, options.MemorySizeOptions); options.MemorySizeOptions = MemorySizeOptions.Minimal; Assert.Equal(MemorySizeOptions.Minimal, options.MemorySizeOptions); options.MemorySizeOptions = MemorySizeOptions.Never; Assert.Equal(MemorySizeOptions.Never, options.MemorySizeOptions); options.MemorySizeOptions = MemorySizeOptions.Default; Assert.Equal(MemorySizeOptions.Default, options.MemorySizeOptions); options.BranchSize = true; Assert.True(options.BranchSize); options.BranchSize = false; Assert.False(options.BranchSize); options.RipRelativeAddresses = true; Assert.True(options.RipRelativeAddresses); options.RipRelativeAddresses = false; Assert.False(options.RipRelativeAddresses); } [Fact] void NumberFormattingOptions_ctor_throws_if_null_options() { Assert.Throws<ArgumentNullException>(() => new NumberFormattingOptions(null, false, false, false)); } public static IEnumerable<object[]> AllFormatters { get { var result = new List<object[]>(); foreach (var formatter in Utils.GetAllFormatters()) result.Add(new object[] { formatter }); return result.ToArray(); } } [Theory] [MemberData(nameof(AllFormatters))] void Methods_throw_if_null_input(Formatter formatter) { Instruction instruction = default; instruction.Code = Code.Mov_rm64_r64; instruction.Op0Register = Register.RAX; instruction.Op1Register = Register.RCX; Assert.Throws<ArgumentNullException>(() => formatter.FormatMnemonic(instruction, null)); Assert.Throws<ArgumentNullException>(() => formatter.FormatMnemonic(instruction, null, FormatMnemonicOptions.None)); Assert.Throws<ArgumentNullException>(() => formatter.FormatOperand(instruction, null, 0)); Assert.Throws<ArgumentNullException>(() => formatter.FormatOperandSeparator(instruction, null)); Assert.Throws<ArgumentNullException>(() => formatter.FormatAllOperands(instruction, null)); Assert.Throws<ArgumentNullException>(() => formatter.Format(instruction, null)); } [Theory] [MemberData(nameof(AllFormatters))] void Methods_throw_if_invalid_operand_or_instructionOperand(Formatter formatter) { { Instruction instruction = default; instruction.Code = Code.Mov_rm64_r64; instruction.Op0Register = Register.RAX; instruction.Op1Register = Register.RCX; const int numOps = 2; const int numInstrOps = 2; Assert.Equal(numOps, formatter.GetOperandCount(instruction)); Assert.Equal(numInstrOps, instruction.OpCount); #if INSTR_INFO Assert.Throws<ArgumentOutOfRangeException>(() => formatter.TryGetOpAccess(instruction, -1, out _)); Assert.Throws<ArgumentOutOfRangeException>(() => formatter.TryGetOpAccess(instruction, numOps, out _)); #endif Assert.Throws<ArgumentOutOfRangeException>(() => formatter.GetInstructionOperand(instruction, -1)); Assert.Throws<ArgumentOutOfRangeException>(() => formatter.GetInstructionOperand(instruction, numOps)); Assert.Throws<ArgumentOutOfRangeException>(() => formatter.GetFormatterOperand(instruction, -1)); Assert.Throws<ArgumentOutOfRangeException>(() => formatter.GetFormatterOperand(instruction, numInstrOps)); Assert.Throws<ArgumentOutOfRangeException>(() => formatter.FormatOperand(instruction, new StringOutput(), -1)); Assert.Throws<ArgumentOutOfRangeException>(() => formatter.FormatOperand(instruction, new StringOutput(), numOps)); } { Instruction invalid = default; #if INSTR_INFO Assert.Throws<ArgumentOutOfRangeException>(() => formatter.TryGetOpAccess(invalid, -1, out _)); Assert.Throws<ArgumentOutOfRangeException>(() => formatter.TryGetOpAccess(invalid, 0, out _)); #endif Assert.Throws<ArgumentOutOfRangeException>(() => formatter.GetInstructionOperand(invalid, -1)); Assert.Throws<ArgumentOutOfRangeException>(() => formatter.GetInstructionOperand(invalid, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => formatter.GetFormatterOperand(invalid, -1)); Assert.Throws<ArgumentOutOfRangeException>(() => formatter.GetFormatterOperand(invalid, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => formatter.FormatOperand(invalid, new StringOutput(), -1)); Assert.Throws<ArgumentOutOfRangeException>(() => formatter.FormatOperand(invalid, new StringOutput(), 0)); } #if ENCODER { var db = Instruction.CreateDeclareByte(new byte[8]); #if INSTR_INFO Assert.Throws<ArgumentOutOfRangeException>(() => formatter.TryGetOpAccess(db, -1, out _)); #endif Assert.Throws<ArgumentOutOfRangeException>(() => formatter.GetInstructionOperand(db, -1)); Assert.Throws<ArgumentOutOfRangeException>(() => formatter.GetFormatterOperand(db, -1)); Assert.Throws<ArgumentOutOfRangeException>(() => formatter.FormatOperand(db, new StringOutput(), -1)); Assert.Equal(8, db.DeclareDataCount); for (int i = 0; i < db.DeclareDataCount; i++) { #if INSTR_INFO formatter.TryGetOpAccess(db, i, out _); #endif formatter.GetInstructionOperand(db, i); formatter.FormatOperand(db, new StringOutput(), i); } for (int i = db.DeclareDataCount; i < 17; i++) { #if INSTR_INFO Assert.Throws<ArgumentOutOfRangeException>(() => formatter.TryGetOpAccess(db, i, out _)); #endif Assert.Throws<ArgumentOutOfRangeException>(() => formatter.GetInstructionOperand(db, i)); Assert.Throws<ArgumentOutOfRangeException>(() => formatter.FormatOperand(db, new StringOutput(), i)); } Assert.Throws<ArgumentOutOfRangeException>(() => formatter.GetFormatterOperand(db, 0)); } #endif #if ENCODER { var dw = Instruction.CreateDeclareWord(new byte[8]); #if INSTR_INFO Assert.Throws<ArgumentOutOfRangeException>(() => formatter.TryGetOpAccess(dw, -1, out _)); #endif Assert.Throws<ArgumentOutOfRangeException>(() => formatter.GetInstructionOperand(dw, -1)); Assert.Throws<ArgumentOutOfRangeException>(() => formatter.GetFormatterOperand(dw, -1)); Assert.Throws<ArgumentOutOfRangeException>(() => formatter.FormatOperand(dw, new StringOutput(), -1)); Assert.Equal(4, dw.DeclareDataCount); for (int i = 0; i < dw.DeclareDataCount; i++) { #if INSTR_INFO formatter.TryGetOpAccess(dw, i, out _); #endif formatter.GetInstructionOperand(dw, i); formatter.FormatOperand(dw, new StringOutput(), i); } for (int i = dw.DeclareDataCount; i < 17; i++) { #if INSTR_INFO Assert.Throws<ArgumentOutOfRangeException>(() => formatter.TryGetOpAccess(dw, i, out _)); #endif Assert.Throws<ArgumentOutOfRangeException>(() => formatter.GetInstructionOperand(dw, i)); Assert.Throws<ArgumentOutOfRangeException>(() => formatter.FormatOperand(dw, new StringOutput(), i)); } Assert.Throws<ArgumentOutOfRangeException>(() => formatter.GetFormatterOperand(dw, 0)); } #endif #if ENCODER { var dd = Instruction.CreateDeclareDword(new byte[8]); #if INSTR_INFO Assert.Throws<ArgumentOutOfRangeException>(() => formatter.TryGetOpAccess(dd, -1, out _)); #endif Assert.Throws<ArgumentOutOfRangeException>(() => formatter.GetInstructionOperand(dd, -1)); Assert.Throws<ArgumentOutOfRangeException>(() => formatter.GetFormatterOperand(dd, -1)); Assert.Throws<ArgumentOutOfRangeException>(() => formatter.FormatOperand(dd, new StringOutput(), -1)); Assert.Equal(2, dd.DeclareDataCount); for (int i = 0; i < dd.DeclareDataCount; i++) { #if INSTR_INFO formatter.TryGetOpAccess(dd, i, out _); #endif formatter.GetInstructionOperand(dd, i); formatter.FormatOperand(dd, new StringOutput(), i); } for (int i = dd.DeclareDataCount; i < 17; i++) { #if INSTR_INFO Assert.Throws<ArgumentOutOfRangeException>(() => formatter.TryGetOpAccess(dd, i, out _)); #endif Assert.Throws<ArgumentOutOfRangeException>(() => formatter.GetInstructionOperand(dd, i)); Assert.Throws<ArgumentOutOfRangeException>(() => formatter.FormatOperand(dd, new StringOutput(), i)); } Assert.Throws<ArgumentOutOfRangeException>(() => formatter.GetFormatterOperand(dd, 0)); } #endif #if ENCODER { var dq = Instruction.CreateDeclareQword(new byte[8]); #if INSTR_INFO Assert.Throws<ArgumentOutOfRangeException>(() => formatter.TryGetOpAccess(dq, -1, out _)); #endif Assert.Throws<ArgumentOutOfRangeException>(() => formatter.GetInstructionOperand(dq, -1)); Assert.Throws<ArgumentOutOfRangeException>(() => formatter.GetFormatterOperand(dq, -1)); Assert.Throws<ArgumentOutOfRangeException>(() => formatter.FormatOperand(dq, new StringOutput(), -1)); Assert.Equal(1, dq.DeclareDataCount); for (int i = 0; i < dq.DeclareDataCount; i++) { #if INSTR_INFO formatter.TryGetOpAccess(dq, i, out _); #endif formatter.GetInstructionOperand(dq, i); formatter.FormatOperand(dq, new StringOutput(), i); } for (int i = dq.DeclareDataCount; i < 17; i++) { #if INSTR_INFO Assert.Throws<ArgumentOutOfRangeException>(() => formatter.TryGetOpAccess(dq, i, out _)); #endif Assert.Throws<ArgumentOutOfRangeException>(() => formatter.GetInstructionOperand(dq, i)); Assert.Throws<ArgumentOutOfRangeException>(() => formatter.FormatOperand(dq, new StringOutput(), i)); } Assert.Throws<ArgumentOutOfRangeException>(() => formatter.GetFormatterOperand(dq, 0)); } #endif } [Fact] void StringOutput_throws_if_invalid_input() { Assert.Throws<ArgumentNullException>(() => new StringOutput(null)); } [Fact] void StringOutput_uses_input_sb() { var sb = new System.Text.StringBuilder(); sb.Append("Text"); var output = new StringOutput(sb); output.Write("hello", FormatterTextKind.Text); Assert.Equal("Texthello", sb.ToString()); Assert.Equal("Texthello", output.ToString()); } [Fact] void Verify_default_formatter_options() { var options = new FormatterOptions(); Assert.False(options.UppercasePrefixes); Assert.False(options.UppercaseMnemonics); Assert.False(options.UppercaseRegisters); Assert.False(options.UppercaseKeywords); Assert.False(options.UppercaseDecorators); Assert.False(options.UppercaseAll); Assert.Equal(0, options.FirstOperandCharIndex); Assert.Equal(0, options.TabSize); Assert.False(options.SpaceAfterOperandSeparator); Assert.False(options.SpaceAfterMemoryBracket); Assert.False(options.SpaceBetweenMemoryAddOperators); Assert.False(options.SpaceBetweenMemoryMulOperators); Assert.False(options.ScaleBeforeIndex); Assert.False(options.AlwaysShowScale); Assert.False(options.AlwaysShowSegmentRegister); Assert.False(options.ShowZeroDisplacements); Assert.Null(options.HexPrefix); Assert.Null(options.HexSuffix); Assert.Equal(4, options.HexDigitGroupSize); Assert.Null(options.DecimalPrefix); Assert.Null(options.DecimalSuffix); Assert.Equal(3, options.DecimalDigitGroupSize); Assert.Null(options.OctalPrefix); Assert.Null(options.OctalSuffix); Assert.Equal(4, options.OctalDigitGroupSize); Assert.Null(options.BinaryPrefix); Assert.Null(options.BinarySuffix); Assert.Equal(4, options.BinaryDigitGroupSize); Assert.Null(options.DigitSeparator); Assert.False(options.LeadingZeroes); Assert.True(options.UppercaseHex); Assert.True(options.SmallHexNumbersInDecimal); Assert.True(options.AddLeadingZeroToHexNumbers); Assert.Equal(NumberBase.Hexadecimal, options.NumberBase); Assert.True(options.BranchLeadingZeroes); Assert.False(options.SignedImmediateOperands); Assert.True(options.SignedMemoryDisplacements); Assert.False(options.DisplacementLeadingZeroes); Assert.Equal(MemorySizeOptions.Default, options.MemorySizeOptions); Assert.False(options.RipRelativeAddresses); Assert.True(options.ShowBranchSize); Assert.True(options.UsePseudoOps); Assert.False(options.ShowSymbolAddress); Assert.False(options.PreferST0); Assert.Equal(CC_b.b, options.CC_b); Assert.Equal(CC_ae.ae, options.CC_ae); Assert.Equal(CC_e.e, options.CC_e); Assert.Equal(CC_ne.ne, options.CC_ne); Assert.Equal(CC_be.be, options.CC_be); Assert.Equal(CC_a.a, options.CC_a); Assert.Equal(CC_p.p, options.CC_p); Assert.Equal(CC_np.np, options.CC_np); Assert.Equal(CC_l.l, options.CC_l); Assert.Equal(CC_ge.ge, options.CC_ge); Assert.Equal(CC_le.le, options.CC_le); Assert.Equal(CC_g.g, options.CC_g); Assert.False(options.ShowUselessPrefixes); Assert.False(options.GasNakedRegisters); Assert.False(options.GasShowMnemonicSizeSuffix); Assert.False(options.GasSpaceAfterMemoryOperandComma); Assert.True(options.MasmAddDsPrefix32); Assert.True(options.MasmSymbolDisplInBrackets); Assert.True(options.MasmDisplInBrackets); Assert.False(options.NasmShowSignExtendedImmediateSize); } [Fact] void Throws_if_invalid_CC_value() { Assert.Throws<ArgumentOutOfRangeException>(() => new FormatterOptions().CC_b = (CC_b)3); Assert.Throws<ArgumentOutOfRangeException>(() => new FormatterOptions().CC_ae = (CC_ae)3); Assert.Throws<ArgumentOutOfRangeException>(() => new FormatterOptions().CC_e = (CC_e)2); Assert.Throws<ArgumentOutOfRangeException>(() => new FormatterOptions().CC_ne = (CC_ne)2); Assert.Throws<ArgumentOutOfRangeException>(() => new FormatterOptions().CC_be = (CC_be)2); Assert.Throws<ArgumentOutOfRangeException>(() => new FormatterOptions().CC_a = (CC_a)2); Assert.Throws<ArgumentOutOfRangeException>(() => new FormatterOptions().CC_p = (CC_p)2); Assert.Throws<ArgumentOutOfRangeException>(() => new FormatterOptions().CC_np = (CC_np)2); Assert.Throws<ArgumentOutOfRangeException>(() => new FormatterOptions().CC_l = (CC_l)2); Assert.Throws<ArgumentOutOfRangeException>(() => new FormatterOptions().CC_ge = (CC_ge)2); Assert.Throws<ArgumentOutOfRangeException>(() => new FormatterOptions().CC_le = (CC_le)2); Assert.Throws<ArgumentOutOfRangeException>(() => new FormatterOptions().CC_g = (CC_g)2); } } } #endif
// 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 CompareEqualUnorderedScalarBoolean() { var test = new BooleanComparisonOpTest__CompareEqualUnorderedScalarBoolean(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse.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 (Sse.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local works test.RunLclFldScenario(); // Validates passing an instance member works test.RunFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class BooleanComparisonOpTest__CompareEqualUnorderedScalarBoolean { private const int VectorSize = 16; private const int Op1ElementCount = VectorSize / sizeof(Single); private const int Op2ElementCount = VectorSize / sizeof(Single); private static Single[] _data1 = new Single[Op1ElementCount]; private static Single[] _data2 = new Single[Op2ElementCount]; private static Vector128<Single> _clsVar1; private static Vector128<Single> _clsVar2; private Vector128<Single> _fld1; private Vector128<Single> _fld2; private BooleanComparisonOpTest__DataTable<Single, Single> _dataTable; static BooleanComparisonOpTest__CompareEqualUnorderedScalarBoolean() { var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (float)(random.NextDouble()); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data1[0]), VectorSize); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (float)(random.NextDouble()); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar2), ref Unsafe.As<Single, byte>(ref _data2[0]), VectorSize); } public BooleanComparisonOpTest__CompareEqualUnorderedScalarBoolean() { Succeeded = true; var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (float)(random.NextDouble()); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), VectorSize); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (float)(random.NextDouble()); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), VectorSize); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (float)(random.NextDouble()); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (float)(random.NextDouble()); } _dataTable = new BooleanComparisonOpTest__DataTable<Single, Single>(_data1, _data2, VectorSize); } public bool IsSupported => Sse.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { var result = Sse.CompareEqualUnorderedScalar( Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr) ); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result); } public void RunBasicScenario_Load() { var result = Sse.CompareEqualUnorderedScalar( Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr)) ); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result); } public void RunBasicScenario_LoadAligned() { var result = Sse.CompareEqualUnorderedScalar( Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr)) ); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result); } public void RunReflectionScenario_UnsafeRead() { var result = typeof(Sse).GetMethod(nameof(Sse.CompareEqualUnorderedScalar), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result)); } public void RunReflectionScenario_Load() { var result = typeof(Sse).GetMethod(nameof(Sse.CompareEqualUnorderedScalar), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) }) .Invoke(null, new object[] { Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr)) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result)); } public void RunReflectionScenario_LoadAligned() { var result = typeof(Sse).GetMethod(nameof(Sse.CompareEqualUnorderedScalar), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) }) .Invoke(null, new object[] { Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr)) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result)); } public void RunClsVarScenario() { var result = Sse.CompareEqualUnorderedScalar( _clsVar1, _clsVar2 ); ValidateResult(_clsVar1, _clsVar2, result); } public void RunLclVarScenario_UnsafeRead() { var left = Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr); var right = Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr); var result = Sse.CompareEqualUnorderedScalar(left, right); ValidateResult(left, right, result); } public void RunLclVarScenario_Load() { var left = Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)); var right = Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr)); var result = Sse.CompareEqualUnorderedScalar(left, right); ValidateResult(left, right, result); } public void RunLclVarScenario_LoadAligned() { var left = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)); var right = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr)); var result = Sse.CompareEqualUnorderedScalar(left, right); ValidateResult(left, right, result); } public void RunLclFldScenario() { var test = new BooleanComparisonOpTest__CompareEqualUnorderedScalarBoolean(); var result = Sse.CompareEqualUnorderedScalar(test._fld1, test._fld2); ValidateResult(test._fld1, test._fld2, result); } public void RunFldScenario() { var result = Sse.CompareEqualUnorderedScalar(_fld1, _fld2); ValidateResult(_fld1, _fld2, result); } public void RunUnsupportedScenario() { Succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector128<Single> left, Vector128<Single> right, bool result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Single[] inArray2 = new Single[Op2ElementCount]; Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left); Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right); ValidateResult(inArray1, inArray2, result, method); } private void ValidateResult(void* left, void* right, bool result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Single[] inArray2 = new Single[Op2ElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize); ValidateResult(inArray1, inArray2, result, method); } private void ValidateResult(Single[] left, Single[] right, bool result, [CallerMemberName] string method = "") { if ((left[0] == right[0]) != result) { Succeeded = false; Console.WriteLine($"{nameof(Sse)}.{nameof(Sse.CompareEqualUnorderedScalar)}<Boolean>(Vector128<Single>, Vector128<Single>): {method} failed:"); Console.WriteLine($" left: ({string.Join(", ", left)})"); Console.WriteLine($" right: ({string.Join(", ", right)})"); Console.WriteLine($" result: ({string.Join(", ", result)})"); Console.WriteLine(); } } } }
/// Credit jack.sydorenko, firagon /// Sourced from - http://forum.unity3d.com/threads/new-ui-and-line-drawing.253772/ /// Updated/Refactored from - http://forum.unity3d.com/threads/new-ui-and-line-drawing.253772/#post-2528050 using System.Collections.Generic; namespace UnityEngine.UI.Extensions { [AddComponentMenu("UI/Extensions/Primitives/UILineRenderer")] public class UILineRenderer : UIPrimitiveBase { private enum SegmentType { Start, Middle, End, } public enum JoinType { Bevel, Miter } public enum BezierType { None, Quick, Basic, Improved, } private const float MIN_MITER_JOIN = 15 * Mathf.Deg2Rad; // A bevel 'nice' join displaces the vertices of the line segment instead of simply rendering a // quad to connect the endpoints. This improves the look of textured and transparent lines, since // there is no overlapping. private const float MIN_BEVEL_NICE_JOIN = 30 * Mathf.Deg2Rad; private static readonly Vector2 UV_TOP_LEFT = Vector2.zero; private static readonly Vector2 UV_BOTTOM_LEFT = new Vector2(0, 1); private static readonly Vector2 UV_TOP_CENTER = new Vector2(0.5f, 0); private static readonly Vector2 UV_BOTTOM_CENTER = new Vector2(0.5f, 1); private static readonly Vector2 UV_TOP_RIGHT = new Vector2(1, 0); private static readonly Vector2 UV_BOTTOM_RIGHT = new Vector2(1, 1); private static readonly Vector2[] startUvs = new[] { UV_TOP_LEFT, UV_BOTTOM_LEFT, UV_BOTTOM_CENTER, UV_TOP_CENTER }; private static readonly Vector2[] middleUvs = new[] { UV_TOP_CENTER, UV_BOTTOM_CENTER, UV_BOTTOM_CENTER, UV_TOP_CENTER }; private static readonly Vector2[] endUvs = new[] { UV_TOP_CENTER, UV_BOTTOM_CENTER, UV_BOTTOM_RIGHT, UV_TOP_RIGHT }; [SerializeField] private Rect m_UVRect = new Rect(0f, 0f, 1f, 1f); [SerializeField] private Vector2[] m_points; public float LineThickness = 2; public bool UseMargins; public Vector2 Margin; public bool relativeSize; public bool LineList = false; public bool LineCaps = false; public JoinType LineJoins = JoinType.Bevel; public BezierType BezierMode = BezierType.None; public int BezierSegmentsPerCurve = 10; /// <summary> /// UV rectangle used by the texture. /// </summary> public Rect uvRect { get { return m_UVRect; } set { if (m_UVRect == value) return; m_UVRect = value; SetVerticesDirty(); } } /// <summary> /// Points to be drawn in the line. /// </summary> public Vector2[] Points { get { return m_points; } set { if (m_points == value) return; m_points = value; SetAllDirty(); } } protected override void OnPopulateMesh(VertexHelper vh) { if (m_points == null) return; Vector2[] pointsToDraw = m_points; //If Bezier is desired, pick the implementation if (BezierMode != BezierType.None && m_points.Length > 3) { BezierPath bezierPath = new BezierPath(); bezierPath.SetControlPoints(pointsToDraw); bezierPath.SegmentsPerCurve = BezierSegmentsPerCurve; List<Vector2> drawingPoints; switch (BezierMode) { case BezierType.Basic: drawingPoints = bezierPath.GetDrawingPoints0(); break; case BezierType.Improved: drawingPoints = bezierPath.GetDrawingPoints1(); break; default: drawingPoints = bezierPath.GetDrawingPoints2(); break; } pointsToDraw = drawingPoints.ToArray(); } var sizeX = rectTransform.rect.width; var sizeY = rectTransform.rect.height; var offsetX = -rectTransform.pivot.x * rectTransform.rect.width; var offsetY = -rectTransform.pivot.y * rectTransform.rect.height; // don't want to scale based on the size of the rect, so this is switchable now if (!relativeSize) { sizeX = 1; sizeY = 1; } if (UseMargins) { sizeX -= Margin.x; sizeY -= Margin.y; offsetX += Margin.x / 2f; offsetY += Margin.y / 2f; } vh.Clear(); // Generate the quads that make up the wide line var segments = new List<UIVertex[]>(); if (LineList) { for (var i = 1; i < pointsToDraw.Length; i += 2) { var start = pointsToDraw[i - 1]; var end = pointsToDraw[i]; start = new Vector2(start.x * sizeX + offsetX, start.y * sizeY + offsetY); end = new Vector2(end.x * sizeX + offsetX, end.y * sizeY + offsetY); if (LineCaps) { segments.Add(CreateLineCap(start, end, SegmentType.Start)); } segments.Add(CreateLineSegment(start, end, SegmentType.Middle)); if (LineCaps) { segments.Add(CreateLineCap(start, end, SegmentType.End)); } } } else { for (var i = 1; i < pointsToDraw.Length; i++) { var start = pointsToDraw[i - 1]; var end = pointsToDraw[i]; start = new Vector2(start.x * sizeX + offsetX, start.y * sizeY + offsetY); end = new Vector2(end.x * sizeX + offsetX, end.y * sizeY + offsetY); if (LineCaps && i == 1) { segments.Add(CreateLineCap(start, end, SegmentType.Start)); } segments.Add(CreateLineSegment(start, end, SegmentType.Middle)); if (LineCaps && i == pointsToDraw.Length - 1) { segments.Add(CreateLineCap(start, end, SegmentType.End)); } } } // Add the line segments to the vertex helper, creating any joins as needed for (var i = 0; i < segments.Count; i++) { if (!LineList && i < segments.Count - 1) { var vec1 = segments[i][1].position - segments[i][2].position; var vec2 = segments[i + 1][2].position - segments[i + 1][1].position; var angle = Vector2.Angle(vec1, vec2) * Mathf.Deg2Rad; // Positive sign means the line is turning in a 'clockwise' direction var sign = Mathf.Sign(Vector3.Cross(vec1.normalized, vec2.normalized).z); // Calculate the miter point var miterDistance = LineThickness / (2 * Mathf.Tan(angle / 2)); var miterPointA = segments[i][2].position - vec1.normalized * miterDistance * sign; var miterPointB = segments[i][3].position + vec1.normalized * miterDistance * sign; var joinType = LineJoins; if (joinType == JoinType.Miter) { // Make sure we can make a miter join without too many artifacts. if (miterDistance < vec1.magnitude / 2 && miterDistance < vec2.magnitude / 2 && angle > MIN_MITER_JOIN) { segments[i][2].position = miterPointA; segments[i][3].position = miterPointB; segments[i + 1][0].position = miterPointB; segments[i + 1][1].position = miterPointA; } else { joinType = JoinType.Bevel; } } if (joinType == JoinType.Bevel) { if (miterDistance < vec1.magnitude / 2 && miterDistance < vec2.magnitude / 2 && angle > MIN_BEVEL_NICE_JOIN) { if (sign < 0) { segments[i][2].position = miterPointA; segments[i + 1][1].position = miterPointA; } else { segments[i][3].position = miterPointB; segments[i + 1][0].position = miterPointB; } } var join = new UIVertex[] { segments[i][2], segments[i][3], segments[i + 1][0], segments[i + 1][1] }; vh.AddUIVertexQuad(join); } } vh.AddUIVertexQuad(segments[i]); } } private UIVertex[] CreateLineCap(Vector2 start, Vector2 end, SegmentType type) { if (type == SegmentType.Start) { var capStart = start - ((end - start).normalized * LineThickness / 2); return CreateLineSegment(capStart, start, SegmentType.Start); } else if (type == SegmentType.End) { var capEnd = end + ((end - start).normalized * LineThickness / 2); return CreateLineSegment(end, capEnd, SegmentType.End); } Debug.LogError("Bad SegmentType passed in to CreateLineCap. Must be SegmentType.Start or SegmentType.End"); return null; } private UIVertex[] CreateLineSegment(Vector2 start, Vector2 end, SegmentType type) { var uvs = middleUvs; if (type == SegmentType.Start) uvs = startUvs; else if (type == SegmentType.End) uvs = endUvs; Vector2 offset = new Vector2(start.y - end.y, end.x - start.x).normalized * LineThickness / 2; var v1 = start - offset; var v2 = start + offset; var v3 = end + offset; var v4 = end - offset; return SetVbo(new[] { v1, v2, v3, v4 }, uvs); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.Azure.AcceptanceTestsPaging { using System; using System.Linq; using System.Collections.Generic; using System.Diagnostics; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Microsoft.Rest.Serialization; using Newtonsoft.Json; using Microsoft.Rest.Azure; using Models; /// <summary> /// Long-running Operation for AutoRest /// </summary> public partial class AutoRestPagingTestService : ServiceClient<AutoRestPagingTestService>, IAutoRestPagingTestService, IAzureClient { /// <summary> /// The base URI of the service. /// </summary> public Uri BaseUri { get; set; } /// <summary> /// Gets or sets json serialization settings. /// </summary> public JsonSerializerSettings SerializationSettings { get; private set; } /// <summary> /// Gets or sets json deserialization settings. /// </summary> public JsonSerializerSettings DeserializationSettings { get; private set; } /// <summary> /// Gets Azure subscription credentials. /// </summary> public ServiceClientCredentials Credentials { get; private set; } /// <summary> /// Gets or sets the preferred language for the response. /// </summary> public string AcceptLanguage { get; set; } /// <summary> /// Gets or sets the retry timeout in seconds for Long Running Operations. /// Default value is 30. /// </summary> public int? LongRunningOperationRetryTimeout { get; set; } /// <summary> /// When set to true a unique x-ms-client-request-id value is generated and /// included in each request. Default is true. /// </summary> public bool? GenerateClientRequestId { get; set; } /// <summary> /// Gets the IPagingOperations. /// </summary> public virtual IPagingOperations Paging { get; private set; } /// <summary> /// Initializes a new instance of the AutoRestPagingTestService class. /// </summary> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected AutoRestPagingTestService(params DelegatingHandler[] handlers) : base(handlers) { this.Initialize(); } /// <summary> /// Initializes a new instance of the AutoRestPagingTestService class. /// </summary> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected AutoRestPagingTestService(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers) { this.Initialize(); } /// <summary> /// Initializes a new instance of the AutoRestPagingTestService class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> protected AutoRestPagingTestService(Uri baseUri, params DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new ArgumentNullException("baseUri"); } this.BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the AutoRestPagingTestService class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> protected AutoRestPagingTestService(Uri baseUri, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new ArgumentNullException("baseUri"); } this.BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the AutoRestPagingTestService class. /// </summary> /// <param name='credentials'> /// Required. Gets Azure subscription credentials. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public AutoRestPagingTestService(ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers) { if (credentials == null) { throw new ArgumentNullException("credentials"); } this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the AutoRestPagingTestService class. /// </summary> /// <param name='credentials'> /// Required. Gets Azure subscription credentials. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public AutoRestPagingTestService(ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (credentials == null) { throw new ArgumentNullException("credentials"); } this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the AutoRestPagingTestService class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Gets Azure subscription credentials. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public AutoRestPagingTestService(Uri baseUri, ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new ArgumentNullException("baseUri"); } if (credentials == null) { throw new ArgumentNullException("credentials"); } this.BaseUri = baseUri; this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the AutoRestPagingTestService class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Gets Azure subscription credentials. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public AutoRestPagingTestService(Uri baseUri, ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new ArgumentNullException("baseUri"); } if (credentials == null) { throw new ArgumentNullException("credentials"); } this.BaseUri = baseUri; this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes client properties. /// </summary> private void Initialize() { this.Paging = new PagingOperations(this); this.BaseUri = new Uri("http://localhost"); this.AcceptLanguage = "en-US"; this.LongRunningOperationRetryTimeout = 30; this.GenerateClientRequestId = true; SerializationSettings = new JsonSerializerSettings { Formatting = Formatting.Indented, DateFormatHandling = DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = DateTimeZoneHandling.Utc, NullValueHandling = NullValueHandling.Ignore, ReferenceLoopHandling = ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new List<JsonConverter> { new Iso8601TimeSpanConverter() } }; DeserializationSettings = new JsonSerializerSettings { DateFormatHandling = DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = DateTimeZoneHandling.Utc, NullValueHandling = NullValueHandling.Ignore, ReferenceLoopHandling = ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new List<JsonConverter> { new Iso8601TimeSpanConverter() } }; DeserializationSettings.Converters.Add(new CloudErrorJsonConverter()); } } }
using Lucene.Net.Diagnostics; using Lucene.Net.Index; using Lucene.Net.Support; using System.Collections.Generic; using JCG = J2N.Collections.Generic; namespace Lucene.Net.Search.Spans { /* * 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 AtomicReaderContext = Lucene.Net.Index.AtomicReaderContext; using IndexReaderContext = Lucene.Net.Index.IndexReaderContext; using ReaderUtil = Lucene.Net.Index.ReaderUtil; using Term = Lucene.Net.Index.Term; using TermContext = Lucene.Net.Index.TermContext; /// /// <summary> /// A wrapper to perform span operations on a non-leaf reader context /// <p> /// NOTE: this should be used for testing purposes only /// @lucene.internal /// </summary> public class MultiSpansWrapper : Spans // can't be package private due to payloads { private readonly SpanQuery query; private readonly IList<AtomicReaderContext> leaves; private int leafOrd = 0; private Spans current; private readonly IDictionary<Term, TermContext> termContexts; private readonly int numLeaves; private MultiSpansWrapper(IList<AtomicReaderContext> leaves, SpanQuery query, IDictionary<Term, TermContext> termContexts) { this.query = query; this.leaves = leaves; this.numLeaves = leaves.Count; this.termContexts = termContexts; } public static Spans Wrap(IndexReaderContext topLevelReaderContext, SpanQuery query) { IDictionary<Term, TermContext> termContexts = new Dictionary<Term, TermContext>(); JCG.SortedSet<Term> terms = new JCG.SortedSet<Term>(); query.ExtractTerms(terms); foreach (Term term in terms) { termContexts[term] = TermContext.Build(topLevelReaderContext, term); } IList<AtomicReaderContext> leaves = topLevelReaderContext.Leaves; if (leaves.Count == 1) { AtomicReaderContext ctx = leaves[0]; return query.GetSpans(ctx, ((AtomicReader)ctx.Reader).LiveDocs, termContexts); } return new MultiSpansWrapper(leaves, query, termContexts); } public override bool MoveNext() { if (leafOrd >= numLeaves) { return false; } if (current == null) { AtomicReaderContext ctx = leaves[leafOrd]; current = query.GetSpans(ctx, ((AtomicReader)ctx.Reader).LiveDocs, termContexts); } while (true) { if (current.MoveNext()) { return true; } if (++leafOrd < numLeaves) { AtomicReaderContext ctx = leaves[leafOrd]; current = query.GetSpans(ctx, ((AtomicReader)ctx.Reader).LiveDocs, termContexts); } else { current = null; break; } } return false; } public override bool SkipTo(int target) { if (leafOrd >= numLeaves) { return false; } int subIndex = ReaderUtil.SubIndex(target, leaves); if (Debugging.AssertsEnabled) Debugging.Assert(subIndex >= leafOrd); if (subIndex != leafOrd) { AtomicReaderContext ctx = leaves[subIndex]; current = query.GetSpans(ctx, ((AtomicReader)ctx.Reader).LiveDocs, termContexts); leafOrd = subIndex; } else if (current == null) { AtomicReaderContext ctx = leaves[leafOrd]; current = query.GetSpans(ctx, ((AtomicReader)ctx.Reader).LiveDocs, termContexts); } while (true) { if (target < leaves[leafOrd].DocBase) { // target was in the previous slice if (current.MoveNext()) { return true; } } else if (current.SkipTo(target - leaves[leafOrd].DocBase)) { return true; } if (++leafOrd < numLeaves) { AtomicReaderContext ctx = leaves[leafOrd]; current = query.GetSpans(ctx, ((AtomicReader)ctx.Reader).LiveDocs, termContexts); } else { current = null; break; } } return false; } public override int Doc { get { if (current == null) { return DocIdSetIterator.NO_MORE_DOCS; } return current.Doc + leaves[leafOrd].DocBase; } } public override int Start { get { if (current == null) { return DocIdSetIterator.NO_MORE_DOCS; } return current.Start; } } public override int End { get { if (current == null) { return DocIdSetIterator.NO_MORE_DOCS; } return current.End; } } public override ICollection<byte[]> GetPayload() { if (current == null) { return Collections.EmptyList<byte[]>(); } return current.GetPayload(); } public override bool IsPayloadAvailable { get { if (current == null) { return false; } return current.IsPayloadAvailable; } } public override long GetCost() { return int.MaxValue; // just for tests } } }
// // LiveWebGalleryDialog.cs // // Author: // Anton Keks <anton@azib.net> // // Copyright (C) 2009 Novell, Inc. // Copyright (C) 2009 Anton Keks // // 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.Net; using System.Reflection; using FSpot; using FSpot.Core; using Gtk; using Mono.Unix; using Hyena; namespace FSpot.Tools.LiveWebGallery { internal class LiveWebGalleryDialog : FSpot.UI.Dialog.BuilderDialog { #pragma warning disable 649 [GtkBeans.Builder.Object] Gtk.LinkButton url_button; [GtkBeans.Builder.Object] Gtk.ToggleButton activate_button; [GtkBeans.Builder.Object] Gtk.Button copy_button; [GtkBeans.Builder.Object] Gtk.Label stats_label; [GtkBeans.Builder.Object] Gtk.RadioButton current_view_radio; [GtkBeans.Builder.Object] Gtk.RadioButton tagged_radio; [GtkBeans.Builder.Object] Gtk.RadioButton selected_radio; [GtkBeans.Builder.Object] Gtk.Button tag_button; [GtkBeans.Builder.Object] Gtk.CheckButton limit_checkbox; [GtkBeans.Builder.Object] Gtk.SpinButton limit_spin; [GtkBeans.Builder.Object] Gtk.CheckButton allow_tagging_checkbox; [GtkBeans.Builder.Object] Gtk.Button tag_edit_button; #pragma warning restore 649 private SimpleWebServer server; private ILiveWebGalleryOptions options; private LiveWebGalleryStats stats; private IPAddress last_ip; private string last_client; public LiveWebGalleryDialog (SimpleWebServer server, ILiveWebGalleryOptions options, LiveWebGalleryStats stats) : base (Assembly.GetExecutingAssembly (), "LiveWebGallery.ui", "live_web_gallery_dialog") { this.server = server; this.options = options; this.stats = stats; Modal = false; activate_button.Active = server.Active; UpdateGalleryURL (); limit_checkbox.Active = options.LimitMaxPhotos; limit_spin.Sensitive = options.LimitMaxPhotos; limit_spin.Value = options.MaxPhotos; UpdateQueryRadios (); HandleQueryTagSelected (options.QueryTag != null ? options.QueryTag : App.Instance.Database.Tags.GetTagById(1)); allow_tagging_checkbox.Active = options.TaggingAllowed; tag_edit_button.Sensitive = options.TaggingAllowed; HandleEditableTagSelected (options.EditableTag != null ? options.EditableTag : App.Instance.Database.Tags.GetTagById(3)); HandleStatsChanged (null, null); activate_button.Toggled += HandleActivated; copy_button.Clicked +=HandleCopyClicked; current_view_radio.Toggled += HandleRadioChanged; tagged_radio.Toggled += HandleRadioChanged; selected_radio.Toggled += HandleRadioChanged; tag_button.Clicked += HandleQueryTagClicked; limit_checkbox.Toggled += HandleLimitToggled; limit_spin.ValueChanged += HandleLimitValueChanged; allow_tagging_checkbox.Toggled += HandleAllowTaggingToggled; tag_edit_button.Clicked += HandleTagForEditClicked; stats.StatsChanged += HandleStatsChanged; } void HandleCopyClicked(object sender, EventArgs e) { Clipboard.Get(Gdk.Atom.Intern("CLIPBOARD", true)).Text = url_button.Uri; } void HandleStatsChanged (object sender, EventArgs e) { ThreadAssist.ProxyToMain (() => { if (last_ip == null || !last_ip.Equals (stats.LastIP)) { last_ip = stats.LastIP; try { last_client = Dns.GetHostEntry (last_ip).HostName; } catch (Exception) { last_client = last_ip != null ? last_ip.ToString () : Catalog.GetString ("none"); } } stats_label.Text = string.Format(Catalog.GetString (" Gallery: {0}, Photos: {1}, Last client: {3}"), stats.GalleryViews, stats.PhotoViews, stats.BytesSent / 1024, last_client); }); } void HandleLimitToggled (object sender, EventArgs e) { options.LimitMaxPhotos = limit_checkbox.Active; limit_spin.Sensitive = limit_checkbox.Active; HandleLimitValueChanged (sender, e); } void HandleLimitValueChanged (object sender, EventArgs e) { options.MaxPhotos = limit_spin.ValueAsInt; } void HandleRadioChanged (object o, EventArgs e) { tag_button.Sensitive = tagged_radio.Active; if (tagged_radio.Active) options.QueryType = QueryType.ByTag; else if (current_view_radio.Active) options.QueryType = QueryType.CurrentView; else options.QueryType = QueryType.Selected; } void UpdateQueryRadios () { switch (options.QueryType) { case QueryType.ByTag: tagged_radio.Active = true; break; case QueryType.CurrentView: current_view_radio.Active = true; break; case QueryType.Selected: default: selected_radio.Active = true; break; } HandleRadioChanged (null, null); } void HandleActivated (object o, EventArgs e) { if (activate_button.Active) server.Start (); else server.Stop (); UpdateGalleryURL (); } void UpdateGalleryURL () { url_button.Sensitive = server.Active; copy_button.Sensitive = server.Active; if (server.Active) { url_button.Uri = "http://" + server.HostPort; url_button.Label = url_button.Uri; } else { url_button.Label = Catalog.GetString ("Gallery is inactive"); } } void ShowTagMenuFor (Widget widget, TagMenu.TagSelectedHandler handler) { TagMenu tag_menu = new TagMenu (null, App.Instance.Database.Tags); tag_menu.TagSelected += handler; tag_menu.Populate (); int x, y; GetPosition (out x, out y); x += widget.Allocation.X; y += widget.Allocation.Y; tag_menu.Popup (null, null, delegate (Menu menu, out int x_, out int y_, out bool push_in) {x_ = x; y_ = y; push_in = true;}, 0, 0); } void HandleQueryTagClicked (object sender, EventArgs e) { ShowTagMenuFor (tag_button, HandleQueryTagSelected); } void HandleQueryTagSelected (Tag tag) { options.QueryTag = tag; tag_button.Label = tag.Name; tag_button.Image = tag.Icon != null ? new Gtk.Image (tag.Icon.ScaleSimple (16, 16, Gdk.InterpType.Bilinear)) : null; } void HandleAllowTaggingToggled (object sender, EventArgs e) { tag_edit_button.Sensitive = allow_tagging_checkbox.Active; options.TaggingAllowed = allow_tagging_checkbox.Active; } void HandleTagForEditClicked (object sender, EventArgs e) { ShowTagMenuFor (tag_edit_button, HandleEditableTagSelected); } void HandleEditableTagSelected (Tag tag) { options.EditableTag = tag; tag_edit_button.Label = tag.Name; tag_edit_button.Image = tag.Icon != null ? new Gtk.Image (tag.Icon.ScaleSimple (16, 16, Gdk.InterpType.Bilinear)) : null; } } }
using System; using System.Numerics; using System.Collections.Generic; using Xunit; using ipaddress; //namespace ipaddress namespace address_test { class IPv4Prefix { public String ip; public uint prefix; public IPv4Prefix(String ip, uint prefix) { this.ip = ip; this.prefix = prefix; } } class IPv4Test { public Dictionary<String, IPv4Prefix> valid_ipv4 = new Dictionary<String, IPv4Prefix>(); public List<String> invalid_ipv4; public List<String> valid_ipv4_range; public Dictionary<String, String> netmask_values = new Dictionary<String, String>(); public Dictionary<String, UInt32> decimal_values = new Dictionary<String, UInt32>(); public IPAddress ip; public IPAddress network; public Dictionary<String, String> networks = new Dictionary<String, String>(); public Dictionary<String, String> broadcast = new Dictionary<String, String>(); public IPAddress class_a; public IPAddress class_b; public IPAddress class_c; public Dictionary<String, UInt32> classful = new Dictionary<String, UInt32>(); public IPv4Test(List<String> invalid_ipv4, List<String> valid_ipv4_range, IPAddress ip, IPAddress network, IPAddress class_a, IPAddress class_b, IPAddress class_c) { this.invalid_ipv4 = invalid_ipv4; this.valid_ipv4_range = valid_ipv4_range; this.ip = ip; this.network = network; this.class_a = class_a; this.class_b = class_b; this.class_c = class_c; } } public class TestIpv4 { static IPv4Test setup() { var ipv4t = new IPv4Test( new List<String> { "10.0.0.256", "10.0.0.0.0" }, new List<String> { "10.0.0.1-254", "10.0.1-254.0", "10.1-254.0.0" }, IpV4.create("172.16.10.1/24").unwrap(), IpV4.create("172.16.10.0/24").unwrap(), IpV4.create("10.0.0.1/8").unwrap(), IpV4.create("172.16.0.1/16").unwrap(), IpV4.create("192.168.0.1/24").unwrap()); ipv4t.valid_ipv4.Add("9.9/17", new IPv4Prefix( "9.0.0.9", 17 )); ipv4t.valid_ipv4.Add("100.1.100", new IPv4Prefix( "100.1.0.100", 32 )); ipv4t.valid_ipv4.Add("0.0.0.0/0", new IPv4Prefix( "0.0.0.0", 0 )); ipv4t.valid_ipv4.Add("10.0.0.0", new IPv4Prefix( "10.0.0.0", 32 )); ipv4t.valid_ipv4.Add("10.0.0.1", new IPv4Prefix( "10.0.0.1", 32 )); ipv4t.valid_ipv4.Add("10.0.0.1/24", new IPv4Prefix( "10.0.0.1", 24 )); ipv4t.valid_ipv4.Add("10.0.0.9/255.255.255.0", new IPv4Prefix( "10.0.0.9", 24 )); ipv4t.netmask_values.Add("0.0.0.0/0", "0.0.0.0"); ipv4t.netmask_values.Add("10.0.0.0/8", "255.0.0.0"); ipv4t.netmask_values.Add("172.16.0.0/16", "255.255.0.0"); ipv4t.netmask_values.Add("192.168.0.0/24", "255.255.255.0"); ipv4t.netmask_values.Add("192.168.100.4/30", "255.255.255.252"); ipv4t.decimal_values.Add("0.0.0.0/0", 0); ipv4t.decimal_values.Add("10.0.0.0/8", 167772160); ipv4t.decimal_values.Add("172.16.0.0/16", 2886729728); ipv4t.decimal_values.Add("192.168.0.0/24", 3232235520); ipv4t.decimal_values.Add("192.168.100.4/30", 3232261124); ipv4t.ip = IPAddress.parse("172.16.10.1/24").unwrap(); ipv4t.network = IPAddress.parse("172.16.10.0/24").unwrap(); ipv4t.broadcast.Add("10.0.0.0/8", "10.255.255.255/8"); ipv4t.broadcast.Add("172.16.0.0/16", "172.16.255.255/16"); ipv4t.broadcast.Add("192.168.0.0/24", "192.168.0.255/24"); ipv4t.broadcast.Add("192.168.100.4/30", "192.168.100.7/30"); ipv4t.networks.Add("10.5.4.3/8", "10.0.0.0/8"); ipv4t.networks.Add("172.16.5.4/16", "172.16.0.0/16"); ipv4t.networks.Add("192.168.4.3/24", "192.168.4.0/24"); ipv4t.networks.Add("192.168.100.5/30", "192.168.100.4/30"); ipv4t.class_a = IPAddress.parse("10.0.0.1/8").unwrap(); ipv4t.class_b = IPAddress.parse("172.16.0.1/16").unwrap(); ipv4t.class_c = IPAddress.parse("192.168.0.1/24").unwrap(); ipv4t.classful.Add("10.1.1.1", 8); ipv4t.classful.Add("150.1.1.1", 16); ipv4t.classful.Add("200.1.1.1", 24); return ipv4t; } [Fact] void test_initialize() { var s = setup(); foreach (var kp in s.valid_ipv4) { var i = kp.Key; var x = kp.Value; var ip = IPAddress.parse(i).unwrap(); Assert.True(ip.is_ipv4() && !ip.is_ipv6()); } Assert.Equal(32u, s.ip.prefix.ip_bits.bits); Assert.True(IPAddress.parse("1.f.13.1/-3").isErr()); Assert.True(IPAddress.parse("10.0.0.0/8").isOk()); } [Fact] void test_initialize_format_error() { foreach (var i in setup().invalid_ipv4) { Assert.True(IPAddress.parse(i).isErr()); } Assert.True(IPAddress.parse("10.0.0.0/asd").isErr()); } [Fact] void test_initialize_without_prefix() { Assert.True(IPAddress.parse("10.10.0.0").isOk()); var ip = IPAddress.parse("10.10.0.0").unwrap(); Assert.True(!ip.is_ipv6() && ip.is_ipv4()); Assert.Equal(32u, ip.prefix.num); } [Fact] void test_attributes() { foreach (var kp in setup().valid_ipv4) { var arg = kp.Key; var attr = kp.Value; var ip = IPAddress.parse(arg).unwrap(); // println!("test_attributes:{}:{:?}", arg, attr); Assert.Equal(attr.ip, ip.to_s()); Assert.Equal(attr.prefix, ip.prefix.num); } } [Fact] void test_octets() { var ip = IPAddress.parse("10.1.2.3/8").unwrap(); TestIpAddress.Compare(ip.parts(), new List<uint> { 10, 1, 2, 3 }); } [Fact] void test_method_to_string() { foreach (var kp in setup().valid_ipv4) { var arg = kp.Key; var attr = kp.Value; var ip = IPAddress.parse(arg).unwrap(); Assert.Equal(string.Format("{0}/{1}", attr.ip, attr.prefix), ip.to_string()); } } [Fact] void test_method_to_s() { foreach (var kp in setup().valid_ipv4) { var arg = kp.Key; var attr = kp.Value; var ip = IPAddress.parse(arg).unwrap(); Assert.Equal(attr.ip, ip.to_s()); // var ip_c = IPAddress.parse(arg).unwrap(); // Assert.Equal(attr.ip, ip.to_s()); } } [Fact] void test_netmask() { foreach (var kp in setup().netmask_values) { var addr = kp.Key; var mask = kp.Value; var ip = IPAddress.parse(addr).unwrap(); Assert.Equal(ip.netmask().to_s(), mask); } } [Fact] void test_method_to_u32() { foreach (var kp in setup().decimal_values) { var addr = kp.Key; var val = kp.Value; var ip = IPAddress.parse(addr).unwrap(); Assert.Equal(ip.host_address, val); } } [Fact] void test_method_is_network() { Assert.Equal(true, setup().network.is_network()); Assert.Equal(false, setup().ip.is_network()); } [Fact] void test_one_address_network() { var network = IPAddress.parse("172.16.10.1/32").unwrap(); Assert.Equal(false, network.is_network()); } [Fact] void test_method_broadcast() { foreach (var kp in setup().broadcast) { var addr = kp.Key; var bcast = kp.Value; var ip = IPAddress.parse(addr).unwrap(); Assert.Equal(bcast, ip.broadcast().to_string()); } } [Fact] void test_method_network() { foreach (var kp in setup().networks) { var addr = kp.Key; var net = kp.Value; var ip = IPAddress.parse(addr).unwrap(); Assert.Equal(net, ip.network().to_string()); } } [Fact] void test_method_bits() { var ip = IPAddress.parse("127.0.0.1").unwrap(); Assert.Equal("01111111000000000000000000000001", ip.bits()); } [Fact] void test_method_first() { var ip = IPAddress.parse("192.168.100.0/24").unwrap(); Assert.Equal("192.168.100.1", ip.first().to_s()); ip = IPAddress.parse("192.168.100.50/24").unwrap(); Assert.Equal("192.168.100.1", ip.first().to_s()); } [Fact] void test_method_last() { var ip = IPAddress.parse("192.168.100.0/24").unwrap(); Assert.Equal("192.168.100.254", ip.last().to_s()); ip = IPAddress.parse("192.168.100.50/24").unwrap(); Assert.Equal("192.168.100.254", ip.last().to_s()); } [Fact] void test_method_each_host() { var ip = IPAddress.parse("10.0.0.1/29").unwrap(); var arr = new List<String>(); ip.each_host(i => arr.Add(i.to_s()) ); Assert.Equal(arr, new List<String> { "10.0.0.1", "10.0.0.2", "10.0.0.3", "10.0.0.4", "10.0.0.5", "10.0.0.6" }); } [Fact] void test_method_each() { var ip = IPAddress.parse("10.0.0.1/29").unwrap(); var arr = new List<String>(); ip.each(i => arr.Add(i.to_s()) ); Assert.Equal(arr, new List<String> {"10.0.0.0", "10.0.0.1", "10.0.0.2", "10.0.0.3", "10.0.0.4", "10.0.0.5", "10.0.0.6", "10.0.0.7" }); } [Fact] void test_method_size() { var ip = IPAddress.parse("10.0.0.1/29").unwrap(); Assert.Equal(ip.size(), new BigInteger(8)); } [Fact] void test_method_network_u32() { Assert.Equal(2886732288, setup().ip.network().host_address); } [Fact] void test_method_broadcast_u32() { Assert.Equal(2886732543, setup().ip.broadcast().host_address); } [Fact] void test_method_include() { var ip = IPAddress.parse("192.168.10.100/24").unwrap(); var addr = IPAddress.parse("192.168.10.102/24").unwrap(); Assert.Equal(true, ip.includes(addr)); Assert.Equal(false, ip.includes(IPAddress.parse("172.16.0.48").unwrap())); ip = IPAddress.parse("10.0.0.0/8").unwrap(); Assert.Equal(true, ip.includes(IPAddress.parse("10.0.0.0/9").unwrap())); Assert.Equal(true, ip.includes(IPAddress.parse("10.1.1.1/32").unwrap())); Assert.Equal(true, ip.includes(IPAddress.parse("10.1.1.1/9").unwrap())); Assert.Equal(false, ip.includes(IPAddress.parse("172.16.0.0/16").unwrap())); Assert.Equal(false, ip.includes(IPAddress.parse("10.0.0.0/7").unwrap())); Assert.Equal(false, ip.includes(IPAddress.parse("5.5.5.5/32").unwrap())); Assert.Equal(false, ip.includes(IPAddress.parse("11.0.0.0/8").unwrap())); ip = IPAddress.parse("13.13.0.0/13").unwrap(); Assert.Equal(false, ip.includes(IPAddress.parse("13.16.0.0/32").unwrap())); } [Fact] void test_method_include_all() { var ip = IPAddress.parse("192.168.10.100/24").unwrap(); var addr1 = IPAddress.parse("192.168.10.102/24").unwrap(); var addr2 = IPAddress.parse("192.168.10.103/24").unwrap(); Assert.Equal(true, ip.includes_all(new List<IPAddress> { addr1, addr2 })); Assert.Equal(false, ip.includes_all(new List<IPAddress> { addr1, IPAddress.parse("13.16.0.0/32").unwrap() })); } [Fact] void test_method_ipv4() { Assert.Equal(true, setup().ip.is_ipv4()); } [Fact] void test_method_ipv6() { Assert.Equal(false, setup().ip.is_ipv6()); } [Fact] void test_method_private() { Assert.Equal(true, IPAddress.parse("169.254.10.50/24").unwrap().is_private()); Assert.Equal(true, IPAddress.parse("192.168.10.50/24").unwrap().is_private()); Assert.Equal(true, IPAddress.parse("192.168.10.50/16").unwrap().is_private()); Assert.Equal(true, IPAddress.parse("172.16.77.40/24").unwrap().is_private()); Assert.Equal(true, IPAddress.parse("172.16.10.50/14").unwrap().is_private()); Assert.Equal(true, IPAddress.parse("10.10.10.10/10").unwrap().is_private()); Assert.Equal(true, IPAddress.parse("10.0.0.0/8").unwrap().is_private()); Assert.Equal(false, IPAddress.parse("192.168.10.50/12").unwrap().is_private()); Assert.Equal(false, IPAddress.parse("3.3.3.3").unwrap().is_private()); Assert.Equal(false, IPAddress.parse("10.0.0.0/7").unwrap().is_private()); Assert.Equal(false, IPAddress.parse("172.32.0.0/12").unwrap().is_private()); Assert.Equal(false, IPAddress.parse("172.16.0.0/11").unwrap().is_private()); Assert.Equal(false, IPAddress.parse("192.0.0.2/24").unwrap().is_private()); } [Fact] void test_method_octet() { Assert.Equal(setup().ip.parts()[0], 172u); Assert.Equal(setup().ip.parts()[1], 16u); Assert.Equal(setup().ip.parts()[2], 10u); Assert.Equal(setup().ip.parts()[3], 1u); } [Fact] void test_method_a() { Assert.Equal(true, IpV4.is_class_a(setup().class_a)); Assert.Equal(false, IpV4.is_class_a(setup().class_b)); Assert.Equal(false, IpV4.is_class_a(setup().class_c)); } [Fact] void test_method_b() { Assert.Equal(true, IpV4.is_class_b(setup().class_b)); Assert.Equal(false, IpV4.is_class_b(setup().class_a)); Assert.Equal(false, IpV4.is_class_b(setup().class_c)); } [Fact] void test_method_c() { Assert.Equal(true, IpV4.is_class_c(setup().class_c)); Assert.Equal(false, IpV4.is_class_c(setup().class_a)); Assert.Equal(false, IpV4.is_class_c(setup().class_b)); } [Fact] void test_method_to_ipv6() { Assert.Equal("::ac10:a01", setup().ip.to_ipv6().to_s()); } [Fact] void test_method_reverse() { Assert.Equal(setup().ip.dns_reverse(), "10.16.172.in-addr.arpa"); } [Fact] void test_method_dns_rev_domains() { Assert.Equal(IPAddress.parse("173.17.5.1/23").unwrap().dns_rev_domains(), new List<String> { "4.17.173.in-addr.arpa", "5.17.173.in-addr.arpa" }); Assert.Equal(IPAddress.parse("173.17.1.1/15").unwrap().dns_rev_domains(), new List<String> { "16.173.in-addr.arpa", "17.173.in-addr.arpa" }); Assert.Equal(IPAddress.parse("173.17.1.1/7").unwrap().dns_rev_domains(), new List<String> { "172.in-addr.arpa", "173.in-addr.arpa" }); Assert.Equal(IPAddress.parse("173.17.1.1/29").unwrap().dns_rev_domains(), new List<String> { "0.1.17.173.in-addr.arpa", "1.1.17.173.in-addr.arpa", "2.1.17.173.in-addr.arpa", "3.1.17.173.in-addr.arpa", "4.1.17.173.in-addr.arpa", "5.1.17.173.in-addr.arpa", "6.1.17.173.in-addr.arpa", "7.1.17.173.in-addr.arpa"}); Assert.Equal(IPAddress.parse("174.17.1.1/24").unwrap().dns_rev_domains(), new List<String> { "1.17.174.in-addr.arpa" }); Assert.Equal(IPAddress.parse("175.17.1.1/16").unwrap().dns_rev_domains(), new List<String> { "17.175.in-addr.arpa" }); Assert.Equal(IPAddress.parse("176.17.1.1/8").unwrap().dns_rev_domains(), new List<String> { "176.in-addr.arpa" }); Assert.Equal(IPAddress.parse("177.17.1.1/0").unwrap().dns_rev_domains(), new List<String> { "in-addr.arpa" }); Assert.Equal(IPAddress.parse("178.17.1.1/32").unwrap().dns_rev_domains(), new List<String> { "1.1.17.178.in-addr.arpa" }); } [Fact] void test_method_compare() { var ip1 = IPAddress.parse("10.1.1.1/8").unwrap(); var ip2 = IPAddress.parse("10.1.1.1/16").unwrap(); var ip3 = IPAddress.parse("172.16.1.1/14").unwrap(); var ip4 = IPAddress.parse("10.1.1.1/8").unwrap(); // ip2 should be greater than ip1 Assert.Equal(true, ip1.lt(ip2)); Assert.Equal(false, ip1.gt(ip2)); Assert.Equal(false, ip2.lt(ip1)); // ip2 should be less than ip3 Assert.Equal(true, ip2.lt(ip3)); Assert.Equal(false, ip2.gt(ip3)); // ip1 should be less than ip3 Assert.Equal(true, ip1.lt(ip3)); Assert.Equal(false, ip1.gt(ip3)); Assert.Equal(false, ip3.lt(ip1)); // ip1 should be equal to itself Assert.Equal(true, ip1.equal(ip1)); // ip1 should be equal to ip4 Assert.Equal(true, ip1.equal(ip4)); // test sorting var res = IPAddress.sort(new List<IPAddress> { ip1, ip2, ip3 }); Assert.Equal(IPAddress.to_string_vec(res), new List<String> { "10.1.1.1/8", "10.1.1.1/16", "172.16.1.1/14" }); // test same prefix ip1 = IPAddress.parse("10.0.0.0/24").unwrap(); ip2 = IPAddress.parse("10.0.0.0/16").unwrap(); ip3 = IPAddress.parse("10.0.0.0/8").unwrap(); { res = IPAddress.sort(new List<IPAddress> { ip1, ip2, ip3 }); Assert.Equal(IPAddress.to_string_vec(res), new List<String> { "10.0.0.0/8", "10.0.0.0/16", "10.0.0.0/24" }); } } [Fact] void test_method_minus() { var ip1 = IPAddress.parse("10.1.1.1/8").unwrap(); var ip2 = IPAddress.parse("10.1.1.10/8").unwrap(); Assert.Equal(9, (int)ip2.sub(ip1)); Assert.Equal(9, (int)ip1.sub(ip2)); } [Fact] void test_method_plus() { var ip1 = IPAddress.parse("172.16.10.1/24").unwrap(); var ip2 = IPAddress.parse("172.16.11.2/24").unwrap(); Assert.Equal(IPAddress.to_string_vec(ip1.add(ip2)), new List<String> { "172.16.10.0/23" }); ip2 = IPAddress.parse("172.16.12.2/24").unwrap(); Assert.Equal(IPAddress.to_string_vec(ip1.add(ip2)), new List<String> { ip1.network().to_string(), ip2.network().to_string() }); ip1 = IPAddress.parse("10.0.0.0/23").unwrap(); ip2 = IPAddress.parse("10.0.2.0/24").unwrap(); Assert.Equal(IPAddress.to_string_vec(ip1.add(ip2)), new List<String> { "10.0.0.0/23", "10.0.2.0/24" }); ip1 = IPAddress.parse("10.0.0.0/23").unwrap(); ip2 = IPAddress.parse("10.0.2.0/24").unwrap(); Assert.Equal(IPAddress.to_string_vec(ip1.add(ip2)), new List<String> { "10.0.0.0/23", "10.0.2.0/24" }); ip1 = IPAddress.parse("10.0.0.0/16").unwrap(); ip2 = IPAddress.parse("10.0.2.0/24").unwrap(); Assert.Equal(IPAddress.to_string_vec(ip1.add(ip2)), new List<String> { "10.0.0.0/16" }); ip1 = IPAddress.parse("10.0.0.0/23").unwrap(); ip2 = IPAddress.parse("10.1.0.0/24").unwrap(); Assert.Equal(IPAddress.to_string_vec(ip1.add(ip2)), new List<String> { "10.0.0.0/23", "10.1.0.0/24" }); } [Fact] void test_method_netmask_equal() { var ip = IPAddress.parse("10.1.1.1/16").unwrap(); Assert.Equal(16u, ip.prefix.num); var ip2 = ip.change_netmask("255.255.255.0").unwrap(); Assert.Equal(24u, ip2.prefix.num); } [Fact] void test_method_split() { Assert.True(setup().ip.split(0).isErr()); Assert.True(setup().ip.split(257).isErr()); TestIpAddress.Compare(setup().ip.split(1).unwrap(), new List<IPAddress> { setup().ip.network() }); TestIpAddress.Compare(IPAddress.to_string_vec(setup().network.split(8).unwrap()), new List<String> { "172.16.10.0/27", "172.16.10.32/27", "172.16.10.64/27", "172.16.10.96/27", "172.16.10.128/27", "172.16.10.160/27", "172.16.10.192/27", "172.16.10.224/27"}); TestIpAddress.Compare(IPAddress.to_string_vec(setup().network.split(7).unwrap()), new List<String> { "172.16.10.0/27", "172.16.10.32/27", "172.16.10.64/27", "172.16.10.96/27", "172.16.10.128/27", "172.16.10.160/27", "172.16.10.192/26" }); TestIpAddress.Compare(IPAddress.to_string_vec(setup().network.split(6).unwrap()), new List<String> { "172.16.10.0/27", "172.16.10.32/27", "172.16.10.64/27", "172.16.10.96/27", "172.16.10.128/26", "172.16.10.192/26" }); TestIpAddress.Compare(IPAddress.to_string_vec(setup().network.split(5).unwrap()), new List<String> { "172.16.10.0/27", "172.16.10.32/27", "172.16.10.64/27", "172.16.10.96/27", "172.16.10.128/25" }); TestIpAddress.Compare(IPAddress.to_string_vec(setup().network.split(4).unwrap()), new List<String> { "172.16.10.0/26", "172.16.10.64/26", "172.16.10.128/26", "172.16.10.192/26" }); TestIpAddress.Compare(IPAddress.to_string_vec(setup().network.split(3).unwrap()), new List<String> { "172.16.10.0/26", "172.16.10.64/26", "172.16.10.128/25" }); TestIpAddress.Compare(IPAddress.to_string_vec(setup().network.split(2).unwrap()), new List<String> { "172.16.10.0/25", "172.16.10.128/25" }); TestIpAddress.Compare(IPAddress.to_string_vec(setup().network.split(1).unwrap()), new List<String> { "172.16.10.0/24" }); } [Fact] void test_method_subnet() { Assert.True(setup().network.subnet(23).isErr()); Assert.True(setup().network.subnet(33).isErr()); Assert.True(setup().ip.subnet(30).isOk()); TestIpAddress.Compare(IPAddress.to_string_vec(setup().network.subnet(26).unwrap()), new List<String> { "172.16.10.0/26", "172.16.10.64/26", "172.16.10.128/26", "172.16.10.192/26" }); TestIpAddress.Compare(IPAddress.to_string_vec(setup().network.subnet(25).unwrap()), new List<String> { "172.16.10.0/25", "172.16.10.128/25" }); TestIpAddress.Compare(IPAddress.to_string_vec(setup().network.subnet(24).unwrap()), new List<String> { "172.16.10.0/24" }); } [Fact] void test_method_supernet() { Assert.True(setup().ip.supernet(24).isErr()); Assert.Equal("0.0.0.0/0", setup().ip.supernet(0).unwrap().to_string()); // Assert.Equal("0.0.0.0/0", setup().ip.supernet(-2).unwrap().to_string()); Assert.Equal("172.16.10.0/23", setup().ip.supernet(23).unwrap().to_string()); Assert.Equal("172.16.8.0/22", setup().ip.supernet(22).unwrap().to_string()); } [Fact] void test_classmethod_parse_u32() { foreach (var kp in setup().decimal_values) { var addr = kp.Key; var value = kp.Value; var ip = IpV4.from_u32(value, 32).unwrap(); var splitted = addr.Split(new string[] { "/" }, StringSplitOptions.None); var ip2 = ip.change_prefix(uint.Parse(splitted[1])).unwrap(); Assert.Equal(ip2.to_string(), addr); } } // void test_classhmethod_extract() { // var str = "foobar172.16.10.1barbaz"; // Assert.Equal("172.16.10.1", IPAddress.extract(str).to_s // } [Fact] void test_classmethod_summarize() { // Should return self if only one network given TestIpAddress.Compare(IPAddress.summarize(new List<IPAddress> { setup().ip }), new List<IPAddress> { setup().ip.network() }); // Summarize homogeneous networks var ip1 = IPAddress.parse("172.16.10.1/24").unwrap(); var ip2 = IPAddress.parse("172.16.11.2/24").unwrap(); TestIpAddress.Compare(IPAddress.to_string_vec(IPAddress.summarize(new List<IPAddress> { ip1, ip2 })), new List<String> { "172.16.10.0/23" }); ip1 = IPAddress.parse("10.0.0.1/24").unwrap(); ip2 = IPAddress.parse("10.0.1.1/24").unwrap(); var ip3 = IPAddress.parse("10.0.2.1/24").unwrap(); var ip4 = IPAddress.parse("10.0.3.1/24").unwrap(); TestIpAddress.Compare(IPAddress.to_string_vec(IPAddress.summarize(new List<IPAddress> { ip1, ip2, ip3, ip4 })), new List<String> { "10.0.0.0/22" }); ip1 = IPAddress.parse("10.0.0.1/24").unwrap(); ip2 = IPAddress.parse("10.0.1.1/24").unwrap(); ip3 = IPAddress.parse("10.0.2.1/24").unwrap(); ip4 = IPAddress.parse("10.0.3.1/24").unwrap(); TestIpAddress.Compare(IPAddress.to_string_vec(IPAddress.summarize(new List<IPAddress> { ip4, ip3, ip2, ip1 })), new List<String> { "10.0.0.0/22" }); // Summarize non homogeneous networks ip1 = IPAddress.parse("10.0.0.0/23").unwrap(); ip2 = IPAddress.parse("10.0.2.0/24").unwrap(); TestIpAddress.Compare(IPAddress.to_string_vec(IPAddress.summarize(new List<IPAddress> { ip1, ip2 })), new List<String> { "10.0.0.0/23", "10.0.2.0/24"}); ip1 = IPAddress.parse("10.0.0.0/16").unwrap(); ip2 = IPAddress.parse("10.0.2.0/24").unwrap(); TestIpAddress.Compare(IPAddress.to_string_vec(IPAddress.summarize(new List<IPAddress> { ip1, ip2 })), new List<String> { "10.0.0.0/16" }); ip1 = IPAddress.parse("10.0.0.0/23").unwrap(); ip2 = IPAddress.parse("10.1.0.0/24").unwrap(); TestIpAddress.Compare(IPAddress.to_string_vec(IPAddress.summarize(new List<IPAddress> { ip1, ip2})), new List<String> { "10.0.0.0/23", "10.1.0.0/24"}); ip1 = IPAddress.parse("10.0.0.0/23").unwrap(); ip2 = IPAddress.parse("10.0.2.0/23").unwrap(); ip3 = IPAddress.parse("10.0.4.0/24").unwrap(); ip4 = IPAddress.parse("10.0.6.0/24").unwrap(); TestIpAddress.Compare(IPAddress.to_string_vec(IPAddress.summarize(new List<IPAddress> { ip1, ip2, ip3, ip4})), new List<String> { "10.0.0.0/22", "10.0.4.0/24", "10.0.6.0/24"}); ip1 = IPAddress.parse("10.0.1.1/24").unwrap(); ip2 = IPAddress.parse("10.0.2.1/24").unwrap(); ip3 = IPAddress.parse("10.0.3.1/24").unwrap(); ip4 = IPAddress.parse("10.0.4.1/24").unwrap(); TestIpAddress.Compare(IPAddress.to_string_vec(IPAddress.summarize(new List<IPAddress> { ip1, ip2, ip3, ip4})), new List<String> { "10.0.1.0/24", "10.0.2.0/23", "10.0.4.0/24"}); ip1 = IPAddress.parse("10.0.1.1/24").unwrap(); ip2 = IPAddress.parse("10.0.2.1/24").unwrap(); ip3 = IPAddress.parse("10.0.3.1/24").unwrap(); ip4 = IPAddress.parse("10.0.4.1/24").unwrap(); TestIpAddress.Compare(IPAddress.to_string_vec(IPAddress.summarize(new List<IPAddress>{ip4, ip3, ip2, ip1 })), new List<String>{"10.0.1.0/24", "10.0.2.0/23", "10.0.4.0/24" }); ip1 = IPAddress.parse("10.0.1.1/24").unwrap(); ip2 = IPAddress.parse("10.10.2.1/24").unwrap(); ip3 = IPAddress.parse("172.16.0.1/24").unwrap(); ip4 = IPAddress.parse("172.16.1.1/24").unwrap(); TestIpAddress.Compare(IPAddress.to_string_vec(IPAddress.summarize(new List<IPAddress> { ip1, ip2, ip3, ip4 })), new List<String> { "10.0.1.0/24", "10.10.2.0/24", "172.16.0.0/23" }); var ips = new List<IPAddress> {IPAddress.parse("10.0.0.12/30").unwrap(), IPAddress.parse("10.0.100.0/24").unwrap()}; TestIpAddress.Compare(IPAddress.to_string_vec(IPAddress.summarize(ips)), new List<String> { "10.0.0.12/30", "10.0.100.0/24" }); ips = new List<IPAddress> { IPAddress.parse("172.16.0.0/31").unwrap(), IPAddress.parse("10.10.2.1/32").unwrap() }; TestIpAddress.Compare(IPAddress.to_string_vec(IPAddress.summarize(ips)), new List<String> { "10.10.2.1/32", "172.16.0.0/31" }); var xips = new List<IPAddress> {IPAddress.parse("172.16.0.0/32").unwrap(), IPAddress.parse("10.10.2.1/32").unwrap()}; TestIpAddress.Compare(IPAddress.to_string_vec(IPAddress.summarize(xips)), new List<String> { "10.10.2.1/32", "172.16.0.0/32" }); } [Fact] void test_classmethod_parse_classful() { foreach (var kp in setup().classful) { var ip = kp.Key; var prefix = kp.Value; var res = IpV4.parse_classful(ip).unwrap(); Assert.Equal(prefix, res.prefix.num); Assert.Equal(string.Format("{0}/{1}", ip, prefix), res.to_string()); } Assert.True(IpV4.parse_classful("192.168.256.257").isErr()); } } }
using Microsoft.AspNetCore.Html; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.AspNetCore.Mvc.Routing; using Microsoft.Extensions.DependencyInjection; using MvcTemplate.Components.Security; using MvcTemplate.Resources; using MvcTemplate.Tests; using NonFactors.Mvc.Grid; using NSubstitute; using System; using System.IO; using System.Linq.Expressions; using System.Text.Encodings.Web; using Xunit; namespace MvcTemplate.Components.Extensions.Tests { public class MvcGridExtensionsTests { private IGridColumnsOf<AllTypesView> columns; private IHtmlGrid<AllTypesView> html; private ViewContext context; public MvcGridExtensionsTests() { IHtmlHelper htmlHelper = HtmlHelperFactory.CreateHtmlHelper(); Grid<AllTypesView> grid = new(Array.Empty<AllTypesView>()); html = new HtmlGrid<AllTypesView>(htmlHelper, grid); columns = new GridColumns<AllTypesView>(grid); context = html.Grid.ViewContext!; } [Fact] public void AddAction_Unauthorized_Empty() { IGridColumn<AllTypesView, IHtmlContent> actual = columns.AddAction("Edit", "fa fa-pencil-alt"); Assert.Empty(actual.ValueFor(new GridRow<AllTypesView>(new AllTypesView(), 0)).ToString()); Assert.Empty(columns); } [Fact] public void AddAction_Authorized_Renders() { AllTypesView view = new(); StringWriter writer = new(); IUrlHelper url = context.HttpContext.RequestServices.GetRequiredService<IUrlHelperFactory>().GetUrlHelper(context); IAuthorization authorization = html.Grid.ViewContext!.HttpContext.RequestServices.GetRequiredService<IAuthorization>(); url.Action(Arg.Any<UrlActionContext>()).Returns("/test"); authorization.IsGrantedFor(Arg.Any<Int64?>(), "//Details").Returns(true); IGridColumn<AllTypesView, IHtmlContent> column = columns.AddAction("Details", "fa fa-info"); column.ValueFor(new GridRow<AllTypesView>(view, 0)).WriteTo(writer, HtmlEncoder.Default); String expected = $"<a class=\"fa fa-info\" href=\"/test\" title=\"{Resource.ForAction("Details")}\"></a>"; String actual = writer.ToString(); Assert.Equal(expected, actual); } [Fact] public void AddAction_NoId_Throws() { IAuthorization authorization = html.Grid.ViewContext!.HttpContext.RequestServices.GetRequiredService<IAuthorization>(); IGridColumnsOf<Object> gridColumns = new GridColumns<Object>(new Grid<Object>(Array.Empty<Object>())); authorization.IsGrantedFor(Arg.Any<Int64?>(), Arg.Any<String>()).Returns(true); gridColumns.Grid.ViewContext = html.Grid.ViewContext; IGridColumn<Object, IHtmlContent> column = gridColumns.AddAction("Delete", "fa fa-times"); String actual = Assert.Throws<Exception>(() => column.ValueFor(new GridRow<Object>(new Object(), 0))).Message; String expected = "Object type does not have an id."; Assert.Equal(expected, actual); } [Fact] public void AddDate_Column() { Expression<Func<AllTypesView, DateTime>> expression = (model) => model.DateTimeField; IGridColumn<AllTypesView, DateTime> actual = columns.AddDate(expression); Assert.Equal("text-center", actual.CssClasses); Assert.Equal("date-time-field", actual.Name); Assert.Equal(expression, actual.Expression); Assert.Equal("{0:d}", actual.Format); Assert.Empty(actual.Title.ToString()); Assert.Single(columns); } [Fact] public void AddDate_Nullable_Column() { Expression<Func<AllTypesView, DateTime?>> expression = (model) => model.NullableDateTimeField; IGridColumn<AllTypesView, DateTime?> actual = columns.AddDate(expression); Assert.Equal("nullable-date-time-field", actual.Name); Assert.Equal("text-center", actual.CssClasses); Assert.Equal(expression, actual.Expression); Assert.Empty(actual.Title.ToString()); Assert.Equal("{0:d}", actual.Format); Assert.Single(columns); } [Fact] public void AddBoolean_Column() { Expression<Func<AllTypesView, Boolean>> expression = (model) => model.BooleanField; IGridColumn<AllTypesView, Boolean> actual = columns.AddBoolean(expression); Assert.Equal("text-center", actual.CssClasses); Assert.Equal(expression, actual.Expression); Assert.Equal("boolean-field", actual.Name); Assert.Empty(actual.Title.ToString()); Assert.Single(columns); } [Fact] public void AddBoolean_True() { GridRow<AllTypesView> row = new(new AllTypesView { BooleanField = true }, 0); IGridColumn<AllTypesView, Boolean> column = columns.AddBoolean(model => model.BooleanField); String? actual = column.ValueFor(row).ToString(); String? expected = Resource.ForString("Yes"); Assert.Equal(expected, actual); } [Fact] public void AddBoolean_False() { GridRow<AllTypesView> row = new(new AllTypesView { BooleanField = false }, 0); IGridColumn<AllTypesView, Boolean> column = columns.AddBoolean(model => model.BooleanField); String? actual = column.ValueFor(row).ToString(); String? expected = Resource.ForString("No"); Assert.Equal(expected, actual); } [Fact] public void AddBoolean_Nullable_Column() { Expression<Func<AllTypesView, Boolean?>> expression = (model) => model.NullableBooleanField; IGridColumn<AllTypesView, Boolean?> actual = columns.AddBoolean(expression); Assert.Equal("nullable-boolean-field", actual.Name); Assert.Equal("text-center", actual.CssClasses); Assert.Equal(expression, actual.Expression); Assert.Empty(actual.Title.ToString()); Assert.Single(columns); } [Fact] public void AddBoolean_Nullable() { GridRow<AllTypesView> row = new(new AllTypesView { NullableBooleanField = null }, 0); IGridColumn<AllTypesView, Boolean?> column = columns.AddBoolean(model => model.NullableBooleanField); Assert.Empty(column.ValueFor(row).ToString()); } [Fact] public void AddBoolean_Nullable_True() { GridRow<AllTypesView> row = new(new AllTypesView { NullableBooleanField = true }, 0); IGridColumn<AllTypesView, Boolean?> column = columns.AddBoolean(model => model.NullableBooleanField); String? actual = column.ValueFor(row).ToString(); String? expected = Resource.ForString("Yes"); Assert.Equal(expected, actual); } [Fact] public void AddBoolean_Nullable_False() { GridRow<AllTypesView> row = new(new AllTypesView { NullableBooleanField = false }, 0); IGridColumn<AllTypesView, Boolean?> column = columns.AddBoolean(model => model.NullableBooleanField); String? actual = column.ValueFor(row).ToString(); String? expected = Resource.ForString("No"); Assert.Equal(expected, actual); } [Fact] public void AddDateTime_Column() { Expression<Func<AllTypesView, DateTime>> expression = (model) => model.DateTimeField; IGridColumn<AllTypesView, DateTime> actual = columns.AddDateTime(expression); Assert.Equal("text-center", actual.CssClasses); Assert.Equal("date-time-field", actual.Name); Assert.Equal(expression, actual.Expression); Assert.Empty(actual.Title.ToString()); Assert.Equal("{0:g}", actual.Format); Assert.Single(columns); } [Fact] public void AddDateTime_Nullable_Column() { Expression<Func<AllTypesView, DateTime?>> expression = (model) => model.NullableDateTimeField; IGridColumn<AllTypesView, DateTime?> actual = columns.AddDateTime(expression); Assert.Equal("nullable-date-time-field", actual.Name); Assert.Equal("text-center", actual.CssClasses); Assert.Equal(expression, actual.Expression); Assert.Empty(actual.Title.ToString()); Assert.Equal("{0:g}", actual.Format); Assert.Single(columns); } [Fact] public void AddProperty_Column() { Expression<Func<AllTypesView, AllTypesView>> expression = (model) => model; IGridColumn<AllTypesView, AllTypesView> actual = columns.AddProperty(expression); Assert.Equal("text-left", actual.CssClasses); Assert.Equal(expression, actual.Expression); Assert.Empty(actual.Title.ToString()); Assert.Empty(actual.Name); Assert.Single(columns); } [Fact] public void AddProperty_SetsColumnName() { Expression<Func<AllTypesView, SByte?>> expression = (model) => model.NullableSByteField; String actual = columns.AddProperty(expression).Name; String expected = "nullable-s-byte-field"; Assert.Equal(expected, actual); } [Fact] public void AddProperty_SetsCssClassForEnum() { AssertCssClassFor(model => model.EnumField, "text-left"); } [Fact] public void AddProperty_SetsCssClassForSByte() { AssertCssClassFor(model => model.SByteField, "text-right"); } [Fact] public void AddProperty_SetsCssClassForByte() { AssertCssClassFor(model => model.ByteField, "text-right"); } [Fact] public void AddProperty_SetsCssClassForInt16() { AssertCssClassFor(model => model.Int16Field, "text-right"); } [Fact] public void AddProperty_SetsCssClassForUInt16() { AssertCssClassFor(model => model.UInt16Field, "text-right"); } [Fact] public void AddProperty_SetsCssClassForInt32() { AssertCssClassFor(model => model.Int32Field, "text-right"); } [Fact] public void AddProperty_SetsCssClassForUInt32() { AssertCssClassFor(model => model.UInt32Field, "text-right"); } [Fact] public void AddProperty_SetsCssClassForInt64() { AssertCssClassFor(model => model.Int64Field, "text-right"); } [Fact] public void AddProperty_SetsCssClassForUInt64() { AssertCssClassFor(model => model.UInt64Field, "text-right"); } [Fact] public void AddProperty_SetsCssClassForSingle() { AssertCssClassFor(model => model.SingleField, "text-right"); } [Fact] public void AddProperty_SetsCssClassForDouble() { AssertCssClassFor(model => model.DoubleField, "text-right"); } [Fact] public void AddProperty_SetsCssClassForDecimal() { AssertCssClassFor(model => model.DecimalField, "text-right"); } [Fact] public void AddProperty_SetsCssClassForBoolean() { AssertCssClassFor(model => model.BooleanField, "text-center"); } [Fact] public void AddProperty_SetsCssClassForDateTime() { AssertCssClassFor(model => model.DateTimeField, "text-center"); } [Fact] public void AddProperty_SetsCssClassForNullableEnum() { AssertCssClassFor(model => model.NullableEnumField, "text-left"); } [Fact] public void AddProperty_SetsCssClassForNullableSByte() { AssertCssClassFor(model => model.NullableSByteField, "text-right"); } [Fact] public void AddProperty_SetsCssClassForNullableByte() { AssertCssClassFor(model => model.NullableByteField, "text-right"); } [Fact] public void AddProperty_SetsCssClassForNullableInt16() { AssertCssClassFor(model => model.NullableInt16Field, "text-right"); } [Fact] public void AddProperty_SetsCssClassForNullableUInt16() { AssertCssClassFor(model => model.NullableUInt16Field, "text-right"); } [Fact] public void AddProperty_SetsCssClassForNullableInt32() { AssertCssClassFor(model => model.NullableInt32Field, "text-right"); } [Fact] public void AddProperty_SetsCssClassForNullableUInt32() { AssertCssClassFor(model => model.NullableUInt32Field, "text-right"); } [Fact] public void AddProperty_SetsCssClassForNullableInt64() { AssertCssClassFor(model => model.NullableInt64Field, "text-right"); } [Fact] public void AddProperty_SetsCssClassForNullableUInt64() { AssertCssClassFor(model => model.NullableUInt64Field, "text-right"); } [Fact] public void AddProperty_SetsCssClassForNullableSingle() { AssertCssClassFor(model => model.NullableSingleField, "text-right"); } [Fact] public void AddProperty_SetsCssClassForNullableDouble() { AssertCssClassFor(model => model.NullableDoubleField, "text-right"); } [Fact] public void AddProperty_SetsCssClassForNullableDecimal() { AssertCssClassFor(model => model.NullableDecimalField, "text-right"); } [Fact] public void AddProperty_SetsCssClassForNullableBoolean() { AssertCssClassFor(model => model.NullableBooleanField, "text-center"); } [Fact] public void AddProperty_SetsCssClassForNullableDateTime() { AssertCssClassFor(model => model.NullableDateTimeField, "text-center"); } [Fact] public void AddProperty_SetsCssClassForOtherTypes() { AssertCssClassFor(model => model.StringField, "text-left"); } [Theory] [InlineData("", "table-hover")] [InlineData(" ", "table-hover")] [InlineData(null, "table-hover")] [InlineData("test", "test table-hover")] [InlineData(" test", "test table-hover")] [InlineData("test ", "test table-hover")] [InlineData(" test ", "test table-hover")] public void ApplyDefaults_Values(String? cssClasses, String expectedClasses) { IGridColumn column = html.Grid.Columns.Add(model => model.ByteField); html.Grid.Attributes["class"] = cssClasses; column.Filter.IsEnabled = null; column.Sort.IsEnabled = null; IGrid actual = html.ApplyDefaults().Grid; Assert.Equal(Resource.ForString("NoDataFound"), actual.EmptyText); Assert.Equal(expectedClasses, html.Grid.Attributes["class"]); Assert.True(column.Filter.IsEnabled); Assert.True(column.Sort.IsEnabled); Assert.NotEmpty(actual.Columns); } private void AssertCssClassFor<TProperty>(Expression<Func<AllTypesView, TProperty>> property, String cssClasses) { IGridColumn<AllTypesView, TProperty> column = columns.AddProperty(property); String actual = column.CssClasses; String expected = cssClasses; Assert.Equal(expected, actual); } } }
/*This code is managed under the Apache v2 license. To see an overview: http://www.tldrlegal.com/license/apache-license-2.0-(apache-2.0) Author: Robert Gawdzik www.github.com/rgawdzik/ THIS CODE HAS NO FORM OF ANY WARRANTY, AND IS CONSIDERED AS-IS. */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Paradox.Game.Classes.Ships; using Paradox.Game.Classes.Levels; using Paradox.Game.Classes.Cameras; using Paradox.Game.Classes.HUD; namespace Paradox.Game.Classes { public class HUDManager { #region Contact Struct struct Contact { public enum ContactState : byte { Friend = 0, Enemy, FriendBase, EnemyBase, Player }; public ContactState State; public Vector2 Position; public Contact(ContactState state, Vector2 position) { State = state; Position = position; } } #endregion #region Variables and Properties private List<Contact> _contactList; private GraphicsDevice _device; private Texture2D[] _radarImages; private SpriteBatch _spriteBatch; private SpriteFont _font; private SpriteFont _HUDFont; private SpriteFont _HUDFontSmall; private string _life; private int _lifeInt; private string _shipPostion; private string _speed; private string _missles; private int _amountFriends; private int _amountEnemies; private TimeSpan _elapsedTimeSeconds; private ShipOverlay _friendOverlay; private ShipOverlay _enemyOverlay; private Texture2D[] _HUDImages; private Texture2D _crosshair; private SpawnerManager _spawnerManager; private bool _respawn; private bool _leavingBattlefield; private TimeSpan _timeLeft; private int _score; private bool _spaceBattle; #endregion #region Constructor public HUDManager(GraphicsDevice device, SpriteBatch spriteBatch, SpawnerManager spawnerManager, SpriteFont font, SpriteFont hudfont, SpriteFont hudfontsmall, Texture2D[] radarImages, ShipOverlay friendOverlay, ShipOverlay enemyOverlay, Texture2D[] hudImages, Texture2D crosshair, Save save) { _font = font; _spriteBatch = spriteBatch; _elapsedTimeSeconds = TimeSpan.Zero; _contactList = new List<Contact>(); _radarImages = radarImages; _device = device; _life = "0"; _speed = ""; _missles = ""; _friendOverlay = friendOverlay; _enemyOverlay = enemyOverlay; _HUDImages = hudImages; _HUDFont = hudfont; _spawnerManager = spawnerManager; _crosshair = crosshair; _spaceBattle = save.Config.SpaceBattle; _spawnerManager.Selected += (object sender, EventArgs args) => { //A ship has been selected, therefore respawn is false. _respawn = false; }; _respawn = false; _HUDFontSmall = hudfontsmall; } #endregion #region Update /// <summary> /// Updates the HUD with it's specified parameters that are important to the user. /// </summary> public void Update(GameTime gameTime, PlayerShip ship, List<Enemy> enemyList, List<Friend> friendList, Starbase friendBase, Starbase enemyBase, int amtEnemyLeft, int amtFriendLeft, Level level, TimeSpan timeLeft) { if (ship.Life <= 0) { //The ship is dead, we must show the respawn menu _respawn = true; } if (_respawn) { _spawnerManager.UpdateManager(); } _life = ship.Life * 10 + "%"; _lifeInt = ship.Life * 10; _shipPostion = "[PlayerPosition] " + ship.ShipPosition.ToString(); _speed = ship._shipSpeed * 100 + " m/s"; GenerateRadar(friendList, enemyList, ship, friendBase, enemyBase); _missles = ship.AmountMissles() + "M"; _amountEnemies = amtEnemyLeft; _amountFriends = amtFriendLeft; _timeLeft = timeLeft; _leavingBattlefield = ship.LeftBattle; _score = level.Score; } #endregion #region Draw public void Draw(Camera camera, List<Friend> friendList, List<Enemy> enemyList, List<Objective> objectiveList) { if (!_respawn) { _spriteBatch.Begin(); foreach (Contact contact in _contactList) { _spriteBatch.Draw(_radarImages[(int)contact.State], new Vector2(_device.Viewport.Width - 140 + contact.Position.X, contact.Position.Y + 120), Color.White); } //Hard coded HUD Overlay Positions, dependant on the screenWidth and height. //Bottom Left Overlay _spriteBatch.Draw(_HUDImages[0], new Vector2(0, _device.Viewport.Height - 50), Color.White); if (_lifeInt > 70) _spriteBatch.DrawString(_HUDFont, _life, new Vector2(0, _device.Viewport.Height - 45), Color.DarkGreen); else if (_lifeInt > 50) _spriteBatch.DrawString(_HUDFont, _life, new Vector2(0, _device.Viewport.Height - 45), Color.Yellow); else _spriteBatch.DrawString(_HUDFont, _life, new Vector2(0, _device.Viewport.Height - 45), Color.Red); _spriteBatch.DrawString(_HUDFont, _missles, new Vector2(110, _device.Viewport.Height - 45), Color.White); //Bottom Right Overlay _spriteBatch.Draw(_HUDImages[1], new Vector2(_device.Viewport.Width - 250, _device.Viewport.Height - 50), Color.White); _spriteBatch.DrawString(_HUDFont, _speed, new Vector2(_device.Viewport.Width - 200, _device.Viewport.Height - 45), Color.White); //Top Left Overlay _spriteBatch.Draw(_HUDImages[2], new Vector2(0, 0), Color.White); _spriteBatch.DrawString(_HUDFont, (int)_timeLeft.TotalMinutes + "m :" + (int)_timeLeft.Seconds + "s", new Vector2(45, 4), Color.White); //Middle Overlay _spriteBatch.Draw(_HUDImages[3], new Vector2(_device.Viewport.Width / 2 - 150, 0), Color.White); _spriteBatch.DrawString(_HUDFont, _amountFriends.ToString(), new Vector2(_device.Viewport.Width / 2 - 90, 0), Color.White); //Draws how many friends. _spriteBatch.DrawString(_HUDFont, _amountEnemies.ToString(), new Vector2(_device.Viewport.Width / 2 + 20, 0), Color.White); //Draws how many enemies. //Cross Hair _spriteBatch.Draw(_crosshair, new Vector2(_device.Viewport.Width / 2 - 18, _device.Viewport.Height / 2 - 110), Color.White); //Objective Drawing: _spriteBatch.DrawString(_HUDFont, "Objectives", new Vector2(0, 70), Color.White); for (int i = 0; i < objectiveList.Count; i++) { if (objectiveList[i].IsDone && !objectiveList[i].IsFailed) _spriteBatch.DrawString(_HUDFontSmall, objectiveList[i].Title, new Vector2(0, 70 + (i * 30 + 40)), Color.Green); else if (objectiveList[i].IsDone) _spriteBatch.DrawString(_HUDFontSmall, objectiveList[i].Title, new Vector2(0, 70 + (i * 30 + 40)), Color.Red); else _spriteBatch.DrawString(_HUDFontSmall, objectiveList[i].Title, new Vector2(0, 70 + (i * 30 + 40)), Color.White); } if (_leavingBattlefield) { _spriteBatch.DrawString(_HUDFont, "You are leaving the Battlefield", new Vector2(_device.Viewport.Width / 2 - 300, _device.Viewport.Height - 300), Color.White); } if (_spaceBattle) { _spriteBatch.DrawString(_HUDFont, "Score: " + _score, new Vector2(_device.Viewport.Width - 200, _device.Viewport.Height - 125), Color.White); } _spriteBatch.End(); RasterizerState rs = new RasterizerState(); rs.CullMode = CullMode.None; _device.RasterizerState = rs; _device.BlendState = BlendState.NonPremultiplied; foreach (Enemy enemy in enemyList) { _enemyOverlay.OverlayDraw(camera, enemy.ShipPosition); } foreach (Friend friend in friendList) { _friendOverlay.OverlayDraw(camera, friend.ShipPosition); } RasterizerState rs2 = new RasterizerState(); rs2.CullMode = CullMode.CullCounterClockwiseFace; _device.RasterizerState = rs2; } else { _spawnerManager.DrawSpawner(_spriteBatch); _spriteBatch.Begin(); //Middle Overlay _spriteBatch.Draw(_HUDImages[3], new Vector2(_device.Viewport.Width / 2 - 150, 0), Color.White); _spriteBatch.DrawString(_HUDFont, _amountFriends.ToString(), new Vector2(_device.Viewport.Width / 2 - 90, 0), Color.White); //Draws how many friends. _spriteBatch.DrawString(_HUDFont, _amountEnemies.ToString(), new Vector2(_device.Viewport.Width / 2 + 20, 0), Color.White); //Draws how many enemies. _spriteBatch.DrawString(_HUDFont, "Choose your ship, press F to spawn", new Vector2(_device.Viewport.Width / 2 - 350, _device.Viewport.Height - 300), Color.White); _spriteBatch.End(); } } #endregion #region Helper Methods public void GenerateRadar(List<Friend> friendList, List<Enemy> enemyList, PlayerShip player, Starbase friendBase, Starbase enemyBase) { _contactList.Clear(); //Adds Enemies to the radar. foreach (Enemy enemy in enemyList) { _contactList.Add(new Contact(Contact.ContactState.Enemy, new Vector2(enemy.ShipPosition.X / 10, enemy.ShipPosition.Z / 10))); } foreach (Friend friend in friendList) { _contactList.Add(new Contact(Contact.ContactState.Friend, new Vector2(friend.ShipPosition.X / 10, friend.ShipPosition.Z / 10))); } //Adds PlayerShip to the radar. _contactList.Add(new Contact(Contact.ContactState.Friend, new Vector2(player.ShipPosition.X / 10, player.ShipPosition.Z / 10))); //Add star bases to the radar _contactList.Add(new Contact(Contact.ContactState.FriendBase, new Vector2(friendBase.Position.X / 10, friendBase.Position.Z / 10))); _contactList.Add(new Contact(Contact.ContactState.EnemyBase, new Vector2(enemyBase.Position.X / 10, enemyBase.Position.Z / 10))); } #endregion } }
using System; using System.IO; using System.Text; using System.Collections.Generic; namespace Platform.IO { /// <summary> /// Provides extension methods and static utility methods for <see cref="Stream"/> objects. /// </summary> public static class StreamUtils { /// <summary> /// Writes the given buffer to the stream /// </summary> /// <param name="s">The stream to write to</param> /// <param name="buffer">The buffer to write</param> public static void WriteAll(this Stream s, byte[] buffer) { s.Write(buffer, 0, buffer.Length); } /// <summary> /// Gets an <see cref="IEnumerator{T}"/> for the given stream /// </summary> /// <param name="s">The stream</param> /// <returns>An <see cref="IEnumerator{T}"/></returns> public static IEnumerator<byte> GetEnumerator(this Stream s) { return s.ToEnumerable().GetEnumerator(); } /// <summary> /// Converts the given stream into an <see cref="IEnumerable{T}"/> /// </summary> /// <param name="s">The stream</param> /// <returns>An <see cref="IEnumerable{T}"/></returns> public static IEnumerable<byte> ToEnumerable(this Stream s) { int x; for (;;) { x = s.ReadByte(); if (x == -1) { break; } yield return (byte)x; } } [ThreadStatic] private static byte[] dynamicBlockBuffer; /// <summary> /// Reads a block from a stream while the given predicate validates. /// </summary> /// <param name="stream">The stream to read from</param> /// <param name="keepGoing"> /// A predicate that will be passed the current byte and evaluate to /// True the method should continue reading from the stream /// </param> /// <returns> /// A <see cref="Pair{A,B}"/> containing an array of bytes containing the block read /// and the total length of valid data read. The array may be larger than the length /// of valid data read. All elements in the array after the valid data will be 0. /// Use <see cref="Array.Resize{T}"/> to resize the array to the exact length if necessary. /// </returns> public static Pair<byte[], int> ReadDynamicBlock(this Stream stream, Predicate<byte> keepGoing) { int x; int length; byte[] buffer; if (dynamicBlockBuffer == null) { dynamicBlockBuffer = new byte[256]; } buffer = dynamicBlockBuffer; length = 0; for (;;) { x = stream.ReadByte(); if (x == -1 || !keepGoing((byte)x)) { break; } if (length == buffer.Length) { byte[] newBuffer; newBuffer = new byte[buffer.Length * 2]; Array.Copy(buffer, newBuffer, buffer.Length); buffer = newBuffer; } buffer[length++] = (byte)x; } return new Pair<byte[], int>(buffer, length); } [ThreadStatic] private static char[] t_CharBuffer = null; /// <summary> /// Reads a textual line from a stream without reading ahead and consuming more /// bytes than necessary to read the line. /// </summary> /// <remarks> /// <para> /// This method is intended to be use where a stream is used with both binary /// data and encoded text. /// </para> /// <para> /// Because decoding without buffering requires detecting end of line characters /// reliabily without buffering, this method only supports the UTF-8 and ASCII /// encodings. /// </para> /// <para> /// This method uses TLS buffers and is thread safe. /// </para> /// </remarks> /// <param name="stream"> /// The stream to read the textual line from. /// </param> /// <param name="encoding"> /// The encoding to use. /// Only <see cref="Encoding.UTF8"/> and <see cref="Encoding.ASCII"/> are supported. /// </param> /// <param name="maxBytes"> /// The maximum number of bytes to read before throwing an <see cref="OverflowException"/>. /// If maxbytes is encountered, the stream is left in an unstable state for reading /// text. /// </param> /// <returns></returns> public static string ReadLineUnbuffered(this Stream stream, Encoding encoding, int maxBytes) { var lastByte = -1; var byteCount = 0; if (encoding != Encoding.UTF8 && encoding != Encoding.ASCII) { throw new ArgumentException(encoding.ToString(), "encoding"); } var retval = stream.ReadDynamicBlock(delegate(byte x) { if (x == '\n' && lastByte == '\r') { return false; } lastByte = x; byteCount++; if (byteCount > maxBytes) { throw new OverflowException(); } return true; }); var maxCharCount = encoding.GetMaxCharCount(retval.Right); if (t_CharBuffer == null || (t_CharBuffer != null && maxCharCount > t_CharBuffer.Length)) { int newLength = t_CharBuffer == null ? 64 : t_CharBuffer.Length; while (newLength < maxCharCount) { newLength *= 2; } Array.Resize(ref t_CharBuffer, newLength); } var charCount = Encoding.UTF8.GetChars(retval.Left, 0, lastByte == '\r' ? retval.Right - 1 : retval.Right, t_CharBuffer, 0); return new string(t_CharBuffer, 0, charCount); } public static void CopyTo(this Stream stream, Stream destination) { var buffer = new byte[4096]; while (true) { var read = stream.Read(buffer, 0, buffer.Length); if (read == 0) { break; } destination.Write(buffer, 0, read); } } } }
// Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.IO; using System.Linq; using Microsoft.DotNet.Cli.Utils; using Microsoft.DotNet.PlatformAbstractions; namespace Microsoft.DotNet.Tools.Common { public static class PathUtility { public static bool IsPlaceholderFile(string path) { return string.Equals(Path.GetFileName(path), "_._", StringComparison.Ordinal); } public static bool IsChildOfDirectory(string dir, string candidate) { if (dir == null) { throw new ArgumentNullException(nameof(dir)); } if (candidate == null) { throw new ArgumentNullException(nameof(candidate)); } dir = Path.GetFullPath(dir); dir = EnsureTrailingSlash(dir); candidate = Path.GetFullPath(candidate); return candidate.StartsWith(dir, StringComparison.OrdinalIgnoreCase); } public static string EnsureTrailingSlash(string path) { return EnsureTrailingCharacter(path, Path.DirectorySeparatorChar); } public static string EnsureTrailingForwardSlash(string path) { return EnsureTrailingCharacter(path, '/'); } private static string EnsureTrailingCharacter(string path, char trailingCharacter) { if (path == null) { throw new ArgumentNullException(nameof(path)); } // if the path is empty, we want to return the original string instead of a single trailing character. if (path.Length == 0 || path[path.Length - 1] == trailingCharacter) { return path; } return path + trailingCharacter; } public static string EnsureNoTrailingDirectorySeparator(string path) { if (!string.IsNullOrEmpty(path)) { char lastChar = path[path.Length - 1]; if (lastChar == Path.DirectorySeparatorChar) { path = path.Substring(0, path.Length - 1); } } return path; } public static void EnsureParentDirectoryExists(string filePath) { string directory = Path.GetDirectoryName(filePath); EnsureDirectoryExists(directory); } public static void EnsureDirectoryExists(string directoryPath) { if (!Directory.Exists(directoryPath)) { Directory.CreateDirectory(directoryPath); } } public static bool TryDeleteDirectory(string directoryPath) { try { Directory.Delete(directoryPath, true); return true; } catch { return false; } } /// <summary> /// Returns childItem relative to directory, with Path.DirectorySeparatorChar as separator /// </summary> public static string GetRelativePath(DirectoryInfo directory, FileSystemInfo childItem) { var path1 = EnsureTrailingSlash(directory.FullName); var path2 = childItem.FullName; return GetRelativePath(path1, path2, Path.DirectorySeparatorChar, true); } /// <summary> /// Returns path2 relative to path1, with Path.DirectorySeparatorChar as separator /// </summary> public static string GetRelativePath(string path1, string path2) { if (!Path.IsPathRooted(path1) || !Path.IsPathRooted(path2)) { throw new ArgumentException("both paths need to be rooted/full path"); } return GetRelativePath(path1, path2, Path.DirectorySeparatorChar, true); } /// <summary> /// Returns path2 relative to path1, with Path.DirectorySeparatorChar as separator but ignoring directory /// traversals. /// </summary> public static string GetRelativePathIgnoringDirectoryTraversals(string path1, string path2) { return GetRelativePath(path1, path2, Path.DirectorySeparatorChar, false); } /// <summary> /// Returns path2 relative to path1, with given path separator /// </summary> public static string GetRelativePath(string path1, string path2, char separator, bool includeDirectoryTraversals) { if (string.IsNullOrEmpty(path1)) { throw new ArgumentException("Path must have a value", nameof(path1)); } if (string.IsNullOrEmpty(path2)) { throw new ArgumentException("Path must have a value", nameof(path2)); } StringComparison compare; if (RuntimeEnvironment.OperatingSystemPlatform == Platform.Windows) { compare = StringComparison.OrdinalIgnoreCase; // check if paths are on the same volume if (!string.Equals(Path.GetPathRoot(path1), Path.GetPathRoot(path2), compare)) { // on different volumes, "relative" path is just path2 return path2; } } else { compare = StringComparison.Ordinal; } var index = 0; var path1Segments = path1.Split(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar); var path2Segments = path2.Split(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar); // if path1 does not end with / it is assumed the end is not a directory // we will assume that is isn't a directory by ignoring the last split var len1 = path1Segments.Length - 1; var len2 = path2Segments.Length; // find largest common absolute path between both paths var min = Math.Min(len1, len2); while (min > index) { if (!string.Equals(path1Segments[index], path2Segments[index], compare)) { break; } // Handle scenarios where folder and file have same name (only if os supports same name for file and directory) // e.g. /file/name /file/name/app else if ((len1 == index && len2 > index + 1) || (len1 > index && len2 == index + 1)) { break; } ++index; } var path = ""; // check if path2 ends with a non-directory separator and if path1 has the same non-directory at the end if (len1 + 1 == len2 && !string.IsNullOrEmpty(path1Segments[index]) && string.Equals(path1Segments[index], path2Segments[index], compare)) { return path; } if (includeDirectoryTraversals) { for (var i = index; len1 > i; ++i) { path += ".." + separator; } } for (var i = index; len2 - 1 > i; ++i) { path += path2Segments[i] + separator; } // if path2 doesn't end with an empty string it means it ended with a non-directory name, so we add it back if (!string.IsNullOrEmpty(path2Segments[len2 - 1])) { path += path2Segments[len2 - 1]; } return path; } public static string GetAbsolutePath(string basePath, string relativePath) { if (basePath == null) { throw new ArgumentNullException(nameof(basePath)); } if (relativePath == null) { throw new ArgumentNullException(nameof(relativePath)); } Uri resultUri = new Uri(new Uri(basePath), new Uri(relativePath, UriKind.Relative)); return resultUri.LocalPath; } public static string GetDirectoryName(string path) { path = path.TrimEnd(Path.DirectorySeparatorChar); return path.Substring(Path.GetDirectoryName(path).Length).Trim(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar); } public static string GetPathWithForwardSlashes(string path) { return path.Replace('\\', '/'); } public static string GetPathWithBackSlashes(string path) { return path.Replace('/', '\\'); } public static string GetPathWithDirectorySeparator(string path) { if (Path.DirectorySeparatorChar == '/') { return GetPathWithForwardSlashes(path); } else { return GetPathWithBackSlashes(path); } } public static string RemoveExtraPathSeparators(string path) { if (string.IsNullOrEmpty(path)) { return path; } var components = path.Split(Path.DirectorySeparatorChar); var result = string.Empty; foreach (var component in components) { if (string.IsNullOrEmpty(component)) { continue; } if (string.IsNullOrEmpty(result)) { result = component; // On Windows, manually append a separator for drive references because Path.Combine won't do so if (result.EndsWith(":") && RuntimeEnvironment.OperatingSystemPlatform == Platform.Windows) { result += Path.DirectorySeparatorChar; } } else { result = Path.Combine(result, component); } } if (path[path.Length-1] == Path.DirectorySeparatorChar) { result += Path.DirectorySeparatorChar; } return result; } public static bool HasExtension(this string filePath, string extension) { var comparison = StringComparison.Ordinal; if (RuntimeEnvironment.OperatingSystemPlatform == Platform.Windows) { comparison = StringComparison.OrdinalIgnoreCase; } return Path.GetExtension(filePath).Equals(extension, comparison); } /// <summary> /// Gets the fully-qualified path without failing if the /// path is empty. /// </summary> public static string GetFullPath(string path) { if (string.IsNullOrWhiteSpace(path)) { return path; } return Path.GetFullPath(path); } public static void EnsureAllPathsExist( IReadOnlyCollection<string> paths, string pathDoesNotExistLocalizedFormatString, bool allowDirectories = false) { var notExisting = new List<string>(); foreach (var p in paths) { if (!File.Exists(p) && (!allowDirectories || !Directory.Exists(p))) { notExisting.Add(p); } } if (notExisting.Count > 0) { throw new GracefulException( string.Join( Environment.NewLine, notExisting.Select(p => string.Format(pathDoesNotExistLocalizedFormatString, p)))); } } public static bool IsDirectory(this string path) => File.GetAttributes(path).HasFlag(FileAttributes.Directory); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.Win32.SafeHandles; using System.Collections.Generic; using System.Net.Sockets; using System.Threading; namespace System.Net.NetworkInformation { public class NetworkChange { public static event NetworkAvailabilityChangedEventHandler NetworkAvailabilityChanged { add { AvailabilityChangeListener.Start(value); } remove { AvailabilityChangeListener.Stop(value); } } public static event NetworkAddressChangedEventHandler NetworkAddressChanged { add { AddressChangeListener.Start(value); } remove { AddressChangeListener.Stop(value); } } internal static bool CanListenForNetworkChanges { get { return true; } } internal static class AvailabilityChangeListener { private readonly static object s_syncObject = new object(); private readonly static Dictionary<NetworkAvailabilityChangedEventHandler, ExecutionContext> s_availabilityCallerArray = new Dictionary<NetworkAvailabilityChangedEventHandler, ExecutionContext>(); private readonly static NetworkAddressChangedEventHandler s_addressChange = ChangedAddress; private static volatile bool s_isAvailable = false; private readonly static ContextCallback s_RunHandlerCallback = new ContextCallback(RunHandlerCallback); private static void RunHandlerCallback(object state) { ((NetworkAvailabilityChangedEventHandler)state)(null, new NetworkAvailabilityEventArgs(s_isAvailable)); } private static void ChangedAddress(object sender, EventArgs eventArgs) { lock (s_syncObject) { bool isAvailableNow = SystemNetworkInterface.InternalGetIsNetworkAvailable(); if (isAvailableNow != s_isAvailable) { s_isAvailable = isAvailableNow; var s_copy = new Dictionary<NetworkAvailabilityChangedEventHandler, ExecutionContext>(s_availabilityCallerArray); foreach (var handler in s_copy.Keys) { ExecutionContext context = s_copy[handler]; if (context == null) { handler(null, new NetworkAvailabilityEventArgs(s_isAvailable)); } else { ExecutionContext.Run(context, s_RunHandlerCallback, handler); } } } } } internal static void Start(NetworkAvailabilityChangedEventHandler caller) { lock (s_syncObject) { if (s_availabilityCallerArray.Count == 0) { s_isAvailable = NetworkInterface.GetIsNetworkAvailable(); AddressChangeListener.UnsafeStart(s_addressChange); } if ((caller != null) && (!s_availabilityCallerArray.ContainsKey(caller))) { s_availabilityCallerArray.Add(caller, ExecutionContext.Capture()); } } } internal static void Stop(NetworkAvailabilityChangedEventHandler caller) { lock (s_syncObject) { s_availabilityCallerArray.Remove(caller); if (s_availabilityCallerArray.Count == 0) { AddressChangeListener.Stop(s_addressChange); } } } } // Helper class for detecting address change events. internal unsafe static class AddressChangeListener { private readonly static Dictionary<NetworkAddressChangedEventHandler, ExecutionContext> s_callerArray = new Dictionary<NetworkAddressChangedEventHandler, ExecutionContext>(); private readonly static ContextCallback s_runHandlerCallback = new ContextCallback(RunHandlerCallback); private static RegisteredWaitHandle s_registeredWait; // Need to keep the reference so it isn't GC'd before the native call executes. private static bool s_isListening = false; private static bool s_isPending = false; private static SafeCloseSocketAndEvent s_ipv4Socket = null; private static SafeCloseSocketAndEvent s_ipv6Socket = null; private static WaitHandle s_ipv4WaitHandle = null; private static WaitHandle s_ipv6WaitHandle = null; // Callback fired when an address change occurs. private static void AddressChangedCallback(object stateObject, bool signaled) { lock (s_callerArray) { // The listener was canceled, which would only happen if we aren't listening for more events. s_isPending = false; if (!s_isListening) { return; } s_isListening = false; // Need to copy the array so the callback can call start and stop var copy = new Dictionary<NetworkAddressChangedEventHandler, ExecutionContext>(s_callerArray); try { //wait for the next address change StartHelper(null, false, (StartIPOptions)stateObject); } catch (NetworkInformationException nie) { if (NetEventSource.Log.IsEnabled()) { NetEventSource.Exception(NetEventSource.ComponentType.NetworkInformation, "AddressChangeListener", "AddressChangedCallback", nie); } } foreach (var handler in copy.Keys) { ExecutionContext context = copy[handler]; if (context == null) { handler(null, EventArgs.Empty); } else { ExecutionContext.Run(context, s_runHandlerCallback, handler); } } } } private static void RunHandlerCallback(object state) { ((NetworkAddressChangedEventHandler)state)(null, EventArgs.Empty); } internal static void Start(NetworkAddressChangedEventHandler caller) { StartHelper(caller, true, StartIPOptions.Both); } internal static void UnsafeStart(NetworkAddressChangedEventHandler caller) { StartHelper(caller, false, StartIPOptions.Both); } private static void StartHelper(NetworkAddressChangedEventHandler caller, bool captureContext, StartIPOptions startIPOptions) { lock (s_callerArray) { // Setup changedEvent and native overlapped struct. if (s_ipv4Socket == null) { int blocking; // Sockets will be initialized by the call to OSSupportsIP*. if (Socket.OSSupportsIPv4) { blocking = -1; s_ipv4Socket = SafeCloseSocketAndEvent.CreateWSASocketWithEvent(AddressFamily.InterNetwork, SocketType.Dgram, (ProtocolType)0, true, false); Interop.Winsock.ioctlsocket(s_ipv4Socket, Interop.Winsock.IoctlSocketConstants.FIONBIO, ref blocking); s_ipv4WaitHandle = s_ipv4Socket.GetEventHandle(); } if (Socket.OSSupportsIPv6) { blocking = -1; s_ipv6Socket = SafeCloseSocketAndEvent.CreateWSASocketWithEvent(AddressFamily.InterNetworkV6, SocketType.Dgram, (ProtocolType)0, true, false); Interop.Winsock.ioctlsocket(s_ipv6Socket, Interop.Winsock.IoctlSocketConstants.FIONBIO, ref blocking); s_ipv6WaitHandle = s_ipv6Socket.GetEventHandle(); } } if ((caller != null) && (!s_callerArray.ContainsKey(caller))) { s_callerArray.Add(caller, captureContext ? ExecutionContext.Capture() : null); } if (s_isListening || s_callerArray.Count == 0) { return; } if (!s_isPending) { int length; SocketError errorCode; if (Socket.OSSupportsIPv4 && (startIPOptions & StartIPOptions.StartIPv4) != 0) { s_registeredWait = ThreadPool.RegisterWaitForSingleObject( s_ipv4WaitHandle, new WaitOrTimerCallback(AddressChangedCallback), StartIPOptions.StartIPv4, -1, true); errorCode = Interop.Winsock.WSAIoctl_Blocking( s_ipv4Socket.DangerousGetHandle(), (int)IOControlCode.AddressListChange, null, 0, null, 0, out length, SafeNativeOverlapped.Zero, IntPtr.Zero); if (errorCode != SocketError.Success) { NetworkInformationException exception = new NetworkInformationException(); if (exception.ErrorCode != (uint)SocketError.WouldBlock) { throw exception; } } SafeWaitHandle s_ipv4SocketGetEventHandleSafeWaitHandle = s_ipv4Socket.GetEventHandle().GetSafeWaitHandle(); errorCode = Interop.Winsock.WSAEventSelect( s_ipv4Socket, s_ipv4SocketGetEventHandleSafeWaitHandle, Interop.Winsock.AsyncEventBits.FdAddressListChange); if (errorCode != SocketError.Success) { throw new NetworkInformationException(); } } if (Socket.OSSupportsIPv6 && (startIPOptions & StartIPOptions.StartIPv6) != 0) { s_registeredWait = ThreadPool.RegisterWaitForSingleObject( s_ipv6WaitHandle, new WaitOrTimerCallback(AddressChangedCallback), StartIPOptions.StartIPv6, -1, true); errorCode = Interop.Winsock.WSAIoctl_Blocking( s_ipv6Socket.DangerousGetHandle(), (int)IOControlCode.AddressListChange, null, 0, null, 0, out length, SafeNativeOverlapped.Zero, IntPtr.Zero); if (errorCode != SocketError.Success) { NetworkInformationException exception = new NetworkInformationException(); if (exception.ErrorCode != (uint)SocketError.WouldBlock) { throw exception; } } SafeWaitHandle s_ipv6SocketGetEventHandleSafeWaitHandle = s_ipv6Socket.GetEventHandle().GetSafeWaitHandle(); errorCode = Interop.Winsock.WSAEventSelect( s_ipv6Socket, s_ipv6SocketGetEventHandleSafeWaitHandle, Interop.Winsock.AsyncEventBits.FdAddressListChange); if (errorCode != SocketError.Success) { throw new NetworkInformationException(); } } } s_isListening = true; s_isPending = true; } } internal static void Stop(NetworkAddressChangedEventHandler caller) { lock (s_callerArray) { s_callerArray.Remove(caller); if (s_callerArray.Count == 0 && s_isListening) { s_isListening = false; } } } } } }
/* **************************************************************************** * * 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; using Microsoft.Scripting.Utils; using IronPython.Runtime; using IronPython.Runtime.Operations; namespace IronPython.Compiler { public delegate object CallTarget0(); internal static class PythonCallTargets { public static object OriginalCallTargetN(PythonFunction function, params object[] args) { function.func_code.LazyCompileFirstTarget(function); return ((Func<PythonFunction, object[], object>)function.func_code.Target)(function, args); } #region Generated Python Lazy Call Targets // *** BEGIN GENERATED CODE *** // generated by function: gen_lazy_call_targets from: generate_calls.py public static object OriginalCallTarget0(PythonFunction function) { function.func_code.LazyCompileFirstTarget(function); return ((Func<PythonFunction, object>)function.func_code.Target)(function); } public static object OriginalCallTarget1(PythonFunction function, object arg0) { function.func_code.LazyCompileFirstTarget(function); return ((Func<PythonFunction, object, object>)function.func_code.Target)(function, arg0); } public static object OriginalCallTarget2(PythonFunction function, object arg0, object arg1) { function.func_code.LazyCompileFirstTarget(function); return ((Func<PythonFunction, object, object, object>)function.func_code.Target)(function, arg0, arg1); } public static object OriginalCallTarget3(PythonFunction function, object arg0, object arg1, object arg2) { function.func_code.LazyCompileFirstTarget(function); return ((Func<PythonFunction, object, object, object, object>)function.func_code.Target)(function, arg0, arg1, arg2); } public static object OriginalCallTarget4(PythonFunction function, object arg0, object arg1, object arg2, object arg3) { function.func_code.LazyCompileFirstTarget(function); return ((Func<PythonFunction, object, object, object, object, object>)function.func_code.Target)(function, arg0, arg1, arg2, arg3); } public static object OriginalCallTarget5(PythonFunction function, object arg0, object arg1, object arg2, object arg3, object arg4) { function.func_code.LazyCompileFirstTarget(function); return ((Func<PythonFunction, object, object, object, object, object, object>)function.func_code.Target)(function, arg0, arg1, arg2, arg3, arg4); } public static object OriginalCallTarget6(PythonFunction function, object arg0, object arg1, object arg2, object arg3, object arg4, object arg5) { function.func_code.LazyCompileFirstTarget(function); return ((Func<PythonFunction, object, object, object, object, object, object, object>)function.func_code.Target)(function, arg0, arg1, arg2, arg3, arg4, arg5); } public static object OriginalCallTarget7(PythonFunction function, object arg0, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6) { function.func_code.LazyCompileFirstTarget(function); return ((Func<PythonFunction, object, object, object, object, object, object, object, object>)function.func_code.Target)(function, arg0, arg1, arg2, arg3, arg4, arg5, arg6); } public static object OriginalCallTarget8(PythonFunction function, object arg0, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7) { function.func_code.LazyCompileFirstTarget(function); return ((Func<PythonFunction, object, object, object, object, object, object, object, object, object>)function.func_code.Target)(function, arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7); } public static object OriginalCallTarget9(PythonFunction function, object arg0, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8) { function.func_code.LazyCompileFirstTarget(function); return ((Func<PythonFunction, object, object, object, object, object, object, object, object, object, object>)function.func_code.Target)(function, arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8); } public static object OriginalCallTarget10(PythonFunction function, object arg0, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8, object arg9) { function.func_code.LazyCompileFirstTarget(function); return ((Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object>)function.func_code.Target)(function, arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9); } public static object OriginalCallTarget11(PythonFunction function, object arg0, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8, object arg9, object arg10) { function.func_code.LazyCompileFirstTarget(function); return ((Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object, object>)function.func_code.Target)(function, arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10); } public static object OriginalCallTarget12(PythonFunction function, object arg0, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8, object arg9, object arg10, object arg11) { function.func_code.LazyCompileFirstTarget(function); return ((Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object, object, object>)function.func_code.Target)(function, arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11); } public static object OriginalCallTarget13(PythonFunction function, object arg0, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8, object arg9, object arg10, object arg11, object arg12) { function.func_code.LazyCompileFirstTarget(function); return ((Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object, object, object, object>)function.func_code.Target)(function, arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12); } public static object OriginalCallTarget14(PythonFunction function, object arg0, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8, object arg9, object arg10, object arg11, object arg12, object arg13) { function.func_code.LazyCompileFirstTarget(function); return ((Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object, object, object, object, object>)function.func_code.Target)(function, arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13); } public static object OriginalCallTarget15(PythonFunction function, object arg0, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8, object arg9, object arg10, object arg11, object arg12, object arg13, object arg14) { function.func_code.LazyCompileFirstTarget(function); return ((Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object, object, object, object, object, object>)function.func_code.Target)(function, arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14); } // *** END GENERATED CODE *** #endregion public const int MaxArgs = 15; internal static Type GetPythonTargetType(bool wrapper, int parameters, out Delegate originalTarget) { if (!wrapper) { switch (parameters) { #region Generated Python Call Target Switch // *** BEGIN GENERATED CODE *** // generated by function: gen_python_switch from: generate_calls.py case 0: originalTarget = (Func<PythonFunction, object>)OriginalCallTarget0; return typeof(Func<PythonFunction, object>); case 1: originalTarget = (Func<PythonFunction, object, object>)OriginalCallTarget1; return typeof(Func<PythonFunction, object, object>); case 2: originalTarget = (Func<PythonFunction, object, object, object>)OriginalCallTarget2; return typeof(Func<PythonFunction, object, object, object>); case 3: originalTarget = (Func<PythonFunction, object, object, object, object>)OriginalCallTarget3; return typeof(Func<PythonFunction, object, object, object, object>); case 4: originalTarget = (Func<PythonFunction, object, object, object, object, object>)OriginalCallTarget4; return typeof(Func<PythonFunction, object, object, object, object, object>); case 5: originalTarget = (Func<PythonFunction, object, object, object, object, object, object>)OriginalCallTarget5; return typeof(Func<PythonFunction, object, object, object, object, object, object>); case 6: originalTarget = (Func<PythonFunction, object, object, object, object, object, object, object>)OriginalCallTarget6; return typeof(Func<PythonFunction, object, object, object, object, object, object, object>); case 7: originalTarget = (Func<PythonFunction, object, object, object, object, object, object, object, object>)OriginalCallTarget7; return typeof(Func<PythonFunction, object, object, object, object, object, object, object, object>); case 8: originalTarget = (Func<PythonFunction, object, object, object, object, object, object, object, object, object>)OriginalCallTarget8; return typeof(Func<PythonFunction, object, object, object, object, object, object, object, object, object>); case 9: originalTarget = (Func<PythonFunction, object, object, object, object, object, object, object, object, object, object>)OriginalCallTarget9; return typeof(Func<PythonFunction, object, object, object, object, object, object, object, object, object, object>); case 10: originalTarget = (Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object>)OriginalCallTarget10; return typeof(Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object>); case 11: originalTarget = (Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object, object>)OriginalCallTarget11; return typeof(Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object, object>); case 12: originalTarget = (Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object, object, object>)OriginalCallTarget12; return typeof(Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object, object, object>); case 13: originalTarget = (Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object, object, object, object>)OriginalCallTarget13; return typeof(Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object, object, object, object>); case 14: originalTarget = (Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object, object, object, object, object>)OriginalCallTarget14; return typeof(Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object, object, object, object, object>); case 15: originalTarget = (Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object, object, object, object, object, object>)OriginalCallTarget15; return typeof(Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object, object, object, object, object, object>); // *** END GENERATED CODE *** #endregion } } originalTarget = (Func<PythonFunction, object[], object>)OriginalCallTargetN; return typeof(Func<PythonFunction, object[], object>); } } internal class PythonFunctionRecursionCheckN { private readonly Func<PythonFunction, object[], object> _target; public PythonFunctionRecursionCheckN(Func<PythonFunction, object[], object> target) { _target = target; } public object CallTarget(PythonFunction/*!*/ function, object[] args) { PythonOps.FunctionPushFrame((PythonContext)function.Context.LanguageContext); try { return _target(function, args); } finally { PythonOps.FunctionPopFrame(); } } } #region Generated Python Recursion Enforcement // *** BEGIN GENERATED CODE *** // generated by function: gen_recursion_checks from: generate_calls.py internal class PythonFunctionRecursionCheck0 { private readonly Func<PythonFunction, object> _target; public PythonFunctionRecursionCheck0(Func<PythonFunction, object> target) { _target = target; } public object CallTarget(PythonFunction/*!*/ function) { PythonOps.FunctionPushFrame((PythonContext)function.Context.LanguageContext); try { return _target(function); } finally { PythonOps.FunctionPopFrame(); } } } internal class PythonFunctionRecursionCheck1 { private readonly Func<PythonFunction, object, object> _target; public PythonFunctionRecursionCheck1(Func<PythonFunction, object, object> target) { _target = target; } public object CallTarget(PythonFunction/*!*/ function, object arg0) { PythonOps.FunctionPushFrame((PythonContext)function.Context.LanguageContext); try { return _target(function, arg0); } finally { PythonOps.FunctionPopFrame(); } } } internal class PythonFunctionRecursionCheck2 { private readonly Func<PythonFunction, object, object, object> _target; public PythonFunctionRecursionCheck2(Func<PythonFunction, object, object, object> target) { _target = target; } public object CallTarget(PythonFunction/*!*/ function, object arg0, object arg1) { PythonOps.FunctionPushFrame((PythonContext)function.Context.LanguageContext); try { return _target(function, arg0, arg1); } finally { PythonOps.FunctionPopFrame(); } } } internal class PythonFunctionRecursionCheck3 { private readonly Func<PythonFunction, object, object, object, object> _target; public PythonFunctionRecursionCheck3(Func<PythonFunction, object, object, object, object> target) { _target = target; } public object CallTarget(PythonFunction/*!*/ function, object arg0, object arg1, object arg2) { PythonOps.FunctionPushFrame((PythonContext)function.Context.LanguageContext); try { return _target(function, arg0, arg1, arg2); } finally { PythonOps.FunctionPopFrame(); } } } internal class PythonFunctionRecursionCheck4 { private readonly Func<PythonFunction, object, object, object, object, object> _target; public PythonFunctionRecursionCheck4(Func<PythonFunction, object, object, object, object, object> target) { _target = target; } public object CallTarget(PythonFunction/*!*/ function, object arg0, object arg1, object arg2, object arg3) { PythonOps.FunctionPushFrame((PythonContext)function.Context.LanguageContext); try { return _target(function, arg0, arg1, arg2, arg3); } finally { PythonOps.FunctionPopFrame(); } } } internal class PythonFunctionRecursionCheck5 { private readonly Func<PythonFunction, object, object, object, object, object, object> _target; public PythonFunctionRecursionCheck5(Func<PythonFunction, object, object, object, object, object, object> target) { _target = target; } public object CallTarget(PythonFunction/*!*/ function, object arg0, object arg1, object arg2, object arg3, object arg4) { PythonOps.FunctionPushFrame((PythonContext)function.Context.LanguageContext); try { return _target(function, arg0, arg1, arg2, arg3, arg4); } finally { PythonOps.FunctionPopFrame(); } } } internal class PythonFunctionRecursionCheck6 { private readonly Func<PythonFunction, object, object, object, object, object, object, object> _target; public PythonFunctionRecursionCheck6(Func<PythonFunction, object, object, object, object, object, object, object> target) { _target = target; } public object CallTarget(PythonFunction/*!*/ function, object arg0, object arg1, object arg2, object arg3, object arg4, object arg5) { PythonOps.FunctionPushFrame((PythonContext)function.Context.LanguageContext); try { return _target(function, arg0, arg1, arg2, arg3, arg4, arg5); } finally { PythonOps.FunctionPopFrame(); } } } internal class PythonFunctionRecursionCheck7 { private readonly Func<PythonFunction, object, object, object, object, object, object, object, object> _target; public PythonFunctionRecursionCheck7(Func<PythonFunction, object, object, object, object, object, object, object, object> target) { _target = target; } public object CallTarget(PythonFunction/*!*/ function, object arg0, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6) { PythonOps.FunctionPushFrame((PythonContext)function.Context.LanguageContext); try { return _target(function, arg0, arg1, arg2, arg3, arg4, arg5, arg6); } finally { PythonOps.FunctionPopFrame(); } } } internal class PythonFunctionRecursionCheck8 { private readonly Func<PythonFunction, object, object, object, object, object, object, object, object, object> _target; public PythonFunctionRecursionCheck8(Func<PythonFunction, object, object, object, object, object, object, object, object, object> target) { _target = target; } public object CallTarget(PythonFunction/*!*/ function, object arg0, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7) { PythonOps.FunctionPushFrame((PythonContext)function.Context.LanguageContext); try { return _target(function, arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7); } finally { PythonOps.FunctionPopFrame(); } } } internal class PythonFunctionRecursionCheck9 { private readonly Func<PythonFunction, object, object, object, object, object, object, object, object, object, object> _target; public PythonFunctionRecursionCheck9(Func<PythonFunction, object, object, object, object, object, object, object, object, object, object> target) { _target = target; } public object CallTarget(PythonFunction/*!*/ function, object arg0, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8) { PythonOps.FunctionPushFrame((PythonContext)function.Context.LanguageContext); try { return _target(function, arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8); } finally { PythonOps.FunctionPopFrame(); } } } internal class PythonFunctionRecursionCheck10 { private readonly Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object> _target; public PythonFunctionRecursionCheck10(Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object> target) { _target = target; } public object CallTarget(PythonFunction/*!*/ function, object arg0, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8, object arg9) { PythonOps.FunctionPushFrame((PythonContext)function.Context.LanguageContext); try { return _target(function, arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9); } finally { PythonOps.FunctionPopFrame(); } } } internal class PythonFunctionRecursionCheck11 { private readonly Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object, object> _target; public PythonFunctionRecursionCheck11(Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object, object> target) { _target = target; } public object CallTarget(PythonFunction/*!*/ function, object arg0, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8, object arg9, object arg10) { PythonOps.FunctionPushFrame((PythonContext)function.Context.LanguageContext); try { return _target(function, arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10); } finally { PythonOps.FunctionPopFrame(); } } } internal class PythonFunctionRecursionCheck12 { private readonly Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object, object, object> _target; public PythonFunctionRecursionCheck12(Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object, object, object> target) { _target = target; } public object CallTarget(PythonFunction/*!*/ function, object arg0, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8, object arg9, object arg10, object arg11) { PythonOps.FunctionPushFrame((PythonContext)function.Context.LanguageContext); try { return _target(function, arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11); } finally { PythonOps.FunctionPopFrame(); } } } internal class PythonFunctionRecursionCheck13 { private readonly Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object, object, object, object> _target; public PythonFunctionRecursionCheck13(Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object, object, object, object> target) { _target = target; } public object CallTarget(PythonFunction/*!*/ function, object arg0, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8, object arg9, object arg10, object arg11, object arg12) { PythonOps.FunctionPushFrame((PythonContext)function.Context.LanguageContext); try { return _target(function, arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12); } finally { PythonOps.FunctionPopFrame(); } } } internal class PythonFunctionRecursionCheck14 { private readonly Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object, object, object, object, object> _target; public PythonFunctionRecursionCheck14(Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object, object, object, object, object> target) { _target = target; } public object CallTarget(PythonFunction/*!*/ function, object arg0, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8, object arg9, object arg10, object arg11, object arg12, object arg13) { PythonOps.FunctionPushFrame((PythonContext)function.Context.LanguageContext); try { return _target(function, arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13); } finally { PythonOps.FunctionPopFrame(); } } } internal class PythonFunctionRecursionCheck15 { private readonly Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object, object, object, object, object, object> _target; public PythonFunctionRecursionCheck15(Func<PythonFunction, object, object, object, object, object, object, object, object, object, object, object, object, object, object, object, object> target) { _target = target; } public object CallTarget(PythonFunction/*!*/ function, object arg0, object arg1, object arg2, object arg3, object arg4, object arg5, object arg6, object arg7, object arg8, object arg9, object arg10, object arg11, object arg12, object arg13, object arg14) { PythonOps.FunctionPushFrame((PythonContext)function.Context.LanguageContext); try { return _target(function, arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12, arg13, arg14); } finally { PythonOps.FunctionPopFrame(); } } } // *** END GENERATED CODE *** #endregion }
using GalaSoft.MvvmLight; using GalaSoft.MvvmLight.Command; using Q42.HueApi.Interfaces; using Q42.WinRT.Data; using Q42.WinRT.Portable.Data; using System; using System.Collections.Generic; using System.Linq; namespace Q42.HueApi.WinRT.Sample.ViewModel { /// <summary> /// This class contains properties that the main View can data bind to. /// <para> /// Use the <strong>mvvminpc</strong> snippet to add bindable properties to this ViewModel. /// </para> /// <para> /// You can also use Blend to data bind with the tool's support. /// </para> /// <para> /// See http://www.galasoft.ch/mvvm /// </para> /// </summary> public class MainViewModel : ViewModelBase { public DataLoader LocateBridgeDataLoader { get; set; } public RelayCommand LocateBridgeCommand { get; set; } public DataLoader SsdpLocateBridgeDataLoader { get; set; } public RelayCommand SsdpLocateBridgeCommand { get; set; } public DataLoader RegisterDataLoader { get; set; } public RelayCommand GetLightsCommand { get; set; } public RelayCommand TurnOnCommand { get; set; } public RelayCommand TurnOffCommand { get; set; } public RelayCommand GreenCommand { get; set; } public RelayCommand RedCommand { get; set; } public RelayCommand ColorloopCommand { get; set; } public RelayCommand FlashCommand { get; set; } IBridgeLocator httpLocator = new HttpBridgeLocator(); IBridgeLocator ssdpLocator = new SSDPBridgeLocator(); HueClient _hueClient; private string _httpBridges; public string HttpBridges { get { return _httpBridges; } set { _httpBridges = value; RaisePropertyChanged("HttpBridges"); } } private string _ssdpBridges; public string SsdpBridges { get { return _ssdpBridges; } set { _ssdpBridges = value; RaisePropertyChanged("SsdpBridges"); } } private bool _registerSuccess; public bool RegisterSuccess { get { return _registerSuccess; } set { _registerSuccess = value; RaisePropertyChanged("RegisterSuccess"); } } private string _getLights; public string GetLights { get { return _getLights; } set { _getLights = value; RaisePropertyChanged("GetLights"); } } /// <summary> /// Initializes a new instance of the MainViewModel class. /// </summary> public MainViewModel() { LocateBridgeDataLoader = new DataLoader(); SsdpLocateBridgeDataLoader = new DataLoader(); RegisterDataLoader = new DataLoader(); LocateBridgeCommand = new RelayCommand(LocateBridgeAction); SsdpLocateBridgeCommand = new RelayCommand(SsdpLocateBridgeAction); GetLightsCommand = new RelayCommand(GetLightsAction); TurnOnCommand = new RelayCommand(TurnOnAction); TurnOffCommand = new RelayCommand(TurnOffAction); GreenCommand = new RelayCommand(GreenAction); RedCommand = new RelayCommand(RedAction); ColorloopCommand = new RelayCommand(ColorloopAction); FlashCommand = new RelayCommand(FlashAction); } private async void LocateBridgeAction() { var result = await LocateBridgeDataLoader.LoadAsync(() => httpLocator.LocateBridgesAsync(TimeSpan.FromSeconds(5))); HttpBridges = string.Join(", ", result.ToArray()); if (result.Count() > 0) _hueClient = new HueClient(result.First()); } private async void SsdpLocateBridgeAction() { var result = await SsdpLocateBridgeDataLoader.LoadAsync(() => ssdpLocator.LocateBridgesAsync(TimeSpan.FromSeconds(5))); if (result == null) result = new List<string>(); SsdpBridges = string.Join(", ", result.ToArray()); if (result.Count() > 0) _hueClient = new HueClient(result.First()); } internal async void Register(string p) { var result = await RegisterDataLoader.LoadAsync(() => _hueClient.RegisterAsync(p, p)); RegisterSuccess = !string.IsNullOrEmpty(result); } internal void Initialize(string p) { _hueClient.Initialize(p); } private async void GetLightsAction() { var result = await _hueClient.GetLightsAsync(); GetLights = string.Format("Found {0} lights", result.Count()); } private void RedAction() { LightCommand command = new LightCommand(); command.TurnOn().SetColor("FF0000"); _hueClient.SendCommandAsync(command); } private void GreenAction() { LightCommand command = new LightCommand(); command.TurnOn().SetColor("00FF00"); _hueClient.SendCommandAsync(command); } private void TurnOffAction() { LightCommand command = new LightCommand(); command.TurnOff(); _hueClient.SendCommandAsync(command); } private void TurnOnAction() { LightCommand command = new LightCommand(); command.TurnOn(); _hueClient.SendCommandAsync(command); } private void ColorloopAction() { LightCommand command = new LightCommand(); command.TurnOn(); command.Effect = Effect.ColorLoop; _hueClient.SendCommandAsync(command); } private void FlashAction() { LightCommand command = new LightCommand(); command.TurnOn(); command.Alert = Alert.Once; _hueClient.SendCommandAsync(command); } public void SetColor(int r, int g, int b) { LightCommand command = new LightCommand(); command.TurnOn(); command.SetColor(r, g, b); _hueClient.SendCommandAsync(command); } internal void ManualRegister(string ip) { _hueClient = new HueClient(ip); } } }
namespace Azure.AI.Translation.Document { public partial class DocumentFilter { public DocumentFilter() { } public string Prefix { get { throw null; } set { } } public string Suffix { get { throw null; } set { } } } public partial class DocumentStatusResult { internal DocumentStatusResult() { } public long CharactersCharged { get { throw null; } } public System.DateTimeOffset CreatedOn { get { throw null; } } public string DocumentId { get { throw null; } } public Azure.AI.Translation.Document.DocumentTranslationError Error { get { throw null; } } public bool HasCompleted { get { throw null; } } public System.DateTimeOffset LastModified { get { throw null; } } public System.Uri SourceDocumentUri { get { throw null; } } public Azure.AI.Translation.Document.TranslationStatus Status { get { throw null; } } public System.Uri TranslatedDocumentUri { get { throw null; } } public string TranslateTo { get { throw null; } } public float TranslationProgressPercentage { get { throw null; } } } public partial class DocumentTranslationClient { protected DocumentTranslationClient() { } public DocumentTranslationClient(System.Uri endpoint, Azure.AzureKeyCredential credential) { } public DocumentTranslationClient(System.Uri endpoint, Azure.AzureKeyCredential credential, Azure.AI.Translation.Document.DocumentTranslationClientOptions options) { } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } public virtual Azure.Response<System.Collections.Generic.IReadOnlyList<Azure.AI.Translation.Document.FileFormat>> GetDocumentFormats(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<System.Collections.Generic.IReadOnlyList<Azure.AI.Translation.Document.FileFormat>>> GetDocumentFormatsAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<System.Collections.Generic.IReadOnlyList<Azure.AI.Translation.Document.FileFormat>> GetGlossaryFormats(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<System.Collections.Generic.IReadOnlyList<Azure.AI.Translation.Document.FileFormat>>> GetGlossaryFormatsAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } public virtual Azure.Pageable<Azure.AI.Translation.Document.TranslationStatusResult> GetTranslations(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.AsyncPageable<Azure.AI.Translation.Document.TranslationStatusResult> GetTranslationsAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.AI.Translation.Document.DocumentTranslationOperation StartTranslation(Azure.AI.Translation.Document.DocumentTranslationInput input, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.AI.Translation.Document.DocumentTranslationOperation StartTranslation(System.Collections.Generic.IEnumerable<Azure.AI.Translation.Document.DocumentTranslationInput> inputs, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.AI.Translation.Document.DocumentTranslationOperation> StartTranslationAsync(Azure.AI.Translation.Document.DocumentTranslationInput input, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.AI.Translation.Document.DocumentTranslationOperation> StartTranslationAsync(System.Collections.Generic.IEnumerable<Azure.AI.Translation.Document.DocumentTranslationInput> inputs, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override string ToString() { throw null; } } public partial class DocumentTranslationClientOptions : Azure.Core.ClientOptions { public DocumentTranslationClientOptions(Azure.AI.Translation.Document.DocumentTranslationClientOptions.ServiceVersion version = Azure.AI.Translation.Document.DocumentTranslationClientOptions.ServiceVersion.V1_0_preview_1) { } public enum ServiceVersion { V1_0_preview_1 = 1, } } public partial class DocumentTranslationError { internal DocumentTranslationError() { } public Azure.AI.Translation.Document.DocumentTranslationErrorCode ErrorCode { get { throw null; } } public string Message { get { throw null; } } public string Target { get { throw null; } } } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public readonly partial struct DocumentTranslationErrorCode : System.IEquatable<Azure.AI.Translation.Document.DocumentTranslationErrorCode> { private readonly object _dummy; private readonly int _dummyPrimitive; public DocumentTranslationErrorCode(string value) { throw null; } public static Azure.AI.Translation.Document.DocumentTranslationErrorCode InternalServerError { get { throw null; } } public static Azure.AI.Translation.Document.DocumentTranslationErrorCode InvalidArgument { get { throw null; } } public static Azure.AI.Translation.Document.DocumentTranslationErrorCode InvalidRequest { get { throw null; } } public static Azure.AI.Translation.Document.DocumentTranslationErrorCode RequestRateTooHigh { get { throw null; } } public static Azure.AI.Translation.Document.DocumentTranslationErrorCode ResourceNotFound { get { throw null; } } public static Azure.AI.Translation.Document.DocumentTranslationErrorCode ServiceUnavailable { get { throw null; } } public static Azure.AI.Translation.Document.DocumentTranslationErrorCode Unauthorized { get { throw null; } } public bool Equals(Azure.AI.Translation.Document.DocumentTranslationErrorCode other) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } public static bool operator ==(Azure.AI.Translation.Document.DocumentTranslationErrorCode left, Azure.AI.Translation.Document.DocumentTranslationErrorCode right) { throw null; } public static implicit operator Azure.AI.Translation.Document.DocumentTranslationErrorCode (string value) { throw null; } public static bool operator !=(Azure.AI.Translation.Document.DocumentTranslationErrorCode left, Azure.AI.Translation.Document.DocumentTranslationErrorCode right) { throw null; } public override string ToString() { throw null; } } public partial class DocumentTranslationInput { public DocumentTranslationInput(Azure.AI.Translation.Document.TranslationSource source, System.Collections.Generic.IEnumerable<Azure.AI.Translation.Document.TranslationTarget> targets) { } public DocumentTranslationInput(System.Uri sourceUri, System.Uri targetUri, string targetLanguageCode, Azure.AI.Translation.Document.TranslationGlossary glossary = null) { } public Azure.AI.Translation.Document.TranslationSource Source { get { throw null; } } public Azure.AI.Translation.Document.StorageInputType? StorageType { get { throw null; } set { } } public System.Collections.Generic.IList<Azure.AI.Translation.Document.TranslationTarget> Targets { get { throw null; } } public void AddTarget(System.Uri targetUri, string languageCode, Azure.AI.Translation.Document.TranslationGlossary glossary = null) { } } public partial class DocumentTranslationOperation : Azure.AI.Translation.Document.PageableOperation<Azure.AI.Translation.Document.DocumentStatusResult> { protected DocumentTranslationOperation() { } public DocumentTranslationOperation(string translationId, Azure.AI.Translation.Document.DocumentTranslationClient client) { } public virtual System.DateTimeOffset CreatedOn { get { throw null; } } public virtual int DocumentsCancelled { get { throw null; } } public virtual int DocumentsFailed { get { throw null; } } public virtual int DocumentsInProgress { get { throw null; } } public virtual int DocumentsNotStarted { get { throw null; } } public virtual int DocumentsSucceeded { get { throw null; } } public virtual int DocumentsTotal { get { throw null; } } public override bool HasCompleted { get { throw null; } } public override bool HasValue { get { throw null; } } public override string Id { get { throw null; } } public virtual System.DateTimeOffset LastModified { get { throw null; } } public virtual Azure.AI.Translation.Document.TranslationStatus Status { get { throw null; } } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override Azure.AsyncPageable<Azure.AI.Translation.Document.DocumentStatusResult> Value { get { throw null; } } public virtual void Cancel(System.Threading.CancellationToken cancellationToken) { } public virtual System.Threading.Tasks.Task CancelAsync(System.Threading.CancellationToken cancellationToken) { throw null; } public virtual Azure.Pageable<Azure.AI.Translation.Document.DocumentStatusResult> GetAllDocumentStatuses(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.AsyncPageable<Azure.AI.Translation.Document.DocumentStatusResult> GetAllDocumentStatusesAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<Azure.AI.Translation.Document.DocumentStatusResult> GetDocumentStatus(string documentId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.AI.Translation.Document.DocumentStatusResult>> GetDocumentStatusAsync(string documentId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public override Azure.Response GetRawResponse() { throw null; } public override Azure.Pageable<Azure.AI.Translation.Document.DocumentStatusResult> GetValues() { throw null; } public override Azure.AsyncPageable<Azure.AI.Translation.Document.DocumentStatusResult> GetValuesAsync() { throw null; } public override Azure.Response UpdateStatus(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public override System.Threading.Tasks.ValueTask<Azure.Response> UpdateStatusAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public override System.Threading.Tasks.ValueTask<Azure.Response<Azure.AsyncPageable<Azure.AI.Translation.Document.DocumentStatusResult>>> WaitForCompletionAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public override System.Threading.Tasks.ValueTask<Azure.Response<Azure.AsyncPageable<Azure.AI.Translation.Document.DocumentStatusResult>>> WaitForCompletionAsync(System.TimeSpan pollingInterval, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } } public partial class FileFormat { internal FileFormat() { } public System.Collections.Generic.IReadOnlyList<string> ContentTypes { get { throw null; } } public string DefaultFormatVersion { get { throw null; } } public System.Collections.Generic.IReadOnlyList<string> FileExtensions { get { throw null; } } public string Format { get { throw null; } } public System.Collections.Generic.IReadOnlyList<string> FormatVersions { get { throw null; } } } public abstract partial class PageableOperation<T> : Azure.Operation<Azure.AsyncPageable<T>> where T : notnull { protected PageableOperation() { } public override Azure.AsyncPageable<T> Value { get { throw null; } } public abstract Azure.Pageable<T> GetValues(); public abstract Azure.AsyncPageable<T> GetValuesAsync(); } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public readonly partial struct StorageInputType : System.IEquatable<Azure.AI.Translation.Document.StorageInputType> { private readonly object _dummy; private readonly int _dummyPrimitive; public StorageInputType(string value) { throw null; } public static Azure.AI.Translation.Document.StorageInputType File { get { throw null; } } public static Azure.AI.Translation.Document.StorageInputType Folder { get { throw null; } } public bool Equals(Azure.AI.Translation.Document.StorageInputType other) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } public static bool operator ==(Azure.AI.Translation.Document.StorageInputType left, Azure.AI.Translation.Document.StorageInputType right) { throw null; } public static implicit operator Azure.AI.Translation.Document.StorageInputType (string value) { throw null; } public static bool operator !=(Azure.AI.Translation.Document.StorageInputType left, Azure.AI.Translation.Document.StorageInputType right) { throw null; } public override string ToString() { throw null; } } public partial class TranslationGlossary { public TranslationGlossary(System.Uri glossaryUri, string format) { } public string Format { get { throw null; } } public string FormatVersion { get { throw null; } set { } } public System.Uri GlossaryUri { get { throw null; } } } public partial class TranslationSource { public TranslationSource(System.Uri sourceUri) { } public Azure.AI.Translation.Document.DocumentFilter Filter { get { throw null; } set { } } public string LanguageCode { get { throw null; } set { } } public System.Uri SourceUri { get { throw null; } } } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public readonly partial struct TranslationStatus : System.IEquatable<Azure.AI.Translation.Document.TranslationStatus> { private readonly object _dummy; private readonly int _dummyPrimitive; public TranslationStatus(string value) { throw null; } public static Azure.AI.Translation.Document.TranslationStatus Cancelled { get { throw null; } } public static Azure.AI.Translation.Document.TranslationStatus Cancelling { get { throw null; } } public static Azure.AI.Translation.Document.TranslationStatus Failed { get { throw null; } } public static Azure.AI.Translation.Document.TranslationStatus NotStarted { get { throw null; } } public static Azure.AI.Translation.Document.TranslationStatus Running { get { throw null; } } public static Azure.AI.Translation.Document.TranslationStatus Succeeded { get { throw null; } } public static Azure.AI.Translation.Document.TranslationStatus ValidationFailed { get { throw null; } } public bool Equals(Azure.AI.Translation.Document.TranslationStatus other) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } public static bool operator ==(Azure.AI.Translation.Document.TranslationStatus left, Azure.AI.Translation.Document.TranslationStatus right) { throw null; } public static implicit operator Azure.AI.Translation.Document.TranslationStatus (string value) { throw null; } public static bool operator !=(Azure.AI.Translation.Document.TranslationStatus left, Azure.AI.Translation.Document.TranslationStatus right) { throw null; } public override string ToString() { throw null; } } public partial class TranslationStatusResult { internal TranslationStatusResult() { } public System.DateTimeOffset CreatedOn { get { throw null; } } public int DocumentsCancelled { get { throw null; } } public int DocumentsFailed { get { throw null; } } public int DocumentsInProgress { get { throw null; } } public int DocumentsNotStarted { get { throw null; } } public int DocumentsSucceeded { get { throw null; } } public int DocumentsTotal { get { throw null; } } public Azure.AI.Translation.Document.DocumentTranslationError Error { get { throw null; } } public bool HasCompleted { get { throw null; } } public System.DateTimeOffset LastModified { get { throw null; } } public Azure.AI.Translation.Document.TranslationStatus Status { get { throw null; } } public long TotalCharactersCharged { get { throw null; } } public string TranslationId { get { throw null; } } } public partial class TranslationTarget { public TranslationTarget(System.Uri targetUri, string languageCode) { } public string CategoryId { get { throw null; } set { } } public System.Collections.Generic.IList<Azure.AI.Translation.Document.TranslationGlossary> Glossaries { get { throw null; } } public string LanguageCode { get { throw null; } } public System.Uri TargetUri { get { throw null; } } } }
// // WidgetBackend.cs // // Author: // Lluis Sanchez <lluis@xamarin.com> // // Copyright (c) 2011 Xamarin 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 Xwt.Backends; using Xwt; using System.Collections.Generic; using System.Linq; using Xwt.Drawing; namespace Xwt.GtkBackend { public partial class WidgetBackend: IWidgetBackend, IGtkWidgetBackend { Gtk.Widget widget; Widget frontend; Gtk.EventBox eventBox; IWidgetEventSink eventSink; WidgetEvent enabledEvents; bool destroyed; SizeConstraint currentWidthConstraint = SizeConstraint.Unconstrained; SizeConstraint currentHeightConstraint = SizeConstraint.Unconstrained; bool minSizeSet; class DragDropData { public TransferDataSource CurrentDragData; public Gdk.DragAction DestDragAction; public Gdk.DragAction SourceDragAction; public int DragDataRequests; public TransferDataStore DragData; public bool DragDataForMotion; public Gtk.TargetEntry[] ValidDropTypes; public Point LastDragPosition; } DragDropData dragDropInfo; const WidgetEvent dragDropEvents = WidgetEvent.DragDropCheck | WidgetEvent.DragDrop | WidgetEvent.DragOver | WidgetEvent.DragOverCheck; void IBackend.InitializeBackend (object frontend, ApplicationContext context) { this.frontend = (Widget) frontend; ApplicationContext = context; } void IWidgetBackend.Initialize (IWidgetEventSink sink) { eventSink = sink; Initialize (); } public virtual void Initialize () { } public IWidgetEventSink EventSink { get { return eventSink; } } public Widget Frontend { get { return frontend; } } public ApplicationContext ApplicationContext { get; private set; } public object NativeWidget { get { return RootWidget; } } public Gtk.Widget Widget { get { return widget; } set { if (widget != null) { value.Visible = widget.Visible; GtkEngine.ReplaceChild (widget, value); } widget = value; } } public Gtk.Widget RootWidget { get { return eventBox ?? (Gtk.Widget) Widget; } } public virtual bool Visible { get { return Widget.Visible; } set { Widget.Visible = value; if (eventBox != null) eventBox.Visible = value; } } void RunWhenRealized (Action a) { if (Widget.IsRealized) a (); else { EventHandler h = null; h = delegate { a (); }; EventsRootWidget.Realized += h; } } public virtual bool Sensitive { get { return Widget.Sensitive; } set { Widget.Sensitive = value; if (eventBox != null) eventBox.Sensitive = value; } } public bool CanGetFocus { get { return Widget.CanFocus; } set { Widget.CanFocus = value; } } public bool HasFocus { get { return Widget.IsFocus; } } public virtual void SetFocus () { if (CanGetFocus) Widget.GrabFocus (); } public string TooltipText { get { return Widget.TooltipText; } set { Widget.TooltipText = value; } } static Dictionary<CursorType,Gdk.Cursor> gtkCursors = new Dictionary<CursorType, Gdk.Cursor> (); Gdk.Cursor gdkCursor; internal CursorType CurrentCursor { get; private set; } public void SetCursor (CursorType cursor) { AllocEventBox (); CurrentCursor = cursor; Gdk.Cursor gc; if (!gtkCursors.TryGetValue (cursor, out gc)) { Gdk.CursorType ctype; if (cursor == CursorType.Arrow) ctype = Gdk.CursorType.LeftPtr; else if (cursor == CursorType.Crosshair) ctype = Gdk.CursorType.Crosshair; else if (cursor == CursorType.Hand) ctype = Gdk.CursorType.Hand1; else if (cursor == CursorType.IBeam) ctype = Gdk.CursorType.Xterm; else if (cursor == CursorType.ResizeDown) ctype = Gdk.CursorType.BottomSide; else if (cursor == CursorType.ResizeUp) ctype = Gdk.CursorType.TopSide; else if (cursor == CursorType.ResizeLeft) ctype = Gdk.CursorType.LeftSide; else if (cursor == CursorType.ResizeRight) ctype = Gdk.CursorType.RightSide; else if (cursor == CursorType.ResizeLeftRight) ctype = Gdk.CursorType.SbHDoubleArrow; else if (cursor == CursorType.ResizeUpDown) ctype = Gdk.CursorType.SbVDoubleArrow; else if (cursor == CursorType.Move) ctype = Gdk.CursorType.Fleur; else if (cursor == CursorType.Wait) ctype = Gdk.CursorType.Watch; else if (cursor == CursorType.Help) ctype = Gdk.CursorType.QuestionArrow; else if (cursor == CursorType.Invisible) ctype = (Gdk.CursorType)(-2); // Gdk.CursorType.None, since Gtk 2.16 else ctype = Gdk.CursorType.Arrow; gtkCursors [cursor] = gc = new Gdk.Cursor (ctype); } gdkCursor = gc; // subscribe mouse entered/leaved events, when widget gets/is realized RunWhenRealized(SubscribeCursorEnterLeaveEvent); if (immediateCursorChange) // if realized and mouse inside set immediatly EventsRootWidget.GdkWindow.Cursor = gdkCursor; } bool cursorEnterLeaveSubscribed, immediateCursorChange; void SubscribeCursorEnterLeaveEvent () { if (!cursorEnterLeaveSubscribed) { cursorEnterLeaveSubscribed = true; // subscribe only once EventsRootWidget.AddEvents ((int)Gdk.EventMask.EnterNotifyMask); EventsRootWidget.AddEvents ((int)Gdk.EventMask.LeaveNotifyMask); EventsRootWidget.EnterNotifyEvent += (o, args) => { immediateCursorChange = true; if (gdkCursor != null) ((Gtk.Widget)o).GdkWindow.Cursor = gdkCursor; }; EventsRootWidget.LeaveNotifyEvent += (o, args) => { immediateCursorChange = false; ((Gtk.Widget)o).GdkWindow.Cursor = null; }; } } ~WidgetBackend () { Dispose (false); } public void Dispose () { GC.SuppressFinalize (this); Dispose (true); } protected virtual void Dispose (bool disposing) { if (Widget != null && disposing && Widget.Parent == null && !destroyed) { MarkDestroyed (Frontend); Widget.Destroy (); } if (IMContext != null) IMContext.Dispose (); } void MarkDestroyed (Widget w) { var bk = (WidgetBackend) Toolkit.GetBackend (w); bk.destroyed = true; foreach (var c in w.Surface.Children) MarkDestroyed (c); } public Size Size { get { return new Size (Widget.Allocation.Width, Widget.Allocation.Height); } } public void SetSizeConstraints (SizeConstraint widthConstraint, SizeConstraint heightConstraint) { currentWidthConstraint = widthConstraint; currentHeightConstraint = heightConstraint; } DragDropData DragDropInfo { get { if (dragDropInfo == null) dragDropInfo = new DragDropData (); return dragDropInfo; } } public Point ConvertToScreenCoordinates (Point widgetCoordinates) { if (Widget.ParentWindow == null) return Point.Zero; int x, y; Widget.ParentWindow.GetOrigin (out x, out y); var a = Widget.Allocation; x += a.X; y += a.Y; return new Point (x + widgetCoordinates.X, y + widgetCoordinates.Y); } Pango.FontDescription customFont; public virtual object Font { get { return customFont ?? Widget.Style.FontDescription; } set { var fd = (Pango.FontDescription) value; customFont = fd; Widget.ModifyFont (fd); } } Color? customBackgroundColor; public virtual Color BackgroundColor { get { return customBackgroundColor.HasValue ? customBackgroundColor.Value : Widget.Style.Background (Gtk.StateType.Normal).ToXwtValue (); } set { customBackgroundColor = value; AllocEventBox (visibleWindow: true); OnSetBackgroundColor (value); } } public virtual bool UsingCustomBackgroundColor { get { return customBackgroundColor.HasValue; } } Gtk.Widget IGtkWidgetBackend.Widget { get { return RootWidget; } } protected virtual Gtk.Widget EventsRootWidget { get { return eventBox ?? Widget; } } bool needsEventBox = true; // require event box by default protected virtual bool NeedsEventBox { get { return needsEventBox; } set { needsEventBox = value; } } public static Gtk.Widget GetWidget (IWidgetBackend w) { return w != null ? ((IGtkWidgetBackend)w).Widget : null; } public virtual void UpdateChildPlacement (IWidgetBackend childBackend) { SetChildPlacement (childBackend); } public static Gtk.Widget GetWidgetWithPlacement (IWidgetBackend childBackend) { var backend = (WidgetBackend)childBackend; var child = backend.RootWidget; var wrapper = child.Parent as WidgetPlacementWrapper; if (wrapper != null) return wrapper; if (!NeedsAlignmentWrapper (backend.Frontend)) return child; wrapper = new WidgetPlacementWrapper (); wrapper.UpdatePlacement (backend.Frontend); wrapper.Show (); wrapper.Add (child); return wrapper; } public static void RemoveChildPlacement (Gtk.Widget w) { if (w == null) return; if (w is WidgetPlacementWrapper) { var wp = (WidgetPlacementWrapper)w; wp.Remove (wp.Child); } } static bool NeedsAlignmentWrapper (Widget fw) { return fw.HorizontalPlacement != WidgetPlacement.Fill || fw.VerticalPlacement != WidgetPlacement.Fill || fw.Margin.VerticalSpacing != 0 || fw.Margin.HorizontalSpacing != 0; } public static void SetChildPlacement (IWidgetBackend childBackend) { var backend = (WidgetBackend)childBackend; var child = backend.RootWidget; var wrapper = child.Parent as WidgetPlacementWrapper; var fw = backend.Frontend; if (!NeedsAlignmentWrapper (fw)) { if (wrapper != null) { wrapper.Remove (child); GtkEngine.ReplaceChild (wrapper, child); } return; } if (wrapper == null) { wrapper = new WidgetPlacementWrapper (); wrapper.Show (); GtkEngine.ReplaceChild (child, wrapper); wrapper.Add (child); } wrapper.UpdatePlacement (fw); } public virtual void UpdateLayout () { Widget.QueueResize (); if (!Widget.IsRealized) { // This is a workaround to a GTK bug. When a widget is inside a ScrolledWindow, sometimes the QueueResize call on // the widget is ignored if the widget is not realized. var p = Widget.Parent; while (p != null && !(p is Gtk.ScrolledWindow)) p = p.Parent; if (p != null) p.QueueResize (); } } protected void AllocEventBox (bool visibleWindow = false) { // Wraps the widget with an event box. Required for some // widgets such as Label which doesn't have its own gdk window if (visibleWindow) { if (eventBox != null) eventBox.VisibleWindow = true; else if (EventsRootWidget is Gtk.EventBox) ((Gtk.EventBox)EventsRootWidget).VisibleWindow = true; } if (!NeedsEventBox) return; if (eventBox == null && !EventsRootWidget.GetHasWindow()) { if (EventsRootWidget is Gtk.EventBox) { ((Gtk.EventBox)EventsRootWidget).VisibleWindow = visibleWindow; return; } eventBox = new Gtk.EventBox (); eventBox.Visible = Widget.Visible; eventBox.Sensitive = Widget.Sensitive; eventBox.VisibleWindow = visibleWindow; GtkEngine.ReplaceChild (Widget, eventBox); eventBox.Add (Widget); } } public virtual void EnableEvent (object eventId) { if (eventId is WidgetEvent) { WidgetEvent ev = (WidgetEvent) eventId; switch (ev) { case WidgetEvent.DragLeave: AllocEventBox (); EventsRootWidget.DragLeave += HandleWidgetDragLeave; break; case WidgetEvent.DragStarted: AllocEventBox (); EventsRootWidget.DragBegin += HandleWidgetDragBegin; break; case WidgetEvent.KeyPressed: Widget.KeyPressEvent += HandleKeyPressEvent; break; case WidgetEvent.KeyReleased: Widget.KeyReleaseEvent += HandleKeyReleaseEvent; break; case WidgetEvent.GotFocus: EventsRootWidget.AddEvents ((int)Gdk.EventMask.FocusChangeMask); Widget.FocusGrabbed += HandleWidgetFocusInEvent; break; case WidgetEvent.LostFocus: EventsRootWidget.AddEvents ((int)Gdk.EventMask.FocusChangeMask); Widget.FocusOutEvent += HandleWidgetFocusOutEvent; break; case WidgetEvent.MouseEntered: AllocEventBox (); EventsRootWidget.AddEvents ((int)Gdk.EventMask.EnterNotifyMask); EventsRootWidget.EnterNotifyEvent += HandleEnterNotifyEvent; break; case WidgetEvent.MouseExited: AllocEventBox (); EventsRootWidget.AddEvents ((int)Gdk.EventMask.LeaveNotifyMask); EventsRootWidget.LeaveNotifyEvent += HandleLeaveNotifyEvent; break; case WidgetEvent.ButtonPressed: AllocEventBox (); EventsRootWidget.AddEvents ((int)Gdk.EventMask.ButtonPressMask); EventsRootWidget.ButtonPressEvent += HandleButtonPressEvent; break; case WidgetEvent.ButtonReleased: AllocEventBox (); EventsRootWidget.AddEvents ((int)Gdk.EventMask.ButtonReleaseMask); EventsRootWidget.ButtonReleaseEvent += HandleButtonReleaseEvent; break; case WidgetEvent.MouseMoved: AllocEventBox (); EventsRootWidget.AddEvents ((int)Gdk.EventMask.PointerMotionMask); EventsRootWidget.MotionNotifyEvent += HandleMotionNotifyEvent; break; case WidgetEvent.BoundsChanged: Widget.SizeAllocated += HandleWidgetBoundsChanged; break; case WidgetEvent.MouseScrolled: AllocEventBox(); EventsRootWidget.AddEvents ((int)Gdk.EventMask.ScrollMask); Widget.ScrollEvent += HandleScrollEvent; break; case WidgetEvent.TextInput: if (EditableWidget != null) { EditableWidget.TextInserted += HandleTextInserted; } else { RunWhenRealized (delegate { if (IMContext == null) { IMContext = new Gtk.IMMulticontext (); IMContext.ClientWindow = EventsRootWidget.GdkWindow; IMContext.Commit += HandleImCommitEvent; } }); Widget.KeyPressEvent += HandleTextInputKeyPressEvent; Widget.KeyReleaseEvent += HandleTextInputKeyReleaseEvent; } break; } if ((ev & dragDropEvents) != 0 && (enabledEvents & dragDropEvents) == 0) { // Enabling a drag&drop event for the first time AllocEventBox (); EventsRootWidget.DragDrop += HandleWidgetDragDrop; EventsRootWidget.DragMotion += HandleWidgetDragMotion; EventsRootWidget.DragDataReceived += HandleWidgetDragDataReceived; } if ((ev & WidgetEvent.PreferredSizeCheck) != 0) { EnableSizeCheckEvents (); } enabledEvents |= ev; } } public virtual void DisableEvent (object eventId) { if (eventId is WidgetEvent) { WidgetEvent ev = (WidgetEvent) eventId; switch (ev) { case WidgetEvent.DragLeave: EventsRootWidget.DragLeave -= HandleWidgetDragLeave; break; case WidgetEvent.DragStarted: EventsRootWidget.DragBegin -= HandleWidgetDragBegin; break; case WidgetEvent.KeyPressed: Widget.KeyPressEvent -= HandleKeyPressEvent; break; case WidgetEvent.KeyReleased: Widget.KeyReleaseEvent -= HandleKeyReleaseEvent; break; case WidgetEvent.GotFocus: Widget.FocusInEvent -= HandleWidgetFocusInEvent; break; case WidgetEvent.LostFocus: Widget.FocusOutEvent -= HandleWidgetFocusOutEvent; break; case WidgetEvent.MouseEntered: EventsRootWidget.EnterNotifyEvent -= HandleEnterNotifyEvent; break; case WidgetEvent.MouseExited: EventsRootWidget.LeaveNotifyEvent -= HandleLeaveNotifyEvent; break; case WidgetEvent.ButtonPressed: if (!EventsRootWidget.IsRealized) EventsRootWidget.Events &= ~Gdk.EventMask.ButtonPressMask; EventsRootWidget.ButtonPressEvent -= HandleButtonPressEvent; break; case WidgetEvent.ButtonReleased: if (!EventsRootWidget.IsRealized) EventsRootWidget.Events &= Gdk.EventMask.ButtonReleaseMask; EventsRootWidget.ButtonReleaseEvent -= HandleButtonReleaseEvent; break; case WidgetEvent.MouseMoved: if (!EventsRootWidget.IsRealized) EventsRootWidget.Events &= Gdk.EventMask.PointerMotionMask; EventsRootWidget.MotionNotifyEvent -= HandleMotionNotifyEvent; break; case WidgetEvent.BoundsChanged: Widget.SizeAllocated -= HandleWidgetBoundsChanged; break; case WidgetEvent.MouseScrolled: if (!EventsRootWidget.IsRealized) EventsRootWidget.Events &= ~Gdk.EventMask.ScrollMask; Widget.ScrollEvent -= HandleScrollEvent; break; case WidgetEvent.TextInput: if (EditableWidget != null) { EditableWidget.TextInserted -= HandleTextInserted; } else { if (IMContext != null) IMContext.Commit -= HandleImCommitEvent; Widget.KeyPressEvent -= HandleTextInputKeyPressEvent; Widget.KeyReleaseEvent -= HandleTextInputKeyReleaseEvent; } break; } enabledEvents &= ~ev; if ((ev & dragDropEvents) != 0 && (enabledEvents & dragDropEvents) == 0) { // All drag&drop events have been disabled EventsRootWidget.DragDrop -= HandleWidgetDragDrop; EventsRootWidget.DragMotion -= HandleWidgetDragMotion; EventsRootWidget.DragDataReceived -= HandleWidgetDragDataReceived; } if ((ev & WidgetEvent.PreferredSizeCheck) != 0) { DisableSizeCheckEvents (); } if ((ev & WidgetEvent.GotFocus) == 0 && (enabledEvents & WidgetEvent.LostFocus) == 0 && !EventsRootWidget.IsRealized) { EventsRootWidget.Events &= ~Gdk.EventMask.FocusChangeMask; } } } Gdk.Rectangle lastAllocation; void HandleWidgetBoundsChanged (object o, Gtk.SizeAllocatedArgs args) { if (Widget.Allocation != lastAllocation) { lastAllocation = Widget.Allocation; ApplicationContext.InvokeUserCode (delegate { EventSink.OnBoundsChanged (); }); } } [GLib.ConnectBefore] void HandleKeyReleaseEvent (object o, Gtk.KeyReleaseEventArgs args) { KeyEventArgs kargs = GetKeyReleaseEventArgs (args); if (kargs == null) return; ApplicationContext.InvokeUserCode (delegate { EventSink.OnKeyReleased (kargs); }); if (kargs.Handled) args.RetVal = true; } protected virtual KeyEventArgs GetKeyReleaseEventArgs (Gtk.KeyReleaseEventArgs args) { Key k = (Key)args.Event.KeyValue; ModifierKeys m = ModifierKeys.None; if ((args.Event.State & Gdk.ModifierType.ShiftMask) != 0) m |= ModifierKeys.Shift; if ((args.Event.State & Gdk.ModifierType.ControlMask) != 0) m |= ModifierKeys.Control; if ((args.Event.State & Gdk.ModifierType.Mod1Mask) != 0) m |= ModifierKeys.Alt; return new KeyEventArgs (k, (int)args.Event.KeyValue, m, false, (long)args.Event.Time); } [GLib.ConnectBefore] void HandleKeyPressEvent (object o, Gtk.KeyPressEventArgs args) { KeyEventArgs kargs = GetKeyPressEventArgs (args); if (kargs == null) return; ApplicationContext.InvokeUserCode (delegate { EventSink.OnKeyPressed (kargs); }); if (kargs.Handled) args.RetVal = true; } protected virtual KeyEventArgs GetKeyPressEventArgs (Gtk.KeyPressEventArgs args) { Key k = (Key)args.Event.KeyValue; ModifierKeys m = args.Event.State.ToXwtValue (); return new KeyEventArgs (k, (int)args.Event.KeyValue, m, false, (long)args.Event.Time); } protected Gtk.IMContext IMContext { get; set; } [GLib.ConnectBefore] void HandleTextInserted (object o, Gtk.TextInsertedArgs args) { if (String.IsNullOrEmpty (args.GetText ())) return; var pargs = new TextInputEventArgs (args.GetText ()); ApplicationContext.InvokeUserCode (delegate { EventSink.OnTextInput (pargs); }); if (pargs.Handled) ((GLib.Object)o).StopSignal ("insert-text"); } [GLib.ConnectBefore] void HandleTextInputKeyReleaseEvent (object o, Gtk.KeyReleaseEventArgs args) { if (IMContext != null) IMContext.FilterKeypress (args.Event); } [GLib.ConnectBefore] void HandleTextInputKeyPressEvent (object o, Gtk.KeyPressEventArgs args) { if (IMContext != null) IMContext.FilterKeypress (args.Event); // new lines are not triggered by im, handle them here if (args.Event.Key == Gdk.Key.Return || args.Event.Key == Gdk.Key.ISO_Enter || args.Event.Key == Gdk.Key.KP_Enter) { var pargs = new TextInputEventArgs (Environment.NewLine); ApplicationContext.InvokeUserCode (delegate { EventSink.OnTextInput (pargs); }); } } [GLib.ConnectBefore] void HandleImCommitEvent (object o, Gtk.CommitArgs args) { if (String.IsNullOrEmpty (args.Str)) return; var pargs = new TextInputEventArgs (args.Str); ApplicationContext.InvokeUserCode (delegate { EventSink.OnTextInput (pargs); }); if (pargs.Handled) args.RetVal = true; } [GLib.ConnectBefore] void HandleScrollEvent(object o, Gtk.ScrollEventArgs args) { var a = GetScrollEventArgs (args); if (a == null) return; ApplicationContext.InvokeUserCode (delegate { EventSink.OnMouseScrolled(a); }); if (a.Handled) args.RetVal = true; } protected virtual MouseScrolledEventArgs GetScrollEventArgs (Gtk.ScrollEventArgs args) { var direction = args.Event.Direction.ToXwtValue (); var pointer_coords = EventsRootWidget.CheckPointerCoordinates (args.Event.Window, args.Event.X, args.Event.Y); return new MouseScrolledEventArgs ((long) args.Event.Time, pointer_coords.X, pointer_coords.Y, direction); } void HandleWidgetFocusOutEvent (object o, Gtk.FocusOutEventArgs args) { ApplicationContext.InvokeUserCode (delegate { EventSink.OnLostFocus (); }); } void HandleWidgetFocusInEvent (object o, EventArgs args) { if (!CanGetFocus) return; ApplicationContext.InvokeUserCode (delegate { EventSink.OnGotFocus (); }); } void HandleLeaveNotifyEvent (object o, Gtk.LeaveNotifyEventArgs args) { if (args.Event.Detail == Gdk.NotifyType.Inferior) return; ApplicationContext.InvokeUserCode (delegate { EventSink.OnMouseExited (); }); } void HandleEnterNotifyEvent (object o, Gtk.EnterNotifyEventArgs args) { if (args.Event.Detail == Gdk.NotifyType.Inferior) return; ApplicationContext.InvokeUserCode (delegate { EventSink.OnMouseEntered (); }); } protected virtual void OnEnterNotifyEvent (Gtk.EnterNotifyEventArgs args) {} void HandleMotionNotifyEvent (object o, Gtk.MotionNotifyEventArgs args) { var a = GetMouseMovedEventArgs (args); if (a == null) return; ApplicationContext.InvokeUserCode (delegate { EventSink.OnMouseMoved (a); }); if (a.Handled) args.RetVal = true; } protected virtual MouseMovedEventArgs GetMouseMovedEventArgs (Gtk.MotionNotifyEventArgs args) { var pointer_coords = EventsRootWidget.CheckPointerCoordinates (args.Event.Window, args.Event.X, args.Event.Y); return new MouseMovedEventArgs ((long) args.Event.Time, pointer_coords.X, pointer_coords.Y); } void HandleButtonReleaseEvent (object o, Gtk.ButtonReleaseEventArgs args) { var a = GetButtonReleaseEventArgs (args); if (a == null) return; ApplicationContext.InvokeUserCode (delegate { EventSink.OnButtonReleased (a); }); if (a.Handled) args.RetVal = true; } protected virtual ButtonEventArgs GetButtonReleaseEventArgs (Gtk.ButtonReleaseEventArgs args) { var a = new ButtonEventArgs (); var pointer_coords = EventsRootWidget.CheckPointerCoordinates (args.Event.Window, args.Event.X, args.Event.Y); a.X = pointer_coords.X; a.Y = pointer_coords.Y; a.Button = (PointerButton) args.Event.Button; return a; } [GLib.ConnectBeforeAttribute] void HandleButtonPressEvent (object o, Gtk.ButtonPressEventArgs args) { var a = GetButtonPressEventArgs (args); if (a == null) return; ApplicationContext.InvokeUserCode (delegate { EventSink.OnButtonPressed (a); }); if (a.Handled) args.RetVal = true; } protected virtual ButtonEventArgs GetButtonPressEventArgs (Gtk.ButtonPressEventArgs args) { var a = new ButtonEventArgs (); var pointer_coords = EventsRootWidget.CheckPointerCoordinates (args.Event.Window, args.Event.X, args.Event.Y); a.X = pointer_coords.X; a.Y = pointer_coords.Y; a.Button = (PointerButton) args.Event.Button; if (args.Event.Type == Gdk.EventType.TwoButtonPress) a.MultiplePress = 2; else if (args.Event.Type == Gdk.EventType.ThreeButtonPress) a.MultiplePress = 3; else a.MultiplePress = 1; return a; } [GLib.ConnectBefore] void HandleWidgetDragMotion (object o, Gtk.DragMotionArgs args) { args.RetVal = DoDragMotion (args.Context, args.X, args.Y, args.Time); } internal bool DoDragMotion (Gdk.DragContext context, int x, int y, uint time) { DragDropInfo.LastDragPosition = new Point (x, y); DragDropAction ac; if ((enabledEvents & WidgetEvent.DragOverCheck) == 0) { if ((enabledEvents & WidgetEvent.DragOver) != 0) ac = DragDropAction.Default; else ac = ConvertDragAction (DragDropInfo.DestDragAction); } else { // This is a workaround to what seems to be a mac gtk bug. // Suggested action is set to all when no control key is pressed var cact = ConvertDragAction (context.Actions); if (cact == DragDropAction.All) cact = DragDropAction.Move; var target = Gtk.Drag.DestFindTarget (EventsRootWidget, context, null); var targetTypes = Util.GetDragTypes (new Gdk.Atom[] { target }); DragOverCheckEventArgs da = new DragOverCheckEventArgs (new Point (x, y), targetTypes, cact); ApplicationContext.InvokeUserCode (delegate { EventSink.OnDragOverCheck (da); }); ac = da.AllowedAction; if ((enabledEvents & WidgetEvent.DragOver) == 0 && ac == DragDropAction.Default) ac = DragDropAction.None; } if (ac == DragDropAction.None) { OnSetDragStatus (context, x, y, time, (Gdk.DragAction)0); return true; } else if (ac == DragDropAction.Default) { // Undefined, we need more data QueryDragData (context, time, true); return true; } else { // Gtk.Drag.Highlight (Widget); OnSetDragStatus (context, x, y, time, ConvertDragAction (ac)); return true; } } [GLib.ConnectBefore] void HandleWidgetDragDrop (object o, Gtk.DragDropArgs args) { args.RetVal = DoDragDrop (args.Context, args.X, args.Y, args.Time); } internal bool DoDragDrop (Gdk.DragContext context, int x, int y, uint time) { DragDropInfo.LastDragPosition = new Point (x, y); var cda = ConvertDragAction (context.GetSelectedAction()); DragDropResult res; if ((enabledEvents & WidgetEvent.DragDropCheck) == 0) { if ((enabledEvents & WidgetEvent.DragDrop) != 0) res = DragDropResult.None; else res = DragDropResult.Canceled; } else { DragCheckEventArgs da = new DragCheckEventArgs (new Point (x, y), Util.GetDragTypes (context.ListTargets ()), cda); ApplicationContext.InvokeUserCode (delegate { EventSink.OnDragDropCheck (da); }); res = da.Result; if ((enabledEvents & WidgetEvent.DragDrop) == 0 && res == DragDropResult.None) res = DragDropResult.Canceled; } if (res == DragDropResult.Canceled) { Gtk.Drag.Finish (context, false, false, time); return true; } else if (res == DragDropResult.Success) { Gtk.Drag.Finish (context, true, cda == DragDropAction.Move, time); return true; } else { // Undefined, we need more data QueryDragData (context, time, false); return true; } } void HandleWidgetDragLeave (object o, Gtk.DragLeaveArgs args) { ApplicationContext.InvokeUserCode (delegate { eventSink.OnDragLeave (EventArgs.Empty); }); } void QueryDragData (Gdk.DragContext ctx, uint time, bool isMotionEvent) { DragDropInfo.DragDataForMotion = isMotionEvent; DragDropInfo.DragData = new TransferDataStore (); DragDropInfo.DragDataRequests = DragDropInfo.ValidDropTypes.Length; foreach (var t in DragDropInfo.ValidDropTypes) { var at = Gdk.Atom.Intern (t.Target, true); Gtk.Drag.GetData (EventsRootWidget, ctx, at, time); } } void HandleWidgetDragDataReceived (object o, Gtk.DragDataReceivedArgs args) { args.RetVal = DoDragDataReceived (args.Context, args.X, args.Y, args.SelectionData, args.Info, args.Time); } internal bool DoDragDataReceived (Gdk.DragContext context, int x, int y, Gtk.SelectionData selectionData, uint info, uint time) { if (DragDropInfo.DragDataRequests == 0) { // Got the data without requesting it. Create the datastore here DragDropInfo.DragData = new TransferDataStore (); DragDropInfo.LastDragPosition = new Point (x, y); DragDropInfo.DragDataRequests = 1; } DragDropInfo.DragDataRequests--; // If multiple drag/drop data types are supported, we need to iterate through them all and // append the data. If one of the supported data types is not found, there's no need to // bail out. We must raise the event Util.GetSelectionData (ApplicationContext, selectionData, DragDropInfo.DragData); if (DragDropInfo.DragDataRequests == 0) { if (DragDropInfo.DragDataForMotion) { // If no specific action is set, it means that no key has been pressed. // In that case, use Move or Copy or Link as default (when allowed, in this order). var cact = ConvertDragAction (context.Actions); if (cact != DragDropAction.Copy && cact != DragDropAction.Move && cact != DragDropAction.Link) { if (cact.HasFlag (DragDropAction.Move)) cact = DragDropAction.Move; else if (cact.HasFlag (DragDropAction.Copy)) cact = DragDropAction.Copy; else if (cact.HasFlag (DragDropAction.Link)) cact = DragDropAction.Link; else cact = DragDropAction.None; } DragOverEventArgs da = new DragOverEventArgs (DragDropInfo.LastDragPosition, DragDropInfo.DragData, cact); ApplicationContext.InvokeUserCode (delegate { EventSink.OnDragOver (da); }); OnSetDragStatus (context, (int)DragDropInfo.LastDragPosition.X, (int)DragDropInfo.LastDragPosition.Y, time, ConvertDragAction (da.AllowedAction)); return true; } else { // Use Context.Action here since that's the action selected in DragOver var cda = ConvertDragAction (context.GetSelectedAction()); DragEventArgs da = new DragEventArgs (DragDropInfo.LastDragPosition, DragDropInfo.DragData, cda); ApplicationContext.InvokeUserCode (delegate { EventSink.OnDragDrop (da); }); Gtk.Drag.Finish (context, da.Success, cda == DragDropAction.Move, time); return true; } } else return false; } protected virtual void OnSetDragStatus (Gdk.DragContext context, int x, int y, uint time, Gdk.DragAction action) { Gdk.Drag.Status (context, action, time); } void HandleWidgetDragBegin (object o, Gtk.DragBeginArgs args) { // If SetDragSource has not been called, ignore the event if (DragDropInfo.SourceDragAction == default (Gdk.DragAction)) return; DragStartData sdata = null; ApplicationContext.InvokeUserCode (delegate { sdata = EventSink.OnDragStarted (); }); if (sdata == null) return; DragDropInfo.CurrentDragData = sdata.Data; if (sdata.ImageBackend != null) { var gi = (GtkImage)sdata.ImageBackend; var img = gi.ToPixbuf (ApplicationContext, Widget); Gtk.Drag.SetIconPixbuf (args.Context, img, (int)sdata.HotX, (int)sdata.HotY); } HandleDragBegin (null, args); } class IconInitializer { public Gdk.Pixbuf Image; public double HotX, HotY; public Gtk.Widget Widget; public static void Init (Gtk.Widget w, Gdk.Pixbuf image, double hotX, double hotY) { IconInitializer ii = new WidgetBackend.IconInitializer (); ii.Image = image; ii.HotX = hotX; ii.HotY = hotY; ii.Widget = w; w.DragBegin += ii.Begin; } void Begin (object o, Gtk.DragBeginArgs args) { Gtk.Drag.SetIconPixbuf (args.Context, Image, (int)HotX, (int)HotY); Widget.DragBegin -= Begin; } } public void DragStart (DragStartData sdata) { AllocEventBox (); Gdk.DragAction action = ConvertDragAction (sdata.DragAction); DragDropInfo.CurrentDragData = sdata.Data; EventsRootWidget.DragBegin += HandleDragBegin; if (sdata.ImageBackend != null) { var img = ((GtkImage)sdata.ImageBackend).ToPixbuf (ApplicationContext, Widget); IconInitializer.Init (EventsRootWidget, img, sdata.HotX, sdata.HotY); } Gtk.Drag.Begin (EventsRootWidget, Util.BuildTargetTable (sdata.Data.DataTypes), action, 1, Gtk.Global.CurrentEvent ?? new Gdk.Event (IntPtr.Zero)); } void HandleDragBegin (object o, Gtk.DragBeginArgs args) { EventsRootWidget.DragEnd += HandleWidgetDragEnd; EventsRootWidget.DragFailed += HandleDragFailed; EventsRootWidget.DragDataDelete += HandleDragDataDelete; EventsRootWidget.DragDataGet += HandleWidgetDragDataGet; } void HandleWidgetDragDataGet (object o, Gtk.DragDataGetArgs args) { Util.SetDragData (DragDropInfo.CurrentDragData, args); } void HandleDragFailed (object o, Gtk.DragFailedArgs args) { Console.WriteLine ("FAILED"); } void HandleDragDataDelete (object o, Gtk.DragDataDeleteArgs args) { DoDragaDataDelete (); } internal void DoDragaDataDelete () { FinishDrag (true); } void HandleWidgetDragEnd (object o, Gtk.DragEndArgs args) { FinishDrag (false); } void FinishDrag (bool delete) { EventsRootWidget.DragEnd -= HandleWidgetDragEnd; EventsRootWidget.DragDataGet -= HandleWidgetDragDataGet; EventsRootWidget.DragFailed -= HandleDragFailed; EventsRootWidget.DragDataDelete -= HandleDragDataDelete; EventsRootWidget.DragBegin -= HandleDragBegin; // This event is subscribed only when manualy starting a drag ApplicationContext.InvokeUserCode (delegate { eventSink.OnDragFinished (new DragFinishedEventArgs (delete)); }); } public void SetDragTarget (TransferDataType[] types, DragDropAction dragAction) { DragDropInfo.DestDragAction = ConvertDragAction (dragAction); var table = Util.BuildTargetTable (types); DragDropInfo.ValidDropTypes = (Gtk.TargetEntry[]) table; OnSetDragTarget (DragDropInfo.ValidDropTypes, DragDropInfo.DestDragAction); } protected virtual void OnSetDragTarget (Gtk.TargetEntry[] table, Gdk.DragAction actions) { AllocEventBox (); Gtk.Drag.DestSet (EventsRootWidget, Gtk.DestDefaults.Highlight, table, actions); } public void SetDragSource (TransferDataType[] types, DragDropAction dragAction) { AllocEventBox (); DragDropInfo.SourceDragAction = ConvertDragAction (dragAction); var table = Util.BuildTargetTable (types); OnSetDragSource (Gdk.ModifierType.Button1Mask, (Gtk.TargetEntry[]) table, DragDropInfo.SourceDragAction); } protected virtual void OnSetDragSource (Gdk.ModifierType modifierType, Gtk.TargetEntry[] table, Gdk.DragAction actions) { Gtk.Drag.SourceSet (EventsRootWidget, modifierType, table, actions); } Gdk.DragAction ConvertDragAction (DragDropAction dragAction) { Gdk.DragAction action = (Gdk.DragAction)0; if ((dragAction & DragDropAction.Copy) != 0) action |= Gdk.DragAction.Copy; if ((dragAction & DragDropAction.Move) != 0) action |= Gdk.DragAction.Move; if ((dragAction & DragDropAction.Link) != 0) action |= Gdk.DragAction.Link; return action; } DragDropAction ConvertDragAction (Gdk.DragAction dragAction) { DragDropAction action = (DragDropAction)0; if ((dragAction & Gdk.DragAction.Copy) != 0) action |= DragDropAction.Copy; if ((dragAction & Gdk.DragAction.Move) != 0) action |= DragDropAction.Move; if ((dragAction & Gdk.DragAction.Link) != 0) action |= DragDropAction.Link; return action; } } public interface IGtkWidgetBackend { Gtk.Widget Widget { get; } } class WidgetPlacementWrapper: Gtk.Alignment, IConstraintProvider { public WidgetPlacementWrapper (): base (0, 0, 1, 1) { } public void UpdatePlacement (Xwt.Widget widget) { LeftPadding = (uint)widget.MarginLeft; RightPadding = (uint)widget.MarginRight; TopPadding = (uint)widget.MarginTop; BottomPadding = (uint)widget.MarginBottom; Xalign = (float) widget.HorizontalPlacement.GetValue (); Yalign = (float) widget.VerticalPlacement.GetValue (); Xscale = (widget.HorizontalPlacement == WidgetPlacement.Fill) ? 1 : 0; Yscale = (widget.VerticalPlacement == WidgetPlacement.Fill) ? 1 : 0; } #region IConstraintProvider implementation public void GetConstraints (Gtk.Widget target, out SizeConstraint width, out SizeConstraint height) { if (Parent is IConstraintProvider) ((IConstraintProvider)Parent).GetConstraints (this, out width, out height); else width = height = SizeConstraint.Unconstrained; } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Text; using System.Collections.Generic; public class BringUpTest { const int Pass = 100; const int Fail = -1; public static int Main() { if (TestInterfaceCache() == Fail) return Fail; if (TestMultipleInterfaces() == Fail) return Fail; if (TestArrayInterfaces() == Fail) return Fail; if (TestVariantInterfaces() == Fail) return Fail; if (TestSpecialArrayInterfaces() == Fail) return Fail; return Pass; } #region Interface Dispatch Cache Test private static int TestInterfaceCache() { MyInterface[] itfs = new MyInterface[50]; itfs[0] = new Foo0(); itfs[1] = new Foo1(); itfs[2] = new Foo2(); itfs[3] = new Foo3(); itfs[4] = new Foo4(); itfs[5] = new Foo5(); itfs[6] = new Foo6(); itfs[7] = new Foo7(); itfs[8] = new Foo8(); itfs[9] = new Foo9(); itfs[10] = new Foo10(); itfs[11] = new Foo11(); itfs[12] = new Foo12(); itfs[13] = new Foo13(); itfs[14] = new Foo14(); itfs[15] = new Foo15(); itfs[16] = new Foo16(); itfs[17] = new Foo17(); itfs[18] = new Foo18(); itfs[19] = new Foo19(); itfs[20] = new Foo20(); itfs[21] = new Foo21(); itfs[22] = new Foo22(); itfs[23] = new Foo23(); itfs[24] = new Foo24(); itfs[25] = new Foo25(); itfs[26] = new Foo26(); itfs[27] = new Foo27(); itfs[28] = new Foo28(); itfs[29] = new Foo29(); itfs[30] = new Foo30(); itfs[31] = new Foo31(); itfs[32] = new Foo32(); itfs[33] = new Foo33(); itfs[34] = new Foo34(); itfs[35] = new Foo35(); itfs[36] = new Foo36(); itfs[37] = new Foo37(); itfs[38] = new Foo38(); itfs[39] = new Foo39(); itfs[40] = new Foo40(); itfs[41] = new Foo41(); itfs[42] = new Foo42(); itfs[43] = new Foo43(); itfs[44] = new Foo44(); itfs[45] = new Foo45(); itfs[46] = new Foo46(); itfs[47] = new Foo47(); itfs[48] = new Foo48(); itfs[49] = new Foo49(); StringBuilder sb = new StringBuilder(); int counter = 0; for (int i = 0; i < 50; i++) { sb.Append(itfs[i].GetAString()); counter += itfs[i].GetAnInt(); } string expected = "Foo0Foo1Foo2Foo3Foo4Foo5Foo6Foo7Foo8Foo9Foo10Foo11Foo12Foo13Foo14Foo15Foo16Foo17Foo18Foo19Foo20Foo21Foo22Foo23Foo24Foo25Foo26Foo27Foo28Foo29Foo30Foo31Foo32Foo33Foo34Foo35Foo36Foo37Foo38Foo39Foo40Foo41Foo42Foo43Foo44Foo45Foo46Foo47Foo48Foo49"; if (!expected.Equals(sb.ToString())) { Console.WriteLine("Concatenating strings from interface calls failed."); Console.Write("Expected: "); Console.WriteLine(expected); Console.Write(" Actual: "); Console.WriteLine(sb.ToString()); return Fail; } if (counter != 1225) { Console.WriteLine("Summing ints from interface calls failed."); Console.WriteLine("Expected: 1225"); Console.Write("Actual: "); Console.WriteLine(counter); return Fail; } return 100; } interface MyInterface { int GetAnInt(); string GetAString(); } class Foo0 : MyInterface { public int GetAnInt() { return 0; } public string GetAString() { return "Foo0"; } } class Foo1 : MyInterface { public int GetAnInt() { return 1; } public string GetAString() { return "Foo1"; } } class Foo2 : MyInterface { public int GetAnInt() { return 2; } public string GetAString() { return "Foo2"; } } class Foo3 : MyInterface { public int GetAnInt() { return 3; } public string GetAString() { return "Foo3"; } } class Foo4 : MyInterface { public int GetAnInt() { return 4; } public string GetAString() { return "Foo4"; } } class Foo5 : MyInterface { public int GetAnInt() { return 5; } public string GetAString() { return "Foo5"; } } class Foo6 : MyInterface { public int GetAnInt() { return 6; } public string GetAString() { return "Foo6"; } } class Foo7 : MyInterface { public int GetAnInt() { return 7; } public string GetAString() { return "Foo7"; } } class Foo8 : MyInterface { public int GetAnInt() { return 8; } public string GetAString() { return "Foo8"; } } class Foo9 : MyInterface { public int GetAnInt() { return 9; } public string GetAString() { return "Foo9"; } } class Foo10 : MyInterface { public int GetAnInt() { return 10; } public string GetAString() { return "Foo10"; } } class Foo11 : MyInterface { public int GetAnInt() { return 11; } public string GetAString() { return "Foo11"; } } class Foo12 : MyInterface { public int GetAnInt() { return 12; } public string GetAString() { return "Foo12"; } } class Foo13 : MyInterface { public int GetAnInt() { return 13; } public string GetAString() { return "Foo13"; } } class Foo14 : MyInterface { public int GetAnInt() { return 14; } public string GetAString() { return "Foo14"; } } class Foo15 : MyInterface { public int GetAnInt() { return 15; } public string GetAString() { return "Foo15"; } } class Foo16 : MyInterface { public int GetAnInt() { return 16; } public string GetAString() { return "Foo16"; } } class Foo17 : MyInterface { public int GetAnInt() { return 17; } public string GetAString() { return "Foo17"; } } class Foo18 : MyInterface { public int GetAnInt() { return 18; } public string GetAString() { return "Foo18"; } } class Foo19 : MyInterface { public int GetAnInt() { return 19; } public string GetAString() { return "Foo19"; } } class Foo20 : MyInterface { public int GetAnInt() { return 20; } public string GetAString() { return "Foo20"; } } class Foo21 : MyInterface { public int GetAnInt() { return 21; } public string GetAString() { return "Foo21"; } } class Foo22 : MyInterface { public int GetAnInt() { return 22; } public string GetAString() { return "Foo22"; } } class Foo23 : MyInterface { public int GetAnInt() { return 23; } public string GetAString() { return "Foo23"; } } class Foo24 : MyInterface { public int GetAnInt() { return 24; } public string GetAString() { return "Foo24"; } } class Foo25 : MyInterface { public int GetAnInt() { return 25; } public string GetAString() { return "Foo25"; } } class Foo26 : MyInterface { public int GetAnInt() { return 26; } public string GetAString() { return "Foo26"; } } class Foo27 : MyInterface { public int GetAnInt() { return 27; } public string GetAString() { return "Foo27"; } } class Foo28 : MyInterface { public int GetAnInt() { return 28; } public string GetAString() { return "Foo28"; } } class Foo29 : MyInterface { public int GetAnInt() { return 29; } public string GetAString() { return "Foo29"; } } class Foo30 : MyInterface { public int GetAnInt() { return 30; } public string GetAString() { return "Foo30"; } } class Foo31 : MyInterface { public int GetAnInt() { return 31; } public string GetAString() { return "Foo31"; } } class Foo32 : MyInterface { public int GetAnInt() { return 32; } public string GetAString() { return "Foo32"; } } class Foo33 : MyInterface { public int GetAnInt() { return 33; } public string GetAString() { return "Foo33"; } } class Foo34 : MyInterface { public int GetAnInt() { return 34; } public string GetAString() { return "Foo34"; } } class Foo35 : MyInterface { public int GetAnInt() { return 35; } public string GetAString() { return "Foo35"; } } class Foo36 : MyInterface { public int GetAnInt() { return 36; } public string GetAString() { return "Foo36"; } } class Foo37 : MyInterface { public int GetAnInt() { return 37; } public string GetAString() { return "Foo37"; } } class Foo38 : MyInterface { public int GetAnInt() { return 38; } public string GetAString() { return "Foo38"; } } class Foo39 : MyInterface { public int GetAnInt() { return 39; } public string GetAString() { return "Foo39"; } } class Foo40 : MyInterface { public int GetAnInt() { return 40; } public string GetAString() { return "Foo40"; } } class Foo41 : MyInterface { public int GetAnInt() { return 41; } public string GetAString() { return "Foo41"; } } class Foo42 : MyInterface { public int GetAnInt() { return 42; } public string GetAString() { return "Foo42"; } } class Foo43 : MyInterface { public int GetAnInt() { return 43; } public string GetAString() { return "Foo43"; } } class Foo44 : MyInterface { public int GetAnInt() { return 44; } public string GetAString() { return "Foo44"; } } class Foo45 : MyInterface { public int GetAnInt() { return 45; } public string GetAString() { return "Foo45"; } } class Foo46 : MyInterface { public int GetAnInt() { return 46; } public string GetAString() { return "Foo46"; } } class Foo47 : MyInterface { public int GetAnInt() { return 47; } public string GetAString() { return "Foo47"; } } class Foo48 : MyInterface { public int GetAnInt() { return 48; } public string GetAString() { return "Foo48"; } } class Foo49 : MyInterface { public int GetAnInt() { return 49; } public string GetAString() { return "Foo49"; } } #endregion #region Implicit Interface Test private static int TestMultipleInterfaces() { TestClass<int> testInt = new TestClass<int>(5); MyInterface myInterface = testInt as MyInterface; if (!myInterface.GetAString().Equals("TestClass")) { Console.Write("On type TestClass, MyInterface.GetAString() returned "); Console.Write(myInterface.GetAString()); Console.WriteLine(" Expected: TestClass"); return Fail; } if (myInterface.GetAnInt() != 1) { Console.Write("On type TestClass, MyInterface.GetAnInt() returned "); Console.Write(myInterface.GetAnInt()); Console.WriteLine(" Expected: 1"); return Fail; } Interface<int> itf = testInt as Interface<int>; if (itf.GetT() != 5) { Console.Write("On type TestClass, Interface<int>::GetT() returned "); Console.Write(itf.GetT()); Console.WriteLine(" Expected: 5"); return Fail; } return Pass; } interface Interface<T> { T GetT(); } class TestClass<T> : MyInterface, Interface<T> { T _t; public TestClass(T t) { _t = t; } public T GetT() { return _t; } public int GetAnInt() { return 1; } public string GetAString() { return "TestClass"; } } #endregion #region Array Interfaces Test private static int TestArrayInterfaces() { { object stringArray = new string[] { "A", "B", "C", "D" }; Console.WriteLine("Testing IEnumerable<T> on array..."); string result = String.Empty; foreach (var s in (System.Collections.Generic.IEnumerable<string>)stringArray) result += s; if (result != "ABCD") { Console.WriteLine("Failed."); return Fail; } } { object stringArray = new string[] { "A", "B", "C", "D" }; Console.WriteLine("Testing IEnumerable on array..."); string result = String.Empty; foreach (var s in (System.Collections.IEnumerable)stringArray) result += s; if (result != "ABCD") { Console.WriteLine("Failed."); return Fail; } } { object intArray = new int[5, 5]; Console.WriteLine("Testing IList on MDArray..."); if (((System.Collections.IList)intArray).Count != 25) { Console.WriteLine("Failed."); return Fail; } } return Pass; } #endregion #region Variant interface tests interface IContravariantInterface<in T> { string DoContravariant(T value); } interface ICovariantInterface<out T> { T DoCovariant(object value); } class TypeWithVariantInterfaces<T> : IContravariantInterface<T>, ICovariantInterface<T> { public string DoContravariant(T value) { return value.ToString(); } public T DoCovariant(object value) { return value is T ? (T)value : default(T); } } static IContravariantInterface<string> s_contravariantObject = new TypeWithVariantInterfaces<object>(); static ICovariantInterface<object> s_covariantObject = new TypeWithVariantInterfaces<string>(); static IEnumerable<int> s_arrayCovariantObject = (IEnumerable<int>)(object)new uint[] { 5, 10, 15 }; private static int TestVariantInterfaces() { if (s_contravariantObject.DoContravariant("Hello") != "Hello") return Fail; if (s_covariantObject.DoCovariant("World") as string != "World") return Fail; int sum = 0; foreach (var e in s_arrayCovariantObject) sum += e; if (sum != 30) return Fail; return Pass; } class SpecialArrayBase { } class SpecialArrayDerived : SpecialArrayBase { } // NOTE: ICollection is not a variant interface, but arrays can cast with it as if it was static ICollection<SpecialArrayBase> s_specialDerived = new SpecialArrayDerived[42]; static ICollection<uint> s_specialInt = (ICollection<uint>)(object)new int[85]; private static int TestSpecialArrayInterfaces() { if (s_specialDerived.Count != 42) return Fail; if (s_specialInt.Count != 85) return Fail; return Pass; } #endregion }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gax = Google.Api.Gax; using gcav = Google.Cloud.AutoML.V1; using sys = System; namespace Google.Cloud.AutoML.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}/modelEvaluations/{model_evaluation}</c>. /// </summary> ProjectLocationModelModelEvaluation = 1, } private static gax::PathTemplate s_projectLocationModelModelEvaluation = new gax::PathTemplate("projects/{project}/locations/{location}/models/{model}/modelEvaluations/{model_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}/modelEvaluations/{model_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="modelEvaluationId">The <c>ModelEvaluation</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 FromProjectLocationModelModelEvaluation(string projectId, string locationId, string modelId, string modelEvaluationId) => new ModelEvaluationName(ResourceNameType.ProjectLocationModelModelEvaluation, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), modelId: gax::GaxPreconditions.CheckNotNullOrEmpty(modelId, nameof(modelId)), modelEvaluationId: gax::GaxPreconditions.CheckNotNullOrEmpty(modelEvaluationId, nameof(modelEvaluationId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="ModelEvaluationName"/> with pattern /// <c>projects/{project}/locations/{location}/models/{model}/modelEvaluations/{model_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="modelEvaluationId">The <c>ModelEvaluation</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}/modelEvaluations/{model_evaluation}</c>. /// </returns> public static string Format(string projectId, string locationId, string modelId, string modelEvaluationId) => FormatProjectLocationModelModelEvaluation(projectId, locationId, modelId, modelEvaluationId); /// <summary> /// Formats the IDs into the string representation of this <see cref="ModelEvaluationName"/> with pattern /// <c>projects/{project}/locations/{location}/models/{model}/modelEvaluations/{model_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="modelEvaluationId">The <c>ModelEvaluation</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}/modelEvaluations/{model_evaluation}</c>. /// </returns> public static string FormatProjectLocationModelModelEvaluation(string projectId, string locationId, string modelId, string modelEvaluationId) => s_projectLocationModelModelEvaluation.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(modelId, nameof(modelId)), gax::GaxPreconditions.CheckNotNullOrEmpty(modelEvaluationId, nameof(modelEvaluationId))); /// <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}/modelEvaluations/{model_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}/modelEvaluations/{model_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}/modelEvaluations/{model_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}/modelEvaluations/{model_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_projectLocationModelModelEvaluation.TryParseName(modelEvaluationName, out resourceName)) { result = FromProjectLocationModelModelEvaluation(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 locationId = null, string modelId = null, string modelEvaluationId = null, string projectId = null) { Type = type; UnparsedResource = unparsedResourceName; LocationId = locationId; ModelId = modelId; ModelEvaluationId = modelEvaluationId; 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}/modelEvaluations/{model_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="modelEvaluationId">The <c>ModelEvaluation</c> ID. Must not be <c>null</c> or empty.</param> public ModelEvaluationName(string projectId, string locationId, string modelId, string modelEvaluationId) : this(ResourceNameType.ProjectLocationModelModelEvaluation, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), modelId: gax::GaxPreconditions.CheckNotNullOrEmpty(modelId, nameof(modelId)), modelEvaluationId: gax::GaxPreconditions.CheckNotNullOrEmpty(modelEvaluationId, nameof(modelEvaluationId))) { } /// <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>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>ModelEvaluation</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource /// name. /// </summary> public string ModelEvaluationId { 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.ProjectLocationModelModelEvaluation: return s_projectLocationModelModelEvaluation.Expand(ProjectId, LocationId, ModelId, ModelEvaluationId); 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 Corporation. All rights reserved. // Licensed under the MIT License. using Newtonsoft.Json.Linq; using ReactNative.Reflection; using ReactNative.UIManager; using ReactNative.UIManager.Annotations; using ReactNative.UIManager.Events; using ReactNative.Views.Extensions; using ReactNative.Views.Text; using System; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Input; using System.Windows.Media; namespace ReactNative.Views.TextInput { /// <summary> /// View manager for <see cref="ReactTextBox"/>. /// </summary> internal class ReactTextInputManager : BaseViewManager<ReactTextBox, ReactTextInputShadowNode> { internal const int FocusTextInput = 1; internal const int BlurTextInput = 2; private bool? _blurOnSubmit; internal static readonly Color DefaultTextBoxBorder = Color.FromArgb(255, 122, 122, 122); internal static readonly Color DefaultPlaceholderTextColor = Color.FromArgb(255, 0, 0, 0); /// <summary> /// The name of the view manager. /// </summary> public override string Name => "RCTTextBox"; /// <summary> /// The exported custom bubbling event types. /// </summary> public override JObject CustomBubblingEventTypeConstants { get { return new JObject { { "topSubmitEditing", new JObject { { "phasedRegistrationNames", new JObject { { "bubbled" , "onSubmitEditing" }, { "captured" , "onSubmitEditingCapture" } } } } }, { "topEndEditing", new JObject { { "phasedRegistrationNames", new JObject { { "bubbled" , "onEndEditing" }, { "captured" , "onEndEditingCapture" } } } } } }; } } /// <summary> /// The commands map for the <see cref="ReactTextInputManager"/>. /// </summary> public override JObject ViewCommandsMap { get { return new JObject { { "focusTextInput", FocusTextInput }, { "blurTextInput", BlurTextInput }, }; } } /// <summary> /// Sets the font size on the <see cref="ReactTextBox"/>. /// </summary> /// <param name="view">The view instance.</param> /// <param name="fontSize">The font size.</param> [ReactProp(ViewProps.FontSize)] public void SetFontSize(ReactTextBox view, double fontSize) { view.FontSize = fontSize; } /// <summary> /// Sets the font color for the node. /// </summary> /// <param name="view">The view instance.</param> /// <param name="color">The masked color value.</param> [ReactProp(ViewProps.Color, CustomType = "Color")] public void SetColor(ReactTextBox view, uint? color) { view.Foreground = color.HasValue ? new SolidColorBrush(ColorHelpers.Parse(color.Value)) : null; } /// <summary> /// Sets the font family for the node. /// </summary> /// <param name="view">The view instance.</param> /// <param name="familyName">The font family.</param> [ReactProp(ViewProps.FontFamily)] public void SetFontFamily(ReactTextBox view, string familyName) { view.FontFamily = familyName != null ? new FontFamily(familyName) : new FontFamily(); } /// <summary> /// Sets the font weight for the node. /// </summary> /// <param name="view">The view instance.</param> /// <param name="fontWeightString">The font weight string.</param> [ReactProp(ViewProps.FontWeight)] public void SetFontWeight(ReactTextBox view, string fontWeightString) { var fontWeight = FontStyleHelpers.ParseFontWeight(fontWeightString); view.FontWeight = fontWeight ?? FontWeights.Normal; } /// <summary> /// Sets the font style for the node. /// </summary> /// <param name="view">The view instance.</param> /// <param name="fontStyleString">The font style string.</param> [ReactProp(ViewProps.FontStyle)] public void SetFontStyle(ReactTextBox view, string fontStyleString) { var fontStyle = EnumHelpers.ParseNullable<FontStyle>(fontStyleString); view.FontStyle = fontStyle ?? new FontStyle(); } /// <summary> /// Sets whether to track selection changes on the <see cref="ReactTextBox"/>. /// </summary> /// <param name="view">The view instance.</param> /// <param name="onSelectionChange">The indicator.</param> [ReactProp("onSelectionChange", DefaultBoolean = false)] public void SetOnSelectionChange(ReactTextBox view, bool onSelectionChange) { view.OnSelectionChange = onSelectionChange; } /// <summary> /// Sets the default text placeholder prop on the <see cref="ReactTextBox"/>. /// </summary> /// <param name="view">The view instance.</param> /// <param name="placeholder">The placeholder text.</param> [ReactProp("placeholder")] public void SetPlaceholder(ReactTextBox view, string placeholder) { PlaceholderAdorner.SetText(view, placeholder); } /// <summary> /// Sets the placeholderTextColor prop on the <see cref="ReactTextBox"/>. /// </summary> /// <param name="view">The view instance.</param> /// <param name="color">The placeholder text color.</param> [ReactProp("placeholderTextColor", CustomType = "Color")] public void SetPlaceholderTextColor(ReactTextBox view, uint? color) { var brush = color.HasValue ? new SolidColorBrush(ColorHelpers.Parse(color.Value)) : new SolidColorBrush(DefaultPlaceholderTextColor); PlaceholderAdorner.SetTextColor(view, brush); } /// <summary> /// Sets the border color for the <see cref="ReactTextBox"/>. /// </summary> /// <param name="view">The view instance</param> /// <param name="color">The masked color value.</param> [ReactProp(ViewProps.BorderColor, CustomType = "Color")] public void SetBorderColor(ReactTextBox view, uint? color) { view.BorderBrush = color.HasValue ? new SolidColorBrush(ColorHelpers.Parse(color.Value)) : new SolidColorBrush(DefaultTextBoxBorder); } /// <summary> /// Sets the background color for the <see cref="ReactTextBox"/>. /// </summary> /// <param name="view">The view instance.</param> /// <param name="color">The masked color value.</param> [ReactProp(ViewProps.BackgroundColor, CustomType = "Color")] public void SetBackgroundColor(ReactTextBox view, uint? color) { view.Background = color.HasValue ? new SolidColorBrush(ColorHelpers.Parse(color.Value)) : new SolidColorBrush(Colors.White); } /// <summary> /// Sets the selection color for the <see cref="ReactTextBox"/>. /// </summary> /// <param name="view">The view instance.</param> /// <param name="color">The masked color value.</param> [ReactProp("selectionColor", CustomType = "Color")] public void SetSelectionColor(ReactTextBox view, uint color) { view.SelectionBrush = new SolidColorBrush(ColorHelpers.Parse(color)); view.CaretBrush = new SolidColorBrush(ColorHelpers.Parse(color)); } /// <summary> /// Sets the caret index for the <see cref="ReactTextBox"/>. /// </summary> /// <param name="view">The view instance.</param> /// <param name="index">cursor position value.</param> [ReactProp("caretIndex")] public void SetCaretIndex(ReactTextBox view, int index) { view.CaretIndex = index; } /// <summary> /// Sets the text alignment prop on the <see cref="ReactTextBox"/>. /// </summary> /// <param name="view">The view instance.</param> /// <param name="alignment">The text alignment.</param> [ReactProp(ViewProps.TextAlign)] public void SetTextAlign(ReactTextBox view, string alignment) { view.TextAlignment = EnumHelpers.Parse<TextAlignment>(alignment); } /// <summary> /// Sets the text alignment prop on the <see cref="ReactTextBox"/>. /// </summary> /// <param name="view">The view instance.</param> /// <param name="alignment">The text alignment.</param> [ReactProp(ViewProps.TextAlignVertical)] public void SetTextVerticalAlign(ReactTextBox view, string alignment) { view.VerticalContentAlignment = EnumHelpers.Parse<VerticalAlignment>(alignment); } /// <summary> /// Sets the editablity prop on the <see cref="ReactTextBox"/>. /// </summary> /// <param name="view">The view instance.</param> /// <param name="editable">The editable flag.</param> [ReactProp("editable")] public void SetEditable(ReactTextBox view, bool editable) { view.IsEnabled = editable; } /// <summary> /// Sets whether the view is a tab stop. /// </summary> /// <param name="view">The view instance.</param> /// <param name="isTabStop"> /// <code>true</code> if the view is a tab stop, otherwise <code>false</code> (control can't get keyboard focus or accept keyboard input in this case). /// </param> [ReactProp("isTabStop")] public void SetIsTabStop(ReactTextBox view, bool isTabStop) { view.IsTabStop = isTabStop; } /// <summary> /// Sets the max character length prop on the <see cref="ReactTextBox"/>. /// </summary> /// <param name="view">The view instance.</param> /// <param name="maxCharLength">The max length.</param> [ReactProp("maxLength")] public void SetMaxLength(ReactTextBox view, int maxCharLength) { view.MaxLength = maxCharLength; } /// <summary> /// Sets whether to enable autocorrect on the <see cref="ReactTextBox"/>. /// </summary> /// <param name="view">The view instance.</param> /// <param name="autoCorrect">The autocorrect flag.</param> [ReactProp("autoCorrect")] public void SetAutoCorrect(ReactTextBox view, bool autoCorrect) { var checker = view.SpellCheck; checker.IsEnabled = autoCorrect; } /// <summary> /// Sets whether to enable multiline input on the <see cref="ReactTextBox"/>. /// </summary> /// <param name="view">The view instance.</param> /// <param name="multiline">The multiline flag.</param> [ReactProp("multiline", DefaultBoolean = false)] public void SetMultiline(ReactTextBox view, bool multiline) { view.AcceptsReturn = multiline; view.TextWrapping = multiline ? TextWrapping.Wrap : TextWrapping.NoWrap; if (_blurOnSubmit == null) { _blurOnSubmit = !multiline; } } /// <summary> /// Sets the keyboard type on the <see cref="ReactTextBox"/>. /// </summary> /// <param name="view">The view instance.</param> /// <param name="keyboardType">The keyboard type.</param> [ReactProp("keyboardType")] public void SetKeyboardType(ReactTextBox view, string keyboardType) { view.InputScope = null; if (keyboardType != null) { var inputScope = new InputScope(); inputScope.Names.Add( new InputScopeName( InputScopeHelpers.FromString(keyboardType))); view.InputScope = inputScope; } } /// <summary> /// Sets the border width for a <see cref="ReactTextBox"/>. /// </summary> /// <param name="view">The view instance.</param> /// <param name="width">The border width.</param> [ReactProp(ViewProps.BorderWidth)] public void SetBorderWidth(ReactTextBox view, int width) { view.BorderThickness = new Thickness(width); } /// <summary> /// Sets whether the text should be cleared on focus. /// </summary> /// <param name="view">The view instance.</param> /// <param name="clearTextOnFocus">The indicator.</param> [ReactProp("clearTextOnFocus")] public void SetClearTextOnFocus(ReactTextBox view, bool clearTextOnFocus) { view.ClearTextOnFocus = clearTextOnFocus; } /// <summary> /// Sets whether the text should be selected on focus. /// </summary> /// <param name="view">The view instance.</param> /// <param name="selectTextOnFocus">The indicator.</param> [ReactProp("selectTextOnFocus")] public void SetSelectTextOnFocus(ReactTextBox view, bool selectTextOnFocus) { view.SelectTextOnFocus = selectTextOnFocus; } /// <summary> /// Sets autoCapitalize property. Can tell TextInput to automatically capitalize certain characters /// </summary> /// <param name="view">The view instance.</param> /// <param name="mode">Mode <see cref="ReactNative.Views.TextInput.AutoCapitalizeMode"/></param> [ReactProp("autoCapitalize")] public void SetAutocapitalize(ReactTextBox view, string mode) { var binding = AutoCapitalize.GetBinder(AutoCapitalize.FromString(mode)); ; view.SetBinding(TextBox.TextProperty, binding); } [ReactProp("blurOnSubmit")] public void SetBlurOnSubmit(ReactTextBox view, bool blurOnSubmit) { _blurOnSubmit = blurOnSubmit; } /// <summary> /// Controls the visibility of the DeleteButton. /// </summary> /// <param name="view">The view instance.</param> /// <param name="clearButtonMode">Visibility of the DeleteButton.</param> [ReactProp("clearButtonMode")] public void SetClearButtonMode(ReactTextBox view, string clearButtonMode) { // Ignored, there's no X shown in WPF } /// <summary> /// Create the shadow node instance. /// </summary> /// <returns>The shadow node instance.</returns> public override ReactTextInputShadowNode CreateShadowNodeInstance() { return new ReactTextInputShadowNode(); } /// <summary> /// Implement this method to receive events/commands directly from /// JavaScript through the <see cref="ReactTextBox"/>. /// </summary> /// <param name="view"> /// The view instance that should receive the command. /// </param> /// <param name="commandId">Identifer for the command.</param> /// <param name="args">Optional arguments for the command.</param> public override void ReceiveCommand(ReactTextBox view, int commandId, JArray args) { if (commandId == FocusTextInput) { view.Focus(); } else if (commandId == BlurTextInput) { view.Blur(); } } /// <summary> /// Update the view with extra data. /// </summary> /// <param name="view">The view instance.</param> /// <param name="extraData">The extra data.</param> public override void UpdateExtraData(ReactTextBox view, object extraData) { var paddings = extraData as float[]; var textUpdate = default(Tuple<int, string>); if (paddings != null) { view.Padding = new Thickness( paddings[0], paddings[1], paddings[2], paddings[3]); } else if ((textUpdate = extraData as Tuple<int, string>) != null) { var javaScriptCount = textUpdate.Item1; if (javaScriptCount < view.CurrentEventCount) { return; } view.TextChanged -= OnTextChanged; var removeOnSelectionChange = view.OnSelectionChange; if (removeOnSelectionChange) { view.OnSelectionChange = false; } var text = textUpdate.Item2; var selectionStart = view.SelectionStart; var selectionLength = view.SelectionLength; var textLength = text?.Length ?? 0; var maxLength = textLength - selectionLength; view.Text = text ?? ""; view.SelectionStart = Math.Min(selectionStart, textLength); view.SelectionLength = Math.Min(selectionLength, maxLength < 0 ? 0 : maxLength); if (removeOnSelectionChange) { view.OnSelectionChange = true; } view.TextChanged += OnTextChanged; } } /// <summary> /// Called when view is detached from view hierarchy and allows for /// additional cleanup by the <see cref="ReactTextInputManager"/>. /// subclass. Unregister all event handlers for the <see cref="ReactTextBox"/>. /// </summary> /// <param name="reactContext">The React context.</param> /// <param name="view">The <see cref="ReactTextBox"/>.</param> public override void OnDropViewInstance(ThemedReactContext reactContext, ReactTextBox view) { base.OnDropViewInstance(reactContext, view); view.PreviewKeyDown -= OnKeyDown; view.LostFocus -= OnLostFocus; view.GotFocus -= OnGotFocus; view.TextChanged -= OnTextChanged; } public override void SetDimensions(ReactTextBox view, Dimensions dimensions) { base.SetDimensions(view, dimensions); view.MinWidth = dimensions.Width; view.MinHeight = dimensions.Height; } /// <summary> /// Returns the view instance for <see cref="ReactTextBox"/>. /// </summary> /// <param name="reactContext"></param> /// <returns></returns> protected override ReactTextBox CreateViewInstance(ThemedReactContext reactContext) { var view = new ReactTextBox { AcceptsReturn = false, }; var binding = AutoCapitalize.GetBinder(AutoCapitalizeMode.Sentences); view.SetBinding(TextBox.TextProperty, binding); return view; } /// <summary> /// Installing the textchanged event emitter on the <see cref="TextInput"/> Control. /// </summary> /// <param name="reactContext">The React context.</param> /// <param name="view">The <see cref="ReactTextBox"/> view instance.</param> protected override void AddEventEmitters(ThemedReactContext reactContext, ReactTextBox view) { base.AddEventEmitters(reactContext, view); view.TextChanged += OnTextChanged; view.GotFocus += OnGotFocus; view.LostFocus += OnLostFocus; view.PreviewKeyDown += OnKeyDown; } private void OnTextChanged(object sender, TextChangedEventArgs e) { var textBox = (ReactTextBox)sender; textBox.GetReactContext() .GetNativeModule<UIManagerModule>() .EventDispatcher .DispatchEvent( new ReactTextChangedEvent( textBox.GetTag(), textBox.Text, textBox.CurrentEventCount)); } private void OnGotFocus(object sender, RoutedEventArgs e) { var textBox = (ReactTextBox)sender; textBox.GetReactContext() .GetNativeModule<UIManagerModule>() .EventDispatcher .DispatchEvent( new FocusEvent(textBox.GetTag())); } private void OnLostFocus(object sender, RoutedEventArgs e) { var textBox = (ReactTextBox)sender; var eventDispatcher = textBox.GetReactContext() .GetNativeModule<UIManagerModule>() .EventDispatcher; eventDispatcher.DispatchEvent( new BlurEvent(textBox.GetTag())); eventDispatcher.DispatchEvent( new ReactTextInputEndEditingEvent( textBox.GetTag(), textBox.Text)); } private void OnKeyDown(object sender, KeyEventArgs e) { var shiftModifier = (Keyboard.Modifiers & ModifierKeys.Shift) == ModifierKeys.Shift; var controlModifier = (Keyboard.Modifiers & ModifierKeys.Control) == ModifierKeys.Control; var blurOnSubmit = (_blurOnSubmit.HasValue && _blurOnSubmit.Value); var textBox = (ReactTextBox)sender; if (e.Key == Key.Enter && !shiftModifier) { if (!textBox.AcceptsReturn || blurOnSubmit || controlModifier) { e.Handled = true; if (blurOnSubmit) { textBox.Blur(); } textBox.GetReactContext() .GetNativeModule<UIManagerModule>() .EventDispatcher .DispatchEvent( new ReactTextInputSubmitEditingEvent( textBox.GetTag(), textBox.Text)); } } if (!e.Handled) { textBox.GetReactContext() .GetNativeModule<UIManagerModule>() .EventDispatcher .DispatchEvent( new KeyEvent( KeyEvent.KeyPressEventString, textBox.GetTag(), e.Key)); } } } }
using System; using System.IO; using System.Diagnostics; using ID3Lib; namespace MP3Lib { /// <summary> /// Read mp3 frame header /// </summary> /// <remarks> /// additional info: http://www.codeproject.com/KB/audio-video/mpegaudioinfo.aspx /// </remarks> public class AudioFrameHeader { #region Enums /// <summary> /// stereo mode options /// </summary> public enum ChannelModeCode { /// <summary> /// 00 - full stereo (2 indepentent channels) /// </summary> Stereo = 0, /// <summary> /// 01 - joint stereo (stereo encoded as sum + difference) /// </summary> JointStereo = 1, /// <summary> /// 10 - two independent soundtracks (e.g. 2 languages) /// </summary> DualMono = 2, /// <summary> /// 11 - just one channel /// </summary> Mono = 3 } /// <summary> /// emphasis options /// </summary> public enum EmphasisCode { /// <summary> /// 00 - none /// </summary> None = 0, /// <summary> /// 01 - 50/15 ms /// </summary> E5015 = 1, /// <summary> /// 10 - reserved /// </summary> Reserved = 2, /// <summary> /// 11 - CCIT J.17 /// </summary> CCIT = 3 } #endregion #region Static Fields // bit rate, indexed by RawBitRate static uint[] V1L1 = new uint[] { 0, 32, 64, 96, 128, 160, 192, 224, 256, 288, 320, 352, 384, 416, 448, uint.MaxValue }; static uint[] V1L2 = new uint[] { 0, 32, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384, uint.MaxValue }; static uint[] V1L3 = new uint[] { 0, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, uint.MaxValue }; static uint[] V2L1 = new uint[] { 0, 32, 48, 56, 64, 80, 96, 112, 128, 144, 160, 176, 192, 224, 256, uint.MaxValue }; static uint[] V2L2L3 = new uint[] { 0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160, uint.MaxValue }; // Frequency sampling speed, indexed by RawSampleFreq static uint[] MPEG1 = new uint[] { 44100, 48000, 32000, uint.MaxValue }; static uint[] MPEG2 = new uint[] { 22050, 24000, 16000, uint.MaxValue }; static uint[] MPEG25 = new uint[] { 11025, 12000, 8000, uint.MaxValue }; // AudioFrame size in samples, indexed by RawLayer // 0 (illegal) 1=L3 2=L2 3=L1 static uint[] V1Size = new uint[] { uint.MaxValue, 1152, 1152, 384 }; static uint[] V2Size = new uint[] { uint.MaxValue, 576, 1152, 384 }; // Channel Mode names, indexed by ChannelMode static string[] MPEGChannelMode = new string[] { "Stereo", "Joint Stereo", "Dual channel (2 mono channels)", "Single channel (Mono)" }; // Layer names, indexed by RawLayer static string[] MPEGLayer = new string[] { "Reserved", "Layer III", "Layer II", "Layer I" }; // Emphasis names, indexed by Emphasis static string[] MPEGEmphasis = new string[] { "None", "50/15 ms", "Reserved", "CCIT J.17" }; #endregion #region Fields /// <summary> /// byte array containing at least 4 bytes of raw frame data /// </summary> protected byte[] _headerBuffer = null; #endregion #region Internal Properties //MPEG sync mark // 76543210 76543210 76543210 76543210 // 11111111 111..... ........ ........ //MPEG Audio version ID byte RawMpegVersion { get { return (byte)((_headerBuffer[1] & 0x18) >> 3); } } // ........ ...XX... ........ ........ //Layer description byte RawLayer { get { return (byte)((_headerBuffer[1] & 0x06)>>1); } } // ........ .....XX. ........ ........ //Protection bit 0 - Protected by CRC (16bit crc follows header) bool RawProtection { get { return (_headerBuffer[1] & 0x01)>0; } } // ........ .......X ........ ........ //Bitrate index byte RawBitRate { get { return (byte)((_headerBuffer[2] & 0xf0)>>4); } } // ........ ........ XXXX.... ........ //Sampling rate frequency index byte RawSampleFreq { get { return (byte)((_headerBuffer[2] & 0x0C)>>2); } } // ........ ........ ....XX.. ........ //Padding bit bool RawPadding { get { return (_headerBuffer[2] & 0x02)>0; } } // ........ ........ ......X. ........ //Private bit. bool RawPrivate { get { return (_headerBuffer[2] & 0x01)>0; } } // ........ ........ .......X ........ //Chanel Mode 00 - Stereo, 01 - JointStereo, 10 - Dual Mono, 11 - Mono byte RawChannelMode { get { return (byte)((_headerBuffer[3] & 0xC0)>>6); } } // ........ ........ ........ XX...... // Mode Extension - only if joint stereo byte RawModeExtension{ get { return (byte)((_headerBuffer[3] & 0x30) >> 4); } } // ........ ........ ........ ..XX.... // Copyright bool RawCopyright { get { return (_headerBuffer[3] & 0x08)>0; } } // ........ ........ ........ ....X... // Original bool RawOriginal { get { return (_headerBuffer[3] & 0x04)>0; } } // ........ ........ ........ .....X.. // Emphasis byte RawEmphasis { get { return (byte)((_headerBuffer[3] & 0x03)); } } // ........ ........ ........ ......XX #endregion #region Public Properties /// <summary> /// Simple validity check to verify all header fields are in legal ranges /// </summary> public bool Valid { get { return RawMpegVersion != 1 && RawLayer != 0 && RawBitRate != 15 && RawSampleFreq != 3 && RawBitRate != 15; } } /// <summary> /// mpeg version and layer /// </summary> public string VersionLayer { get { switch(RawMpegVersion) { case 0: // MPEG 2.5 { switch (RawLayer) { case 1: // Layer III return "MPEG-2.5 layer 3"; case 2: // Layer II and I return "MPEG-2.5 layer 2"; case 3: return "MPEG-2.5 layer 1"; default: throw new InvalidAudioFrameException("MPEG Version 2.5 Layer not recognised"); } } case 2: // MPEG 2 { switch(RawLayer) { case 1: // Layer III return "MPEG-2 layer 3"; case 2: // Layer II and I return "MPEG-2 layer 2"; case 3: return "MPEG-2 layer 1"; default: throw new InvalidAudioFrameException("MPEG Version 2 (ISO/IEC 13818-3) Layer not recognised"); } } case 3: // MPEG 1 { switch(RawLayer) { case 1: // Layer III return "MPEG-1 layer 3"; case 2: // Layer II and I return "MPEG-1 layer 2"; case 3: return "MPEG-1 layer 1"; default: throw new InvalidAudioFrameException("MPEG Version 1 (ISO/IEC 11172-3) Layer not recognised"); } } default: throw new InvalidAudioFrameException("MPEG Version not recognised"); } } } /// <summary> /// mpeg layer /// </summary> public uint Layer { get { switch( RawLayer ) { case 1: // Layer III return 3; case 2: // Layer II return 2; case 3: // Layer I return 1; default: throw new InvalidAudioFrameException("MPEG Layer not recognised"); } } } /// <summary> /// bitrate for this frame /// 0 for "free", i.e. free format. The free bitrate must remain constant, /// and must be lower than the maximum allowed bitrate. /// VBR encoders usually select a different one of the standard bitrates for each frame. /// </summary> public uint? BitRate { get { uint retval; switch(RawMpegVersion) { case 0: // MPEG 2.5 { switch (RawLayer) { case 1: // Layer III retval = V2L2L3[RawBitRate]; break; case 2: // Layer II retval = V2L2L3[RawBitRate]; break; case 3: // Layer I retval = V2L1[RawBitRate]; break; default: throw new InvalidAudioFrameException("MPEG Version 2.5 BitRate not recognised"); } break; } case 2: // MPEG 2 { switch(RawLayer) { case 1: // Layer III retval = V2L2L3[RawBitRate]; break; case 2: // Layer II retval = V2L2L3[RawBitRate]; break; case 3: // Layer I retval = V2L1[RawBitRate]; break; default: throw new InvalidAudioFrameException("MPEG Version 2 (ISO/IEC 13818-3) BitRate not recognised"); } break; } case 3: // MPEG 1 { switch(RawLayer) { case 1: // Layer III retval = V1L3[RawBitRate]; break; case 2: // Layer II retval = V1L2[RawBitRate]; break; case 3: // Layer I retval = V1L1[RawBitRate]; break; default: throw new InvalidAudioFrameException("MPEG Version 1 (ISO/IEC 11172-3) BitRate not recognised"); } break; } default: throw new InvalidAudioFrameException("MPEG Version not recognised"); } if (retval == uint.MaxValue) throw new InvalidAudioFrameException("MPEG BitRate not recognised"); else if (retval == 0) return null; else return retval * 1000; } } /// <summary> /// samples per second; same for every frame /// </summary> public uint SamplesPerSecond { get { uint retval; switch(RawMpegVersion) { case 0: // MPEG 2.5 retval = MPEG25[RawSampleFreq]; break; case 2: // MPEG 2 retval = MPEG2[RawSampleFreq]; break; case 3: // MPEG 1 retval = MPEG1[RawSampleFreq]; break; default: throw new InvalidAudioFrameException("MPEG Version not recognised"); } if (retval == uint.MaxValue) throw new InvalidAudioFrameException("MPEG SampleFreq not recognised"); else return retval; } } /// <summary> /// samples per frame; same for every frame /// </summary> public uint SamplesPerFrame { get { uint retval; switch (RawMpegVersion) { case 0: // MPEG 2.5 case 2: // MPEG 2 retval = V2Size[RawLayer]; break; case 3: // MPEG 1 retval = V1Size[RawLayer]; break; default: throw new InvalidAudioFrameException("MPEG Version not recognised"); } if (retval == uint.MaxValue) throw new InvalidAudioFrameException("MPEG Layer not recognised"); else return retval; } } /// <summary> /// seconds per frame; same for every frame /// e.g. 384 Samples/Frame / 44100 Samples/Second = 8.7mS each /// </summary> public double SecondsPerFrame { get { return (double)SamplesPerFrame / SamplesPerSecond; } } /// <summary> /// is it a "free" bitrate file? /// </summary> /// <remarks>most frames know how big they are, but free bitrate files can only know their frame length at the file level.</remarks> public bool IsFreeBitRate { get { return RawBitRate == 0; } } /// <summary> /// padding size; different for every frame /// </summary> /// <remarks> /// Padding is used to exactly fit the bitrate. /// As an example: 128kbps 44.1kHz layer II uses a lot of 418 bytes /// and some of 417 bytes long frames to get the exact 128k bitrate. /// For Layer I slot is 32 bits (4 bytes) long /// For Layer II and Layer III slot is 8 bits (1 byte) long. /// </remarks> public uint PaddingSize { get { if (RawPadding) { switch (RawMpegVersion) { case 0: // MPEG 2.5 case 2: // MPEG 2 return 1; case 3: // MPEG 1 return 4; default: throw new InvalidAudioFrameException("MPEG Version not recognised"); } } else return 0; } } /// <summary> /// length of this frame in bytes; different for every frame /// bitrate calculation includes the standard header bytes of normal audio frames already /// returns null for 'free' bitrate files /// because parsing the audio coefficients to work out how long it should be is too much work. /// If you want to know how long the frame is, ask the audio stream, not the header. /// </summary> public uint? FrameLengthInBytes { get { uint? bitRate = BitRate; if( bitRate == null ) { // free bitrate files are (just about) supported, but you can't tell how long a frame is from the header. // Instead, you have to read forwards until you find another header and measure the difference. return null; } switch (RawMpegVersion) { case 0: // MPEG 2.5 case 2: // MPEG 2 { switch (RawLayer) { case 1: // Layer III // FrameLengthInBytes = 72 * BitRate / SamplesPerSecond + Padding return 72 * bitRate.Value / SamplesPerSecond + (uint)(RawPadding ? 1 : 0); case 2: // Layer II // FrameLengthInBytes = 144 * BitRate / SamplesPerSecond + Padding return 144 * bitRate.Value / SamplesPerSecond + (uint)(RawPadding ? 1 : 0); case 3: // Layer I // FrameLengthInBytes = (12 * BitRate / SamplesPerSecond + Padding) * 4 return (12 * bitRate.Value / SamplesPerSecond + (uint)(RawPadding ? 1 : 0)) * 4; default: throw new InvalidAudioFrameException("MPEG 2 Layer not recognised"); } } case 3: // MPEG 1 { switch (RawLayer) { case 1: // Layer III // FrameLengthInBytes = 144 * BitRate / SamplesPerSecond + Padding return 144 * bitRate.Value / SamplesPerSecond + (uint)(RawPadding ? 1 : 0); case 2: // Layer II // FrameLengthInBytes = 144 * BitRate / SamplesPerSecond + Padding return 144 * bitRate.Value / SamplesPerSecond + (uint)(RawPadding ? 1 : 0); case 3: // Layer I // FrameLengthInBytes = (12 * BitRate / SamplesPerSecond + Padding) * 4 return (12 * bitRate.Value / SamplesPerSecond + (uint)(RawPadding ? 1 : 0)) * 4; default: throw new InvalidAudioFrameException("MPEG 1 Layer not recognised"); } } default: throw new InvalidAudioFrameException("MPEG Version not recognised"); } } } /// <summary> /// 'ideal' length of a frame at this bitrate; returns double, disregards padding. /// returns null for 'free' bitrate files /// because parsing the audio coefficients to work out how long it should be is too much work. /// If you want to know how long the frame should be, ask the audio stream, not the header. /// </summary> public double? IdealisedFrameLengthInBytes { get { uint? bitRate = BitRate; if( bitRate == null ) // free bitrate files are (just about) supported, but you can't tell how long a frame is from the header. // Instead, you have to read forwards until you find another header and measure the difference. return null; switch (RawMpegVersion) { case 0: // MPEG 2.5 case 2: // MPEG 2 { switch (RawLayer) { case 1: // Layer III // FrameLengthInBytes = 72 * BitRate / SamplesPerSecond + Padding return 72.0 * bitRate.Value / SamplesPerSecond; case 2: // Layer II // FrameLengthInBytes = 144 * BitRate / SamplesPerSecond + Padding return 144.0 * bitRate.Value / SamplesPerSecond; case 3: // Layer I // FrameLengthInBytes = (12 * BitRate / SamplesPerSecond + Padding) * 4 return 12.0 * bitRate.Value / SamplesPerSecond * 4; default: throw new InvalidAudioFrameException("MPEG 2 Layer not recognised"); } } case 3: // MPEG 1 { switch (RawLayer) { case 1: // Layer III // FrameLengthInBytes = 144 * BitRate / SamplesPerSecond + Padding return 144.0 * bitRate.Value / SamplesPerSecond; case 2: // Layer II // FrameLengthInBytes = 144 * BitRate / SamplesPerSecond + Padding return 144.0 * bitRate.Value / SamplesPerSecond; case 3: // Layer I // FrameLengthInBytes = (12 * BitRate / SamplesPerSecond + Padding) * 4 return 12.0 * bitRate.Value / SamplesPerSecond * 4; default: throw new InvalidAudioFrameException("MPEG 1 Layer not recognised"); } } default: throw new InvalidAudioFrameException("MPEG Version not recognised"); } } } /// <summary> /// checksum size /// Protection = 0 - Protected by CRC (16bit crc follows header), 1 - Not protected /// </summary> public uint ChecksumSize { get { if (!RawProtection) return 2; else return 0; } } /// <summary> /// channel config block size; different for every frame /// </summary> public uint SideInfoSize { get { switch (RawMpegVersion) { case 0: // MPEG 2.5 case 2: // MPEG 2 if( IsMono ) return 9; else return 17; case 3: // MPEG 1 if( IsMono ) return 17; else return 32; default: throw new InvalidAudioFrameException("MPEG Version not recognised"); } } } /// <summary> /// size of standard header /// NB not all these bytes will have been read in /// </summary> public uint HeaderSize { get { return 4 + ChecksumSize + SideInfoSize; } } /// <summary> /// Checksum /// </summary> public bool CRCs { get { return !RawProtection; } } /// <summary> /// Copyright /// </summary> public bool Copyright { get { return RawCopyright; } } /// <summary> /// Original /// </summary> public bool Original { get { return RawOriginal; } } /// <summary> /// Private /// </summary> public bool Private { get { return RawPrivate; } } /// <summary> /// mono; must be same for every frame /// </summary> public bool IsMono { get { return (ChannelModeCode)RawChannelMode == ChannelModeCode.Mono; } } /// <summary> /// stereo mode; different for every frame /// </summary> public ChannelModeCode ChannelMode { get { return (ChannelModeCode)RawChannelMode; } } /// <summary> /// emphasis; different for every frame /// </summary> public EmphasisCode Emphasis { get { return (EmphasisCode)RawEmphasis; } } /// <summary> /// some text to show we decoded it correctly /// </summary> public virtual string DebugString { get { //----MP3 header---- // MPEG-1 layer 3 // 44100Hz Joint Stereo // Frame: 418 bytes // CRCs: No, Copyrighted: No // Original: No, Emphasis: None string retval = String.Format("----MP3 header----\n {0}\n {1}Hz {2}\n Frame: {3} bytes\n CRCs: {4}, Copyrighted: {5}\n Original: {6}, Emphasis: {7}", VersionLayer, SamplesPerSecond, MPEGChannelMode[(int)ChannelMode], FrameLengthInBytes, CRCs ? "No" : "Yes", Copyright ? "No" : "Yes", Original ? "No" : "Yes", MPEGEmphasis[(int)Emphasis]); return retval; } } #endregion #region Construction /// <summary> /// construct MP3FrameHeader from 4 supplied bytes /// </summary> /// <param name="frameHeader"></param> public AudioFrameHeader(byte[] frameHeader) { _headerBuffer = frameHeader; } #endregion /// <summary> /// compare headers /// </summary> // return true if identical or related // return false if no similarities // (from an idea in CMPAHeader, http://www.codeproject.com/KB/audio-video/mpegaudioinfo.aspx) bool IsCompatible( AudioFrameHeader destHeader ) { // version change never possible if (destHeader.RawMpegVersion != RawMpegVersion) return false; // layer change never possible if (destHeader.RawLayer != RawLayer) return false; // sampling rate change never possible if (destHeader.RawSampleFreq != RawSampleFreq) return false; // from mono to stereo never possible if (destHeader.IsMono != IsMono) return false; if (destHeader.RawEmphasis != RawEmphasis) return false; return true; } } }
// This file is part of Wintermute Engine // For conditions of distribution and use, see copyright notice in license.txt // http://dead-code.org/redir.php?target=wme using System; using System.Collections.Generic; using System.Text; namespace DeadCode.WME.DefinitionFileParser { public class DefinitionFileItem { ////////////////////////////////////////////////////////////////////////// protected class Token { public string Value; public int Line; public Token(string Value, int Line) { this.Value = Value; this.Line = Line; } }; public string Name; public string Value; public int LineNum; public DefinitionFileItem Parent; public List<DefinitionFileItem> Children = new List<DefinitionFileItem>(); ////////////////////////////////////////////////////////////////////////// protected bool ParseStructure(ref List<Token> Tokens) { string Name; List<Token> Value; int LineNum; while(GetValue(ref Tokens, out Name, out Value, out LineNum)) { DefinitionFileItem item = new DefinitionFileItem(); item.Name = Name; item.Parent = this; item.LineNum = LineNum; Children.Add(item); string value; if(IsValue(Value, out value)) { item.Value = value; } else { while (Value.Count > 0) { item.ParseStructure(ref Value); } } } if (Tokens.Count == 0) return true; else { Tokens.Clear(); return false; } } ////////////////////////////////////////////////////////////////////////// private bool IsValue(List<Token> Value, out string value) { value = ""; if(Value.Count==1) { value = Value[0].Value; return true; } foreach(Token token in Value) { if (token.Value == "{" || token.Value == "}" || token.Value == "=") return false; else value += token.Value; } return true; } ////////////////////////////////////////////////////////////////////////// private bool GetValue(ref List<Token> Tokens, out string Name, out List<Token> Value, out int LineNum) { Name = null; Value = null; LineNum = 0; if (Tokens.Count < 3) return false; Value = new List<Token>(); int Index = 0; Name = Tokens[Index++].Value; LineNum = Tokens[Index].Line; // optional = Token Temp = Tokens[Index++]; if (Temp.Value == "=") Temp = Tokens[Index++]; if(Temp.Value == "{") { int Nest = 1; while(Index < Tokens.Count) { Temp = Tokens[Index++]; if (Temp.Value == "{") { Value.Add(Temp); Nest++; } else if(Temp.Value == "}") { Nest--; if (Nest == 0) break; Value.Add(Temp); } else Value.Add(Temp); } if (Nest != 0) throw new Exception("Syntax error"); } else { Value.Add(Temp); } List<Token> NewTokens = new List<Token>(); for(int i=Index; i<Tokens.Count; i++) { NewTokens.Add(Tokens[i]); } Tokens = NewTokens; return true; } ////////////////////////////////////////////////////////////////////////// public string GetString() { if (Value != null) return Value; else return ""; } ////////////////////////////////////////////////////////////////////////// public int GetInt() { try { return Convert.ToInt32(Value); } catch { return 0; } } ////////////////////////////////////////////////////////////////////////// public double GetDouble() { try { return Convert.ToDouble(Value); } catch { return 0.0f; } } ////////////////////////////////////////////////////////////////////////// public bool GetBool() { try { if (Value == null) return false; else return Value.ToLower() == "true" || Value.ToLower() == "yes" || Value.ToLower() == "true" || GetInt() > 0; } catch { return false; } } ////////////////////////////////////////////////////////////////////////// public int[] GetIntArray() { List<int> IntList = new List<int>(); string[] StrList = Value.Split(new char[] { ',' }); foreach(string Str in StrList) { int i; try { i = Convert.ToInt32(Str.Trim()); } catch { i = 0; } IntList.Add(i); } return IntList.ToArray(); } ////////////////////////////////////////////////////////////////////////// public override string ToString() { string Ret; Ret = Name; if (Children.Count > 0) Ret += "{ " + Children.Count.ToString() + " }"; else Ret += "=" + Value; return Ret; } } }
#region Apache License // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion using System; using System.Collections; using log4net.ObjectRenderer; using log4net.Core; using log4net.Util; using log4net.Plugin; namespace log4net.Repository { /// <summary> /// Base implementation of <see cref="ILoggerRepository"/> /// </summary> /// <remarks> /// <para> /// Default abstract implementation of the <see cref="ILoggerRepository"/> interface. /// </para> /// <para> /// Skeleton implementation of the <see cref="ILoggerRepository"/> interface. /// All <see cref="ILoggerRepository"/> types can extend this type. /// </para> /// </remarks> /// <author>Nicko Cadell</author> /// <author>Gert Driesen</author> public abstract class LoggerRepositorySkeleton : ILoggerRepository { #region Member Variables private string m_name; private RendererMap m_rendererMap; private PluginMap m_pluginMap; private LevelMap m_levelMap; private Level m_threshold; private bool m_configured; private ICollection m_configurationMessages; private event LoggerRepositoryShutdownEventHandler m_shutdownEvent; private event LoggerRepositoryConfigurationResetEventHandler m_configurationResetEvent; private event LoggerRepositoryConfigurationChangedEventHandler m_configurationChangedEvent; private PropertiesDictionary m_properties; #endregion #region Constructors /// <summary> /// Default Constructor /// </summary> /// <remarks> /// <para> /// Initializes the repository with default (empty) properties. /// </para> /// </remarks> protected LoggerRepositorySkeleton() : this(new PropertiesDictionary()) { } /// <summary> /// Construct the repository using specific properties /// </summary> /// <param name="properties">the properties to set for this repository</param> /// <remarks> /// <para> /// Initializes the repository with specified properties. /// </para> /// </remarks> protected LoggerRepositorySkeleton(PropertiesDictionary properties) { m_properties = properties; m_rendererMap = new RendererMap(); m_pluginMap = new PluginMap(this); m_levelMap = new LevelMap(); m_configurationMessages = EmptyCollection.Instance; m_configured = false; AddBuiltinLevels(); // Don't disable any levels by default. m_threshold = Level.All; } #endregion #region Implementation of ILoggerRepository /// <summary> /// The name of the repository /// </summary> /// <value> /// The string name of the repository /// </value> /// <remarks> /// <para> /// The name of this repository. The name is /// used to store and lookup the repositories /// stored by the <see cref="IRepositorySelector"/>. /// </para> /// </remarks> virtual public string Name { get { return m_name; } set { m_name = value; } } /// <summary> /// The threshold for all events in this repository /// </summary> /// <value> /// The threshold for all events in this repository /// </value> /// <remarks> /// <para> /// The threshold for all events in this repository /// </para> /// </remarks> virtual public Level Threshold { get { return m_threshold; } set { if (value != null) { m_threshold = value; } else { // Must not set threshold to null LogLog.Warn(declaringType, "LoggerRepositorySkeleton: Threshold cannot be set to null. Setting to ALL"); m_threshold = Level.All; } } } /// <summary> /// RendererMap accesses the object renderer map for this repository. /// </summary> /// <value> /// RendererMap accesses the object renderer map for this repository. /// </value> /// <remarks> /// <para> /// RendererMap accesses the object renderer map for this repository. /// </para> /// <para> /// The RendererMap holds a mapping between types and /// <see cref="IObjectRenderer"/> objects. /// </para> /// </remarks> virtual public RendererMap RendererMap { get { return m_rendererMap; } } /// <summary> /// The plugin map for this repository. /// </summary> /// <value> /// The plugin map for this repository. /// </value> /// <remarks> /// <para> /// The plugin map holds the <see cref="IPlugin"/> instances /// that have been attached to this repository. /// </para> /// </remarks> virtual public PluginMap PluginMap { get { return m_pluginMap; } } /// <summary> /// Get the level map for the Repository. /// </summary> /// <remarks> /// <para> /// Get the level map for the Repository. /// </para> /// <para> /// The level map defines the mappings between /// level names and <see cref="Level"/> objects in /// this repository. /// </para> /// </remarks> virtual public LevelMap LevelMap { get { return m_levelMap; } } /// <summary> /// Test if logger exists /// </summary> /// <param name="name">The name of the logger to lookup</param> /// <returns>The Logger object with the name specified</returns> /// <remarks> /// <para> /// Check if the named logger exists in the repository. If so return /// its reference, otherwise returns <c>null</c>. /// </para> /// </remarks> abstract public ILogger Exists(string name); /// <summary> /// Returns all the currently defined loggers in the repository /// </summary> /// <returns>All the defined loggers</returns> /// <remarks> /// <para> /// Returns all the currently defined loggers in the repository as an Array. /// </para> /// </remarks> abstract public ILogger[] GetCurrentLoggers(); /// <summary> /// Return a new logger instance /// </summary> /// <param name="name">The name of the logger to retrieve</param> /// <returns>The logger object with the name specified</returns> /// <remarks> /// <para> /// Return a new logger instance. /// </para> /// <para> /// If a logger of that name already exists, then it will be /// returned. Otherwise, a new logger will be instantiated and /// then linked with its existing ancestors as well as children. /// </para> /// </remarks> abstract public ILogger GetLogger(string name); /// <summary> /// Shutdown the repository /// </summary> /// <remarks> /// <para> /// Shutdown the repository. Can be overridden in a subclass. /// This base class implementation notifies the <see cref="ShutdownEvent"/> /// listeners and all attached plugins of the shutdown event. /// </para> /// </remarks> virtual public void Shutdown() { // Shutdown attached plugins foreach(IPlugin plugin in PluginMap.AllPlugins) { plugin.Shutdown(); } // Notify listeners OnShutdown(null); } /// <summary> /// Reset the repositories configuration to a default state /// </summary> /// <remarks> /// <para> /// Reset all values contained in this instance to their /// default state. /// </para> /// <para> /// Existing loggers are not removed. They are just reset. /// </para> /// <para> /// This method should be used sparingly and with care as it will /// block all logging until it is completed. /// </para> /// </remarks> virtual public void ResetConfiguration() { // Clear internal data structures m_rendererMap.Clear(); m_levelMap.Clear(); m_configurationMessages = EmptyCollection.Instance; // Add the predefined levels to the map AddBuiltinLevels(); Configured = false; // Notify listeners OnConfigurationReset(null); } /// <summary> /// Log the logEvent through this repository. /// </summary> /// <param name="logEvent">the event to log</param> /// <remarks> /// <para> /// This method should not normally be used to log. /// The <see cref="ILog"/> interface should be used /// for routine logging. This interface can be obtained /// using the <see cref="M:log4net.LogManager.GetLogger(string)"/> method. /// </para> /// <para> /// The <c>logEvent</c> is delivered to the appropriate logger and /// that logger is then responsible for logging the event. /// </para> /// </remarks> abstract public void Log(LoggingEvent logEvent); /// <summary> /// Flag indicates if this repository has been configured. /// </summary> /// <value> /// Flag indicates if this repository has been configured. /// </value> /// <remarks> /// <para> /// Flag indicates if this repository has been configured. /// </para> /// </remarks> virtual public bool Configured { get { return m_configured; } set { m_configured = value; } } /// <summary> /// Contains a list of internal messages captures during the /// last configuration. /// </summary> virtual public ICollection ConfigurationMessages { get { return m_configurationMessages; } set { m_configurationMessages = value; } } /// <summary> /// Event to notify that the repository has been shutdown. /// </summary> /// <value> /// Event to notify that the repository has been shutdown. /// </value> /// <remarks> /// <para> /// Event raised when the repository has been shutdown. /// </para> /// </remarks> public event LoggerRepositoryShutdownEventHandler ShutdownEvent { add { m_shutdownEvent += value; } remove { m_shutdownEvent -= value; } } /// <summary> /// Event to notify that the repository has had its configuration reset. /// </summary> /// <value> /// Event to notify that the repository has had its configuration reset. /// </value> /// <remarks> /// <para> /// Event raised when the repository's configuration has been /// reset to default. /// </para> /// </remarks> public event LoggerRepositoryConfigurationResetEventHandler ConfigurationReset { add { m_configurationResetEvent += value; } remove { m_configurationResetEvent -= value; } } /// <summary> /// Event to notify that the repository has had its configuration changed. /// </summary> /// <value> /// Event to notify that the repository has had its configuration changed. /// </value> /// <remarks> /// <para> /// Event raised when the repository's configuration has been changed. /// </para> /// </remarks> public event LoggerRepositoryConfigurationChangedEventHandler ConfigurationChanged { add { m_configurationChangedEvent += value; } remove { m_configurationChangedEvent -= value; } } /// <summary> /// Repository specific properties /// </summary> /// <value> /// Repository specific properties /// </value> /// <remarks> /// These properties can be specified on a repository specific basis /// </remarks> public PropertiesDictionary Properties { get { return m_properties; } } /// <summary> /// Returns all the Appenders that are configured as an Array. /// </summary> /// <returns>All the Appenders</returns> /// <remarks> /// <para> /// Returns all the Appenders that are configured as an Array. /// </para> /// </remarks> abstract public log4net.Appender.IAppender[] GetAppenders(); #endregion #region Private Static Fields /// <summary> /// The fully qualified type of the LoggerRepositorySkeleton class. /// </summary> /// <remarks> /// Used by the internal logger to record the Type of the /// log message. /// </remarks> private readonly static Type declaringType = typeof(LoggerRepositorySkeleton); #endregion Private Static Fields private void AddBuiltinLevels() { // Add the predefined levels to the map m_levelMap.Add(Level.Off); // Unrecoverable errors m_levelMap.Add(Level.Emergency); m_levelMap.Add(Level.Fatal); m_levelMap.Add(Level.Alert); // Recoverable errors m_levelMap.Add(Level.Critical); m_levelMap.Add(Level.Severe); m_levelMap.Add(Level.Error); m_levelMap.Add(Level.Warn); // Information m_levelMap.Add(Level.Notice); m_levelMap.Add(Level.Info); // Debug m_levelMap.Add(Level.Debug); m_levelMap.Add(Level.Fine); m_levelMap.Add(Level.Trace); m_levelMap.Add(Level.Finer); m_levelMap.Add(Level.Verbose); m_levelMap.Add(Level.Finest); m_levelMap.Add(Level.All); } /// <summary> /// Adds an object renderer for a specific class. /// </summary> /// <param name="typeToRender">The type that will be rendered by the renderer supplied.</param> /// <param name="rendererInstance">The object renderer used to render the object.</param> /// <remarks> /// <para> /// Adds an object renderer for a specific class. /// </para> /// </remarks> virtual public void AddRenderer(Type typeToRender, IObjectRenderer rendererInstance) { if (typeToRender == null) { throw new ArgumentNullException("typeToRender"); } if (rendererInstance == null) { throw new ArgumentNullException("rendererInstance"); } m_rendererMap.Put(typeToRender, rendererInstance); } /// <summary> /// Notify the registered listeners that the repository is shutting down /// </summary> /// <param name="e">Empty EventArgs</param> /// <remarks> /// <para> /// Notify any listeners that this repository is shutting down. /// </para> /// </remarks> protected virtual void OnShutdown(EventArgs e) { if (e == null) { e = EventArgs.Empty; } LoggerRepositoryShutdownEventHandler handler = m_shutdownEvent; if (handler != null) { handler(this, e); } } /// <summary> /// Notify the registered listeners that the repository has had its configuration reset /// </summary> /// <param name="e">Empty EventArgs</param> /// <remarks> /// <para> /// Notify any listeners that this repository's configuration has been reset. /// </para> /// </remarks> protected virtual void OnConfigurationReset(EventArgs e) { if (e == null) { e = EventArgs.Empty; } LoggerRepositoryConfigurationResetEventHandler handler = m_configurationResetEvent; if (handler != null) { handler(this, e); } } /// <summary> /// Notify the registered listeners that the repository has had its configuration changed /// </summary> /// <param name="e">Empty EventArgs</param> /// <remarks> /// <para> /// Notify any listeners that this repository's configuration has changed. /// </para> /// </remarks> protected virtual void OnConfigurationChanged(EventArgs e) { if (e == null) { e = EventArgs.Empty; } LoggerRepositoryConfigurationChangedEventHandler handler = m_configurationChangedEvent; if (handler != null) { handler(this, e); } } /// <summary> /// Raise a configuration changed event on this repository /// </summary> /// <param name="e">EventArgs.Empty</param> /// <remarks> /// <para> /// Applications that programmatically change the configuration of the repository should /// raise this event notification to notify listeners. /// </para> /// </remarks> public void RaiseConfigurationChanged(EventArgs e) { OnConfigurationChanged(e); } } }
//Distant Terrain Mod for Daggerfall-Unity //http://www.reddit.com/r/dftfu //http://www.dfworkshop.net/ //Author: Michael Rauter (a.k.a. Nystul) //License: MIT License (http://www.opensource.org/licenses/mit-license.php) // only define CREATE_* if you want to manually create the maps - usually this should not be necessary (and never do in executable build - only from editor - otherwise paths are wrong) //#define CREATE_PERSISTENT_LOCATION_RANGE_MAPS //#define CREATE_PERSISTENT_TREE_COVERAGE_MAP #define LOAD_TREE_COVERAGE_MAP using UnityEngine; using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Text; // for Encoding.UTF8 using DaggerfallConnect; using DaggerfallConnect.Arena2; using DaggerfallConnect.Utility; using DaggerfallWorkshop; using DaggerfallWorkshop.Game; using DaggerfallWorkshop.Utility; namespace DistantTerrain { /// <summary> /// </summary> public static class ImprovedWorldTerrain { const string filenameMapLocationRangeX = "mapLocationRangeX.bin"; const string filenameMapLocationRangeY = "mapLocationRangeY.bin"; const string filenameTreeCoverageMap = "mapTreeCoverage.bin"; const string out_filepathMapLocationRangeX = "Game/Addons/DistantTerrain/Resources/mapLocationRangeX_out.bin"; // only used on manual trigger in unity editor - never in executable - so it should be ok const string out_filepathMapLocationRangeY = "Game/Addons/DistantTerrain/Resources/mapLocationRangeY_out.bin"; // only used on manual trigger in unity editor - never in executable - so it should be ok const string out_filepathOutTreeCoverageMap = "Game/Addons/DistantTerrain/Resources/mapTreeCoverage_out.bin"; // only used on manual trigger in unity editor - never in executable - so it should be ok const float minDistanceFromWaterForExtraExaggeration = 3.0f; // when does exaggeration start in terms of how far does terrain have to be away from water const float exaggerationFactorWaterDistance = 0.075f; // 0.15f; //0.123f; //0.15f; // how strong is the distance from water incorporated into the multiplier const float extraExaggerationFactorLocationDistance = 0.0275f; // how strong is the distance from locations incorporated into the multiplier public const float maxHeightsExaggerationMultiplier = 25.0f; // this directly affects maxTerrainHeight in TerrainHelper.cs: maxTerrainHeight should be maxHeightsExaggerationMultiplier * baseHeightScale * 128 + noiseMapScale * 128 + extraNoiseScale // additional height noise based on climate public const float additionalHeightNoiseClimateOcean = 0.0f; public const float additionalHeightNoiseClimateDesert = 0.85f; //0.35f; public const float additionalHeightNoiseClimateDesert2 = 1.05f; public const float additionalHeightNoiseClimateMountain = 0.45f; public const float additionalHeightNoiseClimateRainforest = 0.77f; public const float additionalHeightNoiseClimateSwamp = 1.7f; public const float additionalHeightNoiseClimateSubtropical = 0.65f; public const float additionalHeightNoiseClimateMountainWoods = 1.05f; public const float additionalHeightNoiseClimateWoodlands = 0.59f; //0.45f; public const float additionalHeightNoiseClimateHauntedWoodlands = 0.25f; // 2D distance transform image - squared distance to water pixels of the world map private static float[] mapDistanceSquaredFromWater = null; // 2D distance transform image - squared distance to world map pixels with location private static float[] mapDistanceSquaredFromLocations = null; // map of multiplier values private static float[] mapMultipliers = null; // map with location positions private static byte[] mapLocations = null; // map with tree coverage private static byte[] mapTreeCoverage = null; private static byte[] mapLocationRangeX = null; private static byte[] mapLocationRangeY = null; // indicates if improved terrain is initialized (InitImprovedWorldTerrain() function was called) private static bool init = false; public static bool IsInit { get { return init; } } public static void Unload() { mapDistanceSquaredFromWater = null; mapDistanceSquaredFromLocations = null; mapMultipliers = null; mapLocations = null; mapTreeCoverage = null; mapLocationRangeX = null; mapLocationRangeY = null; //Resources.UnloadUnusedAssets(); //System.GC.Collect(); } /// <summary> /// Gets or sets map with location positions /// </summary> public static byte[] MapLocations { get { return mapLocations; } set { mapLocations = value; } } public static byte[] MapTreeCoverage { get { return mapTreeCoverage; } set { mapTreeCoverage = value; } } public static byte[] MapLocationRangeX { get { return mapLocationRangeX; } set { mapLocationRangeX = value; } } public static byte[] MapLocationRangeY { get { return mapLocationRangeY; } set { mapLocationRangeY = value; } } /// <summary> /// Gets or sets map with squared distance to water pixels. /// </summary> public static float[] MapDistanceSquaredFromWater { get { return mapDistanceSquaredFromWater; } set { mapDistanceSquaredFromWater = value; } } /// <summary> /// gets the distance to water for a given world map pixel. /// </summary> public static float getDistanceFromWater(int mapPixelX, int mapPixelY) { if (init) { return ((float)Math.Sqrt(mapDistanceSquaredFromWater[mapPixelY * WoodsFile.mapWidthValue + mapPixelX])); } else { DaggerfallUnity.LogMessage("ImprovedWorldTerrain not initialized.", true); return (1.0f); } } /// <summary> /// computes the height multiplier for a given world map pixel. /// </summary> public static float computeHeightMultiplier(int mapPixelX, int mapPixelY) { if (init) { if ((mapPixelX >= 0) && (mapPixelX < WoodsFile.mapWidthValue) && (mapPixelY >= 0) && (mapPixelY < WoodsFile.mapHeightValue)) { return (mapMultipliers[mapPixelY * WoodsFile.mapWidthValue + mapPixelX]); } else { return (1.0f); } } else { return (1.0f); } } private static float GetAdditionalHeightBasedOnClimate(int mapPixelX, int mapPixelY) { int worldClimate = DaggerfallUnity.Instance.ContentReader.MapFileReader.GetClimateIndex(mapPixelX, mapPixelY); float additionalHeightBasedOnClimate = 0.0f; switch (worldClimate) { case (int)MapsFile.Climates.Ocean: additionalHeightBasedOnClimate = additionalHeightNoiseClimateOcean; break; case (int)MapsFile.Climates.Desert: additionalHeightBasedOnClimate = additionalHeightNoiseClimateDesert; break; case (int)MapsFile.Climates.Desert2: additionalHeightBasedOnClimate = additionalHeightNoiseClimateDesert2; break; case (int)MapsFile.Climates.Mountain: additionalHeightBasedOnClimate = additionalHeightNoiseClimateMountain; break; case (int)MapsFile.Climates.Rainforest: additionalHeightBasedOnClimate = additionalHeightNoiseClimateRainforest; break; case (int)MapsFile.Climates.Swamp: additionalHeightBasedOnClimate = additionalHeightNoiseClimateSwamp; break; case (int)MapsFile.Climates.Subtropical: additionalHeightBasedOnClimate = additionalHeightNoiseClimateSubtropical; break; case (int)MapsFile.Climates.MountainWoods: additionalHeightBasedOnClimate = additionalHeightNoiseClimateMountainWoods; break; case (int)MapsFile.Climates.Woodlands: additionalHeightBasedOnClimate = additionalHeightNoiseClimateWoodlands; break; case (int)MapsFile.Climates.HauntedWoodlands: additionalHeightBasedOnClimate = additionalHeightNoiseClimateHauntedWoodlands; break; } return additionalHeightBasedOnClimate; } /// <summary> /// initializes resources (mapDistanceSquaredFromWater, mapDistanceSquaredFromLocations, mapMultipliers) and smoothes small height map /// </summary> public static void InitImprovedWorldTerrain(ContentReader contentReader) { if (!init) { #if CREATE_PERSISTENT_LOCATION_RANGE_MAPS { int width = WoodsFile.mapWidthValue; int height = WoodsFile.mapHeightValue; mapLocationRangeX = new byte[width * height]; mapLocationRangeY = new byte[width * height]; //int y = 204; //int x = 718; for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { //MapPixelData MapData = TerrainHelper.GetMapPixelData(contentReader, x, y); //if (MapData.hasLocation) //{ // int locationRangeX = (int)MapData.locationRect.xMax - (int)MapData.locationRect.xMin; // int locationRangeY = (int)MapData.locationRect.yMax - (int)MapData.locationRect.yMin; //} ContentReader.MapSummary mapSummary; int regionIndex = -1, mapIndex = -1; bool hasLocation = contentReader.HasLocation(x, y, out mapSummary); if (hasLocation) { regionIndex = mapSummary.RegionIndex; mapIndex = mapSummary.MapIndex; DFLocation location = contentReader.MapFileReader.GetLocation(regionIndex, mapIndex); byte locationRangeX = location.Exterior.ExteriorData.Width; byte locationRangeY = location.Exterior.ExteriorData.Height; mapLocationRangeX[y * width + x] = locationRangeX; mapLocationRangeY[y * width + x] = locationRangeY; } } } // save to files FileStream ostream; ostream = new FileStream(Path.Combine(Application.dataPath, out_filepathMapLocationRangeX), FileMode.Create, FileAccess.Write); BinaryWriter writerMapLocationRangeX = new BinaryWriter(ostream, Encoding.UTF8); writerMapLocationRangeX.Write(mapLocationRangeX, 0, width * height); writerMapLocationRangeX.Close(); ostream.Close(); ostream = new FileStream(Path.Combine(Application.dataPath, out_filepathMapLocationRangeY), FileMode.Create, FileAccess.Write); BinaryWriter writerMapLocationRangeY = new BinaryWriter(ostream, Encoding.UTF8); writerMapLocationRangeY.Write(mapLocationRangeY, 0, width * height); writerMapLocationRangeY.Close(); ostream.Close(); } #else { int width = WoodsFile.mapWidthValue; int height = WoodsFile.mapHeightValue; mapLocationRangeX = new byte[width * height]; mapLocationRangeY = new byte[width * height]; MemoryStream istream; TextAsset assetMapLocationRangeX = Resources.Load<TextAsset>(filenameMapLocationRangeX); if (assetMapLocationRangeX != null) { istream = new MemoryStream(assetMapLocationRangeX.bytes); BinaryReader readerMapLocationRangeX = new BinaryReader(istream, Encoding.UTF8); readerMapLocationRangeX.Read(mapLocationRangeX, 0, width * height); readerMapLocationRangeX.Close(); istream.Close(); } TextAsset assetMapLocationRangeY = Resources.Load<TextAsset>(filenameMapLocationRangeY); if (assetMapLocationRangeY) { istream = new MemoryStream(assetMapLocationRangeY.bytes); BinaryReader readerMapLocationRangeY = new BinaryReader(istream, Encoding.UTF8); readerMapLocationRangeY.Read(mapLocationRangeY, 0, width * height); readerMapLocationRangeY.Close(); istream.Close(); } //FileStream istream; //istream = new FileStream(filepathMapLocationRangeX, FileMode.Open, FileAccess.Read); //BinaryReader readerMapLocationRangeX = new BinaryReader(istream, Encoding.UTF8); //readerMapLocationRangeX.Read(mapLocationRangeX, 0, width * height); //readerMapLocationRangeX.Close(); //istream.Close(); //istream = new FileStream(filepathMapLocationRangeY, FileMode.Open, FileAccess.Read); //BinaryReader readerMapLocationRangeY = new BinaryReader(istream, Encoding.UTF8); //readerMapLocationRangeY.Read(mapLocationRangeY, 0, width * height); //readerMapLocationRangeY.Close(); //istream.Close(); } #endif if (mapDistanceSquaredFromWater == null) { byte[] heightMapArray = contentReader.WoodsFileReader.Buffer.Clone() as byte[]; int width = WoodsFile.mapWidthValue; int height = WoodsFile.mapHeightValue; for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { if (heightMapArray[y * width + x] <= 2) heightMapArray[y * width + x] = 1; else heightMapArray[y * width + x] = 0; } } //now set image borders to "water" (this is a workaround to prevent mountains to become too high in north-east and south-east edge of map) for (int y = 0; y < height; y++) { heightMapArray[y * width + 0] = 1; heightMapArray[y * width + width - 1] = 1; } for (int x = 0; x < width; x++) { heightMapArray[0 * width + x] = 1; heightMapArray[(height - 1) * width + x] = 1; } mapDistanceSquaredFromWater = imageDistanceTransform(heightMapArray, width, height, 1); heightMapArray = null; } if (mapDistanceSquaredFromLocations == null) { int width = WoodsFile.mapWidthValue; int height = WoodsFile.mapHeightValue; mapLocations = new byte[width * height]; for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { ContentReader.MapSummary summary; if (contentReader.HasLocation(x + 1, y+1, out summary)) mapLocations[y * width + x] = 1; else mapLocations[y * width + x] = 0; } } mapDistanceSquaredFromLocations = imageDistanceTransform(mapLocations, width, height, 1); } if (mapMultipliers == null) { int width = WoodsFile.mapWidthValue; int height = WoodsFile.mapHeightValue; mapMultipliers = new float[width * height]; // compute the multiplier and store it in mapMultipliers for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { float distanceFromWater = (float)Math.Sqrt(mapDistanceSquaredFromWater[y * WoodsFile.mapWidthValue + x]); float distanceFromLocation = (float)Math.Sqrt(mapDistanceSquaredFromLocations[y * WoodsFile.mapWidthValue + x]); float multiplierLocation = (distanceFromLocation * extraExaggerationFactorLocationDistance + 1.0f); // terrain distant from location gets extra exaggeration if (distanceFromWater < minDistanceFromWaterForExtraExaggeration) // except if it is near water multiplierLocation = 1.0f; // Seed random with terrain key UnityEngine.Random.InitState(TerrainHelper.MakeTerrainKey(x, y)); float additionalHeightBasedOnClimate = GetAdditionalHeightBasedOnClimate(x, y); float additionalHeightApplied = UnityEngine.Random.Range(-additionalHeightBasedOnClimate * 0.5f, additionalHeightBasedOnClimate); mapMultipliers[y * width + x] = (Math.Min(maxHeightsExaggerationMultiplier, additionalHeightApplied + /*multiplierLocation **/ Math.Max(1.0f, distanceFromWater * exaggerationFactorWaterDistance))); } } // multipliedMap gets smoothed float[] newmapMultipliers = mapMultipliers.Clone() as float[]; float[,] weights = { { 0.0625f, 0.125f, 0.0625f }, { 0.125f, 0.25f, 0.125f }, { 0.0625f, 0.125f, 0.0625f } }; for (int y = 1; y < height - 1; y++) { for (int x = 1; x < width - 1; x++) { if (mapDistanceSquaredFromLocations[y * width + x] <= 2) // at and around locations ( <= 2 ... only map pixels in 8-connected neighborhood (distanceFromLocationMaps stores squared distances...)) { newmapMultipliers[y * width + x] = weights[0, 0] * mapMultipliers[(y - 1) * width + (x - 1)] + weights[0, 1] * mapMultipliers[(y - 1) * width + (x)] + weights[0, 2] * mapMultipliers[(y - 1) * width + (x + 1)] + weights[1, 0] * mapMultipliers[(y - 0) * width + (x - 1)] + weights[1, 1] * mapMultipliers[(y - 0) * width + (x)] + weights[1, 2] * mapMultipliers[(y - 0) * width + (x + 1)] + weights[2, 0] * mapMultipliers[(y + 1) * width + (x - 1)] + weights[2, 1] * mapMultipliers[(y + 1) * width + (x)] + weights[2, 2] * mapMultipliers[(y + 1) * width + (x + 1)]; } } } mapMultipliers = newmapMultipliers; newmapMultipliers = null; weights = null; } //the height map gets smoothed as well { int width = WoodsFile.mapWidthValue; int height = WoodsFile.mapHeightValue; byte[] heightMapBuffer = contentReader.WoodsFileReader.Buffer.Clone() as byte[]; int[,] intWeights = { { 1, 2, 1 }, { 2, 4, 2 }, { 1, 2, 1 } }; for (int y = 1; y < height - 1; y++) { for (int x = 1; x < width - 1; x++) { if (mapDistanceSquaredFromWater[y * width + x] > 0) // check if squared distance from water is greater than zero -> if it is no water pixel { int value = intWeights[0, 0] * (int)heightMapBuffer[(y - 1) * width + (x - 1)] + intWeights[0, 1] * (int)heightMapBuffer[(y - 1) * width + (x)] + intWeights[0, 2] * (int)heightMapBuffer[(y - 1) * width + (x + 1)] + intWeights[1, 0] * (int)heightMapBuffer[(y - 0) * width + (x - 1)] + intWeights[1, 1] * (int)heightMapBuffer[(y - 0) * width + (x)] + intWeights[1, 2] * (int)heightMapBuffer[(y - 0) * width + (x + 1)] + intWeights[2, 0] * (int)heightMapBuffer[(y + 1) * width + (x - 1)] + intWeights[2, 1] * (int)heightMapBuffer[(y + 1) * width + (x)] + intWeights[2, 2] * (int)heightMapBuffer[(y + 1) * width + (x + 1)]; heightMapBuffer[y * width + x] = (byte)(value / 16); } } } contentReader.WoodsFileReader.Buffer = heightMapBuffer; heightMapBuffer = null; intWeights = null; } // build tree coverage map if (mapTreeCoverage == null) { int width = WoodsFile.mapWidthValue; int height = WoodsFile.mapHeightValue; mapTreeCoverage = new byte[width * height]; #if !LOAD_TREE_COVERAGE_MAP { float startTreeCoverageAtElevation = ImprovedTerrainSampler.baseHeightScale * 2.0f; // ImprovedTerrainSampler.scaledBeachElevation; float minTreeCoverageSaturated = ImprovedTerrainSampler.baseHeightScale * 6.0f; float maxTreeCoverageSaturated = ImprovedTerrainSampler.baseHeightScale * 60.0f; float endTreeCoverageAtElevation = ImprovedTerrainSampler.baseHeightScale * 80.0f; //float maxElevation = 0.0f; for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { int readIndex = (height - 1 - y) * width + x; float w = 0.0f; //float elevation = ((float)contentReader.WoodsFileReader.Buffer[(height - 1 - y) * width + x]) / 255.0f; // *mapMultipliers[index]; float elevation = ((float)contentReader.WoodsFileReader.Buffer[readIndex]) * mapMultipliers[readIndex]; //maxElevation = Math.Max(maxElevation, elevation); if ((elevation > minTreeCoverageSaturated) && (elevation < maxTreeCoverageSaturated)) { w = 1.0f; } else if ((elevation >= startTreeCoverageAtElevation) && (elevation <= minTreeCoverageSaturated)) { w = (elevation - startTreeCoverageAtElevation) / (minTreeCoverageSaturated - startTreeCoverageAtElevation); } else if ((elevation >= maxTreeCoverageSaturated) && (elevation <= endTreeCoverageAtElevation)) { w = 1.0f - ((elevation - maxTreeCoverageSaturated) / (endTreeCoverageAtElevation - maxTreeCoverageSaturated)); } //w = 0.65f * w + 0.35f * Math.Min(6.0f, (float)Math.Sqrt(mapDistanceSquaredFromLocations[y * width + x])) / 6.0f; mapTreeCoverage[(y) * width + x] = Convert.ToByte(w * 255.0f); //if (elevation>0.05f) // mapTreeCoverage[index] = Convert.ToByte(250); //w * 255.0f); //else mapTreeCoverage[index] = Convert.ToByte(0); //if (elevation >= startTreeCoverageAtElevation) //{ // mapTreeCoverage[(y) * width + x] = Convert.ToByte(255.0f); //} else{ // mapTreeCoverage[(y) * width + x] = Convert.ToByte(0.0f); //} } } } #else { MemoryStream istream; TextAsset assetMapTreeCoverage = Resources.Load<TextAsset>(filenameTreeCoverageMap); if (assetMapTreeCoverage) { istream = new MemoryStream(assetMapTreeCoverage.bytes); BinaryReader readerMapTreeCoverage = new BinaryReader(istream, Encoding.UTF8); readerMapTreeCoverage.Read(mapTreeCoverage, 0, width * height); readerMapTreeCoverage.Close(); istream.Close(); } } #endif #if CREATE_PERSISTENT_TREE_COVERAGE_MAP { FileStream ostream = new FileStream(Path.Combine(Application.dataPath, out_filepathOutTreeCoverageMap), FileMode.Create, FileAccess.Write); BinaryWriter writerMapTreeCoverage = new BinaryWriter(ostream, Encoding.UTF8); writerMapTreeCoverage.Write(mapTreeCoverage, 0, width * height); writerMapTreeCoverage.Close(); ostream.Close(); } #endif //Debug.Log(string.Format("max elevation: {0}", maxElevation)); } init = true; } } /* distance transform of image (will get binarized) using squared distance */ public static float[] imageDistanceTransform(byte[] imgIn, int width, int height, byte maskValue) { const float INF = 1E20f; // allocate image and initialize float[] imgOut = new float[width * height]; for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { if (imgIn[y * width + x] == maskValue) imgOut[y * width + x] = 0; // pixels with maskValue -> distance 0 else imgOut[y * width + x] = INF; // set to infinite } } distanceTransform2D(ref imgOut, width, height); return imgOut; } /* euklidean distance transform (based on an implementation of Pedro Felzenszwalb (from paper Fast distance transform in C++ by Felzenszwalb and Huttenlocher))*/ /* distance transform of 1d function using squared distance */ private static float[] distanceTransform1D(ref float[] f, int n) { const float INF = 1E20f; float[] d = new float[n]; int[] v = new int[n]; float[] z = new float[n + 1]; int k = 0; v[0] = 0; z[0] = -INF; z[1] = +INF; for (int q = 1; q <= n - 1; q++) { float s = ((f[q] + (q * q)) - (f[v[k]] + (v[k] * v[k]))) / (2 * q - 2 * v[k]); while (s <= z[k]) { k--; s = ((f[q] + (q * q)) - (f[v[k]] + (v[k] * v[k]))) / (2 * q - 2 * v[k]); } k++; v[k] = q; z[k] = s; z[k + 1] = +INF; } k = 0; for (int q = 0; q <= n - 1; q++) { while (z[k + 1] < q) k++; d[q] = (q - v[k]) * (q - v[k]) + f[v[k]]; } return d; } /* in-place 2D distance transform on float array using squared distance, float array must be initialized with 0 for maskValue-pixels and infinite otherwise*/ private static void distanceTransform2D(ref float[] img, int width, int height) { float[] f = new float[Math.Max(width, height)]; // transform along columns for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { f[y] = img[y * width + x]; } float[] d = distanceTransform1D(ref f, height); for (int y = 0; y < height; y++) { img[y * width + x] = d[y]; } } // transform along rows for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { f[x] = img[y * width + x]; } float[] d = distanceTransform1D(ref f, width); for (int x = 0; x < width; x++) { img[y * width + x] = d[x]; } } } } }
using System; using System.Linq; using Microsoft.Azure.WebJobs; using Microsoft.Azure.WebJobs.Host; using System.Threading.Tasks; using System.Collections.Generic; using Microsoft.ServiceBus; using Microsoft.Azure.Management.ResourceManager.Fluent; using Microsoft.Azure.Management.Fluent; namespace MyDurableTaskApp { public static class DurableScaling { private const int ThresholdUp = 5000; private const int ThresholdDown = 1000; private static readonly TimeSpan Period = TimeSpan.FromMinutes(10); private static readonly TimeSpan CooldownPeriod = TimeSpan.FromMinutes(10); [FunctionName(nameof(MetricCollector))] public static async Task MetricCollector( [TimerTrigger("0 */1 * * * *")] TimerInfo myTimer, [OrchestrationClient] DurableOrchestrationClient client, TraceWriter log) { log.Info($"MetricCollector function executed at: {DateTime.Now}"); var resource = Environment.GetEnvironmentVariable("ResourceToScale"); //await client.TerminateAsync(resource, ""); var status = await client.GetStatusAsync(resource); if (status == null) { await client.StartNewAsync(nameof(ScalingLogic), resource, new ScalingState()); } else { var metric = ServiceBusHelper.GetSubscriptionMetric(resource); log.Info($"Collector: Current metric value is {metric.Value.Value} at {DateTime.Now}"); await client.RaiseEventAsync(resource, nameof(Metric), metric); } } [FunctionName(nameof(ScalingLogic))] public static async Task<ScalingState> ScalingLogic([OrchestrationTrigger] DurableOrchestrationContext context, TraceWriter log) { var state = context.GetInput<ScalingState>(); log.Info($"Current state is {state}. Waiting for next value."); var metric = await context.WaitForExternalEvent<Metric>(nameof(Metric)); var history = state.History; log.Info($"Scaling logic: Received {metric.Name}, previous state is {string.Join(", ", history)}"); // 2. Add current metric value, remove old values history.Add(metric.Value); history.RemoveAll(e => e.Time < metric.Value.Time.Subtract(Period)); // 3. Compare the aggregates to thresholds, produce scaling action if needed ScaleAction action = null; if (history.Count >= 5 && context.CurrentUtcDateTime - state.LastScalingActionTime > CooldownPeriod) { var average = (int)history.Average(e => e.Value); var maximum = history.Max(e => e.Value); if (average > ThresholdUp) { log.Info($"Scaling logic: Value {average} is too high, scaling {metric.ResourceName} up..."); action = new ScaleAction(metric.ResourceName, ScaleActionType.Up); } else if (maximum < ThresholdDown) { log.Info($"Scaling logic: Value {maximum} is low, scaling {metric.ResourceName} down..."); action = new ScaleAction(metric.ResourceName, ScaleActionType.Down); } } // 4. If scaling is needed, call Scaler if (action != null) { var result = await context.CallFunctionAsync<int>(nameof(Scaler), action); log.Info($"Scaling logic: Scaled to {result} instances."); state.LastScalingActionTime = context.CurrentUtcDateTime; } context.ContinueAsNew(state); return state; } [FunctionName(nameof(Scaler))] public static int Scaler([ActivityTrigger] DurableActivityContext context, TraceWriter log) { log.Info($"Scaler executed at: {DateTime.Now}"); var action = context.GetInput<ScaleAction>(); var newCapacity = ScalingHelper.ChangeAppServiceInstanceCount( action.ResourceName, action.Type == ScaleActionType.Down ? -1 : +1); return newCapacity; } } public class ScalingState { public List<MetricValue> History { get; } = new List<MetricValue>(); public DateTime LastScalingActionTime { get; set; } = DateTime.MinValue; } public class Metric { public Metric(string resourceName, string name, MetricValue value) { this.ResourceName = resourceName; this.Name = name; this.Value = value; } public string ResourceName { get; } public string Name { get; } public MetricValue Value { get; } } public class MetricValue { public MetricValue(DateTime time, int value) { this.Time = time; this.Value = value; } public DateTime Time { get; } public int Value { get; } public override string ToString() { return $"{this.Time.ToShortTimeString()}: {this.Value}"; } } public class ScaleAction { public ScaleAction(string resourceName, ScaleActionType type) { this.ResourceName = resourceName; this.Type = type; } public string ResourceName { get; } public ScaleActionType Type { get; } } public enum ScaleActionType { Up, Down } public static class ServiceBusHelper { public static Metric GetSubscriptionMetric(string resource) { var topic = Environment.GetEnvironmentVariable("Topic"); var subscription = Environment.GetEnvironmentVariable("Subscription"); var backlog = ServiceBusHelper.GetSubscriptionBacklog(topic, subscription); var value = new MetricValue(DateTime.UtcNow, (int)backlog); return new Metric(resource, $"{topic}-{subscription}-backlog", value); } public static long GetSubscriptionBacklog(string topic, string subscription) { var connectionString = Environment.GetEnvironmentVariable("ServiceBusConnection"); var nsmgr = NamespaceManager.CreateFromConnectionString(connectionString); var subscriptionClient = nsmgr.GetSubscription(topic, subscription); return subscriptionClient.MessageCountDetails.ActiveMessageCount; } } public static class ScalingHelper { public static int ChangeAppServiceInstanceCount(string resourceName, int delta) { var secrets = Environment.GetEnvironmentVariable("ServicePrincipal").Split(','); var credentials = SdkContext.AzureCredentialsFactory .FromServicePrincipal(secrets[0], secrets[1], secrets[2], AzureEnvironment.AzureGlobalCloud); var azure = Azure.Configure() .Authenticate(credentials) .WithDefaultSubscription(); var plan = azure.AppServices .AppServicePlans .List() .First(p => p.Name.Contains(resourceName)); var newCapacity = plan.Capacity + delta; plan.Update() .WithCapacity(newCapacity) .Apply(); return newCapacity; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. namespace Microsoft.Azure.Management.Redis.Fluent.RedisCache.Update { using Microsoft.Azure.Management.Redis.Fluent.Models; using System; using System.Collections.Generic; /// <summary> /// The template for a Redis Cache update operation, containing all the settings that can be modified. /// </summary> public interface IUpdate : Microsoft.Azure.Management.ResourceManager.Fluent.Core.ResourceActions.IAppliable<Microsoft.Azure.Management.Redis.Fluent.IRedisCache>, Microsoft.Azure.Management.ResourceManager.Fluent.Core.Resource.Update.IUpdateWithTags<Microsoft.Azure.Management.Redis.Fluent.RedisCache.Update.IUpdate>, Microsoft.Azure.Management.Redis.Fluent.RedisCache.Update.IWithSku, Microsoft.Azure.Management.Redis.Fluent.RedisCache.Update.IWithNonSslPort, Microsoft.Azure.Management.Redis.Fluent.RedisCache.Update.IWithRedisConfiguration, Microsoft.Azure.Management.Redis.Fluent.RedisCache.Update.IUpdateBeta { /// <summary> /// Adds Patch schedule to the current Premium Cluster Cache. /// </summary> /// <param name="dayOfWeek">Day of week when cache can be patched.</param> /// <param name="startHourUtc">Start hour after which cache patching can start.</param> /// <return>The next stage of Redis Cache with Premium SKU definition.</return> Microsoft.Azure.Management.Redis.Fluent.RedisCache.Update.IUpdate WithPatchSchedule(Microsoft.Azure.Management.Redis.Fluent.Models.DayOfWeek dayOfWeek, int startHourUtc); /// <summary> /// Adds Patch schedule to the current Premium Cluster Cache. /// </summary> /// <param name="dayOfWeek">Day of week when cache can be patched.</param> /// <param name="startHourUtc">Start hour after which cache patching can start.</param> /// <param name="maintenanceWindow">ISO8601 timespan specifying how much time cache patching can take.</param> /// <return>The next stage of Redis Cache with Premium SKU definition.</return> Microsoft.Azure.Management.Redis.Fluent.RedisCache.Update.IUpdate WithPatchSchedule(Microsoft.Azure.Management.Redis.Fluent.Models.DayOfWeek dayOfWeek, int startHourUtc, TimeSpan maintenanceWindow); /// <summary> /// Adds Patch schedule to the current Premium Cluster Cache. /// </summary> /// <param name="scheduleEntry">Patch schedule entry for Premium Redis Cache.</param> /// <return>The next stage of Redis Cache with Premium SKU definition.</return> Microsoft.Azure.Management.Redis.Fluent.RedisCache.Update.IUpdate WithPatchSchedule(ScheduleEntry scheduleEntry); /// <summary> /// Adds Patch schedule to the current Premium Cluster Cache. /// </summary> /// <param name="scheduleEntry">List of patch schedule entries for Premium Redis Cache.</param> /// <return>The next stage of Redis Cache with Premium SKU definition.</return> Microsoft.Azure.Management.Redis.Fluent.RedisCache.Update.IUpdate WithPatchSchedule(IList<Microsoft.Azure.Management.Redis.Fluent.Models.ScheduleEntry> scheduleEntry); /// <summary> /// The number of shards to be created on a Premium Cluster Cache. /// </summary> /// <param name="shardCount">The shard count value to set.</param> /// <return>The next stage of Redis Cache update.</return> Microsoft.Azure.Management.Redis.Fluent.RedisCache.Update.IUpdate WithShardCount(int shardCount); } /// <summary> /// A Redis Cache update allowing Redis configuration to be modified. /// </summary> public interface IWithRedisConfiguration { /// <summary> /// Cleans all the configuration settings being set on Redis Cache. /// </summary> /// <return>The next stage of Redis Cache update.</return> Microsoft.Azure.Management.Redis.Fluent.RedisCache.Update.IUpdate WithoutRedisConfiguration(); /// <summary> /// Removes specified Redis Cache configuration setting. /// </summary> /// <param name="key">Redis configuration name.</param> /// <return>The next stage of Redis Cache update.</return> Microsoft.Azure.Management.Redis.Fluent.RedisCache.Update.IUpdate WithoutRedisConfiguration(string key); /// <summary> /// All Redis Settings. Few possible keys: /// rdb-backup-enabled, rdb-storage-connection-string, rdb-backup-frequency, maxmemory-delta, maxmemory-policy, /// notify-keyspace-events, maxmemory-samples, slowlog-log-slower-than, slowlog-max-len, list-max-ziplist-entries, /// list-max-ziplist-value, hash-max-ziplist-entries, hash-max-ziplist-value, set -max-intset-entries, /// zset-max-ziplist-entries, zset-max-ziplist-value etc. /// </summary> /// <param name="redisConfiguration">Configuration of Redis Cache as a map indexed by configuration name.</param> /// <return>The next stage of Redis Cache update.</return> Microsoft.Azure.Management.Redis.Fluent.RedisCache.Update.IUpdate WithRedisConfiguration(IDictionary<string,string> redisConfiguration); /// <summary> /// Specifies Redis Setting. /// rdb-backup-enabled, rdb-storage-connection-string, rdb-backup-frequency, maxmemory-delta, maxmemory-policy, /// notify-keyspace-events, maxmemory-samples, slowlog-log-slower-than, slowlog-max-len, list-max-ziplist-entries, /// list-max-ziplist-value, hash-max-ziplist-entries, hash-max-ziplist-value, set -max-intset-entries, /// zset-max-ziplist-entries, zset-max-ziplist-value etc. /// </summary> /// <param name="key">Redis configuration name.</param> /// <param name="value">Redis configuration value.</param> /// <return>The next stage of Redis Cache update.</return> Microsoft.Azure.Management.Redis.Fluent.RedisCache.Update.IUpdate WithRedisConfiguration(string key, string value); } /// <summary> /// A Redis Cache update stage allowing to change the parameters. /// </summary> public interface IWithSku { /// <summary> /// Updates Redis Cache to Basic sku with new capacity. /// </summary> /// <param name="capacity">Specifies what size of Redis Cache to update to for Basic sku with C family (0, 1, 2, 3, 4, 5, 6).</param> /// <return>The next stage of Redis Cache update.</return> Microsoft.Azure.Management.Redis.Fluent.RedisCache.Update.IUpdate WithBasicSku(int capacity); /// <summary> /// Updates Redis Cache to Premium sku. /// </summary> /// <return>The next stage of Redis Cache update.</return> Microsoft.Azure.Management.Redis.Fluent.RedisCache.Update.IUpdate WithPremiumSku(); /// <summary> /// Updates Redis Cache to Premium sku with new capacity. /// </summary> /// <param name="capacity">Specifies what size of Redis Cache to update to for Premium sku with P family (1, 2, 3, 4).</param> /// <return>The next stage of Redis Cache update.</return> Microsoft.Azure.Management.Redis.Fluent.RedisCache.Update.IUpdate WithPremiumSku(int capacity); /// <summary> /// Updates Redis Cache to Standard sku. /// </summary> /// <return>The next stage of Redis Cache update.</return> Microsoft.Azure.Management.Redis.Fluent.RedisCache.Update.IUpdate WithStandardSku(); /// <summary> /// Updates Redis Cache to Standard sku with new capacity. /// </summary> /// <param name="capacity">Specifies what size of Redis Cache to update to for Standard sku with C family (0, 1, 2, 3, 4, 5, 6).</param> /// <return>The next stage of Redis Cache update.</return> Microsoft.Azure.Management.Redis.Fluent.RedisCache.Update.IUpdate WithStandardSku(int capacity); } /// <summary> /// A Redis Cache update allowing non SSL port to be enabled or disabled. /// </summary> public interface IWithNonSslPort { /// <summary> /// Enables non-ssl Redis server port (6379). /// </summary> /// <return>The next stage of Redis Cache update.</return> Microsoft.Azure.Management.Redis.Fluent.RedisCache.Update.IUpdate WithNonSslPort(); /// <summary> /// Disables non-ssl Redis server port (6379). /// </summary> /// <return>The next stage of Redis Cache update.</return> Microsoft.Azure.Management.Redis.Fluent.RedisCache.Update.IUpdate WithoutNonSslPort(); } /// <summary> /// The template for a Redis Cache update operation, containing all the settings that can be modified. /// </summary> public interface IUpdateBeta : Microsoft.Azure.Management.ResourceManager.Fluent.Core.IBeta { /// <summary> /// Creates or updates Redis cache firewall rule with range of IP addresses permitted to connect to the cache. /// </summary> /// <param name="name">Name of the rule.</param> /// <param name="lowestIp">Lowest IP address included in the range.</param> /// <param name="highestIp">Highest IP address included in the range.</param> /// <return>The next stage of Redis Cache update.</return> Microsoft.Azure.Management.Redis.Fluent.RedisCache.Update.IUpdate WithFirewallRule(string name, string lowestIp, string highestIp); /// <summary> /// Creates or updates Redis cache firewall rule with range of IP addresses permitted to connect to the cache. /// </summary> /// <param name="rule">Firewall rule that specifies name, lowest and highest IP address included in the range of permitted IP addresses.</param> /// <return>The next stage of Redis Cache update.</return> Microsoft.Azure.Management.Redis.Fluent.RedisCache.Update.IUpdate WithFirewallRule(IRedisFirewallRule rule); /// <summary> /// Requires clients to use a specified TLS version (or higher) to connect (e,g, '1.0', '1.1', '1.2'). /// </summary> /// <param name="tlsVersion">Minimum TLS version.</param> /// <return>The next stage of Redis Cache definition.</return> Microsoft.Azure.Management.Redis.Fluent.RedisCache.Update.IUpdate WithMinimumTlsVersion(TlsVersion tlsVersion); /// <summary> /// Deletes a single firewall rule in the current Redis cache instance. /// </summary> /// <param name="name">Name of the rule.</param> /// <return>The next stage of Redis Cache update.</return> Microsoft.Azure.Management.Redis.Fluent.RedisCache.Update.IUpdate WithoutFirewallRule(string name); /// <summary> /// Removes the requirement for clients minimum TLS version. /// </summary> /// <return>The next stage of Redis Cache definition.</return> Microsoft.Azure.Management.Redis.Fluent.RedisCache.Update.IUpdate WithoutMinimumTlsVersion(); /// <summary> /// Removes all Patch schedules from the current Premium Cluster Cache. /// </summary> /// <return>The next stage of Redis Cache with Premium SKU definition.</return> Microsoft.Azure.Management.Redis.Fluent.RedisCache.Update.IUpdate WithoutPatchSchedule(); } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; using System.Linq; using Xunit; namespace System.Collections.Immutable.Test { public class ImmutableArrayExtensionsTest { private static readonly ImmutableArray<int> emptyDefault = default(ImmutableArray<int>); private static readonly ImmutableArray<int> empty = ImmutableArray.Create<int>(); private static readonly ImmutableArray<int> oneElement = ImmutableArray.Create(1); private static readonly ImmutableArray<int> manyElements = ImmutableArray.Create(1, 2, 3); private static readonly ImmutableArray<GenericParameterHelper> oneElementRefType = ImmutableArray.Create(new GenericParameterHelper(1)); private static readonly ImmutableArray<string> twoElementRefTypeWithNull = ImmutableArray.Create("1", null); private static readonly ImmutableArray<int>.Builder emptyBuilder = ImmutableArray.Create<int>().ToBuilder(); private static readonly ImmutableArray<int>.Builder oneElementBuilder = ImmutableArray.Create<int>(1).ToBuilder(); private static readonly ImmutableArray<int>.Builder manyElementsBuilder = ImmutableArray.Create<int>(1, 2, 3).ToBuilder(); [Fact] public void Select() { Assert.Equal(new[] { 4, 5, 6 }, ImmutableArrayExtensions.Select(manyElements, n => n + 3)); Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.Select<int, bool>(manyElements, null)); } [Fact] public void SelectEmptyDefault() { Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.Select<int, bool>(emptyDefault, null)); Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.Select(emptyDefault, n => true)); } [Fact] public void SelectEmpty() { Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.Select<int, bool>(empty, null)); Assert.False(ImmutableArrayExtensions.Select(empty, n => true).Any()); } [Fact] public void Where() { Assert.Equal(new[] { 2, 3 }, ImmutableArrayExtensions.Where(manyElements, n => n > 1)); Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.Where(manyElements, null)); } [Fact] public void WhereEmptyDefault() { Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.Where(emptyDefault, null)); Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.Where(emptyDefault, n => true)); } [Fact] public void WhereEmpty() { Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.Where(empty, null)); Assert.False(ImmutableArrayExtensions.Where(empty, n => true).Any()); } [Fact] public void Any() { Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.Any(oneElement, null)); Assert.True(ImmutableArrayExtensions.Any(oneElement)); Assert.True(ImmutableArrayExtensions.Any(manyElements, n => n == 2)); Assert.False(ImmutableArrayExtensions.Any(manyElements, n => n == 4)); Assert.True(ImmutableArrayExtensions.Any(oneElementBuilder)); } [Fact] public void AnyEmptyDefault() { Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.Any(emptyDefault)); Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.Any(emptyDefault, n => true)); Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.Any(emptyDefault, null)); } [Fact] public void AnyEmpty() { Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.Any(empty, null)); Assert.False(ImmutableArrayExtensions.Any(empty)); Assert.False(ImmutableArrayExtensions.Any(empty, n => true)); } [Fact] public void All() { Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.All(oneElement, null)); Assert.False(ImmutableArrayExtensions.All(manyElements, n => n == 2)); Assert.True(ImmutableArrayExtensions.All(manyElements, n => n > 0)); } [Fact] public void AllEmptyDefault() { Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.All(emptyDefault, n => true)); Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.All(emptyDefault, null)); } [Fact] public void AllEmpty() { Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.All(empty, null)); Assert.True(ImmutableArrayExtensions.All(empty, n => { Assert.True(false); return false; })); // predicate should never be invoked. } [Fact] public void SequenceEqual() { Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.SequenceEqual(oneElement, (IEnumerable<int>)null)); foreach (IEqualityComparer<int> comparer in new[] { null, EqualityComparer<int>.Default }) { Assert.True(ImmutableArrayExtensions.SequenceEqual(manyElements, manyElements, comparer)); Assert.True(ImmutableArrayExtensions.SequenceEqual(manyElements, (IEnumerable<int>)manyElements.ToArray(), comparer)); Assert.True(ImmutableArrayExtensions.SequenceEqual(manyElements, ImmutableArray.Create(manyElements.ToArray()), comparer)); Assert.False(ImmutableArrayExtensions.SequenceEqual(manyElements, oneElement, comparer)); Assert.False(ImmutableArrayExtensions.SequenceEqual(manyElements, (IEnumerable<int>)oneElement.ToArray(), comparer)); Assert.False(ImmutableArrayExtensions.SequenceEqual(manyElements, ImmutableArray.Create(oneElement.ToArray()), comparer)); Assert.False(ImmutableArrayExtensions.SequenceEqual(manyElements, (IEnumerable<int>)manyElements.Add(1).ToArray(), comparer)); Assert.False(ImmutableArrayExtensions.SequenceEqual(manyElements.Add(1), manyElements.Add(2).ToArray(), comparer)); Assert.False(ImmutableArrayExtensions.SequenceEqual(manyElements.Add(1), (IEnumerable<int>)manyElements.Add(2).ToArray(), comparer)); } Assert.True(ImmutableArrayExtensions.SequenceEqual(manyElements, manyElements, (a, b) => true)); Assert.False(ImmutableArrayExtensions.SequenceEqual(manyElements, oneElement, (a, b) => a == b)); Assert.False(ImmutableArrayExtensions.SequenceEqual(manyElements.Add(1), manyElements.Add(2), (a, b) => a == b)); Assert.True(ImmutableArrayExtensions.SequenceEqual(manyElements.Add(1), manyElements.Add(1), (a, b) => a == b)); Assert.False(ImmutableArrayExtensions.SequenceEqual(manyElements, ImmutableArray.Create(manyElements.ToArray()), (a, b) => false)); Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.SequenceEqual(oneElement, oneElement, (Func<int, int, bool>)null)); } [Fact] public void SequenceEqualEmptyDefault() { Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.SequenceEqual(oneElement, emptyDefault)); Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.SequenceEqual(emptyDefault, empty)); Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.SequenceEqual(emptyDefault, emptyDefault)); Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.SequenceEqual(emptyDefault, emptyDefault, (Func<int, int, bool>)null)); } [Fact] public void SequenceEqualEmpty() { Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.SequenceEqual(empty, (IEnumerable<int>)null)); Assert.True(ImmutableArrayExtensions.SequenceEqual(empty, empty)); Assert.True(ImmutableArrayExtensions.SequenceEqual(empty, empty.ToArray())); Assert.True(ImmutableArrayExtensions.SequenceEqual(empty, empty, (a, b) => true)); Assert.True(ImmutableArrayExtensions.SequenceEqual(empty, empty, (a, b) => false)); } [Fact] public void Aggregate() { Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.Aggregate(oneElement, null)); Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.Aggregate(oneElement, 1, null)); Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.Aggregate<int, int, int>(oneElement, 1, null, null)); Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.Aggregate<int, int, int>(oneElement, 1, (a, b) => a + b, null)); Assert.Equal(Enumerable.Aggregate(manyElements, (a, b) => a * b), ImmutableArrayExtensions.Aggregate(manyElements, (a, b) => a * b)); Assert.Equal(Enumerable.Aggregate(manyElements, 5, (a, b) => a * b), ImmutableArrayExtensions.Aggregate(manyElements, 5, (a, b) => a * b)); Assert.Equal(Enumerable.Aggregate(manyElements, 5, (a, b) => a * b, a => -a), ImmutableArrayExtensions.Aggregate(manyElements, 5, (a, b) => a * b, a => -a)); } [Fact] public void AggregateEmptyDefault() { Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.Aggregate(emptyDefault, (a, b) => a + b)); Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.Aggregate(emptyDefault, 1, (a, b) => a + b)); Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.Aggregate<int, int, int>(emptyDefault, 1, (a, b) => a + b, a => a)); } [Fact] public void AggregateEmpty() { Assert.Equal(0, ImmutableArrayExtensions.Aggregate(empty, (a, b) => a + b)); Assert.Equal(1, ImmutableArrayExtensions.Aggregate(empty, 1, (a, b) => a + b)); Assert.Equal(1, ImmutableArrayExtensions.Aggregate<int, int, int>(empty, 1, (a, b) => a + b, a => a)); } [Fact] public void ElementAt() { // Basis for some assertions that follow Assert.Throws<IndexOutOfRangeException>(() => Enumerable.ElementAt(empty, 0)); Assert.Throws<IndexOutOfRangeException>(() => Enumerable.ElementAt(manyElements, -1)); Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.ElementAt(emptyDefault, 0)); Assert.Throws<IndexOutOfRangeException>(() => ImmutableArrayExtensions.ElementAt(empty, 0)); Assert.Throws<IndexOutOfRangeException>(() => ImmutableArrayExtensions.ElementAt(manyElements, -1)); Assert.Equal(1, ImmutableArrayExtensions.ElementAt(oneElement, 0)); Assert.Equal(3, ImmutableArrayExtensions.ElementAt(manyElements, 2)); } [Fact] public void ElementAtOrDefault() { Assert.Equal(Enumerable.ElementAtOrDefault(manyElements, -1), ImmutableArrayExtensions.ElementAtOrDefault(manyElements, -1)); Assert.Equal(Enumerable.ElementAtOrDefault(manyElements, 3), ImmutableArrayExtensions.ElementAtOrDefault(manyElements, 3)); Assert.Throws<InvalidOperationException>(() => Enumerable.ElementAtOrDefault(emptyDefault, 0)); Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.ElementAtOrDefault(emptyDefault, 0)); Assert.Equal(0, ImmutableArrayExtensions.ElementAtOrDefault(empty, 0)); Assert.Equal(0, ImmutableArrayExtensions.ElementAtOrDefault(empty, 1)); Assert.Equal(1, ImmutableArrayExtensions.ElementAtOrDefault(oneElement, 0)); Assert.Equal(3, ImmutableArrayExtensions.ElementAtOrDefault(manyElements, 2)); } [Fact] public void First() { Assert.Equal(Enumerable.First(oneElement), ImmutableArrayExtensions.First(oneElement)); Assert.Equal(Enumerable.First(oneElement, i => true), ImmutableArrayExtensions.First(oneElement, i => true)); Assert.Equal(Enumerable.First(manyElements), ImmutableArrayExtensions.First(manyElements)); Assert.Equal(Enumerable.First(manyElements, i => true), ImmutableArrayExtensions.First(manyElements, i => true)); Assert.Equal(Enumerable.First(oneElementBuilder), ImmutableArrayExtensions.First(oneElementBuilder)); Assert.Equal(Enumerable.First(manyElementsBuilder), ImmutableArrayExtensions.First(manyElementsBuilder)); Assert.Throws<InvalidOperationException>(() => ImmutableArrayExtensions.First(empty)); Assert.Throws<InvalidOperationException>(() => ImmutableArrayExtensions.First(empty, i => true)); Assert.Throws<InvalidOperationException>(() => ImmutableArrayExtensions.First(manyElements, i => false)); } [Fact] public void FirstEmpty() { Assert.Throws<InvalidOperationException>(() => ImmutableArrayExtensions.First(empty)); Assert.Throws<InvalidOperationException>(() => ImmutableArrayExtensions.First(empty, n => true)); Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.First(empty, null)); Assert.Throws<InvalidOperationException>(() => ImmutableArrayExtensions.First(emptyBuilder)); } [Fact] public void FirstEmptyDefault() { Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.First(emptyDefault)); Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.First(emptyDefault, n => true)); Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.First(emptyDefault, null)); } [Fact] public void FirstOrDefault() { Assert.Equal(Enumerable.FirstOrDefault(oneElement), ImmutableArrayExtensions.FirstOrDefault(oneElement)); Assert.Equal(Enumerable.FirstOrDefault(manyElements), ImmutableArrayExtensions.FirstOrDefault(manyElements)); foreach (bool result in new[] { true, false }) { Assert.Equal(Enumerable.FirstOrDefault(oneElement, i => result), ImmutableArrayExtensions.FirstOrDefault(oneElement, i => result)); Assert.Equal(Enumerable.FirstOrDefault(manyElements, i => result), ImmutableArrayExtensions.FirstOrDefault(manyElements, i => result)); } Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.FirstOrDefault(oneElement, null)); Assert.Equal(Enumerable.FirstOrDefault(oneElementBuilder), ImmutableArrayExtensions.FirstOrDefault(oneElementBuilder)); Assert.Equal(Enumerable.FirstOrDefault(manyElementsBuilder), ImmutableArrayExtensions.FirstOrDefault(manyElementsBuilder)); } [Fact] public void FirstOrDefaultEmpty() { Assert.Equal(0, ImmutableArrayExtensions.FirstOrDefault(empty)); Assert.Equal(0, ImmutableArrayExtensions.FirstOrDefault(empty, n => true)); Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.FirstOrDefault(empty, null)); Assert.Equal(0, ImmutableArrayExtensions.FirstOrDefault(emptyBuilder)); } [Fact] public void FirstOrDefaultEmptyDefault() { Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.FirstOrDefault(emptyDefault)); Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.FirstOrDefault(emptyDefault, n => true)); Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.FirstOrDefault(emptyDefault, null)); } [Fact] public void Last() { Assert.Equal(Enumerable.Last(oneElement), ImmutableArrayExtensions.Last(oneElement)); Assert.Equal(Enumerable.Last(oneElement, i => true), ImmutableArrayExtensions.Last(oneElement, i => true)); Assert.Throws<InvalidOperationException>(() => ImmutableArrayExtensions.Last(oneElement, i => false)); Assert.Equal(Enumerable.Last(manyElements), ImmutableArrayExtensions.Last(manyElements)); Assert.Equal(Enumerable.Last(manyElements, i => true), ImmutableArrayExtensions.Last(manyElements, i => true)); Assert.Throws<InvalidOperationException>(() => ImmutableArrayExtensions.Last(manyElements, i => false)); Assert.Equal(Enumerable.Last(oneElementBuilder), ImmutableArrayExtensions.Last(oneElementBuilder)); Assert.Equal(Enumerable.Last(manyElementsBuilder), ImmutableArrayExtensions.Last(manyElementsBuilder)); } [Fact] public void LastEmpty() { Assert.Throws<InvalidOperationException>(() => ImmutableArrayExtensions.Last(empty)); Assert.Throws<InvalidOperationException>(() => ImmutableArrayExtensions.Last(empty, n => true)); Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.Last(empty, null)); Assert.Throws<InvalidOperationException>(() => ImmutableArrayExtensions.Last(emptyBuilder)); } [Fact] public void LastEmptyDefault() { Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.Last(emptyDefault)); Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.Last(emptyDefault, n => true)); Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.Last(emptyDefault, null)); } [Fact] public void LastOrDefault() { Assert.Equal(Enumerable.LastOrDefault(oneElement), ImmutableArrayExtensions.LastOrDefault(oneElement)); Assert.Equal(Enumerable.LastOrDefault(manyElements), ImmutableArrayExtensions.LastOrDefault(manyElements)); foreach (bool result in new[] { true, false }) { Assert.Equal(Enumerable.LastOrDefault(oneElement, i => result), ImmutableArrayExtensions.LastOrDefault(oneElement, i => result)); Assert.Equal(Enumerable.LastOrDefault(manyElements, i => result), ImmutableArrayExtensions.LastOrDefault(manyElements, i => result)); } Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.LastOrDefault(oneElement, null)); Assert.Equal(Enumerable.LastOrDefault(oneElementBuilder), ImmutableArrayExtensions.LastOrDefault(oneElementBuilder)); Assert.Equal(Enumerable.LastOrDefault(manyElementsBuilder), ImmutableArrayExtensions.LastOrDefault(manyElementsBuilder)); } [Fact] public void LastOrDefaultEmpty() { Assert.Equal(0, ImmutableArrayExtensions.LastOrDefault(empty)); Assert.Equal(0, ImmutableArrayExtensions.LastOrDefault(empty, n => true)); Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.LastOrDefault(empty, null)); Assert.Equal(0, ImmutableArrayExtensions.LastOrDefault(emptyBuilder)); } [Fact] public void LastOrDefaultEmptyDefault() { Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.LastOrDefault(emptyDefault)); Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.LastOrDefault(emptyDefault, n => true)); Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.LastOrDefault(emptyDefault, null)); } [Fact] public void Single() { Assert.Equal(Enumerable.Single(oneElement), ImmutableArrayExtensions.Single(oneElement)); Assert.Equal(Enumerable.Single(oneElement), ImmutableArrayExtensions.Single(oneElement, i => true)); Assert.Throws<InvalidOperationException>(() => ImmutableArrayExtensions.Single(manyElements)); Assert.Throws<InvalidOperationException>(() => ImmutableArrayExtensions.Single(manyElements, i => true)); Assert.Throws<InvalidOperationException>(() => ImmutableArrayExtensions.Single(manyElements, i => false)); Assert.Throws<InvalidOperationException>(() => ImmutableArrayExtensions.Single(oneElement, i => false)); } [Fact] public void SingleEmpty() { Assert.Throws<InvalidOperationException>(() => ImmutableArrayExtensions.Single(empty)); Assert.Throws<InvalidOperationException>(() => ImmutableArrayExtensions.Single(empty, n => true)); Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.Single(empty, null)); } [Fact] public void SingleEmptyDefault() { Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.Single(emptyDefault)); Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.Single(emptyDefault, n => true)); Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.Single(emptyDefault, null)); } [Fact] public void SingleOrDefault() { Assert.Equal(Enumerable.SingleOrDefault(oneElement), ImmutableArrayExtensions.SingleOrDefault(oneElement)); Assert.Equal(Enumerable.SingleOrDefault(oneElement), ImmutableArrayExtensions.SingleOrDefault(oneElement, i => true)); Assert.Equal(Enumerable.SingleOrDefault(oneElement, i => false), ImmutableArrayExtensions.SingleOrDefault(oneElement, i => false)); Assert.Throws<InvalidOperationException>(() => ImmutableArrayExtensions.SingleOrDefault(manyElements)); Assert.Throws<InvalidOperationException>(() => ImmutableArrayExtensions.SingleOrDefault(manyElements, i => true)); Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.SingleOrDefault(oneElement, null)); } [Fact] public void SingleOrDefaultEmpty() { Assert.Equal(0, ImmutableArrayExtensions.SingleOrDefault(empty)); Assert.Equal(0, ImmutableArrayExtensions.SingleOrDefault(empty, n => true)); Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.SingleOrDefault(empty, null)); } [Fact] public void SingleOrDefaultEmptyDefault() { Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.SingleOrDefault(emptyDefault)); Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.SingleOrDefault(emptyDefault, n => true)); Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.SingleOrDefault(emptyDefault, null)); } [Fact] public void ToDictionary() { Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.ToDictionary(manyElements, (Func<int, int>)null)); Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.ToDictionary(manyElements, (Func<int, int>)null, n => n)); Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.ToDictionary(manyElements, (Func<int, int>)null, n => n, EqualityComparer<int>.Default)); Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.ToDictionary(manyElements, n => n, (Func<int, string>)null)); Assert.Throws<ArgumentNullException>(() => ImmutableArrayExtensions.ToDictionary(manyElements, n => n, (Func<int, string>)null, EqualityComparer<int>.Default)); var stringToString = ImmutableArrayExtensions.ToDictionary(manyElements, n => n.ToString(), n => (n * 2).ToString()); Assert.Equal(stringToString.Count, manyElements.Length); Assert.Equal("2", stringToString["1"]); Assert.Equal("4", stringToString["2"]); Assert.Equal("6", stringToString["3"]); var stringToInt = ImmutableArrayExtensions.ToDictionary(manyElements, n => n.ToString()); Assert.Equal(stringToString.Count, manyElements.Length); Assert.Equal(1, stringToInt["1"]); Assert.Equal(2, stringToInt["2"]); Assert.Equal(3, stringToInt["3"]); Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.ToDictionary(emptyDefault, n => n)); Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.ToDictionary(emptyDefault, n => n, n => n)); Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.ToDictionary(emptyDefault, n => n, EqualityComparer<int>.Default)); Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.ToDictionary(emptyDefault, n => n, n => n, EqualityComparer<int>.Default)); } [Fact] public void ToArray() { Assert.Equal(0, ImmutableArrayExtensions.ToArray(empty).Length); Assert.Throws<NullReferenceException>(() => ImmutableArrayExtensions.ToArray(emptyDefault)); Assert.Equal(manyElements.ToArray(), ImmutableArrayExtensions.ToArray(manyElements)); } } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="Arg.cs"> // Copyright (c) 2011-2018 https://github.com/logjam2. // </copyright> // Licensed under the <a href="https://github.com/logjam2/logjam/blob/master/LICENSE.txt">Apache License, Version 2.0</a>; // you may not use this file except in compliance with the License. // -------------------------------------------------------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Diagnostics; namespace LogJam.Shared.Internal { #if CODECONTRACTS using System.Diagnostics.Contracts; using System.Linq; #endif /// <summary> /// Argument validation helpers. /// </summary> internal static class Arg { [ContractAbbreviator] public static void NotNull<T>(T value, string parameterName) { #if CODECONTRACTS Contract.Requires<ArgumentNullException>(value != null); #else if (value == null) { throw new ArgumentNullException(parameterName); } #endif } [Conditional("DEBUG")] [ContractAbbreviator] public static void DebugNotNull<T>(T value, string parameterName) { #if CODECONTRACTS Contract.Requires<ArgumentNullException>(value != null); #else if (value == null) { throw new ArgumentNullException(parameterName); } #endif } [ContractAbbreviator] public static void NotNullOrEmpty<T>(T[] array, string parameterName) { #if CODECONTRACTS Contract.Requires<ArgumentNullException>(array != null); Contract.Requires<ArgumentException>(array.Length > 0, $"{parameterName} array must not be empty"); #else if (array == null) { throw new ArgumentNullException(parameterName); } if (array.Length == 0) { throw new ArgumentException($"{parameterName} array must not be empty", paramName: parameterName); } #endif } [ContractAbbreviator] public static void NoneNull<T>(T[] array, string parameterName) { #if CODECONTRACTS Contract.Requires<ArgumentNullException>(array != null); Contract.Requires<ArgumentException>(array.All(e => e != null), $"{parameterName} array cannot contain any null elements"); #else if (array == null) { throw new ArgumentNullException(parameterName); } for (int i = 0; i < array.Length; ++i) { if (array[i] == null) { throw new ArgumentException($"{parameterName} array cannot contain any null elements", paramName: parameterName); } } #endif } [ContractAbbreviator] public static void NotNullOrEmpty<T>(ICollection<T> collection, string parameterName) { #if CODECONTRACTS Contract.Requires<ArgumentNullException>(collection != null); Contract.Requires<ArgumentException>(collection.Count > 0, $"{parameterName} collection must not be empty"); #else if (collection == null) { throw new ArgumentNullException(parameterName); } if (collection.Count == 0) { throw new ArgumentException($"{parameterName} collection must not be empty", paramName: parameterName); } #endif } [ContractAbbreviator] public static void NoneNull<T>(IEnumerable<T> collection, string parameterName) { #if CODECONTRACTS Contract.Requires<ArgumentNullException>(collection != null); Contract.Requires<ArgumentException>(collection.All(e => e != null), $"{parameterName} collection cannot contain any null elements"); #else if (collection == null) { throw new ArgumentNullException(parameterName); } foreach (T t in collection) { if (t == null) { throw new ArgumentException($"{parameterName} collection cannot contain any null elements", paramName: parameterName); } } #endif } [ContractAbbreviator] public static void NotNullOrEmpty(string value, string parameterName) { #if CODECONTRACTS Contract.Requires<ArgumentNullException>(value != null); Contract.Requires<ArgumentException>(value.Length > 0, $"{parameterName} string must not be empty"); #else if (value == null) { throw new ArgumentNullException(parameterName); } if (value.Length == 0) { throw new ArgumentException($"{parameterName} string must not be empty", paramName: parameterName); } #endif } /// <summary> /// Throws an <see cref="ArgumentException" /> if <paramref name="value" /> is empty or all whitespace. /// Throws an <see cref="ArgumentNullException" /> if <paramref name="value" /> is <c>null</c>. /// </summary> /// <param name="value"></param> /// <param name="parameterName"></param> [ContractAbbreviator] public static void NotNullOrWhitespace(string value, string parameterName) { #if CODECONTRACTS Contract.Requires<ArgumentNullException>(value != null); Contract.Requires<ArgumentException>(! string.IsNullOrWhiteSpace(value), $"The argument for parameter {parameterName} must not be all whitespace."); #else if (value == null) { throw new ArgumentNullException(parameterName); } int i = 0; for (; i < value.Length; i++) { if (! char.IsWhiteSpace(value[i])) { break; } } if (i == value.Length) { throw new ArgumentException($"The argument for parameter {parameterName} must not be empty or all whitespace.", paramName: parameterName); } #endif } [ContractAbbreviator] public static void InRange(int value, int minimum, int maximum, string parameterName) { #if CODECONTRACTS Contract.Requires<ArgumentOutOfRangeException>(value >= minimum, $"{parameterName} value {value} cannot be less than {minimum}."); Contract.Requires<ArgumentOutOfRangeException>(value <= maximum, $"{parameterName} value {value} cannot be greater than {maximum}."); #else if (value < minimum) { throw new ArgumentOutOfRangeException(paramName: parameterName, actualValue: value, message: $"{parameterName} value {value} cannot be less than {minimum}."); } if (value > maximum) { throw new ArgumentOutOfRangeException(paramName: parameterName, actualValue: value, message: $"{parameterName} value {value} cannot be greater than {maximum}."); } #endif } [ContractAbbreviator] public static void Requires(bool assertion, string assertionDescription) { #if CODECONTRACTS Contract.Requires<ArgumentException>(assertion, assertionDescription); #else if (! assertion) { throw new ArgumentException(assertionDescription); } #endif } [ContractAbbreviator] [Conditional("DEBUG")] public static void DebugRequires(bool assertion, string assertionDescription) { #if CODECONTRACTS Contract.Requires<ArgumentException>(assertion, assertionDescription); #else if (! assertion) { throw new ArgumentException(assertionDescription); } #endif } /// <summary> /// Verifies that <paramref name="value" /> is of type <typeparamref name="T" />. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="value">The value of the parameter.</param> /// <param name="parameterName">The name of the parameter.</param> /// <param name="message"></param> [ContractAbbreviator] public static void Is<T>(object value, string parameterName, string message = null) { #if CODECONTRACTS Contract.Requires<ArgumentException>((value is T), message); #else if (! (value is T)) { if (message != null) { throw new ArgumentException($"Must be type {typeof(T).FullName}", paramName: parameterName); } else { throw new ArgumentException(message, paramName: parameterName); } } #endif } /// <summary> /// Verifies that <paramref name="value" /> is NOT of type <typeparamref name="T" />. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="value">The value of the parameter.</param> /// <param name="parameterName">The name of the parameter.</param> /// <param name="message"></param> [ContractAbbreviator] public static void IsNot<T>(object value, string parameterName, string message = null) { #if CODECONTRACTS Contract.Requires<ArgumentException>((value is T), message); #else if ((value is T)) { if (message != null) { throw new ArgumentException($"Must not be type {typeof(T).FullName}", paramName: parameterName); } else { throw new ArgumentException(message, paramName: parameterName); } } #endif } } }
/* * Copyright (c) 2008, openmetaverse.org * All rights reserved. * * - Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * - Neither the name of the openmetaverse.org nor the names * of its contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Runtime.InteropServices; using System.Globalization; namespace OpenMetaverse { /// <summary> /// A three-dimensional vector with doubleing-point values /// </summary> [Serializable] [StructLayout(LayoutKind.Sequential)] public struct Vector3d : IComparable<Vector3d>, IEquatable<Vector3d> { /// <summary>X value</summary> public double X; /// <summary>Y value</summary> public double Y; /// <summary>Z value</summary> public double Z; #region Constructors public Vector3d(double x, double y, double z) { X = x; Y = y; Z = z; } public Vector3d(double value) { X = value; Y = value; Z = value; } /// <summary> /// Constructor, builds a vector from a byte array /// </summary> /// <param name="byteArray">Byte array containing three eight-byte doubles</param> /// <param name="pos">Beginning position in the byte array</param> public Vector3d(byte[] byteArray, int pos) { X = Y = Z = 0d; FromBytes(byteArray, pos); } public Vector3d(Vector3 vector) { X = vector.X; Y = vector.Y; Z = vector.Z; } public Vector3d(Vector3d vector) { X = vector.X; Y = vector.Y; Z = vector.Z; } #endregion Constructors #region Public Methods public double Length() { return Math.Sqrt(DistanceSquared(this, Zero)); } public double LengthSquared() { return DistanceSquared(this, Zero); } public void Normalize() { this = Normalize(this); } /// <summary> /// Test if this vector is equal to another vector, within a given /// tolerance range /// </summary> /// <param name="vec">Vector to test against</param> /// <param name="tolerance">The acceptable magnitude of difference /// between the two vectors</param> /// <returns>True if the magnitude of difference between the two vectors /// is less than the given tolerance, otherwise false</returns> public bool ApproxEquals(Vector3d vec, double tolerance) { Vector3d diff = this - vec; return (diff.Length() <= tolerance); } /// <summary> /// IComparable.CompareTo implementation /// </summary> public int CompareTo(Vector3d vector) { return this.Length().CompareTo(vector.Length()); } /// <summary> /// Test if this vector is composed of all finite numbers /// </summary> public bool IsFinite() { return (Utils.IsFinite(X) && Utils.IsFinite(Y) && Utils.IsFinite(Z)); } /// <summary> /// Builds a vector from a byte array /// </summary> /// <param name="byteArray">Byte array containing a 24 byte vector</param> /// <param name="pos">Beginning position in the byte array</param> public void FromBytes(byte[] byteArray, int pos) { if (!BitConverter.IsLittleEndian) { // Big endian architecture byte[] conversionBuffer = new byte[24]; Buffer.BlockCopy(byteArray, pos, conversionBuffer, 0, 24); Array.Reverse(conversionBuffer, 0, 8); Array.Reverse(conversionBuffer, 8, 8); Array.Reverse(conversionBuffer, 16, 8); X = BitConverter.ToDouble(conversionBuffer, 0); Y = BitConverter.ToDouble(conversionBuffer, 8); Z = BitConverter.ToDouble(conversionBuffer, 16); } else { // Little endian architecture X = BitConverter.ToDouble(byteArray, pos); Y = BitConverter.ToDouble(byteArray, pos + 8); Z = BitConverter.ToDouble(byteArray, pos + 16); } } /// <summary> /// Returns the raw bytes for this vector /// </summary> /// <returns>A 24 byte array containing X, Y, and Z</returns> public byte[] GetBytes() { byte[] byteArray = new byte[24]; Buffer.BlockCopy(BitConverter.GetBytes(X), 0, byteArray, 0, 8); Buffer.BlockCopy(BitConverter.GetBytes(Y), 0, byteArray, 8, 8); Buffer.BlockCopy(BitConverter.GetBytes(Z), 0, byteArray, 16, 8); if (!BitConverter.IsLittleEndian) { Array.Reverse(byteArray, 0, 8); Array.Reverse(byteArray, 8, 8); Array.Reverse(byteArray, 16, 8); } return byteArray; } #endregion Public Methods #region Static Methods public static Vector3d Add(Vector3d value1, Vector3d value2) { value1.X += value2.X; value1.Y += value2.Y; value1.Z += value2.Z; return value1; } public static Vector3d Clamp(Vector3d value1, Vector3d min, Vector3d max) { return new Vector3d( Utils.Clamp(value1.X, min.X, max.X), Utils.Clamp(value1.Y, min.Y, max.Y), Utils.Clamp(value1.Z, min.Z, max.Z)); } public static Vector3d Cross(Vector3d value1, Vector3d value2) { return new Vector3d( value1.Y * value2.Z - value2.Y * value1.Z, value1.Z * value2.X - value2.Z * value1.X, value1.X * value2.Y - value2.X * value1.Y); } public static double Distance(Vector3d value1, Vector3d value2) { return Math.Sqrt(DistanceSquared(value1, value2)); } public static double DistanceSquared(Vector3d value1, Vector3d value2) { return (value1.X - value2.X) * (value1.X - value2.X) + (value1.Y - value2.Y) * (value1.Y - value2.Y) + (value1.Z - value2.Z) * (value1.Z - value2.Z); } public static Vector3d Divide(Vector3d value1, Vector3d value2) { value1.X /= value2.X; value1.Y /= value2.Y; value1.Z /= value2.Z; return value1; } public static Vector3d Divide(Vector3d value1, double value2) { double factor = 1d / value2; value1.X *= factor; value1.Y *= factor; value1.Z *= factor; return value1; } public static double Dot(Vector3d value1, Vector3d value2) { return value1.X * value2.X + value1.Y * value2.Y + value1.Z * value2.Z; } public static Vector3d Lerp(Vector3d value1, Vector3d value2, double amount) { return new Vector3d( Utils.Lerp(value1.X, value2.X, amount), Utils.Lerp(value1.Y, value2.Y, amount), Utils.Lerp(value1.Z, value2.Z, amount)); } public static Vector3d Max(Vector3d value1, Vector3d value2) { return new Vector3d( Math.Max(value1.X, value2.X), Math.Max(value1.Y, value2.Y), Math.Max(value1.Z, value2.Z)); } public static Vector3d Min(Vector3d value1, Vector3d value2) { return new Vector3d( Math.Min(value1.X, value2.X), Math.Min(value1.Y, value2.Y), Math.Min(value1.Z, value2.Z)); } public static Vector3d Multiply(Vector3d value1, Vector3d value2) { value1.X *= value2.X; value1.Y *= value2.Y; value1.Z *= value2.Z; return value1; } public static Vector3d Multiply(Vector3d value1, double scaleFactor) { value1.X *= scaleFactor; value1.Y *= scaleFactor; value1.Z *= scaleFactor; return value1; } public static Vector3d Negate(Vector3d value) { value.X = -value.X; value.Y = -value.Y; value.Z = -value.Z; return value; } public static Vector3d Normalize(Vector3d value) { double factor = Distance(value, Zero); if (factor > Double.Epsilon) { factor = 1d / factor; value.X *= factor; value.Y *= factor; value.Z *= factor; } else { value.X = 0d; value.Y = 0d; value.Z = 0d; } return value; } /// <summary> /// Parse a vector from a string /// </summary> /// <param name="val">A string representation of a 3D vector, enclosed /// in arrow brackets and separated by commas</param> public static Vector3d Parse(string val) { char[] splitChar = { ',' }; string[] split = val.Replace("<", String.Empty).Replace(">", String.Empty).Split(splitChar); return new Vector3d( Double.Parse(split[0].Trim(), Utils.EnUsCulture), Double.Parse(split[1].Trim(), Utils.EnUsCulture), Double.Parse(split[2].Trim(), Utils.EnUsCulture)); } public static bool TryParse(string val, out Vector3d result) { try { result = Parse(val); return true; } catch (Exception) { result = Vector3d.Zero; return false; } } /// <summary> /// Interpolates between two vectors using a cubic equation /// </summary> public static Vector3d SmoothStep(Vector3d value1, Vector3d value2, double amount) { return new Vector3d( Utils.SmoothStep(value1.X, value2.X, amount), Utils.SmoothStep(value1.Y, value2.Y, amount), Utils.SmoothStep(value1.Z, value2.Z, amount)); } public static Vector3d Subtract(Vector3d value1, Vector3d value2) { value1.X -= value2.X; value1.Y -= value2.Y; value1.Z -= value2.Z; return value1; } #endregion Static Methods #region Overrides public override bool Equals(object obj) { return (obj is Vector3d) ? this == (Vector3d)obj : false; } public bool Equals(Vector3d other) { return this == other; } public override int GetHashCode() { return X.GetHashCode() ^ Y.GetHashCode() ^ Z.GetHashCode(); } /// <summary> /// Get a formatted string representation of the vector /// </summary> /// <returns>A string representation of the vector</returns> public override string ToString() { return String.Format(Utils.EnUsCulture, "<{0}, {1}, {2}>", X, Y, Z); } /// <summary> /// Get a string representation of the vector elements with up to three /// decimal digits and separated by spaces only /// </summary> /// <returns>Raw string representation of the vector</returns> public string ToRawString() { CultureInfo enUs = new CultureInfo("en-us"); enUs.NumberFormat.NumberDecimalDigits = 3; return String.Format(enUs, "{0} {1} {2}", X, Y, Z); } #endregion Overrides #region Operators public static bool operator ==(Vector3d value1, Vector3d value2) { return value1.X == value2.X && value1.Y == value2.Y && value1.Z == value2.Z; } public static bool operator !=(Vector3d value1, Vector3d value2) { return !(value1 == value2); } public static Vector3d operator +(Vector3d value1, Vector3d value2) { value1.X += value2.X; value1.Y += value2.Y; value1.Z += value2.Z; return value1; } public static Vector3d operator -(Vector3d value) { value.X = -value.X; value.Y = -value.Y; value.Z = -value.Z; return value; } public static Vector3d operator -(Vector3d value1, Vector3d value2) { value1.X -= value2.X; value1.Y -= value2.Y; value1.Z -= value2.Z; return value1; } public static Vector3d operator *(Vector3d value1, Vector3d value2) { value1.X *= value2.X; value1.Y *= value2.Y; value1.Z *= value2.Z; return value1; } public static Vector3d operator *(Vector3d value, double scaleFactor) { value.X *= scaleFactor; value.Y *= scaleFactor; value.Z *= scaleFactor; return value; } public static Vector3d operator /(Vector3d value1, Vector3d value2) { value1.X /= value2.X; value1.Y /= value2.Y; value1.Z /= value2.Z; return value1; } public static Vector3d operator /(Vector3d value, double divider) { double factor = 1d / divider; value.X *= factor; value.Y *= factor; value.Z *= factor; return value; } /// <summary> /// Cross product between two vectors /// </summary> public static Vector3d operator %(Vector3d value1, Vector3d value2) { return Cross(value1, value2); } #endregion Operators /// <summary>A vector with a value of 0,0,0</summary> public readonly static Vector3d Zero = new Vector3d(); /// <summary>A vector with a value of 1,1,1</summary> public readonly static Vector3d One = new Vector3d(); /// <summary>A unit vector facing forward (X axis), value of 1,0,0</summary> public readonly static Vector3d UnitX = new Vector3d(1d, 0d, 0d); /// <summary>A unit vector facing left (Y axis), value of 0,1,0</summary> public readonly static Vector3d UnitY = new Vector3d(0d, 1d, 0d); /// <summary>A unit vector facing up (Z axis), value of 0,0,1</summary> public readonly static Vector3d UnitZ = new Vector3d(0d, 0d, 1d); } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Collections.ObjectModel; using System.Linq; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using System.Runtime.CompilerServices; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.CSharp.UnitTests; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests; using Microsoft.DiaSymReader; using Microsoft.VisualStudio.Debugger.Clr; using Microsoft.VisualStudio.Debugger.Evaluation; using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.UnitTests { public abstract class ExpressionCompilerTestBase : CSharpTestBase, IDisposable { private readonly ArrayBuilder<IDisposable> _runtimeInstances = ArrayBuilder<IDisposable>.GetInstance(); internal static readonly ImmutableArray<Alias> NoAliases = ImmutableArray<Alias>.Empty; protected ExpressionCompilerTestBase() { // We never want to swallow Exceptions (generate a non-fatal Watson) when running tests. ExpressionEvaluatorFatalError.IsFailFastEnabled = true; } public override void Dispose() { base.Dispose(); foreach (var instance in _runtimeInstances) { instance.Dispose(); } _runtimeInstances.Free(); } internal static void WithRuntimeInstance(Compilation compilation, Action<RuntimeInstance> validator) { WithRuntimeInstance(compilation, null, true, validator); } internal static void WithRuntimeInstance(Compilation compilation, IEnumerable<MetadataReference> references, Action<RuntimeInstance> validator) { WithRuntimeInstance(compilation, references, true, validator); } internal static void WithRuntimeInstance(Compilation compilation, IEnumerable<MetadataReference> references, bool includeLocalSignatures, Action<RuntimeInstance> validator) { foreach (var debugFormat in new[] { DebugInformationFormat.Pdb, DebugInformationFormat.PortablePdb }) { using (var instance = RuntimeInstance.Create(compilation, references, debugFormat, includeLocalSignatures)) { validator(instance); } } } internal RuntimeInstance CreateRuntimeInstance(IEnumerable<ModuleInstance> modules) { var instance = RuntimeInstance.Create(modules); _runtimeInstances.Add(instance); return instance; } internal RuntimeInstance CreateRuntimeInstance( Compilation compilation, IEnumerable<MetadataReference> references = null, DebugInformationFormat debugFormat = DebugInformationFormat.Pdb, bool includeLocalSignatures = true) { var instance = RuntimeInstance.Create(compilation, references, debugFormat, includeLocalSignatures); _runtimeInstances.Add(instance); return instance; } internal RuntimeInstance CreateRuntimeInstance( ModuleInstance module, IEnumerable<MetadataReference> references) { var instance = RuntimeInstance.Create(module, references, DebugInformationFormat.Pdb); _runtimeInstances.Add(instance); return instance; } internal static void GetContextState( RuntimeInstance runtime, string methodOrTypeName, out ImmutableArray<MetadataBlock> blocks, out Guid moduleVersionId, out ISymUnmanagedReader symReader, out int methodOrTypeToken, out int localSignatureToken) { var moduleInstances = runtime.Modules; blocks = moduleInstances.SelectAsArray(m => m.MetadataBlock); var compilation = blocks.ToCompilation(); var methodOrType = GetMethodOrTypeBySignature(compilation, methodOrTypeName); var module = (PEModuleSymbol)methodOrType.ContainingModule; var id = module.Module.GetModuleVersionIdOrThrow(); var moduleInstance = moduleInstances.First(m => m.ModuleVersionId == id); moduleVersionId = id; symReader = (ISymUnmanagedReader)moduleInstance.SymReader; EntityHandle methodOrTypeHandle; if (methodOrType.Kind == SymbolKind.Method) { methodOrTypeHandle = ((PEMethodSymbol)methodOrType).Handle; localSignatureToken = moduleInstance.GetLocalSignatureToken((MethodDefinitionHandle)methodOrTypeHandle); } else { methodOrTypeHandle = ((PENamedTypeSymbol)methodOrType).Handle; localSignatureToken = -1; } MetadataReader reader = null; // null should be ok methodOrTypeToken = reader.GetToken(methodOrTypeHandle); } internal static EvaluationContext CreateMethodContext( RuntimeInstance runtime, string methodName, int atLineNumber = -1) { ImmutableArray<MetadataBlock> blocks; Guid moduleVersionId; ISymUnmanagedReader symReader; int methodToken; int localSignatureToken; GetContextState(runtime, methodName, out blocks, out moduleVersionId, out symReader, out methodToken, out localSignatureToken); uint ilOffset = ExpressionCompilerTestHelpers.GetOffset(methodToken, symReader, atLineNumber); return EvaluationContext.CreateMethodContext( default(CSharpMetadataContext), blocks, symReader, moduleVersionId, methodToken: methodToken, methodVersion: 1, ilOffset: ilOffset, localSignatureToken: localSignatureToken); } internal static EvaluationContext CreateTypeContext( RuntimeInstance runtime, string typeName) { ImmutableArray<MetadataBlock> blocks; Guid moduleVersionId; ISymUnmanagedReader symReader; int typeToken; int localSignatureToken; GetContextState(runtime, typeName, out blocks, out moduleVersionId, out symReader, out typeToken, out localSignatureToken); return EvaluationContext.CreateTypeContext( default(CSharpMetadataContext), blocks, moduleVersionId, typeToken); } internal CompilationTestData Evaluate( string source, OutputKind outputKind, string methodName, string expr, int atLineNumber = -1, bool includeSymbols = true) { ResultProperties resultProperties; string error; var result = Evaluate(source, outputKind, methodName, expr, out resultProperties, out error, atLineNumber, includeSymbols); Assert.Null(error); return result; } internal CompilationTestData Evaluate( string source, OutputKind outputKind, string methodName, string expr, out ResultProperties resultProperties, out string error, int atLineNumber = -1, bool includeSymbols = true) { var compilation0 = CreateCompilationWithMscorlib( source, options: (outputKind == OutputKind.DynamicallyLinkedLibrary) ? TestOptions.DebugDll : TestOptions.DebugExe); var runtime = CreateRuntimeInstance(compilation0, debugFormat: includeSymbols ? DebugInformationFormat.Pdb : 0); var context = CreateMethodContext(runtime, methodName, atLineNumber); var testData = new CompilationTestData(); ImmutableArray<AssemblyIdentity> missingAssemblyIdentities; var result = context.CompileExpression( expr, DkmEvaluationFlags.TreatAsExpression, NoAliases, DebuggerDiagnosticFormatter.Instance, out resultProperties, out error, out missingAssemblyIdentities, EnsureEnglishUICulture.PreferredOrNull, testData); Assert.Empty(missingAssemblyIdentities); return testData; } /// <summary> /// Verify all type parameters from the method /// are from that method or containing types. /// </summary> internal static void VerifyTypeParameters(MethodSymbol method) { Assert.True(method.IsContainingSymbolOfAllTypeParameters(method.ReturnType)); AssertEx.All(method.TypeParameters, typeParameter => method.IsContainingSymbolOfAllTypeParameters(typeParameter)); AssertEx.All(method.TypeArguments, typeArgument => method.IsContainingSymbolOfAllTypeParameters(typeArgument)); AssertEx.All(method.Parameters, parameter => method.IsContainingSymbolOfAllTypeParameters(parameter.Type)); VerifyTypeParameters(method.ContainingType); } internal static void VerifyLocal( CompilationTestData testData, string typeName, LocalAndMethod localAndMethod, string expectedMethodName, string expectedLocalName, string expectedLocalDisplayName = null, DkmClrCompilationResultFlags expectedFlags = DkmClrCompilationResultFlags.None, string expectedILOpt = null, bool expectedGeneric = false, [CallerFilePath]string expectedValueSourcePath = null, [CallerLineNumber]int expectedValueSourceLine = 0) { ExpressionCompilerTestHelpers.VerifyLocal<MethodSymbol>( testData, typeName, localAndMethod, expectedMethodName, expectedLocalName, expectedLocalDisplayName ?? expectedLocalName, expectedFlags, VerifyTypeParameters, expectedILOpt, expectedGeneric, expectedValueSourcePath, expectedValueSourceLine); } /// <summary> /// Verify all type parameters from the type /// are from that type or containing types. /// </summary> internal static void VerifyTypeParameters(NamedTypeSymbol type) { AssertEx.All(type.TypeParameters, typeParameter => type.IsContainingSymbolOfAllTypeParameters(typeParameter)); AssertEx.All(type.TypeArguments, typeArgument => type.IsContainingSymbolOfAllTypeParameters(typeArgument)); var container = type.ContainingType; if ((object)container != null) { VerifyTypeParameters(container); } } internal static Symbol GetMethodOrTypeBySignature(Compilation compilation, string signature) { string[] parameterTypeNames; var methodOrTypeName = ExpressionCompilerTestHelpers.GetMethodOrTypeSignatureParts(signature, out parameterTypeNames); var candidates = compilation.GetMembers(methodOrTypeName); var methodOrType = (parameterTypeNames == null) ? candidates.FirstOrDefault() : candidates.FirstOrDefault(c => parameterTypeNames.SequenceEqual(((MethodSymbol)c).Parameters.Select(p => p.Type.Name))); Assert.False(methodOrType == null, "Could not find method or type with signature '" + signature + "'."); return methodOrType; } internal static Alias VariableAlias(string name, Type type = null) { return VariableAlias(name, (type ?? typeof(object)).AssemblyQualifiedName); } internal static Alias VariableAlias(string name, string typeAssemblyQualifiedName) { return new Alias(DkmClrAliasKind.Variable, name, name, typeAssemblyQualifiedName, default(Guid), null); } internal static Alias ObjectIdAlias(uint id, Type type = null) { return ObjectIdAlias(id, (type ?? typeof(object)).AssemblyQualifiedName); } internal static Alias ObjectIdAlias(uint id, string typeAssemblyQualifiedName) { Assert.NotEqual(0u, id); // Not a valid id. var name = $"${id}"; return new Alias(DkmClrAliasKind.ObjectId, name, name, typeAssemblyQualifiedName, default(Guid), null); } internal static Alias ReturnValueAlias(int id = -1, Type type = null) { return ReturnValueAlias(id, (type ?? typeof(object)).AssemblyQualifiedName); } internal static Alias ReturnValueAlias(int id, string typeAssemblyQualifiedName) { var name = $"Method M{(id < 0 ? "" : id.ToString())} returned"; var fullName = id < 0 ? "$ReturnValue" : $"$ReturnValue{id}"; return new Alias(DkmClrAliasKind.ReturnValue, name, fullName, typeAssemblyQualifiedName, default(Guid), null); } internal static Alias ExceptionAlias(Type type = null, bool stowed = false) { return ExceptionAlias((type ?? typeof(Exception)).AssemblyQualifiedName, stowed); } internal static Alias ExceptionAlias(string typeAssemblyQualifiedName, bool stowed = false) { var name = "Error"; var fullName = stowed ? "$stowedexception" : "$exception"; var kind = stowed ? DkmClrAliasKind.StowedException : DkmClrAliasKind.Exception; return new Alias(kind, name, fullName, typeAssemblyQualifiedName, default(Guid), null); } internal static Alias Alias(DkmClrAliasKind kind, string name, string fullName, string type, ReadOnlyCollection<byte> payload) { return new Alias(kind, name, fullName, type, (payload == null) ? default(Guid) : CustomTypeInfo.PayloadTypeId, payload); } internal static MethodDebugInfo<TypeSymbol, LocalSymbol> GetMethodDebugInfo(RuntimeInstance runtime, string qualifiedMethodName, int ilOffset = 0) { var peCompilation = runtime.Modules.SelectAsArray(m => m.MetadataBlock).ToCompilation(); var peMethod = peCompilation.GlobalNamespace.GetMember<PEMethodSymbol>(qualifiedMethodName); var peModule = (PEModuleSymbol)peMethod.ContainingModule; var symReader = runtime.Modules.Single(mi => mi.ModuleVersionId == peModule.Module.GetModuleVersionIdOrThrow()).SymReader; var symbolProvider = new CSharpEESymbolProvider(peCompilation.SourceAssembly, peModule, peMethod); return MethodDebugInfo<TypeSymbol, LocalSymbol>.ReadMethodDebugInfo((ISymUnmanagedReader3)symReader, symbolProvider, MetadataTokens.GetToken(peMethod.Handle), methodVersion: 1, ilOffset: ilOffset, isVisualBasicMethod: false); } internal static SynthesizedAttributeData GetDynamicAttributeIfAny(IMethodSymbol method) { return GetAttributeIfAny(method, "System.Runtime.CompilerServices.DynamicAttribute"); } internal static SynthesizedAttributeData GetTupleElementNamesAttributeIfAny(IMethodSymbol method) { return GetAttributeIfAny(method, "System.Runtime.CompilerServices.TupleElementNamesAttribute"); } internal static SynthesizedAttributeData GetAttributeIfAny(IMethodSymbol method, string typeName) { return method.GetSynthesizedAttributes(forReturnType: true). Where(a => a.AttributeClass.ToTestDisplayString() == typeName). SingleOrDefault(); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text.RegularExpressions; using Palaso.Code; using Palaso.WritingSystems.Collation; namespace Palaso.WritingSystems { /// <summary> /// This class stores the information used to define various writing system properties. The Language, Script, Region and Variant /// properties conform to the subtags of the same name defined in BCP47 (Rfc5646) and are enforced by the Rfc5646Tag class. it is worth /// noting that for historical reasons this class does not provide seperate fields for variant and private use components as /// defined in BCP47. Instead the ConcatenateVariantAndPrivateUse and SplitVariantAndPrivateUse methods are provided for consumers /// to generate a single variant subtag that contains both fields seperated by "-x-". /// Furthermore the WritingSystemDefinition.WellknownSubtags class provides certain well defined Subtags that carry special meaning /// apart from the IANA subtag registry. In particular this class defines "qaa" as the default "unlisted language" language subtag. /// It should be used when there is no match for a language in the IANA subtag registry. Private use properties are "emic" and "etic" /// which mark phonemic and phonetic writing systems respectively. These must always be used in conjunction with the "fonipa" variant. /// Likewise "audio" marks a writing system as audio and must always be used in conjunction with script "Zxxx". Convenience methods /// are provided for Ipa and Audio properties as IpaStatus and IsVoice respectively. /// </summary> public class WritingSystemDefinition : IClonableGeneric<WritingSystemDefinition>, IWritingSystemDefinition, ILegacyWritingSystemDefinition { public enum SortRulesType { /// <summary> /// Default Unicode ordering rules (actually CustomICU without any rules) /// </summary> [Description("Default Ordering")] DefaultOrdering, /// <summary> /// Custom Simple (Shoebox/Toolbox) style rules /// </summary> [Description("Custom Simple (Shoebox style) rules")] CustomSimple, /// <summary> /// Custom ICU rules /// </summary> [Description("Custom ICU rules")] CustomICU, /// <summary> /// Use the sort rules from another language. When this is set, the SortRules are interpreted as a cultureId for the language to sort like. /// </summary> [Description("Same as another language")] OtherLanguage } //This is the version of our writingsystemDefinition implementation and is mostly used for migration purposes. //This should not be confused with the version of the locale data contained in this writing system. //That information is stored in the "VersionNumber" property. public const int LatestWritingSystemDefinitionVersion = 2; private RFC5646Tag _rfcTag; private const int kMinimumFontSize=7; private const int kDefaultSizeIfWeDontKnow = 10; private string _languageName; private string _abbreviation; private bool _isUnicodeEncoded; private string _versionNumber; private string _versionDescription; private DateTime _dateModified; private string _defaultFontName; private float _defaultFontSize; private string _keyboard; private SortRulesType _sortUsing; private string _sortRules; private string _spellCheckingId; private string _nativeName; private bool _rightToLeftScript; private ICollator _collator; private string _id; /// <summary> /// Creates a new WritingSystemDefinition with Language subtag set to "qaa" /// </summary> public WritingSystemDefinition() { _sortUsing = SortRulesType.DefaultOrdering; _isUnicodeEncoded = true; _rfcTag = new RFC5646Tag(); UpdateIdFromRfcTag(); } /// <summary> /// Creates a new WritingSystemDefinition by parsing a valid BCP47 tag /// </summary> /// <param name="bcp47Tag">A valid BCP47 tag</param> public WritingSystemDefinition(string bcp47Tag) : this() { _rfcTag = RFC5646Tag.Parse(bcp47Tag); _abbreviation = _languageName = _nativeName = string.Empty; UpdateIdFromRfcTag(); } /// <summary> /// True when the validity of the writing system defn's tag is being enforced. This is the normal and default state. /// Setting this true will throw unless the tag has previously been put into a valid state. /// Attempting to Save the writing system defn will set this true (and may throw). /// </summary> public bool RequiresValidTag { get { return _rfcTag.RequiresValidTag; } set { _rfcTag.RequiresValidTag = value; CheckVariantAndScriptRules(); } } /// <summary> /// Creates a new WritingSystemDefinition /// </summary> /// <param name="language">A valid BCP47 language subtag</param> /// <param name="script">A valid BCP47 script subtag</param> /// <param name="region">A valid BCP47 region subtag</param> /// <param name="variant">A valid BCP47 variant subtag</param> /// <param name="abbreviation">The desired abbreviation for this writing system definition</param> /// <param name="rightToLeftScript">Indicates whether this writing system uses a right to left script</param> public WritingSystemDefinition(string language, string script, string region, string variant, string abbreviation, bool rightToLeftScript) : this() { string variantPart; string privateUsePart; SplitVariantAndPrivateUse(variant, out variantPart, out privateUsePart); _rfcTag = new RFC5646Tag(language, script, region, variantPart, privateUsePart); _abbreviation = abbreviation; _rightToLeftScript = rightToLeftScript; UpdateIdFromRfcTag(); } /// <summary> /// Copy constructor from IWritingSystem: useable only if the interface is in fact implemented by this class. /// </summary> /// <param name="ws"></param> internal WritingSystemDefinition(IWritingSystemDefinition ws) : this ((WritingSystemDefinition)ws) { } /// <summary> /// Copy constructor. /// </summary> /// <param name="ws">The ws.</param> public WritingSystemDefinition(WritingSystemDefinition ws) { _abbreviation = ws._abbreviation; _rightToLeftScript = ws._rightToLeftScript; _defaultFontName = ws._defaultFontName; _defaultFontSize = ws._defaultFontSize; _keyboard = ws._keyboard; _versionNumber = ws._versionNumber; _versionDescription = ws._versionDescription; _nativeName = ws._nativeName; _sortUsing = ws._sortUsing; _sortRules = ws._sortRules; _spellCheckingId = ws._spellCheckingId; _dateModified = ws._dateModified; _isUnicodeEncoded = ws._isUnicodeEncoded; _rfcTag = new RFC5646Tag(ws._rfcTag); _languageName = ws._languageName; if (ws._localKeyboard != null) _localKeyboard = ws._localKeyboard.Clone(); WindowsLcid = ws.WindowsLcid; foreach (var kbd in ws._knownKeyboards) _knownKeyboards.Add(kbd.Clone()); _id = ws._id; } ///<summary> ///This is the version of the locale data contained in this writing system. ///This should not be confused with the version of our writingsystemDefinition implementation which is mostly used for migration purposes. ///That information is stored in the "LatestWritingSystemDefinitionVersion" property. ///</summary> virtual public string VersionNumber { get { return _versionNumber; } set { UpdateString(ref _versionNumber, value); } } virtual public string VersionDescription { get { return _versionDescription; } set { UpdateString(ref _versionDescription, value); } } virtual public DateTime DateModified { get { return _dateModified; } set { _dateModified = value; } } public IEnumerable<Iso639LanguageCode> ValidLanguages { get { return StandardTags.ValidIso639LanguageCodes; } } public IEnumerable<Iso15924Script> ValidScript { get { return StandardTags.ValidIso15924Scripts; } } public IEnumerable<IanaSubtag> ValidRegions { get { return StandardTags.ValidIso3166Regions; } } public IEnumerable<IanaSubtag> ValidVariants { get { foreach (var variant in StandardTags.ValidRegisteredVariants) { yield return variant; } } } /// <summary> /// Adjusts the BCP47 tag to indicate the desired form of Ipa by inserting fonipa in the variant and emic or etic in private use where necessary. /// </summary> virtual public IpaStatusChoices IpaStatus { get { if (Rfc5646TagIsPhonemicConform) { return IpaStatusChoices.IpaPhonemic; } if (Rfc5646TagIsPhoneticConform) { return IpaStatusChoices.IpaPhonetic; } if (VariantSubTagIsIpaConform) { return IpaStatusChoices.Ipa; } return IpaStatusChoices.NotIpa; } set { if (IpaStatus == value) { return; } //We need this to make sure that our language tag won't start with the variant "fonipa" if(_rfcTag.Language == "") { _rfcTag.Language = WellKnownSubTags.Unlisted.Language; } _rfcTag.RemoveFromPrivateUse(WellKnownSubTags.Audio.PrivateUseSubtag); /* "There are some variant subtags that have no prefix field, * eg. fonipa (International IpaPhonetic Alphabet). Such variants * should appear after any other variant subtags with prefix information." */ _rfcTag.RemoveFromPrivateUse("x-etic"); _rfcTag.RemoveFromPrivateUse("x-emic"); _rfcTag.RemoveFromVariant("fonipa"); switch (value) { default: break; case IpaStatusChoices.Ipa: _rfcTag.AddToVariant(WellKnownSubTags.Ipa.VariantSubtag); break; case IpaStatusChoices.IpaPhonemic: _rfcTag.AddToVariant(WellKnownSubTags.Ipa.VariantSubtag); _rfcTag.AddToPrivateUse(WellKnownSubTags.Ipa.PhonemicPrivateUseSubtag); break; case IpaStatusChoices.IpaPhonetic: _rfcTag.AddToVariant(WellKnownSubTags.Ipa.VariantSubtag); _rfcTag.AddToPrivateUse(WellKnownSubTags.Ipa.PhoneticPrivateUseSubtag); break; } Modified = true; UpdateIdFromRfcTag(); } } /// <summary> /// Adjusts the BCP47 tag to indicate that this is an "audio writing system" by inserting "audio" in the private use and "Zxxx" in the script /// </summary> virtual public bool IsVoice { get { return ScriptSubTagIsAudio && VariantSubTagIsAudio; } set { if (IsVoice == value) { return; } if (value) { IpaStatus = IpaStatusChoices.NotIpa; Keyboard = string.Empty; if(Language == "") { Language = WellKnownSubTags.Unlisted.Language; } Script = WellKnownSubTags.Audio.Script; _rfcTag.AddToPrivateUse(WellKnownSubTags.Audio.PrivateUseSubtag); } else { _rfcTag.Script = String.Empty; _rfcTag.RemoveFromPrivateUse(WellKnownSubTags.Audio.PrivateUseSubtag); } Modified = true; UpdateIdFromRfcTag(); CheckVariantAndScriptRules(); } } private bool VariantSubTagIsAudio { get { return _rfcTag.PrivateUseContains(WellKnownSubTags.Audio.PrivateUseSubtag); } } private bool ScriptSubTagIsAudio { get { return _rfcTag.Script.Equals(WellKnownSubTags.Audio.Script,StringComparison.OrdinalIgnoreCase); } } /// <summary> /// A string representing the subtag of the same name as defined by BCP47. /// Note that the variant also includes the private use subtags. These are appended to the variant subtags seperated by "-x-" /// Also note the convenience methods "SplitVariantAndPrivateUse" and "ConcatenateVariantAndPrivateUse" for easier /// variant/ private use handling /// </summary> // Todo: this could/should become an ordered list of variant tags virtual public string Variant { get { string variantToReturn = ConcatenateVariantAndPrivateUse(_rfcTag.Variant, _rfcTag.PrivateUse); return variantToReturn; } set { value = value ?? ""; if (value == Variant) { return; } // Note that the WritingSystemDefinition provides no direct support for private use except via Variant set. string variant; string privateUse; SplitVariantAndPrivateUse(value, out variant, out privateUse); _rfcTag.Variant = variant; _rfcTag.PrivateUse = privateUse; Modified = true; UpdateIdFromRfcTag(); CheckVariantAndScriptRules(); } } /// <summary> /// Adds a valid BCP47 registered variant subtag to the variant. Any other tag is inserted as private use. /// </summary> /// <param name="registeredVariantOrPrivateUseSubtag">A valid variant tag or another tag which will be inserted into private use.</param> public void AddToVariant(string registeredVariantOrPrivateUseSubtag) { if (StandardTags.IsValidRegisteredVariant(registeredVariantOrPrivateUseSubtag)) { _rfcTag.AddToVariant(registeredVariantOrPrivateUseSubtag); } else { _rfcTag.AddToPrivateUse(registeredVariantOrPrivateUseSubtag); } UpdateIdFromRfcTag(); CheckVariantAndScriptRules(); } /// <summary> /// A convenience method to help consumers deal with variant and private use subtags both being stored in the Variant property. /// This method will search the Variant part of the BCP47 tag for an "x" extension marker and split the tag into variant and private use sections /// Note the complementary method "ConcatenateVariantAndPrivateUse" /// </summary> /// <param name="variantAndPrivateUse">The string containing variant and private use sections seperated by an "x" private use subtag</param> /// <param name="variant">The resulting variant section</param> /// <param name="privateUse">The resulting private use section</param> public static void SplitVariantAndPrivateUse(string variantAndPrivateUse, out string variant, out string privateUse) { if (variantAndPrivateUse.StartsWith("x-",StringComparison.OrdinalIgnoreCase)) // Private Use at the beginning { variantAndPrivateUse = variantAndPrivateUse.Substring(2); // Strip the leading x- variant = ""; privateUse = variantAndPrivateUse; } else if (variantAndPrivateUse.Contains("-x-", StringComparison.OrdinalIgnoreCase)) // Private Use from the middle { string[] partsOfVariant = variantAndPrivateUse.Split(new[] { "-x-" }, StringSplitOptions.None); if(partsOfVariant.Length == 1) //Must have been a capital X { partsOfVariant = variantAndPrivateUse.Split(new[] { "-X-" }, StringSplitOptions.None); } variant = partsOfVariant[0]; privateUse = partsOfVariant[1]; } else // No Private Use, it's contains variants only { variant = variantAndPrivateUse; privateUse = ""; } } /// <summary> /// A convenience method to help consumers deal with registeredVariantSubtags and private use subtags both being stored in the Variant property. /// This method will insert a "x" private use subtag between a set of registered BCP47 variants and a set of private use subtags /// Note the complementary method "ConcatenateVariantAndPrivateUse" /// </summary> /// <param name="registeredVariantSubtags">A set of registered variant subtags</param> /// <param name="privateUseSubtags">A set of private use subtags</param> /// <returns>The resulting combination of registeredVariantSubtags and private use.</returns> public static string ConcatenateVariantAndPrivateUse(string registeredVariantSubtags, string privateUseSubtags) { if(String.IsNullOrEmpty(privateUseSubtags)) { return registeredVariantSubtags; } if(!privateUseSubtags.StartsWith("x-", StringComparison.OrdinalIgnoreCase)) { privateUseSubtags = String.Concat("x-", privateUseSubtags); } string variantToReturn = registeredVariantSubtags; if (!String.IsNullOrEmpty(privateUseSubtags)) { if (!String.IsNullOrEmpty(variantToReturn)) { variantToReturn += "-"; } variantToReturn += privateUseSubtags; } return variantToReturn; } private void CheckVariantAndScriptRules() { if (!RequiresValidTag) return; if (VariantSubTagIsAudio && !ScriptSubTagIsAudio) { throw new ArgumentException("The script subtag must be set to " + WellKnownSubTags.Audio.Script + " when the variant tag indicates an audio writing system."); } bool rfcTagHasAnyIpa = VariantSubTagIsIpaConform || _rfcTag.PrivateUseContains(WellKnownSubTags.Ipa.PhonemicPrivateUseSubtag) || _rfcTag.PrivateUseContains(WellKnownSubTags.Ipa.PhoneticPrivateUseSubtag); if (VariantSubTagIsAudio && rfcTagHasAnyIpa) { throw new ArgumentException("A writing system may not be marked as audio and ipa at the same time."); } if((_rfcTag.PrivateUseContains(WellKnownSubTags.Ipa.PhonemicPrivateUseSubtag) || _rfcTag.PrivateUseContains(WellKnownSubTags.Ipa.PhoneticPrivateUseSubtag)) && !VariantSubTagIsIpaConform) { throw new ArgumentException("A writing system may not be marked as phonetic (x-etic) or phonemic (x-emic) and lack the variant marker fonipa."); } } private bool VariantSubTagIsIpaConform { get { return _rfcTag.VariantContains(WellKnownSubTags.Ipa.VariantSubtag); } } private bool Rfc5646TagIsPhoneticConform { get { return _rfcTag.VariantContains(WellKnownSubTags.Ipa.VariantSubtag) && _rfcTag.PrivateUseContains(WellKnownSubTags.Ipa.PhoneticPrivateUseSubtag); } } private bool Rfc5646TagIsPhonemicConform { get { return _rfcTag.VariantContains(WellKnownSubTags.Ipa.VariantSubtag) && _rfcTag.PrivateUseContains(WellKnownSubTags.Ipa.PhonemicPrivateUseSubtag); } } /// <summary> /// Sets all BCP47 language tag components at once. /// This method is useful for avoiding invalid intermediate states when switching from one valid tag to another. /// </summary> /// <param name="language">A valid BCP47 language subtag.</param> /// <param name="script">A valid BCP47 script subtag.</param> /// <param name="region">A valid BCP47 region subtag.</param> /// <param name="variant">A valid BCP47 variant subtag.</param> public void SetAllComponents(string language, string script, string region, string variant) { string oldId = _rfcTag.CompleteTag; string variantPart; string privateUsePart; SplitVariantAndPrivateUse(variant, out variantPart, out privateUsePart); _rfcTag = new RFC5646Tag(language, script, region, variantPart, privateUsePart); UpdateIdFromRfcTag(); if(oldId == _rfcTag.CompleteTag) { return; } Modified = true; CheckVariantAndScriptRules(); } /// <summary> /// A string representing the subtag of the same name as defined by BCP47. /// </summary> virtual public string Region { get { return _rfcTag.Region; } set { value = value ?? ""; if (value == Region) { return; } _rfcTag.Region = value; UpdateIdFromRfcTag(); Modified = true; } } /// <summary> /// A string representing the subtag of the same name as defined by BCP47. /// </summary> virtual public string Language { get { return _rfcTag.Language; } set { value = value ?? ""; if (value == Language) { return; } _rfcTag.Language = value; UpdateIdFromRfcTag(); Modified = true; } } /// <summary> /// The desired abbreviation for the writing system /// </summary> virtual public string Abbreviation { get { if (String.IsNullOrEmpty(_abbreviation)) { // Use the language subtag unless it's an unlisted language. // If it's an unlisted language, use the private use area language subtag. if (Language == "qaa") { int idx = Id.IndexOf("-x-"); if (idx > 0 && Id.Length > idx + 3) { var abbr = Id.Substring(idx + 3); idx = abbr.IndexOf('-'); if (idx > 0) abbr = abbr.Substring(0, idx); return abbr; } } return Language; } return _abbreviation; } set { UpdateString(ref _abbreviation, value); } } /// <summary> /// A string representing the subtag of the same name as defined by BCP47. /// </summary> virtual public string Script { get { return _rfcTag.Script; } set { value = value ?? ""; if (value == Script) { return; } _rfcTag.Script = value; Modified = true; UpdateIdFromRfcTag(); CheckVariantAndScriptRules(); } } /// <summary> /// The language name to use. Typically this is the language name associated with the BCP47 language subtag as defined by the IANA subtag registry /// </summary> virtual public string LanguageName { get { if (!String.IsNullOrEmpty(_languageName)) { return _languageName; } var code = StandardTags.ValidIso639LanguageCodes.FirstOrDefault(c => c.Code.Equals(Language)); if (code != null) { return code.Name; } return "Unknown Language"; // TODO Make the below work. //return StandardTags.LanguageName(Language) ?? "Unknown Language"; } set { value = value ?? ""; UpdateString(ref _languageName, value); } } /// <summary> /// This method will make a copy of the given writing system and /// then make the Id unique compared to list of Ids passed in by /// appending dupl# where # is a digit that increases with the /// number of duplicates found. /// </summary> /// <param name="writingSystemToCopy"></param> /// <param name="otherWritingsystemIds"></param> /// <returns></returns> public static WritingSystemDefinition CreateCopyWithUniqueId( IWritingSystemDefinition writingSystemToCopy, IEnumerable<string> otherWritingsystemIds) { var newWs = writingSystemToCopy.Clone(); var lastAppended = String.Empty; int duplicateNumber = 0; while (otherWritingsystemIds.Any(id => id.Equals(newWs.Id, StringComparison.OrdinalIgnoreCase))) { newWs._rfcTag.RemoveFromPrivateUse(lastAppended); var currentToAppend = String.Format("dupl{0}", duplicateNumber); if (!newWs._rfcTag.PrivateUse.Contains(currentToAppend)) { newWs._rfcTag.AddToPrivateUse(currentToAppend); newWs.UpdateIdFromRfcTag(); lastAppended = currentToAppend; } duplicateNumber++; } return newWs; } protected void UpdateString(ref string field, string value) { if (field == value) return; //count null as same as "" if (String.IsNullOrEmpty(field) && String.IsNullOrEmpty(value)) { return; } Modified = true; field = value; } /// <summary> /// Used by IWritingSystemRepository to identify writing systems. Only change this if you would like to replace a writing system with the same StoreId /// already contained in the repo. This is useful creating a temporary copy of a writing system that you may or may not care to persist to the /// IWritingSystemRepository. /// Typical use would therefor be: /// ws.Clone(wsorig); /// ws.StoreId=wsOrig.StoreId; /// **make changes to ws** /// repo.Set(ws); /// </summary> virtual public string StoreID { get; set; } /// <summary> /// A automatically generated descriptive label for the writing system definition. /// </summary> virtual public string DisplayLabel { get { //jh (Oct 2010) made it start with RFC5646 because all ws's in a lang start with the //same abbreviation, making imppossible to see (in SOLID for example) which you chose. bool languageIsUnknown = Bcp47Tag.Equals(WellKnownSubTags.Unlisted.Language, StringComparison.OrdinalIgnoreCase); if (!String.IsNullOrEmpty(Bcp47Tag) && !languageIsUnknown) { return Bcp47Tag; } if (languageIsUnknown) { if (!String.IsNullOrEmpty(_abbreviation)) { return _abbreviation; } if (!String.IsNullOrEmpty(_languageName)) { string n = _languageName; return n.Substring(0, n.Length > 4 ? 4 : n.Length); } } return "???"; } } virtual public string ListLabel { get { //the idea here is to give writing systems a nice legible label for. For this reason subtags are replaced with nice labels var wsToConstructLabelFrom = this.Clone(); string n = string.Empty; n = !String.IsNullOrEmpty(wsToConstructLabelFrom.LanguageName) ? wsToConstructLabelFrom.LanguageName : wsToConstructLabelFrom.DisplayLabel; string details = ""; if (wsToConstructLabelFrom.IpaStatus != IpaStatusChoices.NotIpa) { switch (IpaStatus) { case IpaStatusChoices.Ipa: details += "IPA-"; break; case IpaStatusChoices.IpaPhonetic: details += "IPA-etic-"; break; case IpaStatusChoices.IpaPhonemic: details += "IPA-emic-"; break; default: throw new ArgumentOutOfRangeException(); } wsToConstructLabelFrom.IpaStatus = IpaStatusChoices.NotIpa; } if (wsToConstructLabelFrom.IsVoice) { details += "Voice-"; wsToConstructLabelFrom.IsVoice = false; } if (wsToConstructLabelFrom.IsDuplicate) { var duplicateNumbers = new List<string>(wsToConstructLabelFrom.DuplicateNumbers); foreach (var number in duplicateNumbers) { details += "Copy"; if (number != "0") { details += number; } details += "-"; wsToConstructLabelFrom._rfcTag.RemoveFromPrivateUse("dupl" + number); } } if (!String.IsNullOrEmpty(wsToConstructLabelFrom.Script)) { details += wsToConstructLabelFrom.Script+"-"; } if (!String.IsNullOrEmpty(wsToConstructLabelFrom.Region)) { details += wsToConstructLabelFrom.Region + "-"; } if (!String.IsNullOrEmpty(wsToConstructLabelFrom.Variant)) { details += wsToConstructLabelFrom.Variant + "-"; } details = details.Trim(new[] { '-' }); if (details.Length > 0) details = " ("+details + ")"; return n+details; } } protected bool IsDuplicate { get { return _rfcTag.GetPrivateUseSubtagsMatchingRegEx(@"^dupl\d$").Count() != 0; } } protected IEnumerable<string> DuplicateNumbers { get { return _rfcTag.GetPrivateUseSubtagsMatchingRegEx(@"^dupl\d$").Select(subtag => Regex.Match(subtag, @"\d*$").Value); } } /// <summary> /// The current BCP47 tag which is a concatenation of the Language, Script, Region and Variant properties. /// </summary> public string Bcp47Tag { get { return _rfcTag.CompleteTag; } } /// <summary> /// The identifier for this writing syetm definition. Use this in files and as a key to the IWritingSystemRepository. /// Note that this is usually identical to the Bcp47 tag and should rarely differ. /// </summary> public string Id { get { return _id; } internal set { value = value ?? ""; _id = value; Modified = true; } } /// <summary> /// Indicates whether the writing system definition has been modified. /// Note that this flag is automatically set by all methods that cause a modification and is reset by the IwritingSystemRepository.Save() method /// </summary> virtual public bool Modified { get; set; } virtual public bool MarkedForDeletion { get; set; } /// <summary> /// The font used to display data encoded in this writing system /// </summary> virtual public string DefaultFontName { get { return _defaultFontName; } set { UpdateString(ref _defaultFontName, value); } } /// <summary> /// the preferred font size to use for data encoded in this writing system. /// </summary> virtual public float DefaultFontSize { get { return _defaultFontSize; } set { if (value == _defaultFontSize) { return; } if (value < 0 || float.IsNaN(value) || float.IsInfinity(value)) { throw new ArgumentOutOfRangeException(); } _defaultFontSize = value; Modified = true; } } /// <summary> /// enforcing a minimum on _defaultFontSize, while reasonable, just messed up too many IO unit tests /// </summary> /// <returns></returns> virtual public float GetDefaultFontSizeOrMinimum() { if (_defaultFontSize < kMinimumFontSize) return kDefaultSizeIfWeDontKnow; return _defaultFontSize; } /// <summary> /// The preferred keyboard to use to generate data encoded in this writing system. /// </summary> virtual public string Keyboard { get { if(String.IsNullOrEmpty(_keyboard)) { return ""; } return _keyboard; } set { UpdateString(ref _keyboard, value); } } private IKeyboardDefinition _localKeyboard; public string WindowsLcid { get; set; } public IKeyboardDefinition LocalKeyboard { get { if (_localKeyboard == null) { var available = new HashSet<IKeyboardDefinition>(WritingSystems.Keyboard.Controller.AllAvailableKeyboards); _localKeyboard = (from k in KnownKeyboards where available.Contains(k) select k).FirstOrDefault(); } if (_localKeyboard == null) { _localKeyboard = WritingSystems.Keyboard.Controller.DefaultForWritingSystem(this); } return _localKeyboard; } set { _localKeyboard = value; AddKnownKeyboard(value); Modified = true; } } internal IKeyboardDefinition RawLocalKeyboard { get { return _localKeyboard; } } /// <summary> /// Indicates whether this writing system is read and written from left to right or right to left /// </summary> virtual public bool RightToLeftScript { get { return _rightToLeftScript; } set { if(value != _rightToLeftScript) { Modified = true; _rightToLeftScript = value; } } } /// <summary> /// The windows "NativeName" from the Culture class /// </summary> virtual public string NativeName { get { return _nativeName; } set { UpdateString(ref _nativeName, value); } } /// <summary> /// Indicates the type of sort rules used to encode the sort order. /// Note that the actual sort rules are contained in the SortRules property /// </summary> virtual public SortRulesType SortUsing { get { return _sortUsing; } set { if (value != _sortUsing) { _sortUsing = value; _collator = null; Modified = true; } } } /// <summary> /// The sort rules that efine the sort order. /// Note that you must indicate the type of sort rules used by setting the "SortUsing" property /// </summary> virtual public string SortRules { get { return _sortRules ?? string.Empty; } set { _collator = null; UpdateString(ref _sortRules, value); } } /// <summary> /// A convenience method for sorting like anthoer language /// </summary> /// <param name="languageCode">A valid language code</param> public void SortUsingOtherLanguage(string languageCode) { SortUsing = SortRulesType.OtherLanguage; SortRules = languageCode; } /// <summary> /// A convenience method for sorting with custom ICU rules /// </summary> /// <param name="sortRules">custom ICU sortrules</param> public void SortUsingCustomICU(string sortRules) { SortUsing = SortRulesType.CustomICU; SortRules = sortRules; } /// <summary> /// A convenience method for sorting with "shoebox" style rules /// </summary> /// <param name="sortRules">"shoebox" style rules</param> public void SortUsingCustomSimple(string sortRules) { SortUsing = SortRulesType.CustomSimple; SortRules = sortRules; } /// <summary> /// The id used to select the spell checker. /// </summary> virtual public string SpellCheckingId { get { return _spellCheckingId; } set { UpdateString(ref _spellCheckingId, value); } } /// <summary> /// Returns an ICollator interface that can be used to sort strings based /// on the custom collation rules. /// </summary> virtual public ICollator Collator { get { if (_collator == null) { switch (SortUsing) { case SortRulesType.DefaultOrdering: _collator = new IcuRulesCollator(String.Empty); // was SystemCollator(null); break; case SortRulesType.CustomSimple: _collator = new SimpleRulesCollator(SortRules); break; case SortRulesType.CustomICU: _collator = new IcuRulesCollator(SortRules); break; case SortRulesType.OtherLanguage: _collator = new SystemCollator(SortRules); break; } } return _collator; } } /// <summary> /// Tests whether the current custom collation rules are valid. /// </summary> /// <param name="message">Used for an error message if rules do not validate.</param> /// <returns>True if rules are valid, false otherwise.</returns> virtual public bool ValidateCollationRules(out string message) { message = null; switch (SortUsing) { case SortRulesType.DefaultOrdering: return String.IsNullOrEmpty(SortRules); case SortRulesType.CustomICU: return IcuRulesCollator.ValidateSortRules(SortRules, out message); case SortRulesType.CustomSimple: return SimpleRulesCollator.ValidateSimpleRules(SortRules, out message); case SortRulesType.OtherLanguage: try { new SystemCollator(SortRules); } catch (Exception e) { message = String.Format("Error while validating sorting rules: {0}", e.Message); return false; } return true; } return false; } public override string ToString() { return _rfcTag.ToString(); } /// <summary> /// Creates a clone of the current writing system. /// Note that this excludes the properties: Modified, MarkedForDeletion and StoreID /// </summary> /// <returns></returns> virtual public WritingSystemDefinition Clone() { return new WritingSystemDefinition(this); } public override bool Equals(Object obj) { if (!(obj is WritingSystemDefinition)) return false; return Equals((WritingSystemDefinition)obj); } public bool Equals(WritingSystemDefinition other) { if (other == null) return false; if (!_rfcTag.Equals(other._rfcTag)) return false; if ((_languageName != null && !_languageName.Equals(other._languageName)) || (other._languageName != null && !other._languageName.Equals(_languageName))) return false; if ((_abbreviation != null && !_abbreviation.Equals(other._abbreviation)) || (other._abbreviation != null && !other._abbreviation.Equals(_abbreviation))) return false; if ((_versionNumber != null && !_versionNumber.Equals(other._versionNumber)) || (other._versionNumber != null && !other._versionNumber.Equals(_versionNumber))) return false; if ((_versionDescription != null && !_versionDescription.Equals(other._versionDescription)) || (other._versionDescription != null && !other._versionDescription.Equals(_versionDescription))) return false; if ((_defaultFontName != null && !_defaultFontName.Equals(other._defaultFontName)) || (other._defaultFontName != null && !other._defaultFontName.Equals(_defaultFontName))) return false; if ((_keyboard != null && !_keyboard.Equals(other._keyboard)) || (other._keyboard != null && !other._keyboard.Equals(_keyboard))) return false; if ((_sortRules != null && !_sortRules.Equals(other._sortRules)) || (other._sortRules != null && !other._sortRules.Equals(_sortRules))) return false; if ((_spellCheckingId != null && !_spellCheckingId.Equals(other._spellCheckingId)) || (other._spellCheckingId != null && !other._spellCheckingId.Equals(_spellCheckingId))) return false; if ((_nativeName != null && !_nativeName.Equals(other._nativeName)) || (other._nativeName != null && !other._nativeName.Equals(_nativeName))) return false; if ((_id != null && !_id.Equals(other._id)) || (other._id != null && !other._id.Equals(_id))) return false; if (!_isUnicodeEncoded.Equals(other._isUnicodeEncoded)) return false; if (!_dateModified.Equals(other._dateModified)) return false; if (!_defaultFontSize.Equals(other._defaultFontSize)) return false; if (!SortUsing.Equals(other.SortUsing)) return false; if (!_rightToLeftScript.Equals(other._rightToLeftScript)) return false; if ((_localKeyboard != null && !_localKeyboard.Equals(other._localKeyboard)) || (_localKeyboard == null && other._localKeyboard != null)) return false; if (WindowsLcid != other.WindowsLcid) return false; if (_knownKeyboards.Count != other._knownKeyboards.Count) return false; for (int i = 0; i < _knownKeyboards.Count; i++) { if (!_knownKeyboards[i].Equals(other._knownKeyboards[i])) return false; } return true; } private void UpdateIdFromRfcTag() { _id = Bcp47Tag; } /// <summary> /// Indicates whether this writing system is unicode encoded or legacy encoded /// </summary> public bool IsUnicodeEncoded { get { return _isUnicodeEncoded; } set { if (value != _isUnicodeEncoded) { Modified = true; _isUnicodeEncoded = value; } } } /// <summary> /// Parses the supplied BCP47 tag and sets the Language, Script, Region and Variant properties accordingly /// </summary> /// <param name="completeTag">A valid BCP47 tag</param> public void SetTagFromString(string completeTag) { _rfcTag = RFC5646Tag.Parse(completeTag); UpdateIdFromRfcTag(); Modified = true; } /// <summary> /// Parses the supplied BCP47 tag and return a new writing system definition with the correspnding Language, Script, Region and Variant properties /// </summary> /// <param name="bcp47Tag">A valid BCP47 tag</param> public static WritingSystemDefinition Parse(string bcp47Tag) { var writingSystemDefinition = new WritingSystemDefinition(); writingSystemDefinition.SetTagFromString(bcp47Tag); return writingSystemDefinition; } /// <summary> /// Returns a new writing system definition with the corresponding Language, Script, Region and Variant properties set /// </summary> public static WritingSystemDefinition FromSubtags(string language, string script, string region, string variantAndPrivateUse) { return new WritingSystemDefinition(language, script, region, variantAndPrivateUse, string.Empty, false); } /// <summary> /// Filters out all "WellKnownSubTags" out of a list of subtags /// </summary> /// <param name="privateUseTokens"></param> /// <returns></returns> public static IEnumerable<string> FilterWellKnownPrivateUseTags(IEnumerable<string> privateUseTokens) { foreach (var privateUseToken in privateUseTokens) { string strippedToken = RFC5646Tag.StripLeadingPrivateUseMarker(privateUseToken); if (strippedToken.Equals(RFC5646Tag.StripLeadingPrivateUseMarker(WellKnownSubTags.Audio.PrivateUseSubtag), StringComparison.OrdinalIgnoreCase) || strippedToken.Equals(RFC5646Tag.StripLeadingPrivateUseMarker(WellKnownSubTags.Ipa.PhonemicPrivateUseSubtag), StringComparison.OrdinalIgnoreCase) || strippedToken.Equals(RFC5646Tag.StripLeadingPrivateUseMarker(WellKnownSubTags.Ipa.PhoneticPrivateUseSubtag), StringComparison.OrdinalIgnoreCase)) continue; yield return privateUseToken; } } List<IKeyboardDefinition> _knownKeyboards = new List<IKeyboardDefinition>(); public IEnumerable<IKeyboardDefinition> KnownKeyboards { get { return _knownKeyboards; } } public void AddKnownKeyboard(IKeyboardDefinition newKeyboard) { if (newKeyboard == null) return; // Review JohnT: how should this affect order? // e.g.: last added should be first? // Current algorithm keeps them in the order added, hopefully meaning the most likely one, added first, // remains the default. if (KnownKeyboards.Contains(newKeyboard)) return; _knownKeyboards.Add(newKeyboard); Modified = true; } /// <summary> /// Returns the available keyboards (known to Keyboard.Controller) that are not KnownKeyboards for this writing system. /// </summary> public IEnumerable<IKeyboardDefinition> OtherAvailableKeyboards { get { return WritingSystems.Keyboard.Controller.AllAvailableKeyboards.Except(KnownKeyboards); } } } public enum IpaStatusChoices { NotIpa, Ipa, IpaPhonetic, IpaPhonemic } public class WellKnownSubTags { public class Unlisted { public const string Language = "qaa"; } public class Unwritten { public const string Script = "Zxxx"; } //The "x-" is required before each of the strings below, since WritingSystemDefinition needs "x-" to distinguish BCP47 private use from variant //Without the "x-" a consumer who wanted to set a writing ystem as audio would have to write: ws.Variant = "x-" + WellKnownSubtags.Audio.PrivateUseSubtag public class Audio { public const string PrivateUseSubtag = "x-audio"; public const string Script= Unwritten.Script; } public class Ipa { public const string VariantSubtag = "fonipa"; public const string PhonemicPrivateUseSubtag = "x-emic"; public const string PhoneticPrivateUseSubtag = "x-etic"; } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using BI.Interface.Areas.HelpPage.ModelDescriptions; using BI.Interface.Areas.HelpPage.Models; namespace BI.Interface.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } // Example: // [TypeConverter(typeof(PointConverter))] // public class Point // { // public Point(int x, int y) // { // X = x; // Y = y; // } // public int X { get; set; } // public int Y { get; set; } // } // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. // // public class Point // { // public int X { get; set; } // public int Y { get; set; } // } // Regular complex class Point will have properties X and Y added to UriParameters collection. if (complexTypeDescription != null && !IsBindableWithTypeConverter(parameterType)) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
using UnityEngine; using UnityEditor; using System.Collections; using System.Collections.Generic; using System.Net; using System.IO; using System; using System.Reflection; using System.Xml.Serialization; using System.Linq; namespace Igor { public class IgorBuildDesktop : IgorModuleBase { public override string GetModuleName() { return "Build.Desktop"; } public override void RegisterModule() { bool DidRegister = IgorCore.RegisterNewModule(this); IgorBuildCommon.RegisterBuildPlatforms(new string[] {"OSX32", "OSX64", "OSXUniversal", "Windows32", "Windows64", "Linux32", "Linux64", "LinuxUniversal"}); } public static BuildTarget GetBuildTargetForCurrentJob(out bool bWindows, out bool bOSX, out bool bLinux, string AllParams = "") { string PlatformString = IgorJobConfig.GetStringParam(IgorBuildCommon.PlatformFlag); if(PlatformString == "") { PlatformString = IgorRuntimeUtils.GetStringParam(AllParams, IgorBuildCommon.PlatformFlag); } bWindows = false; bOSX = false; bLinux = false; BuildTarget CurrentJobBuildTarget = BuildTarget.StandaloneOSXIntel; if(PlatformString.Contains("OSX32")) { CurrentJobBuildTarget = BuildTarget.StandaloneOSXIntel; bOSX = true; } else if(PlatformString.Contains("OSX64")) { CurrentJobBuildTarget = BuildTarget.StandaloneOSXIntel64; bOSX = true; } else if(PlatformString.Contains("OSXUniversal")) { CurrentJobBuildTarget = BuildTarget.StandaloneOSXUniversal; bOSX = true; } else if(PlatformString.Contains("Windows32")) { CurrentJobBuildTarget = BuildTarget.StandaloneWindows; bWindows = true; } else if(PlatformString.Contains("Windows64")) { CurrentJobBuildTarget = BuildTarget.StandaloneWindows64; bWindows = true; } else if(PlatformString.Contains("Linux32")) { CurrentJobBuildTarget = BuildTarget.StandaloneLinux; bLinux = true; } else if(PlatformString.Contains("Linux64")) { CurrentJobBuildTarget = BuildTarget.StandaloneLinux64; bLinux = true; } else if(PlatformString.Contains("LinuxUniversal")) { CurrentJobBuildTarget = BuildTarget.StandaloneLinuxUniversal; bLinux = true; } return CurrentJobBuildTarget; } public override void ProcessArgs(IIgorStepHandler StepHandler) { if(IgorJobConfig.IsBoolParamSet(IgorBuildCommon.BuildFlag)) { IgorCore.SetModuleActiveForJob(this); bool bWindows = false; bool bOSX = false; bool bLinux = false; JobBuildTarget = GetBuildTargetForCurrentJob(out bWindows, out bOSX, out bLinux); if(bOSX) { StepHandler.RegisterJobStep(IgorBuildCommon.SwitchPlatformStep, this, SwitchPlatforms); StepHandler.RegisterJobStep(IgorBuildCommon.BuildStep, this, BuildOSX); } else if(bWindows) { StepHandler.RegisterJobStep(IgorBuildCommon.SwitchPlatformStep, this, SwitchPlatforms); StepHandler.RegisterJobStep(IgorBuildCommon.BuildStep, this, BuildWindows); } else if(bLinux) { StepHandler.RegisterJobStep(IgorBuildCommon.SwitchPlatformStep, this, SwitchPlatforms); StepHandler.RegisterJobStep(IgorBuildCommon.BuildStep, this, BuildLinux); } } } public virtual string GetBuiltNameConfigKeyForPlatform(string PlatformName) { return "Built" + PlatformName + "Name"; } public override bool ShouldDrawInspectorForParams(string CurrentParams) { bool bBuilding = IgorRuntimeUtils.IsBoolParamSet(CurrentParams, IgorBuildCommon.BuildFlag); bool bRecognizedPlatform = false; if(bBuilding) { string Platform = IgorRuntimeUtils.GetStringParam(CurrentParams, IgorBuildCommon.PlatformFlag); if(Platform == "OSX32") { bRecognizedPlatform = true; } else if(Platform == "OSX64") { bRecognizedPlatform = true; } else if(Platform == "OSXUniversal") { bRecognizedPlatform = true; } else if(Platform == "Windows32") { bRecognizedPlatform = true; } else if(Platform == "Windows64") { bRecognizedPlatform = true; } else if(Platform == "Linux32") { bRecognizedPlatform = true; } else if(Platform == "Linux64") { bRecognizedPlatform = true; } else if(Platform == "LinuxUniversal") { bRecognizedPlatform = true; } } return bBuilding && bRecognizedPlatform; } public override string DrawJobInspectorAndGetEnabledParams(string CurrentParams) { string EnabledParams = CurrentParams; string Platform = IgorRuntimeUtils.GetStringParam(CurrentParams, IgorBuildCommon.PlatformFlag); DrawStringConfigParamDifferentOverride(ref EnabledParams, "Built name", IgorBuildCommon.BuiltNameFlag, GetBuiltNameConfigKeyForPlatform(Platform)); return EnabledParams; } public BuildTarget JobBuildTarget = BuildTarget.StandaloneOSXIntel; public List<IgorBuildCommon.GetExtraBuildOptions> BuildOptionsDelegates = new List<IgorBuildCommon.GetExtraBuildOptions>(); public virtual void AddDelegateCallback(IgorBuildCommon.GetExtraBuildOptions NewDelegate) { if(!BuildOptionsDelegates.Contains(NewDelegate)) { BuildOptionsDelegates.Add(NewDelegate); } } public virtual string GetBuiltNameForTarget(BuildTarget NewTarget) { string BuiltName = ""; bool bOSX = false; bool bWindows = false; bool bLinux = false; if(NewTarget == BuildTarget.StandaloneOSXIntel) { BuiltName = GetConfigString("BuiltOSX32Name"); bOSX = true; } else if(NewTarget == BuildTarget.StandaloneOSXIntel64) { BuiltName = GetConfigString("BuiltOSX64Name"); bOSX = true; } else if(NewTarget == BuildTarget.StandaloneOSXUniversal) { BuiltName = GetConfigString("BuiltOSXUniversalName"); bOSX = true; } if(NewTarget == BuildTarget.StandaloneWindows) { BuiltName = GetConfigString("BuiltWindows32Name"); bWindows = true; } else if(NewTarget == BuildTarget.StandaloneWindows64) { BuiltName = GetConfigString("BuiltWindows64Name"); bWindows = true; } if(NewTarget == BuildTarget.StandaloneLinux) { BuiltName = GetConfigString("BuiltLinux32Name"); bLinux = true; } else if(NewTarget == BuildTarget.StandaloneLinux64) { BuiltName = GetConfigString("BuiltLinux64Name"); bLinux = true; } else if(NewTarget == BuildTarget.StandaloneLinuxUniversal) { BuiltName = GetConfigString("BuiltLinuxUniversalName"); bLinux = true; } if(BuiltName == "") { if(bOSX) { BuiltName = GetConfigString("BuiltOSXName"); } else if(bWindows) { BuiltName = GetConfigString("BuiltWindowsName"); } else if(bLinux) { BuiltName = GetConfigString("BuiltLinuxName"); } } if(BuiltName == "") { BuiltName = IgorJobConfig.GetStringParam(IgorBuildCommon.BuiltNameFlag); } if(BuiltName == "") { BuiltName = Path.GetFileName(EditorUserBuildSettings.GetBuildLocation(NewTarget)); } if(BuiltName == "") { if(bOSX) { BuiltName = "Unity.app"; } else if(bWindows) { BuiltName = "Unity.exe"; } else if(bLinux) { BuiltName = "Unity"; } } if(!bLinux && !BuiltName.Contains(".exe") && !BuiltName.Contains(".app")) { if(bOSX) { BuiltName += ".app"; } if(bWindows) { BuiltName += ".exe"; } } if(!string.IsNullOrEmpty(BuiltName) && IgorJobConfig.IsBoolParamSet(IgorBuildCommon.AppendCommitInfoFlag)) { string CommitInfo = IgorBuildCommon.GetCommitInfo(); if(!string.IsNullOrEmpty(CommitInfo)) { BuiltName = BuiltName.Insert(BuiltName.IndexOf("."), "_" + CommitInfo); } } return BuiltName; } public virtual bool IsPlatformWindows(BuildTarget CurrentTarget) { if(CurrentTarget == BuildTarget.StandaloneWindows || CurrentTarget == BuildTarget.StandaloneWindows64) { return true; } return false; } public virtual BuildOptions GetExternalBuildOptions(BuildTarget CurrentTarget) { BuildOptions ExtraOptions = BuildOptions.None; foreach(IgorBuildCommon.GetExtraBuildOptions CurrentDelegate in BuildOptionsDelegates) { ExtraOptions |= CurrentDelegate(CurrentTarget); } return ExtraOptions; } public virtual bool SwitchPlatforms() { Log("Switching platforms to " + JobBuildTarget); EditorUserBuildSettings.SwitchActiveBuildTarget(JobBuildTarget); return true; } public virtual bool BuildOSX() { Log("Building OSX build (Target:" + JobBuildTarget + ")"); return Build(); } public virtual bool BuildWindows() { Log("Building Windows build (Target:" + JobBuildTarget + ")"); return Build(); } public virtual bool BuildLinux() { Log("Building Linux build (Target:" + JobBuildTarget + ")"); return Build(); } public virtual bool Build() { string BuiltName = GetBuiltNameForTarget(JobBuildTarget); string BuiltBaseName = BuiltName; if(BuiltBaseName.Contains(".")) { BuiltBaseName = BuiltName.Substring(0, BuiltBaseName.LastIndexOf('.')); } string DataFolderName = BuiltBaseName + "_Data"; if(File.Exists(BuiltName)) { IgorRuntimeUtils.DeleteFile(BuiltName); } if(Directory.Exists(DataFolderName)) { IgorRuntimeUtils.DeleteDirectory(DataFolderName); } #if !UNITY_4_3 BuiltName = System.IO.Path.Combine(System.IO.Path.GetFullPath("."), BuiltName); #endif BuildPipeline.BuildPlayer(IgorUtils.GetLevels(), BuiltName, JobBuildTarget, IgorBuildCommon.GetBuildOptions()); Log("Destination file is: " + BuiltName); List<string> BuiltFiles = new List<string>(); if(Directory.Exists(DataFolderName)) { if(IgorAssert.EnsureTrue(this, File.Exists(BuiltName), "The built file " + BuiltName + " doesn't exist. Something went wrong during the build step. Please check the logs!")) { BuiltFiles.Add(BuiltName); } if(IgorAssert.EnsureTrue(this, Directory.Exists(DataFolderName), "The built data directory for the Windows build " + DataFolderName + " doesn't exist. Something went wrong during the build step. Please check the logs!")) { BuiltFiles.Add(DataFolderName); } } else { if(IgorAssert.EnsureTrue(this, Directory.Exists(BuiltName), "The built app directory for the Mac build " + BuiltName + " doesn't exist. Something went wrong during the build step. Please check the logs!")) { BuiltFiles.Add(BuiltName); } } IgorCore.SetNewModuleProducts(BuiltFiles); return true; } } }
/* * f1livetiming - Part of the Live Timing Library for .NET * Copyright (C) 2009 Liam Lowey * * http://livetiming.turnitin.co.uk/ * * 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.IO; using System.Net; using System.Net.Sockets; using System.Threading; using Common.Patterns.Command; using Common.Utils.Threading; using F1.Runtime; using F1.Exceptions; using log4net; namespace F1.Network { /// <summary> /// This driver is used to connect to the live server and pull the data. It's implementation relies /// on the proactor async pattern implemented by .NET sockets to send/receive data. However calls /// into the socket are all serialised to prevent race conditions through the command queue based /// thread. /// </summary> class AsyncConnectionDriver : SimpleThreadedQueueBase, IDriver, IDisposable { #region Configuration Constants const string HOST = "live-timing.formula1.com"; const int PORT = 4321; const int BLOB_SIZE = 256; const int SEND_INTERVAL = 1000; #endregion private readonly ILog _log = LogManager.GetLogger("AsyncConnectionDriver"); #region Internal data private readonly Socket _incoming; private readonly Runtime.Runtime _runtime; private readonly MemoryStream _memStream; private int _refreshRate = SEND_INTERVAL; private readonly Timer _timer; #endregion public AsyncConnectionDriver(Runtime.Runtime runtime, MemoryStream memStream) : base(false) { try { _memStream = memStream; _runtime = runtime; _runtime.Driver = this; IPHostEntry e = Dns.GetHostEntry(HOST); _incoming = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); _log.InfoFormat("Resolved {0} to {1}.", HOST, e.AddressList[0].ToString()); _log.Info("Connecting..."); #if COMPACT EndPoint ep = new IPEndPoint(e.AddressList[0], PORT); _incoming.Connect(ep); _incoming.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 10000); #else _incoming.Connect(e.AddressList, PORT); _incoming.ReceiveTimeout = 10000; // 10 seconds because we may not always be receiving data #endif // Queue the first read and write CmdQueue.Push(CommandFactory.MakeCommand(DoNextRead, new byte[BLOB_SIZE])); CmdQueue.Push(CommandFactory.MakeCommand(DoPing)); Start(); // We've sent the first request so schedule timer to start one interval later _timer = new Timer(TimerPingCallback, null, _refreshRate, _refreshRate); _log.Info("Connected."); } catch (SocketException e) { throw new ConnectionException(e); } } #region Internal writer thread private void TimerPingCallback(object state) { // It's time to do another ping CmdQueue.Push(CommandFactory.MakeCommand(DoPing)); } private void DoPing() { byte[] reqPacket = { 0x10 }; _incoming.BeginSend(reqPacket, 0, 1, SocketFlags.None, OnWriteData, null); } private void OnWriteData(IAsyncResult res) { // This method exists purely to perform the remainder of the proactor // pattern implemented for .NET socket Async behaviour when writing. _incoming.EndSend(res); // Block on this call until data received. } #endregion #region Internal reader thread private void DoNextRead(byte[] blob) { _incoming.BeginReceive(blob, 0, blob.Length, SocketFlags.None, OnReceiveData, blob); } private void DoProcessData(byte[] blob, int dataLength) { long oldPosition = _memStream.Position; if (oldPosition == _memStream.Length) { // We're at the edge of the stream, so to prevent a backlog // of data building up, start overwriting from the beginning. _memStream.Seek(0, SeekOrigin.Begin); _memStream.SetLength(0); oldPosition = 0; } else { // There is some data still left to be read, so to avoid overwriting // it we must append this block to the end of the stream. _memStream.Seek(0, SeekOrigin.End); } // Push new data onto the end of our stream. _memStream.Write(blob, 0, dataLength); // Restore the read head position after the write so that the reads // start from the correct position. _memStream.Seek(oldPosition, SeekOrigin.Begin); // Process new data try { while (_runtime.HandleRead()) { } } catch(Exception e) { _log.Warn("HandleRead() - " + e.Message); // Error while processing the data, so we abort and discard the remainder // of read/write requests pending. Stop(JoinMethod.DontJoin, true); // Don't join this thread to this thread. } } private void OnReceiveData(IAsyncResult res) { int data = _incoming.EndReceive(res); byte[] blob = res.AsyncState as byte[]; if (data > 0) { // We received data so push it back onto the queue for processing CmdQueue.Push(CommandFactory.MakeCommand(DoProcessData, blob, data)); } // Queue up next read with new blob (assume that processing of data happens // prior to queueing the next read so we can recycle the blob). CmdQueue.Push(CommandFactory.MakeCommand(DoNextRead, blob)); } #endregion #region Implementation of IDriver private void DoSetRefresh(int refreshRate) { _refreshRate = refreshRate * 1000; // it's fine to change the due time because we generally only // up the refresh rate. _timer.Change(_refreshRate, _refreshRate); } public void SetRefresh(int refreshRate) { CmdQueue.PushUrgent(CommandFactory.MakeCommand(DoSetRefresh, refreshRate)); } public void Terminate() { _log.Warn("Terminate() - Exiting AsyncConnection."); // don't join because we maybe calling back from our own thread. // discard messages so we don't queue new socket requests after calling Dispose. Stop(JoinMethod.DontJoin, true); } public void UpdateCurrentKeyFrame(int currentFrame) { } #endregion #region IDisposable Members public void Dispose() { Stop(JoinMethod.Join, true); } #endregion } }
// Radial Menu|Prefabs|0040 namespace VRTK { using UnityEngine; using System.Collections; using UnityEngine.Events; using System.Collections.Generic; using UnityEngine.UI; using UnityEngine.EventSystems; public delegate void HapticPulseEventHandler(ushort strength); /// <summary> /// This adds a UI element into the world space that can be dropped into a Controller object and used to create and use Radial Menus from the touchpad. /// </summary> /// <remarks> /// If the RadialMenu is placed inside a controller, it will automatically find a `VRTK_ControllerEvents` in its parent to use at the input. However, a `VRTK_ControllerEvents` can be defined explicitly by setting the `Events` parameter of the `Radial Menu Controller` script also attached to the prefab. /// /// The RadialMenu can also be placed inside a `VRTK_InteractableObject` for the RadialMenu to be anchored to a world object instead of the controller. The `Events Manager` parameter will automatically be set if the RadialMenu is a child of an InteractableObject, but it can also be set manually in the inspector. Additionally, for the RadialMenu to be anchored in the world, the `RadialMenuController` script in the prefab must be replaced with `VRTK_IndependentRadialMenuController`. See the script information for further details on making the RadialMenu independent of the controllers. /// </remarks> /// <example> /// `VRTK/Examples/030_Controls_RadialTouchpadMenu` displays a radial menu for each controller. The left controller uses the `Hide On Release` variable, so it will only be visible if the left touchpad is being touched. It also uses the `Execute On Unclick` variable to delay execution until the touchpad button is unclicked. The example scene also contains a demonstration of anchoring the RadialMenu to an interactable cube instead of a controller. /// </example> [ExecuteInEditMode] public class RadialMenu : MonoBehaviour { #region Variables [Tooltip("An array of Buttons that define the interactive buttons required to be displayed as part of the radial menu.")] public List<RadialMenuButton> buttons; [Tooltip("The base for each button in the menu, by default set to a dynamic circle arc that will fill up a portion of the menu.")] public GameObject buttonPrefab; [Tooltip("Percentage of the menu the buttons should fill, 1.0 is a pie slice, 0.1 is a thin ring.")] [Range(0f, 1f)] public float buttonThickness = 0.5f; [Tooltip("The background colour of the buttons, default is white.")] public Color buttonColor = Color.white; [Tooltip("The distance the buttons should move away from the centre. This creates space between the individual buttons.")] public float offsetDistance = 1; [Tooltip("The additional rotation of the Radial Menu.")] [Range(0, 359)] public float offsetRotation; [Tooltip("Whether button icons should rotate according to their arc or be vertical compared to the controller.")] public bool rotateIcons; [Tooltip("The margin in pixels that the icon should keep within the button.")] public float iconMargin; [Tooltip("Whether the buttons are shown")] public bool isShown; [Tooltip("Whether the buttons should be visible when not in use.")] public bool hideOnRelease; [Tooltip("Whether the button action should happen when the button is released, as opposed to happening immediately when the button is pressed.")] public bool executeOnUnclick; [Tooltip("The base strength of the haptic pulses when the selected button is changed, or a button is pressed. Set to zero to disable.")] [Range(0, 1599)] public ushort baseHapticStrength; public event HapticPulseEventHandler FireHapticPulse; //Has to be public to keep state from editor -> play mode? [Tooltip("The actual GameObjects that make up the radial menu.")] public List<GameObject> menuButtons; private int currentHover = -1; private int currentPress = -1; #endregion #region Unity Methods private void Awake() { if (Application.isPlaying) { if (!isShown) { transform.localScale = Vector3.zero; } RegenerateButtons(); } } private void Update() { //Keep track of pressed button and constantly invoke Hold event if (currentPress != -1) { buttons[currentPress].OnHold.Invoke(); } } #endregion #region Interaction //Turns and Angle and Event type into a button action private void InteractButton(float angle, ButtonEvent evt) //Can't pass ExecuteEvents as parameter? Unity gives error { //Get button ID from angle float buttonAngle = 360f / buttons.Count; //Each button is an arc with this angle angle = mod((angle + offsetRotation), 360); //Offset the touch coordinate with our offset int buttonID = (int)mod(((angle + (buttonAngle / 2f)) / buttonAngle), buttons.Count); //Convert angle into ButtonID (This is the magic) var pointer = new PointerEventData(EventSystem.current); //Create a new EventSystem (UI) Event //If we changed buttons while moving, un-hover and un-click the last button we were on if (currentHover != buttonID && currentHover != -1) { ExecuteEvents.Execute(menuButtons[currentHover], pointer, ExecuteEvents.pointerUpHandler); ExecuteEvents.Execute(menuButtons[currentHover], pointer, ExecuteEvents.pointerExitHandler); buttons[currentHover].OnHoverExit.Invoke(); if (executeOnUnclick && currentPress != -1) { ExecuteEvents.Execute(menuButtons[buttonID], pointer, ExecuteEvents.pointerDownHandler); AttempHapticPulse((ushort)(baseHapticStrength * 1.666f)); } } if (evt == ButtonEvent.click) //Click button if click, and keep track of current press (executes button action) { ExecuteEvents.Execute(menuButtons[buttonID], pointer, ExecuteEvents.pointerDownHandler); currentPress = buttonID; if (!executeOnUnclick) { buttons[buttonID].OnClick.Invoke(); AttempHapticPulse((ushort)(baseHapticStrength * 2.5f)); } } else if (evt == ButtonEvent.unclick) //Clear press id to stop invoking OnHold method (hide menu) { ExecuteEvents.Execute(menuButtons[buttonID], pointer, ExecuteEvents.pointerUpHandler); currentPress = -1; if (executeOnUnclick) { AttempHapticPulse((ushort)(baseHapticStrength * 2.5f)); buttons[buttonID].OnClick.Invoke(); } } else if (evt == ButtonEvent.hoverOn && currentHover != buttonID) // Show hover UI event (darken button etc). Show menu { ExecuteEvents.Execute(menuButtons[buttonID], pointer, ExecuteEvents.pointerEnterHandler); buttons[buttonID].OnHoverEnter.Invoke(); AttempHapticPulse(baseHapticStrength); } currentHover = buttonID; //Set current hover ID, need this to un-hover if selected button changes } /* * Public methods to call Interact */ public void HoverButton(float angle) { InteractButton(angle, ButtonEvent.hoverOn); } public void ClickButton(float angle) { InteractButton(angle, ButtonEvent.click); } public void UnClickButton(float angle) { InteractButton(angle, ButtonEvent.unclick); } public void ToggleMenu() { if (isShown) { HideMenu(true); } else { ShowMenu(); } } public void StopTouching() { if (currentHover != -1) { var pointer = new PointerEventData(EventSystem.current); ExecuteEvents.Execute(menuButtons[currentHover], pointer, ExecuteEvents.pointerExitHandler); buttons[currentHover].OnHoverExit.Invoke(); currentHover = -1; } } /* * Public methods to Show/Hide menu */ public void ShowMenu() { if (!isShown) { isShown = true; StopCoroutine("TweenMenuScale"); StartCoroutine("TweenMenuScale", isShown); } } public RadialMenuButton GetButton(int id) { if (id < buttons.Count) { return buttons[id]; } return null; } public void HideMenu(bool force) { if (isShown && (hideOnRelease || force)) { isShown = false; StopCoroutine("TweenMenuScale"); StartCoroutine("TweenMenuScale", isShown); } } //Simple tweening for menu, scales linearly from 0 to 1 and 1 to 0 private IEnumerator TweenMenuScale(bool show) { float targetScale = 0; Vector3 Dir = -1 * Vector3.one; if (show) { targetScale = 1; Dir = Vector3.one; } int i = 0; //Sanity check for infinite loops while (i < 250 && ((show && transform.localScale.x < targetScale) || (!show && transform.localScale.x > targetScale))) { transform.localScale += Dir * Time.deltaTime * 4f; //Tweening function - currently 0.25 second linear yield return true; i++; } transform.localScale = Dir * targetScale; StopCoroutine("TweenMenuScale"); } private void AttempHapticPulse(ushort strength) { if (strength > 0 && FireHapticPulse != null) { FireHapticPulse(strength); } } #endregion #region Generation //Creates all the button Arcs and populates them with desired icons public void RegenerateButtons() { RemoveAllButtons(); for (int i = 0; i < buttons.Count; i++) { // Initial placement/instantiation GameObject newButton = Instantiate(buttonPrefab); newButton.transform.SetParent(transform); newButton.transform.localScale = Vector3.one; newButton.GetComponent<RectTransform>().offsetMax = Vector2.zero; newButton.GetComponent<RectTransform>().offsetMin = Vector2.zero; //Setup button arc UICircle circle = newButton.GetComponent<UICircle>(); if (buttonThickness == 1) { circle.fill = true; } else { circle.thickness = (int)(buttonThickness * (GetComponent<RectTransform>().rect.width / 2f)); } int fillPerc = (int)(100f / buttons.Count); circle.fillPercent = fillPerc; circle.color = buttonColor; //Final placement/rotation float angle = ((360 / buttons.Count) * i) + offsetRotation; newButton.transform.localEulerAngles = new Vector3(0, 0, angle); newButton.layer = 4; //UI Layer newButton.transform.localPosition = Vector3.zero; if (circle.fillPercent < 55) { float angleRad = (angle * Mathf.PI) / 180f; Vector2 angleVector = new Vector2(-Mathf.Cos(angleRad), -Mathf.Sin(angleRad)); newButton.transform.localPosition += (Vector3)angleVector * offsetDistance; } //Place and populate Button Icon GameObject buttonIcon = newButton.GetComponentInChildren<RadialButtonIcon>().gameObject; if (buttons[i].ButtonIcon == null) { buttonIcon.SetActive(false); } else { buttonIcon.GetComponent<Image>().sprite = buttons[i].ButtonIcon; buttonIcon.transform.localPosition = new Vector2(-1 * ((newButton.GetComponent<RectTransform>().rect.width / 2f) - (circle.thickness / 2f)), 0); //Min icon size from thickness and arc float scale1 = Mathf.Abs(circle.thickness); float R = Mathf.Abs(buttonIcon.transform.localPosition.x); float bAngle = (359f * circle.fillPercent * 0.01f * Mathf.PI) / 180f; float scale2 = (R * 2 * Mathf.Sin(bAngle / 2f)); if (circle.fillPercent > 24) //Scale calc doesn't work for > 90 degrees { scale2 = float.MaxValue; } float iconScale = Mathf.Min(scale1, scale2) - iconMargin; buttonIcon.GetComponent<RectTransform>().sizeDelta = new Vector2(iconScale, iconScale); //Rotate icons all vertically if desired if (!rotateIcons) { buttonIcon.transform.eulerAngles = GetComponentInParent<Canvas>().transform.eulerAngles; } } menuButtons.Add(newButton); } } public void AddButton(RadialMenuButton newButton) { buttons.Add(newButton); RegenerateButtons(); } private void RemoveAllButtons() { if (menuButtons == null) { menuButtons = new List<GameObject>(); } for (int i = 0; i < menuButtons.Count; i++) { DestroyImmediate(menuButtons[i]); } menuButtons = new List<GameObject>(); } #endregion #region Utility private float mod(float a, float b) { return a - b * Mathf.Floor(a / b); } #endregion } [System.Serializable] public class RadialMenuButton { public Sprite ButtonIcon; public UnityEvent OnClick; public UnityEvent OnHold; public UnityEvent OnHoverEnter; public UnityEvent OnHoverExit; } public enum ButtonEvent { hoverOn, hoverOff, click, unclick } }
using BefunGen.AST.CodeGen; using BefunGen.AST.CodeGen.Tags; using BefunGen.AST.DirectRun; using BefunGen.AST.Exceptions; using BefunGen.MathExtensions; using System; using System.Collections.Generic; using System.Linq; namespace BefunGen.AST { public class Program : ASTObject { //TODO Possible Optimizations [LOW PRIO] //Optimize -> ArrayValuePointer/DisplayArrayPointer when Indizies Constant -> Direct Link //Optimize -> Remove unused global/local variables (not params) //Optimize -> Remove NOP - Switch Cases public string Identifier; public readonly Method MainMethod; public readonly List<Method> MethodList; // Includes MainStatement (at 0) public readonly List<VarDeclaration> Constants; public readonly List<VarDeclaration> Variables; // Global Variables public bool HasDisplay { get { return DisplayHeight * DisplayWidth > 0; } } public int DisplayOffsetX; public int DisplayOffsetY; public readonly int DisplayWidth; public readonly int DisplayHeight; public Program(SourceCodePosition pos, ProgramHeader hdr, List<VarDeclaration> c, List<VarDeclaration> g, Method m, List<Method> mlst) : base(hdr.Position) { this.Identifier = hdr.Identifier; this.Constants = c; this.Variables = g; this.MainMethod = m; this.MethodList = mlst.ToList(); this.DisplayWidth = hdr.DisplayWidth; this.DisplayHeight = hdr.DisplayHeight; MethodList.Insert(0, MainMethod); MainMethod.AddReference(null); AddPredefConstants(); MethodList.ForEach(pm => pm.Owner = this); Constants.ForEach(pc => pc.SetConstant()); TestConstantsForDefinition(); TestGlobalVarsForDefinition(); TestDuplicateIdentifierCondition(); } public override string GetDebugString() { return string.Format("#Program [{0}|{1}] ({2})\n[\n#Constants:\n{3}\n#Variables:\n{4}\n#Body:\n{5}\n]", DisplayWidth, DisplayHeight, Identifier, Indent(GetDebugStringForList(Constants)), Indent(GetDebugStringForList(Variables)), Indent(GetDebugStringForList(MethodList)) ); } public string GetWellFormattedHeader() { if (HasDisplay) { return string.Format("{0} : display [{1}, {2}]", Identifier, DisplayWidth, DisplayHeight); } else { return Identifier; } } private void AddPredefConstants() { Constants.Insert(0, new VarDeclarationValue( new SourceCodePosition(), new BTypeInt(new SourceCodePosition()), "DISPLAY_SIZE", new LiteralInt(new SourceCodePosition(), DisplayWidth * DisplayHeight))); Constants.Insert(0, new VarDeclarationValue( new SourceCodePosition(), new BTypeInt(new SourceCodePosition()), "DISPLAY_HEIGHT", new LiteralInt(new SourceCodePosition(), DisplayHeight))); Constants.Insert(0, new VarDeclarationValue( new SourceCodePosition(), new BTypeInt(new SourceCodePosition()), "DISPLAY_WIDTH", new LiteralInt(new SourceCodePosition(), DisplayWidth))); } private void TestConstantsForDefinition() { foreach (VarDeclaration v in Constants) if (!v.HasCompleteUserDefiniedInitialValue) throw new UndefiniedValueInitConstantException(v.Position, v.Identifier); } private void TestGlobalVarsForDefinition() { foreach (VarDeclaration v in Variables) if (v.HasCompleteUserDefiniedInitialValue) throw new InitGlobalVariableException(v.Position, v.Identifier); } private void TestDuplicateIdentifierCondition() { // Duplicate in Global variables if (Variables.Any(lp1 => Variables.Any(lp2 => lp1.Identifier.ToLower() == lp2.Identifier.ToLower() && lp1 != lp2))) { VarDeclaration err = Variables.Last(lp1 => Variables.Any(lp2 => lp1.Identifier.ToLower() == lp2.Identifier.ToLower())); throw new DuplicateIdentifierException(err.Position, err.Identifier); } // Duplicate in Constants if (Constants.Any(lp1 => Constants.Any(lp2 => lp1.Identifier.ToLower() == lp2.Identifier.ToLower() && lp1 != lp2))) { VarDeclaration err = Constants.Last(lp1 => Constants.Any(lp2 => lp1.Identifier.ToLower() == lp2.Identifier.ToLower())); throw new DuplicateIdentifierException(err.Position, err.Identifier); } // Name Conflict Global variables <-> Constants if (Constants.Any(lp1 => Variables.Any(lp2 => lp1.Identifier.ToLower() == lp2.Identifier.ToLower() && lp1 != lp2))) { VarDeclaration err = Constants.Last(lp1 => Variables.Any(lp2 => lp1.Identifier.ToLower() == lp2.Identifier.ToLower())); throw new DuplicateIdentifierException(err.Position, err.Identifier); } // Name Methods if (MethodList.Any(lp1 => MethodList.Any(lp2 => lp1.Identifier.ToLower() == lp2.Identifier.ToLower() && lp1 != lp2))) { Method err = MethodList.Last(lp1 => MethodList.Any(lp2 => lp1.Identifier.ToLower() == lp2.Identifier.ToLower())); throw new DuplicateIdentifierException(err.Position, err.Identifier); } // Name Conflict Local variables <-> (Constants & Global variables) foreach (Method m in MethodList) { foreach (VarDeclaration t in m.Variables) { if (Constants.Any(pl => pl.Identifier.ToLower() == t.Identifier.ToLower()) || Variables.Any(pl => pl.Identifier.ToLower() == t.Identifier.ToLower())) { throw new DuplicateIdentifierException(t.Position, t.Identifier); } } } } #region Prepare public void Prepare() { // Reset ID-Counter Method.ResetCounter(); VarDeclaration.ResetCounter(); Statement.ResetCounter(); IntegrateStatementLists(); // Flattens StatementList Hierachie && Cleans it up (Removes NOP's, empty StmtLists) ForceMethodReturn(); // Every Method must always end with a RETURN && No Return in Main {{CODE-MANIPULATION}} AddressMethods(); // Methods get their Address AddressCodePoints(); // CodeAdressesTargets get their Address LinkVariables(); // Variable-uses get their ID InlineConstants(); // ValuePointer to Constants become Literals {{CODE-MANIPULATION}} EvaluateExpressions(); // Simplify Expressions if possible {{CODE-MANIPULATION}} LinkMethods(); // Methodcalls get their ID && Labels + MethodCalls get their CodePointAddress RemoveUnreferencedMethods(); LinkResultTypes(); // Statements get their Result-Type (and implicit casting is added) } private void IntegrateStatementLists() { foreach (Method m in MethodList) m.IntegrateStatementLists(); } private void AddressMethods() { foreach (Method m in MethodList) m.CreateCodeAddress(); } private void AddressCodePoints() { foreach (Method m in MethodList) m.AddressCodePoints(); } private void LinkVariables() { foreach (Method m in MethodList) m.LinkVariables(); } private void InlineConstants() { if (Constants.Count == 0) return; foreach (Method m in MethodList) m.InlineConstants(); } private void LinkMethods() { foreach (Method m in MethodList) m.LinkMethods(this); } private void RemoveUnreferencedMethods() { if (CGO.RemUnreferencedMethods) { for (int i = MethodList.Count - 1; i >= 0; i--) { if (MethodList[i].ReferenceCount == 0) { MethodList.RemoveAt(i); } } } } private void LinkResultTypes() { foreach (Method m in MethodList) m.LinkResultTypes(); } private void ForceMethodReturn() { foreach (Method m in MethodList) m.ForceMethodReturn(m == MainMethod); MainMethod.RaiseErrorOnReturnStatement(); } private void EvaluateExpressions() { if (!CGO.CompileTimeEvaluateExpressions) return; // It's disabled foreach (Method m in MethodList) m.EvaluateExpressions(); } #endregion public Method FindMethodByIdentifier(string ident) { return MethodList.Count(p => p.Identifier.ToLower() == ident.ToLower()) == 1 ? MethodList.Single(p => p.Identifier.ToLower() == ident.ToLower()) : null; } public int GetMaxReturnValueWidth() { return MathExt.Max(1, MethodList.Select(p => p.ResultType.GetCodeSize()).ToArray()); } public CodePiece GenerateCode(string initialDisp = "") //TODO Make two runs - use first run for width estimation { var estimationRun = GenerateCode(0, initialDisp); return GenerateCode(estimationRun.Width, initialDisp); } private CodePiece GenerateCode(int estimatedWidth, string initialDisp) { // v {TEMP..} // 0 v{STACKFLOODER} < // {++++++++++++} | // v < // ############### // ############### // ## ## // ## {DISPLAY} ## // ## ## // ############### // ############### | // v < // :# $ {GLOBALVAR} # // !# $ {GLOBALVAR} ! // ## $ // ># $ {METHOD} // |# $ {++++++} // # $ {++++++} // ##$ // #>$ {METHOD} // #|$ {++++++} // # $ {++++++} // # $ {METHOD} // # $ {++++++} ResetBeforeCodeGen(); List<Tuple<MathExt.Point, CodePiece>> methPieces = new List<Tuple<MathExt.Point, CodePiece>>(); CodeGenEnvironment env = new CodeGenEnvironment(); env.MaxVarDeclarationWidth = MathExt.Max(estimatedWidth - 4 - CodeGenConstants.LANE_VERTICAL_MARGIN - 2, CodeGenConstants.MinVarDeclarationWidth, DisplayWidth, CGO.DefaultVarDeclarationWidth); CodePiece p = new CodePiece(); int maxReturnValWidth = GetMaxReturnValueWidth(); int methOffsetX = 4 + CodeGenConstants.LANE_VERTICAL_MARGIN; #region Generate Top Lane CodePiece pTopLane = new CodePiece(); pTopLane[0, 0] = BCHelper.PCDown; pTopLane[CodeGenConstants.TMP_FIELDPOS_IO_ARR.X, CodeGenConstants.TMP_FIELDPOS_IO_ARR.Y] = BCHelper.Chr(CGO.DefaultTempSymbol, new TemporaryCodeFieldTag()); env.TMP_FIELD_IO_ARR = CodeGenConstants.TMP_FIELDPOS_IO_ARR; pTopLane[CodeGenConstants.TMP_FIELDPOS_OUT_ARR.X, CodeGenConstants.TMP_FIELDPOS_OUT_ARR.Y] = BCHelper.Chr(CGO.DefaultTempSymbol, new TemporaryCodeFieldTag()); env.TMP_FIELD_OUT_ARR = CodeGenConstants.TMP_FIELDPOS_OUT_ARR; pTopLane[CodeGenConstants.TMP_FIELDPOS_JMP_ADDR.X, CodeGenConstants.TMP_FIELDPOS_JMP_ADDR.Y] = BCHelper.Chr(CGO.DefaultTempSymbol, new TemporaryCodeFieldTag()); env.TMP_FIELD_JMP_ADDR = CodeGenConstants.TMP_FIELDPOS_JMP_ADDR; pTopLane[CodeGenConstants.TMP_FIELDPOS_GENERAL.X, CodeGenConstants.TMP_FIELDPOS_GENERAL.Y] = BCHelper.Chr(CGO.DefaultTempSymbol, new TemporaryCodeFieldTag()); env.TMP_FIELD_GENERAL = CodeGenConstants.TMP_FIELDPOS_GENERAL; int tempDeclHeight = 0; if (maxReturnValWidth < (CodeGenConstants.TOP_COMMENT_X - CodeGenConstants.TMP_ARRFIELDPOS_RETURNVAL_TL.X - 3)) { // Single line env.TMP_ARRFIELD_RETURNVAL = new VarDeclarationPosition(CodeGenConstants.TMP_ARRFIELDPOS_RETURNVAL_TL, maxReturnValWidth, 1, maxReturnValWidth); pTopLane.Fill( env.TMP_ARRFIELD_RETURNVAL.X, env.TMP_ARRFIELD_RETURNVAL.Y, env.TMP_ARRFIELD_RETURNVAL.X + maxReturnValWidth, env.TMP_ARRFIELD_RETURNVAL.Y + 1, BCHelper.Chr(CGO.DefaultResultTempSymbol), new TemporaryResultCodeFieldTag(maxReturnValWidth)); tempDeclHeight = 1; } else { // Multiline (or at least in its own seperate row) var space = CodePieceStore.CreateVariableSpace( maxReturnValWidth, CGO, env.MaxVarDeclarationWidth, BCHelper.Chr(CGO.DefaultResultTempSymbol), new TemporaryResultCodeFieldTag(maxReturnValWidth)); env.TMP_ARRFIELD_RETURNVAL = space.Item2 + new MathExt.Point(1, 1); pTopLane.SetAt(1, 1, space.Item1); tempDeclHeight = 1 + space.Item1.Height; } pTopLane.SetText(CodeGenConstants.TOP_COMMENT_X, 0, "// generated by BefunGen v" + CodeGenConstants.BEFUNGEN_VERSION); pTopLane.CreateColWw(0, 1, tempDeclHeight); pTopLane[0, tempDeclHeight] = BCHelper.Digit0; pTopLane[2, tempDeclHeight] = BCHelper.PCDown; CodePiece pFlooder = CodePieceStore.BooleanStackFlooder(); pTopLane.SetAt(3, tempDeclHeight, pFlooder); CodePiece displayValue = GenerateCode_DisplayValue(initialDisp); CodePiece pDisplay = GenerateCode_Display(displayValue); DisplayOffsetX = 3; DisplayOffsetY = 2 + tempDeclHeight; pTopLane.SetAt(DisplayOffsetX, DisplayOffsetY, pDisplay); int topLaneBottomRow = 2 + tempDeclHeight + pDisplay.Height; DisplayOffsetX += CGO.DisplayBorderThickness; DisplayOffsetY += CGO.DisplayBorderThickness; pTopLane[0, topLaneBottomRow] = BCHelper.PCDown; pTopLane[1, topLaneBottomRow] = BCHelper.Walkway; pTopLane.FillColWw(0, tempDeclHeight + 1, topLaneBottomRow); pTopLane.FillColWw(2, tempDeclHeight + 1, topLaneBottomRow + 1); p.SetAt(0, 0, pTopLane); #endregion int laneStartY = p.MaxY; int methOffsetY = p.MaxY; // +3 For the MinY=3 of VerticalLaneTurnout_Dec #region Insert VariableSpace CodePiece pVars = CodePieceStore.CreateVariableSpace(Variables, methOffsetX, methOffsetY, CGO, env.MaxVarDeclarationWidth); p.SetAt(methOffsetX, methOffsetY, pVars); #endregion methOffsetY += Math.Max(0, pVars.Height - 3); // -3 For the MinY=3 of VerticalLaneTurnout_Dec methOffsetY += 3; // +3 For the MinY=3 of VerticalLaneTurnout_Dec #region Insert Methods for (int i = 0; i < MethodList.Count; i++) { Method m = MethodList[i]; CodePiece pMethod = m.GenerateCode(env, methOffsetX, methOffsetY); if (p.HasActiveTag(typeof(MethodEntryFullInitializationTag))) // Force MethodEntry_FullIntialization Distance (at least so that lanes can be generated) { int pLast = p.FindAllActiveCodeTags(typeof(MethodEntryFullInitializationTag)).Last().Y; int pNext = pMethod.FindAllActiveCodeTags(typeof(MethodEntryFullInitializationTag)).First().Y + (methOffsetY - pMethod.MinY); int overflow = (pNext - pLast) - CodePieceStore.VerticalLaneTurnout_Dec(false).Height; if (overflow < 0) { methOffsetY -= overflow; } } int mx = methOffsetX - pMethod.MinX; int my = methOffsetY - pMethod.MinY; methPieces.Add(Tuple.Create(new MathExt.Point(mx, my), pMethod)); p.SetAt(mx, my, pMethod); methOffsetY += pMethod.Height + CodeGenConstants.VERTICAL_METHOD_DISTANCE; } #endregion int highwayX = p.MaxX; #region Generate Lane Chooser p.FillRowWw(tempDeclHeight, 3 + pFlooder.Width, highwayX); p.FillRowWw(topLaneBottomRow, 3, highwayX); p[highwayX, tempDeclHeight] = BCHelper.PCLeft; p[highwayX, topLaneBottomRow - 1] = BCHelper.IfVertical; p[highwayX, topLaneBottomRow + 0] = BCHelper.PCLeft; p[highwayX, topLaneBottomRow + 1] = BCHelper.PCJump; p[highwayX, topLaneBottomRow + 2] = BCHelper.Not; p.FillColWw(highwayX, tempDeclHeight+1, topLaneBottomRow - 1); #endregion #region Generate Lanes (Left Lane && Right Lane) List<TagLocation> methodEntries = p.FindAllActiveCodeTags(typeof(MethodEntryFullInitializationTag)) // Left Lane .OrderBy(tp => tp.Y) .ToList(); List<TagLocation> codeEntries = p.FindAllActiveCodeTags(typeof(MethodCallHorizontalReEntryTag)) // Right Lane .OrderBy(tp => tp.Y) .ToList(); int last; bool first; //######### LEFT LANE ######### first = true; last = laneStartY; foreach (TagLocation methodEntry in methodEntries) { CodePiece pTurnout = CodePieceStore.VerticalLaneTurnout_Dec(first); p.FillColWw(0, last, methodEntry.Y + pTurnout.MinY); p.SetAt(0, methodEntry.Y, pTurnout); p.FillRowWw(methodEntry.Y, 4, methodEntry.X); last = methodEntry.Y + pTurnout.MaxY; first = false; } //p.FillColWW(0, last, p.MaxY); //######### RIGHT LANE ######### first = true; last = laneStartY; foreach (TagLocation codeEntry in codeEntries) { CodePiece pTurnout = CodePieceStore.VerticalLaneTurnout_Test(); p.FillColWw(2, last, codeEntry.Y + pTurnout.MinY); p.SetAt(2, codeEntry.Y, pTurnout); p.CreateRowWw(codeEntry.Y, 4, codeEntry.X); last = codeEntry.Y + pTurnout.MaxY; first = false; } //p.FillColWW(2, last, p.MaxY); //######### MIDDLE LANE ######### p.Fill(1, laneStartY, 2, p.MaxY, BCHelper.PCJump); //######### POP LANE ######### p.Fill(3, laneStartY, 4, p.MaxY, BCHelper.StackPop); #endregion #region Generate Highway (Path on right side of code) List<TagLocation> codeExits = p.FindAllActiveCodeTags(typeof(MethodCallHorizontalExitTag)) .OrderBy(tp => tp.Y) .ToList(); first = true; last = topLaneBottomRow + 3; foreach (TagLocation exit in codeExits) { p.FillColWw(highwayX, last, exit.Y); p[highwayX, exit.Y] = BCHelper.PCUp; p.CreateRowWw(exit.Y, exit.X + 1, highwayX); last = exit.Y + 1; exit.Tag.Deactivate(); first = false; } #endregion return p; } private CodePiece GenerateCode_Display(CodePiece val) { MathExt.Point s = new MathExt.Point(DisplayWidth, DisplayHeight); int b = CGO.DisplayBorderThickness; CodePiece p = new CodePiece(); if (s.Size == 0) return p; p.SetAt(b, b, val); // 44111111 // 44111111 // 44 22 // 44 22 // 44 22 // 44 22 // 33333322 // 33333322 p.Fill(b, 0, s.X + 2 * b, b, BCHelper.Chr(CGO.DisplayBorder)); // 1 p.Fill(s.X + b, b, s.X + 2 * b, s.Y + 2 * b, BCHelper.Chr(CGO.DisplayBorder)); // 2 p.Fill(0, s.Y + b, s.X + b, s.Y + 2 * b, BCHelper.Chr(CGO.DisplayBorder)); // 3 p.Fill(0, 0, b, s.Y + b, BCHelper.Chr(CGO.DisplayBorder)); // 4 p.SetTag(0, 0, new DisplayTopLeftTag(this, DisplayWidth + 2 * b, DisplayHeight + 2 * b)); return p; } private CodePiece GenerateCode_DisplayValue(string dv) { CodePiece r = new CodePiece(); int w = dv.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.None).Max(s => s.Length); int h = dv.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.None).Length; if (dv == "") { w = 0; h = 0; } if (w > DisplayWidth || h > DisplayHeight) throw new InitialDisplayValueTooBigException(DisplayWidth, DisplayHeight, w, h); string[] split = dv.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.None); BefungeCommand def = BCHelper.Chr(CGO.DefaultDisplayValue); if (def.Type == BefungeCommandType.NOP) def = BCHelper.Walkway; for (int y = 0; y < DisplayHeight; y++) { for (int x = 0; x < DisplayWidth; x++) { r[x, y] = (y < split.Length && x < split[y].Length) ? BCHelper.Chr(split[y][x]) : def; } } return r; } private void ResetBeforeCodeGen() { foreach (var v in Variables) v.ResetBeforeCodeGen(); foreach (var m in MethodList) m.ResetBeforeCodeGen(); Method.ResetCounter(); VarDeclaration.ResetCounter(); Statement.ResetCounter(); } public void RunDirect(RunnerEnvironment env, string initialDisp) { env.ResetDisplay(DisplayWidth, DisplayHeight, initialDisp, ' '); foreach (var ml in MethodList) env.RegisterMethod(ml); foreach (var cc in Constants) env.RegisterGlobalVariable(cc); foreach (var vv in Variables) env.RegisterGlobalVariable(vv); MainMethod.RunDirect(env, new List<long>(), out _); } } public class ProgramFooter : ASTObject // TEMPORARY -- NOT IN RESULTING AST { public ProgramFooter(SourceCodePosition pos) : base(pos) { } public override string GetDebugString() { throw new AccessTemporaryASTObjectException(Position); } } public class ProgramHeader : ASTObject // TEMPORARY -- NOT IN RESULTING AST { public readonly string Identifier; public readonly int DisplayWidth; public readonly int DisplayHeight; public ProgramHeader(SourceCodePosition pos, string id) : this(pos, id, 0, 0) { // -- } public ProgramHeader(SourceCodePosition pos, string ident, int w, int h) : base(pos) { this.Identifier = ident; if (ASTObject.IsKeyword(ident)) { throw new IllegalIdentifierException(Position, ident); } if (w * h == 0) { DisplayWidth = 0; DisplayHeight = 0; } else { DisplayWidth = w; DisplayHeight = h; } } public override string GetDebugString() { throw new AccessTemporaryASTObjectException(Position); } } }
using System; using System.Diagnostics; namespace Badget.LibListview.Controls { /// <summary> /// Direction of column sorting /// </summary> public enum SortDirections { /// <summary> /// Ascending Items /// </summary> SortAscending, /// <summary> /// Descending Items /// </summary> SortDescending } /// <summary> /// Summary description for GLQuickSort. /// </summary> internal class GLQuickSort { public GLQuickSort() { // // TODO: Add constructor logic here // } private enum CompareDirection { GreaterThan, LessThan }; /// <summary> /// compare only numeric values in items. Warning, this can end up slowing down routine quite a bit /// </summary> private bool m_bNumericCompare = false; public bool NumericCompare { get { return m_bNumericCompare; } set { m_bNumericCompare = value; } } /// <summary> /// Stop this sort before it finishes /// </summary> private bool m_bStopRequested = false; public bool StopRequested { get { return m_bStopRequested; } set { m_bStopRequested = value; } } /// <summary> /// Column within the items structure to sort /// </summary> private int m_nSortColumn = 0; public int SortColumn { get { return m_nSortColumn; } set { m_nSortColumn = value; } } /// <summary> /// Direction this sorting routine will move items /// </summary> private SortDirections m_SortDirection = SortDirections.SortDescending; public SortDirections SortDirection { get { return m_SortDirection; } set{ m_SortDirection = value; } } public void QuickSort( GLItemCollection items, int vleft, int vright) { int w, x; GLItem tmpItem; int Med = 4; if ((vright-vleft)>Med) { w = (vright+vleft)/2; if (CompareItems( items[vleft], items[w], CompareDirection.GreaterThan )) swap(items,vleft,w); if (CompareItems( items[vleft], items[vright], CompareDirection.GreaterThan )) swap(items,vleft,vright); if (CompareItems( items[w], items[vright], CompareDirection.GreaterThan )) swap(items,w,vright); x = vright-1; swap(items,w,x); w = vleft; tmpItem = items[x]; while( true ) { while( this.CompareItems( items[++w], tmpItem, CompareDirection.LessThan ) ); while( this.CompareItems( items[--x], tmpItem, CompareDirection.GreaterThan ) ); if (x<w) break; swap(items,w,x); if ( m_bStopRequested ) return; } swap(items,w,vright-1); QuickSort(items,vleft,x); QuickSort(items,w+1,vright); } } private void swap(GLItemCollection items, int x, int w) { GLItem tmpItem; tmpItem = items[x]; items[x] = items[w]; items[w] = tmpItem; } public void GLInsertionSort(GLItemCollection items, int nLow0, int nHigh0) { int w; GLItem tmpItem; for ( int x=nLow0+1; x<=nHigh0; x++) { tmpItem = items[x]; w=x; while ( (w>nLow0) && ( this.CompareItems( items[w-1], tmpItem, CompareDirection.GreaterThan ) ) ) { items[w] = items[w-1]; w--; } items[w] = tmpItem; } } public void sort( GLItemCollection items ) { QuickSort( items, 0, items.Count - 1); GLInsertionSort( items, 0,items.Count -1); } private bool CompareItems( GLItem item1, GLItem item2, CompareDirection direction ) { // add a numeric compare here also bool dir = false; if ( direction == CompareDirection.GreaterThan ) dir=true; if ( this.SortDirection == SortDirections.SortAscending ) dir = !dir; // flip it if ( !this.NumericCompare ) { if ( dir ) { return ( item1.SubItems[SortColumn].Text.CompareTo( item2.SubItems[SortColumn].Text ) < 0 ); } else { return ( item1.SubItems[SortColumn].Text.CompareTo( item2.SubItems[SortColumn].Text ) > 0 ); } } else { try { double n1 = Double.Parse( item1.SubItems[SortColumn].Text ); double n2 = Double.Parse( item2.SubItems[SortColumn].Text ); if ( dir ) { // compare the numeric values inside the columns return ( n1 < n2 ); } else { return ( n1 > n2 ); } } catch( Exception ex ) { // no numeric value (bad bad) Debug.WriteLine( ex.ToString() ); return false; } } } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System.Diagnostics.CodeAnalysis; using System.Runtime.Serialization; using System.Management.Automation.Internal; namespace System.Management.Automation { /// <summary> /// Defines the exception thrown for all Metadata errors. /// </summary> [Serializable] public class MetadataException : RuntimeException { internal const string MetadataMemberInitialization = "MetadataMemberInitialization"; internal const string BaseName = "Metadata"; /// <summary> /// Initializes a new instance of MetadataException with serialization parameters. /// </summary> /// <param name="info">Serialization information.</param> /// <param name="context">Streaming context.</param> protected MetadataException(SerializationInfo info, StreamingContext context) : base(info, context) { SetErrorCategory(ErrorCategory.MetadataError); } /// <summary> /// Initializes a new instance of MetadataException with the message set /// to typeof(MetadataException).FullName. /// </summary> public MetadataException() : base(typeof(MetadataException).FullName) { SetErrorCategory(ErrorCategory.MetadataError); } /// <summary> /// Initializes a new instance of MetadataException setting the message. /// </summary> /// <param name="message">The exception's message.</param> public MetadataException(string message) : base(message) { SetErrorCategory(ErrorCategory.MetadataError); } /// <summary> /// Initializes a new instance of MetadataException setting the message and innerException. /// </summary> /// <param name="message">The exception's message.</param> /// <param name="innerException">The exceptions's inner exception.</param> public MetadataException(string message, Exception innerException) : base(message, innerException) { SetErrorCategory(ErrorCategory.MetadataError); } internal MetadataException(string errorId, Exception innerException, string resourceStr, params object[] arguments) : base(StringUtil.Format(resourceStr, arguments), innerException) { SetErrorCategory(ErrorCategory.MetadataError); SetErrorId(errorId); } } /// <summary> /// Defines the exception thrown for all Validate attributes. /// </summary> [Serializable] [SuppressMessage("Microsoft.Usage", "CA2240:ImplementISerializableCorrectly")] public class ValidationMetadataException : MetadataException { internal const string ValidateRangeElementType = "ValidateRangeElementType"; internal const string ValidateRangePositiveFailure = "ValidateRangePositiveFailure"; internal const string ValidateRangeNonNegativeFailure = "ValidateRangeNonNegativeFailure"; internal const string ValidateRangeNegativeFailure = "ValidateRangeNegativeFailure"; internal const string ValidateRangeNonPositiveFailure = "ValidateRangeNonPositiveFailure"; internal const string ValidateRangeMinRangeMaxRangeType = "ValidateRangeMinRangeMaxRangeType"; internal const string ValidateRangeNotIComparable = "ValidateRangeNotIComparable"; internal const string ValidateRangeMaxRangeSmallerThanMinRange = "ValidateRangeMaxRangeSmallerThanMinRange"; internal const string ValidateRangeGreaterThanMaxRangeFailure = "ValidateRangeGreaterThanMaxRangeFailure"; internal const string ValidateRangeSmallerThanMinRangeFailure = "ValidateRangeSmallerThanMinRangeFailure"; internal const string ValidateFailureResult = "ValidateFailureResult"; internal const string ValidatePatternFailure = "ValidatePatternFailure"; internal const string ValidateScriptFailure = "ValidateScriptFailure"; internal const string ValidateCountNotInArray = "ValidateCountNotInArray"; internal const string ValidateCountMaxLengthSmallerThanMinLength = "ValidateCountMaxLengthSmallerThanMinLength"; internal const string ValidateCountMinLengthFailure = "ValidateCountMinLengthFailure"; internal const string ValidateCountMaxLengthFailure = "ValidateCountMaxLengthFailure"; internal const string ValidateLengthMaxLengthSmallerThanMinLength = "ValidateLengthMaxLengthSmallerThanMinLength"; internal const string ValidateLengthNotString = "ValidateLengthNotString"; internal const string ValidateLengthMinLengthFailure = "ValidateLengthMinLengthFailure"; internal const string ValidateLengthMaxLengthFailure = "ValidateLengthMaxLengthFailure"; internal const string ValidateSetFailure = "ValidateSetFailure"; internal const string ValidateVersionFailure = "ValidateVersionFailure"; internal const string InvalidValueFailure = "InvalidValueFailure"; /// <summary> /// Initializes a new instance of ValidationMetadataException with serialization parameters. /// </summary> /// <param name="info">Serialization information.</param> /// <param name="context">Streaming context.</param> protected ValidationMetadataException(SerializationInfo info, StreamingContext context) : base(info, context) { } /// <summary> /// Initializes a new instance of ValidationMetadataException with the message set /// to typeof(ValidationMetadataException).FullName. /// </summary> public ValidationMetadataException() : base(typeof(ValidationMetadataException).FullName) { } /// <summary> /// Initializes a new instance of ValidationMetadataException setting the message. /// </summary> /// <param name="message">The exception's message.</param> public ValidationMetadataException(string message) : this(message, false) { } /// <summary> /// Initializes a new instance of ValidationMetadataException setting the message and innerException. /// </summary> /// <param name="message">The exception's message.</param> /// <param name="innerException">The exceptions's inner exception.</param> public ValidationMetadataException(string message, Exception innerException) : base(message, innerException) { } internal ValidationMetadataException(string errorId, Exception innerException, string resourceStr, params object[] arguments) : base(errorId, innerException, resourceStr, arguments) { } /// <summary> /// Initialize a new instance of ValidationMetadataException. This validation exception could be /// ignored in positional binding phase if the <para>swallowException</para> is set to be true. /// </summary> /// <param name="message"> /// The error message</param> /// <param name="swallowException"> /// Indicate whether to swallow this exception in positional binding phase /// </param> internal ValidationMetadataException(string message, bool swallowException) : base(message) { _swallowException = swallowException; } /// <summary> /// Make the positional binding swallow this exception when it's set to true. /// </summary> /// <remarks> /// This property is only used internally in the positional binding phase /// </remarks> internal bool SwallowException { get { return _swallowException; } } private bool _swallowException = false; } /// <summary> /// Defines the exception thrown for all ArgumentTransformation attributes. /// </summary> [Serializable] public class ArgumentTransformationMetadataException : MetadataException { internal const string ArgumentTransformationArgumentsShouldBeStrings = "ArgumentTransformationArgumentsShouldBeStrings"; /// <summary> /// Initializes a new instance of ArgumentTransformationMetadataException with serialization parameters. /// </summary> /// <param name="info">Serialization information.</param> /// <param name="context">Streaming context.</param> protected ArgumentTransformationMetadataException(SerializationInfo info, StreamingContext context) : base(info, context) { } /// <summary> /// Initializes a new instance of ArgumentTransformationMetadataException with the message set /// to typeof(ArgumentTransformationMetadataException).FullName. /// </summary> public ArgumentTransformationMetadataException() : base(typeof(ArgumentTransformationMetadataException).FullName) { } /// <summary> /// Initializes a new instance of ArgumentTransformationMetadataException setting the message. /// </summary> /// <param name="message">The exception's message.</param> public ArgumentTransformationMetadataException(string message) : base(message) { } /// <summary> /// Initializes a new instance of ArgumentTransformationMetadataException setting the message and innerException. /// </summary> /// <param name="message">The exception's message.</param> /// <param name="innerException">The exceptions's inner exception.</param> public ArgumentTransformationMetadataException(string message, Exception innerException) : base(message, innerException) { } internal ArgumentTransformationMetadataException(string errorId, Exception innerException, string resourceStr, params object[] arguments) : base(errorId, innerException, resourceStr, arguments) { } } /// <summary> /// Defines the exception thrown for all parameter binding exceptions related to metadata attributes. /// </summary> [Serializable] public class ParsingMetadataException : MetadataException { internal const string ParsingTooManyParameterSets = "ParsingTooManyParameterSets"; /// <summary> /// Initializes a new instance of ParsingMetadataException with serialization parameters. /// </summary> /// <param name="info">Serialization information.</param> /// <param name="context">Streaming context.</param> protected ParsingMetadataException(SerializationInfo info, StreamingContext context) : base(info, context) { } /// <summary> /// Initializes a new instance of ParsingMetadataException with the message set /// to typeof(ParsingMetadataException).FullName. /// </summary> public ParsingMetadataException() : base(typeof(ParsingMetadataException).FullName) { } /// <summary> /// Initializes a new instance of ParsingMetadataException setting the message. /// </summary> /// <param name="message">The exception's message.</param> public ParsingMetadataException(string message) : base(message) { } /// <summary> /// Initializes a new instance of ParsingMetadataException setting the message and innerException. /// </summary> /// <param name="message">The exception's message.</param> /// <param name="innerException">The exceptions's inner exception.</param> public ParsingMetadataException(string message, Exception innerException) : base(message, innerException) { } internal ParsingMetadataException(string errorId, Exception innerException, string resourceStr, params object[] arguments) : base(errorId, innerException, resourceStr, arguments) { } } }
/******************************************************************** * * PropertyBag.cs * -------------- * Derived from PropertyBag.cs by Tony Allowatt * CodeProject: http://www.codeproject.com/cs/miscctrl/bending_property.asp * Last Update: 04/05/2005 * ********************************************************************/ using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Drawing.Design; using System.Reflection; using CslaGenerator.Attributes; using CslaGenerator.Metadata; namespace CslaGenerator.Util.PropertyBags { /// <summary> /// Represents a collection of custom properties that can be selected into a /// PropertyGrid to provide functionality beyond that of the simple reflection /// normally used to query an object's properties. /// </summary> public class DecoratorArgumentBag : ICustomTypeDescriptor { #region PropertySpecCollection class definition /// <summary> /// Encapsulates a collection of PropertySpec objects. /// </summary> [Serializable] public class PropertySpecCollection : IList { private readonly ArrayList _innerArray; /// <summary> /// Initializes a new instance of the PropertySpecCollection class. /// </summary> public PropertySpecCollection() { _innerArray = new ArrayList(); } /// <summary> /// Gets or sets the element at the specified index. /// In C#, this property is the indexer for the PropertySpecCollection class. /// </summary> /// <param name="index">The zero-based index of the element to get or set.</param> /// <value> /// The element at the specified index. /// </value> public PropertySpec this[int index] { get { return (PropertySpec) _innerArray[index]; } set { _innerArray[index] = value; } } #region IList Members /// <summary> /// Gets the number of elements in the PropertySpecCollection. /// </summary> /// <value> /// The number of elements contained in the PropertySpecCollection. /// </value> public int Count { get { return _innerArray.Count; } } /// <summary> /// Gets a value indicating whether the PropertySpecCollection has a fixed size. /// </summary> /// <value> /// true if the PropertySpecCollection has a fixed size; otherwise, false. /// </value> public bool IsFixedSize { get { return false; } } /// <summary> /// Gets a value indicating whether the PropertySpecCollection is read-only. /// </summary> public bool IsReadOnly { get { return false; } } /// <summary> /// Gets a value indicating whether access to the collection is synchronized (thread-safe). /// </summary> /// <value> /// true if access to the PropertySpecCollection is synchronized (thread-safe); otherwise, false. /// </value> public bool IsSynchronized { get { return false; } } /// <summary> /// Gets an object that can be used to synchronize access to the collection. /// </summary> /// <value> /// An object that can be used to synchronize access to the collection. /// </value> object ICollection.SyncRoot { get { return null; } } /// <summary> /// Removes all elements from the PropertySpecCollection. /// </summary> public void Clear() { _innerArray.Clear(); } /// <summary> /// Returns an enumerator that can iterate through the PropertySpecCollection. /// </summary> /// <returns>An IEnumerator for the entire PropertySpecCollection.</returns> public IEnumerator GetEnumerator() { return _innerArray.GetEnumerator(); } /// <summary> /// Removes the object at the specified index of the PropertySpecCollection. /// </summary> /// <param name="index">The zero-based index of the element to remove.</param> public void RemoveAt(int index) { _innerArray.RemoveAt(index); } #endregion /// <summary> /// Adds a PropertySpec to the end of the PropertySpecCollection. /// </summary> /// <param name="value">The PropertySpec to be added to the end of the PropertySpecCollection.</param> /// <returns>The PropertySpecCollection index at which the value has been added.</returns> public int Add(PropertySpec value) { int index = _innerArray.Add(value); return index; } /// <summary> /// Adds the elements of an array of PropertySpec objects to the end of the PropertySpecCollection. /// </summary> /// <param name="array">The PropertySpec array whose elements should be added to the end of the /// PropertySpecCollection.</param> public void AddRange(PropertySpec[] array) { _innerArray.AddRange(array); } /// <summary> /// Determines whether a PropertySpec is in the PropertySpecCollection. /// </summary> /// <param name="item">The PropertySpec to locate in the PropertySpecCollection. The element to locate /// can be a null reference (Nothing in Visual Basic).</param> /// <returns>true if item is found in the PropertySpecCollection; otherwise, false.</returns> public bool Contains(PropertySpec item) { return _innerArray.Contains(item); } /// <summary> /// Determines whether a PropertySpec with the specified name is in the PropertySpecCollection. /// </summary> /// <param name="name">The name of the PropertySpec to locate in the PropertySpecCollection.</param> /// <returns>true if item is found in the PropertySpecCollection; otherwise, false.</returns> public bool Contains(string name) { foreach (PropertySpec spec in _innerArray) if (spec.Name == name) return true; return false; } /// <summary> /// Copies the entire PropertySpecCollection to a compatible one-dimensional Array, starting at the /// beginning of the target array. /// </summary> /// <param name="array">The one-dimensional Array that is the destination of the elements copied /// from PropertySpecCollection. The Array must have zero-based indexing.</param> public void CopyTo(PropertySpec[] array) { _innerArray.CopyTo(array); } /// <summary> /// Copies the PropertySpecCollection or a portion of it to a one-dimensional array. /// </summary> /// <param name="array">The one-dimensional Array that is the destination of the elements copied /// from the collection.</param> /// <param name="index">The zero-based index in array at which copying begins.</param> public void CopyTo(PropertySpec[] array, int index) { _innerArray.CopyTo(array, index); } /// <summary> /// Searches for the specified PropertySpec and returns the zero-based index of the first /// occurrence within the entire PropertySpecCollection. /// </summary> /// <param name="value">The PropertySpec to locate in the PropertySpecCollection.</param> /// <returns>The zero-based index of the first occurrence of value within the entire PropertySpecCollection, /// if found; otherwise, -1.</returns> public int IndexOf(PropertySpec value) { return _innerArray.IndexOf(value); } /// <summary> /// Searches for the PropertySpec with the specified name and returns the zero-based index of /// the first occurrence within the entire PropertySpecCollection. /// </summary> /// <param name="name">The name of the PropertySpec to locate in the PropertySpecCollection.</param> /// <returns>The zero-based index of the first occurrence of value within the entire PropertySpecCollection, /// if found; otherwise, -1.</returns> public int IndexOf(string name) { int i = 0; foreach (PropertySpec spec in _innerArray) { //if (spec.Name == name) if (spec.TargetProperty == name) return i; i++; } return -1; } /// <summary> /// Inserts a PropertySpec object into the PropertySpecCollection at the specified index. /// </summary> /// <param name="index">The zero-based index at which value should be inserted.</param> /// <param name="value">The PropertySpec to insert.</param> public void Insert(int index, PropertySpec value) { _innerArray.Insert(index, value); } /// <summary> /// Removes the first occurrence of a specific object from the PropertySpecCollection. /// </summary> /// <param name="obj">The PropertySpec to remove from the PropertySpecCollection.</param> public void Remove(PropertySpec obj) { _innerArray.Remove(obj); } /// <summary> /// Removes the property with the specified name from the PropertySpecCollection. /// </summary> /// <param name="name">The name of the PropertySpec to remove from the PropertySpecCollection.</param> public void Remove(string name) { int index = IndexOf(name); RemoveAt(index); } /// <summary> /// Copies the elements of the PropertySpecCollection to a new PropertySpec array. /// </summary> /// <returns>A PropertySpec array containing copies of the elements of the PropertySpecCollection.</returns> public PropertySpec[] ToArray() { return (PropertySpec[]) _innerArray.ToArray(typeof (PropertySpec)); } #region Explicit interface implementations for ICollection and IList /// <summary> /// This member supports the .NET Framework infrastructure and is not intended to be used directly from your code. /// </summary> void ICollection.CopyTo(Array array, int index) { CopyTo((PropertySpec[]) array, index); } /// <summary> /// This member supports the .NET Framework infrastructure and is not intended to be used directly from your code. /// </summary> int IList.Add(object value) { return Add((PropertySpec) value); } /// <summary> /// This member supports the .NET Framework infrastructure and is not intended to be used directly from your code. /// </summary> bool IList.Contains(object obj) { return Contains((PropertySpec) obj); } /// <summary> /// This member supports the .NET Framework infrastructure and is not intended to be used directly from your code. /// </summary> object IList.this[int index] { get { return this[index]; } set { this[index] = (PropertySpec) value; } } /// <summary> /// This member supports the .NET Framework infrastructure and is not intended to be used directly from your code. /// </summary> int IList.IndexOf(object obj) { return IndexOf((PropertySpec) obj); } /// <summary> /// This member supports the .NET Framework infrastructure and is not intended to be used directly from your code. /// </summary> void IList.Insert(int index, object value) { Insert(index, (PropertySpec) value); } /// <summary> /// This member supports the .NET Framework infrastructure and is not intended to be used directly from your code. /// </summary> void IList.Remove(object value) { Remove((PropertySpec) value); } #endregion } #endregion #region PropertySpecDescriptor class definition private class PropertySpecDescriptor : PropertyDescriptor { private readonly DecoratorArgumentBag _bag; private readonly PropertySpec _item; public PropertySpecDescriptor(PropertySpec item, DecoratorArgumentBag bag, string name, Attribute[] attrs) : base(name, attrs) { _bag = bag; _item = item; } public override Type ComponentType { get { return _item.GetType(); } } public override bool IsReadOnly { get { return (Attributes.Matches(ReadOnlyAttribute.Yes)); } } public override Type PropertyType { get { return Type.GetType(_item.TypeName); } } public override bool CanResetValue(object component) { if (_item.DefaultValue == null) return false; return !GetValue(component).Equals(_item.DefaultValue); } public override object GetValue(object component) { // Have the property bag raise an event to get the current value // of the property. var e = new PropertySpecEventArgs(_item, null); _bag.OnGetValue(e); return e.Value; } public override void ResetValue(object component) { SetValue(component, _item.DefaultValue); } public override void SetValue(object component, object value) { // Have the property bag raise an event to set the current value // of the property. var e = new PropertySpecEventArgs(_item, value); _bag.OnSetValue(e); } public override bool ShouldSerializeValue(object component) { object val = GetValue(component); if (_item.DefaultValue == null && val == null) return false; return !val.Equals(_item.DefaultValue); } } #endregion #region Properties and Events private readonly PropertySpecCollection _properties; private string _defaultProperty; private DecoratorArgument[] _selectedObject; /// <summary> /// Initializes a new instance of the DecoratorArgumentBag class. /// </summary> public DecoratorArgumentBag() { _defaultProperty = null; _properties = new PropertySpecCollection(); } public DecoratorArgumentBag(DecoratorArgument obj) : this(new[] {obj}) { } public DecoratorArgumentBag(DecoratorArgument[] obj) { _defaultProperty = "Name"; _properties = new PropertySpecCollection(); _selectedObject = obj; InitPropertyBag(); } /// <summary> /// Gets or sets the name of the default property in the collection. /// </summary> public string DefaultProperty { get { return _defaultProperty; } set { _defaultProperty = value; } } /// <summary> /// Gets or sets the name of the default property in the collection. /// </summary> public DecoratorArgument[] SelectedObject { get { return _selectedObject; } set { _selectedObject = value; InitPropertyBag(); } } /// <summary> /// Gets the collection of properties contained within this DecoratorArgumentBag. /// </summary> public PropertySpecCollection Properties { get { return _properties; } } /// <summary> /// Occurs when a PropertyGrid requests the value of a property. /// </summary> public event PropertySpecEventHandler GetValue; /// <summary> /// Occurs when the user changes the value of a property in a PropertyGrid. /// </summary> public event PropertySpecEventHandler SetValue; /// <summary> /// Raises the GetValue event. /// </summary> /// <param name="e">A PropertySpecEventArgs that contains the event data.</param> protected virtual void OnGetValue(PropertySpecEventArgs e) { if (e.Value != null) GetValue(this, e); e.Value = GetProperty(e.Property.TargetObject, e.Property.TargetProperty, e.Property.DefaultValue); } /// <summary> /// Raises the SetValue event. /// </summary> /// <param name="e">A PropertySpecEventArgs that contains the event data.</param> protected virtual void OnSetValue(PropertySpecEventArgs e) { if (SetValue != null) SetValue(this, e); SetProperty(e.Property.TargetObject, e.Property.TargetProperty, e.Value); } #endregion #region Initialize Propertybag private void InitPropertyBag() { PropertyInfo pi; Type t = typeof (DecoratorArgument); // _selectedObject.GetType(); PropertyInfo[] props = t.GetProperties(); // Display information for all properties. for (int i = 0; i < props.Length; i++) { pi = props[i]; object[] myAttributes = pi.GetCustomAttributes(true); string category = ""; string description = ""; bool isreadonly = false; bool isbrowsable = true; object defaultvalue = null; string userfriendlyname = ""; string typeconverter = ""; string designertypename = ""; string helptopic = ""; bool bindable = true; string editor = ""; for (int n = 0; n < myAttributes.Length; n++) { var a = (Attribute) myAttributes[n]; switch (a.GetType().ToString()) { case "System.ComponentModel.CategoryAttribute": category = ((CategoryAttribute) a).Category; break; case "System.ComponentModel.DescriptionAttribute": description = ((DescriptionAttribute) a).Description; break; case "System.ComponentModel.ReadOnlyAttribute": isreadonly = ((ReadOnlyAttribute) a).IsReadOnly; break; case "System.ComponentModel.BrowsableAttribute": isbrowsable = ((BrowsableAttribute) a).Browsable; break; case "System.ComponentModel.DefaultValueAttribute": defaultvalue = ((DefaultValueAttribute) a).Value; break; case "CslaGenerator.Attributes.UserFriendlyNameAttribute": userfriendlyname = ((UserFriendlyNameAttribute) a).UserFriendlyName; break; case "CslaGenerator.Attributes.HelpTopicAttribute": helptopic = ((HelpTopicAttribute) a).HelpTopic; break; case "System.ComponentModel.TypeConverterAttribute": typeconverter = ((TypeConverterAttribute) a).ConverterTypeName; break; case "System.ComponentModel.DesignerAttribute": designertypename = ((DesignerAttribute) a).DesignerTypeName; break; case "System.ComponentModel.BindableAttribute": bindable = ((BindableAttribute) a).Bindable; break; case "System.ComponentModel.EditorAttribute": editor = ((EditorAttribute) a).EditorTypeName; break; } } userfriendlyname = userfriendlyname.Length > 0 ? userfriendlyname : pi.Name; var types = new List<string>(); foreach (var obj in _selectedObject) { if (!types.Contains(obj.Name)) types.Add(obj.Name); } // here get rid of ComponentName and Parent bool isValidProperty = (pi.Name != "Properties" && pi.Name != "ComponentName" && pi.Name != "Parent"); if (isValidProperty && IsBrowsable(types.ToArray(), pi.Name)) { // CR added missing parameters //this.Properties.Add(new PropertySpec(userfriendlyname,pi.PropertyType.AssemblyQualifiedName,category,description,defaultvalue, editor, typeconverter, _selectedObject, pi.Name,helptopic)); Properties.Add(new PropertySpec(userfriendlyname, pi.PropertyType.AssemblyQualifiedName, category, description, defaultvalue, editor, typeconverter, _selectedObject, pi.Name, helptopic, isreadonly, isbrowsable, designertypename, bindable)); } } } #endregion private readonly Dictionary<string, PropertyInfo> propertyInfoCache = new Dictionary<string, PropertyInfo>(); private PropertyInfo GetPropertyInfoCache(string propertyName) { if (!propertyInfoCache.ContainsKey(propertyName)) { propertyInfoCache.Add(propertyName, typeof (DecoratorArgument).GetProperty(propertyName)); } return propertyInfoCache[propertyName]; } private bool IsEnumerable(PropertyInfo prop) { if (prop.PropertyType == typeof (string)) return false; Type[] interfaces = prop.PropertyType.GetInterfaces(); foreach (Type typ in interfaces) if (typ.Name.Contains("IEnumerable")) return true; return false; } #region IsBrowsable map objectType:propertyName -> true | false private bool IsBrowsable(string[] objectType, string propertyName) { try { /*if ((GeneratorController.Current.CurrentUnit.GenerationParams.GenerateAuthorization == AuthorizationLevel.None || GeneratorController.Current.CurrentUnit.GenerationParams.GenerateAuthorization == AuthorizationLevel.ObjectLevel) && (propertyName == "ReadRoles" || propertyName == "WriteRoles")) return false;*/ if (_selectedObject.Length > 1 && IsEnumerable(GetPropertyInfoCache(propertyName))) return false; return true; } catch //(Exception e) { Debug.WriteLine(objectType + ":" + propertyName); return true; } } #endregion #region Reflection functions private object GetField(Type t, string name, object target) { object obj = null; Type tx; FieldInfo[] fields; //fields = target.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public); fields = target.GetType().GetFields(BindingFlags.Public); tx = target.GetType(); obj = tx.InvokeMember(name, BindingFlags.Default | BindingFlags.GetField, null, target, new object[] {}); return obj; } private object SetField(Type t, string name, object value, object target) { object obj; obj = t.InvokeMember(name, BindingFlags.Default | BindingFlags.SetField, null, target, new[] {value}); return obj; } private bool SetProperty(object obj, string propertyName, object val) { try { // get a reference to the PropertyInfo, exit if no property with that // name PropertyInfo pi = typeof (DecoratorArgument).GetProperty(propertyName); if (pi == null) return false; // convert the value to the expected type val = Convert.ChangeType(val, pi.PropertyType); // attempt the assignment foreach (DecoratorArgument bo in (DecoratorArgument[]) obj) pi.SetValue(bo, val, null); return true; } catch { return false; } } private object GetProperty(object obj, string propertyName, object defaultValue) { try { PropertyInfo pi = GetPropertyInfoCache(propertyName); if (!(pi == null)) { var objs = (DecoratorArgument[]) obj; var valueList = new ArrayList(); foreach (DecoratorArgument bo in objs) { object value = pi.GetValue(bo, null); if (!valueList.Contains(value)) { valueList.Add(value); } } switch (valueList.Count) { case 1: return valueList[0]; default: return string.Empty; } } } catch (Exception ex) { Console.WriteLine(ex.Message); } // if property doesn't exist or throws return defaultValue; } #endregion #region ICustomTypeDescriptor explicit interface definitions // Most of the functions required by the ICustomTypeDescriptor are // merely pssed on to the default TypeDescriptor for this type, // which will do something appropriate. The exceptions are noted // below. AttributeCollection ICustomTypeDescriptor.GetAttributes() { return TypeDescriptor.GetAttributes(this, true); } string ICustomTypeDescriptor.GetClassName() { return TypeDescriptor.GetClassName(this, true); } string ICustomTypeDescriptor.GetComponentName() { return TypeDescriptor.GetComponentName(this, true); } TypeConverter ICustomTypeDescriptor.GetConverter() { return TypeDescriptor.GetConverter(this, true); } EventDescriptor ICustomTypeDescriptor.GetDefaultEvent() { return TypeDescriptor.GetDefaultEvent(this, true); } PropertyDescriptor ICustomTypeDescriptor.GetDefaultProperty() { // This function searches the property list for the property // with the same name as the DefaultProperty specified, and // returns a property descriptor for it. If no property is // found that matches DefaultProperty, a null reference is // returned instead. PropertySpec propertySpec = null; if (_defaultProperty != null) { int index = _properties.IndexOf(_defaultProperty); propertySpec = _properties[index]; } if (propertySpec != null) return new PropertySpecDescriptor(propertySpec, this, propertySpec.Name, null); return null; } object ICustomTypeDescriptor.GetEditor(Type editorBaseType) { return TypeDescriptor.GetEditor(this, editorBaseType, true); } EventDescriptorCollection ICustomTypeDescriptor.GetEvents() { return TypeDescriptor.GetEvents(this, true); } EventDescriptorCollection ICustomTypeDescriptor.GetEvents(Attribute[] attributes) { return TypeDescriptor.GetEvents(this, attributes, true); } PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties() { return ((ICustomTypeDescriptor) this).GetProperties(new Attribute[0]); } PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties(Attribute[] attributes) { // Rather than passing this function on to the default TypeDescriptor, // which would return the actual properties of DecoratorArgumentBag, I construct // a list here that contains property descriptors for the elements of the // Properties list in the bag. var props = new ArrayList(); foreach (PropertySpec property in _properties) { var attrs = new ArrayList(); // If a category, description, editor, or type converter are specified // in the PropertySpec, create attributes to define that relationship. if (property.Category != null) attrs.Add(new CategoryAttribute(property.Category)); if (property.Description != null) attrs.Add(new DescriptionAttribute(property.Description)); if (property.EditorTypeName != null) attrs.Add(new EditorAttribute(property.EditorTypeName, typeof (UITypeEditor))); if (property.ConverterTypeName != null) attrs.Add(new TypeConverterAttribute(property.ConverterTypeName)); // Additionally, append the custom attributes associated with the // PropertySpec, if any. if (property.Attributes != null) attrs.AddRange(property.Attributes); if (property.DefaultValue != null) attrs.Add(new DefaultValueAttribute(property.DefaultValue)); attrs.Add(new BrowsableAttribute(property.Browsable)); attrs.Add(new ReadOnlyAttribute(property.ReadOnly)); attrs.Add(new BindableAttribute(property.Bindable)); var attrArray = (Attribute[]) attrs.ToArray(typeof (Attribute)); // Create a new property descriptor for the property item, and add // it to the list. var pd = new PropertySpecDescriptor(property, this, property.Name, attrArray); props.Add(pd); } // Convert the list of PropertyDescriptors to a collection that the // ICustomTypeDescriptor can use, and return it. var propArray = (PropertyDescriptor[]) props.ToArray( typeof (PropertyDescriptor)); return new PropertyDescriptorCollection(propArray); } object ICustomTypeDescriptor.GetPropertyOwner(PropertyDescriptor pd) { return this; } #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 Xunit; namespace System.SpanTests { public static partial class SpanTests { [Fact] public static void ZeroLengthLastIndexOfAny_TwoByte() { var sp = new Span<int>(Array.Empty<int>()); int idx = sp.LastIndexOfAny(0, 0); Assert.Equal(-1, idx); } [Fact] public static void DefaultFilledLastIndexOfAny_TwoByte() { var rnd = new Random(42); for (int length = 0; length < byte.MaxValue; length++) { var a = new int[length]; var span = new Span<int>(a); int[] targets = { default, 99 }; for (int i = 0; i < length; i++) { int index = rnd.Next(0, 2) == 0 ? 0 : 1; int target0 = targets[index]; int target1 = targets[(index + 1) % 2]; int idx = span.LastIndexOfAny(target0, target1); Assert.Equal(span.Length - 1, idx); } } } [Fact] public static void TestMatchLastIndexOfAny_TwoByte() { for (int length = 0; length < byte.MaxValue; length++) { var a = new int[length]; for (int i = 0; i < length; i++) { a[i] = i + 1; } var span = new Span<int>(a); for (int targetIndex = 0; targetIndex < length; targetIndex++) { int target0 = a[targetIndex]; int target1 = 0; int idx = span.LastIndexOfAny(target0, target1); Assert.Equal(targetIndex, idx); } for (int targetIndex = 0; targetIndex < length - 1; targetIndex++) { int target0 = a[targetIndex]; int target1 = a[targetIndex + 1]; int idx = span.LastIndexOfAny(target0, target1); Assert.Equal(targetIndex + 1, idx); } for (int targetIndex = 0; targetIndex < length - 1; targetIndex++) { int target0 = 0; int target1 = a[targetIndex + 1]; int idx = span.LastIndexOfAny(target0, target1); Assert.Equal(targetIndex + 1, idx); } } } [Fact] public static void TestNoMatchLastIndexOfAny_TwoByte() { var rnd = new Random(42); for (int length = 0; length < byte.MaxValue; length++) { var a = new int[length]; int target0 = rnd.Next(1, 256); int target1 = rnd.Next(1, 256); var span = new Span<int>(a); int idx = span.LastIndexOfAny(target0, target1); Assert.Equal(-1, idx); } } [Fact] public static void TestMultipleMatchLastIndexOfAny_TwoByte() { for (int length = 3; length < byte.MaxValue; length++) { var a = new int[length]; for (int i = 0; i < length; i++) { int val = i + 1; a[i] = val == 200 ? 201 : val; } a[length - 1] = 200; a[length - 2] = 200; a[length - 3] = 200; var span = new Span<int>(a); int idx = span.LastIndexOfAny(200, 200); Assert.Equal(length - 1, idx); } } [Fact] public static void MakeSureNoChecksGoOutOfRangeLastIndexOfAny_TwoByte() { for (int length = 1; length < byte.MaxValue; length++) { var a = new int[length + 2]; a[0] = 99; a[length + 1] = 98; var span = new Span<int>(a, 1, length - 1); int index = span.LastIndexOfAny(99, 98); Assert.Equal(-1, index); } for (int length = 1; length < byte.MaxValue; length++) { var a = new int[length + 2]; a[0] = 99; a[length + 1] = 99; var span = new Span<int>(a, 1, length - 1); int index = span.LastIndexOfAny(99, 99); Assert.Equal(-1, index); } } [Fact] public static void ZeroLengthIndexOf_ThreeByte() { var sp = new Span<int>(Array.Empty<int>()); int idx = sp.LastIndexOfAny(0, 0, 0); Assert.Equal(-1, idx); } [Fact] public static void DefaultFilledLastIndexOfAny_ThreeByte() { var rnd = new Random(42); for (int length = 0; length < byte.MaxValue; length++) { var a = new int[length]; var span = new Span<int>(a); int[] targets = { default, 99, 98 }; for (int i = 0; i < length; i++) { int index = rnd.Next(0, 3); int target0 = targets[index]; int target1 = targets[(index + 1) % 2]; int target2 = targets[(index + 1) % 3]; int idx = span.LastIndexOfAny(target0, target1, target2); Assert.Equal(span.Length - 1, idx); } } } [Fact] public static void TestMatchLastIndexOfAny_ThreeByte() { for (int length = 0; length < byte.MaxValue; length++) { var a = new int[length]; for (int i = 0; i < length; i++) { a[i] = i + 1; } var span = new Span<int>(a); for (int targetIndex = 0; targetIndex < length; targetIndex++) { int target0 = a[targetIndex]; int target1 = 0; int target2 = 0; int idx = span.LastIndexOfAny(target0, target1, target2); Assert.Equal(targetIndex, idx); } for (int targetIndex = 0; targetIndex < length - 2; targetIndex++) { int target0 = a[targetIndex]; int target1 = a[targetIndex + 1]; int target2 = a[targetIndex + 2]; int idx = span.LastIndexOfAny(target0, target1, target2); Assert.Equal(targetIndex + 2, idx); } for (int targetIndex = 0; targetIndex < length - 2; targetIndex++) { int target0 = 0; int target1 = 0; int target2 = a[targetIndex + 2]; int idx = span.LastIndexOfAny(target0, target1, target2); Assert.Equal(targetIndex + 2, idx); } } } [Fact] public static void TestNoMatchLastIndexOfAny_ThreeByte() { var rnd = new Random(42); for (int length = 0; length < byte.MaxValue; length++) { var a = new int[length]; int target0 = rnd.Next(1, 256); int target1 = rnd.Next(1, 256); int target2 = rnd.Next(1, 256); var span = new Span<int>(a); int idx = span.LastIndexOfAny(target0, target1, target2); Assert.Equal(-1, idx); } } [Fact] public static void TestMultipleMatchLastIndexOfAny_ThreeByte() { for (int length = 4; length < byte.MaxValue; length++) { var a = new int[length]; for (int i = 0; i < length; i++) { int val = i + 1; a[i] = val == 200 ? 201 : val; } a[length - 1] = 200; a[length - 2] = 200; a[length - 3] = 200; a[length - 4] = 200; var span = new Span<int>(a); int idx = span.LastIndexOfAny(200, 200, 200); Assert.Equal(length - 1, idx); } } [Fact] public static void MakeSureNoChecksGoOutOfRangeLastIndexOfAny_ThreeByte() { for (int length = 1; length < byte.MaxValue; length++) { var a = new int[length + 2]; a[0] = 99; a[length + 1] = 98; var span = new Span<int>(a, 1, length - 1); int index = span.LastIndexOfAny(99, 98, 99); Assert.Equal(-1, index); } for (int length = 1; length < byte.MaxValue; length++) { var a = new int[length + 2]; a[0] = 99; a[length + 1] = 99; var span = new Span<int>(a, 1, length - 1); int index = span.LastIndexOfAny(99, 99, 99); Assert.Equal(-1, index); } } [Fact] public static void ZeroLengthLastIndexOfAny_ManyByte() { var sp = new Span<int>(Array.Empty<int>()); var values = new ReadOnlySpan<int>(new int[] { 0, 0, 0, 0 }); int idx = sp.LastIndexOfAny(values); Assert.Equal(-1, idx); values = new ReadOnlySpan<int>(new int[] { }); idx = sp.LastIndexOfAny(values); Assert.Equal(0, idx); } [Fact] public static void DefaultFilledLastIndexOfAny_ManyByte() { for (int length = 0; length < byte.MaxValue; length++) { var a = new int[length]; var span = new Span<int>(a); var values = new ReadOnlySpan<int>(new int[] { default, 99, 98, 0 }); for (int i = 0; i < length; i++) { int idx = span.LastIndexOfAny(values); Assert.Equal(span.Length - 1, idx); } } } [Fact] public static void TestMatchLastIndexOfAny_ManyByte() { for (int length = 0; length < byte.MaxValue; length++) { var a = new int[length]; for (int i = 0; i < length; i++) { a[i] = i + 1; } var span = new Span<int>(a); for (int targetIndex = 0; targetIndex < length; targetIndex++) { var values = new ReadOnlySpan<int>(new int[] { a[targetIndex], 0, 0, 0 }); int idx = span.LastIndexOfAny(values); Assert.Equal(targetIndex, idx); } for (int targetIndex = 0; targetIndex < length - 3; targetIndex++) { var values = new ReadOnlySpan<int>(new int[] { a[targetIndex], a[targetIndex + 1], a[targetIndex + 2], a[targetIndex + 3] }); int idx = span.LastIndexOfAny(values); Assert.Equal(targetIndex + 3, idx); } for (int targetIndex = 0; targetIndex < length - 3; targetIndex++) { var values = new ReadOnlySpan<int>(new int[] { 0, 0, 0, a[targetIndex + 3] }); int idx = span.LastIndexOfAny(values); Assert.Equal(targetIndex + 3, idx); } } } [Fact] public static void TestMatchValuesLargerLastIndexOfAny_ManyByte() { var rnd = new Random(42); for (int length = 2; length < byte.MaxValue; length++) { var a = new int[length]; int expectedIndex = length / 2; for (int i = 0; i < length; i++) { if (i == expectedIndex) { continue; } a[i] = 255; } var span = new Span<int>(a); var targets = new int[length * 2]; for (int i = 0; i < targets.Length; i++) { if (i == length + 1) { continue; } targets[i] = rnd.Next(1, 255); } var values = new ReadOnlySpan<int>(targets); int idx = span.LastIndexOfAny(values); Assert.Equal(expectedIndex, idx); } } [Fact] public static void TestNoMatchLastIndexOfAny_ManyByte() { var rnd = new Random(42); for (int length = 1; length < byte.MaxValue; length++) { var a = new int[length]; var targets = new int[length]; for (int i = 0; i < targets.Length; i++) { targets[i] = rnd.Next(1, 256); } var span = new Span<int>(a); var values = new ReadOnlySpan<int>(targets); int idx = span.LastIndexOfAny(values); Assert.Equal(-1, idx); } } [Fact] public static void TestNoMatchValuesLargerLastIndexOfAny_ManyByte() { var rnd = new Random(42); for (int length = 1; length < byte.MaxValue; length++) { var a = new int[length]; var targets = new int[length * 2]; for (int i = 0; i < targets.Length; i++) { targets[i] = rnd.Next(1, 256); } var span = new Span<int>(a); var values = new ReadOnlySpan<int>(targets); int idx = span.LastIndexOfAny(values); Assert.Equal(-1, idx); } } [Fact] public static void TestMultipleMatchLastIndexOfAny_ManyByte() { for (int length = 5; length < byte.MaxValue; length++) { var a = new int[length]; for (int i = 0; i < length; i++) { int val = i + 1; a[i] = val == 200 ? 201 : val; } a[length - 1] = 200; a[length - 2] = 200; a[length - 3] = 200; a[length - 4] = 200; a[length - 5] = 200; var span = new Span<int>(a); var values = new ReadOnlySpan<int>(new int[] { 200, 200, 200, 200, 200, 200, 200, 200, 200 }); int idx = span.LastIndexOfAny(values); Assert.Equal(length - 1, idx); } } [Fact] public static void MakeSureNoChecksGoOutOfRangeLastIndexOfAny_ManyByte() { for (int length = 1; length < byte.MaxValue; length++) { var a = new int[length + 2]; a[0] = 99; a[length + 1] = 98; var span = new Span<int>(a, 1, length - 1); var values = new ReadOnlySpan<int>(new int[] { 99, 98, 99, 98, 99, 98 }); int index = span.LastIndexOfAny(values); Assert.Equal(-1, index); } for (int length = 1; length < byte.MaxValue; length++) { var a = new int[length + 2]; a[0] = 99; a[length + 1] = 99; var span = new Span<int>(a, 1, length - 1); var values = new ReadOnlySpan<int>(new int[] { 99, 99, 99, 99, 99, 99 }); int index = span.LastIndexOfAny(values); Assert.Equal(-1, index); } } [Fact] public static void ZeroLengthLastIndexOfAny_String_TwoByte() { var sp = new Span<string>(Array.Empty<string>()); int idx = sp.LastIndexOfAny("0", "0"); Assert.Equal(-1, idx); } [Fact] public static void DefaultFilledLastIndexOfAny_String_TwoByte() { var rnd = new Random(42); for (int length = 0; length < byte.MaxValue; length++) { var a = new string[length]; var span = new Span<string>(a); span.Fill(""); string[] targets = { "", "99" }; for (int i = 0; i < length; i++) { int index = rnd.Next(0, 2) == 0 ? 0 : 1; string target0 = targets[index]; string target1 = targets[(index + 1) % 2]; int idx = span.LastIndexOfAny(target0, target1); Assert.Equal(span.Length - 1, idx); } } } [Fact] public static void TestMatchLastIndexOfAny_String_TwoByte() { for (int length = 0; length < byte.MaxValue; length++) { var a = new string[length]; for (int i = 0; i < length; i++) { a[i] = (i + 1).ToString(); } var span = new Span<string>(a); for (int targetIndex = 0; targetIndex < length; targetIndex++) { string target0 = a[targetIndex]; string target1 = "0"; int idx = span.LastIndexOfAny(target0, target1); Assert.Equal(targetIndex, idx); } for (int targetIndex = 0; targetIndex < length - 1; targetIndex++) { string target0 = a[targetIndex]; string target1 = a[targetIndex + 1]; int idx = span.LastIndexOfAny(target0, target1); Assert.Equal(targetIndex + 1, idx); } for (int targetIndex = 0; targetIndex < length - 1; targetIndex++) { string target0 = "0"; string target1 = a[targetIndex + 1]; int idx = span.LastIndexOfAny(target0, target1); Assert.Equal(targetIndex + 1, idx); } } } [Fact] public static void TestNoMatchLastIndexOfAny_String_TwoByte() { var rnd = new Random(42); for (int length = 0; length < byte.MaxValue; length++) { var a = new string[length]; string target0 = rnd.Next(1, 256).ToString(); string target1 = rnd.Next(1, 256).ToString(); var span = new Span<string>(a); int idx = span.LastIndexOfAny(target0, target1); Assert.Equal(-1, idx); } } [Fact] public static void TestMultipleMatchLastIndexOfAny_String_TwoByte() { for (int length = 3; length < byte.MaxValue; length++) { var a = new string[length]; for (int i = 0; i < length; i++) { string val = (i + 1).ToString(); a[i] = val == "200" ? "201" : val; } a[length - 1] = "200"; a[length - 2] = "200"; a[length - 3] = "200"; var span = new Span<string>(a); int idx = span.LastIndexOfAny("200", "200"); Assert.Equal(length - 1, idx); } } [Fact] public static void MakeSureNoChecksGoOutOfRangeLastIndexOfAny_String_TwoByte() { for (int length = 1; length < byte.MaxValue; length++) { var a = new string[length + 2]; a[0] = "99"; a[length + 1] = "98"; var span = new Span<string>(a, 1, length - 1); int index = span.LastIndexOfAny("99", "98"); Assert.Equal(-1, index); } for (int length = 1; length < byte.MaxValue; length++) { var a = new string[length + 2]; a[0] = "99"; a[length + 1] = "99"; var span = new Span<string>(a, 1, length - 1); int index = span.LastIndexOfAny("99", "99"); Assert.Equal(-1, index); } } [Fact] public static void ZeroLengthIndexOf_String_ThreeByte() { var sp = new Span<string>(Array.Empty<string>()); int idx = sp.LastIndexOfAny("0", "0", "0"); Assert.Equal(-1, idx); } [Fact] public static void DefaultFilledLastIndexOfAny_String_ThreeByte() { var rnd = new Random(42); for (int length = 0; length < byte.MaxValue; length++) { var a = new string[length]; var span = new Span<string>(a); span.Fill(""); string[] targets = { "", "99", "98" }; for (int i = 0; i < length; i++) { int index = rnd.Next(0, 3); string target0 = targets[index]; string target1 = targets[(index + 1) % 2]; string target2 = targets[(index + 1) % 3]; int idx = span.LastIndexOfAny(target0, target1, target2); Assert.Equal(span.Length - 1, idx); } } } [Fact] public static void TestMatchLastIndexOfAny_String_ThreeByte() { for (int length = 0; length < byte.MaxValue; length++) { var a = new string[length]; for (int i = 0; i < length; i++) { a[i] = (i + 1).ToString(); } var span = new Span<string>(a); for (int targetIndex = 0; targetIndex < length; targetIndex++) { string target0 = a[targetIndex]; string target1 = "0"; string target2 = "0"; int idx = span.LastIndexOfAny(target0, target1, target2); Assert.Equal(targetIndex, idx); } for (int targetIndex = 0; targetIndex < length - 2; targetIndex++) { string target0 = a[targetIndex]; string target1 = a[targetIndex + 1]; string target2 = a[targetIndex + 2]; int idx = span.LastIndexOfAny(target0, target1, target2); Assert.Equal(targetIndex + 2, idx); } for (int targetIndex = 0; targetIndex < length - 2; targetIndex++) { string target0 = "0"; string target1 = "0"; string target2 = a[targetIndex + 2]; int idx = span.LastIndexOfAny(target0, target1, target2); Assert.Equal(targetIndex + 2, idx); } } } [Fact] public static void TestNoMatchLastIndexOfAny_String_ThreeByte() { var rnd = new Random(42); for (int length = 0; length < byte.MaxValue; length++) { var a = new string[length]; string target0 = rnd.Next(1, 256).ToString(); string target1 = rnd.Next(1, 256).ToString(); string target2 = rnd.Next(1, 256).ToString(); var span = new Span<string>(a); int idx = span.LastIndexOfAny(target0, target1, target2); Assert.Equal(-1, idx); } } [Fact] public static void TestMultipleMatchLastIndexOfAny_String_ThreeByte() { for (int length = 4; length < byte.MaxValue; length++) { var a = new string[length]; for (int i = 0; i < length; i++) { string val = (i + 1).ToString(); a[i] = val == "200" ? "201" : val; } a[length - 1] = "200"; a[length - 2] = "200"; a[length - 3] = "200"; a[length - 4] = "200"; var span = new Span<string>(a); int idx = span.LastIndexOfAny("200", "200", "200"); Assert.Equal(length - 1, idx); } } [Fact] public static void MakeSureNoChecksGoOutOfRangeLastIndexOfAny_String_ThreeByte() { for (int length = 1; length < byte.MaxValue; length++) { var a = new string[length + 2]; a[0] = "99"; a[length + 1] = "98"; var span = new Span<string>(a, 1, length - 1); int index = span.LastIndexOfAny("99", "98", "99"); Assert.Equal(-1, index); } for (int length = 1; length < byte.MaxValue; length++) { var a = new string[length + 2]; a[0] = "99"; a[length + 1] = "99"; var span = new Span<string>(a, 1, length - 1); int index = span.LastIndexOfAny("99", "99", "99"); Assert.Equal(-1, index); } } [Fact] public static void ZeroLengthLastIndexOfAny_String_ManyByte() { var sp = new Span<string>(Array.Empty<string>()); var values = new ReadOnlySpan<string>(new string[] { "0", "0", "0", "0" }); int idx = sp.LastIndexOfAny(values); Assert.Equal(-1, idx); values = new ReadOnlySpan<string>(new string[] { }); idx = sp.LastIndexOfAny(values); Assert.Equal(0, idx); } [Fact] public static void DefaultFilledLastIndexOfAny_String_ManyByte() { for (int length = 0; length < byte.MaxValue; length++) { var a = new string[length]; var span = new Span<string>(a); span.Fill(""); var values = new ReadOnlySpan<string>(new string[] { "", "99", "98", "0" }); for (int i = 0; i < length; i++) { int idx = span.LastIndexOfAny(values); Assert.Equal(span.Length - 1, idx); } } } [Fact] public static void TestMatchLastIndexOfAny_String_ManyByte() { for (int length = 0; length < byte.MaxValue; length++) { var a = new string[length]; for (int i = 0; i < length; i++) { a[i] = (i + 1).ToString(); } var span = new Span<string>(a); for (int targetIndex = 0; targetIndex < length; targetIndex++) { var values = new ReadOnlySpan<string>(new string[] { a[targetIndex], "0", "0", "0" }); int idx = span.LastIndexOfAny(values); Assert.Equal(targetIndex, idx); } for (int targetIndex = 0; targetIndex < length - 3; targetIndex++) { var values = new ReadOnlySpan<string>(new string[] { a[targetIndex], a[targetIndex + 1], a[targetIndex + 2], a[targetIndex + 3] }); int idx = span.LastIndexOfAny(values); Assert.Equal(targetIndex + 3, idx); } for (int targetIndex = 0; targetIndex < length - 3; targetIndex++) { var values = new ReadOnlySpan<string>(new string[] { "0", "0", "0", a[targetIndex + 3] }); int idx = span.LastIndexOfAny(values); Assert.Equal(targetIndex + 3, idx); } } } [Fact] public static void TestMatchValuesLargerLastIndexOfAny_String_ManyByte() { var rnd = new Random(42); for (int length = 2; length < byte.MaxValue; length++) { var a = new string[length]; int expectedIndex = length / 2; for (int i = 0; i < length; i++) { if (i == expectedIndex) { a[i] = "val"; continue; } a[i] = "255"; } var span = new Span<string>(a); var targets = new string[length * 2]; for (int i = 0; i < targets.Length; i++) { if (i == length + 1) { targets[i] = "val"; continue; } targets[i] = rnd.Next(1, 255).ToString(); } var values = new ReadOnlySpan<string>(targets); int idx = span.LastIndexOfAny(values); Assert.Equal(expectedIndex, idx); } } [Fact] public static void TestNoMatchLastIndexOfAny_String_ManyByte() { var rnd = new Random(42); for (int length = 1; length < byte.MaxValue; length++) { var a = new string[length]; var targets = new string[length]; for (int i = 0; i < targets.Length; i++) { targets[i] = rnd.Next(1, 256).ToString(); } var span = new Span<string>(a); var values = new ReadOnlySpan<string>(targets); int idx = span.LastIndexOfAny(values); Assert.Equal(-1, idx); } } [Fact] public static void TestNoMatchValuesLargerLastIndexOfAny_String_ManyByte() { var rnd = new Random(42); for (int length = 1; length < byte.MaxValue; length++) { var a = new string[length]; var targets = new string[length * 2]; for (int i = 0; i < targets.Length; i++) { targets[i] = rnd.Next(1, 256).ToString(); } var span = new Span<string>(a); var values = new ReadOnlySpan<string>(targets); int idx = span.LastIndexOfAny(values); Assert.Equal(-1, idx); } } [Fact] public static void TestMultipleMatchLastIndexOfAny_String_ManyByte() { for (int length = 5; length < byte.MaxValue; length++) { var a = new string[length]; for (int i = 0; i < length; i++) { string val = (i + 1).ToString(); a[i] = val == "200" ? "201" : val; } a[length - 1] = "200"; a[length - 2] = "200"; a[length - 3] = "200"; a[length - 4] = "200"; a[length - 5] = "200"; var span = new Span<string>(a); var values = new ReadOnlySpan<string>(new string[] { "200", "200", "200", "200", "200", "200", "200", "200", "200" }); int idx = span.LastIndexOfAny(values); Assert.Equal(length - 1, idx); } } [Fact] public static void MakeSureNoChecksGoOutOfRangeLastIndexOfAny_String_ManyByte() { for (int length = 1; length < byte.MaxValue; length++) { var a = new string[length + 2]; a[0] = "99"; a[length + 1] = "98"; var span = new Span<string>(a, 1, length - 1); var values = new ReadOnlySpan<string>(new string[] { "99", "98", "99", "98", "99", "98" }); int index = span.LastIndexOfAny(values); Assert.Equal(-1, index); } for (int length = 1; length < byte.MaxValue; length++) { var a = new string[length + 2]; a[0] = "99"; a[length + 1] = "99"; var span = new Span<string>(a, 1, length - 1); var values = new ReadOnlySpan<string>(new string[] { "99", "99", "99", "99", "99", "99" }); int index = span.LastIndexOfAny(values); Assert.Equal(-1, index); } } } }
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. using System; using System.Collections.Generic; using System.Text; using System.Collections; using System.IO; using System.Reflection; using System.Resources; using System.Windows.Forms; using Microsoft.Build.Framework; using Microsoft.Win32; using Microsoft.Build.Utilities; using System.Collections.Specialized; using System.Diagnostics; namespace NaCl.Build.CPPTasks { public class NaClCompile : NaClToolTask { [Required] public string NaCLCompilerPath { get; set; } public int ProcessorNumber { get; set; } public bool MultiProcessorCompilation { get; set; } [Required] public string ConfigurationType { get; set; } [Obsolete] protected override StringDictionary EnvironmentOverride { get { string show = OutputCommandLine ? "1" : "0"; string cores = Convert.ToString(ProcessorNumber); return new StringDictionary() { {"NACL_GCC_CORES", cores}, {"NACL_GCC_SHOW_COMMANDS", show } }; } } public NaClCompile() : base(new ResourceManager("NaCl.Build.CPPTasks.Properties.Resources", Assembly.GetExecutingAssembly())) { this.EnvironmentVariables = new string[] { "CYGWIN=nodosfilewarning", "LC_CTYPE=C" }; } protected override void LogEventsFromTextOutput(string singleLine, MessageImportance messageImportance) { base.LogEventsFromTextOutput(GCCUtilities.ConvertGCCOutput(singleLine), messageImportance); } static string GetObjectFile(ITaskItem source) { string objectFilePath = Path.GetFullPath(source.GetMetadata("ObjectFileName")); // cl.exe will accept a folder name as the ObjectFileName in which case // the objectfile is created as <ObjectFileName>/<basename>.obj. Here // we mimic this behaviour. if ((File.GetAttributes(objectFilePath) & FileAttributes.Directory) != 0) { objectFilePath = Path.Combine(objectFilePath, Path.GetFileName(source.ItemSpec)); objectFilePath = Path.ChangeExtension(objectFilePath, ".obj"); } return objectFilePath; } protected override void OutputReadTLog(ITaskItem[] compiledSources, CanonicalTrackedOutputFiles outputs) { string trackerPath = Path.GetFullPath(TlogDirectory + ReadTLogFilenames[0]); //save tlog for sources not compiled during this execution TaskItem readTrackerItem = new TaskItem(trackerPath); CanonicalTrackedInputFiles files = new CanonicalTrackedInputFiles(new TaskItem[] { readTrackerItem }, Sources, outputs, false, false); files.RemoveEntriesForSource(compiledSources); files.SaveTlog(); //add tlog information for compiled sources using (StreamWriter writer = new StreamWriter(trackerPath, true, Encoding.Unicode)) { foreach (ITaskItem source in compiledSources) { string sourcePath = Path.GetFullPath(source.ItemSpec).ToUpperInvariant(); string objectFilePath = GetObjectFile(source); string depFilePath = Path.ChangeExtension(objectFilePath, ".d"); try { if (File.Exists(depFilePath) == false) { Log.LogMessage(MessageImportance.High, depFilePath + " not found"); } else { writer.WriteLine("^" + sourcePath); DependencyParser parser = new DependencyParser(depFilePath); foreach (string filename in parser.Dependencies) { //source itself not required if (filename == sourcePath) continue; if (File.Exists(filename) == false) { Log.LogMessage(MessageImportance.High, "File " + sourcePath + " is missing dependency " + filename); } string fname = filename.ToUpperInvariant(); fname = Path.GetFullPath(fname); writer.WriteLine(fname); } //remove d file try { File.Delete(depFilePath); } finally { } } } catch (Exception) { Log.LogError("Failed to update " + readTrackerItem + " for " + sourcePath); } } } } protected override CanonicalTrackedOutputFiles OutputWriteTLog(ITaskItem[] compiledSources) { string path = Path.Combine(TlogDirectory, WriteTLogFilename); TaskItem item = new TaskItem(path); CanonicalTrackedOutputFiles trackedFiles = new CanonicalTrackedOutputFiles(new TaskItem[] { item }); foreach (ITaskItem sourceItem in compiledSources) { //remove this entry associated with compiled source which is about to be recomputed trackedFiles.RemoveEntriesForSource(sourceItem); //add entry with updated information trackedFiles.AddComputedOutputForSourceRoot(Path.GetFullPath(sourceItem.ItemSpec).ToUpperInvariant(), Path.GetFullPath(GetObjectFile(sourceItem)).ToUpperInvariant()); } //output tlog trackedFiles.SaveTlog(); return trackedFiles; } protected override string TLogCommandForSource(ITaskItem source) { return GenerateCommandLineForSource(source) + " " + source.GetMetadata("FullPath").ToUpperInvariant(); } protected override void OutputCommandTLog(ITaskItem[] compiledSources) { IDictionary<string, string> commandLines = GenerateCommandLinesFromTlog(); // if (compiledSources != null) { foreach (ITaskItem source in compiledSources) { string rmSource = FileTracker.FormatRootingMarker(source); commandLines[rmSource] = TLogCommandForSource(source); } } //write tlog using (StreamWriter writer = new StreamWriter(this.TLogCommandFile.GetMetadata("FullPath"), false, Encoding.Unicode)) { foreach (KeyValuePair<string, string> p in commandLines) { string keyLine = "^" + p.Key; writer.WriteLine(keyLine); writer.WriteLine(p.Value); } } } protected string GenerateCommandLineForSource(ITaskItem sourceFile, bool fullOutputName=false) { StringBuilder commandLine = new StringBuilder(GCCUtilities.s_CommandLineLength); //build command line from components and add required switches string props = xamlParser.Parse(sourceFile, fullOutputName, null); commandLine.Append(props); commandLine.Append(" -c"); // Remove rtti items as they are not relevant in C compilation and will // produce warnings if (SourceIsC(sourceFile.ToString())) { commandLine.Replace("-fno-rtti", ""); commandLine.Replace("-frtti", ""); } if (ConfigurationType == "DynamicLibrary") { commandLine.Append(" -fPIC"); } return commandLine.ToString(); } private int Compile(string pathToTool) { if (Platform.Equals("pnacl", StringComparison.OrdinalIgnoreCase)) { if (!SDKUtilities.FindPython()) { Log.LogError("PNaCl compilation requires python in your executable path."); return -1; } // The SDK root is five levels up from the compiler binary. string sdkroot = Path.GetDirectoryName(Path.GetDirectoryName(pathToTool)); sdkroot = Path.GetDirectoryName(Path.GetDirectoryName(sdkroot)); if (!SDKUtilities.SupportsPNaCl(sdkroot)) { int revision; int version = SDKUtilities.GetSDKVersion(sdkroot, out revision); Log.LogError("The configured version of the NaCl SDK ({0} r{1}) is too old " + "for building PNaCl projects.\n" + "Please install at least 24 r{2} using the naclsdk command " + "line tool.", version, revision, SDKUtilities.MinPNaCLSDKVersion, SDKUtilities.MinPNaCLSDKRevision); return -1; } } // If multiprocess compilation is enabled (not the VS default) // and the number of processors to use is not 1, then use the // compiler_wrapper python script to run multiple instances of // gcc if (MultiProcessorCompilation && ProcessorNumber != 1) { if (!SDKUtilities.FindPython()) { Log.LogWarning("Multi-processor Compilation with NaCl requires that python " + "be available in the visual studio executable path.\n" + "Please disable Multi-processor Compilation in the project " + "properties or add python to the your executable path.\n" + "Falling back to serial compilation.\n"); } else { return CompileParallel(pathToTool); } } return CompileSerial(pathToTool); } private int CompileSerial(string pathToTool) { int returnCode = 0; foreach (ITaskItem sourceItem in CompileSourceList) { try { string commandLine = GenerateCommandLineForSource(sourceItem, true); commandLine += " " + GCCUtilities.ConvertPathWindowsToPosix(sourceItem.ToString()); if (OutputCommandLine) { string logMessage = pathToTool + " " + commandLine; Log.LogMessage(logMessage); } else { base.Log.LogMessage(Path.GetFileName(sourceItem.ToString())); } // compile returnCode = base.ExecuteTool(pathToTool, commandLine, string.Empty); } catch (Exception) { returnCode = base.ExitCode; } //abort if an error was encountered if (returnCode != 0) { return returnCode; } } return returnCode; } private int CompileParallel(string pathToTool) { int returnCode = 0; // Compute sources that can be compiled together. Dictionary<string, List<ITaskItem>> srcGroups = new Dictionary<string, List<ITaskItem>>(); foreach (ITaskItem sourceItem in CompileSourceList) { string commandLine = GenerateCommandLineForSource(sourceItem); if (srcGroups.ContainsKey(commandLine)) { srcGroups[commandLine].Add(sourceItem); } else { srcGroups.Add(commandLine, new List<ITaskItem> {sourceItem}); } } string pythonScript = Path.GetDirectoryName(Path.GetDirectoryName(PropertiesFile)); pythonScript = Path.Combine(pythonScript, "compiler_wrapper.py"); foreach (KeyValuePair<string, List<ITaskItem>> entry in srcGroups) { string commandLine = entry.Key; string cmd = "\"" + pathToTool + "\" " + commandLine + " --"; List<ITaskItem> sources = entry.Value; foreach (ITaskItem sourceItem in sources) { cmd += " "; cmd += GCCUtilities.ConvertPathWindowsToPosix(sourceItem.ToString()); } try { // compile this group of sources returnCode = base.ExecuteTool("python", cmd, "\"" + pythonScript + "\""); } catch (Exception e) { Log.LogMessage("compiler exception: {0}", e); returnCode = base.ExitCode; } //abort if an error was encountered if (returnCode != 0) break; } Log.LogMessage(MessageImportance.Low, "compiler returned: {0}", returnCode); return returnCode; } protected override int ExecuteTool(string pathToTool, string responseFileCommands, string commandLineCommands) { if (File.Exists(pathToTool) == false) { base.Log.LogMessageFromText("Unable to find NaCL compiler: " + pathToTool, MessageImportance.High); return -1; } int returnCode = -1; try { returnCode = Compile(pathToTool); } finally { } return returnCode; } protected override string GenerateResponseFileCommands() { return ""; } protected bool SourceIsC(string sourceFilename) { string fileExt = Path.GetExtension(sourceFilename.ToString()); if (fileExt == ".c") return true; else return false; } protected override string CommandTLogFilename { get { return BaseTool() + ".compile.command.1.tlog"; } } protected override string[] ReadTLogFilenames { get { return new string[] { BaseTool() + ".compile.read.1.tlog" }; } } protected override string WriteTLogFilename { get { return BaseTool() + ".compile.write.1.tlog"; } } protected override string ToolName { get { return NaCLCompilerPath; } } } }
// // ChangePhotoPathGui.cs // // Author: // Stephane Delcroix <sdelcroix*novell.com> // // Copyright (C) 2008 Novell, Inc. // Copyright (C) 2008 Stephane Delcroix // // 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. // // // ChangePhotoPath.IChangePhotoPathGui.cs: The Gui to change the photo path in photos.db // // Author: // Bengt Thuree (bengt@thuree.com) // // Copyright (C) 2007 // using System; using FSpot.Extensions; using FSpot.UI.Dialog; //using Gnome.Vfs; using Hyena; using Hyena.Widgets; namespace FSpot.Tools.ChangePhotoPath { public class Dump : Gtk.Dialog, ICommand, IChangePhotoPathGui { private string dialog_name = "ChangePhotoPath"; private GtkBeans.Builder builder; private Gtk.Dialog dialog; private ChangePathController contr; private ProgressDialog progress_dialog; private int progress_dialog_total = 0; #pragma warning disable 649 [GtkBeans.Builder.Object] Gtk.Entry old_common_uri; [GtkBeans.Builder.Object] Gtk.Label new_common_uri; #pragma warning restore 649 private bool LaunchController() { try { contr = new ChangePathController ( this ); } catch (Exception e) { Log.Exception(e); return false; } return true; } public void create_progress_dialog(string txt, int total) { progress_dialog = new ProgressDialog (txt, ProgressDialog.CancelButtonType.Stop, total, dialog); } public void LaunchDialog() { CreateDialog(); Dialog.Modal = false; Dialog.TransientFor = null; if (LaunchController() && contr.CanWeRun()) { DisplayDoNotStopFSpotMsg(); Dialog.ShowAll(); Dialog.Response += HandleResponse; } else { DisplayOrigBasePathNotFoundMsg(); Dialog.Destroy(); } } private void CreateDialog() { builder = new GtkBeans.Builder (null, "ChangePhotoPath.ui", null); builder.Autoconnect (this); } private Gtk.Dialog Dialog { get { if (dialog == null) dialog = new Gtk.Dialog (builder.GetRawObject (dialog_name)); return dialog; } } private void DisplayMsg(Gtk.MessageType MessageType, string msg) { HigMessageDialog.RunHigMessageDialog ( null, Gtk.DialogFlags.Modal | Gtk.DialogFlags.DestroyWithParent, MessageType, Gtk.ButtonsType.Ok, msg, null); } private void DisplayDoNotStopFSpotMsg() { DisplayMsg (Gtk.MessageType.Info, "It will take a long time for SqLite to update the database if you have many photos." + "\nWe recommend you to let F-Spot be running during the night to ensure everything is written to disk."+ "\nChanging path on 23000 photos took 2 hours until sqlite had updated all photos in the database."); } private void DisplayOrigBasePathNotFoundMsg() { DisplayMsg (Gtk.MessageType.Error, "Could not find an old base path. /YYYY/MM/DD need to start with /20, /19 or /18."); } private void DisplayCancelledMsg() { DisplayMsg (Gtk.MessageType.Warning, "Operation aborted. Database has not been modified."); } private void DisplaySamePathMsg() { DisplayMsg (Gtk.MessageType.Warning, "New and Old base path are the same."); } private void DisplayNoPhotosFoundMsg() { DisplayMsg (Gtk.MessageType.Warning, "Did not find any photos with the old base path."); } private void DisplayExecutionOkMsg() { DisplayMsg (Gtk.MessageType.Info, "Completed successfully. Please ensure you wait 1-2 hour before you exit f-spot. This to ensure the database cache is written to disk."); } private void DisplayExecutionNotOkMsg() { DisplayMsg (Gtk.MessageType.Error, "An error occurred. Reverted all changes to the database."); } private void HandleResponse (object sender, Gtk.ResponseArgs args) { bool destroy_dialog = false; ChangePhotoPath.ProcessResult tmp_res; if (args.ResponseId == Gtk.ResponseType.Ok) { tmp_res = contr.ChangePathOnPhotos (old_common_uri.Text, new_common_uri.Text); switch (tmp_res) { case ProcessResult.Ok : DisplayExecutionOkMsg(); destroy_dialog=true; break; case ProcessResult.Cancelled : DisplayCancelledMsg(); break; case ProcessResult.Error : DisplayExecutionNotOkMsg(); break; case ProcessResult.SamePath : DisplaySamePathMsg(); break; case ProcessResult.NoPhotosFound : DisplayNoPhotosFoundMsg(); break; case ProcessResult.Processing : Log.Debug ("processing"); break; } } else destroy_dialog = true; remove_progress_dialog(); if (destroy_dialog) Dialog.Destroy(); return; } public void DisplayDefaultPaths (string oldpath, string newpath) { old_common_uri.Text = oldpath; new_common_uri.Text = newpath; } public void remove_progress_dialog () { if (progress_dialog != null) { progress_dialog.Destroy(); progress_dialog = null; } } public void check_if_remove_progress_dialog (int total) { if (total != progress_dialog_total) remove_progress_dialog(); } public bool UpdateProgressBar (string hdr_txt, string txt, int total) { if (progress_dialog != null) check_if_remove_progress_dialog(total); if (progress_dialog == null) create_progress_dialog(hdr_txt, total); progress_dialog_total = total; return progress_dialog.Update (string.Format ("{0} ", txt)); } public void Run (object sender, EventArgs args) { try { LaunchDialog( ); } catch (Exception e) { Log.Exception(e); } } } }
//----------------------------------------------------------------------------- // Copyright (c) 2013 GarageGames, LLC // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. //----------------------------------------------------------------------------- $toyAllCategoryIndex = 1; $defaultToySelected = false; //----------------------------------------------------------------------------- function ToyCategorySelectList::onSelect(%this) { // Fetch the index. %index = %this.currentToyCategory; $defaultToySelected = false; ToyListArray.initialize(%index); ToyListScroller.computeSizes(); ToyListScroller.scrollToTop(); // Unload the active toy. unloadToy(); // Flag as the default toy selected. if ($defaultToySelected) { loadToy($defaultModuleID); } else { if ( ToyListArray.getCount() > 0 ) { %firstToyButton = ToyListArray.getObject(0); if (isObject(%firstToyButton)) %firstToyButton.performSelect(); } } if ($platform $= "Android") hideSplashScreen(); } //----------------------------------------------------------------------------- function ToyCategorySelectList::initialize(%this) { %this.toyCategories[$toyAllCategoryIndex] = "All"; %this.toyCategories[$toyAllCategoryIndex+1] = "Physics"; %this.toyCategories[$toyAllCategoryIndex+2] = "Features"; %this.toyCategories[$toyAllCategoryIndex+3] = "Stress Testing"; %this.toyCategories[$toyAllCategoryIndex+4] = "Fun and Games"; %this.toyCategories[$toyAllCategoryIndex+5] = "Custom"; %this.toyCategories[$toyAllCategoryIndex+6] = "Experiments"; %this.maxToyCategories = $toyAllCategoryIndex + 7; // Set the "All" category as the default. // NOTE: This is important to use so that the user-configurable default toy // can be selected at start-up. %this.currentToyCategory = $toyAllCategoryIndex; %this.setText("All"); %this.onSelect(); } //----------------------------------------------------------------------------- function ToyCategorySelectList::nextCategory(%this) { if (%this.currentToyCategory >= %this.maxToyCategories) return; %this.currentToyCategory++; %text = %this.toyCategories[%this.currentToyCategory]; %this.setText(%text); %this.onSelect(); } //----------------------------------------------------------------------------- function ToyCategorySelectList::previousCategory(%this) { if (%this.currentToyCategory <= $toyAllCategoryIndex) return; %this.currentToyCategory--; %text = %this.toyCategories[%this.currentToyCategory]; %this.setText(%text); %this.onSelect(); } //----------------------------------------------------------------------------- function initializeToolbox() { // Populate the stock colors. %colorCount = getStockColorCount(); for ( %i = 0; %i < %colorCount; %i++ ) { // Fetch stock color name. %colorName = getStockColorName(%i); // Add to the list. BackgroundColorSelectList.add( getStockColorName(%i), %i ); // Select the color if it's the default one. if ( %colorName $= $pref::Sandbox::defaultBackgroundColor ) BackgroundColorSelectList.setSelected( %i ); } BackgroundColorSelectList.sort(); ToyCategorySelectList.initialize(); // Is this on the desktop? if ( $platform $= "windows" || $platform $= "macos" ) { // Yes, so make the controls screen controls visible. ResolutionSelectLabel.Visible = true; ResolutionSelectList.Visible = true; FullscreenOptionLabel.Visible = true; FullscreenOptionButton.Visible = true; // Fetch the active resolution. %activeResolution = getRes(); %activeWidth = getWord(%activeResolution, 0); %activeHeight = getWord(%activeResolution, 1); %activeBpp = getWord(%activeResolution, 2); // Fetch the resolutions. %resolutionList = getResolutionList( $pref::Video::displayDevice ); %resolutionCount = getWordCount( %resolutionList ) / 3; %inputIndex = 0; %outputIndex = 0; for( %i = 0; %i < %resolutionCount; %i++ ) { // Fetch the resolution entry. %width = getWord( %resolutionList, %inputIndex ); %height = getWord( %resolutionList, %inputIndex+1 ); %bpp = getWord( %resolutionList, %inputIndex+2 ); %inputIndex += 3; // Skip the 16-bit ones. if ( %bpp == 16 ) continue; // Store the resolution. $sandboxResolutions[%outputIndex] = %width SPC %height SPC %bpp; // Add to the list. ResolutionSelectList.add( %width @ "x" @ %height SPC "(" @ %bpp @ ")", %outputIndex ); // Select the resolution if it's the default one. if ( %width == %activeWidth && %height == %activeHeight && %bpp == %activeBpp ) ResolutionSelectList.setSelected( %outputIndex ); %outputIndex++; } } // Configure the main overlay. SandboxWindow.add(MainOverlay); %horizPosition = getWord(SandboxWindow.Extent, 0) - getWord(MainOverlay.Extent, 0); %verticalPosition = getWord(SandboxWindow.Extent, 1) - getWord(MainOverlay.Extent, 1); MainOverlay.position = %horizPosition SPC %verticalPosition; } //----------------------------------------------------------------------------- function toggleToolbox(%make) { // Finish if being released. if ( !%make ) return; // Finish if the console is awake. if ( ConsoleDialog.isAwake() ) return; // Is the toolbox awake? if ( ToolboxDialog.isAwake() ) { // Yes, so deactivate it. if ( $enableDirectInput ) activateKeyboard(); Canvas.popDialog(ToolboxDialog); MainOverlay.setVisible(1); return; } // Activate it. if ( $enableDirectInput ) deactivateKeyboard(); MainOverlay.setVisible(0); Canvas.pushDialog(ToolboxDialog); } //----------------------------------------------------------------------------- function BackgroundColorSelectList::onSelect(%this) { // Fetch the index. $activeBackgroundColor = %this.getSelected(); // Finish if the sandbox scene is not available. if ( !isObject(SandboxScene) ) return; // Set the scene color. Canvas.BackgroundColor = getStockColorName($activeBackgroundColor); Canvas.UseBackgroundColor = true; } //----------------------------------------------------------------------------- function ResolutionSelectList::onSelect(%this) { // Finish if the sandbox scene is not available. if ( !isObject(SandboxScene) ) return; // Fetch the index. %index = %this.getSelected(); // Fetch resolution. %resolution = $sandboxResolutions[%index]; // Set the screen mode. setScreenMode( GetWord( %resolution , 0 ), GetWord( %resolution, 1 ), GetWord( %resolution, 2 ), $pref::Video::fullScreen ); } //----------------------------------------------------------------------------- function PauseSceneModeButton::onClick(%this) { // Sanity! if ( !isObject(SandboxScene) ) { error( "Cannot pause/unpause the Sandbox scene as it does not exist." ); return; } // Toggle the scene pause. SandboxScene.setScenePause( !SandboxScene.getScenePause() ); } //----------------------------------------------------------------------------- function ReloadToyOverlayButton::onClick(%this) { // Finish if no toy is loaded. if ( !isObject(Sandbox.ActiveToy) ) return; // Reset custom controls. resetCustomControls(); // Reload the toy. loadToy( Sandbox.ActiveToy ); } //----------------------------------------------------------------------------- function RestartToyOverlayButton::onClick(%this) { // Finish if no toy is loaded. if ( !isObject(Sandbox.ActiveToy) ) return; // Reset the toy. if ( Sandbox.ActiveToy.ScopeSet.isMethod("reset") ) Sandbox.ActiveToy.ScopeSet.reset(); } //----------------------------------------------------------------------------- function updateToolboxOptions() { // Finish if the sandbox scene is not available. if ( !isObject(SandboxScene) ) return; // Set the scene color. Canvas.BackgroundColor = getStockColorName($activeBackgroundColor); Canvas.UseBackgroundColor = true; // Set option. if ( $pref::Sandbox::metricsOption ) SandboxScene.setDebugOn( "metrics" ); else SandboxScene.setDebugOff( "metrics" ); // Set option. if ( $pref::Sandbox::fpsmetricsOption ) SandboxScene.setDebugOn( "fps" ); else SandboxScene.setDebugOff( "fps" ); // Set option. if ( $pref::Sandbox::controllersOption ) SandboxScene.setDebugOn( "controllers" ); else SandboxScene.setDebugOff( "controllers" ); // Set option. if ( $pref::Sandbox::jointsOption ) SandboxScene.setDebugOn( "joints" ); else SandboxScene.setDebugOff( "joints" ); // Set option. if ( $pref::Sandbox::wireframeOption ) SandboxScene.setDebugOn( "wireframe" ); else SandboxScene.setDebugOff( "wireframe" ); // Set option. if ( $pref::Sandbox::aabbOption ) SandboxScene.setDebugOn( "aabb" ); else SandboxScene.setDebugOff( "aabb" ); // Set option. if ( $pref::Sandbox::oobbOption ) SandboxScene.setDebugOn( "oobb" ); else SandboxScene.setDebugOff( "oobb" ); // Set option. if ( $pref::Sandbox::sleepOption ) SandboxScene.setDebugOn( "sleep" ); else SandboxScene.setDebugOff( "sleep" ); // Set option. if ( $pref::Sandbox::collisionOption ) SandboxScene.setDebugOn( "collision" ); else SandboxScene.setDebugOff( "collision" ); // Set option. if ( $pref::Sandbox::positionOption ) SandboxScene.setDebugOn( "position" ); else SandboxScene.setDebugOff( "position" ); // Set option. if ( $pref::Sandbox::sortOption ) SandboxScene.setDebugOn( "sort" ); else SandboxScene.setDebugOff( "sort" ); // Set the options check-boxe. MetricsOptionCheckBox.setStateOn( $pref::Sandbox::metricsOption ); FpsMetricsOptionCheckBox.setStateOn( $pref::Sandbox::fpsmetricsOption ); ControllersOptionCheckBox.setStateOn( $pref::Sandbox::controllersOption ); JointsOptionCheckBox.setStateOn( $pref::Sandbox::jointsOption ); WireframeOptionCheckBox.setStateOn( $pref::Sandbox::wireframeOption ); AABBOptionCheckBox.setStateOn( $pref::Sandbox::aabbOption ); OOBBOptionCheckBox.setStateOn( $pref::Sandbox::oobbOption ); SleepOptionCheckBox.setStateOn( $pref::Sandbox::sleepOption ); CollisionOptionCheckBox.setStateOn( $pref::Sandbox::collisionOption ); PositionOptionCheckBox.setStateOn( $pref::Sandbox::positionOption ); SortOptionCheckBox.setStateOn( $pref::Sandbox::sortOption ); BatchOptionCheckBox.setStateOn( SandboxScene.getBatchingEnabled() ); // Is this on the desktop? //if ( $platform $= "windows" || $platform $= "macos" ) if ( $platform !$= "iOS" && $platform !$= "Android" ) { // Set the fullscreen check-box. FullscreenOptionButton.setStateOn( $pref::Video::fullScreen ); // Set the full-screen mode appropriately. if ( isFullScreen() != $pref::Video::fullScreen ) toggleFullScreen(); } } //----------------------------------------------------------------------------- function setFullscreenOption( %flag ) { $pref::Video::fullScreen = %flag; updateToolboxOptions(); } //----------------------------------------------------------------------------- function setMetricsOption( %flag ) { $pref::Sandbox::metricsOption = %flag; updateToolboxOptions(); } //----------------------------------------------------------------------------- function setFPSMetricsOption( %flag ) { $pref::Sandbox::fpsmetricsOption = %flag; updateToolboxOptions(); } //----------------------------------------------------------------------------- function setMetricsOption( %flag ) { $pref::Sandbox::metricsOption = %flag; updateToolboxOptions(); } //----------------------------------------------------------------------------- function setControllersOption( %flag ) { $pref::Sandbox::controllersOption = %flag; updateToolboxOptions(); } //----------------------------------------------------------------------------- function setJointsOption( %flag ) { $pref::Sandbox::jointsOption = %flag; updateToolboxOptions(); } //----------------------------------------------------------------------------- function setWireframeOption( %flag ) { $pref::Sandbox::wireframeOption = %flag; updateToolboxOptions(); } //----------------------------------------------------------------------------- function setAABBOption( %flag ) { $pref::Sandbox::aabbOption = %flag; updateToolboxOptions(); } //----------------------------------------------------------------------------- function setOOBBOption( %flag ) { $pref::Sandbox::oobbOption = %flag; updateToolboxOptions(); } //----------------------------------------------------------------------------- function setSleepOption( %flag ) { $pref::Sandbox::sleepOption = %flag; updateToolboxOptions(); } //----------------------------------------------------------------------------- function setCollisionOption( %flag ) { $pref::Sandbox::collisionOption = %flag; updateToolboxOptions(); } //----------------------------------------------------------------------------- function setPositionOption( %flag ) { $pref::Sandbox::positionOption = %flag; updateToolboxOptions(); } //----------------------------------------------------------------------------- function setSortOption( %flag ) { $pref::Sandbox::sortOption = %flag; updateToolboxOptions(); } //----------------------------------------------------------------------------- function ToyListScroller::scrollToNext(%this) { %currentScroll = %this.getScrollPositionY(); %currentScroll += 85; %this.setScrollPosition(0, %currentScroll); } //----------------------------------------------------------------------------- function ToyListScroller::scrollToPrevious(%this) { %currentScroll = %this.getScrollPositionY(); %currentScroll -= 85; %this.setScrollPosition(0, %currentScroll); } //----------------------------------------------------------------------------- function ToyListArray::initialize(%this, %index) { %this.clear(); %currentExtent = %this.extent; %newExtent = getWord(%currentExtent, 0) SPC "20"; %this.Extent = %newExtent; // Fetch the toy count. %toyCount = SandboxToys.getCount(); // Populate toys in the selected category. for ( %toyIndex = 0; %toyIndex < %toyCount; %toyIndex++ ) { // Fetch the toy module. %moduleDefinition = SandboxToys.getObject( %toyIndex ); // Skip the toy module if the "all" category is not selected and if the toy is not in the selected category. if ( %index != $toyAllCategoryIndex && %moduleDefinition.ToyCategoryIndex != %index ) continue; // Fetch the module version. %versionId = %moduleDefinition.versionId; // Format module title so that version#1 doesn't show version but all other versions do. if ( %versionId == 1 ) %moduleTitle = %moduleDefinition.moduleId; else %moduleTitle = %moduleDefinition.moduleId SPC "(v" @ %moduleDefinition.versionId @ ")"; // Add the toy GUI list. %this.addToyButton(%moduleTitle, %moduleDefinition); // Select the toy if it's the default and we've not selected a toy yet. if (!$defaultToySelected && %moduleDefinition.moduleId $= $pref::Sandbox::defaultToyId && %moduleDefinition.versionId == $pref::Sandbox::defaultToyVersionId ) { $defaultToySelected = true; $defaultModuleID = %moduleDefinition.getId(); } } } //----------------------------------------------------------------------------- function ToyListArray::addToyButton(%this, %moduleTitle, %moduleDefintion) { %button = new GuiButtonCtrl() { canSaveDynamicFields = "0"; HorizSizing = "relative"; class = "ToySelectButton"; VertSizing = "relative"; isContainer = "0"; Profile = "BlueButtonProfile"; toolTipProfile = "GuiToolTipProfile"; toolTip = %moduleDefintion.Description; Position = "0 0"; Extent = "160 80"; Visible = "1"; toy = %moduleDefintion.getId(); isContainer = "0"; Active = "1"; text = %moduleTitle; groupNum = "-1"; buttonType = "PushButton"; useMouseEvents = "0"; }; %button.command = %button @ ".performSelect();"; %this.add(%button); } //----------------------------------------------------------------------------- function ToySelectButton::performSelect(%this) { // Finish if already selected. if ( %this.toy == Sandbox.ActiveToy ) return; // Load the selected toy. loadToy( %this.toy ); }
#region File Description //----------------------------------------------------------------------------- // AnimatedModelProcessor.cs // // Microsoft XNA Community Game Platform // Copyright (C) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- #endregion #region Using Statements using System; using System.Collections.Generic; using CustomModelAnimation; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Content.Pipeline; using Microsoft.Xna.Framework.Content.Pipeline.Graphics; using Microsoft.Xna.Framework.Content.Pipeline.Processors; #endregion namespace CustomModelAnimationPipeline { /// <summary> /// Custom processor extends the builtin framework ModelProcessor class, /// adding animation support. /// </summary> [ContentProcessor(DisplayName = "Animated Model Processor")] public class AnimatedModelProcessor : ModelProcessor { const int MaxBones = 59; /// <summary> /// The main Process method converts an intermediate format content pipeline /// NodeContent tree to a ModelConte nt object with embedded animation data. /// </summary> public override ModelContent Process(NodeContent input, ContentProcessorContext context) { ValidateMesh(input, context, null); List<int> boneHierarchy = new List<int>(); // Chain to the base ModelProcessor class so it can convert the model data. ModelContent model = base.Process(input, context); // Add each of the bones foreach (ModelBoneContent bone in model.Bones) { boneHierarchy.Add(model.Bones.IndexOf(bone.Parent as ModelBoneContent)); } // Animation clips inside the object (mesh) Dictionary<string, ModelAnimationClip> animationClips = new Dictionary<string, ModelAnimationClip>(); // Animation clips at the root of the object Dictionary<string, ModelAnimationClip> rootClips = new Dictionary<string, ModelAnimationClip>(); // Process the animations ProcessAnimations(input, model, animationClips, rootClips); // Store the data for the model model.Tag = new ModelData(animationClips, rootClips, null, null, boneHierarchy); return model; } /// <summary> /// Converts an intermediate format content pipeline AnimationContentDictionary /// object to our runtime AnimationClip format. /// </summary> static void ProcessAnimations( NodeContent input, ModelContent model, Dictionary<string, ModelAnimationClip> animationClips, Dictionary<string, ModelAnimationClip> rootClips) { // Build up a table mapping bone names to indices. Dictionary<string, int> boneMap = new Dictionary<string, int>(); for (int i = 0; i < model.Bones.Count; i++) { string boneName = model.Bones[i].Name; if (!string.IsNullOrEmpty(boneName)) boneMap.Add(boneName, i); } // Convert each animation in the root of the object foreach (KeyValuePair<string, AnimationContent> animation in input.Animations) { ModelAnimationClip processed = ProcessRootAnimation(animation.Value, model.Bones[0].Name); rootClips.Add(animation.Key, processed); } // Get the unique names of the animations on the mesh children List<string> animationNames = new List<string>(); AddAnimationNodes(animationNames, input); // Now create those animations foreach (string key in animationNames) { ModelAnimationClip processed = ProcessAnimation(key, boneMap, input, model); animationClips.Add(key, processed); } } static void AddAnimationNodes(List<string> animationNames, NodeContent node) { foreach (NodeContent childNode in node.Children) { // If this node doesn't have keyframes for this animation we should just skip it foreach (string key in childNode.Animations.Keys) { if (!animationNames.Contains(key)) animationNames.Add(key); } AddAnimationNodes(animationNames, childNode); } } /// <summary> /// Converts an intermediate format content pipeline AnimationContent /// object to our runtime AnimationClip format. /// </summary> public static ModelAnimationClip ProcessRootAnimation(AnimationContent animation, string name) { List<ModelKeyframe> keyframes = new List<ModelKeyframe>(); // The root animation is controlling the root of the bones AnimationChannel channel = animation.Channels[name]; // Add the transformations on the root of the model foreach (AnimationKeyframe keyframe in channel) { keyframes.Add(new ModelKeyframe(0, keyframe.Time, keyframe.Transform)); } // Sort the merged keyframes by time. keyframes.Sort(CompareKeyframeTimes); if (keyframes.Count == 0) throw new InvalidContentException("Animation has no keyframes."); if (animation.Duration <= TimeSpan.Zero) throw new InvalidContentException("Animation has a zero duration."); return new ModelAnimationClip(animation.Duration, keyframes); } /// <summary> /// Converts an intermediate format content pipeline AnimationContent /// object to our runtime AnimationClip format. /// </summary> static ModelAnimationClip ProcessAnimation( string animationName, Dictionary<string, int> boneMap, NodeContent input, ModelContent model) { List<ModelKeyframe> keyframes = new List<ModelKeyframe>(); TimeSpan duration = TimeSpan.Zero; AddTransformationNodes(animationName, boneMap, input, keyframes, ref duration); // Sort the merged keyframes by time. keyframes.Sort(CompareKeyframeTimes); if (keyframes.Count == 0) throw new InvalidContentException("Animation has no keyframes."); if (duration <= TimeSpan.Zero) throw new InvalidContentException("Animation has a zero duration."); return new ModelAnimationClip(duration, keyframes); } static void AddTransformationNodes( string animationName, Dictionary<string, int> boneMap, NodeContent input, List<ModelKeyframe> keyframes, ref TimeSpan duration) { // Add the transformation on each of the meshes foreach (NodeContent childNode in input.Children) { // If this node doesn't have keyframes for this animation we should just skip it if (childNode.Animations.ContainsKey(animationName)) { AnimationChannel childChannel = childNode.Animations[animationName].Channels[childNode.Name]; if (childNode.Animations[animationName].Duration != duration) { if (duration < childNode.Animations[animationName].Duration) duration = childNode.Animations[animationName].Duration; } int boneIndex; if (!boneMap.TryGetValue(childNode.Name, out boneIndex)) { throw new InvalidContentException(string.Format( "Found animation for bone '{0}', which is not part of the model.", childNode.Name)); } foreach (AnimationKeyframe keyframe in childChannel) { keyframes.Add(new ModelKeyframe(boneIndex, keyframe.Time, keyframe.Transform)); } } AddTransformationNodes(animationName, boneMap, childNode, keyframes, ref duration); } } /// <summary> /// Comparison function for sorting keyframes into ascending time order. /// </summary> static int CompareKeyframeTimes(ModelKeyframe a, ModelKeyframe b) { return a.Time.CompareTo(b.Time); } /// <summary> /// Makes sure this mesh contains the kind of data we know how to animate. /// </summary> static void ValidateMesh(NodeContent node, ContentProcessorContext context, string parentBoneName) { MeshContent mesh = node as MeshContent; if (mesh != null) { // Validate the mesh. if (parentBoneName != null) { context.Logger.LogWarning(null, null, "Mesh {0} is a child of bone {1}. AnimatedModelProcessor " + "does not correctly handle meshes that are children of bones.", mesh.Name, parentBoneName); } } else if (node is BoneContent) { // If this is a bone, remember that we are now looking inside it. parentBoneName = node.Name; } // Recurse (iterating over a copy of the child collection, // because validating children may delete some of them). foreach (NodeContent child in new List<NodeContent>(node.Children)) ValidateMesh(child, context, parentBoneName); } /// <summary> /// Bakes unwanted transforms into the model geometry, /// so everything ends up in the same coordinate system. /// </summary> static void FlattenTransforms(NodeContent node, BoneContent skeleton) { foreach (NodeContent child in node.Children) { // Don't process the skeleton, because that is special. if (child == skeleton) continue; // Bake the local transform into the actual geometry. MeshHelper.TransformScene(child, child.Transform); // Having baked it, we can now set the local // coordinate system back to identity. child.Transform = Matrix.Identity; // Recurse. FlattenTransforms(child, skeleton); } } } }
// ------------------------------------------------------------------------------ // 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 OnenoteSectionsCollectionRequest. /// </summary> public partial class OnenoteSectionsCollectionRequest : BaseRequest, IOnenoteSectionsCollectionRequest { /// <summary> /// Constructs a new OnenoteSectionsCollectionRequest. /// </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 OnenoteSectionsCollectionRequest( string requestUrl, IBaseClient client, IEnumerable<Option> options) : base(requestUrl, client, options) { } /// <summary> /// Adds the specified OnenoteSection to the collection via POST. /// </summary> /// <param name="onenoteSection">The OnenoteSection to add.</param> /// <returns>The created OnenoteSection.</returns> public System.Threading.Tasks.Task<OnenoteSection> AddAsync(OnenoteSection onenoteSection) { return this.AddAsync(onenoteSection, CancellationToken.None); } /// <summary> /// Adds the specified OnenoteSection to the collection via POST. /// </summary> /// <param name="onenoteSection">The OnenoteSection to add.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The created OnenoteSection.</returns> public System.Threading.Tasks.Task<OnenoteSection> AddAsync(OnenoteSection onenoteSection, CancellationToken cancellationToken) { this.ContentType = "application/json"; this.Method = "POST"; return this.SendAsync<OnenoteSection>(onenoteSection, cancellationToken); } /// <summary> /// Gets the collection page. /// </summary> /// <returns>The collection page.</returns> public System.Threading.Tasks.Task<IOnenoteSectionsCollectionPage> 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<IOnenoteSectionsCollectionPage> GetAsync(CancellationToken cancellationToken) { this.Method = "GET"; var response = await this.SendAsync<OnenoteSectionsCollectionResponse>(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 IOnenoteSectionsCollectionRequest 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 IOnenoteSectionsCollectionRequest Expand(Expression<Func<OnenoteSection, 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 IOnenoteSectionsCollectionRequest 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 IOnenoteSectionsCollectionRequest Select(Expression<Func<OnenoteSection, 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 IOnenoteSectionsCollectionRequest 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 IOnenoteSectionsCollectionRequest 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 IOnenoteSectionsCollectionRequest 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 IOnenoteSectionsCollectionRequest OrderBy(string value) { this.QueryOptions.Add(new QueryOption("$orderby", value)); return this; } } }
/* * 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. */ // Uncomment to make asset Get requests for existing // #define WAIT_ON_INPROGRESS_REQUESTS using System; using System.IO; using System.Collections.Generic; using System.Reflection; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Binary; using System.Threading; using System.Timers; using log4net; using Nini.Config; using Mono.Addins; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Framework.Console; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Services.Interfaces; [assembly: Addin("FlotsamAssetCache", "1.1")] [assembly: AddinDependency("OpenSim", "0.5")] namespace Flotsam.RegionModules.AssetCache { [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule")] public class FlotsamAssetCache : ISharedRegionModule, IImprovedAssetCache, IAssetService { private static readonly ILog m_log = LogManager.GetLogger( MethodBase.GetCurrentMethod().DeclaringType); private bool m_Enabled; private const string m_ModuleName = "FlotsamAssetCache"; private const string m_DefaultCacheDirectory = m_ModuleName; private string m_CacheDirectory = m_DefaultCacheDirectory; private readonly List<char> m_InvalidChars = new List<char>(); private int m_LogLevel = 0; private ulong m_HitRateDisplay = 1; // How often to display hit statistics, given in requests private static ulong m_Requests; private static ulong m_RequestsForInprogress; private static ulong m_DiskHits; private static ulong m_MemoryHits; private static double m_HitRateMemory; private static double m_HitRateFile; #if WAIT_ON_INPROGRESS_REQUESTS private Dictionary<string, ManualResetEvent> m_CurrentlyWriting = new Dictionary<string, ManualResetEvent>(); private int m_WaitOnInprogressTimeout = 3000; #else private List<string> m_CurrentlyWriting = new List<string>(); #endif private ExpiringCache<string, AssetBase> m_MemoryCache; private bool m_MemoryCacheEnabled = true; // Expiration is expressed in hours. private const double m_DefaultMemoryExpiration = 1.0; private const double m_DefaultFileExpiration = 48; private TimeSpan m_MemoryExpiration = TimeSpan.Zero; private TimeSpan m_FileExpiration = TimeSpan.Zero; private TimeSpan m_FileExpirationCleanupTimer = TimeSpan.Zero; private static int m_CacheDirectoryTiers = 1; private static int m_CacheDirectoryTierLen = 3; private static int m_CacheWarnAt = 30000; private System.Timers.Timer m_CacheCleanTimer; private IAssetService m_AssetService; private List<Scene> m_Scenes = new List<Scene>(); private bool m_DeepScanBeforePurge; public FlotsamAssetCache() { m_InvalidChars.AddRange(Path.GetInvalidPathChars()); m_InvalidChars.AddRange(Path.GetInvalidFileNameChars()); } public Type ReplaceableInterface { get { return null; } } public string Name { get { return m_ModuleName; } } public void Initialise(IConfigSource source) { IConfig moduleConfig = source.Configs["Modules"]; if (moduleConfig != null) { string name = moduleConfig.GetString("AssetCaching", String.Empty); if (name == Name) { m_MemoryCache = new ExpiringCache<string, AssetBase>(); m_Enabled = true; m_log.InfoFormat("[FLOTSAM ASSET CACHE]: {0} enabled", this.Name); IConfig assetConfig = source.Configs["AssetCache"]; if (assetConfig == null) { m_log.Warn("[FLOTSAM ASSET CACHE]: AssetCache missing from OpenSim.ini, using defaults."); m_log.InfoFormat("[FLOTSAM ASSET CACHE]: Cache Directory", m_DefaultCacheDirectory); return; } m_CacheDirectory = assetConfig.GetString("CacheDirectory", m_DefaultCacheDirectory); m_log.InfoFormat("[FLOTSAM ASSET CACHE]: Cache Directory", m_DefaultCacheDirectory); m_MemoryCacheEnabled = assetConfig.GetBoolean("MemoryCacheEnabled", false); m_MemoryExpiration = TimeSpan.FromHours(assetConfig.GetDouble("MemoryCacheTimeout", m_DefaultMemoryExpiration)); #if WAIT_ON_INPROGRESS_REQUESTS m_WaitOnInprogressTimeout = assetConfig.GetInt("WaitOnInprogressTimeout", 3000); #endif m_LogLevel = assetConfig.GetInt("LogLevel", 0); m_HitRateDisplay = (ulong)assetConfig.GetInt("HitRateDisplay", 1000); m_FileExpiration = TimeSpan.FromHours(assetConfig.GetDouble("FileCacheTimeout", m_DefaultFileExpiration)); m_FileExpirationCleanupTimer = TimeSpan.FromHours(assetConfig.GetDouble("FileCleanupTimer", m_DefaultFileExpiration)); if ((m_FileExpiration > TimeSpan.Zero) && (m_FileExpirationCleanupTimer > TimeSpan.Zero)) { m_CacheCleanTimer = new System.Timers.Timer(m_FileExpirationCleanupTimer.TotalMilliseconds); m_CacheCleanTimer.AutoReset = true; m_CacheCleanTimer.Elapsed += CleanupExpiredFiles; lock (m_CacheCleanTimer) m_CacheCleanTimer.Start(); } m_CacheDirectoryTiers = assetConfig.GetInt("CacheDirectoryTiers", 1); if (m_CacheDirectoryTiers < 1) { m_CacheDirectoryTiers = 1; } else if (m_CacheDirectoryTiers > 3) { m_CacheDirectoryTiers = 3; } m_CacheDirectoryTierLen = assetConfig.GetInt("CacheDirectoryTierLength", 3); if (m_CacheDirectoryTierLen < 1) { m_CacheDirectoryTierLen = 1; } else if (m_CacheDirectoryTierLen > 4) { m_CacheDirectoryTierLen = 4; } m_CacheWarnAt = assetConfig.GetInt("CacheWarnAt", 30000); m_DeepScanBeforePurge = assetConfig.GetBoolean("DeepScanBeforePurge", false); MainConsole.Instance.Commands.AddCommand(this.Name, true, "fcache status", "fcache status", "Display cache status", HandleConsoleCommand); MainConsole.Instance.Commands.AddCommand(this.Name, true, "fcache clear", "fcache clear [file] [memory]", "Remove all assets in the file and/or memory cache", HandleConsoleCommand); MainConsole.Instance.Commands.AddCommand(this.Name, true, "fcache assets", "fcache assets", "Attempt a deep scan and cache of all assets in all scenes", HandleConsoleCommand); MainConsole.Instance.Commands.AddCommand(this.Name, true, "fcache expire", "fcache expire <datetime>", "Purge cached assets older then the specified date/time", HandleConsoleCommand); } } } public void PostInitialise() { } public void Close() { } public void AddRegion(Scene scene) { if (m_Enabled) { scene.RegisterModuleInterface<IImprovedAssetCache>(this); m_Scenes.Add(scene); if (m_AssetService == null) { m_AssetService = scene.RequestModuleInterface<IAssetService>(); } } } public void RemoveRegion(Scene scene) { if (m_Enabled) { scene.UnregisterModuleInterface<IImprovedAssetCache>(this); m_Scenes.Remove(scene); } } public void RegionLoaded(Scene scene) { } //////////////////////////////////////////////////////////// // IImprovedAssetCache // private void UpdateMemoryCache(string key, AssetBase asset) { if (m_MemoryCacheEnabled) { if (m_MemoryExpiration > TimeSpan.Zero) { m_MemoryCache.AddOrUpdate(key, asset, m_MemoryExpiration); } else { m_MemoryCache.AddOrUpdate(key, asset, Double.MaxValue); } } } public void Cache(AssetBase asset) { // TODO: Spawn this off to some seperate thread to do the actual writing if (asset != null) { UpdateMemoryCache(asset.ID, asset); string filename = GetFileName(asset.ID); try { // If the file is already cached, don't cache it, just touch it so access time is updated if (File.Exists(filename)) { File.SetLastAccessTime(filename, DateTime.Now); } else { // Once we start writing, make sure we flag that we're writing // that object to the cache so that we don't try to write the // same file multiple times. lock (m_CurrentlyWriting) { #if WAIT_ON_INPROGRESS_REQUESTS if (m_CurrentlyWriting.ContainsKey(filename)) { return; } else { m_CurrentlyWriting.Add(filename, new ManualResetEvent(false)); } #else if (m_CurrentlyWriting.Contains(filename)) { return; } else { m_CurrentlyWriting.Add(filename); } #endif } Util.FireAndForget( delegate { WriteFileCache(filename, asset); }); } } catch (Exception e) { LogException(e); } } } public AssetBase Get(string id) { m_Requests++; AssetBase asset = null; if (m_MemoryCacheEnabled && m_MemoryCache.TryGetValue(id, out asset)) { m_MemoryHits++; } else { string filename = GetFileName(id); if (File.Exists(filename)) { FileStream stream = null; try { stream = File.Open(filename, FileMode.Open, FileAccess.Read, FileShare.Read); BinaryFormatter bformatter = new BinaryFormatter(); asset = (AssetBase)bformatter.Deserialize(stream); UpdateMemoryCache(id, asset); m_DiskHits++; } catch (System.Runtime.Serialization.SerializationException e) { LogException(e); // If there was a problem deserializing the asset, the asset may // either be corrupted OR was serialized under an old format // {different version of AssetBase} -- we should attempt to // delete it and re-cache File.Delete(filename); } catch (Exception e) { LogException(e); } finally { if (stream != null) stream.Close(); } } #if WAIT_ON_INPROGRESS_REQUESTS // Check if we're already downloading this asset. If so, try to wait for it to // download. if (m_WaitOnInprogressTimeout > 0) { m_RequestsForInprogress++; ManualResetEvent waitEvent; if (m_CurrentlyWriting.TryGetValue(filename, out waitEvent)) { waitEvent.WaitOne(m_WaitOnInprogressTimeout); return Get(id); } } #else // Track how often we have the problem that an asset is requested while // it is still being downloaded by a previous request. if (m_CurrentlyWriting.Contains(filename)) { m_RequestsForInprogress++; } #endif } if (((m_LogLevel >= 1)) && (m_HitRateDisplay != 0) && (m_Requests % m_HitRateDisplay == 0)) { m_HitRateFile = (double)m_DiskHits / m_Requests * 100.0; m_log.InfoFormat("[FLOTSAM ASSET CACHE]: Cache Get :: {0} :: {1}", id, asset == null ? "Miss" : "Hit"); m_log.InfoFormat("[FLOTSAM ASSET CACHE]: File Hit Rate {0}% for {1} requests", m_HitRateFile.ToString("0.00"), m_Requests); if (m_MemoryCacheEnabled) { m_HitRateMemory = (double)m_MemoryHits / m_Requests * 100.0; m_log.InfoFormat("[FLOTSAM ASSET CACHE]: Memory Hit Rate {0}% for {1} requests", m_HitRateMemory.ToString("0.00"), m_Requests); } m_log.InfoFormat("[FLOTSAM ASSET CACHE]: {0} unnessesary requests due to requests for assets that are currently downloading.", m_RequestsForInprogress); } return asset; } public AssetBase GetCached(string id) { return Get(id); } public void Expire(string id) { if (m_LogLevel >= 2) m_log.DebugFormat("[FLOTSAM ASSET CACHE]: Expiring Asset {0}.", id); try { string filename = GetFileName(id); if (File.Exists(filename)) { File.Delete(filename); } if (m_MemoryCacheEnabled) m_MemoryCache.Remove(id); } catch (Exception e) { LogException(e); } } public void Clear() { if (m_LogLevel >= 2) m_log.Debug("[FLOTSAM ASSET CACHE]: Clearing Cache."); foreach (string dir in Directory.GetDirectories(m_CacheDirectory)) { Directory.Delete(dir); } if (m_MemoryCacheEnabled) m_MemoryCache.Clear(); } private void CleanupExpiredFiles(object source, ElapsedEventArgs e) { if (m_LogLevel >= 2) m_log.DebugFormat("[FLOTSAM ASSET CACHE]: Checking for expired files older then {0}.", m_FileExpiration.ToString()); // Purge all files last accessed prior to this point DateTime purgeLine = DateTime.Now - m_FileExpiration; // An optional deep scan at this point will ensure assets present in scenes, // or referenced by objects in the scene, but not recently accessed // are not purged. if (m_DeepScanBeforePurge) { CacheScenes(); } foreach (string dir in Directory.GetDirectories(m_CacheDirectory)) { CleanExpiredFiles(dir, purgeLine); } } /// <summary> /// Recurses through specified directory checking for asset files last /// accessed prior to the specified purge line and deletes them. Also /// removes empty tier directories. /// </summary> /// <param name="dir"></param> private void CleanExpiredFiles(string dir, DateTime purgeLine) { foreach (string file in Directory.GetFiles(dir)) { if (File.GetLastAccessTime(file) < purgeLine) { File.Delete(file); } } // Recurse into lower tiers foreach (string subdir in Directory.GetDirectories(dir)) { CleanExpiredFiles(subdir, purgeLine); } // Check if a tier directory is empty, if so, delete it int dirSize = Directory.GetFiles(dir).Length + Directory.GetDirectories(dir).Length; if (dirSize == 0) { Directory.Delete(dir); } else if (dirSize >= m_CacheWarnAt) { m_log.WarnFormat("[FLOTSAM ASSET CACHE]: Cache folder exceeded CacheWarnAt limit {0} {1}. Suggest increasing tiers, tier length, or reducing cache expiration", dir, dirSize); } } /// <summary> /// Determines the filename for an AssetID stored in the file cache /// </summary> /// <param name="id"></param> /// <returns></returns> private string GetFileName(string id) { // Would it be faster to just hash the darn thing? foreach (char c in m_InvalidChars) { id = id.Replace(c, '_'); } string path = m_CacheDirectory; for (int p = 1; p <= m_CacheDirectoryTiers; p++) { string pathPart = id.Substring((p - 1) * m_CacheDirectoryTierLen, m_CacheDirectoryTierLen); path = Path.Combine(path, pathPart); } return Path.Combine(path, id); } /// <summary> /// Writes a file to the file cache, creating any nessesary /// tier directories along the way /// </summary> /// <param name="filename"></param> /// <param name="asset"></param> private void WriteFileCache(string filename, AssetBase asset) { Stream stream = null; // Make sure the target cache directory exists string directory = Path.GetDirectoryName(filename); // Write file first to a temp name, so that it doesn't look // like it's already cached while it's still writing. string tempname = Path.Combine(directory, Path.GetRandomFileName()); try { if (!Directory.Exists(directory)) { Directory.CreateDirectory(directory); } stream = File.Open(tempname, FileMode.Create); BinaryFormatter bformatter = new BinaryFormatter(); bformatter.Serialize(stream, asset); stream.Close(); // Now that it's written, rename it so that it can be found. File.Move(tempname, filename); if (m_LogLevel >= 2) m_log.DebugFormat("[FLOTSAM ASSET CACHE]: Cache Stored :: {0}", asset.ID); } catch (Exception e) { LogException(e); } finally { if (stream != null) stream.Close(); // Even if the write fails with an exception, we need to make sure // that we release the lock on that file, otherwise it'll never get // cached lock (m_CurrentlyWriting) { #if WAIT_ON_INPROGRESS_REQUESTS ManualResetEvent waitEvent; if (m_CurrentlyWriting.TryGetValue(filename, out waitEvent)) { m_CurrentlyWriting.Remove(filename); waitEvent.Set(); } #else if (m_CurrentlyWriting.Contains(filename)) { m_CurrentlyWriting.Remove(filename); } #endif } } } private static void LogException(Exception e) { string[] text = e.ToString().Split(new char[] { '\n' }); foreach (string t in text) { m_log.ErrorFormat("[FLOTSAM ASSET CACHE]: {0} ", t); } } /// <summary> /// Scan through the file cache, and return number of assets currently cached. /// </summary> /// <param name="dir"></param> /// <returns></returns> private int GetFileCacheCount(string dir) { int count = Directory.GetFiles(dir).Length; foreach (string subdir in Directory.GetDirectories(dir)) { count += GetFileCacheCount(subdir); } return count; } /// <summary> /// This notes the last time the Region had a deep asset scan performed on it. /// </summary> /// <param name="RegionID"></param> private void StampRegionStatusFile(UUID RegionID) { string RegionCacheStatusFile = Path.Combine(m_CacheDirectory, "RegionStatus_" + RegionID.ToString() + ".fac"); if (File.Exists(RegionCacheStatusFile)) { File.SetLastWriteTime(RegionCacheStatusFile, DateTime.Now); } else { File.WriteAllText(RegionCacheStatusFile, "Please do not delete this file unless you are manually clearing your Flotsam Asset Cache."); } } /// <summary> /// Iterates through all Scenes, doing a deep scan through assets /// to cache all assets present in the scene or referenced by assets /// in the scene /// </summary> /// <returns></returns> private int CacheScenes() { UuidGatherer gatherer = new UuidGatherer(m_AssetService); Dictionary<UUID, AssetType> assets = new Dictionary<UUID, AssetType>(); foreach (Scene s in m_Scenes) { StampRegionStatusFile(s.RegionInfo.RegionID); s.ForEachSOG(delegate(SceneObjectGroup e) { gatherer.GatherAssetUuids(e, assets); } ); } foreach (UUID assetID in assets.Keys) { string filename = GetFileName(assetID.ToString()); if (File.Exists(filename)) { File.SetLastAccessTime(filename, DateTime.Now); } else { m_AssetService.Get(assetID.ToString()); } } return assets.Keys.Count; } /// <summary> /// Deletes all cache contents /// </summary> private void ClearFileCache() { foreach (string dir in Directory.GetDirectories(m_CacheDirectory)) { try { Directory.Delete(dir, true); } catch (Exception e) { LogException(e); } } foreach (string file in Directory.GetFiles(m_CacheDirectory)) { try { File.Delete(file); } catch (Exception e) { LogException(e); } } } #region Console Commands private void HandleConsoleCommand(string module, string[] cmdparams) { if (cmdparams.Length >= 2) { string cmd = cmdparams[1]; switch (cmd) { case "status": m_log.InfoFormat("[FLOTSAM ASSET CACHE] Memory Cache : {0} assets", m_MemoryCache.Count); int fileCount = GetFileCacheCount(m_CacheDirectory); m_log.InfoFormat("[FLOTSAM ASSET CACHE] File Cache : {0} assets", fileCount); foreach (string s in Directory.GetFiles(m_CacheDirectory, "*.fac")) { m_log.Info("[FLOTSAM ASSET CACHE] Deep Scans were performed on the following regions:"); string RegionID = s.Remove(0,s.IndexOf("_")).Replace(".fac",""); DateTime RegionDeepScanTMStamp = File.GetLastWriteTime(s); m_log.InfoFormat("[FLOTSAM ASSET CACHE] Region: {0}, {1}", RegionID, RegionDeepScanTMStamp.ToString("MM/dd/yyyy hh:mm:ss")); } break; case "clear": if (cmdparams.Length < 3) { m_log.Warn("[FLOTSAM ASSET CACHE] Please specify memory and/or file cache."); break; } foreach (string s in cmdparams) { if (s.ToLower() == "memory") { m_MemoryCache.Clear(); m_log.Info("[FLOTSAM ASSET CACHE] Memory cache cleared."); } else if (s.ToLower() == "file") { ClearFileCache(); m_log.Info("[FLOTSAM ASSET CACHE] File cache cleared."); } } break; case "assets": m_log.Info("[FLOTSAM ASSET CACHE] Caching all assets, in all scenes."); Util.FireAndForget(delegate { int assetsCached = CacheScenes(); m_log.InfoFormat("[FLOTSAM ASSET CACHE] Completed Scene Caching, {0} assets found.", assetsCached); }); break; case "expire": if (cmdparams.Length < 3) { m_log.InfoFormat("[FLOTSAM ASSET CACHE] Invalid parameters for Expire, please specify a valid date & time", cmd); break; } string s_expirationDate = ""; DateTime expirationDate; if (cmdparams.Length > 3) { s_expirationDate = string.Join(" ", cmdparams, 2, cmdparams.Length - 2); } else { s_expirationDate = cmdparams[2]; } if (!DateTime.TryParse(s_expirationDate, out expirationDate)) { m_log.InfoFormat("[FLOTSAM ASSET CACHE] {0} is not a valid date & time", cmd); break; } CleanExpiredFiles(m_CacheDirectory, expirationDate); break; default: m_log.InfoFormat("[FLOTSAM ASSET CACHE] Unknown command {0}", cmd); break; } } else if (cmdparams.Length == 1) { m_log.InfoFormat("[FLOTSAM ASSET CACHE] flotsamcache status - Display cache status"); m_log.InfoFormat("[FLOTSAM ASSET CACHE] flotsamcache clearmem - Remove all assets cached in memory"); m_log.InfoFormat("[FLOTSAM ASSET CACHE] flotsamcache clearfile - Remove all assets cached on disk"); m_log.InfoFormat("[FLOTSAM ASSET CACHE] flotsamcache cachescenes - Attempt a deep cache of all assets in all scenes"); m_log.InfoFormat("[FLOTSAM ASSET CACHE] flotsamcache <datetime> - Purge assets older then the specified date & time"); } } #endregion #region IAssetService Members public AssetMetadata GetMetadata(string id) { AssetBase asset = Get(id); return asset.Metadata; } public byte[] GetData(string id) { AssetBase asset = Get(id); return asset.Data; } public bool Get(string id, object sender, AssetRetrieved handler) { AssetBase asset = Get(id); handler(id, sender, asset); return true; } public string Store(AssetBase asset) { if (asset.FullID == UUID.Zero) { asset.FullID = UUID.Random(); } Cache(asset); return asset.ID; } public bool UpdateContent(string id, byte[] data) { AssetBase asset = Get(id); asset.Data = data; Cache(asset); return true; } public bool Delete(string id) { Expire(id); return true; } #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 Microsoft.Win32.SafeHandles; using System.Collections.Generic; using System.Net.Sockets; using System.Threading; namespace System.Net.NetworkInformation { public class NetworkChange { //introduced for supporting design-time loading of System.Windows.dll [Obsolete("This API supports the .NET Framework infrastructure and is not intended to be used directly from your code.", true)] public static void RegisterNetworkChange(NetworkChange nc) { } public static event NetworkAvailabilityChangedEventHandler NetworkAvailabilityChanged { add { AvailabilityChangeListener.Start(value); } remove { AvailabilityChangeListener.Stop(value); } } public static event NetworkAddressChangedEventHandler NetworkAddressChanged { add { AddressChangeListener.Start(value); } remove { AddressChangeListener.Stop(value); } } internal static bool CanListenForNetworkChanges { get { return true; } } internal static class AvailabilityChangeListener { private static readonly object s_syncObject = new object(); private static readonly Dictionary<NetworkAvailabilityChangedEventHandler, ExecutionContext> s_availabilityCallerArray = new Dictionary<NetworkAvailabilityChangedEventHandler, ExecutionContext>(); private static readonly NetworkAddressChangedEventHandler s_addressChange = ChangedAddress; private static volatile bool s_isAvailable = false; private static readonly ContextCallback s_RunHandlerCallback = new ContextCallback(RunHandlerCallback); private static void RunHandlerCallback(object state) { ((NetworkAvailabilityChangedEventHandler)state)(null, new NetworkAvailabilityEventArgs(s_isAvailable)); } private static void ChangedAddress(object sender, EventArgs eventArgs) { lock (s_syncObject) { bool isAvailableNow = SystemNetworkInterface.InternalGetIsNetworkAvailable(); if (isAvailableNow != s_isAvailable) { s_isAvailable = isAvailableNow; var s_copy = new Dictionary<NetworkAvailabilityChangedEventHandler, ExecutionContext>(s_availabilityCallerArray); foreach (var handler in s_copy.Keys) { ExecutionContext context = s_copy[handler]; if (context == null) { handler(null, new NetworkAvailabilityEventArgs(s_isAvailable)); } else { ExecutionContext.Run(context, s_RunHandlerCallback, handler); } } } } } internal static void Start(NetworkAvailabilityChangedEventHandler caller) { lock (s_syncObject) { if (s_availabilityCallerArray.Count == 0) { s_isAvailable = NetworkInterface.GetIsNetworkAvailable(); AddressChangeListener.UnsafeStart(s_addressChange); } if ((caller != null) && (!s_availabilityCallerArray.ContainsKey(caller))) { s_availabilityCallerArray.Add(caller, ExecutionContext.Capture()); } } } internal static void Stop(NetworkAvailabilityChangedEventHandler caller) { lock (s_syncObject) { s_availabilityCallerArray.Remove(caller); if (s_availabilityCallerArray.Count == 0) { AddressChangeListener.Stop(s_addressChange); } } } } // Helper class for detecting address change events. internal static unsafe class AddressChangeListener { private static readonly Dictionary<NetworkAddressChangedEventHandler, ExecutionContext> s_callerArray = new Dictionary<NetworkAddressChangedEventHandler, ExecutionContext>(); private static readonly ContextCallback s_runHandlerCallback = new ContextCallback(RunHandlerCallback); private static RegisteredWaitHandle s_registeredWait; // Need to keep the reference so it isn't GC'd before the native call executes. private static bool s_isListening = false; private static bool s_isPending = false; private static SafeCloseSocketAndEvent s_ipv4Socket = null; private static SafeCloseSocketAndEvent s_ipv6Socket = null; private static WaitHandle s_ipv4WaitHandle = null; private static WaitHandle s_ipv6WaitHandle = null; // Callback fired when an address change occurs. private static void AddressChangedCallback(object stateObject, bool signaled) { lock (s_callerArray) { // The listener was canceled, which would only happen if we aren't listening for more events. s_isPending = false; if (!s_isListening) { return; } s_isListening = false; // Need to copy the array so the callback can call start and stop var copy = new Dictionary<NetworkAddressChangedEventHandler, ExecutionContext>(s_callerArray); try { //wait for the next address change StartHelper(null, false, (StartIPOptions)stateObject); } catch (NetworkInformationException nie) { if (NetEventSource.IsEnabled) NetEventSource.Error(null, nie); } foreach (var handler in copy.Keys) { ExecutionContext context = copy[handler]; if (context == null) { handler(null, EventArgs.Empty); } else { ExecutionContext.Run(context, s_runHandlerCallback, handler); } } } } private static void RunHandlerCallback(object state) { ((NetworkAddressChangedEventHandler)state)(null, EventArgs.Empty); } internal static void Start(NetworkAddressChangedEventHandler caller) { StartHelper(caller, true, StartIPOptions.Both); } internal static void UnsafeStart(NetworkAddressChangedEventHandler caller) { StartHelper(caller, false, StartIPOptions.Both); } private static void StartHelper(NetworkAddressChangedEventHandler caller, bool captureContext, StartIPOptions startIPOptions) { lock (s_callerArray) { // Setup changedEvent and native overlapped struct. if (s_ipv4Socket == null) { int blocking; // Sockets will be initialized by the call to OSSupportsIP*. if (Socket.OSSupportsIPv4) { blocking = -1; s_ipv4Socket = SafeCloseSocketAndEvent.CreateWSASocketWithEvent(AddressFamily.InterNetwork, SocketType.Dgram, (ProtocolType)0, true, false); Interop.Winsock.ioctlsocket(s_ipv4Socket, Interop.Winsock.IoctlSocketConstants.FIONBIO, ref blocking); s_ipv4WaitHandle = s_ipv4Socket.GetEventHandle(); } if (Socket.OSSupportsIPv6) { blocking = -1; s_ipv6Socket = SafeCloseSocketAndEvent.CreateWSASocketWithEvent(AddressFamily.InterNetworkV6, SocketType.Dgram, (ProtocolType)0, true, false); Interop.Winsock.ioctlsocket(s_ipv6Socket, Interop.Winsock.IoctlSocketConstants.FIONBIO, ref blocking); s_ipv6WaitHandle = s_ipv6Socket.GetEventHandle(); } } if ((caller != null) && (!s_callerArray.ContainsKey(caller))) { s_callerArray.Add(caller, captureContext ? ExecutionContext.Capture() : null); } if (s_isListening || s_callerArray.Count == 0) { return; } if (!s_isPending) { int length; SocketError errorCode; if (Socket.OSSupportsIPv4 && (startIPOptions & StartIPOptions.StartIPv4) != 0) { s_registeredWait = ThreadPool.RegisterWaitForSingleObject( s_ipv4WaitHandle, new WaitOrTimerCallback(AddressChangedCallback), StartIPOptions.StartIPv4, -1, true); errorCode = Interop.Winsock.WSAIoctl_Blocking( s_ipv4Socket.DangerousGetHandle(), (int)IOControlCode.AddressListChange, null, 0, null, 0, out length, IntPtr.Zero, IntPtr.Zero); if (errorCode != SocketError.Success) { NetworkInformationException exception = new NetworkInformationException(); if (exception.ErrorCode != (uint)SocketError.WouldBlock) { throw exception; } } SafeWaitHandle s_ipv4SocketGetEventHandleSafeWaitHandle = s_ipv4Socket.GetEventHandle().GetSafeWaitHandle(); errorCode = Interop.Winsock.WSAEventSelect( s_ipv4Socket, s_ipv4SocketGetEventHandleSafeWaitHandle, Interop.Winsock.AsyncEventBits.FdAddressListChange); if (errorCode != SocketError.Success) { throw new NetworkInformationException(); } } if (Socket.OSSupportsIPv6 && (startIPOptions & StartIPOptions.StartIPv6) != 0) { s_registeredWait = ThreadPool.RegisterWaitForSingleObject( s_ipv6WaitHandle, new WaitOrTimerCallback(AddressChangedCallback), StartIPOptions.StartIPv6, -1, true); errorCode = Interop.Winsock.WSAIoctl_Blocking( s_ipv6Socket.DangerousGetHandle(), (int)IOControlCode.AddressListChange, null, 0, null, 0, out length, IntPtr.Zero, IntPtr.Zero); if (errorCode != SocketError.Success) { NetworkInformationException exception = new NetworkInformationException(); if (exception.ErrorCode != (uint)SocketError.WouldBlock) { throw exception; } } SafeWaitHandle s_ipv6SocketGetEventHandleSafeWaitHandle = s_ipv6Socket.GetEventHandle().GetSafeWaitHandle(); errorCode = Interop.Winsock.WSAEventSelect( s_ipv6Socket, s_ipv6SocketGetEventHandleSafeWaitHandle, Interop.Winsock.AsyncEventBits.FdAddressListChange); if (errorCode != SocketError.Success) { throw new NetworkInformationException(); } } } s_isListening = true; s_isPending = true; } } internal static void Stop(NetworkAddressChangedEventHandler caller) { lock (s_callerArray) { s_callerArray.Remove(caller); if (s_callerArray.Count == 0 && s_isListening) { s_isListening = false; } } } } } }
using System; using System.Collections.Generic; // ReSharper disable InconsistentNaming // ReSharper disable CheckNamespace // Copyright (c) 2006, 2008 Tony Garnock-Jones <tonyg@lshift.net> // Copyright (c) 2006, 2008 LShift Ltd. <query@lshift.net> // // 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. // // // // Migration to C# (3.0 / .Net 2.0 for Visual Studio 2008) from // Javascript, Copyright (c) 2012 Tao Klerks <tao@klerks.biz> // // This ported code is NOT cleaned up in terms of style, nor tested/optimized for // performance, nor even tested for correctness across all methods - it is an // extremely simplistic minimal-changes conversion/porting. The plan is to clean // it up to be more pleasant to look at an deal with at a later time. // To anyone who is familiar with and understands the original terminology of // diff and diff3 concepts, I apologize for my fanciful naming strategy - I has // to come up with object names and haven't yet had a chance to review the // literature. // Also added a "diff_merge_keepall()" implementation for simplistic 2-way merge. // namespace hw.Helper; public class UtilDiff { public enum Side { Conflict = -1 , Left = 0 , Old = 1 , Right = 2 } public class CandidateThing { public int file1index { get; set; } public int file2index { get; set; } public CandidateThing chain { get; set; } } public class commonOrDifferentThing { public List<string> common { get; set; } public List<string> file1 { get; set; } public List<string> file2 { get; set; } } public class patchDescriptionThing { public int Offset { get; set; } public int Length { get; set; } public List<string> Chunk { get; set; } internal patchDescriptionThing() { } internal patchDescriptionThing(string[] file, int offset, int length) { Offset = offset; Length = length; Chunk = new(file.SliceJS(offset, offset + length)); } } public class patchResult { public patchDescriptionThing file1 { get; set; } public patchDescriptionThing file2 { get; set; } } public class chunkReference { public int offset { get; set; } public int length { get; set; } } public class diffSet { public chunkReference file1 { get; set; } public chunkReference file2 { get; set; } } public class diff3Set : IComparable<diff3Set> { public Side side { get; set; } public int file1offset { get; set; } public int file1length { get; set; } public int file2offset { get; set; } public int file2length { get; set; } public int CompareTo(diff3Set other) { if(file1offset != other.file1offset) return file1offset.CompareTo(other.file1offset); return side.CompareTo(other.side); } } public class patch3Set { public Side side { get; set; } public int offset { get; set; } public int length { get; set; } public int conflictOldOffset { get; set; } public int conflictOldLength { get; set; } public int conflictRightOffset { get; set; } public int conflictRightLength { get; set; } } public interface IMergeResultBlock { // amusingly, I can't figure out anything they have in common. } public class MergeOKResultBlock : IMergeResultBlock { public string[] ContentLines { get; set; } } public class MergeConflictResultBlock : IMergeResultBlock { public string[] LeftLines { get; set; } public int LeftIndex { get; set; } public string[] OldLines { get; set; } public int OldIndex { get; set; } public string[] RightLines { get; set; } public int RightIndex { get; set; } } sealed class conflictRegion { public int file1RegionStart { get; set; } public int file1RegionEnd { get; set; } public int file2RegionStart { get; set; } public int file2RegionEnd { get; set; } } public static CandidateThing longest_common_subsequence(string[] file1, string[] file2) { /* Text diff algorithm following Hunt and McIlroy 1976. * J. W. Hunt and M. D. McIlroy, An algorithm for differential file * comparison, Bell Telephone Laboratories CSTR #41 (1976) * http://www.cs.dartmouth.edu/~doug/ * * Expects two arrays of strings. */ var equivalenceClasses = new Dictionary<string, List<int>>(); List<int> file2indices; var candidates = new Dictionary<int, CandidateThing>(); candidates.Add(0, new() { file1index = -1, file2index = -1, chain = null }); for(var j = 0; j < file2.Length; j++) { var line = file2[j]; if(equivalenceClasses.ContainsKey(line)) equivalenceClasses[line].Add(j); else equivalenceClasses.Add(line, new() { j }); } for(var i = 0; i < file1.Length; i++) { var line = file1[i]; //MATTHIEU ADDED NULL_CHECK FOR LINE if(line != null && equivalenceClasses.ContainsKey(line)) file2indices = equivalenceClasses[line]; else file2indices = new(); var r = 0; var s = 0; var c = candidates[0]; for(var jX = 0; jX < file2indices.Count; jX++) { var j = file2indices[jX]; for(s = r; s < candidates.Count; s++) if(candidates[s].file2index < j && (s == candidates.Count - 1 || candidates[s + 1].file2index > j)) break; if(s < candidates.Count) { var newCandidate = new CandidateThing { file1index = i, file2index = j, chain = candidates[s] }; candidates[r] = c; r = s + 1; c = newCandidate; if(r == candidates.Count) break; // no point in examining further (j)s } } candidates[r] = c; } // At this point, we know the LCS: it's in the reverse of the // linked-list through .chain of // candidates[candidates.length - 1]. return candidates[candidates.Count - 1]; } static void processCommon(ref commonOrDifferentThing common, List<commonOrDifferentThing> result) { //first condition added by Matthieu if(common.common != null && common.common.Count > 0) { common.common.Reverse(); result.Add(common); common = new(); } } public static List<commonOrDifferentThing> diff_comm(string[] file1, string[] file2) { // We apply the LCS to build a "comm"-style picture of the // differences between file1 and file2. var result = new List<commonOrDifferentThing>(); var tail1 = file1.Length; var tail2 = file2.Length; var common = new commonOrDifferentThing { common = new() }; for(var candidate = longest_common_subsequence(file1, file2); candidate != null; candidate = candidate.chain) { var different = new commonOrDifferentThing { file1 = new(), file2 = new() }; while(--tail1 > candidate.file1index) different.file1.Add(file1[tail1]); while(--tail2 > candidate.file2index) different.file2.Add(file2[tail2]); if(different.file1.Count > 0 || different.file2.Count > 0) { processCommon(ref common, result); different.file1.Reverse(); different.file2.Reverse(); result.Add(different); } if(tail1 >= 0) { //MATTHIEU added common.common if it doesn't exist already if(common.common == null) common.common = new(); common.common.Add(file1[tail1]); } } processCommon(ref common, result); result.Reverse(); return result; } public static List<patchResult> diff_patch(string[] file1, string[] file2) { // We apply the LCD to build a JSON representation of a // diff(1)-style patch. var result = new List<patchResult>(); var tail1 = file1.Length; var tail2 = file2.Length; for(var candidate = longest_common_subsequence(file1, file2); candidate != null; candidate = candidate.chain) { var mismatchLength1 = tail1 - candidate.file1index - 1; var mismatchLength2 = tail2 - candidate.file2index - 1; tail1 = candidate.file1index; tail2 = candidate.file2index; if(mismatchLength1 > 0 || mismatchLength2 > 0) { var thisResult = new patchResult { file1 = new(file1, candidate.file1index + 1, mismatchLength1) , file2 = new(file2, candidate.file2index + 1, mismatchLength2) }; result.Add(thisResult); } } result.Reverse(); return result; } public static List<patchResult> strip_patch(List<patchResult> patch) { // Takes the output of Diff.diff_patch(), and removes // information from it. It can still be used by patch(), // below, but can no longer be inverted. var newpatch = new List<patchResult>(); for(var i = 0; i < patch.Count; i++) { var chunk = patch[i]; newpatch.Add(new() { file1 = new() { Offset = chunk.file1.Offset, Length = chunk.file1.Length } , file2 = new() { Chunk = chunk.file1.Chunk } }); } return newpatch; } public static void invert_patch(List<patchResult> patch) { // Takes the output of Diff.diff_patch(), and inverts the // sense of it, so that it can be applied to file2 to give // file1 rather than the other way around. for(var i = 0; i < patch.Count; i++) { var chunk = patch[i]; var tmp = chunk.file1; chunk.file1 = chunk.file2; chunk.file2 = tmp; } } static void copyCommon(int targetOffset, ref int commonOffset, string[] file, List<string> result) { while(commonOffset < targetOffset) { result.Add(file[commonOffset]); commonOffset++; } } public static List<string> patch(string[] file, List<patchResult> patch) { // Applies a patch to a file. // // Given file1 and file2, Diff.patch(file1, Diff.diff_patch(file1, file2)) should give file2. var result = new List<string>(); var commonOffset = 0; for(var chunkIndex = 0; chunkIndex < patch.Count; chunkIndex++) { var chunk = patch[chunkIndex]; copyCommon(chunk.file1.Offset, ref commonOffset, file, result); for(var lineIndex = 0; lineIndex < chunk.file2.Chunk.Count; lineIndex++) result.Add(chunk.file2.Chunk[lineIndex]); commonOffset += chunk.file1.Length; } copyCommon(file.Length, ref commonOffset, file, result); return result; } public static List<string> diff_merge_keepall(string[] file1, string[] file2) { // Non-destructively merges two files. // // This is NOT a three-way merge - content will often be DUPLICATED by this process, eg // when starting from the same file some content was moved around on one of the copies. // // To handle typical "common ancestor" situations and avoid incorrect duplication of // content, use diff3_merge instead. // // This method's behaviour is similar to gnu diff's "if-then-else" (-D) format, but // without the if/then/else lines! // var result = new List<string>(); var file1CompletedToOffset = 0; var diffPatches = diff_patch(file1, file2); for(var chunkIndex = 0; chunkIndex < diffPatches.Count; chunkIndex++) { var chunk = diffPatches[chunkIndex]; if(chunk.file2.Length > 0) { //copy any not-yet-copied portion of file1 to the end of this patch entry result.AddRange(file1.SliceJS(file1CompletedToOffset, chunk.file1.Offset + chunk.file1.Length)); file1CompletedToOffset = chunk.file1.Offset + chunk.file1.Length; //copy the file2 portion of this patch entry result.AddRange(chunk.file2.Chunk); } } //copy any not-yet-copied portion of file1 to the end of the file result.AddRange(file1.SliceJS(file1CompletedToOffset, file1.Length)); return result; } public static List<diffSet> diff_indices(string[] file1, string[] file2) { // We apply the LCS to give a simple representation of the // offsets and lengths of mismatched chunks in the input // files. This is used by diff3_merge_indices below. var result = new List<diffSet>(); var tail1 = file1.Length; var tail2 = file2.Length; for(var candidate = longest_common_subsequence(file1, file2); candidate != null; candidate = candidate.chain) { var mismatchLength1 = tail1 - candidate.file1index - 1; var mismatchLength2 = tail2 - candidate.file2index - 1; tail1 = candidate.file1index; tail2 = candidate.file2index; if(mismatchLength1 > 0 || mismatchLength2 > 0) result.Add(new() { file1 = new() { offset = tail1 + 1, length = mismatchLength1 } , file2 = new() { offset = tail2 + 1, length = mismatchLength2 } }); } result.Reverse(); return result; } static void addHunk(diffSet h, Side side, List<diff3Set> hunks) => hunks.Add(new() { side = side, file1offset = h.file1.offset, file1length = h.file1.length, file2offset = h.file2.offset , file2length = h.file2.length }); static void copyCommon2(int targetOffset, ref int commonOffset, List<patch3Set> result) { if(targetOffset > commonOffset) result.Add(new() { side = Side.Old, offset = commonOffset, length = targetOffset - commonOffset }); } public static List<patch3Set> diff3_merge_indices(string[] a, string[] o, string[] b) { // Given three files, A, O, and B, where both A and B are // independently derived from O, returns a fairly complicated // internal representation of merge decisions it's taken. The // interested reader may wish to consult // // Sanjeev Khanna, Keshav Kunal, and Benjamin C. Pierce. "A // Formal Investigation of Diff3." In Arvind and Prasad, // editors, Foundations of Software Technology and Theoretical // Computer Science (FSTTCS), December 2007. // // (http://www.cis.upenn.edu/~bcpierce/papers/diff3-short.pdf) var m1 = diff_indices(o, a); var m2 = diff_indices(o, b); var hunks = new List<diff3Set>(); for(var i = 0; i < m1.Count; i++) addHunk(m1[i], Side.Left, hunks); for(var i = 0; i < m2.Count; i++) addHunk(m2[i], Side.Right, hunks); hunks.Sort(); var result = new List<patch3Set>(); var commonOffset = 0; for(var hunkIndex = 0; hunkIndex < hunks.Count; hunkIndex++) { var firstHunkIndex = hunkIndex; var hunk = hunks[hunkIndex]; var regionLhs = hunk.file1offset; var regionRhs = regionLhs + hunk.file1length; while(hunkIndex < hunks.Count - 1) { var maybeOverlapping = hunks[hunkIndex + 1]; var maybeLhs = maybeOverlapping.file1offset; if(maybeLhs > regionRhs) break; regionRhs = Math.Max(regionRhs, maybeLhs + maybeOverlapping.file1length); hunkIndex++; } copyCommon2(regionLhs, ref commonOffset, result); if(firstHunkIndex == hunkIndex) { // The "overlap" was only one hunk long, meaning that // there's no conflict here. Either a and o were the // same, or b and o were the same. if(hunk.file2length > 0) result.Add(new() { side = hunk.side, offset = hunk.file2offset, length = hunk.file2length }); } else { // A proper conflict. Determine the extents of the // regions involved from a, o and b. Effectively merge // all the hunks on the left into one giant hunk, and // do the same for the right; then, correct for skew // in the regions of o that each side changed, and // report appropriate spans for the three sides. var regions = new Dictionary<Side, conflictRegion> { { Side.Left, new conflictRegion { file1RegionStart = a.Length, file1RegionEnd = -1, file2RegionStart = o.Length , file2RegionEnd = -1 } } , { Side.Right, new conflictRegion { file1RegionStart = b.Length, file1RegionEnd = -1, file2RegionStart = o.Length , file2RegionEnd = -1 } } }; for(var i = firstHunkIndex; i <= hunkIndex; i++) { hunk = hunks[i]; var side = hunk.side; var r = regions[side]; var oLhs = hunk.file1offset; var oRhs = oLhs + hunk.file1length; var abLhs = hunk.file2offset; var abRhs = abLhs + hunk.file2length; r.file1RegionStart = Math.Min(abLhs, r.file1RegionStart); r.file1RegionEnd = Math.Max(abRhs, r.file1RegionEnd); r.file2RegionStart = Math.Min(oLhs, r.file2RegionStart); r.file2RegionEnd = Math.Max(oRhs, r.file2RegionEnd); } var aLhs = regions[Side.Left].file1RegionStart + (regionLhs - regions[Side.Left].file2RegionStart); var aRhs = regions[Side.Left].file1RegionEnd + (regionRhs - regions[Side.Left].file2RegionEnd); var bLhs = regions[Side.Right].file1RegionStart + (regionLhs - regions[Side.Right].file2RegionStart); var bRhs = regions[Side.Right].file1RegionEnd + (regionRhs - regions[Side.Right].file2RegionEnd); result.Add(new() { side = Side.Conflict, offset = aLhs, length = aRhs - aLhs, conflictOldOffset = regionLhs , conflictOldLength = regionRhs - regionLhs, conflictRightOffset = bLhs , conflictRightLength = bRhs - bLhs }); } commonOffset = regionRhs; } copyCommon2(o.Length, ref commonOffset, result); return result; } static void flushOk(List<string> okLines, List<IMergeResultBlock> result) { if(okLines.Count > 0) { var okResult = new MergeOKResultBlock(); okResult.ContentLines = okLines.ToArray(); result.Add(okResult); } okLines.Clear(); } static bool isTrueConflict(patch3Set rec, string[] a, string[] b) { if(rec.length != rec.conflictRightLength) return true; var aoff = rec.offset; var boff = rec.conflictRightOffset; for(var j = 0; j < rec.length; j++) if(a[j + aoff] != b[j + boff]) return true; return false; } public static List<IMergeResultBlock> diff3_merge(string[] a, string[] o, string[] b, bool excludeFalseConflicts) { // Applies the output of Diff.diff3_merge_indices to actually // construct the merged file; the returned result alternates // between "ok" and "conflict" blocks. var result = new List<IMergeResultBlock>(); var files = new Dictionary<Side, string[]> { { Side.Left, a }, { Side.Old, o }, { Side.Right, b } }; var indices = diff3_merge_indices(a, o, b); var okLines = new List<string>(); for(var i = 0; i < indices.Count; i++) { var x = indices[i]; var side = x.side; if(side == Side.Conflict) { if(excludeFalseConflicts && !isTrueConflict(x, a, b)) okLines.AddRange(files[0].SliceJS(x.offset, x.offset + x.length)); else { flushOk(okLines, result); result.Add(new MergeConflictResultBlock { LeftLines = a.SliceJS(x.offset, x.offset + x.length), LeftIndex = x.offset , OldLines = o.SliceJS(x.conflictOldOffset, x.conflictOldOffset + x.conflictOldLength) , OldIndex = x.conflictOldOffset , RightLines = b.SliceJS(x.conflictRightOffset, x.conflictRightOffset + x.conflictRightLength) , RightIndex = x.offset }); } } else okLines.AddRange(files[side].SliceJS(x.offset, x.offset + x.length)); } flushOk(okLines, result); return result; } } public static class ArrayExtension { public static T[] SliceJS<T>(this T[] array, int startingIndex, int followingIndex) { if(followingIndex > array.Length) followingIndex = array.Length; var outArray = new T[followingIndex - startingIndex]; for(var i = 0; i < outArray.Length; i++) outArray[i] = array[i + startingIndex]; return outArray; } }
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for Additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ namespace NPOI.SS.Formula.Functions { using System; using NPOI.SS.Formula; using NPOI.SS.Formula.Eval; using NPOI.SS.Util; using NPOI.Util; /** * This class performs a D* calculation. It takes an {@link IDStarAlgorithm} object and * uses it for calculating the result value. Iterating a database and Checking the * entries against the Set of conditions is done here. */ public class DStarRunner : Function3Arg { public enum DStarAlgorithmEnum { DGET, DMIN, // DMAX, // DMAX is not yet implemented } private DStarAlgorithmEnum algoType; public DStarRunner(DStarAlgorithmEnum algorithm) { this.algoType = algorithm; } public ValueEval Evaluate(ValueEval[] args, int srcRowIndex, int srcColumnIndex) { if (args.Length == 3) { return Evaluate(srcRowIndex, srcColumnIndex, args[0], args[1], args[2]); } else { return ErrorEval.VALUE_INVALID; } } public ValueEval Evaluate(int srcRowIndex, int srcColumnIndex, ValueEval database, ValueEval filterColumn, ValueEval conditionDatabase) { // Input Processing and error Checks. if (!(database is AreaEval) || !(conditionDatabase is AreaEval)) { return ErrorEval.VALUE_INVALID; } AreaEval db = (AreaEval)database; AreaEval cdb = (AreaEval)conditionDatabase; try { filterColumn = OperandResolver.GetSingleValue(filterColumn, srcRowIndex, srcColumnIndex); } catch (EvaluationException e) { return e.GetErrorEval(); } int fc; try { fc = GetColumnForName(filterColumn, db); } catch (EvaluationException) { return ErrorEval.VALUE_INVALID; } if (fc == -1) { // column not found return ErrorEval.VALUE_INVALID; } // Create an algorithm runner. IDStarAlgorithm algorithm = null; switch (algoType) { case DStarAlgorithmEnum.DGET: algorithm = new DGet(); break; case DStarAlgorithmEnum.DMIN: algorithm = new DMin(); break; default: throw new InvalidOperationException("Unexpected algorithm type " + algoType + " encountered."); } // Iterate over all db entries. int height = db.Height; for (int row = 1; row < height; ++row) { bool matches = true; try { matches = FullFillsConditions(db, row, cdb); } catch (EvaluationException) { return ErrorEval.VALUE_INVALID; } // Filter each entry. if (matches) { ValueEval currentValueEval = ResolveReference(db, row, fc); // Pass the match to the algorithm and conditionally abort the search. bool shouldContinue = algorithm.ProcessMatch(currentValueEval); if (!shouldContinue) { break; } } } // Return the result of the algorithm. return algorithm.Result; } private enum Operator { largerThan, largerEqualThan, smallerThan, smallerEqualThan, equal } /** * * * @param nameValueEval Must not be a RefEval or AreaEval. Thus make sure resolveReference() is called on the value first! * @param db * @return * @throws EvaluationException */ private static int GetColumnForName(ValueEval nameValueEval, AreaEval db) { String name = OperandResolver.CoerceValueToString(nameValueEval); return GetColumnForString(db, name); } /** * For a given database returns the column number for a column heading. * * @param db Database. * @param name Column heading. * @return Corresponding column number. * @If it's not possible to turn all headings into strings. */ private static int GetColumnForString(AreaEval db, String name) { int resultColumn = -1; int width = db.Width; for (int column = 0; column < width; ++column) { ValueEval columnNameValueEval = ResolveReference(db, 0, column); if (columnNameValueEval is BlankEval) { continue; } if (columnNameValueEval is ErrorEval) { continue; } String columnName = OperandResolver.CoerceValueToString(columnNameValueEval); if (name.Equals(columnName)) { resultColumn = column; break; } } return resultColumn; } /** * Checks a row in a database against a condition database. * * @param db Database. * @param row The row in the database to Check. * @param cdb The condition database to use for Checking. * @return Whether the row matches the conditions. * @If references could not be Resolved or comparison * operators and operands didn't match. */ private static bool FullFillsConditions(AreaEval db, int row, AreaEval cdb) { // Only one row must match to accept the input, so rows are ORed. // Each row is made up of cells where each cell is a condition, // all have to match, so they are ANDed. int height = cdb.Height; for (int conditionRow = 1; conditionRow < height; ++conditionRow) { bool matches = true; int width = cdb.Width; for (int column = 0; column < width; ++column) // columns are ANDed { // Whether the condition column matches a database column, if not it's a // special column that accepts formulas. bool columnCondition = true; ValueEval condition = null; // The condition to apply. condition = ResolveReference(cdb, conditionRow, column); // If the condition is empty it matches. if (condition is BlankEval) continue; // The column in the DB to apply the condition to. ValueEval targetHeader = ResolveReference(cdb, 0, column); if (!(targetHeader is StringValueEval)) { throw new EvaluationException(ErrorEval.VALUE_INVALID); } if (GetColumnForName(targetHeader, db) == -1) // No column found, it's again a special column that accepts formulas. columnCondition = false; if (columnCondition == true) { // normal column condition // Should not throw, Checked above. ValueEval value = ResolveReference(db, row, GetColumnForName(targetHeader, db)); if (!testNormalCondition(value, condition)) { matches = false; break; } } else { // It's a special formula condition. // TODO: Check whether the condition cell contains a formula and return #VALUE! if it doesn't. if (string.IsNullOrEmpty(OperandResolver.CoerceValueToString(condition))) { throw new EvaluationException(ErrorEval.VALUE_INVALID); } throw new NotImplementedException( "D* function with formula conditions"); } } if (matches == true) { return true; } } return false; } /** * Test a value against a simple (&lt; &gt; &lt;= &gt;= = starts-with) condition string. * * @param value The value to Check. * @param condition The condition to check for. * @return Whether the condition holds. * @If comparison operator and operands don't match. */ private static bool testNormalCondition(ValueEval value, ValueEval condition) { if (condition is StringEval) { String conditionString = ((StringEval)condition).StringValue; if (conditionString.StartsWith("<")) { // It's a </<= condition. String number = conditionString.Substring(1); if (number.StartsWith("=")) { number = number.Substring(1); return testNumericCondition(value, Operator.smallerEqualThan, number); } else { return testNumericCondition(value, Operator.smallerThan, number); } } else if (conditionString.StartsWith(">")) { // It's a >/>= condition. String number = conditionString.Substring(1); if (number.StartsWith("=")) { number = number.Substring(1); return testNumericCondition(value, Operator.largerEqualThan, number); } else { return testNumericCondition(value, Operator.largerThan, number); } } else if (conditionString.StartsWith("=")) { // It's a = condition. String stringOrNumber = conditionString.Substring(1); if (string.IsNullOrEmpty(stringOrNumber)) { return value is BlankEval; } // Distinguish between string and number. bool itsANumber = false; try { int.Parse(stringOrNumber); itsANumber = true; } catch (FormatException) { // It's not an int. try { Double.Parse(stringOrNumber); itsANumber = true; } catch (FormatException) { // It's a string. itsANumber = false; } } if (itsANumber) { return testNumericCondition(value, Operator.equal, stringOrNumber); } else { // It's a string. String valueString = value is BlankEval ? "" : OperandResolver.CoerceValueToString(value); return stringOrNumber.Equals(valueString); } } else { // It's a text starts-with condition. if (string.IsNullOrEmpty(conditionString)) { return value is StringEval; } else { String valueString = value is BlankEval ? "" : OperandResolver.CoerceValueToString(value); return valueString.StartsWith(conditionString); } } } else if (condition is NumericValueEval) { double conditionNumber = ((NumericValueEval)condition).NumberValue; Double? valueNumber = GetNumberFromValueEval(value); if (valueNumber == null) { return false; } return conditionNumber == valueNumber; } else if (condition is ErrorEval) { if (value is ErrorEval) { return ((ErrorEval)condition).ErrorCode == ((ErrorEval)value).ErrorCode; } else { return false; } } else { return false; } } /** * Test whether a value matches a numeric condition. * @param valueEval Value to Check. * @param op Comparator to use. * @param condition Value to check against. * @return whether the condition holds. * @If it's impossible to turn the condition into a number. */ private static bool testNumericCondition( ValueEval valueEval, Operator op, String condition) { // Construct double from ValueEval. if (!(valueEval is NumericValueEval)) return false; double value = ((NumericValueEval)valueEval).NumberValue; // Construct double from condition. double conditionValue = 0.0; try { int intValue = Int32.Parse(condition); conditionValue = intValue; } catch (FormatException) { // It's not an int. try { conditionValue = Double.Parse(condition); } catch (FormatException) { // It's not a double. throw new EvaluationException(ErrorEval.VALUE_INVALID); } } int result = NumberComparer.Compare(value, conditionValue); switch (op) { case Operator.largerThan: return result > 0; case Operator.largerEqualThan: return result >= 0; case Operator.smallerThan: return result < 0; case Operator.smallerEqualThan: return result <= 0; case Operator.equal: return result == 0; } return false; // Can not be reached. } private static Double? GetNumberFromValueEval(ValueEval value) { if (value is NumericValueEval) { return ((NumericValueEval)value).NumberValue; } else if (value is StringValueEval) { String stringValue = ((StringValueEval)value).StringValue; try { return Double.Parse(stringValue); } catch (FormatException) { return null; } } else { return null; } } /** * Resolve a ValueEval that's in an AreaEval. * * @param db AreaEval from which the cell to resolve is retrieved. * @param dbRow Relative row in the AreaEval. * @param dbCol Relative column in the AreaEval. * @return A ValueEval that is a NumberEval, StringEval, BoolEval, BlankEval or ErrorEval. */ private static ValueEval ResolveReference(AreaEval db, int dbRow, int dbCol) { try { return OperandResolver.GetSingleValue(db.GetValue(dbRow, dbCol), db.FirstRow + dbRow, db.FirstColumn + dbCol); } catch (EvaluationException e) { return e.GetErrorEval(); } } } }
// 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. #define DEBUG // The behavior of this contract library should be consistent regardless of build type. using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; using System.Reflection; using DeveloperExperience = Internal.DeveloperExperience.DeveloperExperience; #if FEATURE_RELIABILITY_CONTRACTS using System.Runtime.ConstrainedExecution; #endif #if FEATURE_UNTRUSTED_CALLERS using System.Security; using System.Security.Permissions; #endif namespace System.Diagnostics.Contracts { public static partial class Contract { #region Private Methods [ThreadStatic] private static bool t_assertingMustUseRewriter; /// <summary> /// This method is used internally to trigger a failure indicating to the "programmer" that he is using the interface incorrectly. /// It is NEVER used to indicate failure of actual contracts at runtime. /// </summary> #if FEATURE_UNTRUSTED_CALLERS [SecuritySafeCritical] #endif static partial void AssertMustUseRewriter(ContractFailureKind kind, String contractKind) { //TODO: Implement CodeContract failure mechanics including enabling CCIRewrite if (t_assertingMustUseRewriter) { System.Diagnostics.Debug.Assert(false, "Asserting that we must use the rewriter went reentrant. Didn't rewrite this System.Private.CoreLib?"); return; } t_assertingMustUseRewriter = true; //// For better diagnostics, report which assembly is at fault. Walk up stack and //// find the first non-mscorlib assembly. //Assembly thisAssembly = typeof(Contract).Assembly; // In case we refactor mscorlib, use Contract class instead of Object. //StackTrace stack = new StackTrace(); //Assembly probablyNotRewritten = null; //for (int i = 0; i < stack.FrameCount; i++) //{ // Assembly caller = stack.GetFrame(i).GetMethod().DeclaringType.Assembly; // if (caller != thisAssembly) // { // probablyNotRewritten = caller; // break; // } //} //if (probablyNotRewritten == null) // probablyNotRewritten = thisAssembly; //String simpleName = probablyNotRewritten.GetName().Name; String simpleName = "System.Private.CoreLib"; System.Runtime.CompilerServices.ContractHelper.TriggerFailure(kind, SR.Format(SR.MustUseCCRewrite, contractKind, simpleName), null, null, null); t_assertingMustUseRewriter = false; } #endregion Private Methods #region Failure Behavior /// <summary> /// Without contract rewriting, failing Assert/Assumes end up calling this method. /// Code going through the contract rewriter never calls this method. Instead, the rewriter produced failures call /// System.Runtime.CompilerServices.ContractHelper.RaiseContractFailedEvent, followed by /// System.Runtime.CompilerServices.ContractHelper.TriggerFailure. /// </summary> [SuppressMessage("Microsoft.Portability", "CA1903:UseOnlyApiFromTargetedFramework", MessageId = "System.Security.SecuritySafeCriticalAttribute")] [System.Diagnostics.DebuggerNonUserCode] #if FEATURE_RELIABILITY_CONTRACTS [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] #endif static partial void ReportFailure(ContractFailureKind failureKind, String userMessage, String conditionText, Exception innerException) { if (failureKind < ContractFailureKind.Precondition || failureKind > ContractFailureKind.Assume) throw new ArgumentException(SR.Format(SR.Arg_EnumIllegalVal, failureKind), "failureKind"); Contract.EndContractBlock(); // displayMessage == null means: yes we handled it. Otherwise it is the localized failure message String displayMessage = System.Runtime.CompilerServices.ContractHelper.RaiseContractFailedEvent(failureKind, userMessage, conditionText, innerException); if (displayMessage == null) return; System.Runtime.CompilerServices.ContractHelper.TriggerFailure(failureKind, displayMessage, userMessage, conditionText, innerException); } #if !FEATURE_CORECLR /// <summary> /// Allows a managed application environment such as an interactive interpreter (IronPython) /// to be notified of contract failures and /// potentially "handle" them, either by throwing a particular exception type, etc. If any of the /// event handlers sets the Cancel flag in the ContractFailedEventArgs, then the Contract class will /// not pop up an assert dialog box or trigger escalation policy. Hooking this event requires /// full trust, because it will inform you of bugs in the appdomain and because the event handler /// could allow you to continue execution. /// </summary> public static event EventHandler<ContractFailedEventArgs> ContractFailed { #if FEATURE_UNTRUSTED_CALLERS [SecurityCritical] #if FEATURE_LINK_DEMAND [SecurityPermission(SecurityAction.LinkDemand, Unrestricted = true)] #endif #endif add { System.Runtime.CompilerServices.ContractHelper.InternalContractFailed += value; } #if FEATURE_UNTRUSTED_CALLERS [SecurityCritical] #if FEATURE_LINK_DEMAND [SecurityPermission(SecurityAction.LinkDemand, Unrestricted = true)] #endif #endif remove { System.Runtime.CompilerServices.ContractHelper.InternalContractFailed -= value; } } #endif // !FEATURE_CORECLR #endregion FailureBehavior } #if !FEATURE_CORECLR // Not usable on Silverlight by end users due to security, and full trust users have not yet expressed an interest. public sealed class ContractFailedEventArgs : EventArgs { private ContractFailureKind _failureKind; private String _message; private String _condition; private Exception _originalException; private bool _handled; private bool _unwind; internal Exception thrownDuringHandler; #if FEATURE_RELIABILITY_CONTRACTS [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] #endif public ContractFailedEventArgs(ContractFailureKind failureKind, String message, String condition, Exception originalException) { Contract.Requires(originalException == null || failureKind == ContractFailureKind.PostconditionOnException); _failureKind = failureKind; _message = message; _condition = condition; _originalException = originalException; } public String Message { get { return _message; } } public String Condition { get { return _condition; } } public ContractFailureKind FailureKind { get { return _failureKind; } } public Exception OriginalException { get { return _originalException; } } // Whether the event handler "handles" this contract failure, or to fail via escalation policy. public bool Handled { get { return _handled; } } #if FEATURE_UNTRUSTED_CALLERS [SecurityCritical] #if FEATURE_LINK_DEMAND [SecurityPermission(SecurityAction.LinkDemand, Unrestricted = true)] #endif #endif public void SetHandled() { _handled = true; } public bool Unwind { get { return _unwind; } } #if FEATURE_UNTRUSTED_CALLERS [SecurityCritical] #if FEATURE_LINK_DEMAND [SecurityPermission(SecurityAction.LinkDemand, Unrestricted = true)] #endif #endif public void SetUnwind() { _unwind = true; } } #endif // !FEATURE_CORECLR #if FEATURE_SERIALIZATION [Serializable] #else [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1032:ImplementStandardExceptionConstructors")] #endif [SuppressMessage("Microsoft.Design", "CA1064:ExceptionsShouldBePublic")] internal sealed class ContractException : Exception { private readonly ContractFailureKind _Kind; private readonly string _UserMessage; private readonly string _Condition; [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public ContractFailureKind Kind { get { return _Kind; } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public string Failure { get { return this.Message; } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public string UserMessage { get { return _UserMessage; } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] public string Condition { get { return _Condition; } } // Called by COM Interop, if we see COR_E_CODECONTRACTFAILED as an HRESULT. private ContractException() { HResult = System.Runtime.CompilerServices.ContractHelper.COR_E_CODECONTRACTFAILED; } public ContractException(ContractFailureKind kind, string failure, string userMessage, string condition, Exception innerException) : base(failure, innerException) { HResult = System.Runtime.CompilerServices.ContractHelper.COR_E_CODECONTRACTFAILED; _Kind = kind; _UserMessage = userMessage; _Condition = condition; } #if FEATURE_SERIALIZATION private ContractException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context) { _Kind = (ContractFailureKind)info.GetInt32("Kind"); _UserMessage = info.GetString("UserMessage"); _Condition = info.GetString("Condition"); } #endif // FEATURE_SERIALIZATION #if FEATURE_UNTRUSTED_CALLERS && FEATURE_SERIALIZATION [SecurityCritical] #if FEATURE_LINK_DEMAND && FEATURE_SERIALIZATION [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.SerializationFormatter)] #endif // FEATURE_LINK_DEMAND #endif // FEATURE_UNTRUSTED_CALLERS #if FEATURE_SERIALIZATION public override void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { base.GetObjectData(info, context); info.AddValue("Kind", _Kind); info.AddValue("UserMessage", _UserMessage); info.AddValue("Condition", _Condition); } #endif } } namespace System.Runtime.CompilerServices { public static partial class ContractHelper { #region Private fields #if !FEATURE_CORECLR private static volatile EventHandler<ContractFailedEventArgs> s_contractFailedEvent; private static readonly Object s_lockObject = new Object(); #endif // !FEATURE_CORECLR internal const int COR_E_CODECONTRACTFAILED = unchecked((int)0x80131542); #endregion #if !FEATURE_CORECLR /// <summary> /// Allows a managed application environment such as an interactive interpreter (IronPython) or a /// web browser host (Jolt hosting Silverlight in IE) to be notified of contract failures and /// potentially "handle" them, either by throwing a particular exception type, etc. If any of the /// event handlers sets the Cancel flag in the ContractFailedEventArgs, then the Contract class will /// not pop up an assert dialog box or trigger escalation policy. Hooking this event requires /// full trust. /// </summary> internal static event EventHandler<ContractFailedEventArgs> InternalContractFailed { #if FEATURE_UNTRUSTED_CALLERS [SecurityCritical] #endif add { // Eagerly prepare each event handler _marked with a reliability contract_, to // attempt to reduce out of memory exceptions while reporting contract violations. // This only works if the new handler obeys the constraints placed on // constrained execution regions. Eagerly preparing non-reliable event handlers // would be a perf hit and wouldn't significantly improve reliability. // UE: Please mention reliable event handlers should also be marked with the // PrePrepareMethodAttribute to avoid CER eager preparation work when ngen'ed. //#if !FEATURE_CORECLR // System.Runtime.CompilerServices.RuntimeHelpers.PrepareContractedDelegate(value); //#endif lock (s_lockObject) { s_contractFailedEvent += value; } } #if FEATURE_UNTRUSTED_CALLERS [SecurityCritical] #endif remove { lock (s_lockObject) { s_contractFailedEvent -= value; } } } #endif // !FEATURE_CORECLR /// <summary> /// Rewriter will call this method on a contract failure to allow listeners to be notified. /// The method should not perform any failure (assert/throw) itself. /// This method has 3 functions: /// 1. Call any contract hooks (such as listeners to Contract failed events) /// 2. Determine if the listeneres deem the failure as handled (then resultFailureMessage should be set to null) /// 3. Produce a localized resultFailureMessage used in advertising the failure subsequently. /// </summary> /// <param name="resultFailureMessage">Should really be out (or the return value), but partial methods are not flexible enough. /// On exit: null if the event was handled and should not trigger a failure. /// Otherwise, returns the localized failure message</param> [SuppressMessage("Microsoft.Design", "CA1030:UseEventsWhereAppropriate")] [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] [System.Diagnostics.DebuggerNonUserCode] #if FEATURE_RELIABILITY_CONTRACTS [SecuritySafeCritical] #endif static partial void RaiseContractFailedEventImplementation(ContractFailureKind failureKind, String userMessage, String conditionText, Exception innerException, ref string resultFailureMessage) { if (failureKind < ContractFailureKind.Precondition || failureKind > ContractFailureKind.Assume) throw new ArgumentException(SR.Format(SR.Arg_EnumIllegalVal, failureKind), "failureKind"); Contract.EndContractBlock(); string returnValue; String displayMessage = "contract failed."; // Incomplete, but in case of OOM during resource lookup... #if !FEATURE_CORECLR ContractFailedEventArgs eventArgs = null; // In case of OOM. #endif // !FEATURE_CORECLR #if FEATURE_RELIABILITY_CONTRACTS System.Runtime.CompilerServices.RuntimeHelpers.PrepareConstrainedRegions(); #endif try { displayMessage = GetDisplayMessage(failureKind, userMessage, conditionText); #if !FEATURE_CORECLR if (s_contractFailedEvent != null) { eventArgs = new ContractFailedEventArgs(failureKind, displayMessage, conditionText, innerException); foreach (EventHandler<ContractFailedEventArgs> handler in s_contractFailedEvent.GetInvocationList()) { try { handler(null, eventArgs); } catch (Exception e) { eventArgs.thrownDuringHandler = e; eventArgs.SetUnwind(); } } if (eventArgs.Unwind) { //if (Environment.IsCLRHosted) // TriggerCodeContractEscalationPolicy(failureKind, displayMessage, conditionText, innerException); // unwind if (innerException == null) { innerException = eventArgs.thrownDuringHandler; } throw new ContractException(failureKind, displayMessage, userMessage, conditionText, innerException); } } #endif // !FEATURE_CORECLR } finally { #if !FEATURE_CORECLR if (eventArgs != null && eventArgs.Handled) { returnValue = null; // handled } else #endif // !FEATURE_CORECLR { returnValue = displayMessage; } } resultFailureMessage = returnValue; } /// <summary> /// Rewriter calls this method to get the default failure behavior. /// </summary> [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "conditionText")] [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "userMessage")] [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "kind")] [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "innerException")] [System.Diagnostics.DebuggerNonUserCode] #if FEATURE_UNTRUSTED_CALLERS && !FEATURE_CORECLR [SecuritySafeCritical] #endif static partial void TriggerFailureImplementation(ContractFailureKind kind, String displayMessage, String userMessage, String conditionText, Exception innerException) { // If we're here, our intent is to pop up a dialog box (if we can). For developers // interacting live with a debugger, this is a good experience. For Silverlight // hosted in Internet Explorer, the assert window is great. If we cannot // pop up a dialog box, throw an exception (consider a library compiled with // "Assert On Failure" but used in a process that can't pop up asserts, like an // NT Service). For the CLR hosted by server apps like SQL or Exchange, we should // trigger escalation policy. //#if !FEATURE_CORECLR // if (Environment.IsCLRHosted) // { // TriggerCodeContractEscalationPolicy(kind, displayMessage, conditionText, innerException); // // Hosts like SQL may choose to abort the thread, so we will not get here in all cases. // // But if the host's chosen action was to throw an exception, we should throw an exception // // here (which is easier to do in managed code with the right parameters). // throw new ContractException(kind, displayMessage, userMessage, conditionText, innerException); // } //#endif // !FEATURE_CORECLR //TODO: Implement CodeContract failure mechanics including enabling CCIRewrite String stackTrace = null; //@todo: Any reasonable way to get a stack trace here? bool userSelectedIgnore = DeveloperExperience.Default.OnContractFailure(stackTrace, kind, displayMessage, userMessage, conditionText, innerException); if (userSelectedIgnore) return; //if (!Environment.UserInteractive) { throw new ContractException(kind, displayMessage, userMessage, conditionText, innerException); //} //// May need to rethink Assert.Fail w/ TaskDialogIndirect as a model. Window title. Main instruction. Content. Expanded info. //// Optional info like string for collapsed text vs. expanded text. //String windowTitle = SR.Format(GetResourceNameForFailure(kind)); //const int numStackFramesToSkip = 2; // To make stack traces easier to read //System.Diagnostics.Debug.Assert(conditionText, displayMessage, windowTitle, COR_E_CODECONTRACTFAILED, StackTrace.TraceFormat.Normal, numStackFramesToSkip); // If we got here, the user selected Ignore. Continue. } private static String GetFailureMessage(ContractFailureKind failureKind, String conditionText) { bool hasConditionText = !String.IsNullOrEmpty(conditionText); switch (failureKind) { case ContractFailureKind.Assert: return hasConditionText ? SR.Format(SR.AssertionFailed_Cnd, conditionText) : SR.AssertionFailed; case ContractFailureKind.Assume: return hasConditionText ? SR.Format(SR.AssumptionFailed_Cnd, conditionText) : SR.AssumptionFailed; case ContractFailureKind.Precondition: return hasConditionText ? SR.Format(SR.PreconditionFailed_Cnd, conditionText) : SR.PreconditionFailed; case ContractFailureKind.Postcondition: return hasConditionText ? SR.Format(SR.PostconditionFailed_Cnd, conditionText) : SR.PostconditionFailed; case ContractFailureKind.Invariant: return hasConditionText ? SR.Format(SR.InvariantFailed_Cnd, conditionText) : SR.InvariantFailed; case ContractFailureKind.PostconditionOnException: return hasConditionText ? SR.Format(SR.PostconditionOnExceptionFailed_Cnd, conditionText) : SR.PostconditionOnExceptionFailed; default: Contract.Assume(false, "Unreachable code"); return SR.AssumptionFailed; } } #if FEATURE_RELIABILITY_CONTRACTS [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] #endif private static String GetDisplayMessage(ContractFailureKind failureKind, String userMessage, String conditionText) { // Well-formatted English messages will take one of four forms. A sentence ending in // either a period or a colon, the condition string, then the message tacked // on to the end with two spaces in front. // Note that both the conditionText and userMessage may be null. Also, // on Silverlight we may not be able to look up a friendly string for the // error message. Let's leverage Silverlight's default error message there. String failureMessage = GetFailureMessage(failureKind, conditionText); // Now add in the user message, if present. if (!String.IsNullOrEmpty(userMessage)) { return failureMessage + " " + userMessage; } else { return failureMessage; } } //#if !FEATURE_CORECLR // // Will trigger escalation policy, if hosted and the host requested us to do something (such as // // abort the thread or exit the process). Starting in Dev11, for hosted apps the default behavior // // is to throw an exception. // // Implementation notes: // // We implement our default behavior of throwing an exception by simply returning from our native // // method inside the runtime and falling through to throw an exception. // // We must call through this method before calling the method on the Environment class // // because our security team does not yet support SecuritySafeCritical on P/Invoke methods. // // Note this can be called in the context of throwing another exception (EnsuresOnThrow). //#if FEATURE_UNTRUSTED_CALLERS // [SecuritySafeCritical] //#endif //#if FEATURE_RELIABILITY_CONTRACTS // [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] //#endif // [DebuggerNonUserCode] // private static void TriggerCodeContractEscalationPolicy(ContractFailureKind failureKind, String message, String conditionText, Exception innerException) // { // String exceptionAsString = null; // if (innerException != null) // exceptionAsString = innerException.ToString(); // Environment.TriggerCodeContractFailure(failureKind, message, conditionText, exceptionAsString); // } //#endif // !FEATURE_CORECLR } } // namespace System.Runtime.CompilerServices
/* ==================================================================== Copyright 2002-2004 Apache Software Foundation Licensed Under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed Under the License is distributed on an "AS Is" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations Under the License. ==================================================================== */ namespace NPOI.HSSF.Record { using System; using System.Text; using System.IO; using System.Collections; using NPOI.SS.Util; using NPOI.SS.Formula; using NPOI.Util; using NPOI.SS.Formula.PTG; /** * Title: DATAVALIDATION Record (0x01BE)<p/> * Description: This record stores data validation Settings and a list of cell ranges * which contain these Settings. The data validation Settings of a sheet * are stored in a sequential list of DV records. This list Is followed by * DVAL record(s) * @author Dragos Buleandra (dragos.buleandra@trade2b.ro) * @version 2.0-pre */ internal class DVRecord : StandardRecord { private static UnicodeString NULL_TEXT_STRING = new UnicodeString("\0"); public const short sid = 0x01BE; /** Option flags */ private int _option_flags; /** Title of the prompt box */ private UnicodeString _promptTitle; /** Title of the error box */ private UnicodeString _errorTitle; /** Text of the prompt box */ private UnicodeString _promptText; /** Text of the error box */ private UnicodeString _errorText; /** Not used - Excel seems to always write 0x3FE0 */ private short _not_used_1 = 0x3FE0; /** Formula data for first condition (RPN token array without size field) */ private NPOI.SS.Formula.Formula _formula1; /** Not used - Excel seems to always write 0x0000 */ private short _not_used_2 = 0x0000; /** Formula data for second condition (RPN token array without size field) */ private NPOI.SS.Formula.Formula _formula2; /** Cell range address list with all affected ranges */ private CellRangeAddressList _regions; public static int STRING_PROMPT_TITLE = 0; public static int STRING_ERROR_TITLE = 1; public static int STRING_PROMPT_TEXT = 2; public static int STRING_ERROR_TEXT = 3; /** * Option flags field * @see org.apache.poi.hssf.util.HSSFDataValidation utility class */ private BitField opt_data_type = new BitField(0x0000000F); private BitField opt_error_style = new BitField(0x00000070); private BitField opt_string_list_formula = new BitField(0x00000080); private BitField opt_empty_cell_allowed = new BitField(0x00000100); private BitField opt_suppress_dropdown_arrow = new BitField(0x00000200); private BitField opt_show_prompt_on_cell_selected = new BitField(0x00040000); private BitField opt_show_error_on_invalid_value = new BitField(0x00080000); private BitField opt_condition_operator = new BitField(0x00F00000); public DVRecord() { } public DVRecord(int validationType, int operator1, int errorStyle, bool emptyCellAllowed, bool suppressDropDownArrow, bool isExplicitList, bool showPromptBox, String promptTitle, String promptText, bool showErrorBox, String errorTitle, String errorText, Ptg[] formula1, Ptg[] formula2, CellRangeAddressList regions) { int flags = 0; flags = opt_data_type.SetValue(flags, validationType); flags = opt_condition_operator.SetValue(flags, operator1); flags = opt_error_style.SetValue(flags, errorStyle); flags = opt_empty_cell_allowed.SetBoolean(flags, emptyCellAllowed); flags = opt_suppress_dropdown_arrow.SetBoolean(flags, suppressDropDownArrow); flags = opt_string_list_formula.SetBoolean(flags, isExplicitList); flags = opt_show_prompt_on_cell_selected.SetBoolean(flags, showPromptBox); flags = opt_show_error_on_invalid_value.SetBoolean(flags, showErrorBox); _option_flags = flags; _promptTitle = ResolveTitleText(promptTitle); _promptText = ResolveTitleText(promptText); _errorTitle = ResolveTitleText(errorTitle); _errorText = ResolveTitleText(errorText); _formula1 = NPOI.SS.Formula.Formula.Create(formula1); _formula2 = NPOI.SS.Formula.Formula.Create(formula2); _regions = regions; } /** * Constructs a DV record and Sets its fields appropriately. * * @param in the RecordInputstream to Read the record from */ public DVRecord(RecordInputStream in1) { _option_flags = in1.ReadInt(); _promptTitle = ReadUnicodeString(in1); _errorTitle = ReadUnicodeString(in1); _promptText = ReadUnicodeString(in1); _errorText = ReadUnicodeString(in1); int field_size_first_formula = in1.ReadUShort(); _not_used_1 = in1.ReadShort(); //read first formula data condition _formula1 = NPOI.SS.Formula.Formula.Read(field_size_first_formula, in1); int field_size_sec_formula = in1.ReadUShort(); _not_used_2 = in1.ReadShort(); //read sec formula data condition _formula2 = NPOI.SS.Formula.Formula.Read(field_size_sec_formula, in1); //read cell range address list with all affected ranges _regions = new CellRangeAddressList(in1); } /** * When entered via the UI, Excel translates empty string into "\0" * While it is possible to encode the title/text as empty string (Excel doesn't exactly crash), * the resulting tool-tip text / message box looks wrong. It is best to do the same as the * Excel UI and encode 'not present' as "\0". */ private static UnicodeString ResolveTitleText(String str) { if (str == null || str.Length < 1) { return NULL_TEXT_STRING; } return new UnicodeString(str); } private static UnicodeString ReadUnicodeString(RecordInputStream in1) { return new UnicodeString(in1); } /** * Get the condition data type * @return the condition data type * @see org.apache.poi.hssf.util.HSSFDataValidation utility class */ public int DataType { get { return this.opt_data_type.GetValue(this._option_flags); } set { this._option_flags = this.opt_data_type.SetValue(this._option_flags, value); } } /** * Get the condition error style * @return the condition error style * @see org.apache.poi.hssf.util.HSSFDataValidation utility class */ public int ErrorStyle { get { return this.opt_error_style.GetValue(this._option_flags); } set { this._option_flags = this.opt_error_style.SetValue(this._option_flags, value); } } /** * return true if in list validations the string list Is explicitly given in the formula, false otherwise * @return true if in list validations the string list Is explicitly given in the formula, false otherwise * @see org.apache.poi.hssf.util.HSSFDataValidation utility class */ public bool ListExplicitFormula { get { return (this.opt_string_list_formula.IsSet(this._option_flags)); } set { this._option_flags = this.opt_string_list_formula.SetBoolean(this._option_flags, value); } } /** * return true if empty values are allowed in cells, false otherwise * @return if empty values are allowed in cells, false otherwise * @see org.apache.poi.hssf.util.HSSFDataValidation utility class */ public bool EmptyCellAllowed { get { return (this.opt_empty_cell_allowed.IsSet(this._option_flags)); } set { this._option_flags = this.opt_empty_cell_allowed.SetBoolean(this._option_flags, value); } } /** * return true if a prompt window should appear when cell Is selected, false otherwise * @return if a prompt window should appear when cell Is selected, false otherwise * @see org.apache.poi.hssf.util.HSSFDataValidation utility class */ public bool ShowPromptOnCellSelected { get { return (this.opt_show_prompt_on_cell_selected.IsSet(this._option_flags)); } } /** * return true if an error window should appear when an invalid value Is entered in the cell, false otherwise * @return if an error window should appear when an invalid value Is entered in the cell, false otherwise * @see org.apache.poi.hssf.util.HSSFDataValidation utility class */ public bool ShowErrorOnInvalidValue { get { return (this.opt_show_error_on_invalid_value.IsSet(this._option_flags)); } set { this._option_flags = this.opt_show_error_on_invalid_value.SetBoolean(this._option_flags, value); } } /** * Get the condition operator * @return the condition operator * @see org.apache.poi.hssf.util.HSSFDataValidation utility class */ public int ConditionOperator { get { return this.opt_condition_operator.GetValue(this._option_flags); } set { this._option_flags = this.opt_condition_operator.SetValue(this._option_flags, value); } } public CellRangeAddressList CellRangeAddress { get { return this._regions; } set { this._regions = value; } } /** * Gets the option flags field. * @return options - the option flags field */ public int OptionFlags { get { return this._option_flags; } } public override String ToString() { /* @todo DVRecord string representation */ StringBuilder buffer = new StringBuilder(); return buffer.ToString(); } public override void Serialize(ILittleEndianOutput out1) { out1.WriteInt(_option_flags); SerializeUnicodeString(_promptTitle, out1); SerializeUnicodeString(_errorTitle, out1); SerializeUnicodeString(_promptText, out1); SerializeUnicodeString(_errorText, out1); out1.WriteShort(_formula1.EncodedTokenSize); out1.WriteShort(_not_used_1); _formula1.SerializeTokens(out1); out1.WriteShort(_formula2.EncodedTokenSize); out1.WriteShort(_not_used_2); _formula2.SerializeTokens(out1); _regions.Serialize(out1); } private static void SerializeUnicodeString(UnicodeString us, ILittleEndianOutput out1) { StringUtil.WriteUnicodeString(out1, us.String); } private static int GetUnicodeStringSize(UnicodeString us) { String str = us.String; return 3 + str.Length * (StringUtil.HasMultibyte(str) ? 2 : 1); } protected override int DataSize { get { int size = 4 + 2 + 2 + 2 + 2;//header+options_field+first_formula_size+first_unused+sec_formula_size+sec+unused; size += GetUnicodeStringSize(_promptTitle); size += GetUnicodeStringSize(_errorTitle); size += GetUnicodeStringSize(_promptText); size += GetUnicodeStringSize(_errorText); size += _formula1.EncodedTokenSize; size += _formula2.EncodedTokenSize; size += _regions.Size; return size; } } public override short Sid { get { return DVRecord.sid; } } /** * Clones the object. Uses serialisation, as the * contents are somewhat complex */ public override Object Clone() { return CloneViaReserialise(); } } }
// 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.Diagnostics; using System.Linq; using System.Reflection; using System.Reflection.Emit; using System.Runtime.ExceptionServices; using System.Threading; namespace System.Reflection { // Helper class to handle the IL EMIT for the generation of proxies. // Much of this code was taken directly from the Silverlight proxy generation. // Differences between this and the Silverlight version are: // 1. This version is based on DispatchProxy from NET Native and CoreCLR, not RealProxy in Silverlight ServiceModel. // There are several notable differences between them. // 2. Both DispatchProxy and RealProxy permit the caller to ask for a proxy specifying a pair of types: // the interface type to implement, and a base type. But they behave slightly differently: // - RealProxy generates a proxy type that derives from Object and *implements" all the base type's // interfaces plus all the interface type's interfaces. // - DispatchProxy generates a proxy type that *derives* from the base type and implements all // the interface type's interfaces. This is true for both the CLR version in NET Native and this // version for CoreCLR. // 3. DispatchProxy and RealProxy use different type hierarchies for the generated proxies: // - RealProxy type hierarchy is: // proxyType : proxyBaseType : object // Presumably the 'proxyBaseType' in the middle is to allow it to implement the base type's interfaces // explicitly, preventing collision for same name methods on the base and interface types. // - DispatchProxy hierarchy is: // proxyType : baseType (where baseType : DispatchProxy) // The generated DispatchProxy proxy type does not need to generate implementation methods // for the base type's interfaces, because the base type already must have implemented them. // 4. RealProxy required a proxy instance to hold a backpointer to the RealProxy instance to mirror // the .Net Remoting design that required the proxy and RealProxy to be separate instances. // But the DispatchProxy design encourages the proxy type to *be* an DispatchProxy. Therefore, // the proxy's 'this' becomes the equivalent of RealProxy's backpointer to RealProxy, so we were // able to remove an extraneous field and ctor arg from the DispatchProxy proxies. // internal static class DispatchProxyGenerator { // Generated proxies have a private Action field that all generated methods // invoke. It is the first field in the class and the first ctor parameter. private const int InvokeActionFieldAndCtorParameterIndex = 0; // Proxies are requested for a pair of types: base type and interface type. // The generated proxy will subclass the given base type and implement the interface type. // We maintain a cache keyed by 'base type' containing a dictionary keyed by interface type, // containing the generated proxy type for that pair. There are likely to be few (maybe only 1) // base type in use for many interface types. // Note: this differs from Silverlight's RealProxy implementation which keys strictly off the // interface type. But this does not allow the same interface type to be used with more than a // single base type. The implementation here permits multiple interface types to be used with // multiple base types, and the generated proxy types will be unique. // This cache of generated types grows unbounded, one element per unique T/ProxyT pair. // This approach is used to prevent regenerating identical proxy types for identical T/Proxy pairs, // which would ultimately be a more expensive leak. // Proxy instances are not cached. Their lifetime is entirely owned by the caller of DispatchProxy.Create. private static readonly Dictionary<Type, Dictionary<Type, Type>> s_baseTypeAndInterfaceToGeneratedProxyType = new Dictionary<Type, Dictionary<Type, Type>>(); private static readonly ProxyAssembly s_proxyAssembly = new ProxyAssembly(); private static readonly MethodInfo s_dispatchProxyInvokeMethod = typeof(DispatchProxy).GetTypeInfo().GetDeclaredMethod("Invoke"); // Returns a new instance of a proxy the derives from 'baseType' and implements 'interfaceType' internal static object CreateProxyInstance(Type baseType, Type interfaceType) { Debug.Assert(baseType != null); Debug.Assert(interfaceType != null); Type proxiedType = GetProxyType(baseType, interfaceType); return Activator.CreateInstance(proxiedType, (Action<object[]>)DispatchProxyGenerator.Invoke); } private static Type GetProxyType(Type baseType, Type interfaceType) { lock (s_baseTypeAndInterfaceToGeneratedProxyType) { Dictionary<Type, Type> interfaceToProxy = null; if (!s_baseTypeAndInterfaceToGeneratedProxyType.TryGetValue(baseType, out interfaceToProxy)) { interfaceToProxy = new Dictionary<Type, Type>(); s_baseTypeAndInterfaceToGeneratedProxyType[baseType] = interfaceToProxy; } Type generatedProxy = null; if (!interfaceToProxy.TryGetValue(interfaceType, out generatedProxy)) { generatedProxy = GenerateProxyType(baseType, interfaceType); interfaceToProxy[interfaceType] = generatedProxy; } return generatedProxy; } } // Unconditionally generates a new proxy type derived from 'baseType' and implements 'interfaceType' private static Type GenerateProxyType(Type baseType, Type interfaceType) { // Parameter validation is deferred until the point we need to create the proxy. // This prevents unnecessary overhead revalidating cached proxy types. TypeInfo baseTypeInfo = baseType.GetTypeInfo(); // The interface type must be an interface, not a class if (!interfaceType.GetTypeInfo().IsInterface) { // "T" is the generic parameter seen via the public contract throw new ArgumentException(SR.Format(SR.InterfaceType_Must_Be_Interface, interfaceType.FullName), "T"); } // The base type cannot be sealed because the proxy needs to subclass it. if (baseTypeInfo.IsSealed) { // "TProxy" is the generic parameter seen via the public contract throw new ArgumentException(SR.Format(SR.BaseType_Cannot_Be_Sealed, baseTypeInfo.FullName), "TProxy"); } // The base type cannot be abstract if (baseTypeInfo.IsAbstract) { throw new ArgumentException(SR.Format(SR.BaseType_Cannot_Be_Abstract, baseType.FullName), "TProxy"); } // The base type must have a public default ctor if (!baseTypeInfo.DeclaredConstructors.Any(c => c.IsPublic && c.GetParameters().Length == 0)) { throw new ArgumentException(SR.Format(SR.BaseType_Must_Have_Default_Ctor, baseType.FullName), "TProxy"); } // Create a type that derives from 'baseType' provided by caller ProxyBuilder pb = s_proxyAssembly.CreateProxy("generatedProxy", baseType); foreach (Type t in interfaceType.GetTypeInfo().ImplementedInterfaces) pb.AddInterfaceImpl(t); pb.AddInterfaceImpl(interfaceType); Type generatedProxyType = pb.CreateType(); return generatedProxyType; } // All generated proxy methods call this static helper method to dispatch. // Its job is to unpack the arguments and the 'this' instance and to dispatch directly // to the (abstract) DispatchProxy.Invoke() method. private static void Invoke(object[] args) { PackedArgs packed = new PackedArgs(args); MethodBase method = s_proxyAssembly.ResolveMethodToken(packed.DeclaringType, packed.MethodToken); if (method.IsGenericMethodDefinition) method = ((MethodInfo)method).MakeGenericMethod(packed.GenericTypes); // Call (protected method) DispatchProxy.Invoke() try { Debug.Assert(s_dispatchProxyInvokeMethod != null); object returnValue = s_dispatchProxyInvokeMethod.Invoke(packed.DispatchProxy, new object[] { method, packed.Args }); packed.ReturnValue = returnValue; } catch (TargetInvocationException tie) { ExceptionDispatchInfo.Capture(tie.InnerException).Throw(); } } private class PackedArgs { internal const int DispatchProxyPosition = 0; internal const int DeclaringTypePosition = 1; internal const int MethodTokenPosition = 2; internal const int ArgsPosition = 3; internal const int GenericTypesPosition = 4; internal const int ReturnValuePosition = 5; internal static readonly Type[] PackedTypes = new Type[] { typeof(object), typeof(Type), typeof(int), typeof(object[]), typeof(Type[]), typeof(object) }; private object[] _args; internal PackedArgs() : this(new object[PackedTypes.Length]) { } internal PackedArgs(object[] args) { _args = args; } internal DispatchProxy DispatchProxy { get { return (DispatchProxy)_args[DispatchProxyPosition]; } } internal Type DeclaringType { get { return (Type)_args[DeclaringTypePosition]; } } internal int MethodToken { get { return (int)_args[MethodTokenPosition]; } } internal object[] Args { get { return (object[])_args[ArgsPosition]; } } internal Type[] GenericTypes { get { return (Type[])_args[GenericTypesPosition]; } } internal object ReturnValue { /*get { return args[ReturnValuePosition]; }*/ set { _args[ReturnValuePosition] = value; } } } private class ProxyAssembly { private AssemblyBuilder _ab; private ModuleBuilder _mb; private int _typeId = 0; // Maintain a MethodBase-->int, int-->MethodBase mapping to permit generated code // to pass methods by token private Dictionary<MethodBase, int> _methodToToken = new Dictionary<MethodBase, int>(); private List<MethodBase> _methodsByToken = new List<MethodBase>(); private HashSet<string> _ignoresAccessAssemblyNames = new HashSet<string>(); private ConstructorInfo _ignoresAccessChecksToAttributeConstructor; public ProxyAssembly() { _ab = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName("ProxyBuilder"), AssemblyBuilderAccess.Run); _mb = _ab.DefineDynamicModule("testmod"); } // Gets or creates the ConstructorInfo for the IgnoresAccessChecksAttribute. // This attribute is both defined and referenced in the dynamic assembly to // allow access to internal types in other assemblies. internal ConstructorInfo IgnoresAccessChecksAttributeConstructor { get { if (_ignoresAccessChecksToAttributeConstructor == null) { TypeInfo attributeTypeInfo = GenerateTypeInfoOfIgnoresAccessChecksToAttribute(); _ignoresAccessChecksToAttributeConstructor = attributeTypeInfo.DeclaredConstructors.Single(); } return _ignoresAccessChecksToAttributeConstructor; } } public ProxyBuilder CreateProxy(string name, Type proxyBaseType) { int nextId = Interlocked.Increment(ref _typeId); TypeBuilder tb = _mb.DefineType(name + "_" + nextId, TypeAttributes.Public, proxyBaseType); return new ProxyBuilder(this, tb, proxyBaseType); } // Generate the declaration for the IgnoresAccessChecksToAttribute type. // This attribute will be both defined and used in the dynamic assembly. // Each usage identifies the name of the assembly containing non-public // types the dynamic assembly needs to access. Normally those types // would be inaccessible, but this attribute allows them to be visible. // It works like a reverse InternalsVisibleToAttribute. // This method returns the TypeInfo of the generated attribute. private TypeInfo GenerateTypeInfoOfIgnoresAccessChecksToAttribute() { TypeBuilder attributeTypeBuilder = _mb.DefineType("System.Runtime.CompilerServices.IgnoresAccessChecksToAttribute", TypeAttributes.Public | TypeAttributes.Class, typeof(Attribute)); // Create backing field as: // private string assemblyName; FieldBuilder assemblyNameField = attributeTypeBuilder.DefineField("assemblyName", typeof(String), FieldAttributes.Private); // Create ctor as: // public IgnoresAccessChecksToAttribute(string) ConstructorBuilder constructorBuilder = attributeTypeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.HasThis, new Type[] { assemblyNameField.FieldType }); ILGenerator il = constructorBuilder.GetILGenerator(); // Create ctor body as: // this.assemblyName = {ctor parameter 0} il.Emit(OpCodes.Ldarg_0); il.Emit(OpCodes.Ldarg, 1); il.Emit(OpCodes.Stfld, assemblyNameField); // return il.Emit(OpCodes.Ret); // Define property as: // public string AssemblyName {get { return this.assemblyName; } } PropertyBuilder getterPropertyBuilder = attributeTypeBuilder.DefineProperty( "AssemblyName", PropertyAttributes.None, CallingConventions.HasThis, returnType: typeof(String), parameterTypes: null); MethodBuilder getterMethodBuilder = attributeTypeBuilder.DefineMethod( "get_AssemblyName", MethodAttributes.Public, CallingConventions.HasThis, returnType: typeof(String), parameterTypes: null); // Generate body: // return this.assemblyName; il = getterMethodBuilder.GetILGenerator(); il.Emit(OpCodes.Ldarg_0); il.Emit(OpCodes.Ldfld, assemblyNameField); il.Emit(OpCodes.Ret); // Generate the AttributeUsage attribute for this attribute type: // [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] TypeInfo attributeUsageTypeInfo = typeof(AttributeUsageAttribute).GetTypeInfo(); // Find the ctor that takes only AttributeTargets ConstructorInfo attributeUsageConstructorInfo = attributeUsageTypeInfo.DeclaredConstructors .Single(c => c.GetParameters().Count() == 1 && c.GetParameters()[0].ParameterType == typeof(AttributeTargets)); // Find the property to set AllowMultiple PropertyInfo allowMultipleProperty = attributeUsageTypeInfo.DeclaredProperties .Single(f => String.Equals(f.Name, "AllowMultiple")); // Create a builder to construct the instance via the ctor and property CustomAttributeBuilder customAttributeBuilder = new CustomAttributeBuilder(attributeUsageConstructorInfo, new object[] { AttributeTargets.Assembly }, new PropertyInfo[] { allowMultipleProperty }, new object[] { true }); // Attach this attribute instance to the newly defined attribute type attributeTypeBuilder.SetCustomAttribute(customAttributeBuilder); // Make the TypeInfo real so the constructor can be used. return attributeTypeBuilder.CreateTypeInfo(); } // Generates an instance of the IgnoresAccessChecksToAttribute to // identify the given assembly as one which contains internal types // the dynamic assembly will need to reference. internal void GenerateInstanceOfIgnoresAccessChecksToAttribute(string assemblyName) { // Add this assembly level attribute: // [assembly: System.Runtime.CompilerServices.IgnoresAccessChecksToAttribute(assemblyName)] ConstructorInfo attributeConstructor = IgnoresAccessChecksAttributeConstructor; CustomAttributeBuilder customAttributeBuilder = new CustomAttributeBuilder(attributeConstructor, new object[] { assemblyName }); _ab.SetCustomAttribute(customAttributeBuilder); } // Ensures the type we will reference from the dynamic assembly // is visible. Non-public types need to emit an attribute that // allows access from the dynamic assembly. internal void EnsureTypeIsVisible(Type type) { TypeInfo typeInfo = type.GetTypeInfo(); if (!typeInfo.IsVisible) { string assemblyName = typeInfo.Assembly.GetName().Name; if (!_ignoresAccessAssemblyNames.Contains(assemblyName)) { GenerateInstanceOfIgnoresAccessChecksToAttribute(assemblyName); _ignoresAccessAssemblyNames.Add(assemblyName); } } } internal void GetTokenForMethod(MethodBase method, out Type type, out int token) { type = method.DeclaringType; token = 0; if (!_methodToToken.TryGetValue(method, out token)) { _methodsByToken.Add(method); token = _methodsByToken.Count - 1; _methodToToken[method] = token; } } internal MethodBase ResolveMethodToken(Type type, int token) { Debug.Assert(token >= 0 && token < _methodsByToken.Count); return _methodsByToken[token]; } } private class ProxyBuilder { private static readonly MethodInfo s_delegateInvoke = typeof(Action<object[]>).GetTypeInfo().GetDeclaredMethod("Invoke"); private ProxyAssembly _assembly; private TypeBuilder _tb; private Type _proxyBaseType; private List<FieldBuilder> _fields; internal ProxyBuilder(ProxyAssembly assembly, TypeBuilder tb, Type proxyBaseType) { _assembly = assembly; _tb = tb; _proxyBaseType = proxyBaseType; _fields = new List<FieldBuilder>(); _fields.Add(tb.DefineField("invoke", typeof(Action<object[]>), FieldAttributes.Private)); } private void Complete() { Type[] args = new Type[_fields.Count]; for (int i = 0; i < args.Length; i++) { args[i] = _fields[i].FieldType; } ConstructorBuilder cb = _tb.DefineConstructor(MethodAttributes.Public, CallingConventions.HasThis, args); ILGenerator il = cb.GetILGenerator(); // chained ctor call ConstructorInfo baseCtor = _proxyBaseType.GetTypeInfo().DeclaredConstructors.SingleOrDefault(c => c.IsPublic && c.GetParameters().Length == 0); Debug.Assert(baseCtor != null); il.Emit(OpCodes.Ldarg_0); il.Emit(OpCodes.Call, baseCtor); // store all the fields for (int i = 0; i < args.Length; i++) { il.Emit(OpCodes.Ldarg_0); il.Emit(OpCodes.Ldarg, i + 1); il.Emit(OpCodes.Stfld, _fields[i]); } il.Emit(OpCodes.Ret); } internal Type CreateType() { this.Complete(); return _tb.CreateTypeInfo().AsType(); } internal void AddInterfaceImpl(Type iface) { // If necessary, generate an attribute to permit visibility // to internal types. _assembly.EnsureTypeIsVisible(iface); _tb.AddInterfaceImplementation(iface); // AccessorMethods -> Metadata mappings. var propertyMap = new Dictionary<MethodInfo, PropertyAccessorInfo>(MethodInfoEqualityComparer.Instance); foreach (PropertyInfo pi in iface.GetRuntimeProperties()) { var ai = new PropertyAccessorInfo(pi.GetMethod, pi.SetMethod); if (pi.GetMethod != null) propertyMap[pi.GetMethod] = ai; if (pi.SetMethod != null) propertyMap[pi.SetMethod] = ai; } var eventMap = new Dictionary<MethodInfo, EventAccessorInfo>(MethodInfoEqualityComparer.Instance); foreach (EventInfo ei in iface.GetRuntimeEvents()) { var ai = new EventAccessorInfo(ei.AddMethod, ei.RemoveMethod, ei.RaiseMethod); if (ei.AddMethod != null) eventMap[ei.AddMethod] = ai; if (ei.RemoveMethod != null) eventMap[ei.RemoveMethod] = ai; if (ei.RaiseMethod != null) eventMap[ei.RaiseMethod] = ai; } foreach (MethodInfo mi in iface.GetRuntimeMethods()) { MethodBuilder mdb = AddMethodImpl(mi); PropertyAccessorInfo associatedProperty; if (propertyMap.TryGetValue(mi, out associatedProperty)) { if (MethodInfoEqualityComparer.Instance.Equals(associatedProperty.InterfaceGetMethod, mi)) associatedProperty.GetMethodBuilder = mdb; else associatedProperty.SetMethodBuilder = mdb; } EventAccessorInfo associatedEvent; if (eventMap.TryGetValue(mi, out associatedEvent)) { if (MethodInfoEqualityComparer.Instance.Equals(associatedEvent.InterfaceAddMethod, mi)) associatedEvent.AddMethodBuilder = mdb; else if (MethodInfoEqualityComparer.Instance.Equals(associatedEvent.InterfaceRemoveMethod, mi)) associatedEvent.RemoveMethodBuilder = mdb; else associatedEvent.RaiseMethodBuilder = mdb; } } foreach (PropertyInfo pi in iface.GetRuntimeProperties()) { PropertyAccessorInfo ai = propertyMap[pi.GetMethod ?? pi.SetMethod]; PropertyBuilder pb = _tb.DefineProperty(pi.Name, pi.Attributes, pi.PropertyType, pi.GetIndexParameters().Select(p => p.ParameterType).ToArray()); if (ai.GetMethodBuilder != null) pb.SetGetMethod(ai.GetMethodBuilder); if (ai.SetMethodBuilder != null) pb.SetSetMethod(ai.SetMethodBuilder); } foreach (EventInfo ei in iface.GetRuntimeEvents()) { EventAccessorInfo ai = eventMap[ei.AddMethod ?? ei.RemoveMethod]; EventBuilder eb = _tb.DefineEvent(ei.Name, ei.Attributes, ei.EventHandlerType); if (ai.AddMethodBuilder != null) eb.SetAddOnMethod(ai.AddMethodBuilder); if (ai.RemoveMethodBuilder != null) eb.SetRemoveOnMethod(ai.RemoveMethodBuilder); if (ai.RaiseMethodBuilder != null) eb.SetRaiseMethod(ai.RaiseMethodBuilder); } } private MethodBuilder AddMethodImpl(MethodInfo mi) { ParameterInfo[] parameters = mi.GetParameters(); Type[] paramTypes = ParamTypes(parameters, false); MethodBuilder mdb = _tb.DefineMethod(mi.Name, MethodAttributes.Public | MethodAttributes.Virtual, mi.ReturnType, paramTypes); if (mi.ContainsGenericParameters) { Type[] ts = mi.GetGenericArguments(); string[] ss = new string[ts.Length]; for (int i = 0; i < ts.Length; i++) { ss[i] = ts[i].Name; } GenericTypeParameterBuilder[] genericParameters = mdb.DefineGenericParameters(ss); for (int i = 0; i < genericParameters.Length; i++) { genericParameters[i].SetGenericParameterAttributes(ts[i].GetTypeInfo().GenericParameterAttributes); } } ILGenerator il = mdb.GetILGenerator(); ParametersArray args = new ParametersArray(il, paramTypes); // object[] args = new object[paramCount]; il.Emit(OpCodes.Nop); GenericArray<object> argsArr = new GenericArray<object>(il, ParamTypes(parameters, true).Length); for (int i = 0; i < parameters.Length; i++) { // args[i] = argi; if (!parameters[i].IsOut) { argsArr.BeginSet(i); args.Get(i); argsArr.EndSet(parameters[i].ParameterType); } } // object[] packed = new object[PackedArgs.PackedTypes.Length]; GenericArray<object> packedArr = new GenericArray<object>(il, PackedArgs.PackedTypes.Length); // packed[PackedArgs.DispatchProxyPosition] = this; packedArr.BeginSet(PackedArgs.DispatchProxyPosition); il.Emit(OpCodes.Ldarg_0); packedArr.EndSet(typeof(DispatchProxy)); // packed[PackedArgs.DeclaringTypePosition] = typeof(iface); MethodInfo Type_GetTypeFromHandle = typeof(Type).GetRuntimeMethod("GetTypeFromHandle", new Type[] { typeof(RuntimeTypeHandle) }); int methodToken; Type declaringType; _assembly.GetTokenForMethod(mi, out declaringType, out methodToken); packedArr.BeginSet(PackedArgs.DeclaringTypePosition); il.Emit(OpCodes.Ldtoken, declaringType); il.Emit(OpCodes.Call, Type_GetTypeFromHandle); packedArr.EndSet(typeof(object)); // packed[PackedArgs.MethodTokenPosition] = iface method token; packedArr.BeginSet(PackedArgs.MethodTokenPosition); il.Emit(OpCodes.Ldc_I4, methodToken); packedArr.EndSet(typeof(Int32)); // packed[PackedArgs.ArgsPosition] = args; packedArr.BeginSet(PackedArgs.ArgsPosition); argsArr.Load(); packedArr.EndSet(typeof(object[])); // packed[PackedArgs.GenericTypesPosition] = mi.GetGenericArguments(); if (mi.ContainsGenericParameters) { packedArr.BeginSet(PackedArgs.GenericTypesPosition); Type[] genericTypes = mi.GetGenericArguments(); GenericArray<Type> typeArr = new GenericArray<Type>(il, genericTypes.Length); for (int i = 0; i < genericTypes.Length; ++i) { typeArr.BeginSet(i); il.Emit(OpCodes.Ldtoken, genericTypes[i]); il.Emit(OpCodes.Call, Type_GetTypeFromHandle); typeArr.EndSet(typeof(Type)); } typeArr.Load(); packedArr.EndSet(typeof(Type[])); } // Call static DispatchProxyHelper.Invoke(object[]) il.Emit(OpCodes.Ldarg_0); il.Emit(OpCodes.Ldfld, _fields[InvokeActionFieldAndCtorParameterIndex]); // delegate packedArr.Load(); il.Emit(OpCodes.Call, s_delegateInvoke); for (int i = 0; i < parameters.Length; i++) { if (parameters[i].ParameterType.IsByRef) { args.BeginSet(i); argsArr.Get(i); args.EndSet(i, typeof(object)); } } if (mi.ReturnType != typeof(void)) { packedArr.Get(PackedArgs.ReturnValuePosition); Convert(il, typeof(object), mi.ReturnType, false); } il.Emit(OpCodes.Ret); _tb.DefineMethodOverride(mdb, mi); return mdb; } private static Type[] ParamTypes(ParameterInfo[] parms, bool noByRef) { Type[] types = new Type[parms.Length]; for (int i = 0; i < parms.Length; i++) { types[i] = parms[i].ParameterType; if (noByRef && types[i].IsByRef) types[i] = types[i].GetElementType(); } return types; } // TypeCode does not exist in ProjectK or ProjectN. // This lookup method was copied from PortableLibraryThunks\Internal\PortableLibraryThunks\System\TypeThunks.cs // but returns the integer value equivalent to its TypeCode enum. private static int GetTypeCode(Type type) { if (type == null) return 0; // TypeCode.Empty; if (type == typeof(Boolean)) return 3; // TypeCode.Boolean; if (type == typeof(Char)) return 4; // TypeCode.Char; if (type == typeof(SByte)) return 5; // TypeCode.SByte; if (type == typeof(Byte)) return 6; // TypeCode.Byte; if (type == typeof(Int16)) return 7; // TypeCode.Int16; if (type == typeof(UInt16)) return 8; // TypeCode.UInt16; if (type == typeof(Int32)) return 9; // TypeCode.Int32; if (type == typeof(UInt32)) return 10; // TypeCode.UInt32; if (type == typeof(Int64)) return 11; // TypeCode.Int64; if (type == typeof(UInt64)) return 12; // TypeCode.UInt64; if (type == typeof(Single)) return 13; // TypeCode.Single; if (type == typeof(Double)) return 14; // TypeCode.Double; if (type == typeof(Decimal)) return 15; // TypeCode.Decimal; if (type == typeof(DateTime)) return 16; // TypeCode.DateTime; if (type == typeof(String)) return 18; // TypeCode.String; if (type.GetTypeInfo().IsEnum) return GetTypeCode(Enum.GetUnderlyingType(type)); return 1; // TypeCode.Object; } private static OpCode[] s_convOpCodes = new OpCode[] { OpCodes.Nop,//Empty = 0, OpCodes.Nop,//Object = 1, OpCodes.Nop,//DBNull = 2, OpCodes.Conv_I1,//Boolean = 3, OpCodes.Conv_I2,//Char = 4, OpCodes.Conv_I1,//SByte = 5, OpCodes.Conv_U1,//Byte = 6, OpCodes.Conv_I2,//Int16 = 7, OpCodes.Conv_U2,//UInt16 = 8, OpCodes.Conv_I4,//Int32 = 9, OpCodes.Conv_U4,//UInt32 = 10, OpCodes.Conv_I8,//Int64 = 11, OpCodes.Conv_U8,//UInt64 = 12, OpCodes.Conv_R4,//Single = 13, OpCodes.Conv_R8,//Double = 14, OpCodes.Nop,//Decimal = 15, OpCodes.Nop,//DateTime = 16, OpCodes.Nop,//17 OpCodes.Nop,//String = 18, }; private static OpCode[] s_ldindOpCodes = new OpCode[] { OpCodes.Nop,//Empty = 0, OpCodes.Nop,//Object = 1, OpCodes.Nop,//DBNull = 2, OpCodes.Ldind_I1,//Boolean = 3, OpCodes.Ldind_I2,//Char = 4, OpCodes.Ldind_I1,//SByte = 5, OpCodes.Ldind_U1,//Byte = 6, OpCodes.Ldind_I2,//Int16 = 7, OpCodes.Ldind_U2,//UInt16 = 8, OpCodes.Ldind_I4,//Int32 = 9, OpCodes.Ldind_U4,//UInt32 = 10, OpCodes.Ldind_I8,//Int64 = 11, OpCodes.Ldind_I8,//UInt64 = 12, OpCodes.Ldind_R4,//Single = 13, OpCodes.Ldind_R8,//Double = 14, OpCodes.Nop,//Decimal = 15, OpCodes.Nop,//DateTime = 16, OpCodes.Nop,//17 OpCodes.Ldind_Ref,//String = 18, }; private static OpCode[] s_stindOpCodes = new OpCode[] { OpCodes.Nop,//Empty = 0, OpCodes.Nop,//Object = 1, OpCodes.Nop,//DBNull = 2, OpCodes.Stind_I1,//Boolean = 3, OpCodes.Stind_I2,//Char = 4, OpCodes.Stind_I1,//SByte = 5, OpCodes.Stind_I1,//Byte = 6, OpCodes.Stind_I2,//Int16 = 7, OpCodes.Stind_I2,//UInt16 = 8, OpCodes.Stind_I4,//Int32 = 9, OpCodes.Stind_I4,//UInt32 = 10, OpCodes.Stind_I8,//Int64 = 11, OpCodes.Stind_I8,//UInt64 = 12, OpCodes.Stind_R4,//Single = 13, OpCodes.Stind_R8,//Double = 14, OpCodes.Nop,//Decimal = 15, OpCodes.Nop,//DateTime = 16, OpCodes.Nop,//17 OpCodes.Stind_Ref,//String = 18, }; private static void Convert(ILGenerator il, Type source, Type target, bool isAddress) { Debug.Assert(!target.IsByRef); if (target == source) return; TypeInfo sourceTypeInfo = source.GetTypeInfo(); TypeInfo targetTypeInfo = target.GetTypeInfo(); if (source.IsByRef) { Debug.Assert(!isAddress); Type argType = source.GetElementType(); Ldind(il, argType); Convert(il, argType, target, isAddress); return; } if (targetTypeInfo.IsValueType) { if (sourceTypeInfo.IsValueType) { OpCode opCode = s_convOpCodes[GetTypeCode(target)]; Debug.Assert(!opCode.Equals(OpCodes.Nop)); il.Emit(opCode); } else { Debug.Assert(sourceTypeInfo.IsAssignableFrom(targetTypeInfo)); il.Emit(OpCodes.Unbox, target); if (!isAddress) Ldind(il, target); } } else if (targetTypeInfo.IsAssignableFrom(sourceTypeInfo)) { if (sourceTypeInfo.IsValueType) { if (isAddress) Ldind(il, source); il.Emit(OpCodes.Box, source); } } else { Debug.Assert(sourceTypeInfo.IsAssignableFrom(targetTypeInfo) || targetTypeInfo.IsInterface || sourceTypeInfo.IsInterface); if (target.IsGenericParameter) { // T GetProperty<T>() where T : class; Debug.Assert(targetTypeInfo.GenericParameterAttributes == GenericParameterAttributes.ReferenceTypeConstraint); il.Emit(OpCodes.Unbox_Any, target); } else { il.Emit(OpCodes.Castclass, target); } } } private static void Ldind(ILGenerator il, Type type) { OpCode opCode = s_ldindOpCodes[GetTypeCode(type)]; if (!opCode.Equals(OpCodes.Nop)) { il.Emit(opCode); } else { il.Emit(OpCodes.Ldobj, type); } } private static void Stind(ILGenerator il, Type type) { OpCode opCode = s_stindOpCodes[GetTypeCode(type)]; if (!opCode.Equals(OpCodes.Nop)) { il.Emit(opCode); } else { il.Emit(OpCodes.Stobj, type); } } private class ParametersArray { private ILGenerator _il; private Type[] _paramTypes; internal ParametersArray(ILGenerator il, Type[] paramTypes) { _il = il; _paramTypes = paramTypes; } internal void Get(int i) { _il.Emit(OpCodes.Ldarg, i + 1); } internal void BeginSet(int i) { _il.Emit(OpCodes.Ldarg, i + 1); } internal void EndSet(int i, Type stackType) { Debug.Assert(_paramTypes[i].IsByRef); Type argType = _paramTypes[i].GetElementType(); Convert(_il, stackType, argType, false); Stind(_il, argType); } } private class GenericArray<T> { private ILGenerator _il; private LocalBuilder _lb; internal GenericArray(ILGenerator il, int len) { _il = il; _lb = il.DeclareLocal(typeof(T[])); il.Emit(OpCodes.Ldc_I4, len); il.Emit(OpCodes.Newarr, typeof(T)); il.Emit(OpCodes.Stloc, _lb); } internal void Load() { _il.Emit(OpCodes.Ldloc, _lb); } internal void Get(int i) { _il.Emit(OpCodes.Ldloc, _lb); _il.Emit(OpCodes.Ldc_I4, i); _il.Emit(OpCodes.Ldelem_Ref); } internal void BeginSet(int i) { _il.Emit(OpCodes.Ldloc, _lb); _il.Emit(OpCodes.Ldc_I4, i); } internal void EndSet(Type stackType) { Convert(_il, stackType, typeof(T), false); _il.Emit(OpCodes.Stelem_Ref); } } private sealed class PropertyAccessorInfo { public MethodInfo InterfaceGetMethod { get; } public MethodInfo InterfaceSetMethod { get; } public MethodBuilder GetMethodBuilder { get; set; } public MethodBuilder SetMethodBuilder { get; set; } public PropertyAccessorInfo(MethodInfo interfaceGetMethod, MethodInfo interfaceSetMethod) { InterfaceGetMethod = interfaceGetMethod; InterfaceSetMethod = interfaceSetMethod; } } private sealed class EventAccessorInfo { public MethodInfo InterfaceAddMethod { get; } public MethodInfo InterfaceRemoveMethod { get; } public MethodInfo InterfaceRaiseMethod { get; } public MethodBuilder AddMethodBuilder { get; set; } public MethodBuilder RemoveMethodBuilder { get; set; } public MethodBuilder RaiseMethodBuilder { get; set; } public EventAccessorInfo(MethodInfo interfaceAddMethod, MethodInfo interfaceRemoveMethod, MethodInfo interfaceRaiseMethod) { InterfaceAddMethod = interfaceAddMethod; InterfaceRemoveMethod = interfaceRemoveMethod; InterfaceRaiseMethod = interfaceRaiseMethod; } } private sealed class MethodInfoEqualityComparer : EqualityComparer<MethodInfo> { public static readonly MethodInfoEqualityComparer Instance = new MethodInfoEqualityComparer(); private MethodInfoEqualityComparer() { } public sealed override bool Equals(MethodInfo left, MethodInfo right) { if (ReferenceEquals(left, right)) return true; if (left == null) return right == null; else if (right == null) return false; // This assembly should work in netstandard1.3, // so we cannot use MemberInfo.MetadataToken here. // Therefore, it compares honestly referring ECMA-335 I.8.6.1.6 Signature Matching. if (!Equals(left.DeclaringType, right.DeclaringType)) return false; if (!Equals(left.ReturnType, right.ReturnType)) return false; if (left.CallingConvention != right.CallingConvention) return false; if (left.IsStatic != right.IsStatic) return false; if ( left.Name != right.Name) return false; Type[] leftGenericParameters = left.GetGenericArguments(); Type[] rightGenericParameters = right.GetGenericArguments(); if (leftGenericParameters.Length != rightGenericParameters.Length) return false; for (int i = 0; i < leftGenericParameters.Length; i++) { if (!Equals(leftGenericParameters[i], rightGenericParameters[i])) return false; } ParameterInfo[] leftParameters = left.GetParameters(); ParameterInfo[] rightParameters = right.GetParameters(); if (leftParameters.Length != rightParameters.Length) return false; for (int i = 0; i < leftParameters.Length; i++) { if (!Equals(leftParameters[i].ParameterType, rightParameters[i].ParameterType)) return false; } return true; } public sealed override int GetHashCode(MethodInfo obj) { if (obj == null) return 0; int hashCode = obj.DeclaringType.GetHashCode(); hashCode ^= obj.Name.GetHashCode(); foreach (ParameterInfo parameter in obj.GetParameters()) { hashCode ^= parameter.ParameterType.GetHashCode(); } return hashCode; } } } } }
// // System.Data.Common.Key.cs // // Author: // Boris Kirzner <borisk@mainsoft.com> // Konstantin Triger (kostat@mainsoft.com) // /* * Copyright (c) 2002-2004 Mainsoft Corporation. * * 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.Data.SqlExpressions; using System.ComponentModel; namespace System.Data.Common { internal class Key { #region Fields DataTable _table; DataColumn[] _columns; ListSortDirection[] _sortDirection; DataViewRowState _rowStateFilter; IExpression _filter; //Currently IExpression.Eval does not receive DataRowVersion // and always uses the _current version //so need a temp row for Eval calls DataRow _tmpRow; #endregion //Fields #region Constructors internal Key(DataTable table,DataColumn[] columns,ListSortDirection[] sort, DataViewRowState rowState, IExpression filter) { _table = table; _filter = filter; if (_filter != null) _tmpRow = _table.NewNotInitializedRow(); _columns = columns; if (sort != null && sort.Length == columns.Length) { _sortDirection = sort; } else { _sortDirection = new ListSortDirection[columns.Length]; for(int i=0; i < _sortDirection.Length; i++) { _sortDirection[i] = ListSortDirection.Ascending; } } if (rowState != DataViewRowState.None) { _rowStateFilter = rowState; } else { // FIXME : what is the correct value ? _rowStateFilter = DataViewRowState.CurrentRows; } } #endregion // Constructors #region Properties internal DataColumn[] Columns { get { return _columns; } } internal DataTable Table { get { return _table; } } ListSortDirection[] Sort { get { return _sortDirection; } } internal DataViewRowState RowStateFilter { get { return _rowStateFilter; } set { _rowStateFilter = value; } } #endregion // Properties #region Methods internal int CompareRecords(int first, int second) { if (first == second) { return 0; } for(int i = 0; i < Columns.Length; i++) { int res = Columns[i].CompareValues(first,second); if (res == 0) { continue; } return (Sort[i] == ListSortDirection.Ascending) ? res : -res; } return 0; } internal int GetRecord(DataRow row) { int index = Key.GetRecord(row,_rowStateFilter); if (_filter == null) return index; if (index < 0) return index; _tmpRow._current = index; return _filter.EvalBoolean(_tmpRow) ? index : -1; } internal static int GetRecord(DataRow row, DataViewRowState rowStateFilter) { if (row.Original == row.Current) { if ((rowStateFilter & DataViewRowState.Unchanged) != DataViewRowState.None) { return row.Current; } } else if (row.Original == -1) { if ((rowStateFilter & DataViewRowState.Added) != DataViewRowState.None) { return row.Current; } } else if (row.Current == -1) { if ((rowStateFilter & DataViewRowState.Deleted) != DataViewRowState.None) { return row.Original; } } else if ((rowStateFilter & DataViewRowState.ModifiedCurrent) != DataViewRowState.None) { return row.Current; } else if ((rowStateFilter & DataViewRowState.ModifiedOriginal) != DataViewRowState.None) { return row.Original; } return -1; } /// <summary> /// Checks for key equality to parameters set given /// </summary> /// <param name="columns">Columns the key consits of. If this parameter is null, it does not affects equality check</param> /// <param name="sort">Sort order of columns. If this parameter is null, it does not affects equality check</param> /// <param name="rowState">DataViewRowState to check for.If this parameter is null, it does not affects equality check</param> /// <param name="unique">Indicates whenever the index managed by this key allows non-uniqie keys to appear.</param> /// <param name="strict">Indicates whenever unique parameter should affect the equality check.</param> /// <returns></returns> internal bool Equals(DataColumn[] columns, ListSortDirection[] sort, DataViewRowState rowState, IExpression filter) { if (rowState != DataViewRowState.None && RowStateFilter != rowState) { return false; } if (_filter != filter) return false; if (Columns.Length != columns.Length) { return false; } if (sort != null && Sort.Length != sort.Length) { return false; } if (sort != null) { for(int i=0; i < columns.Length; i++) { if (Sort[i] != sort[i] || Columns[i] != columns[i]) { return false; } } } else { for(int i=0; i < columns.Length; i++) { if (Columns[i] != columns[i]) { return false; } } } return true; } #endregion // Methods } }
using Alphaleonis.VSProjectSetMgr.Controls; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Interop; using System.Windows.Media; using System.Windows.Media.Imaging; namespace Alphaleonis.VSProjectSetMgr.ViewModels.Nodes { abstract class ProjectSetNodeViewModel : ObservableBase { #region Private Fields private readonly ISolutionHierarchyItem m_projectSetNode; private readonly ProjectSetContainerNodeViewModel m_parent; private bool m_isSelected; private bool m_isExpanded; private readonly ProjectSetViewModel m_owner; #endregion #region Constructor public ProjectSetNodeViewModel(ProjectSetViewModel owner, ISolutionHierarchyItem projectSetNode, ProjectSetContainerNodeViewModel parent) { m_owner = owner; m_parent = parent; m_projectSetNode = projectSetNode; } #endregion #region Properties public Guid Id { get { return m_projectSetNode.Id; } } public string Name { get { return m_projectSetNode.Name; } } public bool? IsIncluded { get { return m_owner.ModelItem.GetInclusionState(Id); } set { if (IsIncluded != value) { m_owner.ModelItem.SetInclusionState(Id, value); OnPropertyChanged(); OnPropertyChanged("State"); OnParentStateChanged(); if (HasParent) Parent.OnChildStateChanged(); } } } public bool IsSelected { get { return m_isSelected; } set { SetValue(ref m_isSelected, value); } } public bool IsExpanded { get { return m_isExpanded; } set { SetValue(ref m_isExpanded, value); } } public ProjectSetContainerNodeViewModel Parent { get { return m_parent; } } public bool HasParent { get { return m_parent != null; } } public ImageSource Image { get { return Imaging.CreateBitmapSourceFromHIcon(m_projectSetNode.ImageHandle, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); } } public virtual InclusionExclusionCheckBoxState State { get { if (IsIncluded == true) return InclusionExclusionCheckBoxState.Included; else if (IsIncluded == false) return InclusionExclusionCheckBoxState.Excluded; else if (HasParent && Parent.State.IsIncluded()) return InclusionExclusionCheckBoxState.ImplicitlyIncluded; else if (HasIncludedChildren) return InclusionExclusionCheckBoxState.PartiallyIncluded; else return InclusionExclusionCheckBoxState.Unchecked; } set { switch (value) { case InclusionExclusionCheckBoxState.Unchecked: IsIncluded = null; break; case InclusionExclusionCheckBoxState.ImplicitlyIncluded: IsIncluded = null; break; case InclusionExclusionCheckBoxState.Included: IsIncluded = true; break; case InclusionExclusionCheckBoxState.Excluded: IsIncluded = false; break; case InclusionExclusionCheckBoxState.PartiallyIncluded: IsIncluded = null; break; } } } #endregion #region Methods public virtual bool HasIncludedChildren { get { return false; } } public virtual void OnParentStateChanged() { if (!IsIncluded.HasValue) OnPropertyChanged("State"); } public virtual void OnChildStateChanged() { if (!IsIncluded.HasValue) { OnPropertyChanged("State"); if (Parent != null) Parent.OnChildStateChanged(); } } public abstract IEnumerable<ProjectSetNodeViewModel> GetDescendantNodesAndSelf(); public static ProjectSetNodeViewModel CreateFrom(ProjectSetViewModel owner, ISolutionHierarchyItem node, ProjectSetContainerNodeViewModel parent) { if (node == null) throw new ArgumentNullException("node", "node is null."); if (parent == null && node.ItemType != SolutionHierarchyItemType.Solution) throw new ArgumentNullException("parent", "parent is null."); switch (node.ItemType) { case SolutionHierarchyItemType.Solution: return new ProjectSetSolutionRootNodeViewModel(owner, (ISolutionHierarchyContainerItem)node); case SolutionHierarchyItemType.SolutionFolder: return new ProjectSetSolutionFolderNodeViewModel(owner, (ISolutionHierarchyContainerItem)node, parent); case SolutionHierarchyItemType.Project: case SolutionHierarchyItemType.UnloadedProject: return new ProjectSetProjectNodeViewModel(owner, node, parent); default: throw new NotSupportedException(String.Format("Unknown project set node type {0}", node.ItemType)); } } public virtual void UncheckRecursively() { IsIncluded = null; } #endregion } }
// *********************************************************************** // Copyright (c) 2012 Charlie Poole // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** using System; using System.Text; using System.Collections; using System.Globalization; using NUnit.Framework.Internal; namespace NUnit.Framework.Constraints { /// <summary> /// Custom value formatter function /// </summary> /// <param name="val">The value</param> /// <returns></returns> public delegate string ValueFormatter(object val); /// <summary> /// Custom value formatter factory function /// </summary> /// <param name="next">The next formatter function</param> /// <returns>ValueFormatter</returns> /// <remarks>If the given formatter is unable to handle a certain format, it must call the next formatter in the chain</remarks> public delegate ValueFormatter ValueFormatterFactory(ValueFormatter next); /// <summary> /// Static methods used in creating messages /// </summary> internal static class MsgUtils { /// <summary> /// Static string used when strings are clipped /// </summary> private const string ELLIPSIS = "..."; /// <summary> /// Formatting strings used for expected and actual _values /// </summary> private static readonly string Fmt_Null = "null"; private static readonly string Fmt_EmptyString = "<string.Empty>"; private static readonly string Fmt_EmptyCollection = "<empty>"; private static readonly string Fmt_String = "\"{0}\""; private static readonly string Fmt_Char = "'{0}'"; private static readonly string Fmt_DateTime = "yyyy-MM-dd HH:mm:ss.fff"; #if !NETCF private static readonly string Fmt_DateTimeOffset = "yyyy-MM-dd HH:mm:ss.fffzzz"; #endif private static readonly string Fmt_ValueType = "{0}"; private static readonly string Fmt_Default = "<{0}>"; /// <summary> /// Current head of chain of value formatters. Public for testing. /// </summary> public static ValueFormatter DefaultValueFormatter { get; set; } static MsgUtils() { // Initialize formatter to default for values of indeterminate type. DefaultValueFormatter = val => string.Format(Fmt_Default, val); AddFormatter(next => val => val is ValueType ? string.Format(Fmt_ValueType, val) : next(val)); AddFormatter(next => val => val is DateTime ? FormatDateTime((DateTime)val) : next(val)); #if !NETCF AddFormatter(next => val => val is DateTimeOffset ? FormatDateTimeOffset ((DateTimeOffset)val) : next (val)); #endif AddFormatter(next => val => val is decimal ? FormatDecimal((decimal)val) : next(val)); AddFormatter(next => val => val is float ? FormatFloat((float)val) : next(val)); AddFormatter(next => val => val is double ? FormatDouble((double)val) : next(val)); AddFormatter(next => val => val is char ? string.Format(Fmt_Char, val) : next(val)); AddFormatter(next => val => val is IEnumerable ? FormatCollection((IEnumerable)val, 0, 10) : next(val)); AddFormatter(next => val => val is string ? FormatString((string)val) : next(val)); AddFormatter(next => val => val.GetType().IsArray ? FormatArray((Array)val) : next(val)); #if NETCF AddFormatter(next => val => { var vi = val as System.Reflection.MethodInfo; return (vi != null && vi.IsGenericMethodDefinition) ? string.Format(Fmt_Default, vi.Name + "<>") : next(val); }); #endif } /// <summary> /// Add a formatter to the chain of responsibility. /// </summary> /// <param name="formatterFactory"></param> public static void AddFormatter(ValueFormatterFactory formatterFactory) { DefaultValueFormatter = formatterFactory(DefaultValueFormatter); } /// <summary> /// Formats text to represent a generalized value. /// </summary> /// <param name="val">The value</param> /// <returns>The formatted text</returns> public static string FormatValue(object val) { if (val == null) return Fmt_Null; var context = TestExecutionContext.CurrentContext; if (context != null) return context.CurrentValueFormatter(val); else return DefaultValueFormatter(val); } /// <summary> /// Formats text for a collection value, /// starting at a particular point, to a max length /// </summary> /// <param name="collection">The collection containing elements to write.</param> /// <param name="start">The starting point of the elements to write</param> /// <param name="max">The maximum number of elements to write</param> public static string FormatCollection(IEnumerable collection, long start, int max) { int count = 0; int index = 0; System.Text.StringBuilder sb = new System.Text.StringBuilder(); foreach (object obj in collection) { if (index++ >= start) { if (++count > max) break; sb.Append(count == 1 ? "< " : ", "); sb.Append(FormatValue(obj)); } } if (count == 0) return Fmt_EmptyCollection; if (count > max) sb.Append("..."); sb.Append(" >"); return sb.ToString(); } private static string FormatArray(Array array) { if (array.Length == 0) return Fmt_EmptyCollection; int rank = array.Rank; int[] products = new int[rank]; for (int product = 1, r = rank; --r >= 0; ) products[r] = product *= array.GetLength(r); int count = 0; System.Text.StringBuilder sb = new System.Text.StringBuilder(); foreach (object obj in array) { if (count > 0) sb.Append(", "); bool startSegment = false; for (int r = 0; r < rank; r++) { startSegment = startSegment || count % products[r] == 0; if (startSegment) sb.Append("< "); } sb.Append(FormatValue(obj)); ++count; bool nextSegment = false; for (int r = 0; r < rank; r++) { nextSegment = nextSegment || count % products[r] == 0; if (nextSegment) sb.Append(" >"); } } return sb.ToString(); } private static string FormatString(string s) { return s == string.Empty ? Fmt_EmptyString : string.Format(Fmt_String, s); } private static string FormatDouble(double d) { if (double.IsNaN(d) || double.IsInfinity(d)) return d.ToString(); else { string s = d.ToString("G17", CultureInfo.InvariantCulture); if (s.IndexOf('.') > 0) return s + "d"; else return s + ".0d"; } } private static string FormatFloat(float f) { if (float.IsNaN(f) || float.IsInfinity(f)) return f.ToString(); else { string s = f.ToString("G9", CultureInfo.InvariantCulture); if (s.IndexOf('.') > 0) return s + "f"; else return s + ".0f"; } } private static string FormatDecimal(Decimal d) { return d.ToString("G29", CultureInfo.InvariantCulture) + "m"; } private static string FormatDateTime(DateTime dt) { return dt.ToString(Fmt_DateTime, CultureInfo.InvariantCulture); } #if !NETCF private static string FormatDateTimeOffset(DateTimeOffset dto) { return dto.ToString(Fmt_DateTimeOffset, CultureInfo.InvariantCulture); } #endif /// <summary> /// Returns the representation of a type as used in NUnitLite. /// This is the same as Type.ToString() except for arrays, /// which are displayed with their declared sizes. /// </summary> /// <param name="obj"></param> /// <returns></returns> public static string GetTypeRepresentation(object obj) { Array array = obj as Array; if (array == null) return string.Format("<{0}>", obj.GetType()); StringBuilder sb = new StringBuilder(); Type elementType = array.GetType(); int nest = 0; while (elementType.IsArray) { elementType = elementType.GetElementType(); ++nest; } sb.Append(elementType.ToString()); sb.Append('['); for (int r = 0; r < array.Rank; r++) { if (r > 0) sb.Append(','); sb.Append(array.GetLength(r)); } sb.Append(']'); while (--nest > 0) sb.Append("[]"); return string.Format("<{0}>", sb.ToString()); } /// <summary> /// Converts any control characters in a string /// to their escaped representation. /// </summary> /// <param name="s">The string to be converted</param> /// <returns>The converted string</returns> public static string EscapeControlChars(string s) { if (s != null) { StringBuilder sb = new StringBuilder(); foreach (char c in s) { switch (c) { //case '\'': // sb.Append("\\\'"); // break; //case '\"': // sb.Append("\\\""); // break; case '\\': sb.Append("\\\\"); break; case '\0': sb.Append("\\0"); break; case '\a': sb.Append("\\a"); break; case '\b': sb.Append("\\b"); break; case '\f': sb.Append("\\f"); break; case '\n': sb.Append("\\n"); break; case '\r': sb.Append("\\r"); break; case '\t': sb.Append("\\t"); break; case '\v': sb.Append("\\v"); break; case '\x0085': case '\x2028': case '\x2029': sb.Append(string.Format("\\x{0:X4}", (int)c)); break; default: sb.Append(c); break; } } s = sb.ToString(); } return s; } /// <summary> /// Converts any null characters in a string /// to their escaped representation. /// </summary> /// <param name="s">The string to be converted</param> /// <returns>The converted string</returns> public static string EscapeNullCharacters(string s) { if(s != null) { StringBuilder sb = new StringBuilder(); foreach(char c in s) { switch(c) { case '\0': sb.Append("\\0"); break; default: sb.Append(c); break; } } s = sb.ToString(); } return s; } /// <summary> /// Return the a string representation for a set of indices into an array /// </summary> /// <param name="indices">Array of indices for which a string is needed</param> public static string GetArrayIndicesAsString(int[] indices) { StringBuilder sb = new StringBuilder(); sb.Append('['); for (int r = 0; r < indices.Length; r++) { if (r > 0) sb.Append(','); sb.Append(indices[r].ToString()); } sb.Append(']'); return sb.ToString(); } /// <summary> /// Get an array of indices representing the point in a collection or /// array corresponding to a single int index into the collection. /// </summary> /// <param name="collection">The collection to which the indices apply</param> /// <param name="index">Index in the collection</param> /// <returns>Array of indices</returns> public static int[] GetArrayIndicesFromCollectionIndex(IEnumerable collection, long index) { Array array = collection as Array; int rank = array == null ? 1 : array.Rank; int[] result = new int[rank]; for (int r = rank; --r > 0; ) { int l = array.GetLength(r); result[r] = (int)index % l; index /= l; } result[0] = (int)index; return result; } /// <summary> /// Clip a string to a given length, starting at a particular offset, returning the clipped /// string with ellipses representing the removed parts /// </summary> /// <param name="s">The string to be clipped</param> /// <param name="maxStringLength">The maximum permitted length of the result string</param> /// <param name="clipStart">The point at which to start clipping</param> /// <returns>The clipped string</returns> public static string ClipString(string s, int maxStringLength, int clipStart) { int clipLength = maxStringLength; StringBuilder sb = new StringBuilder(); if (clipStart > 0) { clipLength -= ELLIPSIS.Length; sb.Append(ELLIPSIS); } if (s.Length - clipStart > clipLength) { clipLength -= ELLIPSIS.Length; sb.Append(s.Substring(clipStart, clipLength)); sb.Append(ELLIPSIS); } else if (clipStart > 0) sb.Append(s.Substring(clipStart)); else sb.Append(s); return sb.ToString(); } /// <summary> /// Clip the expected and actual strings in a coordinated fashion, /// so that they may be displayed together. /// </summary> /// <param name="expected"></param> /// <param name="actual"></param> /// <param name="maxDisplayLength"></param> /// <param name="mismatch"></param> public static void ClipExpectedAndActual(ref string expected, ref string actual, int maxDisplayLength, int mismatch) { // Case 1: Both strings fit on line int maxStringLength = Math.Max(expected.Length, actual.Length); if (maxStringLength <= maxDisplayLength) return; // Case 2: Assume that the tail of each string fits on line int clipLength = maxDisplayLength - ELLIPSIS.Length; int clipStart = maxStringLength - clipLength; // Case 3: If it doesn't, center the mismatch position if (clipStart > mismatch) clipStart = Math.Max(0, mismatch - clipLength / 2); expected = ClipString(expected, maxDisplayLength, clipStart); actual = ClipString(actual, maxDisplayLength, clipStart); } /// <summary> /// Shows the position two strings start to differ. Comparison /// starts at the start index. /// </summary> /// <param name="expected">The expected string</param> /// <param name="actual">The actual string</param> /// <param name="istart">The index in the strings at which comparison should start</param> /// <param name="ignoreCase">Boolean indicating whether case should be ignored</param> /// <returns>-1 if no mismatch found, or the index where mismatch found</returns> static public int FindMismatchPosition(string expected, string actual, int istart, bool ignoreCase) { int length = Math.Min(expected.Length, actual.Length); string s1 = ignoreCase ? expected.ToLower() : expected; string s2 = ignoreCase ? actual.ToLower() : actual; for (int i = istart; i < length; i++) { if (s1[i] != s2[i]) return i; } // // Strings have same content up to the length of the shorter string. // Mismatch occurs because string lengths are different, so show // that they start differing where the shortest string ends // if (expected.Length != actual.Length) return length; // // Same strings : We shouldn't get here // return -1; } } }
#region License /* The MIT License Copyright (c) 2008 Sky Morey Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #endregion using System; using System.Collections.Generic; using System.Web.Routing; using System.Globalization; using System.Linq.Expressions; using System.Web.UI; #if !MVC2 using HtmlHelperKludge = System.Web.Mvc.HtmlHelper; #endif namespace System.Web.Mvc.Html { /// <summary> /// TextAreaExtensionsEx /// </summary> public static partial class TextAreaExtensionsEx { /// <summary> /// HTMLs the text editor. /// </summary> /// <param name="htmlHelper">The HTML helper.</param> /// <param name="name">The name.</param> /// <returns></returns> public static MvcHtmlString HtmlTextEditor(this HtmlHelper htmlHelper, string name) { return htmlHelper.HtmlTextEditor(name, null, ((IDictionary<string, object>)null)); } /// <summary> /// HTMLs the text editor. /// </summary> /// <param name="htmlHelper">The HTML helper.</param> /// <param name="name">The name.</param> /// <param name="htmlAttributes">The HTML attributes.</param> /// <returns></returns> public static MvcHtmlString HtmlTextEditor(this HtmlHelper htmlHelper, string name, IDictionary<string, object> htmlAttributes) { return htmlHelper.HtmlTextEditor(name, null, htmlAttributes); } /// <summary> /// HTMLs the text editor. /// </summary> /// <param name="htmlHelper">The HTML helper.</param> /// <param name="name">The name.</param> /// <param name="htmlAttributes">The HTML attributes.</param> /// <returns></returns> public static MvcHtmlString HtmlTextEditor(this HtmlHelper htmlHelper, string name, object htmlAttributes) { return htmlHelper.HtmlTextEditor(name, null, (IDictionary<string, object>)HtmlHelperKludge.AnonymousObjectToHtmlAttributes(htmlAttributes)); } /// <summary> /// HTMLs the text editor. /// </summary> /// <param name="htmlHelper">The HTML helper.</param> /// <param name="name">The name.</param> /// <param name="value">The value.</param> /// <returns></returns> public static MvcHtmlString HtmlTextEditor(this HtmlHelper htmlHelper, string name, string value) { return htmlHelper.HtmlTextEditor(name, value, ((IDictionary<string, object>)null)); } /// <summary> /// HTMLs the text editor. /// </summary> /// <param name="htmlHelper">The HTML helper.</param> /// <param name="name">The name.</param> /// <param name="value">The value.</param> /// <param name="htmlAttributes">The HTML attributes.</param> /// <returns></returns> public static MvcHtmlString HtmlTextEditor(this HtmlHelper htmlHelper, string name, string value, IDictionary<string, object> htmlAttributes) { var modelMetadata = ModelMetadata.FromStringExpression(name, htmlHelper.ViewContext.ViewData); if (value != null) modelMetadata.Model = value; var editor = GetEditor(htmlAttributes); return editor.HtmlTextAreaHelper(htmlHelper, modelMetadata, name, _implicitRowsAndColumns, htmlAttributes); } /// <summary> /// HTMLs the text editor. /// </summary> /// <param name="htmlHelper">The HTML helper.</param> /// <param name="name">The name.</param> /// <param name="value">The value.</param> /// <param name="htmlAttributes">The HTML attributes.</param> /// <returns></returns> public static MvcHtmlString HtmlTextEditor(this HtmlHelper htmlHelper, string name, string value, object htmlAttributes) { return htmlHelper.HtmlTextEditor(name, value, (IDictionary<string, object>)HtmlHelperKludge.AnonymousObjectToHtmlAttributes(htmlAttributes)); } /// <summary> /// HTMLs the text editor. /// </summary> /// <param name="htmlHelper">The HTML helper.</param> /// <param name="name">The name.</param> /// <param name="value">The value.</param> /// <param name="rows">The rows.</param> /// <param name="columns">The columns.</param> /// <param name="htmlAttributes">The HTML attributes.</param> /// <returns></returns> public static MvcHtmlString HtmlTextEditor(this HtmlHelper htmlHelper, string name, string value, int rows, int columns, IDictionary<string, object> htmlAttributes) { var modelMetadata = ModelMetadata.FromStringExpression(name, htmlHelper.ViewContext.ViewData); if (value != null) modelMetadata.Model = value; var editor = GetEditor(htmlAttributes); return editor.HtmlTextAreaHelper(htmlHelper, modelMetadata, name, GetRowsAndColumnsDictionary(rows, columns), htmlAttributes); } /// <summary> /// HTMLs the text editor. /// </summary> /// <param name="htmlHelper">The HTML helper.</param> /// <param name="name">The name.</param> /// <param name="value">The value.</param> /// <param name="rows">The rows.</param> /// <param name="columns">The columns.</param> /// <param name="htmlAttributes">The HTML attributes.</param> /// <returns></returns> public static MvcHtmlString HtmlTextEditor(this HtmlHelper htmlHelper, string name, string value, int rows, int columns, object htmlAttributes) { return htmlHelper.HtmlTextEditor(name, value, rows, columns, (IDictionary<string, object>)HtmlHelperKludge.AnonymousObjectToHtmlAttributes(htmlAttributes)); } /// <summary> /// HTMLs the text editor for. /// </summary> /// <typeparam name="TModel">The type of the model.</typeparam> /// <typeparam name="TProperty">The type of the property.</typeparam> /// <param name="htmlHelper">The HTML helper.</param> /// <param name="expression">The expression.</param> /// <returns></returns> public static MvcHtmlString HtmlTextEditorFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression) { return htmlHelper.HtmlTextEditorFor<TModel, TProperty>(expression, ((IDictionary<string, object>)null)); } /// <summary> /// HTMLs the text editor for. /// </summary> /// <typeparam name="TModel">The type of the model.</typeparam> /// <typeparam name="TProperty">The type of the property.</typeparam> /// <param name="htmlHelper">The HTML helper.</param> /// <param name="expression">The expression.</param> /// <param name="htmlAttributes">The HTML attributes.</param> /// <returns></returns> public static MvcHtmlString HtmlTextEditorFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IDictionary<string, object> htmlAttributes) { if (expression == null) throw new ArgumentNullException("expression"); var editor = GetEditor(htmlAttributes); return editor.HtmlTextAreaHelper(htmlHelper, ModelMetadata.FromLambdaExpression<TModel, TProperty>(expression, htmlHelper.ViewData), ExpressionHelper.GetExpressionText(expression), _implicitRowsAndColumns, htmlAttributes); } /// <summary> /// HTMLs the text editor for. /// </summary> /// <typeparam name="TModel">The type of the model.</typeparam> /// <typeparam name="TProperty">The type of the property.</typeparam> /// <param name="htmlHelper">The HTML helper.</param> /// <param name="expression">The expression.</param> /// <param name="htmlAttributes">The HTML attributes.</param> /// <returns></returns> public static MvcHtmlString HtmlTextEditorFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, object htmlAttributes) { return htmlHelper.HtmlTextEditorFor<TModel, TProperty>(expression, (IDictionary<string, object>)HtmlHelperKludge.AnonymousObjectToHtmlAttributes(htmlAttributes)); } /// <summary> /// HTMLs the text editor for. /// </summary> /// <typeparam name="TModel">The type of the model.</typeparam> /// <typeparam name="TProperty">The type of the property.</typeparam> /// <param name="htmlHelper">The HTML helper.</param> /// <param name="expression">The expression.</param> /// <param name="rows">The rows.</param> /// <param name="columns">The columns.</param> /// <param name="htmlAttributes">The HTML attributes.</param> /// <returns></returns> public static MvcHtmlString HtmlTextEditorFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, int rows, int columns, IDictionary<string, object> htmlAttributes) { if (expression == null) throw new ArgumentNullException("expression"); var editor = GetEditor(htmlAttributes); return editor.HtmlTextAreaHelper(htmlHelper, ModelMetadata.FromLambdaExpression<TModel, TProperty>(expression, htmlHelper.ViewData), ExpressionHelper.GetExpressionText(expression), GetRowsAndColumnsDictionary(rows, columns), htmlAttributes); } /// <summary> /// HTMLs the text editor for. /// </summary> /// <typeparam name="TModel">The type of the model.</typeparam> /// <typeparam name="TProperty">The type of the property.</typeparam> /// <param name="htmlHelper">The HTML helper.</param> /// <param name="expression">The expression.</param> /// <param name="rows">The rows.</param> /// <param name="columns">The columns.</param> /// <param name="htmlAttributes">The HTML attributes.</param> /// <returns></returns> public static MvcHtmlString HtmlTextEditorFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, int rows, int columns, object htmlAttributes) { return htmlHelper.HtmlTextEditorFor<TModel, TProperty>(expression, rows, columns, (IDictionary<string, object>)HtmlHelperKludge.AnonymousObjectToHtmlAttributes(htmlAttributes)); } #region Render Editor internal static Dictionary<string, object> _implicitRowsAndColumns; private const int TextAreaColumns = 20; private const int TextAreaRows = 2; static TextAreaExtensionsEx() { var dictionary = new Dictionary<string, object>(); dictionary.Add("rows", 2.ToString(CultureInfo.InvariantCulture)); dictionary.Add("cols", 20.ToString(CultureInfo.InvariantCulture)); _implicitRowsAndColumns = dictionary; } private static Dictionary<string, object> GetRowsAndColumnsDictionary(int rows, int columns) { if (rows < 0) throw new ArgumentOutOfRangeException("rows"); if (columns < 0) throw new ArgumentOutOfRangeException("columns"); var dictionary = new Dictionary<string, object>(); if (rows > 0) dictionary.Add("rows", rows.ToString(CultureInfo.InvariantCulture)); if (columns > 0) dictionary.Add("cols", columns.ToString(CultureInfo.InvariantCulture)); return dictionary; } private static IHtmlTextEditor GetEditor(IDictionary<string, object> htmlAttributes) { throw new NotSupportedException(); // object value; // bool inDebugMode = (!htmlAttributes.TryGetValue("resourceFolder", out value) ? (bool)value : false); // string htmlTextEditorID = (!htmlAttributes.TryGetValue("htmlTextEditorID", out value) ? (string)value : string.Empty); // string toolbarID = (!htmlAttributes.TryGetValue("toolbarID", out value) ? (string)value : string.Empty); // string resourceFolder = (!htmlAttributes.TryGetValue("resourceFolder", out value) ? (string)value : string.Empty); // // // var htmlTextBoxContext = ServiceLocator.Resolve<IHtmlTextBoxContext>(htmlTextEditorID, toolbarID, resourceFolder); // if (inDebugMode) // htmlTextBoxContext.InDebugMode = true; // return ServiceLocator.Resolve<IHtmlTextEditor>(null, htmlTextBoxContext); } #endregion } }
using System; using Csla; using Csla.Data; using Csla.Serialization; using System.ComponentModel.DataAnnotations; using BusinessObjects.Properties; using System.Linq; using BusinessObjects.CoreBusinessClasses; using DalEf; using System.Collections.Generic; namespace BusinessObjects.Documents { [Serializable] public partial class cDocuments_PriceList_Items: CoreBusinessChildClass<cDocuments_PriceList_Items> { public static readonly PropertyInfo< System.Int32 > IdProperty = RegisterProperty< System.Int32 >(p => p.Id, string.Empty); #if !SILVERLIGHT [System.ComponentModel.DataObjectField(true, true)] #endif public System.Int32 Id { get { return GetProperty(IdProperty); } internal set { SetProperty(IdProperty, value); } } private static readonly PropertyInfo< System.Int32 > documentIdProperty = RegisterProperty<System.Int32>(p => p.DocumentId, string.Empty); [Required(ErrorMessageResourceName = "ErrorMessageRequired", ErrorMessageResourceType = typeof(Resources))] public System.Int32 DocumentId { get { return GetProperty(documentIdProperty); } set { SetProperty(documentIdProperty, value); } } private static readonly PropertyInfo<System.Int32> ordinalProperty = RegisterProperty<System.Int32>(p => p.Ordinal, string.Empty); [Required(ErrorMessageResourceName = "ErrorMessageRequired", ErrorMessageResourceType = typeof(Resources))] public System.Int32 Ordinal { get { return GetProperty(ordinalProperty); } set { SetProperty(ordinalProperty, value); } } private static readonly PropertyInfo< System.Int32 > mDEntities_EntityIdProperty = RegisterProperty<System.Int32>(p => p.MDEntities_EntityId, string.Empty); [Required(ErrorMessageResourceName = "ErrorMessageRequired", ErrorMessageResourceType = typeof(Resources))] public System.Int32 MDEntities_EntityId { get { return GetProperty(mDEntities_EntityIdProperty); } set { SetProperty(mDEntities_EntityIdProperty, value); } } private static readonly PropertyInfo< System.Decimal? > calcualtedWholesalePriceProperty = RegisterProperty<System.Decimal?>(p => p.CalcualtedWholesalePrice, string.Empty, (System.Decimal?)null); public System.Decimal? CalcualtedWholesalePrice { get { return GetProperty(calcualtedWholesalePriceProperty); } set { SetProperty(calcualtedWholesalePriceProperty, value); } } private static readonly PropertyInfo< System.Decimal? > wholesalePriceProperty = RegisterProperty<System.Decimal?>(p => p.WholesalePrice, string.Empty, (System.Decimal?)null); public System.Decimal? WholesalePrice { get { return GetProperty(wholesalePriceProperty); } set { SetProperty(wholesalePriceProperty, value); } } private static readonly PropertyInfo< System.Decimal? > wholesalePriceOption1Property = RegisterProperty<System.Decimal?>(p => p.WholesalePriceOption1, string.Empty, (System.Decimal?)null); public System.Decimal? WholesalePriceOption1 { get { return GetProperty(wholesalePriceOption1Property); } set { SetProperty(wholesalePriceOption1Property, value); } } /// <summary> /// Used for optimistic concurrency. /// </summary> [NotUndoable] internal System.Byte[] LastChanged = new System.Byte[8]; internal static cDocuments_PriceList_Items NewDocuments_PriceList_Items() { return DataPortal.CreateChild<cDocuments_PriceList_Items>(); } public static cDocuments_PriceList_Items GetDocuments_PriceList_Items(Documents_PriceList_ItemsCol data) { return DataPortal.FetchChild<cDocuments_PriceList_Items>(data); } #region Data Access [RunLocal] protected override void Child_Create() { BusinessRules.CheckRules(); } private void Child_Fetch(Documents_PriceList_ItemsCol data) { LoadProperty<int>(IdProperty, data.Id); LoadProperty<byte[]>(EntityKeyDataProperty, Serialize(data.EntityKey)); LoadProperty<int>(documentIdProperty, data.DocumentId); LoadProperty<int>(ordinalProperty, data.Ordinal); LoadProperty<int>(mDEntities_EntityIdProperty, data.MDEntities_EntityId); LoadProperty<decimal?>(calcualtedWholesalePriceProperty, data.CalcualtedWholesalePrice); LoadProperty<decimal?>(wholesalePriceProperty, data.WholesalePrice); LoadProperty<decimal?>(wholesalePriceOption1Property, data.WholesalePriceOption1); LastChanged = data.LastChanged; BusinessRules.CheckRules(); } private void Child_Insert(Documents_PriceList parent) { using (var ctx = ObjectContextManager<DocumentsEntities>.GetManager("DocumentsEntities")) { var data = new Documents_PriceList_ItemsCol(); data.Documents_PriceList = parent; data.Ordinal = ReadProperty<int>(ordinalProperty); data.MDEntities_EntityId = ReadProperty<int>(mDEntities_EntityIdProperty); data.CalcualtedWholesalePrice = ReadProperty<decimal?>(calcualtedWholesalePriceProperty); data.WholesalePrice = ReadProperty<decimal?>(wholesalePriceProperty); data.WholesalePriceOption1 = ReadProperty<decimal?>(wholesalePriceOption1Property); ctx.ObjectContext.AddToDocuments_PriceList_ItemsCol(data); data.PropertyChanged += (o, e) => { if (e.PropertyName == "Id") { LoadProperty<int>(IdProperty, data.Id); LoadProperty<int>(documentIdProperty, data.DocumentId); LoadProperty<byte[]>(EntityKeyDataProperty, Serialize(data.EntityKey)); LastChanged = data.LastChanged; } }; } } private void Child_Update() { using (var ctx = ObjectContextManager<DocumentsEntities>.GetManager("DocumentsEntities")) { var data = new Documents_PriceList_ItemsCol(); data.Id = ReadProperty<int>(IdProperty); data.EntityKey = Deserialize(ReadProperty(EntityKeyDataProperty)) as System.Data.EntityKey; ctx.ObjectContext.Attach(data); data.Ordinal = ReadProperty<int>(ordinalProperty); data.MDEntities_EntityId = ReadProperty<int>(mDEntities_EntityIdProperty); data.CalcualtedWholesalePrice = ReadProperty<decimal?>(calcualtedWholesalePriceProperty); data.WholesalePrice = ReadProperty<decimal?>(wholesalePriceProperty); data.WholesalePriceOption1 = ReadProperty<decimal?>(wholesalePriceOption1Property); data.PropertyChanged += (o, e) => { if (e.PropertyName == "LastChanged") LastChanged = data.LastChanged; }; } } private void Child_DeleteSelf() { using (var ctx = ObjectContextManager<DocumentsEntities>.GetManager("DocumentsEntities")) { var data = new Documents_PriceList_ItemsCol(); data.Id = ReadProperty<int>(IdProperty); data.EntityKey = Deserialize(ReadProperty(EntityKeyDataProperty)) as System.Data.EntityKey; //data.SubjectId = parent.Id; ctx.ObjectContext.Attach(data); ctx.ObjectContext.DeleteObject(data); } } #endregion public void MarkChild() { this.MarkAsChild(); } } [Serializable] public partial class cDocuments_PriceList_ItemsCol : BusinessListBase<cDocuments_PriceList_ItemsCol, cDocuments_PriceList_Items> { internal static cDocuments_PriceList_ItemsCol NewDocuments_PriceList_ItemsCol() { return DataPortal.CreateChild<cDocuments_PriceList_ItemsCol>(); } public static cDocuments_PriceList_ItemsCol GetDocuments_PriceList_ItemsCol(IEnumerable<Documents_PriceList_ItemsCol> dataSet) { var childList = new cDocuments_PriceList_ItemsCol(); childList.Fetch(dataSet); return childList; } #region Data Access private void Fetch(IEnumerable<Documents_PriceList_ItemsCol> dataSet) { RaiseListChangedEvents = false; foreach (var data in dataSet) this.Add(cDocuments_PriceList_Items.GetDocuments_PriceList_Items(data)); RaiseListChangedEvents = true; } #endregion //Data Access } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections; using System.Collections.Generic; using Xunit; using SortedList_SortedListUtils; namespace SortedListRemove { public class Driver<K, V> where K : IComparableValue { private Test m_test; public Driver(Test test) { m_test = test; } public void BasicRemove(K[] keys, V[] values) { SortedList<K, V> tbl = new SortedList<K, V>(new ValueKeyComparer<K>()); for (int i = 0; i < keys.Length; i++) { tbl.Add(keys[i], values[i]); } m_test.Eval(tbl.Count == keys.Length); for (int i = 0; i < keys.Length; i++) { m_test.Eval(tbl.Remove(keys[i])); } m_test.Eval(tbl.Count == 0); } public void RemoveNegative(K[] keys, V[] values, K[] missingkeys) { SortedList<K, V> tbl = new SortedList<K, V>(new ValueKeyComparer<K>()); for (int i = 0; i < keys.Length; i++) { tbl.Add(keys[i], values[i]); } m_test.Eval(tbl.Count == keys.Length); for (int i = 0; i < missingkeys.Length; i++) { m_test.Eval(false == tbl.Remove(missingkeys[i])); } m_test.Eval(tbl.Count == keys.Length); } public void RemoveSameKey(K[] keys, V[] values, int index, int repeat) { SortedList<K, V> tbl = new SortedList<K, V>(new ValueKeyComparer<K>()); for (int i = 0; i < keys.Length; i++) { tbl.Add(keys[i], values[i]); } m_test.Eval(tbl.Count == keys.Length); m_test.Eval(tbl.Remove(keys[index])); for (int i = 0; i < repeat; i++) { m_test.Eval(false == tbl.Remove(keys[index])); } m_test.Eval(tbl.Count == keys.Length - 1); } public void AddRemoveSameKey(K[] keys, V[] values, int index, int repeat) { SortedList<K, V> tbl = new SortedList<K, V>(new ValueKeyComparer<K>()); for (int i = 0; i < keys.Length; i++) { tbl.Add(keys[i], values[i]); } m_test.Eval(tbl.Count == keys.Length); m_test.Eval(tbl.Remove(keys[index])); for (int i = 0; i < repeat; i++) { tbl.Add(keys[index], values[index]); m_test.Eval(tbl.Remove(keys[index])); } m_test.Eval(tbl.Count == keys.Length - 1); } public void RemoveValidationsRefType(K[] keys, V[] values) { SortedList<K, V> tbl = new SortedList<K, V>(new ValueKeyComparer<K>()); for (int i = 0; i < keys.Length; i++) { tbl.Add(keys[i], values[i]); } // //try null key // try { tbl.Remove((K)(object)null); m_test.Eval(false, "Excepted ArgumentException but did not get an Exception when trying to remove null."); } catch (ArgumentException) { m_test.Eval(true); } catch (Exception E) { m_test.Eval(false, "Excepted ArgumentException but got unknown Exception when trying to remove null: " + E); } } public void NonGenericIDictionaryBasicRemove(K[] keys, V[] values) { SortedList<K, V> tbl = new SortedList<K, V>(new ValueKeyComparer<K>()); IDictionary _idic = tbl; for (int i = 0; i < keys.Length; i++) { tbl.Add(keys[i], values[i]); } m_test.Eval(tbl.Count == keys.Length); for (int i = 0; i < keys.Length; i++) { _idic.Remove(keys[i]); m_test.Eval(!_idic.Contains(keys[i]), "Expected " + keys[i] + " to not still exist, but Contains returned true."); } m_test.Eval(tbl.Count == 0); } public void NonGenericIDictionaryRemoveNegative(K[] keys, V[] values, K[] missingkeys) { SortedList<K, V> tbl = new SortedList<K, V>(new ValueKeyComparer<K>()); IDictionary _idic = tbl; for (int i = 0; i < keys.Length; i++) { tbl.Add(keys[i], values[i]); } m_test.Eval(tbl.Count == keys.Length); for (int i = 0; i < missingkeys.Length; i++) { _idic.Remove(missingkeys[i]); m_test.Eval(!_idic.Contains(missingkeys[i]), "Expected " + missingkeys[i] + " to not still exist, but Contains returned true."); } m_test.Eval(tbl.Count == keys.Length); } public void NonGenericIDictionaryRemoveSameKey(K[] keys, V[] values, int index, int repeat) { SortedList<K, V> tbl = new SortedList<K, V>(new ValueKeyComparer<K>()); IDictionary _idic = tbl; for (int i = 0; i < keys.Length; i++) { tbl.Add(keys[i], values[i]); } m_test.Eval(tbl.Count == keys.Length); _idic.Remove(keys[index]); m_test.Eval(!_idic.Contains(keys[index]), "Expected " + keys[index] + " to not still exist, but Contains returned true."); for (int i = 0; i < repeat; i++) { _idic.Remove(keys[index]); m_test.Eval(!_idic.Contains(keys[index]), "Expected " + keys[index] + " to not still exist, but Contains returned true."); } m_test.Eval(tbl.Count == keys.Length - 1); } public void NonGenericIDictionaryAddRemoveSameKey(K[] keys, V[] values, int index, int repeat) { SortedList<K, V> tbl = new SortedList<K, V>(new ValueKeyComparer<K>()); IDictionary _idic = tbl; for (int i = 0; i < keys.Length; i++) { tbl.Add(keys[i], values[i]); } m_test.Eval(tbl.Count == keys.Length); _idic.Remove(keys[index]); m_test.Eval(!_idic.Contains(keys[index]), "Expected " + keys[index] + " to not still exist, but Contains returned true."); for (int i = 0; i < repeat; i++) { tbl.Add(keys[index], values[index]); _idic.Remove(keys[index]); m_test.Eval(!_idic.Contains(keys[index]), "Expected " + keys[index] + " to not still exist, but Contains returned true."); } m_test.Eval(tbl.Count == keys.Length - 1); } public void NonGenericIDictionaryRemoveValidations(K[] keys, V[] values) { SortedList<K, V> tbl = new SortedList<K, V>(new ValueKeyComparer<K>()); IDictionary _idic = tbl; for (int i = 0; i < keys.Length; i++) { tbl.Add(keys[i], values[i]); } // //try null key // try { _idic.Remove(null); m_test.Eval(false, "Excepted ArgumentException but did not get an Exception when trying to remove null."); } catch (ArgumentNullException) { m_test.Eval(true); } catch (Exception E) { m_test.Eval(false, "Excepted ArgumentException but got unknown Exception when trying to remove null: " + E); } try { _idic.Remove(new Random(-55)); } catch (Exception E) { m_test.Eval(false, "Excepted ArgumentException but got unknown Exception when trying to remove null: " + E); } } } public class Remove { [Fact] public static void RemoveMain() { Test test = new Test(); Driver<RefX1<int>, ValX1<string>> IntDriver = new Driver<RefX1<int>, ValX1<string>>(test); RefX1<int>[] intArr1 = new RefX1<int>[100]; for (int i = 0; i < 100; i++) { intArr1[i] = new RefX1<int>(i); } RefX1<int>[] intArr2 = new RefX1<int>[10]; for (int i = 0; i < 10; i++) { intArr2[i] = new RefX1<int>(i + 100); } Driver<ValX1<string>, RefX1<int>> StringDriver = new Driver<ValX1<string>, RefX1<int>>(test); ValX1<string>[] stringArr1 = new ValX1<string>[100]; for (int i = 0; i < 100; i++) { stringArr1[i] = new ValX1<string>("SomeTestString" + i.ToString()); } ValX1<string>[] stringArr2 = new ValX1<string>[10]; for (int i = 0; i < 10; i++) { stringArr2[i] = new ValX1<string>("SomeTestString" + (i + 100).ToString()); } //Ref<val>,Val<Ref> IntDriver.BasicRemove(intArr1, stringArr1); IntDriver.RemoveNegative(intArr1, stringArr1, intArr2); IntDriver.RemoveNegative(new RefX1<int>[] { }, new ValX1<string>[] { }, intArr2); IntDriver.RemoveSameKey(intArr1, stringArr1, 0, 2); IntDriver.RemoveSameKey(intArr1, stringArr1, 99, 3); IntDriver.RemoveSameKey(intArr1, stringArr1, 50, 4); IntDriver.RemoveSameKey(intArr1, stringArr1, 1, 5); IntDriver.RemoveSameKey(intArr1, stringArr1, 98, 6); IntDriver.AddRemoveSameKey(intArr1, stringArr1, 0, 2); IntDriver.AddRemoveSameKey(intArr1, stringArr1, 99, 3); IntDriver.AddRemoveSameKey(intArr1, stringArr1, 50, 4); IntDriver.AddRemoveSameKey(intArr1, stringArr1, 1, 5); IntDriver.AddRemoveSameKey(intArr1, stringArr1, 98, 6); IntDriver.RemoveValidationsRefType(intArr1, stringArr1); IntDriver.RemoveValidationsRefType(new RefX1<int>[] { }, new ValX1<string>[] { }); IntDriver.NonGenericIDictionaryBasicRemove(intArr1, stringArr1); IntDriver.NonGenericIDictionaryRemoveNegative(intArr1, stringArr1, intArr2); IntDriver.NonGenericIDictionaryRemoveNegative(new RefX1<int>[] { }, new ValX1<string>[] { }, intArr2); IntDriver.NonGenericIDictionaryRemoveSameKey(intArr1, stringArr1, 0, 2); IntDriver.NonGenericIDictionaryRemoveSameKey(intArr1, stringArr1, 99, 3); IntDriver.NonGenericIDictionaryRemoveSameKey(intArr1, stringArr1, 50, 4); IntDriver.NonGenericIDictionaryRemoveSameKey(intArr1, stringArr1, 1, 5); IntDriver.NonGenericIDictionaryRemoveSameKey(intArr1, stringArr1, 98, 6); IntDriver.NonGenericIDictionaryAddRemoveSameKey(intArr1, stringArr1, 0, 2); IntDriver.NonGenericIDictionaryAddRemoveSameKey(intArr1, stringArr1, 99, 3); IntDriver.NonGenericIDictionaryAddRemoveSameKey(intArr1, stringArr1, 50, 4); IntDriver.NonGenericIDictionaryAddRemoveSameKey(intArr1, stringArr1, 1, 5); IntDriver.NonGenericIDictionaryAddRemoveSameKey(intArr1, stringArr1, 98, 6); IntDriver.NonGenericIDictionaryRemoveValidations(intArr1, stringArr1); IntDriver.NonGenericIDictionaryRemoveValidations(new RefX1<int>[] { }, new ValX1<string>[] { }); //Val<Ref>,Ref<Val> StringDriver.BasicRemove(stringArr1, intArr1); StringDriver.RemoveNegative(stringArr1, intArr1, stringArr2); StringDriver.RemoveNegative(new ValX1<string>[] { }, new RefX1<int>[] { }, stringArr2); StringDriver.RemoveSameKey(stringArr1, intArr1, 0, 2); StringDriver.RemoveSameKey(stringArr1, intArr1, 99, 3); StringDriver.RemoveSameKey(stringArr1, intArr1, 50, 4); StringDriver.RemoveSameKey(stringArr1, intArr1, 1, 5); StringDriver.RemoveSameKey(stringArr1, intArr1, 98, 6); StringDriver.AddRemoveSameKey(stringArr1, intArr1, 0, 2); StringDriver.AddRemoveSameKey(stringArr1, intArr1, 99, 3); StringDriver.AddRemoveSameKey(stringArr1, intArr1, 50, 4); StringDriver.AddRemoveSameKey(stringArr1, intArr1, 1, 5); StringDriver.AddRemoveSameKey(stringArr1, intArr1, 98, 6); StringDriver.NonGenericIDictionaryBasicRemove(stringArr1, intArr1); StringDriver.NonGenericIDictionaryRemoveNegative(stringArr1, intArr1, stringArr2); StringDriver.NonGenericIDictionaryRemoveNegative(new ValX1<string>[] { }, new RefX1<int>[] { }, stringArr2); StringDriver.NonGenericIDictionaryRemoveSameKey(stringArr1, intArr1, 0, 2); StringDriver.NonGenericIDictionaryRemoveSameKey(stringArr1, intArr1, 99, 3); StringDriver.NonGenericIDictionaryRemoveSameKey(stringArr1, intArr1, 50, 4); StringDriver.NonGenericIDictionaryRemoveSameKey(stringArr1, intArr1, 1, 5); StringDriver.NonGenericIDictionaryRemoveSameKey(stringArr1, intArr1, 98, 6); StringDriver.NonGenericIDictionaryAddRemoveSameKey(stringArr1, intArr1, 0, 2); StringDriver.NonGenericIDictionaryAddRemoveSameKey(stringArr1, intArr1, 99, 3); StringDriver.NonGenericIDictionaryAddRemoveSameKey(stringArr1, intArr1, 50, 4); StringDriver.NonGenericIDictionaryAddRemoveSameKey(stringArr1, intArr1, 1, 5); StringDriver.NonGenericIDictionaryAddRemoveSameKey(stringArr1, intArr1, 98, 6); StringDriver.NonGenericIDictionaryRemoveValidations(stringArr1, intArr1); StringDriver.NonGenericIDictionaryRemoveValidations(new ValX1<string>[] { }, new RefX1<int>[] { }); Assert.True(test.result); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace OwinNinjectProject.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. using System; using System.Runtime.Caching.Configuration; using System.Runtime.Caching.Hosting; using System.Diagnostics; using System.Security; using System.Threading; namespace System.Runtime.Caching { // CacheMemoryMonitor uses the internal System.SizedReference type to determine // the size of the cache itselt, and helps us know when to drop entries to avoid // exceeding the cache's memory limit. The limit is configurable (see ConfigUtil.cs). internal sealed class CacheMemoryMonitor : MemoryMonitor, IDisposable { private const long PRIVATE_BYTES_LIMIT_2GB = 800 * MEGABYTE; private const long PRIVATE_BYTES_LIMIT_3GB = 1800 * MEGABYTE; private const long PRIVATE_BYTES_LIMIT_64BIT = 1L * TERABYTE; private const int SAMPLE_COUNT = 2; private static IMemoryCacheManager s_memoryCacheManager; private static long s_autoPrivateBytesLimit = -1; private static long s_effectiveProcessMemoryLimit = -1; private readonly MemoryCache _memoryCache; private readonly long[] _cacheSizeSamples; private readonly DateTime[] _cacheSizeSampleTimes; private int _idx; private SRefMultiple _sizedRefMultiple; private int _gen2Count; private long _memoryLimit; internal long MemoryLimit { get { return _memoryLimit; } } private CacheMemoryMonitor() { // hide default ctor } internal CacheMemoryMonitor(MemoryCache memoryCache, int cacheMemoryLimitMegabytes) { _memoryCache = memoryCache; _gen2Count = GC.CollectionCount(2); _cacheSizeSamples = new long[SAMPLE_COUNT]; _cacheSizeSampleTimes = new DateTime[SAMPLE_COUNT]; if (memoryCache.UseMemoryCacheManager) { InitMemoryCacheManager(); // This magic thing connects us to ObjectCacheHost magically. :/ } InitDisposableMembers(cacheMemoryLimitMegabytes); } private void InitDisposableMembers(int cacheMemoryLimitMegabytes) { bool dispose = true; try { _sizedRefMultiple = new SRefMultiple(_memoryCache.AllSRefTargets); SetLimit(cacheMemoryLimitMegabytes); InitHistory(); dispose = false; } finally { if (dispose) { Dispose(); } } } // Auto-generate the private bytes limit: // - On 64bit, the auto value is MIN(60% physical_ram, 1 TB) // - On x86, for 2GB, the auto value is MIN(60% physical_ram, 800 MB) // - On x86, for 3GB, the auto value is MIN(60% physical_ram, 1800 MB) // // - If it's not a hosted environment (e.g. console app), the 60% in the above // formulas will become 100% because in un-hosted environment we don't launch // other processes such as compiler, etc. private static long AutoPrivateBytesLimit { get { long memoryLimit = s_autoPrivateBytesLimit; if (memoryLimit == -1) { bool is64bit = (IntPtr.Size == 8); long totalPhysical = TotalPhysical; long totalVirtual = TotalVirtual; if (totalPhysical != 0) { long recommendedPrivateByteLimit; if (is64bit) { recommendedPrivateByteLimit = PRIVATE_BYTES_LIMIT_64BIT; } else { // Figure out if it's 2GB or 3GB if (totalVirtual > 2 * GIGABYTE) { recommendedPrivateByteLimit = PRIVATE_BYTES_LIMIT_3GB; } else { recommendedPrivateByteLimit = PRIVATE_BYTES_LIMIT_2GB; } } // use 60% of physical RAM long usableMemory = totalPhysical * 3 / 5; memoryLimit = Math.Min(usableMemory, recommendedPrivateByteLimit); } else { // If GlobalMemoryStatusEx fails, we'll use these as our auto-gen private bytes limit memoryLimit = is64bit ? PRIVATE_BYTES_LIMIT_64BIT : PRIVATE_BYTES_LIMIT_2GB; } Interlocked.Exchange(ref s_autoPrivateBytesLimit, memoryLimit); } return memoryLimit; } } public void Dispose() { SRefMultiple sref = _sizedRefMultiple; if (sref != null && Interlocked.CompareExchange(ref _sizedRefMultiple, null, sref) == sref) { sref.Dispose(); } IMemoryCacheManager memoryCacheManager = s_memoryCacheManager; if (memoryCacheManager != null) { memoryCacheManager.ReleaseCache(_memoryCache); } } internal static long EffectiveProcessMemoryLimit { get { long memoryLimit = s_effectiveProcessMemoryLimit; if (memoryLimit == -1) { memoryLimit = AutoPrivateBytesLimit; Interlocked.Exchange(ref s_effectiveProcessMemoryLimit, memoryLimit); } return memoryLimit; } } protected override int GetCurrentPressure() { // Call GetUpdatedTotalCacheSize to update the total // cache size, if there has been a recent Gen 2 Collection. // This update must happen, otherwise the CacheManager won't // know the total cache size. int gen2Count = GC.CollectionCount(2); SRefMultiple sref = _sizedRefMultiple; if (gen2Count != _gen2Count && sref != null) { // update _gen2Count _gen2Count = gen2Count; // the SizedRef is only updated after a Gen2 Collection // increment the index (it's either 1 or 0) Debug.Assert(SAMPLE_COUNT == 2); _idx = _idx ^ 1; // remember the sample time _cacheSizeSampleTimes[_idx] = DateTime.UtcNow; // remember the sample value _cacheSizeSamples[_idx] = sref.ApproximateSize; Dbg.Trace("MemoryCacheStats", "SizedRef.ApproximateSize=" + _cacheSizeSamples[_idx]); IMemoryCacheManager memoryCacheManager = s_memoryCacheManager; if (memoryCacheManager != null) { memoryCacheManager.UpdateCacheSize(_cacheSizeSamples[_idx], _memoryCache); } } // if there's no memory limit, then there's nothing more to do if (_memoryLimit <= 0) { return 0; } long cacheSize = _cacheSizeSamples[_idx]; // use _memoryLimit as an upper bound so that pressure is a percentage (between 0 and 100, inclusive). if (cacheSize > _memoryLimit) { cacheSize = _memoryLimit; } // PerfCounter: Cache Percentage Process Memory Limit Used // = memory used by this process / process memory limit at pressureHigh // Set private bytes used in kilobytes because the counter is a DWORD // PerfCounters.SetCounter(AppPerfCounter.CACHE_PERCENT_PROC_MEM_LIMIT_USED, (int)(cacheSize >> KILOBYTE_SHIFT)); int result = (int)(cacheSize * 100 / _memoryLimit); return result; } internal override int GetPercentToTrim(DateTime lastTrimTime, int lastTrimPercent) { int percent = 0; if (IsAboveHighPressure()) { long cacheSize = _cacheSizeSamples[_idx]; if (cacheSize > _memoryLimit) { percent = Math.Min(100, (int)((cacheSize - _memoryLimit) * 100L / cacheSize)); } #if PERF Debug.WriteLine(string.Format("CacheMemoryMonitor.GetPercentToTrim: percent={0:N}, lastTrimPercent={1:N}{Environment.NewLine}", percent, lastTrimPercent)); #endif } return percent; } internal void SetLimit(int cacheMemoryLimitMegabytes) { long cacheMemoryLimit = ((long)cacheMemoryLimitMegabytes) << MEGABYTE_SHIFT; _memoryLimit = cacheMemoryLimit != 0 ? cacheMemoryLimit : EffectiveProcessMemoryLimit; Dbg.Trace("MemoryCacheStats", "CacheMemoryMonitor.SetLimit: _memoryLimit=" + (_memoryLimit >> MEGABYTE_SHIFT) + "Mb"); if (_memoryLimit > 0) { _pressureHigh = 100; _pressureLow = 80; } else { _pressureHigh = 99; _pressureLow = 97; } Dbg.Trace("MemoryCacheStats", "CacheMemoryMonitor.SetLimit: _pressureHigh=" + _pressureHigh + ", _pressureLow=" + _pressureLow); } private static void InitMemoryCacheManager() { if (s_memoryCacheManager == null) { IMemoryCacheManager memoryCacheManager = null; IServiceProvider host = ObjectCache.Host; if (host != null) { memoryCacheManager = host.GetService(typeof(IMemoryCacheManager)) as IMemoryCacheManager; } if (memoryCacheManager != null) { Interlocked.CompareExchange(ref s_memoryCacheManager, memoryCacheManager, null); } } } } }
// <copyright file="ResidualStopCriterion.cs" company="Math.NET"> // Math.NET Numerics, part of the Math.NET Project // http://numerics.mathdotnet.com // http://github.com/mathnet/mathnet-numerics // // Copyright (c) 2009-2014 Math.NET // // 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.Diagnostics; using MathNet.Numerics.Properties; namespace MathNet.Numerics.LinearAlgebra.Solvers { /// <summary> /// Defines an <see cref="IIterationStopCriterion{T}"/> that monitors residuals as stop criterion. /// </summary> public sealed class ResidualStopCriterion<T> : IIterationStopCriterion<T> where T : struct, IEquatable<T>, IFormattable { /// <summary> /// The maximum value for the residual below which the calculation is considered converged. /// </summary> double _maximum; /// <summary> /// The minimum number of iterations for which the residual has to be below the maximum before /// the calculation is considered converged. /// </summary> int _minimumIterationsBelowMaximum; /// <summary> /// The status of the calculation /// </summary> IterationStatus _status = IterationStatus.Continue; /// <summary> /// The number of iterations since the residuals got below the maximum. /// </summary> int _iterationCount; /// <summary> /// The iteration number of the last iteration. /// </summary> int _lastIteration = -1; /// <summary> /// Initializes a new instance of the <see cref="ResidualStopCriterion{T}"/> class with the specified /// maximum residual and minimum number of iterations. /// </summary> /// <param name="maximum"> /// The maximum value for the residual below which the calculation is considered converged. /// </param> /// <param name="minimumIterationsBelowMaximum"> /// The minimum number of iterations for which the residual has to be below the maximum before /// the calculation is considered converged. /// </param> public ResidualStopCriterion(double maximum, int minimumIterationsBelowMaximum = 0) { if (maximum < 0) { throw new ArgumentOutOfRangeException("maximum"); } if (minimumIterationsBelowMaximum < 0) { throw new ArgumentOutOfRangeException("minimumIterationsBelowMaximum"); } _maximum = maximum; _minimumIterationsBelowMaximum = minimumIterationsBelowMaximum; } /// <summary> /// Gets or sets the maximum value for the residual below which the calculation is considered /// converged. /// </summary> /// <exception cref="ArgumentOutOfRangeException">Thrown if the <c>Maximum</c> is set to a negative value.</exception> public double Maximum { [DebuggerStepThrough] get { return _maximum; } [DebuggerStepThrough] set { if (value < 0) { throw new ArgumentOutOfRangeException("value"); } _maximum = value; } } /// <summary> /// Gets or sets the minimum number of iterations for which the residual has to be /// below the maximum before the calculation is considered converged. /// </summary> /// <exception cref="ArgumentOutOfRangeException">Thrown if the <c>BelowMaximumFor</c> is set to a value less than 1.</exception> public int MinimumIterationsBelowMaximum { [DebuggerStepThrough] get { return _minimumIterationsBelowMaximum; } [DebuggerStepThrough] set { if (value < 0) { throw new ArgumentOutOfRangeException("value"); } _minimumIterationsBelowMaximum = value; } } /// <summary> /// Determines the status of the iterative calculation based on the stop criteria stored /// by the current <see cref="IIterationStopCriterion{T}"/>. Result is set into <c>Status</c> field. /// </summary> /// <param name="iterationNumber">The number of iterations that have passed so far.</param> /// <param name="solutionVector">The vector containing the current solution values.</param> /// <param name="sourceVector">The right hand side vector.</param> /// <param name="residualVector">The vector containing the current residual vectors.</param> /// <remarks> /// The individual stop criteria may internally track the progress of the calculation based /// on the invocation of this method. Therefore this method should only be called if the /// calculation has moved forwards at least one step. /// </remarks> public IterationStatus DetermineStatus(int iterationNumber, Vector<T> solutionVector, Vector<T> sourceVector, Vector<T> residualVector) { if (iterationNumber < 0) { throw new ArgumentOutOfRangeException("iterationNumber"); } if (solutionVector.Count != sourceVector.Count) { throw new ArgumentException(Resources.ArgumentVectorsSameLength, "sourceVector"); } if (solutionVector.Count != residualVector.Count) { throw new ArgumentException(Resources.ArgumentVectorsSameLength, "residualVector"); } // Store the infinity norms of both the solution and residual vectors // These values will be used to calculate the relative drop in residuals // later on. var residualNorm = residualVector.InfinityNorm(); // This is criterion 1 from Templates for the solution of linear systems. // The problem with this criterion is that it's not limiting enough. For now // we won't use it. Later on we might get back to it. // return mMaximumResidual * (System.Math.Abs(mMatrixNorm) * System.Math.Abs(solutionNorm) + System.Math.Abs(mVectorNorm)); // For now use criterion 2 from Templates for the solution of linear systems. See page 60. // Check the residuals by calculating: // ||r_i|| <= stop_tol * ||b|| var stopCriterion = _maximum*sourceVector.InfinityNorm(); // First check that we have real numbers not NaN's. // NaN's can occur when the iterative process diverges so we // stop if that is the case. if (double.IsNaN(stopCriterion) || double.IsNaN(residualNorm)) { _iterationCount = 0; _status = IterationStatus.Diverged; return _status; } // ||r_i|| <= stop_tol * ||b|| // Stop the calculation if it's clearly smaller than the tolerance if (residualNorm < stopCriterion) { if (_lastIteration <= iterationNumber) { _iterationCount = iterationNumber - _lastIteration; _status = _iterationCount >= _minimumIterationsBelowMaximum ? IterationStatus.Converged : IterationStatus.Continue; } } else { _iterationCount = 0; _status = IterationStatus.Continue; } _lastIteration = iterationNumber; return _status; } /// <summary> /// Gets the current calculation status. /// </summary> public IterationStatus Status { [DebuggerStepThrough] get { return _status; } } /// <summary> /// Resets the <see cref="IIterationStopCriterion{T}"/> to the pre-calculation state. /// </summary> public void Reset() { _status = IterationStatus.Continue; _iterationCount = 0; _lastIteration = -1; } /// <summary> /// Clones the current <see cref="ResidualStopCriterion{T}"/> and its settings. /// </summary> /// <returns>A new instance of the <see cref="ResidualStopCriterion{T}"/> class.</returns> public IIterationStopCriterion<T> Clone() { return new ResidualStopCriterion<T>(_maximum, _minimumIterationsBelowMaximum); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.IO; using System.Text; using System.Threading.Tasks; using Xunit; public class ReadAndWrite { [Fact] public static void WriteOverloads() { TextWriter savedStandardOutput = Console.Out; try { using (MemoryStream memStream = new MemoryStream()) { using (StreamWriter sw = new StreamWriter(memStream)) { Console.SetOut(sw); WriteCore(); } } } finally { Console.SetOut(savedStandardOutput); } } [Fact] public static void WriteToOutputStream_EmptyArray() { Stream outStream = Console.OpenStandardOutput(); outStream.Write(new byte[] { }, 0, 0); } [Fact] [OuterLoop] public static void WriteOverloadsToRealConsole() { WriteCore(); } [Fact] public static void WriteLineOverloads() { TextWriter savedStandardOutput = Console.Out; try { using (MemoryStream memStream = new MemoryStream()) { using (StreamWriter sw = new StreamWriter(memStream)) { Console.SetOut(sw); WriteLineCore(); } } } finally { Console.SetOut(savedStandardOutput); } } [Fact] [OuterLoop] public static void WriteLineOverloadsToRealConsole() { WriteLineCore(); } private static void WriteCore() { // We just want to ensure none of these throw exceptions, we don't actually validate // what was written. Console.Write("{0}", 32); Console.Write("{0}", null); Console.Write("{0} {1}", 32, "Hello"); Console.Write("{0}", null, null); Console.Write("{0} {1} {2}", 32, "Hello", (uint)50); Console.Write("{0}", null, null, null); Console.Write("{0} {1} {2} {3}", 32, "Hello", (uint)50, (ulong)5); Console.Write("{0}", null, null, null, null); Console.Write("{0} {1} {2} {3} {4}", 32, "Hello", (uint)50, (ulong)5, 'a'); Console.Write("{0}", null, null, null, null, null); Console.Write(true); Console.Write('a'); Console.Write(new char[] { 'a', 'b', 'c', 'd', }); Console.Write(new char[] { 'a', 'b', 'c', 'd', }, 1, 2); Console.Write(1.23d); Console.Write(123.456M); Console.Write(1.234f); Console.Write(39); Console.Write(50u); Console.Write(50L); Console.Write(50UL); Console.Write(new object()); Console.Write("Hello World"); } private static void WriteLineCore() { Assert.Equal(Environment.NewLine, Console.Out.NewLine); Console.Out.NewLine = "abcd"; Assert.Equal("abcd", Console.Out.NewLine); Console.Out.NewLine = Environment.NewLine; // We just want to ensure none of these throw exceptions, we don't actually validate // what was written. Console.WriteLine(); Console.WriteLine("{0}", 32); Console.WriteLine("{0}", null); Console.WriteLine("{0} {1}", 32, "Hello"); Console.WriteLine("{0}", null, null); Console.WriteLine("{0} {1} {2}", 32, "Hello", (uint)50); Console.WriteLine("{0}", null, null, null); Console.WriteLine("{0} {1} {2} {3}", 32, "Hello", (uint)50, (ulong)5); Console.WriteLine("{0}", null, null, null, null); Console.WriteLine("{0} {1} {2} {3} {4}", 32, "Hello", (uint)50, (ulong)5, 'a'); Console.WriteLine("{0}", null, null, null, null, null); Console.WriteLine(true); Console.WriteLine('a'); Console.WriteLine(new char[] { 'a', 'b', 'c', 'd', }); Console.WriteLine(new char[] { 'a', 'b', 'c', 'd', }, 1, 2); Console.WriteLine(1.23); Console.WriteLine(123.456M); Console.WriteLine(1.234f); Console.WriteLine(39); Console.WriteLine(50u); Console.WriteLine(50L); Console.WriteLine(50UL); Console.WriteLine(new object()); Console.WriteLine("Hello World"); } [Fact] public static async Task OutWriteAndWriteLineOverloads() { TextWriter savedStandardOutput = Console.Out; try { using (var sw = new StreamWriter(new MemoryStream())) { Console.SetOut(sw); TextWriter writer = Console.Out; Assert.NotNull(writer); Assert.NotEqual(writer, sw); // the writer we provide gets wrapped // We just want to ensure none of these throw exceptions, we don't actually validate // what was written. writer.Write("{0}", 32); writer.Write("{0} {1}", 32, "Hello"); writer.Write("{0} {1} {2}", 32, "Hello", (uint)50); writer.Write("{0} {1} {2} {3}", 32, "Hello", (uint)50, (ulong)5); writer.Write("{0} {1} {2} {3} {4}", 32, "Hello", (uint)50, (ulong)5, 'a'); writer.Write(true); writer.Write('a'); writer.Write(new char[] { 'a', 'b', 'c', 'd', }); writer.Write(new char[] { 'a', 'b', 'c', 'd', }, 1, 2); writer.Write(1.23d); writer.Write(123.456M); writer.Write(1.234f); writer.Write(39); writer.Write(50u); writer.Write(50L); writer.Write(50UL); writer.Write(new object()); writer.Write("Hello World"); writer.Flush(); await writer.WriteAsync('c'); await writer.WriteAsync(new char[] { 'a', 'b', 'c', 'd' }); await writer.WriteAsync(new char[] { 'a', 'b', 'c', 'd' }, 1, 2); await writer.WriteAsync("Hello World"); await writer.WriteLineAsync('c'); await writer.WriteLineAsync(new char[] { 'a', 'b', 'c', 'd' }); await writer.WriteLineAsync(new char[] { 'a', 'b', 'c', 'd' }, 1, 2); await writer.WriteLineAsync("Hello World"); await writer.FlushAsync(); } } finally { Console.SetOut(savedStandardOutput); } } private static unsafe void ValidateConsoleEncoding(Encoding encoding) { Assert.NotNull(encoding); // There's not much validation we can do, but we can at least invoke members // to ensure they don't throw exceptions as they delegate to the underlying // encoding wrapped by ConsoleEncoding. Assert.False(string.IsNullOrWhiteSpace(encoding.EncodingName)); Assert.False(string.IsNullOrWhiteSpace(encoding.WebName)); Assert.True(encoding.CodePage >= 0); bool ignored = encoding.IsSingleByte; // And we can validate that the encoding is self-consistent by roundtripping // data between chars and bytes. string str = "This is the input string."; char[] strAsChars = str.ToCharArray(); byte[] strAsBytes = encoding.GetBytes(str); Assert.Equal(strAsBytes.Length, encoding.GetByteCount(str)); Assert.True(encoding.GetMaxByteCount(str.Length) >= strAsBytes.Length); Assert.Equal(str, encoding.GetString(strAsBytes)); Assert.Equal(str, encoding.GetString(strAsBytes, 0, strAsBytes.Length)); Assert.Equal(str, new string(encoding.GetChars(strAsBytes))); Assert.Equal(str, new string(encoding.GetChars(strAsBytes, 0, strAsBytes.Length))); fixed (byte* bytesPtr = strAsBytes) { char[] outputArr = new char[encoding.GetMaxCharCount(strAsBytes.Length)]; int len = encoding.GetChars(strAsBytes, 0, strAsBytes.Length, outputArr, 0); Assert.Equal(str, new string(outputArr, 0, len)); Assert.Equal(len, encoding.GetCharCount(strAsBytes)); Assert.Equal(len, encoding.GetCharCount(strAsBytes, 0, strAsBytes.Length)); fixed (char* charsPtr = outputArr) { len = encoding.GetChars(bytesPtr, strAsBytes.Length, charsPtr, outputArr.Length); Assert.Equal(str, new string(charsPtr, 0, len)); Assert.Equal(len, encoding.GetCharCount(bytesPtr, strAsBytes.Length)); } Assert.Equal(str, encoding.GetString(bytesPtr, strAsBytes.Length)); } Assert.Equal(strAsBytes, encoding.GetBytes(strAsChars)); Assert.Equal(strAsBytes, encoding.GetBytes(strAsChars, 0, strAsChars.Length)); Assert.Equal(strAsBytes.Length, encoding.GetByteCount(strAsChars)); Assert.Equal(strAsBytes.Length, encoding.GetByteCount(strAsChars, 0, strAsChars.Length)); fixed (char* charsPtr = strAsChars) { Assert.Equal(strAsBytes.Length, encoding.GetByteCount(charsPtr, strAsChars.Length)); byte[] outputArr = new byte[encoding.GetMaxByteCount(strAsChars.Length)]; Assert.Equal(strAsBytes.Length, encoding.GetBytes(strAsChars, 0, strAsChars.Length, outputArr, 0)); fixed (byte* bytesPtr = outputArr) { Assert.Equal(strAsBytes.Length, encoding.GetBytes(charsPtr, strAsChars.Length, bytesPtr, outputArr.Length)); } Assert.Equal(strAsBytes.Length, encoding.GetBytes(str, 0, str.Length, outputArr, 0)); } } [Fact] public static unsafe void OutputEncodingPreamble() { Encoding curEncoding = Console.OutputEncoding; try { Encoding encoding = Console.Out.Encoding; // The primary purpose of ConsoleEncoding is to return an empty preamble. Assert.Equal(Array.Empty<byte>(), encoding.GetPreamble()); // Try setting the ConsoleEncoding to something else and see if it works. Console.OutputEncoding = Encoding.Unicode; // The primary purpose of ConsoleEncoding is to return an empty preamble. Assert.Equal(Array.Empty<byte>(), Console.Out.Encoding.GetPreamble()); } finally { Console.OutputEncoding = curEncoding; } } [Fact] public static unsafe void OutputEncoding() { Encoding curEncoding = Console.OutputEncoding; try { Assert.Same(Console.Out, Console.Out); Encoding encoding = Console.Out.Encoding; Assert.NotNull(encoding); Assert.Same(encoding, Console.Out.Encoding); ValidateConsoleEncoding(encoding); // Try setting the ConsoleEncoding to something else and see if it works. Console.OutputEncoding = Encoding.Unicode; Assert.Equal(Console.OutputEncoding.CodePage, Encoding.Unicode.CodePage); ValidateConsoleEncoding(Console.Out.Encoding); } finally { Console.OutputEncoding = curEncoding; } } static readonly string[] s_testLines = new string[] { "3232 Hello32 Hello 5032 Hello 50 532 Hello 50 5 aTrueaabcdbc1.23123.4561.23439505050System.ObjectHello World", "32", "", "32 Hello", "", "32 Hello 50", "", "32 Hello 50 5", "", "32 Hello 50 5 a", "", "True", "a", "abcd", "bc", "1.23", "123.456", "1.234", "39", "50", "50", "50", "System.Object", "Hello World", }; [Fact] public static void ReadAndReadLine() { TextWriter savedStandardOutput = Console.Out; TextReader savedStandardInput = Console.In; try { using (MemoryStream memStream = new MemoryStream()) { using (StreamWriter sw = new StreamWriter(memStream)) { sw.WriteLine(string.Join(Environment.NewLine, s_testLines)); sw.Flush(); memStream.Seek(0, SeekOrigin.Begin); using (StreamReader sr = new StreamReader(memStream)) { Console.SetIn(sr); for (int i = 0; i < s_testLines[0].Length; i++) { Assert.Equal(s_testLines[0][i], Console.Read()); } // Read the newline at the end of the first line. Assert.Equal("", Console.ReadLine()); for (int i = 1; i < s_testLines.Length; i++) { Assert.Equal(s_testLines[i], sr.ReadLine()); } // We should be at EOF now. Assert.Equal(-1, Console.Read()); } } } } finally { Console.SetOut(savedStandardOutput); Console.SetIn(savedStandardInput); } } [Fact] public static void OpenStandardInput_NegativeBufferSize_ThrowsArgumentOutOfRangeException() { AssertExtensions.Throws<ArgumentOutOfRangeException>("bufferSize", () => Console.OpenStandardInput(-1)); } [Fact] public static void OpenStandardOutput_NegativeBufferSize_ThrowsArgumentOutOfRangeException() { AssertExtensions.Throws<ArgumentOutOfRangeException>("bufferSize", () => Console.OpenStandardOutput(-1)); } [Fact] public static void OpenStandardError_NegativeBufferSize_ThrowsArgumentOutOfRangeException() { AssertExtensions.Throws<ArgumentOutOfRangeException>("bufferSize", () => Console.OpenStandardError(-1)); } }
// Copyright 2011 The Noda Time Authors. All rights reserved. // Use of this source code is governed by the Apache License 2.0, // as found in the LICENSE.txt file. using NodaTime.Globalization; using NodaTime.Utility; using System; using System.Collections.Generic; using System.Globalization; using System.Text; namespace NodaTime.Text.Patterns { /// <summary> /// Builder for a pattern which implements parsing and formatting as a sequence of steps applied /// in turn. /// </summary> internal sealed class SteppedPatternBuilder<TResult, TBucket> where TBucket : ParseBucket<TResult> { internal delegate ParseResult<TResult>? ParseAction(ValueCursor cursor, TBucket bucket); private readonly List<Action<TResult, StringBuilder>> formatActions; private readonly List<ParseAction> parseActions; private readonly Func<TBucket> bucketProvider; private PatternFields usedFields; private bool formatOnly; internal NodaFormatInfo FormatInfo { get; } internal PatternFields UsedFields => usedFields; internal SteppedPatternBuilder(NodaFormatInfo formatInfo, Func<TBucket> bucketProvider) { this.FormatInfo = formatInfo; formatActions = new List<Action<TResult, StringBuilder>>(); parseActions = new List<ParseAction>(); this.bucketProvider = bucketProvider; } /// <summary> /// Calls the bucket provider and returns a sample bucket. This means that any values /// normally propagated via the bucket can also be used when building the pattern. /// </summary> internal TBucket CreateSampleBucket() { return bucketProvider(); } /// <summary> /// Sets this pattern to only be capable of formatting; any attempt to parse using the /// built pattern will fail immediately. /// </summary> internal void SetFormatOnly() { formatOnly = true; } /// <summary> /// Performs common parsing operations: start with a parse action to move the /// value cursor onto the first character, then call a character handler for each /// character in the pattern to build up the steps. If any handler fails, /// that failure is returned - otherwise the return value is null. /// </summary> internal void ParseCustomPattern(string patternText, Dictionary<char, CharacterHandler<TResult, TBucket>> characterHandlers) { var patternCursor = new PatternCursor(patternText); // Now iterate over the pattern. while (patternCursor.MoveNext()) { if (characterHandlers.TryGetValue(patternCursor.Current, out CharacterHandler<TResult, TBucket> handler)) { handler(patternCursor, this); } else { char current = patternCursor.Current; if ((current >= 'A' && current <= 'Z') || (current >= 'a' && current <= 'z') || current == PatternCursor.EmbeddedPatternStart || current == PatternCursor.EmbeddedPatternEnd) { throw new InvalidPatternException(TextErrorMessages.UnquotedLiteral, current); } AddLiteral(patternCursor.Current, ParseResult<TResult>.MismatchedCharacter); } } } /// <summary> /// Validates the combination of fields used. /// </summary> internal void ValidateUsedFields() { // We assume invalid combinations are global across all parsers. The way that // the patterns are parsed ensures we never end up with any invalid individual fields // (e.g. time fields within a date pattern). if ((usedFields & (PatternFields.Era | PatternFields.YearOfEra)) == PatternFields.Era) { throw new InvalidPatternException(TextErrorMessages.EraWithoutYearOfEra); } const PatternFields calendarAndEra = PatternFields.Era | PatternFields.Calendar; if ((usedFields & calendarAndEra) == calendarAndEra) { throw new InvalidPatternException(TextErrorMessages.CalendarAndEra); } } /// <summary> /// Returns a built pattern. This is mostly to keep the API for the builder separate from that of the pattern, /// and for thread safety (publishing a new object, thus leading to a memory barrier). /// Note that this builder *must not* be used after the result has been built. /// </summary> internal IPartialPattern<TResult> Build(TResult sample) { // If we've got an embedded date and any *other* date fields, throw. if (usedFields.HasAny(PatternFields.EmbeddedDate) && usedFields.HasAny(PatternFields.AllDateFields & ~PatternFields.EmbeddedDate)) { throw new InvalidPatternException(TextErrorMessages.DateFieldAndEmbeddedDate); } // Ditto for time if (usedFields.HasAny(PatternFields.EmbeddedTime) && usedFields.HasAny(PatternFields.AllTimeFields & ~PatternFields.EmbeddedTime)) { throw new InvalidPatternException(TextErrorMessages.TimeFieldAndEmbeddedTime); } Action<TResult, StringBuilder>? formatDelegate = null; foreach (Action<TResult, StringBuilder> formatAction in formatActions) { formatDelegate += formatAction.Target is IPostPatternParseFormatAction postAction ? postAction.BuildFormatAction(usedFields) : formatAction; } return new SteppedPattern(formatDelegate!, formatOnly ? null : parseActions.ToArray(), bucketProvider, usedFields, sample); } /// <summary> /// Registers that a pattern field has been used in this pattern, and throws a suitable error /// result if it's already been used. /// </summary> internal void AddField(PatternFields field, char characterInPattern) { PatternFields newUsedFields = usedFields | field; if (newUsedFields == usedFields) { throw new InvalidPatternException(TextErrorMessages.RepeatedFieldInPattern, characterInPattern); } usedFields = newUsedFields; } internal void AddParseAction(ParseAction parseAction) => parseActions.Add(parseAction); internal void AddFormatAction(Action<TResult, StringBuilder> formatAction) => formatActions.Add(formatAction); /// <summary> /// Equivalent of <see cref="AddParseValueAction"/> but for 64-bit integers. Currently only /// positive values are supported. /// </summary> internal void AddParseInt64ValueAction(int minimumDigits, int maximumDigits, char patternChar, long minimumValue, long maximumValue, Action<TBucket, long> valueSetter) { Preconditions.DebugCheckArgumentRange(nameof(minimumValue), minimumValue, 0, long.MaxValue); AddParseAction((cursor, bucket) => { int startingIndex = cursor.Index; if (!cursor.ParseInt64Digits(minimumDigits, maximumDigits, out long value)) { cursor.Move(startingIndex); return ParseResult<TResult>.MismatchedNumber(cursor, new string(patternChar, minimumDigits)); } if (value < minimumValue || value > maximumValue) { cursor.Move(startingIndex); return ParseResult<TResult>.FieldValueOutOfRange(cursor, value, patternChar); } valueSetter(bucket, value); return null; }); } internal void AddParseValueAction(int minimumDigits, int maximumDigits, char patternChar, int minimumValue, int maximumValue, Action<TBucket, int> valueSetter) { AddParseAction((cursor, bucket) => { int startingIndex = cursor.Index; bool negative = cursor.Match('-'); if (negative && minimumValue >= 0) { cursor.Move(startingIndex); return ParseResult<TResult>.UnexpectedNegative(cursor); } if (!cursor.ParseDigits(minimumDigits, maximumDigits, out int value)) { cursor.Move(startingIndex); return ParseResult<TResult>.MismatchedNumber(cursor, new string(patternChar, minimumDigits)); } if (negative) { value = -value; } if (value < minimumValue || value > maximumValue) { cursor.Move(startingIndex); return ParseResult<TResult>.FieldValueOutOfRange(cursor, value, patternChar); } valueSetter(bucket, value); return null; }); } /// <summary> /// Adds text which must be matched exactly when parsing, and appended directly when formatting. /// </summary> internal void AddLiteral(string expectedText, Func<ValueCursor, ParseResult<TResult>> failure) { // Common case - single character literal, often a date or time separator. if (expectedText.Length == 1) { char expectedChar = expectedText[0]; AddParseAction((str, bucket) => str.Match(expectedChar) ? null : failure(str)); AddFormatAction((value, builder) => builder.Append(expectedChar)); return; } AddParseAction((str, bucket) => str.Match(expectedText) ? null : failure(str)); AddFormatAction((value, builder) => builder.Append(expectedText)); } internal static void HandleQuote(PatternCursor pattern, SteppedPatternBuilder<TResult, TBucket> builder) { string quoted = pattern.GetQuotedString(pattern.Current); builder.AddLiteral(quoted, ParseResult<TResult>.QuotedStringMismatch); } internal static void HandleBackslash(PatternCursor pattern, SteppedPatternBuilder<TResult, TBucket> builder) { if (!pattern.MoveNext()) { throw new InvalidPatternException(TextErrorMessages.EscapeAtEndOfString); } builder.AddLiteral(pattern.Current, ParseResult<TResult>.EscapedCharacterMismatch); } #pragma warning disable IDE0060 #pragma warning disable CA1801 // Remove/use unused parameter // Note: the builder parameter is unused, but required so that the method fits the delegate signature. /// <summary> /// Handle a leading "%" which acts as a pseudo-escape - it's mostly used to allow format strings such as "%H" to mean /// "use a custom format string consisting of H instead of a standard pattern H". /// </summary> internal static void HandlePercent(PatternCursor pattern, SteppedPatternBuilder<TResult, TBucket> builder) #pragma warning restore CA1801 #pragma warning restore IDE0060 { if (pattern.HasMoreCharacters) { if (pattern.PeekNext() != '%') { // Handle the next character as normal return; } throw new InvalidPatternException(TextErrorMessages.PercentDoubled); } throw new InvalidPatternException(TextErrorMessages.PercentAtEndOfString); } /// <summary> /// Returns a handler for a zero-padded purely-numeric field specifier, such as "seconds", "minutes", "24-hour", "12-hour" etc. /// </summary> /// <param name="maxCount">Maximum permissible count (usually two)</param> /// <param name="field">Field to remember that we've seen</param> /// <param name="minValue">Minimum valid value for the field (inclusive)</param> /// <param name="maxValue">Maximum value value for the field (inclusive)</param> /// <param name="getter">Delegate to retrieve the field value when formatting</param> /// <param name="setter">Delegate to set the field value into a bucket when parsing</param> /// <returns>The pattern parsing failure, or null on success.</returns> internal static CharacterHandler<TResult, TBucket> HandlePaddedField(int maxCount, PatternFields field, int minValue, int maxValue, Func<TResult, int> getter, Action<TBucket, int> setter) { return (pattern, builder) => { int count = pattern.GetRepeatCount(maxCount); builder.AddField(field, pattern.Current); builder.AddParseValueAction(count, maxCount, pattern.Current, minValue, maxValue, setter); builder.AddFormatLeftPad(count, getter, assumeNonNegative: minValue >= 0, assumeFitsInCount: count == maxCount); }; } /// <summary> /// Adds a character which must be matched exactly when parsing, and appended directly when formatting. /// </summary> internal void AddLiteral(char expectedChar, Func<ValueCursor, char, ParseResult<TResult>> failureSelector) { AddParseAction((str, bucket) => str.Match(expectedChar) ? null : failureSelector(str, expectedChar)); AddFormatAction((value, builder) => builder.Append(expectedChar)); } /// <summary> /// Adds parse actions for a list of strings, such as days of the week or month names. /// The parsing is performed case-insensitively. All candidates are tested, and only the longest /// match is used. /// </summary> internal void AddParseLongestTextAction(char field, Action<TBucket, int> setter, CompareInfo compareInfo, IReadOnlyList<string> textValues) { AddParseAction((str, bucket) => { int bestIndex = -1; int longestMatch = 0; FindLongestMatch(compareInfo, str, textValues, ref bestIndex, ref longestMatch); if (bestIndex != -1) { setter(bucket, bestIndex); str.Move(str.Index + longestMatch); return null; } return ParseResult<TResult>.MismatchedText(str, field); }); } /// <summary> /// Adds parse actions for two list of strings, such as non-genitive and genitive month names. /// The parsing is performed case-insensitively. All candidates are tested, and only the longest /// match is used. /// </summary> internal void AddParseLongestTextAction( char field, Action<TBucket, int> setter, CompareInfo compareInfo, IReadOnlyList<string> textValues1, IReadOnlyList<string> textValues2) { AddParseAction((str, bucket) => { int bestIndex = -1; int longestMatch = 0; FindLongestMatch(compareInfo, str, textValues1, ref bestIndex, ref longestMatch); FindLongestMatch(compareInfo, str, textValues2, ref bestIndex, ref longestMatch); if (bestIndex != -1) { setter(bucket, bestIndex); str.Move(str.Index + longestMatch); return null; } return ParseResult<TResult>.MismatchedText(str, field); }); } /// <summary> /// Find the longest match from a given set of candidate strings, updating the index/length of the best value /// accordingly. /// </summary> private static void FindLongestMatch(CompareInfo compareInfo, ValueCursor cursor, IReadOnlyList<string> values, ref int bestIndex, ref int longestMatch) { for (int i = 0; i < values.Count; i++) { string candidate = values[i]; if (candidate is null || candidate.Length <= longestMatch) { continue; } if (cursor.MatchCaseInsensitive(candidate, compareInfo, false)) { bestIndex = i; longestMatch = candidate.Length; } } } /// <summary> /// Adds parse and format actions for a mandatory positive/negative sign. /// </summary> /// <param name="signSetter">Action to take when to set the given sign within the bucket</param> /// <param name="nonNegativePredicate">Predicate to detect whether the value being formatted is non-negative</param> public void AddRequiredSign(Action<TBucket, bool> signSetter, Func<TResult, bool> nonNegativePredicate) { AddParseAction((str, bucket) => { if (str.Match("-")) { signSetter(bucket, false); return null; } if (str.Match("+")) { signSetter(bucket, true); return null; } return ParseResult<TResult>.MissingSign(str); }); AddFormatAction((value, sb) => sb.Append(nonNegativePredicate(value) ? "+" : "-")); } /// <summary> /// Adds parse and format actions for an "negative only" sign. /// </summary> /// <param name="signSetter">Action to take when to set the given sign within the bucket</param> /// <param name="nonNegativePredicate">Predicate to detect whether the value being formatted is non-negative</param> public void AddNegativeOnlySign(Action<TBucket, bool> signSetter, Func<TResult, bool> nonNegativePredicate) { AddParseAction((str, bucket) => { if (str.Match("-")) { signSetter(bucket, false); return null; } if (str.Match("+")) { return ParseResult<TResult>.PositiveSignInvalid(str); } signSetter(bucket, true); return null; }); AddFormatAction((value, builder) => { if (!nonNegativePredicate(value)) { builder.Append('-'); } }); } /// <summary> /// Adds an action to pad a selected value to a given minimum length. /// </summary> /// <param name="count">The minimum length to pad to</param> /// <param name="selector">The selector function to apply to obtain a value to format</param> /// <param name="assumeNonNegative">Whether it is safe to assume the value will be non-negative</param> /// <param name="assumeFitsInCount">Whether it is safe to assume the value will not exceed the specified length</param> internal void AddFormatLeftPad(int count, Func<TResult, int> selector, bool assumeNonNegative, bool assumeFitsInCount) { if (count == 2 && assumeNonNegative && assumeFitsInCount) { AddFormatAction((value, sb) => FormatHelper.Format2DigitsNonNegative(selector(value), sb)); } else if (count == 4 && assumeFitsInCount) { AddFormatAction((value, sb) => FormatHelper.Format4DigitsValueFits(selector(value), sb)); } else if (assumeNonNegative) { AddFormatAction((value, sb) => FormatHelper.LeftPadNonNegative(selector(value), count, sb)); } else { AddFormatAction((value, sb) => FormatHelper.LeftPad(selector(value), count, sb)); } } internal void AddFormatFraction(int width, int scale, Func<TResult, int> selector) => AddFormatAction((value, sb) => FormatHelper.AppendFraction(selector(value), width, scale, sb)); internal void AddFormatFractionTruncate(int width, int scale, Func<TResult, int> selector) => AddFormatAction((value, sb) => FormatHelper.AppendFractionTruncate(selector(value), width, scale, sb)); /// <summary> /// Handles date, time and date/time embedded patterns. /// </summary> internal void AddEmbeddedLocalPartial( PatternCursor pattern, Func<TBucket, LocalDatePatternParser.LocalDateParseBucket> dateBucketExtractor, Func<TBucket, LocalTimePatternParser.LocalTimeParseBucket> timeBucketExtractor, Func<TResult, LocalDate> dateExtractor, Func<TResult, LocalTime> timeExtractor, // null if date/time embedded patterns are invalid Func<TResult, LocalDateTime>? dateTimeExtractor) { // This will be d (date-only), t (time-only), or < (date and time) // If it's anything else, we'll see the problem when we try to get the pattern. var patternType = pattern.PeekNext(); if (patternType == 'd' || patternType == 't') { pattern.MoveNext(); } string embeddedPatternText = pattern.GetEmbeddedPattern(); switch (patternType) { case '<': { var sampleBucket = CreateSampleBucket(); var templateTime = timeBucketExtractor(sampleBucket).TemplateValue; var templateDate = dateBucketExtractor(sampleBucket).TemplateValue; if (dateTimeExtractor is null) { throw new InvalidPatternException(TextErrorMessages.InvalidEmbeddedPatternType); } AddField(PatternFields.EmbeddedDate, 'l'); AddField(PatternFields.EmbeddedTime, 'l'); AddEmbeddedPattern( LocalDateTimePattern.Create(embeddedPatternText, FormatInfo, templateDate + templateTime).UnderlyingPattern, (bucket, value) => { var dateBucket = dateBucketExtractor(bucket); var timeBucket = timeBucketExtractor(bucket); dateBucket.Calendar = value.Calendar; dateBucket.Year = value.Year; dateBucket.MonthOfYearNumeric = value.Month; dateBucket.DayOfMonth = value.Day; timeBucket.Hours24 = value.Hour; timeBucket.Minutes = value.Minute; timeBucket.Seconds = value.Second; timeBucket.FractionalSeconds = value.NanosecondOfSecond; }, dateTimeExtractor); break; } case 'd': AddEmbeddedDatePattern('l', embeddedPatternText, dateBucketExtractor, dateExtractor); break; case 't': AddEmbeddedTimePattern('l', embeddedPatternText, timeBucketExtractor, timeExtractor); break; default: throw new InvalidOperationException("Bug in Noda Time: embedded pattern type wasn't date, time, or date+time"); } } internal void AddEmbeddedDatePattern( char characterInPattern, string embeddedPatternText, Func<TBucket, LocalDatePatternParser.LocalDateParseBucket> dateBucketExtractor, Func<TResult, LocalDate> dateExtractor) { var templateDate = dateBucketExtractor(CreateSampleBucket()).TemplateValue; AddField(PatternFields.EmbeddedDate, characterInPattern); AddEmbeddedPattern( LocalDatePattern.Create(embeddedPatternText, FormatInfo, templateDate).UnderlyingPattern, (bucket, value) => { var dateBucket = dateBucketExtractor(bucket); dateBucket.Calendar = value.Calendar; dateBucket.Year = value.Year; dateBucket.MonthOfYearNumeric = value.Month; dateBucket.DayOfMonth = value.Day; }, dateExtractor); } internal void AddEmbeddedTimePattern( char characterInPattern, string embeddedPatternText, Func<TBucket, LocalTimePatternParser.LocalTimeParseBucket> timeBucketExtractor, Func<TResult, LocalTime> timeExtractor) { var templateTime = timeBucketExtractor(CreateSampleBucket()).TemplateValue; AddField(PatternFields.EmbeddedTime, characterInPattern); AddEmbeddedPattern( LocalTimePattern.Create(embeddedPatternText, FormatInfo, templateTime).UnderlyingPattern, (bucket, value) => { var timeBucket = timeBucketExtractor(bucket); timeBucket.Hours24 = value.Hour; timeBucket.Minutes = value.Minute; timeBucket.Seconds = value.Second; timeBucket.FractionalSeconds = value.NanosecondOfSecond; }, timeExtractor); } /// <summary> /// Adds parsing/formatting of an embedded pattern, e.g. an offset within a ZonedDateTime/OffsetDateTime. /// </summary> internal void AddEmbeddedPattern<TEmbedded>( IPartialPattern<TEmbedded> embeddedPattern, Action<TBucket, TEmbedded> parseAction, Func<TResult, TEmbedded> valueExtractor) { AddParseAction((value, bucket) => { var result = embeddedPattern.ParsePartial(value); if (!result.Success) { return result.ConvertError<TResult>(); } parseAction(bucket, result.Value); return null; }); AddFormatAction((value, sb) => embeddedPattern.AppendFormat(valueExtractor(value), sb)); } /// <summary> /// Hack to handle genitive month names - we only know what we need to do *after* we've parsed the whole pattern. /// </summary> internal interface IPostPatternParseFormatAction { Action<TResult, StringBuilder> BuildFormatAction(PatternFields finalFields); } private sealed class SteppedPattern : IPartialPattern<TResult> { private readonly Action<TResult, StringBuilder> formatActions; // This will be null if the pattern is only capable of formatting. private readonly ParseAction[]? parseActions; private readonly Func<TBucket> bucketProvider; private readonly PatternFields usedFields; private readonly int expectedLength; public SteppedPattern (Action<TResult, StringBuilder> formatActions, ParseAction[]? parseActions, Func<TBucket> bucketProvider, PatternFields usedFields, TResult sample) { this.formatActions = formatActions; this.parseActions = parseActions; this.bucketProvider = bucketProvider; this.usedFields = usedFields; // Format the sample value to work out the expected length, so we // can use that when creating a StringBuilder. This will definitely not always // be appropriate, but it's a start. StringBuilder builder = new StringBuilder(); formatActions(sample, builder); expectedLength = builder.Length; } public ParseResult<TResult> Parse(string text) { if (parseActions is null) { return ParseResult<TResult>.FormatOnlyPattern; } if (text is null) { return ParseResult<TResult>.ArgumentNull(nameof(text)); } if (text.Length == 0) { return ParseResult<TResult>.ValueStringEmpty; } var valueCursor = new ValueCursor(text); // Prime the pump... the value cursor ends up *before* the first character, but // our steps always assume it's *on* the right character. valueCursor.MoveNext(); var result = ParsePartial(valueCursor); if (!result.Success) { return result; } // Check that we've used up all the text if (valueCursor.Current != TextCursor.Nul) { return ParseResult<TResult>.ExtraValueCharacters(valueCursor, valueCursor.Remainder); } return result; } public string Format(TResult value) { StringBuilder builder = new StringBuilder(expectedLength); // This will call all the actions in the multicast delegate. formatActions(value, builder); return builder.ToString(); } public ParseResult<TResult> ParsePartial(ValueCursor cursor) { // At the moment we shouldn't get a partial parse for a format-only pattern, but // let's guard against it for the future. if (parseActions is null) { return ParseResult<TResult>.FormatOnlyPattern; } TBucket bucket = bucketProvider(); foreach (var action in parseActions) { ParseResult<TResult>? failure = action(cursor, bucket); if (failure != null) { return failure; } } return bucket.CalculateValue(usedFields, cursor.Value); } public StringBuilder AppendFormat(TResult value, StringBuilder builder) { Preconditions.CheckNotNull(builder, nameof(builder)); formatActions(value, builder); return builder; } } } }
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 TripsServer.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 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 BeerBuzzBackend.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; } } }
// This file was generated by CSLA Object Generator - CslaGenFork v4.5 // // Filename: FolderType // ObjectType: FolderType // CSLAType: EditableRoot using System; using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; using DocStore.Business.Util; using Csla.Rules; using Csla.Rules.CommonRules; using DocStore.Business.Security; namespace DocStore.Business { /// <summary> /// Folder type (editable root object).<br/> /// This is a generated <see cref="FolderType"/> business object. /// </summary> [Serializable] public partial class FolderType : BusinessBase<FolderType> { #region Static Fields private static int _lastId; #endregion #region Business Properties /// <summary> /// Maintains metadata about <see cref="FolderTypeID"/> property. /// </summary> [NotUndoable] public static readonly PropertyInfo<int> FolderTypeIDProperty = RegisterProperty<int>(p => p.FolderTypeID, "Folder Type ID"); /// <summary> /// Gets the Folder Type ID. /// </summary> /// <value>The Folder Type ID.</value> public int FolderTypeID { get { return GetProperty(FolderTypeIDProperty); } } /// <summary> /// Maintains metadata about <see cref="FolderTypeName"/> property. /// </summary> public static readonly PropertyInfo<string> FolderTypeNameProperty = RegisterProperty<string>(p => p.FolderTypeName, "Folder Type Name"); /// <summary> /// Gets or sets the Folder Type Name. /// </summary> /// <value>The Folder Type Name.</value> public string FolderTypeName { get { return GetProperty(FolderTypeNameProperty); } set { SetProperty(FolderTypeNameProperty, value); } } /// <summary> /// Maintains metadata about <see cref="CreateDate"/> property. /// </summary> public static readonly PropertyInfo<SmartDate> CreateDateProperty = RegisterProperty<SmartDate>(p => p.CreateDate, "Create Date"); /// <summary> /// Gets the Create Date. /// </summary> /// <value>The Create Date.</value> public SmartDate CreateDate { get { return GetProperty(CreateDateProperty); } } /// <summary> /// Maintains metadata about <see cref="CreateUserID"/> property. /// </summary> public static readonly PropertyInfo<int> CreateUserIDProperty = RegisterProperty<int>(p => p.CreateUserID, "Create User ID"); /// <summary> /// Gets the Create User ID. /// </summary> /// <value>The Create User ID.</value> public int CreateUserID { get { return GetProperty(CreateUserIDProperty); } } /// <summary> /// Maintains metadata about <see cref="ChangeDate"/> property. /// </summary> public static readonly PropertyInfo<SmartDate> ChangeDateProperty = RegisterProperty<SmartDate>(p => p.ChangeDate, "Change Date"); /// <summary> /// Gets the Change Date. /// </summary> /// <value>The Change Date.</value> public SmartDate ChangeDate { get { return GetProperty(ChangeDateProperty); } } /// <summary> /// Maintains metadata about <see cref="ChangeUserID"/> property. /// </summary> public static readonly PropertyInfo<int> ChangeUserIDProperty = RegisterProperty<int>(p => p.ChangeUserID, "Change User ID"); /// <summary> /// Gets the Change User ID. /// </summary> /// <value>The Change User ID.</value> public int ChangeUserID { get { return GetProperty(ChangeUserIDProperty); } } /// <summary> /// Maintains metadata about <see cref="RowVersion"/> property. /// </summary> [NotUndoable] public static readonly PropertyInfo<byte[]> RowVersionProperty = RegisterProperty<byte[]>(p => p.RowVersion, "Row Version"); /// <summary> /// Gets the Row Version. /// </summary> /// <value>The Row Version.</value> public byte[] RowVersion { get { return GetProperty(RowVersionProperty); } } /// <summary> /// Gets the Create User Name. /// </summary> /// <value>The Create User Name.</value> public string CreateUserName { get { var result = string.Empty; if (Admin.UserNVL.GetUserNVL().ContainsKey(CreateUserID)) result = Admin.UserNVL.GetUserNVL().GetItemByKey(CreateUserID).Value; return result; } } /// <summary> /// Gets the Change User Name. /// </summary> /// <value>The Change User Name.</value> public string ChangeUserName { get { var result = string.Empty; if (Admin.UserNVL.GetUserNVL().ContainsKey(ChangeUserID)) result = Admin.UserNVL.GetUserNVL().GetItemByKey(ChangeUserID).Value; return result; } } #endregion #region BusinessBase<T> overrides /// <summary> /// Returns a string that represents the current <see cref="FolderType"/> /// </summary> /// <returns>A <see cref="System.String"/> that represents this instance.</returns> public override string ToString() { // Return the Primary Key as a string return FolderTypeName.ToString(); } #endregion #region Factory Methods /// <summary> /// Factory method. Creates a new <see cref="FolderType"/> object. /// </summary> /// <returns>A reference to the created <see cref="FolderType"/> object.</returns> public static FolderType NewFolderType() { return DataPortal.Create<FolderType>(); } /// <summary> /// Factory method. Loads a <see cref="FolderType"/> object, based on given parameters. /// </summary> /// <param name="folderTypeID">The FolderTypeID parameter of the FolderType to fetch.</param> /// <returns>A reference to the fetched <see cref="FolderType"/> object.</returns> public static FolderType GetFolderType(int folderTypeID) { return DataPortal.Fetch<FolderType>(folderTypeID); } /// <summary> /// Factory method. Deletes a <see cref="FolderType"/> object, based on given parameters. /// </summary> /// <param name="folderTypeID">The FolderTypeID of the FolderType to delete.</param> public static void DeleteFolderType(int folderTypeID) { DataPortal.Delete<FolderType>(folderTypeID); } /// <summary> /// Factory method. Asynchronously creates a new <see cref="FolderType"/> object. /// </summary> /// <param name="callback">The completion callback method.</param> public static void NewFolderType(EventHandler<DataPortalResult<FolderType>> callback) { DataPortal.BeginCreate<FolderType>(callback); } /// <summary> /// Factory method. Asynchronously loads a <see cref="FolderType"/> object, based on given parameters. /// </summary> /// <param name="folderTypeID">The FolderTypeID parameter of the FolderType to fetch.</param> /// <param name="callback">The completion callback method.</param> public static void GetFolderType(int folderTypeID, EventHandler<DataPortalResult<FolderType>> callback) { DataPortal.BeginFetch<FolderType>(folderTypeID, callback); } /// <summary> /// Factory method. Asynchronously deletes a <see cref="FolderType"/> object, based on given parameters. /// </summary> /// <param name="folderTypeID">The FolderTypeID of the FolderType to delete.</param> /// <param name="callback">The completion callback method.</param> public static void DeleteFolderType(int folderTypeID, EventHandler<DataPortalResult<FolderType>> callback) { DataPortal.BeginDelete<FolderType>(folderTypeID, callback); } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="FolderType"/> class. /// </summary> /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public FolderType() { // Use factory methods and do not use direct creation. } #endregion #region Object Authorization /// <summary> /// Adds the object authorization rules. /// </summary> protected static void AddObjectAuthorizationRules() { BusinessRules.AddRule(typeof (FolderType), new IsInRole(AuthorizationActions.CreateObject, "Manager")); BusinessRules.AddRule(typeof (FolderType), new IsInRole(AuthorizationActions.GetObject, "User")); BusinessRules.AddRule(typeof (FolderType), new IsInRole(AuthorizationActions.EditObject, "Manager")); BusinessRules.AddRule(typeof (FolderType), new IsInRole(AuthorizationActions.DeleteObject, "Admin")); AddObjectAuthorizationRulesExtend(); } /// <summary> /// Allows the set up of custom object authorization rules. /// </summary> static partial void AddObjectAuthorizationRulesExtend(); /// <summary> /// Checks if the current user can create a new FolderType object. /// </summary> /// <returns><c>true</c> if the user can create a new object; otherwise, <c>false</c>.</returns> public static bool CanAddObject() { return BusinessRules.HasPermission(Csla.Rules.AuthorizationActions.CreateObject, typeof(FolderType)); } /// <summary> /// Checks if the current user can retrieve FolderType's properties. /// </summary> /// <returns><c>true</c> if the user can read the object; otherwise, <c>false</c>.</returns> public static bool CanGetObject() { return BusinessRules.HasPermission(Csla.Rules.AuthorizationActions.GetObject, typeof(FolderType)); } /// <summary> /// Checks if the current user can change FolderType's properties. /// </summary> /// <returns><c>true</c> if the user can update the object; otherwise, <c>false</c>.</returns> public static bool CanEditObject() { return BusinessRules.HasPermission(Csla.Rules.AuthorizationActions.EditObject, typeof(FolderType)); } /// <summary> /// Checks if the current user can delete a FolderType object. /// </summary> /// <returns><c>true</c> if the user can delete the object; otherwise, <c>false</c>.</returns> public static bool CanDeleteObject() { return BusinessRules.HasPermission(Csla.Rules.AuthorizationActions.DeleteObject, typeof(FolderType)); } #endregion #region Data Access /// <summary> /// Loads default values for the <see cref="FolderType"/> object properties. /// </summary> [RunLocal] protected override void DataPortal_Create() { LoadProperty(FolderTypeIDProperty, System.Threading.Interlocked.Decrement(ref _lastId)); LoadProperty(CreateDateProperty, new SmartDate(DateTime.Now)); LoadProperty(CreateUserIDProperty, UserInformation.UserId); LoadProperty(ChangeDateProperty, ReadProperty(CreateDateProperty)); LoadProperty(ChangeUserIDProperty, ReadProperty(CreateUserIDProperty)); var args = new DataPortalHookArgs(); OnCreate(args); base.DataPortal_Create(); } /// <summary> /// Loads a <see cref="FolderType"/> object from the database, based on given criteria. /// </summary> /// <param name="folderTypeID">The Folder Type ID.</param> protected void DataPortal_Fetch(int folderTypeID) { using (var ctx = ConnectionManager<SqlConnection>.GetManager(Database.DocStoreConnection, false)) { using (var cmd = new SqlCommand("GetFolderType", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@FolderTypeID", folderTypeID).DbType = DbType.Int32; var args = new DataPortalHookArgs(cmd, folderTypeID); OnFetchPre(args); Fetch(cmd); OnFetchPost(args); } } // check all object rules and property rules BusinessRules.CheckRules(); } private void Fetch(SqlCommand cmd) { using (var dr = new SafeDataReader(cmd.ExecuteReader())) { if (dr.Read()) { Fetch(dr); } } } /// <summary> /// Loads a <see cref="FolderType"/> object from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> private void Fetch(SafeDataReader dr) { // Value properties LoadProperty(FolderTypeIDProperty, dr.GetInt32("FolderTypeID")); LoadProperty(FolderTypeNameProperty, dr.GetString("FolderTypeName")); LoadProperty(CreateDateProperty, dr.GetSmartDate("CreateDate", true)); LoadProperty(CreateUserIDProperty, dr.GetInt32("CreateUserID")); LoadProperty(ChangeDateProperty, dr.GetSmartDate("ChangeDate", true)); LoadProperty(ChangeUserIDProperty, dr.GetInt32("ChangeUserID")); LoadProperty(RowVersionProperty, dr.GetValue("RowVersion") as byte[]); var args = new DataPortalHookArgs(dr); OnFetchRead(args); } /// <summary> /// Inserts a new <see cref="FolderType"/> object in the database. /// </summary> protected override void DataPortal_Insert() { SimpleAuditTrail(); using (var ctx = TransactionManager<SqlConnection, SqlTransaction>.GetManager(Database.DocStoreConnection, false)) { using (var cmd = new SqlCommand("AddFolderType", ctx.Connection)) { cmd.Transaction = ctx.Transaction; cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@FolderTypeID", ReadProperty(FolderTypeIDProperty)).Direction = ParameterDirection.Output; cmd.Parameters.AddWithValue("@FolderTypeName", ReadProperty(FolderTypeNameProperty)).DbType = DbType.String; cmd.Parameters.AddWithValue("@CreateDate", ReadProperty(CreateDateProperty).DBValue).DbType = DbType.DateTime2; cmd.Parameters.AddWithValue("@CreateUserID", ReadProperty(CreateUserIDProperty)).DbType = DbType.Int32; cmd.Parameters.AddWithValue("@ChangeDate", ReadProperty(ChangeDateProperty).DBValue).DbType = DbType.DateTime2; cmd.Parameters.AddWithValue("@ChangeUserID", ReadProperty(ChangeUserIDProperty)).DbType = DbType.Int32; cmd.Parameters.Add("@NewRowVersion", SqlDbType.Timestamp).Direction = ParameterDirection.Output; var args = new DataPortalHookArgs(cmd); OnInsertPre(args); cmd.ExecuteNonQuery(); OnInsertPost(args); LoadProperty(FolderTypeIDProperty, (int) cmd.Parameters["@FolderTypeID"].Value); LoadProperty(RowVersionProperty, (byte[]) cmd.Parameters["@NewRowVersion"].Value); } ctx.Commit(); } } /// <summary> /// Updates in the database all changes made to the <see cref="FolderType"/> object. /// </summary> protected override void DataPortal_Update() { SimpleAuditTrail(); using (var ctx = TransactionManager<SqlConnection, SqlTransaction>.GetManager(Database.DocStoreConnection, false)) { using (var cmd = new SqlCommand("UpdateFolderType", ctx.Connection)) { cmd.Transaction = ctx.Transaction; cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@FolderTypeID", ReadProperty(FolderTypeIDProperty)).DbType = DbType.Int32; cmd.Parameters.AddWithValue("@FolderTypeName", ReadProperty(FolderTypeNameProperty)).DbType = DbType.String; cmd.Parameters.AddWithValue("@ChangeDate", ReadProperty(ChangeDateProperty).DBValue).DbType = DbType.DateTime2; cmd.Parameters.AddWithValue("@ChangeUserID", ReadProperty(ChangeUserIDProperty)).DbType = DbType.Int32; cmd.Parameters.AddWithValue("@RowVersion", ReadProperty(RowVersionProperty)).DbType = DbType.Binary; cmd.Parameters.Add("@NewRowVersion", SqlDbType.Timestamp).Direction = ParameterDirection.Output; var args = new DataPortalHookArgs(cmd); OnUpdatePre(args); cmd.ExecuteNonQuery(); OnUpdatePost(args); LoadProperty(RowVersionProperty, (byte[]) cmd.Parameters["@NewRowVersion"].Value); } ctx.Commit(); } } private void SimpleAuditTrail() { LoadProperty(ChangeDateProperty, DateTime.Now); LoadProperty(ChangeUserIDProperty, UserInformation.UserId); OnPropertyChanged("ChangeUserName"); if (IsNew) { LoadProperty(CreateDateProperty, ReadProperty(ChangeDateProperty)); LoadProperty(CreateUserIDProperty, ReadProperty(ChangeUserIDProperty)); OnPropertyChanged("CreateUserName"); } } /// <summary> /// Self deletes the <see cref="FolderType"/> object. /// </summary> protected override void DataPortal_DeleteSelf() { DataPortal_Delete(FolderTypeID); } /// <summary> /// Deletes the <see cref="FolderType"/> object from database. /// </summary> /// <param name="folderTypeID">The delete criteria.</param> protected void DataPortal_Delete(int folderTypeID) { // audit the object, just in case soft delete is used on this object SimpleAuditTrail(); using (var ctx = TransactionManager<SqlConnection, SqlTransaction>.GetManager(Database.DocStoreConnection, false)) { using (var cmd = new SqlCommand("DeleteFolderType", ctx.Connection)) { cmd.Transaction = ctx.Transaction; cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@FolderTypeID", folderTypeID).DbType = DbType.Int32; var args = new DataPortalHookArgs(cmd, folderTypeID); OnDeletePre(args); cmd.ExecuteNonQuery(); OnDeletePost(args); } ctx.Commit(); } } #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 } }
//********************************************************* // // Copyright (c) Microsoft. All rights reserved. // This code is licensed under the MIT License (MIT). // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. // //********************************************************* using ScreenCasting.Controls; using ScreenCasting.Data.Azure; using ScreenCasting.Data.Common; using ScreenCasting.Util; using System; using Windows.ApplicationModel.Core; using Windows.Devices.Enumeration; using Windows.Foundation; using Windows.UI.Core; using Windows.UI.ViewManagement; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Media.Imaging; using Windows.UI.Xaml.Navigation; namespace ScreenCasting { public sealed partial class Scenario05 : Page { private MainPage rootPage; private DevicePicker picker; private VideoMetaData video = null; ProjectionViewBroker pvb = new ProjectionViewBroker(); DeviceInformation activeDevice = null; int thisViewId; public Scenario05() { this.InitializeComponent(); rootPage = MainPage.Current; //Subscribe to player events player.MediaOpened += Player_MediaOpened; player.MediaFailed += Player_MediaFailed; player.CurrentStateChanged += Player_CurrentStateChanged; // Get an Azure hosted video AzureDataProvider dataProvider = new AzureDataProvider(); video = dataProvider.GetRandomVideo(); //Set the source on the player rootPage.NotifyUser(string.Format("Opening '{0}'", video.Title), NotifyType.StatusMessage); this.player.Source = video.VideoLink; this.LicenseText.Text = "License: " + video.License; //Subscribe for the clicked event on the custom cast button ((MediaTransportControlsWithCustomCastButton)this.player.TransportControls).CastButtonClicked += TransportControls_CastButtonClicked; // Instantiate the Device Picker picker = new DevicePicker (); // Get the device selecter for Miracast devices picker.Filter.SupportedDeviceSelectors.Add(ProjectionManager.GetDeviceSelector()); //Hook up device selected event picker.DeviceSelected += Picker_DeviceSelected; //Hook up device disconnected event picker.DisconnectButtonClicked += Picker_DisconnectButtonClicked; //Hook up picker dismissed event picker.DevicePickerDismissed += Picker_DevicePickerDismissed; // Hook up the events that are received when projection is stoppped pvb.ProjectionStopping += Pvb_ProjectionStopping; } private void TransportControls_CastButtonClicked(object sender, EventArgs e) { rootPage.NotifyUser("Custom Cast Button Clicked", NotifyType.StatusMessage); //Pause Current Playback player.Pause(); //Get the custom transport controls MediaTransportControlsWithCustomCastButton mtc = (MediaTransportControlsWithCustomCastButton)this.player.TransportControls; //Retrieve the location of the casting button GeneralTransform transform = mtc.CastButton.TransformToVisual(Window.Current.Content as UIElement); Point pt = transform.TransformPoint(new Point(0, 0)); //Show the picker above our custom cast button picker.Show(new Rect(pt.X, pt.Y, mtc.CastButton.ActualWidth, mtc.CastButton.ActualHeight), Windows.UI.Popups.Placement.Above); } private async void Picker_DeviceSelected(DevicePicker sender, DeviceSelectedEventArgs args) { //Casting must occur from the UI thread. This dispatches the casting calls to the UI thread. await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async () => { try { // Set status to Connecting picker.SetDisplayStatus(args.SelectedDevice, "Connecting", DevicePickerDisplayStatusOptions.ShowProgress); // Getting the selected device improves debugging DeviceInformation selectedDevice = args.SelectedDevice; thisViewId = Windows.UI.ViewManagement.ApplicationView.GetForCurrentView().Id; // If projection is already in progress, then it could be shown on the monitor again // Otherwise, we need to create a new view to show the presentation if (rootPage.ProjectionViewPageControl == null) { // First, create a new, blank view var thisDispatcher = Window.Current.Dispatcher; await CoreApplication.CreateNewView().Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { // ViewLifetimeControl is a wrapper to make sure the view is closed only // when the app is done with it rootPage.ProjectionViewPageControl = ViewLifetimeControl.CreateForCurrentView(); // Assemble some data necessary for the new page pvb.MainPageDispatcher = thisDispatcher; pvb.ProjectionViewPageControl = rootPage.ProjectionViewPageControl; pvb.MainViewId = thisViewId; // Display the page in the view. Note that the view will not become visible // until "StartProjectingAsync" is called var rootFrame = new Frame(); rootFrame.Navigate(typeof(ProjectionViewPage), pvb); Window.Current.Content = rootFrame; Window.Current.Activate(); }); } try { // Start/StopViewInUse are used to signal that the app is interacting with the // view, so it shouldn't be closed yet, even if the user loses access to it rootPage.ProjectionViewPageControl.StartViewInUse(); try { await ProjectionManager.StartProjectingAsync(rootPage.ProjectionViewPageControl.Id, thisViewId, selectedDevice); } catch (Exception ex) { if (!ProjectionManager.ProjectionDisplayAvailable || pvb.ProjectedPage == null) throw ex; } // ProjectionManager currently can throw an exception even when projection has started.\ // Re-throw the exception when projection has not been started after calling StartProjectingAsync if (ProjectionManager.ProjectionDisplayAvailable && pvb.ProjectedPage != null) { this.player.Pause(); await pvb.ProjectedPage.SetMediaSource(this.player.Source, this.player.Position); activeDevice = selectedDevice; // Set status to Connected picker.SetDisplayStatus(args.SelectedDevice, "Connected", DevicePickerDisplayStatusOptions.ShowDisconnectButton); picker.Hide(); } else { rootPage.NotifyUser(string.Format("Projection has failed to '{0}'", selectedDevice.Name), NotifyType.ErrorMessage); // Set status to Failed picker.SetDisplayStatus(args.SelectedDevice, "Connection Failed", DevicePickerDisplayStatusOptions.ShowRetryButton); } } catch (Exception) { rootPage.NotifyUser(string.Format("Projection has failed to '{0}'", selectedDevice.Name), NotifyType.ErrorMessage); // Set status to Failed try { picker.SetDisplayStatus(args.SelectedDevice, "Connection Failed", DevicePickerDisplayStatusOptions.ShowRetryButton); } catch { } } } catch (Exception ex) { UnhandledExceptionPage.ShowUnhandledException(ex); } }); } private async void Picker_DevicePickerDismissed(DevicePicker sender, object args) { //Casting must occur from the UI thread. This dispatches the casting calls to the UI thread. await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { if (activeDevice == null) { player.Play(); } }); } private async void Picker_DisconnectButtonClicked(DevicePicker sender, DeviceDisconnectButtonClickedEventArgs args) { //Casting must occur from the UI thread. This dispatches the casting calls to the UI thread. await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { rootPage.NotifyUser("Disconnect Button clicked", NotifyType.StatusMessage); //Update the display status for the selected device. sender.SetDisplayStatus(args.Device, "Disconnecting", DevicePickerDisplayStatusOptions.ShowProgress); if (this.pvb.ProjectedPage != null) this.pvb.ProjectedPage.StopProjecting(); //Update the display status for the selected device. sender.SetDisplayStatus(args.Device, "Disconnected", DevicePickerDisplayStatusOptions.None); rootPage.NotifyUser("Disconnected", NotifyType.StatusMessage); // Set the active device variables to null activeDevice = null; }); } private async void Pvb_ProjectionStopping(object sender, EventArgs e) { ProjectionViewBroker broker = sender as ProjectionViewBroker; TimeSpan position; Uri source = null; await broker.ProjectedPage.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { position = broker.ProjectedPage.Player.Position; source = broker.ProjectedPage.Player.Source; }); await rootPage.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { rootPage.NotifyUser("Resuming playback on the first screen", NotifyType.StatusMessage); this.player.Source = source; this.player.Position = position; this.player.Play(); rootPage.ProjectionViewPageControl = null; }); } #region MediaElement Status Methods private void Player_CurrentStateChanged(object sender, RoutedEventArgs e) { // Update status rootPage.NotifyUser(string.Format("{0} '{1}'", this.player.CurrentState, video.Title), NotifyType.StatusMessage); } private void Player_MediaFailed(object sender, ExceptionRoutedEventArgs e) { rootPage.NotifyUser(string.Format("Failed to load '{0}'", video.Title), NotifyType.ErrorMessage); } private void Player_MediaOpened(object sender, RoutedEventArgs e) { rootPage.NotifyUser(string.Format("Openend '{0}'", video.Title), NotifyType.StatusMessage); player.Play(); } #endregion protected override void OnNavigatedTo(NavigationEventArgs e) { rootPage = MainPage.Current; } } }
using System; using System.Collections.Generic; using Content.Server.Clothing.Components; using Content.Server.Hands.Components; using Content.Server.Weapon.Ranged.Ammunition.Components; using Content.Server.Weapon.Ranged.Barrels.Components; using Content.Shared.Examine; using Content.Shared.Interaction; using Content.Shared.Verbs; using Content.Shared.Weapons.Ranged.Barrels.Components; using Robust.Shared.Containers; using Robust.Shared.GameObjects; using Robust.Shared.Localization; using Robust.Shared.Player; namespace Content.Server.Weapon.Ranged; public sealed partial class GunSystem { // Probably needs combining with magazines in future given the common functionality. private void OnAmmoBoxAltVerbs(EntityUid uid, AmmoBoxComponent component, GetVerbsEvent<AlternativeVerb> args) { if (args.Hands == null || !args.CanAccess || !args.CanInteract) return; if (component.AmmoLeft == 0) return; AlternativeVerb verb = new() { Text = Loc.GetString("dump-vert-get-data-text"), IconTexture = "/Textures/Interface/VerbIcons/eject.svg.192dpi.png", Act = () => AmmoBoxEjectContents(component, 10) }; args.Verbs.Add(verb); } private void OnAmmoBoxInteractHand(EntityUid uid, AmmoBoxComponent component, InteractHandEvent args) { if (args.Handled) return; TryUse(args.User, component); } private void OnAmmoBoxUse(EntityUid uid, AmmoBoxComponent component, UseInHandEvent args) { if (args.Handled) return; TryUse(args.User, component); } private void OnAmmoBoxInteractUsing(EntityUid uid, AmmoBoxComponent component, InteractUsingEvent args) { if (args.Handled) return; if (TryComp(args.Used, out AmmoComponent? ammoComponent)) { if (TryInsertAmmo(args.User, args.Used, component, ammoComponent)) { args.Handled = true; } return; } if (!TryComp(args.Used, out RangedMagazineComponent? rangedMagazine)) return; for (var i = 0; i < Math.Max(10, rangedMagazine.ShotsLeft); i++) { if (TakeAmmo(rangedMagazine) is not {Valid: true} ammo) { continue; } if (!TryInsertAmmo(args.User, ammo, component)) { TryInsertAmmo(args.User, ammo, rangedMagazine); args.Handled = true; return; } } args.Handled = true; } private void OnAmmoBoxInit(EntityUid uid, AmmoBoxComponent component, ComponentInit args) { component.AmmoContainer = uid.EnsureContainer<Container>($"{component.Name}-container", out var existing); if (existing) { foreach (var entity in component.AmmoContainer.ContainedEntities) { component.UnspawnedCount--; component.SpawnedAmmo.Push(entity); component.AmmoContainer.Insert(entity); } } } private void OnAmmoBoxExamine(EntityUid uid, AmmoBoxComponent component, ExaminedEvent args) { args.PushMarkup(Loc.GetString("ammo-box-component-on-examine-caliber-description", ("caliber", component.Caliber))); args.PushMarkup(Loc.GetString("ammo-box-component-on-examine-remaining-ammo-description", ("ammoLeft", component.AmmoLeft),("capacity", component.Capacity))); } private void OnAmmoBoxMapInit(EntityUid uid, AmmoBoxComponent component, MapInitEvent args) { component.UnspawnedCount += component.Capacity; UpdateAmmoBoxAppearance(uid, component); } private void UpdateAmmoBoxAppearance(EntityUid uid, AmmoBoxComponent ammoBox, AppearanceComponent? appearanceComponent = null) { if (!Resolve(uid, ref appearanceComponent, false)) return; appearanceComponent.SetData(MagazineBarrelVisuals.MagLoaded, true); appearanceComponent.SetData(AmmoVisuals.AmmoCount, ammoBox.AmmoLeft); appearanceComponent.SetData(AmmoVisuals.AmmoMax, ammoBox.Capacity); } private void AmmoBoxEjectContents(AmmoBoxComponent ammoBox, int count) { var ejectCount = Math.Min(count, ammoBox.Capacity); var ejectAmmo = new List<EntityUid>(ejectCount); for (var i = 0; i < Math.Min(count, ammoBox.Capacity); i++) { if (TakeAmmo(ammoBox) is not { } ammo) { break; } ejectAmmo.Add(ammo); } EjectCasings(ejectAmmo); UpdateAmmoBoxAppearance(ammoBox.Owner, ammoBox); } private bool TryUse(EntityUid user, AmmoBoxComponent ammoBox) { if (!TryComp(user, out HandsComponent? handsComponent)) { return false; } if (TakeAmmo(ammoBox) is not { } ammo) { return false; } if (TryComp(ammo, out ItemComponent? item)) { if (!handsComponent.CanPutInHand(item)) { TryInsertAmmo(user, ammo, ammoBox); return false; } handsComponent.PutInHand(item); } UpdateAmmoBoxAppearance(ammoBox.Owner, ammoBox); return true; } public bool TryInsertAmmo(EntityUid user, EntityUid ammo, AmmoBoxComponent ammoBox, AmmoComponent? ammoComponent = null) { if (!Resolve(ammo, ref ammoComponent, false)) { return false; } if (ammoComponent.Caliber != ammoBox.Caliber) { _popup.PopupEntity(Loc.GetString("ammo-box-component-try-insert-ammo-wrong-caliber"), ammo, Filter.Entities(user)); return false; } if (ammoBox.AmmoLeft >= ammoBox.Capacity) { _popup.PopupEntity(Loc.GetString("ammo-box-component-try-insert-ammo-no-room"), ammo, Filter.Entities(user)); return false; } ammoBox.SpawnedAmmo.Push(ammo); ammoBox.AmmoContainer.Insert(ammo); UpdateAmmoBoxAppearance(ammoBox.Owner, ammoBox); return true; } public EntityUid? TakeAmmo(AmmoBoxComponent ammoBox, TransformComponent? xform = null) { if (!Resolve(ammoBox.Owner, ref xform)) return null; if (ammoBox.SpawnedAmmo.TryPop(out var ammo)) { ammoBox.AmmoContainer.Remove(ammo); return ammo; } if (ammoBox.UnspawnedCount > 0) { ammo = EntityManager.SpawnEntity(ammoBox.FillPrototype, xform.Coordinates); // when dumping from held ammo box, this detaches the spawned ammo from the player. EntityManager.GetComponent<TransformComponent>(ammo).AttachParentToContainerOrGrid(); ammoBox.UnspawnedCount--; } return ammo; } }
/* ==================================================================== 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.HSSF.Record { using System; using System.Text; using System.Collections; using NPOI.Util; public enum BOFRecordType { Workbook = 0x05, VBModule = 0x06, Worksheet = 0x10, Chart = 0x20, Excel4Macro = 0x40, WorkspaceFile = 0x100 } /** * Title: Beginning Of File * Description: Somewhat of a misnomer, its used for the beginning of a Set of * records that have a particular pupose or subject. * Used in sheets and workbooks. * REFERENCE: PG 289 Microsoft Excel 97 Developer's Kit (ISBN: 1-57231-498-2) * @author Andrew C. Oliver * @author Jason Height (jheight at chariot dot net dot au) * @version 2.0-pre */ public class BOFRecord : StandardRecord { /** * for BIFF8 files the BOF is 0x809. For earlier versions it was 0x09 or 0x(biffversion)09 */ public const short sid = 0x809; private int field_1_version; private int field_2_type; private int field_3_build; private int field_4_year; private int field_5_history; private int field_6_rversion; /** * suggested default (0x06 - BIFF8) */ public const short VERSION = 0x06; /** * suggested default 0x10d3 */ public const short BUILD = 0x10d3; /** * suggested default 0x07CC (1996) */ public const short BUILD_YEAR = 0x07CC; // 1996 /** * suggested default for a normal sheet (0x41) */ public const short HISTORY_MASK = 0x41; /** * Constructs an empty BOFRecord with no fields Set. */ public BOFRecord() { } private BOFRecord(BOFRecordType type) { field_1_version = VERSION; field_2_type = (int) type; field_3_build = BUILD; field_4_year = BUILD_YEAR; field_5_history = 0x01; field_6_rversion = VERSION; } public static BOFRecord CreateSheetBOF() { return new BOFRecord(BOFRecordType.Worksheet); } /** * Constructs a BOFRecord and Sets its fields appropriately * @param in the RecordInputstream to Read the record from */ public BOFRecord(RecordInputStream in1) { field_1_version = in1.ReadShort(); field_2_type = in1.ReadShort(); // Some external tools don't generate all of // the remaining fields if (in1.Remaining >= 2) { field_3_build = in1.ReadShort(); } if (in1.Remaining >= 2) { field_4_year = in1.ReadShort(); } if (in1.Remaining >= 4) { field_5_history = in1.ReadInt(); } if (in1.Remaining >= 4) { field_6_rversion = in1.ReadInt(); } } /** * Version number - for BIFF8 should be 0x06 * @see #VERSION * @param version version to be Set */ public int Version { set { field_1_version = value; } get { return field_1_version; } } /** * Set the history bit mask (not very useful) * @see #HISTORY_MASK * @param bitmask bitmask to Set for the history */ public int HistoryBitMask { set { field_5_history = value; } get { return field_5_history; } } /** * Set the minimum version required to Read this file * * @see #VERSION * @param version version to Set */ public int RequiredVersion { set { field_6_rversion = value; } get { return field_6_rversion; } } /** * type of object this marks * @see #TYPE_WORKBOOK * @see #TYPE_VB_MODULE * @see #TYPE_WORKSHEET * @see #TYPE_CHART * @see #TYPE_EXCEL_4_MACRO * @see #TYPE_WORKSPACE_FILE * @return short type of object */ public BOFRecordType Type { get { return (BOFRecordType) field_2_type; } set { field_2_type = (int) value; } } private String TypeName { get { switch (Type) { case BOFRecordType.Chart: return "chart"; case BOFRecordType.Excel4Macro: return "excel 4 macro"; case BOFRecordType.VBModule: return "vb module"; case BOFRecordType.Workbook: return "workbook"; case BOFRecordType.Worksheet: return "worksheet"; case BOFRecordType.WorkspaceFile: return "workspace file"; } return "#error unknown type#"; } } /** * Get the build that wrote this file * @see #BUILD * @return short build number of the generator of this file */ public int Build { get { return field_3_build; } set { field_3_build = value; } } /** * Year of the build that wrote this file * @see #BUILD_YEAR * @return short build year of the generator of this file */ public int BuildYear { get { return field_4_year; } set { field_4_year = value; } } public override String ToString() { StringBuilder buffer = new StringBuilder(); buffer.Append("[BOF RECORD]\n"); buffer.Append(" .version = ") .Append(StringUtil.ToHexString(Version)).Append("\n"); buffer.Append(" .type = ") .Append(StringUtil.ToHexString((int) Type)).Append("\n"); buffer.Append(" (").Append(TypeName).Append(")").Append("\n"); buffer.Append(" .build = ") .Append(StringUtil.ToHexString(Build)).Append("\n"); buffer.Append(" .buildyear = ").Append(BuildYear) .Append("\n"); buffer.Append(" .history = ") .Append(StringUtil.ToHexString(HistoryBitMask)).Append("\n"); buffer.Append(" .requiredversion = ") .Append(StringUtil.ToHexString(RequiredVersion)).Append("\n"); buffer.Append("[/BOF RECORD]\n"); return buffer.ToString(); } public override void Serialize(ILittleEndianOutput out1) { out1.WriteShort(Version); out1.WriteShort((int) Type); out1.WriteShort(Build); out1.WriteShort(BuildYear); out1.WriteInt(HistoryBitMask); out1.WriteInt(RequiredVersion); } protected override int DataSize { get { return 16; } } public override short Sid { get { return sid; } } public override object Clone() { BOFRecord rec = new BOFRecord(); rec.field_1_version = field_1_version; rec.field_2_type = field_2_type; rec.field_3_build = field_3_build; rec.field_4_year = field_4_year; rec.field_5_history = field_5_history; rec.field_6_rversion = field_6_rversion; return rec; } } }
// Copyright 2011 The Noda Time Authors. All rights reserved. // Use of this source code is governed by the Apache License 2.0, // as found in the LICENSE.txt file. using System.Collections.Generic; using System.Globalization; using System.Linq; using NodaTime.Properties; using NodaTime.Text; using NUnit.Framework; namespace NodaTime.Test.Text { [TestFixture] public class LocalDateTimePatternTest : PatternTestBase<LocalDateTime> { private static readonly LocalDateTime SampleLocalDateTime = new LocalDateTime(1976, 6, 19, 21, 13, 34).PlusNanoseconds(123456789L); private static readonly LocalDateTime SampleLocalDateTimeToTicks = new LocalDateTime(1976, 6, 19, 21, 13, 34).PlusNanoseconds(123456700L); private static readonly LocalDateTime SampleLocalDateTimeToMillis = new LocalDateTime(1976, 6, 19, 21, 13, 34, 123); private static readonly LocalDateTime SampleLocalDateTimeToSeconds = new LocalDateTime(1976, 6, 19, 21, 13, 34); private static readonly LocalDateTime SampleLocalDateTimeToMinutes = new LocalDateTime(1976, 6, 19, 21, 13); internal static readonly LocalDateTime SampleLocalDateTimeCoptic = new LocalDateTime(1976, 6, 19, 21, 13, 34, CalendarSystem.Coptic).PlusNanoseconds(123456789L); private static readonly string[] AllStandardPatterns = { "f", "F", "g", "G", "o", "O", "s" }; #pragma warning disable 0414 // Used by tests via reflection - do not remove! private static readonly object[] AllCulturesStandardPatterns = (from culture in Cultures.AllCultures from format in AllStandardPatterns select new TestCaseData(culture, format).SetName(culture + ": " + format)).ToArray(); #pragma warning restore 0414 // The standard example date/time used in all the MSDN samples, which means we can just cut and paste // the expected results of the standard patterns. internal static readonly LocalDateTime MsdnStandardExample = new LocalDateTime(2009, 06, 15, 13, 45, 30, 90); internal static readonly LocalDateTime MsdnStandardExampleNoMillis = new LocalDateTime(2009, 06, 15, 13, 45, 30); private static readonly LocalDateTime MsdnStandardExampleNoSeconds = new LocalDateTime(2009, 06, 15, 13, 45); internal static readonly Data[] InvalidPatternData = { new Data { Pattern = "dd MM yyyy HH:MM:SS", Message = Messages.Parse_RepeatedFieldInPattern, Parameters = { 'M' } }, // Note incorrect use of "y" (year) instead of "Y" (year of era) new Data { Pattern = "dd MM yyyy HH:mm:ss gg", Message = Messages.Parse_EraWithoutYearOfEra }, // Era specifier and calendar specifier in the same pattern. new Data { Pattern = "dd MM YYYY HH:mm:ss gg c", Message = Messages.Parse_CalendarAndEra }, }; internal static Data[] ParseFailureData = { new Data { Pattern = "dd MM yyyy HH:mm:ss", Text = "Complete mismatch", Message = Messages.Parse_MismatchedNumber, Parameters = { "dd" }}, new Data { Pattern = "(c)", Text = "(xxx)", Message = Messages.Parse_NoMatchingCalendarSystem }, // 24 as an hour is only valid when the time is midnight new Data { Pattern = "yyyy-MM-dd HH:mm:ss", Text = "2011-10-19 24:00:05", Message = Messages.Parse_InvalidHour24 }, new Data { Pattern = "yyyy-MM-dd HH:mm:ss", Text = "2011-10-19 24:01:00", Message = Messages.Parse_InvalidHour24 }, new Data { Pattern = "yyyy-MM-dd HH:mm", Text = "2011-10-19 24:01", Message = Messages.Parse_InvalidHour24 }, new Data { Pattern = "yyyy-MM-dd HH:mm", Text = "2011-10-19 24:00", Template = new LocalDateTime(1970, 1, 1, 0, 0, 5), Message = Messages.Parse_InvalidHour24}, new Data { Pattern = "yyyy-MM-dd HH", Text = "2011-10-19 24", Template = new LocalDateTime(1970, 1, 1, 0, 5, 0), Message = Messages.Parse_InvalidHour24}, }; internal static Data[] ParseOnlyData = { new Data(2011, 10, 19, 16, 05, 20) { Pattern = "dd MM yyyy", Text = "19 10 2011", Template = new LocalDateTime(2000, 1, 1, 16, 05, 20) }, new Data(2011, 10, 19, 16, 05, 20) { Pattern = "HH:mm:ss", Text = "16:05:20", Template = new LocalDateTime(2011, 10, 19, 0, 0, 0) }, // Parsing using the semi-colon "comma dot" specifier new Data(2011, 10, 19, 16, 05, 20, 352) { Pattern = "yyyy-MM-dd HH:mm:ss;fff", Text = "2011-10-19 16:05:20,352" }, new Data(2011, 10, 19, 16, 05, 20, 352) { Pattern = "yyyy-MM-dd HH:mm:ss;FFF", Text = "2011-10-19 16:05:20,352" }, // 24:00 meaning "start of next day" new Data(2011, 10, 20) { Pattern = "yyyy-MM-dd HH:mm:ss", Text = "2011-10-19 24:00:00" }, new Data(2011, 10, 20) { Pattern = "yyyy-MM-dd HH:mm:ss", Text = "2011-10-19 24:00:00", Template = new LocalDateTime(1970, 1, 1, 0, 5, 0) }, new Data(2011, 10, 20) { Pattern = "yyyy-MM-dd HH:mm", Text = "2011-10-19 24:00" }, new Data(2011, 10, 20) { Pattern = "yyyy-MM-dd HH", Text = "2011-10-19 24" }, }; internal static Data[] FormatOnlyData = { new Data(2011, 10, 19, 16, 05, 20) { Pattern = "ddd yyyy", Text = "Wed 2011" }, }; internal static Data[] FormatAndParseData = { // Standard patterns (US) // Full date/time (short time) new Data(MsdnStandardExampleNoSeconds) { Pattern = "f", Text = "Monday, June 15, 2009 1:45 PM", Culture = Cultures.EnUs }, // Full date/time (long time) new Data(MsdnStandardExampleNoMillis) { Pattern = "F", Text = "Monday, June 15, 2009 1:45:30 PM", Culture = Cultures.EnUs }, // General date/time (short time) new Data(MsdnStandardExampleNoSeconds) { Pattern = "g", Text = "6/15/2009 1:45 PM", Culture = Cultures.EnUs }, // General date/time (longtime) new Data(MsdnStandardExampleNoMillis) { Pattern = "G", Text = "6/15/2009 1:45:30 PM", Culture = Cultures.EnUs }, // Round-trip (o and O - same effect) new Data(MsdnStandardExample) { Pattern = "o", Text = "2009-06-15T13:45:30.0900000", Culture = Cultures.EnUs }, new Data(MsdnStandardExample) { Pattern = "O", Text = "2009-06-15T13:45:30.0900000", Culture = Cultures.EnUs }, new Data(MsdnStandardExample) { Pattern = "r", Text = "2009-06-15T13:45:30.090000000 (ISO)", Culture = Cultures.EnUs }, new Data(SampleLocalDateTimeCoptic) { Pattern = "r", Text = "1976-06-19T21:13:34.123456789 (Coptic)", Culture = Cultures.EnUs }, // Note: No RFC1123, as that requires a time zone. // Sortable / ISO8601 new Data(MsdnStandardExampleNoMillis) { Pattern = "s", Text = "2009-06-15T13:45:30", Culture = Cultures.EnUs }, // Standard patterns (French) new Data(MsdnStandardExampleNoSeconds) { Pattern = "f", Text = "lundi 15 juin 2009 13:45", Culture = Cultures.FrFr }, new Data(MsdnStandardExampleNoMillis) { Pattern = "F", Text = "lundi 15 juin 2009 13:45:30", Culture = Cultures.FrFr }, new Data(MsdnStandardExampleNoSeconds) { Pattern = "g", Text = "15/06/2009 13:45", Culture = Cultures.FrFr }, new Data(MsdnStandardExampleNoMillis) { Pattern = "G", Text = "15/06/2009 13:45:30", Culture = Cultures.FrFr }, // Culture has no impact on round-trip or sortable formats new Data(MsdnStandardExample) { Pattern = "o", Text = "2009-06-15T13:45:30.0900000", Culture = Cultures.FrFr }, new Data(MsdnStandardExample) { Pattern = "O", Text = "2009-06-15T13:45:30.0900000", Culture = Cultures.FrFr }, new Data(MsdnStandardExample) { Pattern = "r", Text = "2009-06-15T13:45:30.090000000 (ISO)", Culture = Cultures.FrFr }, new Data(MsdnStandardExampleNoMillis) { Pattern = "s", Text = "2009-06-15T13:45:30", Culture = Cultures.FrFr }, // Calendar patterns are invariant new Data(MsdnStandardExample) { Pattern = "(c) yyyy-MM-dd'T'HH:mm:ss.FFFFFFFFF", Text = "(ISO) 2009-06-15T13:45:30.09", Culture = Cultures.FrFr }, new Data(MsdnStandardExample) { Pattern = "yyyy-MM-dd(c)'T'HH:mm:ss.FFFFFFFFF", Text = "2009-06-15(ISO)T13:45:30.09", Culture = Cultures.EnUs }, new Data(SampleLocalDateTimeCoptic) { Pattern = "(c) yyyy-MM-dd'T'HH:mm:ss.FFFFFFFFF", Text = "(Coptic) 1976-06-19T21:13:34.123456789", Culture = Cultures.FrFr }, new Data(SampleLocalDateTimeCoptic) { Pattern = "yyyy-MM-dd'C'c'T'HH:mm:ss.FFFFFFFFF", Text = "1976-06-19CCopticT21:13:34.123456789", Culture = Cultures.EnUs }, // Use of the semi-colon "comma dot" specifier new Data(2011, 10, 19, 16, 05, 20, 352) { Pattern = "yyyy-MM-dd HH:mm:ss;fff", Text = "2011-10-19 16:05:20.352" }, new Data(2011, 10, 19, 16, 05, 20, 352) { Pattern = "yyyy-MM-dd HH:mm:ss;FFF", Text = "2011-10-19 16:05:20.352" }, new Data(2011, 10, 19, 16, 05, 20, 352) { Pattern = "yyyy-MM-dd HH:mm:ss;FFF 'end'", Text = "2011-10-19 16:05:20.352 end" }, new Data(2011, 10, 19, 16, 05, 20) { Pattern = "yyyy-MM-dd HH:mm:ss;FFF 'end'", Text = "2011-10-19 16:05:20 end" }, // When the AM designator is a leading substring of the PM designator... new Data(2011, 10, 19, 16, 05, 20) { Pattern = "yyyy-MM-dd h:mm:ss tt", Text = "2011-10-19 4:05:20 FooBar", Culture = Cultures.AwkwardAmPmDesignatorCulture }, new Data(2011, 10, 19, 4, 05, 20) { Pattern = "yyyy-MM-dd h:mm:ss tt", Text = "2011-10-19 4:05:20 Foo", Culture = Cultures.AwkwardAmPmDesignatorCulture }, // Current culture decimal separator is irrelevant when trimming the dot for truncated fractional settings new Data(2011, 10, 19, 4, 5, 6) { Pattern="yyyy-MM-dd HH:mm:ss.FFF", Text="2011-10-19 04:05:06", Culture = Cultures.FrFr }, new Data(2011, 10, 19, 4, 5, 6, 123) { Pattern="yyyy-MM-dd HH:mm:ss.FFF", Text="2011-10-19 04:05:06.123", Culture = Cultures.FrFr }, // Check that unquoted T still works. new Data(2012, 1, 31, 17, 36, 45) { Text = "2012-01-31T17:36:45", Pattern = "yyyy-MM-ddTHH:mm:ss" }, }; internal static IEnumerable<Data> ParseData = ParseOnlyData.Concat(FormatAndParseData); internal static IEnumerable<Data> FormatData = FormatOnlyData.Concat(FormatAndParseData); [Test] [TestCaseSource("AllCulturesStandardPatterns")] public void BclStandardPatternComparison(CultureInfo culture, string pattern) { AssertBclNodaEquality(culture, pattern); } [Test] [TestCaseSource("AllCulturesStandardPatterns")] public void ParseFormattedStandardPattern(CultureInfo culture, string patternText) { var pattern = CreatePatternOrNull(patternText, culture, new LocalDateTime(2000, 1, 1, 0, 0)); if (pattern == null) { return; } // If the pattern really can't distinguish between AM and PM (e.g. it's 12 hour with an // abbreviated AM/PM designator) then let's let it go. if (pattern.Format(SampleLocalDateTime) == pattern.Format(SampleLocalDateTime.PlusHours(-12))) { return; } // If the culture doesn't have either AM or PM designators, we'll end up using the template value // AM/PM, so let's make sure that's right. (This happens on Mono for a few cultures.) if (culture.DateTimeFormat.AMDesignator == "" && culture.DateTimeFormat.PMDesignator == "") { pattern = pattern.WithTemplateValue(new LocalDateTime(2000, 1, 1, 12, 0)); } string formatted = pattern.Format(SampleLocalDateTime); var parseResult = pattern.Parse(formatted); Assert.IsTrue(parseResult.Success); var parsed = parseResult.Value; Assert.That(parsed, Is.EqualTo(SampleLocalDateTime) | Is.EqualTo(SampleLocalDateTimeToTicks) | Is.EqualTo(SampleLocalDateTimeToMillis) | Is.EqualTo(SampleLocalDateTimeToSeconds) | Is.EqualTo(SampleLocalDateTimeToMinutes)); } private void AssertBclNodaEquality(CultureInfo culture, string patternText) { // On Mono, some general patterns include an offset at the end. For the moment, ignore them. // TODO(V1.2): Work out what to do in such cases... if ((patternText == "f" && culture.DateTimeFormat.ShortTimePattern.EndsWith("z")) || (patternText == "F" && culture.DateTimeFormat.FullDateTimePattern.EndsWith("z")) || (patternText == "g" && culture.DateTimeFormat.ShortTimePattern.EndsWith("z")) || (patternText == "G" && culture.DateTimeFormat.LongTimePattern.EndsWith("z"))) { return; } var pattern = CreatePatternOrNull(patternText, culture, LocalDateTimePattern.DefaultTemplateValue); if (pattern == null) { return; } // Formatting a DateTime with an always-invariant pattern (round-trip, sortable) converts to the ISO // calendar in .NET (which is reasonable, as there's no associated calendar). // We should use the Gregorian calendar for those tests. // However, on Mono (at least some versions) the round-trip format (o and O) is broken - it uses // the calendar of the culture instead of the ISO-8601 calendar. So for those cultures, // we'll skip round-trip format tests. // See https://bugzilla.xamarin.com/show_bug.cgi?id=11364 bool alwaysInvariantPattern = "Oos".Contains(patternText); if (alwaysInvariantPattern && TestHelper.IsRunningOnMono && !(culture.Calendar is GregorianCalendar)) { return; } Calendar calendar = alwaysInvariantPattern ? CultureInfo.InvariantCulture.Calendar : culture.Calendar; var calendarSystem = CalendarSystemForCalendar(calendar); if (calendarSystem == null) { // We can't map this calendar system correctly yet; the test would be invalid. return; } // Use the sample date/time, but in the target culture's calendar system, as near as we can get. // We need to specify the right calendar system so that the days of week align properly. var inputValue = SampleLocalDateTime.WithCalendar(calendarSystem); Assert.AreEqual(inputValue.ToDateTimeUnspecified().ToString(patternText, culture), pattern.Format(inputValue)); } // Helper method to make it slightly easier for tests to skip "bad" cultures. private LocalDateTimePattern CreatePatternOrNull(string patternText, CultureInfo culture, LocalDateTime templateValue) { try { return LocalDateTimePattern.Create(patternText, culture); } catch (InvalidPatternException) { // The Malta long date/time pattern in Mono 3.0 is invalid (not just wrong; invalid due to the wrong number of quotes). // Skip it :( // See https://bugzilla.xamarin.com/show_bug.cgi?id=11363 return null; } } public sealed class Data : PatternTestData<LocalDateTime> { // Default to the start of the year 2000. protected override LocalDateTime DefaultTemplate => LocalDateTimePattern.DefaultTemplateValue; /// <summary> /// Initializes a new instance of the <see cref="Data" /> class. /// </summary> /// <param name="value">The value.</param> public Data(LocalDateTime value) : base(value) { } public Data(int year, int month, int day) : this(new LocalDateTime(year, month, day, 0, 0)) { } public Data(int year, int month, int day, int hour, int minute, int second) : this(new LocalDateTime(year, month, day, hour, minute, second)) { } public Data(int year, int month, int day, int hour, int minute, int second, int millis) : this(new LocalDateTime(year, month, day, hour, minute, second, millis)) { } public Data(LocalDate date, LocalTime time) : this(date + time) { } public Data() : this(LocalDateTimePattern.DefaultTemplateValue) { } internal override IPattern<LocalDateTime> CreatePattern() => LocalDateTimePattern.CreateWithInvariantCulture(Pattern) .WithTemplateValue(Template) .WithCulture(Culture); } } }
using System.Collections.Generic; using CSharpGuidelinesAnalyzer.Rules.Framework; using CSharpGuidelinesAnalyzer.Test.TestDataBuilders; using Microsoft.CodeAnalysis.Diagnostics; using Xunit; namespace CSharpGuidelinesAnalyzer.Test.Specs.Framework { public sealed class PreferLanguageSyntaxOverCallingImplementationSpecs : CSharpGuidelinesAnalysisTestFixture { protected override string DiagnosticId => PreferLanguageSyntaxOverCallingImplementationAnalyzer.DiagnosticId; [Fact] internal void When_nullable_value_type_is_checked_for_null_using_null_check_it_must_be_skipped() { // Arrange ParsedSourceCode source = new MemberSourceCodeBuilder() .InDefaultClass(@" void M(int? i) { if (i == null) { } if (i != null) { } } ") .Build(); // Act and assert VerifyGuidelineDiagnostic(source); } [Fact] internal void When_nullable_value_type_is_checked_for_null_using_Nullable_HasValue_property_it_must_be_reported() { // Arrange ParsedSourceCode source = new MemberSourceCodeBuilder() .InDefaultClass(@" void M(int? i) { if ([|i.HasValue|]) { } if (![|i.HasValue|]) { } } ") .Build(); // Act and assert VerifyGuidelineDiagnostic(source, "Replace call to Nullable<T>.HasValue with null check", "Replace call to Nullable<T>.HasValue with null check"); } [Fact] internal void When_nullable_value_type_is_compared_to_numeric_constant_it_must_be_skipped() { // Arrange ParsedSourceCode source = new MemberSourceCodeBuilder() .InDefaultClass(@" void M(int? i) { if (i > 5) { } if (i < 5.0) { } if (i <= 3.0f) { } if (i >= 3.0m) { } if (i == 8u) { } if (i != 8L) { } } ") .Build(); // Act and assert VerifyGuidelineDiagnostic(source); } [Fact] internal void When_nullable_value_type_is_compared_to_numeric_type_it_must_be_skipped() { // Arrange ParsedSourceCode source = new MemberSourceCodeBuilder() .InDefaultClass(@" void M(int? i) { if (i > GetNumber()) { } if (i < GetNumber()) { } if (i <= GetNumber()) { } if (i >= GetNumber()) { } if (i == GetNumber()) { } if (i != GetNumber()) { } } int GetNumber() => throw null; ") .Build(); // Act and assert VerifyGuidelineDiagnostic(source); } [Fact] internal void When_nullable_value_type_is_checked_for_null_in_various_ways_and_compared_to_number_it_must_be_reported() { // Arrange ParsedSourceCode source = new MemberSourceCodeBuilder() .Using(typeof(EqualityComparer<>).Namespace) .InDefaultClass(@" void M(int? i) { if ([|i != null && i > 5|]) { } if ([|i.HasValue && i > 5|]) { } if ([|!(i is null) && i < 5|]) { } if ([|!i.Equals(null) && i <= 3|]) { } if ([|!object.Equals(i, null) && i >= 3|]) { } if ([|!object.ReferenceEquals(i, null) && i > 8|]) { } if ([|!EqualityComparer<int?>.Default.Equals(i, null) && i < 8|]) { } } ") .Build(); // Act and assert VerifyGuidelineDiagnostic(source, "Remove null check in numeric comparison", "Remove null check in numeric comparison", "Remove null check in numeric comparison", "Remove null check in numeric comparison", "Remove null check in numeric comparison", "Remove null check in numeric comparison", "Remove null check in numeric comparison"); } [Fact] internal void When_nullable_value_type_is_checked_for_null_in_various_ways_and_compared_to_number_value_it_must_be_reported() { // Arrange ParsedSourceCode source = new MemberSourceCodeBuilder() .Using(typeof(EqualityComparer<>).Namespace) .InDefaultClass(@" void M(int? i) { if ([|i != null && i.Value > 5|]) { } if ([|!(i is null) && i.Value < 5|]) { } if ([|!i.Equals(null) && i.Value <= 3|]) { } if ([|!object.Equals(i, null) && i.Value >= 3|]) { } if ([|!object.ReferenceEquals(i, null) && i.Value == 8|]) { } if ([|!EqualityComparer<int?>.Default.Equals(i, null) && i.Value == 8|]) { } } ") .Build(); // Act and assert VerifyGuidelineDiagnostic(source, "Remove null check in numeric comparison", "Remove null check in numeric comparison", "Remove null check in numeric comparison", "Remove null check in numeric comparison", "Remove null check in numeric comparison", "Remove null check in numeric comparison"); } [Fact] internal void When_nullable_value_type_is_checked_for_null_and_same_argument_is_compared_to_number_it_must_be_reported() { // Arrange ParsedSourceCode source = new TypeSourceCodeBuilder() .InGlobalScope(@" class C { int? P { get; set; } int? F; void M(int? i, int?[] j, int?[] k, dynamic d) { if ([|i != null && i > 5|]) { } if ([|j[0] != null && j[0] > 5|]) { } if ([|k[i.Value + 1] != null && k[i.Value + 1] > 5|]) { } if ([|!(P is null) && P > 5|]) { } if ([|F != null && F > 5|]) { } int? l = i; if ([|l != null && l > 5|]) { } } } ") .Build(); // Act and assert VerifyGuidelineDiagnostic(source, "Remove null check in numeric comparison", "Remove null check in numeric comparison", "Remove null check in numeric comparison", "Remove null check in numeric comparison", "Remove null check in numeric comparison", "Remove null check in numeric comparison"); } [Fact] internal void When_nullable_value_type_is_checked_for_null_and_same_argument_is_compared_to_number_value_it_must_be_reported() { // Arrange ParsedSourceCode source = new TypeSourceCodeBuilder() .InGlobalScope(@" class C { int? P { get; set; } int? F; void M(int? i, int?[] j, int?[] k, dynamic d) { if ([|i != null && i.Value > 5|]) { } if ([|j[0] != null && j[0].Value > 5|]) { } if ([|k[i.Value + 1] != null && k[i.Value + 1].Value > 5|]) { } if ([|!(P is null) && P.Value > 5|]) { } if ([|F != null && F.Value > 5|]) { } int? l = i; if ([|l != null && l.Value > 5|]) { } } } ") .Build(); // Act and assert VerifyGuidelineDiagnostic(source, "Remove null check in numeric comparison", "Remove null check in numeric comparison", "Remove null check in numeric comparison", "Remove null check in numeric comparison", "Remove null check in numeric comparison", "Remove null check in numeric comparison"); } [Fact] internal void When_nullable_value_type_is_checked_for_null_and_different_argument_is_compared_to_number_it_must_be_skipped() { // Arrange ParsedSourceCode source = new TypeSourceCodeBuilder() .InGlobalScope(@" class C { void M(int? i, int? other, int?[] array, dynamic k) { if (i != null && other > 5) { } if (array[0] != null && array[1] > 5) { } if (k.M() != null && k.M() > 5) { } if (N() != null && N() > 5) { } if (this != null && this > 5) { } } int? N() => throw null; public static bool operator >(C left, int right) => throw null; public static bool operator <(C left, int right) => throw null; } ") .Build(); // Act and assert VerifyGuidelineDiagnostic(source); } [Fact] internal void When_nullable_value_type_is_checked_for_null_and_same_argument_is_compared_for_non_equality_to_nullable_value_it_must_be_reported() { // Arrange ParsedSourceCode source = new TypeSourceCodeBuilder() .InGlobalScope(@" class C { void M(int? i, int? j) { if (i != null && i == j) { } if (i != null && i.Value == j) { } if (i != null && i != j) { } if (i != null && i.Value != j) { } if (i != null && i != 123) { } if (i != null && i.Value != 123) { } if ([|i != null && i > j|]) { } if ([|i != null && i.Value > j|]) { } if ([|i != null && i >= j|]) { } if ([|i != null && i.Value >= j|]) { } if ([|i != null && i < j|]) { } if ([|i != null && i.Value < j|]) { } if ([|i != null && i <= j|]) { } if ([|i != null && i.Value <= j|]) { } } } ") .Build(); // Act and assert VerifyGuidelineDiagnostic(source, "Remove null check in numeric comparison", "Remove null check in numeric comparison", "Remove null check in numeric comparison", "Remove null check in numeric comparison", "Remove null check in numeric comparison", "Remove null check in numeric comparison", "Remove null check in numeric comparison", "Remove null check in numeric comparison"); } [Fact] internal void When_nullable_type_is_used_in_nameof_it_must_be_skipped() { // Arrange ParsedSourceCode source = new TypeSourceCodeBuilder() .InGlobalScope(@" class C { void M(string s) { if (s != nameof(Nullable<int>.HasValue)) { } } } ") .Build(); // Act and assert VerifyGuidelineDiagnostic(source); } protected override DiagnosticAnalyzer CreateAnalyzer() { return new PreferLanguageSyntaxOverCallingImplementationAnalyzer(); } } }
// // 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.Text; using System.Windows.Automation; namespace SelectionPatternSample { /// -------------------------------------------------------------------- /// <summary> /// UI Automation worker class. /// </summary> /// -------------------------------------------------------------------- internal class TargetHandler { private readonly MainWindow _clientApp; private readonly AutomationElement _targetApp; private StringBuilder _feedbackText; private AutomationElement _rootElement; private AutomationEventHandler _targetCloseListener; /// -------------------------------------------------------------------- /// <summary> /// Constructor. /// </summary> /// <param name="client">The client application.</param> /// <param name="target">The target application.</param> /// <remarks> /// Initializes components. /// </remarks> /// -------------------------------------------------------------------- internal TargetHandler(MainWindow client, AutomationElement target) { // Initialize member variables. _clientApp = client; _targetApp = target; } /// -------------------------------------------------------------------- /// <summary> /// The collection of Selection controls in the target. /// </summary> /// -------------------------------------------------------------------- internal AutomationElementCollection TargetControls { get; private set; } /// -------------------------------------------------------------------- /// <summary> /// Start the UI Automation worker. /// </summary> /// -------------------------------------------------------------------- internal void StartWork() { // Get UI Automation root element. _rootElement = AutomationElement.RootElement; // Position the target relative to the client. var clientLocationTop = _clientApp.Top; var clientLocationRight = _clientApp.Width + _clientApp.Left + 100; var transformPattern = _targetApp.GetCurrentPattern(TransformPattern.Pattern) as TransformPattern; transformPattern?.Move(clientLocationRight, clientLocationTop); RegisterTargetClosedListener(); // Get the target controls. CompileTargetControls(); } /// -------------------------------------------------------------------- /// <summary> /// Register the target closed event listener. /// </summary> /// -------------------------------------------------------------------- private void RegisterTargetClosedListener() { _targetCloseListener = OnTargetClosed; Automation.AddAutomationEventHandler( WindowPattern.WindowClosedEvent, _targetApp, TreeScope.Element, _targetCloseListener); } /// -------------------------------------------------------------------- /// <summary> /// The target closed event handler. /// </summary> /// <param name="src">Object that raised the event.</param> /// <param name="e">Event arguments.</param> /// <remarks> /// Changes the state of client controls and removes event listeners. /// </remarks> /// -------------------------------------------------------------------- private void OnTargetClosed(object src, AutomationEventArgs e) { Feedback("Target has been closed. Please wait."); // Automation.RemoveAllEventHandlers is not used here since we don't // want to lose the window closed event listener for the target. RemoveTargetSelectionEventHandlers(); Automation.RemoveAutomationEventHandler( WindowPattern.WindowClosedEvent, _targetApp, _targetCloseListener); _clientApp.SetClientControlState(MainWindow.ControlState.UIAStopped); Feedback(null); } /// -------------------------------------------------------------------- /// <summary> /// Finds the selection and selection item controls of interest /// and initializes necessary event listeners. /// </summary> /// <remarks> /// Handles the special case of two Selection controls being returned /// for a ComboBox control. /// </remarks> /// -------------------------------------------------------------------- private void CompileTargetControls() { var condition = new PropertyCondition( AutomationElement.IsSelectionPatternAvailableProperty, true); // A ComboBox is an aggregate control containing a ListBox // as a child. // Both the ComboBox and its child ListBox support the // SelectionPattern control pattern but all related // functionality is delegated to the child. // For the purposes of this sample we can filter the child // as we do not need to display the redundant information. var andCondition = new AndCondition( condition, new NotCondition( new PropertyCondition( AutomationElement.ClassNameProperty, "ComboLBox"))); TargetControls = _targetApp.FindAll(TreeScope.Children | TreeScope.Descendants, andCondition); _clientApp.EchoTargetControls(); } /// -------------------------------------------------------------------- /// <summary> /// Gets the currently selected SelectionItem objects from target. /// </summary> /// <param name="selectionContainer"> /// The target Selection container. /// </param> /// -------------------------------------------------------------------- internal AutomationElement[] GetTargetCurrentSelection( AutomationElement selectionContainer) { try { var selectionPattern = selectionContainer.GetCurrentPattern( SelectionPattern.Pattern) as SelectionPattern; return selectionPattern.Current.GetSelection(); } catch (InvalidOperationException exc) { Feedback(exc.Message); return null; } } /// -------------------------------------------------------------------- /// <summary> /// Subscribe to the selection events. /// </summary> /// <remarks> /// The events are raised by the SelectionItem elements, /// not the Selection container. /// </remarks> /// -------------------------------------------------------------------- internal void SetTargetSelectionEventHandlers() { foreach (AutomationElement control in TargetControls) { var selectionHandler = new AutomationEventHandler(TargetSelectionHandler); Automation.AddAutomationEventHandler( SelectionItemPattern.ElementSelectedEvent, control, TreeScope.Element | TreeScope.Descendants, selectionHandler); Automation.AddAutomationEventHandler( SelectionItemPattern.ElementAddedToSelectionEvent, control, TreeScope.Element | TreeScope.Descendants, selectionHandler); Automation.AddAutomationEventHandler( SelectionItemPattern.ElementRemovedFromSelectionEvent, control, TreeScope.Element | TreeScope.Descendants, selectionHandler); } } /// -------------------------------------------------------------------- /// <summary> /// Unsubscribe from the selection events. /// </summary> /// <remarks> /// The events are raised by the SelectionItem elements, /// not the Selection container. /// </remarks> /// -------------------------------------------------------------------- internal void RemoveTargetSelectionEventHandlers() { foreach (AutomationElement control in TargetControls) { var selectionHandler = new AutomationEventHandler(TargetSelectionHandler); Automation.RemoveAutomationEventHandler( SelectionItemPattern.ElementSelectedEvent, control, selectionHandler); Automation.RemoveAutomationEventHandler( SelectionItemPattern.ElementAddedToSelectionEvent, control, selectionHandler); Automation.RemoveAutomationEventHandler( SelectionItemPattern.ElementRemovedFromSelectionEvent, control, selectionHandler); } } /// -------------------------------------------------------------------- /// <summary> /// Handles user input in the target. /// </summary> /// <param name="src">Object that raised the event.</param> /// <param name="e">Event arguments.</param> /// -------------------------------------------------------------------- private void TargetSelectionHandler( object src, AutomationEventArgs e) { _feedbackText = new StringBuilder(); // Get the name of the item, which is equivalent to its text. var sourceItem = src as AutomationElement; var selectionItemPattern = sourceItem.GetCurrentPattern(SelectionItemPattern.Pattern) as SelectionItemPattern; AutomationElement sourceContainer; // Special case handling for composite controls. var treeWalker = new TreeWalker(new PropertyCondition( AutomationElement.IsSelectionPatternAvailableProperty, true)); sourceContainer = (treeWalker.GetParent( selectionItemPattern.Current.SelectionContainer) == null) ? selectionItemPattern.Current.SelectionContainer : treeWalker.GetParent( selectionItemPattern.Current.SelectionContainer); switch (e.EventId.ProgrammaticName) { case "SelectionItemPatternIdentifiers.ElementSelectedEvent": _feedbackText.Append(sourceItem.Current.Name) .Append(" of the ") .Append(sourceContainer.Current.AutomationId) .Append(" control was selected."); break; case "SelectionItemPatternIdentifiers.ElementAddedToSelectionEvent": _feedbackText.Append(sourceItem.Current.Name) .Append(" of the ") .Append(sourceContainer.Current.AutomationId) .Append(" control was added to the selection."); break; case "SelectionItemPatternIdentifiers.ElementRemovedFromSelectionEvent": _feedbackText.Append(sourceItem.Current.Name) .Append(" of the ") .Append(sourceContainer.Current.AutomationId) .Append(" control was removed from the selection."); break; } Feedback(_feedbackText.ToString()); for (var controlCounter = 0; controlCounter < TargetControls.Count; controlCounter++) { _clientApp.SetControlPropertiesText(controlCounter); _clientApp.EchoTargetControlSelections( TargetControls[controlCounter], controlCounter); _clientApp.EchoTargetControlProperties( TargetControls[controlCounter], controlCounter); } } /// -------------------------------------------------------------------- /// <summary> /// Gets the selection items from each target control. /// </summary> /// <param name="selectionContainer"> /// The target Selection container. /// </param> /// <returns> /// Automation elements that satisfy the specified conditions. /// </returns> /// -------------------------------------------------------------------- internal AutomationElementCollection GetSelectionItemsFromTarget(AutomationElement selectionContainer) { var condition = new PropertyCondition( AutomationElement.IsSelectionItemPatternAvailableProperty, true); return selectionContainer.FindAll(TreeScope.Children | TreeScope.Descendants, condition); } /// -------------------------------------------------------------------- /// <summary> /// Prints a line of text to the textbox. /// </summary> /// <param name="outputStr">The string to print.</param> /// -------------------------------------------------------------------- private void Feedback(string outputStr) { _clientApp.Feedback(outputStr); } } }
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 SampleIdentityTokenLayer.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; } } }
// ******************************************************************************************************** // Product Name: DotSpatial.Plugins.ShapeEditor.dll // Description: The data access libraries for the DotSpatial project. // ******************************************************************************************************** // // The Original Code is MapWindow.dll // // The Initial Developer of this Original Code is Ted Dunsford. Created 4/11/2009 9:24:49 AM // // Contributor(s): (Open source contributors should list themselves and their modifications here). // // ******************************************************************************************************** using System; using System.ComponentModel; using System.Globalization; using System.Windows.Forms; using DotSpatial.Symbology.Forms; using GeoAPI.Geometries; namespace DotSpatial.Plugins.ShapeEditor { /// <summary> /// A dialog that displays the coordinates while drawing shapes. /// </summary> public class CoordinateDialog : Form { private Button _btnClose; private Button _btnOk; private DoubleBox _dbxM; private DoubleBox _dbxX; private DoubleBox _dbxY; private DoubleBox _dbxZ; private bool _showM; private bool _showZ; private ToolTip _ttHelp; #region Private Variables /// <summary> /// Required designer variable. /// </summary> private IContainer components = null; #endregion #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(CoordinateDialog)); this._btnOk = new System.Windows.Forms.Button(); this._btnClose = new System.Windows.Forms.Button(); this._ttHelp = new System.Windows.Forms.ToolTip(this.components); this._dbxM = new DotSpatial.Symbology.Forms.DoubleBox(); this._dbxZ = new DotSpatial.Symbology.Forms.DoubleBox(); this._dbxY = new DotSpatial.Symbology.Forms.DoubleBox(); this._dbxX = new DotSpatial.Symbology.Forms.DoubleBox(); this.SuspendLayout(); // // _btnOk // resources.ApplyResources(this._btnOk, "_btnOk"); this._btnOk.DialogResult = System.Windows.Forms.DialogResult.OK; this._btnOk.Name = "_btnOk"; this._ttHelp.SetToolTip(this._btnOk, resources.GetString("_btnOk.ToolTip")); this._btnOk.UseVisualStyleBackColor = true; this._btnOk.Click += new System.EventHandler(this.OkButton_Click); // // _btnClose // resources.ApplyResources(this._btnClose, "_btnClose"); this._btnClose.Name = "_btnClose"; this._ttHelp.SetToolTip(this._btnClose, resources.GetString("_btnClose.ToolTip")); this._btnClose.UseVisualStyleBackColor = true; this._btnClose.Click += new System.EventHandler(this.CloseButton_Click); // // _dbxM // resources.ApplyResources(this._dbxM, "_dbxM"); this._dbxM.BackColorInvalid = System.Drawing.Color.Salmon; this._dbxM.BackColorRegular = System.Drawing.Color.Empty; this._dbxM.InvalidHelp = "The value entered could not be correctly parsed into a valid double precision flo" + "ating point value."; this._dbxM.IsValid = true; this._dbxM.Name = "_dbxM"; this._dbxM.NumberFormat = null; this._dbxM.RegularHelp = "Enter a double precision floating point value."; this._dbxM.Value = 0D; this._dbxM.ValidChanged += new System.EventHandler(this.Coordinate_ValidChanged); // // _dbxZ // resources.ApplyResources(this._dbxZ, "_dbxZ"); this._dbxZ.BackColorInvalid = System.Drawing.Color.Salmon; this._dbxZ.BackColorRegular = System.Drawing.Color.Empty; this._dbxZ.InvalidHelp = "The value entered could not be correctly parsed into a valid double precision flo" + "ating point value."; this._dbxZ.IsValid = true; this._dbxZ.Name = "_dbxZ"; this._dbxZ.NumberFormat = null; this._dbxZ.RegularHelp = "Enter a double precision floating point value."; this._dbxZ.Value = 0D; // // _dbxY // resources.ApplyResources(this._dbxY, "_dbxY"); this._dbxY.BackColorInvalid = System.Drawing.Color.Salmon; this._dbxY.BackColorRegular = System.Drawing.Color.Empty; this._dbxY.InvalidHelp = "The value entered could not be correctly parsed into a valid double precision flo" + "ating point value."; this._dbxY.IsValid = true; this._dbxY.Name = "_dbxY"; this._dbxY.NumberFormat = null; this._dbxY.RegularHelp = "Enter a double precision floating point value."; this._dbxY.Value = 0D; this._dbxY.ValidChanged += new System.EventHandler(this.Coordinate_ValidChanged); // // _dbxX // resources.ApplyResources(this._dbxX, "_dbxX"); this._dbxX.BackColorInvalid = System.Drawing.Color.Salmon; this._dbxX.BackColorRegular = System.Drawing.Color.Empty; this._dbxX.InvalidHelp = "The value entered could not be correctly parsed into a valid double precision flo" + "ating point value."; this._dbxX.IsValid = true; this._dbxX.Name = "_dbxX"; this._dbxX.NumberFormat = null; this._dbxX.RegularHelp = "Enter a double precision floating point value."; this._dbxX.Value = 0D; this._dbxX.ValidChanged += new System.EventHandler(this.Coordinate_ValidChanged); // // CoordinateDialog // resources.ApplyResources(this, "$this"); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.Controls.Add(this._dbxM); this.Controls.Add(this._dbxZ); this.Controls.Add(this._dbxY); this.Controls.Add(this._dbxX); this.Controls.Add(this._btnClose); this.Controls.Add(this._btnOk); this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "CoordinateDialog"; this.ShowIcon = false; this.TopMost = true; this.ResumeLayout(false); } #endregion #region Constructors /// <summary> /// Initializes a new instance of the CoordinateDialog class. /// </summary> public CoordinateDialog() { InitializeComponent(); _showM = true; _showZ = true; } #endregion #region Methods #endregion #region Properties /// <summary> /// Gets a coordinate based on the current values. /// </summary> public Coordinate Coordinate { get { Coordinate c = _showZ ? new Coordinate(_dbxX.Value, _dbxY.Value, _dbxZ.Value) : new Coordinate(_dbxX.Value, _dbxY.Value); if (_showM) { c.M = _dbxM.Value; } return c; } } /// <summary> /// Gets or sets a value indicating whether or not to show M values. /// </summary> public bool ShowMValues { get { return _showM; } set { if (_showM != value) { if (value == false) { _dbxM.Visible = false; Height -= 20; } else { _dbxM.Visible = true; Height += 20; } } _showM = value; } } /// <summary> /// Gets or sets a value indicating whether or not to show Z values. /// </summary> public bool ShowZValues { get { return _showZ; } set { if (_showZ != value) { if (value == false) { _dbxZ.Visible = false; _dbxM.Top -= 20; Height -= 20; } else { _dbxZ.Visible = true; _dbxM.Top += 20; Height += 20; } } _showZ = value; } } #endregion #region Events #endregion #region Event Handlers private void Coordinate_ValidChanged(object sender, EventArgs e) { UpdateOk(); } #endregion #region Protected Methods /// <summary> /// Prevents disposing this form when the user closes it. /// </summary> /// <param name="e">The CancelEventArgs parameter allows canceling the complete closure of this dialog.</param> protected override void OnClosing(CancelEventArgs e) { Hide(); e.Cancel = true; base.OnClosing(e); } #endregion #region Private Functions /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #endregion /// <summary> /// Gets or sets the X value. /// </summary> public double X { get { return _dbxX.Value; } set { _dbxX.Text = value.ToString(CultureInfo.CurrentCulture); } } /// <summary> /// Gets or sets the Y value. /// </summary> public double Y { get { return _dbxY.Value; } set { _dbxY.Text = value.ToString(CultureInfo.CurrentCulture); } } /// <summary> /// Gets or sets the Z value. /// </summary> public double Z { get { return _dbxZ.Value; } set { _dbxZ.Text = value.ToString(CultureInfo.CurrentCulture); } } /// <summary> /// Gets or sets the M vlaue. /// </summary> public double M { get { return _dbxM.Value; } set { _dbxM.Text = value.ToString(CultureInfo.CurrentCulture); } } /// <summary> /// Occurs when the ok button is clicked. /// </summary> public event EventHandler CoordinateAdded; private void CloseButton_Click(object sender, EventArgs e) { Hide(); } private void OkButton_Click(object sender, EventArgs e) { if (CoordinateAdded != null) { CoordinateAdded(this, EventArgs.Empty); } Hide(); } private void UpdateOk() { bool isValid = true; if (_dbxX.IsValid == false) { isValid = false; } if (_dbxY.IsValid == false) { isValid = false; } if (_showZ) { if (_dbxZ.IsValid == false) { isValid = false; } } if (_showM) { if (_dbxM.IsValid == false) { isValid = false; } } _btnOk.Enabled = isValid; } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Description; using SampleWebAPI.Areas.HelpPage.Models; namespace SampleWebAPI.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); model = GenerateApiModel(apiDescription, sampleGenerator); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HelpPageSampleGenerator sampleGenerator) { HelpPageApiModel apiModel = new HelpPageApiModel(); apiModel.ApiDescription = apiDescription; try { foreach (var item in sampleGenerator.GetSampleRequests(apiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception Message: {0}", e.Message)); } return apiModel; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Xunit; using System; using System.Xml; using System.Xml.XPath; using XPathTests.Common; namespace XPathTests.FunctionalTests.CoreFunctionLibrary.NodeSetFunctions { /// <summary> /// Core Function Library - Node Set Functions (matches) /// </summary> public static partial class MatchesTests { /// <summary> /// Expected: Selects the last element child of the context node. /// child::*[last()] /// </summary> [Fact] public static void MatchesTest231() { var xml = "xp005.xml"; var startingNodePath = "Doc/Test1/Child5"; var testExpression = @"child::*[last()]"; var expected = true; Utils.XPathMatchTest(xml, testExpression, expected, startingNodePath: startingNodePath); } /// <summary> /// Expected: Selects the second last element child of the context node. /// child::*[last() - 1] /// </summary> [Fact] public static void MatchesTest232() { var xml = "xp005.xml"; var startingNodePath = "Doc/Test1/Child4"; var testExpression = @"child::*[last() - 1]"; var expected = true; Utils.XPathMatchTest(xml, testExpression, expected, startingNodePath: startingNodePath); } /// <summary> /// Expected: Selects the last attribute node of the context node. /// attribute::*[last()] /// </summary> [Fact] public static void MatchesTest233() { var xml = "xp005.xml"; var startingNodePath = "Doc/Test1/@Attr5"; var testExpression = @"attribute::*[last()]"; var expected = true; Utils.XPathMatchTest(xml, testExpression, expected, startingNodePath: startingNodePath); } /// <summary> /// Expected: Selects the second last attribute node of the context node. /// attribute::*[last() - 1] /// </summary> [Fact] public static void MatchesTest234() { var xml = "xp005.xml"; var startingNodePath = "Doc/Test1"; var testExpression = @"attribute::*[last() - 1]"; var expected = new XPathResult(0, new XPathResultToken { NodeType = XPathNodeType.Attribute, LocalName = "Attr4", Name = "Attr4", HasNameTable = true, Value = "Fourth" }); ; Utils.XPathNodesetTest(xml, testExpression, expected, startingNodePath: startingNodePath); } /// <summary> /// Expected: Selects the last element child of the context node. /// child::*[position() = last()] /// </summary> [Fact] public static void MatchesTest235() { var xml = "xp005.xml"; var startingNodePath = "Doc/Test1/Child5"; var testExpression = @"child::*[position() = last()]"; var expected = true; Utils.XPathMatchTest(xml, testExpression, expected, startingNodePath: startingNodePath); } /// <summary> /// Expected: True (based on context node). /// *[position() = last()] (Matches = true) /// </summary> [Fact] public static void MatchesTest236() { var xml = "xp005.xml"; var startingNodePath = "Doc/Test1/Child5"; var testExpression = @"*[position() = last()]"; var expected = true; Utils.XPathMatchTest(xml, testExpression, expected, startingNodePath: startingNodePath); } /// <summary> /// Expected: False (based on context node). /// *[position() = last()] (Matches = false) /// </summary> [Fact] public static void MatchesTest237() { var xml = "xp005.xml"; var startingNodePath = "Doc/Test1/Child4"; var testExpression = @"*[position() = last()]"; var expected = false; Utils.XPathMatchTest(xml, testExpression, expected, startingNodePath: startingNodePath); } /// <summary> /// Expected: True (based on context node). /// @*[position() = last()] (Matches = true) /// </summary> [Fact] public static void MatchesTest238() { var xml = "xp005.xml"; var startingNodePath = "Doc/Test1/@Attr5"; var testExpression = @"@*[position() = last()]"; var expected = true; Utils.XPathMatchTest(xml, testExpression, expected, startingNodePath: startingNodePath); } /// <summary> /// Expected: False (based on context node). /// @*[position() = last()] (Matches = false) /// </summary> [Fact] public static void MatchesTest239() { var xml = "xp005.xml"; var startingNodePath = "Doc/Test1/@Attr4"; var testExpression = @"@*[position() = last()]"; var expected = false; Utils.XPathMatchTest(xml, testExpression, expected, startingNodePath: startingNodePath); } /// <summary> /// Expected: True (based on context node). /// *[last() = 1] (Matches = true) /// </summary> [Fact] public static void MatchesTest2310() { var xml = "xp005.xml"; var startingNodePath = "Doc/Test2/Child1"; var testExpression = @"*[last() = 1]"; var expected = true; Utils.XPathMatchTest(xml, testExpression, expected, startingNodePath: startingNodePath); } /// <summary> /// Expected: True (based on context node). /// *[last() = 1] (Matches = false) /// </summary> [Fact] public static void MatchesTest2311() { var xml = "xp005.xml"; var startingNodePath = "Doc/Test1/Child1"; var testExpression = @"*[last() = 1]"; var expected = false; Utils.XPathMatchTest(xml, testExpression, expected, startingNodePath: startingNodePath); } /// <summary> /// Expected: Selects the 2nd element child of the context node. /// child::*[position() = 2] /// </summary> [Fact] public static void MatchesTest2312() { var xml = "xp005.xml"; var startingNodePath = "Doc/Test1/Child2"; var testExpression = @"child::*[position() = 2]"; var expected = true; Utils.XPathMatchTest(xml, testExpression, expected, startingNodePath: startingNodePath); } /// <summary> /// Expected: Selects the 2nd attribute of the context node. /// attribute::*[position() = 2] /// </summary> [Fact] public static void MatchesTest2313() { var xml = "xp005.xml"; var startingNodePath = "Doc/Test1/@Attr2"; var testExpression = @"attribute::*[position() = 2]"; var expected = true; Utils.XPathMatchTest(xml, testExpression, expected, startingNodePath: startingNodePath); } /// <summary> /// Expected: Selects the 2nd element child of the context node. /// child::*[2] /// </summary> [Fact] public static void MatchesTest2314() { var xml = "xp005.xml"; var startingNodePath = "Doc/Test1/Child2"; var testExpression = @"child::*[2]"; var expected = true; Utils.XPathMatchTest(xml, testExpression, expected, startingNodePath: startingNodePath); } /// <summary> /// Expected: Selects the 2nd attribute of the context node. /// attribute::*[2] /// </summary> [Fact] public static void MatchesTest2315() { var xml = "xp005.xml"; var startingNodePath = "Doc/Test1/@Attr2"; var testExpression = @"attribute::*[2]"; var expected = true; Utils.XPathMatchTest(xml, testExpression, expected, startingNodePath: startingNodePath); } /// <summary> /// Expected: Selects all element children of the context node except the first two. /// child::*[position() > 2] /// </summary> [Fact] public static void MatchesTest2316() { var xml = "xp005.xml"; var startingNodePath = "Doc/Test1/Child4"; var testExpression = @"child::*[position() > 2]"; var expected = true; Utils.XPathMatchTest(xml, testExpression, expected, startingNodePath: startingNodePath); } /// <summary> /// Expected: Selects all element children of the context node. /// child::*[position()] /// </summary> [Fact] public static void MatchesTest2317() { var xml = "xp005.xml"; var startingNodePath = "Doc/Test1/Child3"; var testExpression = @"child::*[position()]"; var expected = true; Utils.XPathMatchTest(xml, testExpression, expected, startingNodePath: startingNodePath); } /// <summary> /// Expected: True (based on context node). /// *[position() = 2] (Matches = true) /// </summary> [Fact] public static void MatchesTest2318() { var xml = "xp005.xml"; var startingNodePath = "Doc/Test1/Child2"; var testExpression = @"*[position() = 2]"; var expected = true; Utils.XPathMatchTest(xml, testExpression, expected, startingNodePath: startingNodePath); } /// <summary> /// Expected: False (based on context node). /// *[position() = 2] (Matches = false) /// </summary> [Fact] public static void MatchesTest2319() { var xml = "xp005.xml"; var startingNodePath = "Doc/Test1/Child3"; var testExpression = @"*[position() = 2]"; var expected = false; Utils.XPathMatchTest(xml, testExpression, expected, startingNodePath: startingNodePath); } /// <summary> /// Expected: True (based on context node). /// @*[position() = 2] (Matches = true) /// </summary> [Fact] public static void MatchesTest2320() { var xml = "xp005.xml"; var startingNodePath = "Doc/Test1/@Attr2"; var testExpression = @"@*[position() = 2]"; var expected = true; Utils.XPathMatchTest(xml, testExpression, expected, startingNodePath: startingNodePath); } /// <summary> /// Expected: True (based on context node). /// @*[position() = 2] (Matches = false) /// </summary> [Fact] public static void MatchesTest2321() { var xml = "xp005.xml"; var startingNodePath = "Doc/Test1/@Attr3"; var testExpression = @"@*[position() = 2]"; var expected = false; Utils.XPathMatchTest(xml, testExpression, expected, startingNodePath: startingNodePath); } /// <summary> /// Expected: Selects the 2nd element child of the context node. /// *[2] (Matches = true) /// </summary> [Fact] public static void MatchesTest2322() { var xml = "xp005.xml"; var startingNodePath = "Doc/Test1/Child2"; var testExpression = @"*[2]"; var expected = true; Utils.XPathMatchTest(xml, testExpression, expected, startingNodePath: startingNodePath); } /// <summary> /// Expected: Selects the 2nd element child of the context node. /// *[2] (Matches = false) /// </summary> [Fact] public static void MatchesTest2323() { var xml = "xp005.xml"; var startingNodePath = "Doc/Test1/Child3"; var testExpression = @"*[2]"; var expected = false; Utils.XPathMatchTest(xml, testExpression, expected, startingNodePath: startingNodePath); } /// <summary> /// Expected: Selects the 2nd element child of the context node. /// @*[2] (Matches = true) /// </summary> [Fact] public static void MatchesTest2324() { var xml = "xp005.xml"; var startingNodePath = "Doc/Test1/@Attr2"; var testExpression = @"@*[2]"; var expected = true; Utils.XPathMatchTest(xml, testExpression, expected, startingNodePath: startingNodePath); } /// <summary> /// Expected: Selects the 2nd element child of the context node. /// @*[2] (Matches = false) /// </summary> [Fact] public static void MatchesTest2325() { var xml = "xp005.xml"; var startingNodePath = "Doc/Test1/@Attr1"; var testExpression = @"@*[2]"; var expected = false; Utils.XPathMatchTest(xml, testExpression, expected, startingNodePath: startingNodePath); } /// <summary> /// Expected: True (based on context node). /// *[position() > 2] (Matches = true) /// </summary> [Fact] public static void MatchesTest2326() { var xml = "xp005.xml"; var startingNodePath = "Doc/Test1/Child3"; var testExpression = @"*[position() > 2]"; var expected = true; Utils.XPathMatchTest(xml, testExpression, expected, startingNodePath: startingNodePath); } /// <summary> /// Expected: False (based on context node). /// *[position() > 2] (Matches = false) /// </summary> [Fact] public static void MatchesTest2327() { var xml = "xp005.xml"; var startingNodePath = "Doc/Test1/Child2"; var testExpression = @"*[position() > 2]"; var expected = false; Utils.XPathMatchTest(xml, testExpression, expected, startingNodePath: startingNodePath); } /// <summary> /// Expected: True (based on context node). /// @*[position() > 2] (Matches = true) /// </summary> [Fact] public static void MatchesTest2328() { var xml = "xp005.xml"; var startingNodePath = "Doc/Test1/@Attr3"; var testExpression = @"@*[position() > 2]"; var expected = true; Utils.XPathMatchTest(xml, testExpression, expected, startingNodePath: startingNodePath); } /// <summary> /// Expected: True (based on context node). /// @*[position() > 2] (Matches = false) /// </summary> [Fact] public static void MatchesTest2329() { var xml = "xp005.xml"; var startingNodePath = "Doc/Test1/@Attr2"; var testExpression = @"@*[position() > 2]"; var expected = false; Utils.XPathMatchTest(xml, testExpression, expected, startingNodePath: startingNodePath); } /// <summary> /// Data file has no DTD, so no element has an ID, expected empty node-set /// id("1") /// </summary> [Fact] [ActiveIssue(20)] public static void MatchesTest2352() { var xml = "id4.xml"; var startingNodePath = "/DMV/Vehicle[1]"; var testExpression = @"id(""1"")"; var expected = false; Utils.XPathMatchTest(xml, testExpression, expected, startingNodePath: startingNodePath); } } }
// jQueryXmlHttpRequest.cs // Script#/Libraries/jQuery/Core // This source code is subject to terms and conditions of the Apache License, Version 2.0. // using System; using System.Net; using System.Runtime.CompilerServices; using System.Threading.Tasks; using System.Xml; namespace jQueryApi { /// <summary> /// Represents an XMLHttpRequest object as a deferred object. /// </summary> [Imported] [IgnoreNamespace] [ScriptName("Object")] public sealed class jQueryXmlHttpRequest : IDeferred { private jQueryXmlHttpRequest() { } /// <summary> /// The ready state property of the XmlHttpRequest object. /// </summary> [IntrinsicProperty] public ReadyState ReadyState { get { return ReadyState.Uninitialized; } } /// <summary> /// The XML document for an XML response. /// </summary> [IntrinsicProperty] [ScriptName("responseXML")] public XmlDocument ResponseXml { get { return null; } } /// <summary> /// The text of the response. /// </summary> [IntrinsicProperty] public string ResponseText { get { return null; } } /// <summary> /// The status code associated with the response. /// </summary> [IntrinsicProperty] public int Status { get { return 0; } } /// <summary> /// The status text of the response. /// </summary> [IntrinsicProperty] public string StatusText { get { return null; } } /// <summary> /// Aborts the request. /// </summary> public void Abort() { } /// <summary> /// Add handlers to be called when the request completes or fails. /// </summary> /// <param name="callbacks">The callbacks to invoke (in order).</param> /// <returns>The current request object.</returns> [ExpandParams] public jQueryXmlHttpRequest Always(params Action[] callbacks) { return null; } /// <summary> /// Add handlers to be called when the request completes or fails. /// </summary> /// <param name="callbacks">The callbacks to invoke (in order).</param> /// <returns>The current request object.</returns> [ExpandParams] public jQueryXmlHttpRequest Always(params Callback[] callbacks) { return null; } /// <summary> /// Adds a callback to handle completion of the request. /// </summary> /// <param name="callback">The callback to invoke.</param> /// <returns>The current request object.</returns> public jQueryXmlHttpRequest Complete(AjaxCompletedCallback callback) { return null; } /// <summary> /// Add handlers to be called when the request is successfully completed. If the /// request is already completed, the handlers are still invoked. /// </summary> /// <param name="doneCallbacks">The callbacks to invoke (in order).</param> /// <returns>The current request object.</returns> [ExpandParams] public jQueryXmlHttpRequest Done(params Action[] doneCallbacks) { return null; } /// <summary> /// Add handlers to be called when the request is successfully completed. If the /// request is already completed, the handlers are still invoked. /// </summary> /// <param name="doneCallbacks">The callbacks to invoke (in order).</param> /// <returns>The current request object.</returns> [ExpandParams] public jQueryXmlHttpRequest Done(params Callback[] doneCallbacks) { return null; } /// <summary> /// Adds a callback to handle an error completing the request. /// </summary> /// <param name="callback">The callback to invoke.</param> /// <returns>The current request object.</returns> public jQueryXmlHttpRequest Error(AjaxErrorCallback callback) { return null; } /// <summary> /// Add handlers to be called when the request errors. If the /// request is already completed, the handlers are still invoked. /// </summary> /// <param name="failCallbacks">The callbacks to invoke (in order).</param> /// <returns>The current request object.</returns> [ExpandParams] public jQueryXmlHttpRequest Fail(params Action[] failCallbacks) { return null; } /// <summary> /// Add handlers to be called when the request errors. If the /// request is already completed, the handlers are still invoked. /// </summary> /// <param name="failCallbacks">The callbacks to invoke (in order).</param> /// <returns>The current request object.</returns> [ExpandParams] public jQueryXmlHttpRequest Fail(params Callback[] failCallbacks) { return null; } /// <summary> /// Gets the response headers associated with the request. /// </summary> /// <returns>The response headers.</returns> public string GetAllResponseHeaders() { return null; } /// <summary> /// Gets a specific response header associated with the request. /// </summary> /// <param name="name">The name of the response header.</param> /// <returns>The response header value.</returns> public string GetResponseHeader(string name) { return null; } /// <summary> /// Sets the mime type on the request. /// </summary> /// <param name="type">The mime type to use.</param> public void OverrideMimeType(string type) { } /// <summary> /// Filters or chains the result of the request. /// </summary> /// <param name="successFilter">The filter to invoke when the request successfully completes.</param> /// <returns>The current request object.</returns> public jQueryXmlHttpRequest Pipe(jQueryDeferredFilter successFilter) { return null; } /// <summary> /// Filters or chains the result of the request. /// </summary> /// <param name="successFilter">The filter to invoke when the request successfully completes.</param> /// <param name="failFilter">The filter to invoke when the request fails.</param> /// <returns>The current request object.</returns> public jQueryXmlHttpRequest Pipe(jQueryDeferredFilter successFilter, jQueryDeferredFilter failFilter) { return null; } /// <summary> /// Sets a request header value. /// </summary> /// <param name="name">The name of the request header.</param> /// <param name="value">The value of the request header.</param> public void SetRequestHeader(string name, string value) { } /// <summary> /// Adds a callback to handle a successful completion of the request. /// </summary> /// <param name="callback">The callback to invoke.</param> /// <returns>The current request object.</returns> public jQueryXmlHttpRequest Success(AjaxCallback callback) { return null; } /// <summary> /// Adds a callback to handle a successful completion of the request. /// </summary> /// <param name="callback">The callback to invoke.</param> /// <returns>The current request object.</returns> public jQueryXmlHttpRequest Success(AjaxRequestCallback callback) { return null; } /// <summary> /// Add handlers to be called when the request is completed. If the /// request is already completed, the handlers are still invoked. /// </summary> /// <param name="doneCallback">The callback to invoke when the request completes successfully.</param> /// <param name="failCallback">The callback to invoke when the request completes with an error.</param> /// <returns>The current request object.</returns> public jQueryXmlHttpRequest Then(Action doneCallback, Action failCallback) { return null; } /// <summary> /// Add handlers to be called when the request is completed. If the /// request is already completed, the handlers are still invoked. /// </summary> /// <param name="doneCallback">The callback to invoke when the request completes successfully.</param> /// <param name="failCallback">The callback to invoke when the request completes with an error.</param> /// <returns>The current request object.</returns> public jQueryXmlHttpRequest Then(Callback doneCallback, Callback failCallback) { return null; } /// <summary> /// Add handlers to be called when the request is completed. If the /// request is already completed, the handlers are still invoked. /// </summary> /// <param name="doneCallbacks">The callbacks to invoke when the request completes successfully.</param> /// <param name="failCallbacks">The callbacks to invoke when the request completes with an error.</param> /// <returns>The current deferred object.</returns> public jQueryXmlHttpRequest Then(Action[] doneCallbacks, Action[] failCallbacks) { return null; } /// <summary> /// Add handlers to be called when the request is completed. If the /// request is already completed, the handlers are still invoked. /// </summary> /// <param name="doneCallbacks">The callbacks to invoke when the request completes successfully.</param> /// <param name="failCallbacks">The callbacks to invoke when the request completes with an error.</param> /// <returns>The current deferred object.</returns> public jQueryXmlHttpRequest Then(Callback[] doneCallbacks, Callback[] failCallbacks) { return null; } [InlineCode("{$System.Threading.Tasks.Task}.fromPromise({this}, 0)")] public TaskAwaiter<object> GetAwaiter() { return null; } #region Implementation of IDeferred void IPromise.Then(Delegate fulfilledHandler) { } void IPromise.Then(Delegate fulfilledHandler, Delegate errorHandler) { } void IPromise.Then(Delegate fulfilledHandler, Delegate errorHandler, Delegate progressHandler) { } IDeferred IDeferred.Always(params Action[] callbacks) { return null; } IDeferred IDeferred.Always(params Callback[] callbacks) { return null; } IDeferred IDeferred.Done(params Action[] doneCallbacks) { return null; } IDeferred IDeferred.Done(params Callback[] doneCallbacks) { return null; } IDeferred IDeferred.Fail(params Action[] failCallbacks) { return null; } IDeferred IDeferred.Fail(params Callback[] failCallbacks) { return null; } bool IDeferred.IsRejected() { return false; } bool IDeferred.IsResolved() { return false; } IDeferred IDeferred.Pipe(jQueryDeferredFilter successFilter) { return null; } IDeferred IDeferred.Pipe(jQueryDeferredFilter successFilter, jQueryDeferredFilter failFilter) { return null; } IDeferred IDeferred.Then(Action doneCallback, Action failCallback) { return null; } IDeferred IDeferred.Then(Callback doneCallback, Callback failCallback) { return null; } IDeferred IDeferred.Then(Action[] doneCallbacks, Action[] failCallbacks) { return null; } IDeferred IDeferred.Then(Callback[] doneCallbacks, Callback[] failCallbacks) { return null; } #endregion } }
/// This code was generated by /// \ / _ _ _| _ _ /// | (_)\/(_)(_|\/| |(/_ v1.0.0 /// / / /// <summary> /// PLEASE NOTE that this class contains preview products that are subject to change. Use them with caution. If you /// currently do not have developer preview access, please contact help@twilio.com. /// /// FieldResource /// </summary> using Newtonsoft.Json; using System; using System.Collections.Generic; using Twilio.Base; using Twilio.Clients; using Twilio.Converters; using Twilio.Exceptions; using Twilio.Http; namespace Twilio.Rest.Autopilot.V1.Assistant.Task { public class FieldResource : Resource { private static Request BuildFetchRequest(FetchFieldOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Get, Rest.Domain.Autopilot, "/v1/Assistants/" + options.PathAssistantSid + "/Tasks/" + options.PathTaskSid + "/Fields/" + options.PathSid + "", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// fetch /// </summary> /// <param name="options"> Fetch Field parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Field </returns> public static FieldResource Fetch(FetchFieldOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildFetchRequest(options, client)); return FromJson(response.Content); } #if !NET35 /// <summary> /// fetch /// </summary> /// <param name="options"> Fetch Field parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Field </returns> public static async System.Threading.Tasks.Task<FieldResource> FetchAsync(FetchFieldOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildFetchRequest(options, client)); return FromJson(response.Content); } #endif /// <summary> /// fetch /// </summary> /// <param name="pathAssistantSid"> The SID of the Assistant that is the parent of the Task associated with the /// resource to fetch </param> /// <param name="pathTaskSid"> The SID of the [Task](https://www.twilio.com/docs/autopilot/api/task) resource /// associated with the Field resource to fetch </param> /// <param name="pathSid"> The unique string that identifies the resource </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Field </returns> public static FieldResource Fetch(string pathAssistantSid, string pathTaskSid, string pathSid, ITwilioRestClient client = null) { var options = new FetchFieldOptions(pathAssistantSid, pathTaskSid, pathSid); return Fetch(options, client); } #if !NET35 /// <summary> /// fetch /// </summary> /// <param name="pathAssistantSid"> The SID of the Assistant that is the parent of the Task associated with the /// resource to fetch </param> /// <param name="pathTaskSid"> The SID of the [Task](https://www.twilio.com/docs/autopilot/api/task) resource /// associated with the Field resource to fetch </param> /// <param name="pathSid"> The unique string that identifies the resource </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Field </returns> public static async System.Threading.Tasks.Task<FieldResource> FetchAsync(string pathAssistantSid, string pathTaskSid, string pathSid, ITwilioRestClient client = null) { var options = new FetchFieldOptions(pathAssistantSid, pathTaskSid, pathSid); return await FetchAsync(options, client); } #endif private static Request BuildReadRequest(ReadFieldOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Get, Rest.Domain.Autopilot, "/v1/Assistants/" + options.PathAssistantSid + "/Tasks/" + options.PathTaskSid + "/Fields", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// read /// </summary> /// <param name="options"> Read Field parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Field </returns> public static ResourceSet<FieldResource> Read(ReadFieldOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildReadRequest(options, client)); var page = Page<FieldResource>.FromJson("fields", response.Content); return new ResourceSet<FieldResource>(page, options, client); } #if !NET35 /// <summary> /// read /// </summary> /// <param name="options"> Read Field parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Field </returns> public static async System.Threading.Tasks.Task<ResourceSet<FieldResource>> ReadAsync(ReadFieldOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildReadRequest(options, client)); var page = Page<FieldResource>.FromJson("fields", response.Content); return new ResourceSet<FieldResource>(page, options, client); } #endif /// <summary> /// read /// </summary> /// <param name="pathAssistantSid"> The SID of the Assistant that is the parent of the Task associated with the /// resources to read. </param> /// <param name="pathTaskSid"> The SID of the [Task](https://www.twilio.com/docs/autopilot/api/task) resource /// associated with the Field resources to read </param> /// <param name="pageSize"> Page size </param> /// <param name="limit"> Record limit </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Field </returns> public static ResourceSet<FieldResource> Read(string pathAssistantSid, string pathTaskSid, int? pageSize = null, long? limit = null, ITwilioRestClient client = null) { var options = new ReadFieldOptions(pathAssistantSid, pathTaskSid){PageSize = pageSize, Limit = limit}; return Read(options, client); } #if !NET35 /// <summary> /// read /// </summary> /// <param name="pathAssistantSid"> The SID of the Assistant that is the parent of the Task associated with the /// resources to read. </param> /// <param name="pathTaskSid"> The SID of the [Task](https://www.twilio.com/docs/autopilot/api/task) resource /// associated with the Field resources to read </param> /// <param name="pageSize"> Page size </param> /// <param name="limit"> Record limit </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Field </returns> public static async System.Threading.Tasks.Task<ResourceSet<FieldResource>> ReadAsync(string pathAssistantSid, string pathTaskSid, int? pageSize = null, long? limit = null, ITwilioRestClient client = null) { var options = new ReadFieldOptions(pathAssistantSid, pathTaskSid){PageSize = pageSize, Limit = limit}; return await ReadAsync(options, client); } #endif /// <summary> /// Fetch the target page of records /// </summary> /// <param name="targetUrl"> API-generated URL for the requested results page </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The target page of records </returns> public static Page<FieldResource> GetPage(string targetUrl, ITwilioRestClient client) { client = client ?? TwilioClient.GetRestClient(); var request = new Request( HttpMethod.Get, targetUrl ); var response = client.Request(request); return Page<FieldResource>.FromJson("fields", response.Content); } /// <summary> /// Fetch the next page of records /// </summary> /// <param name="page"> current page of records </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The next page of records </returns> public static Page<FieldResource> NextPage(Page<FieldResource> page, ITwilioRestClient client) { var request = new Request( HttpMethod.Get, page.GetNextPageUrl(Rest.Domain.Autopilot) ); var response = client.Request(request); return Page<FieldResource>.FromJson("fields", response.Content); } /// <summary> /// Fetch the previous page of records /// </summary> /// <param name="page"> current page of records </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The previous page of records </returns> public static Page<FieldResource> PreviousPage(Page<FieldResource> page, ITwilioRestClient client) { var request = new Request( HttpMethod.Get, page.GetPreviousPageUrl(Rest.Domain.Autopilot) ); var response = client.Request(request); return Page<FieldResource>.FromJson("fields", response.Content); } private static Request BuildCreateRequest(CreateFieldOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Post, Rest.Domain.Autopilot, "/v1/Assistants/" + options.PathAssistantSid + "/Tasks/" + options.PathTaskSid + "/Fields", postParams: options.GetParams(), headerParams: null ); } /// <summary> /// create /// </summary> /// <param name="options"> Create Field parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Field </returns> public static FieldResource Create(CreateFieldOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildCreateRequest(options, client)); return FromJson(response.Content); } #if !NET35 /// <summary> /// create /// </summary> /// <param name="options"> Create Field parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Field </returns> public static async System.Threading.Tasks.Task<FieldResource> CreateAsync(CreateFieldOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildCreateRequest(options, client)); return FromJson(response.Content); } #endif /// <summary> /// create /// </summary> /// <param name="pathAssistantSid"> The SID of the Assistant that is the parent of the Task associated with the new /// resource </param> /// <param name="pathTaskSid"> The SID of the [Task](https://www.twilio.com/docs/autopilot/api/task) resource /// associated with the new Field resource </param> /// <param name="fieldType"> The Field Type of this field </param> /// <param name="uniqueName"> An application-defined string that uniquely identifies the new resource </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Field </returns> public static FieldResource Create(string pathAssistantSid, string pathTaskSid, string fieldType, string uniqueName, ITwilioRestClient client = null) { var options = new CreateFieldOptions(pathAssistantSid, pathTaskSid, fieldType, uniqueName); return Create(options, client); } #if !NET35 /// <summary> /// create /// </summary> /// <param name="pathAssistantSid"> The SID of the Assistant that is the parent of the Task associated with the new /// resource </param> /// <param name="pathTaskSid"> The SID of the [Task](https://www.twilio.com/docs/autopilot/api/task) resource /// associated with the new Field resource </param> /// <param name="fieldType"> The Field Type of this field </param> /// <param name="uniqueName"> An application-defined string that uniquely identifies the new resource </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Field </returns> public static async System.Threading.Tasks.Task<FieldResource> CreateAsync(string pathAssistantSid, string pathTaskSid, string fieldType, string uniqueName, ITwilioRestClient client = null) { var options = new CreateFieldOptions(pathAssistantSid, pathTaskSid, fieldType, uniqueName); return await CreateAsync(options, client); } #endif private static Request BuildDeleteRequest(DeleteFieldOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Delete, Rest.Domain.Autopilot, "/v1/Assistants/" + options.PathAssistantSid + "/Tasks/" + options.PathTaskSid + "/Fields/" + options.PathSid + "", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// delete /// </summary> /// <param name="options"> Delete Field parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Field </returns> public static bool Delete(DeleteFieldOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildDeleteRequest(options, client)); return response.StatusCode == System.Net.HttpStatusCode.NoContent; } #if !NET35 /// <summary> /// delete /// </summary> /// <param name="options"> Delete Field parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Field </returns> public static async System.Threading.Tasks.Task<bool> DeleteAsync(DeleteFieldOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildDeleteRequest(options, client)); return response.StatusCode == System.Net.HttpStatusCode.NoContent; } #endif /// <summary> /// delete /// </summary> /// <param name="pathAssistantSid"> The SID of the Assistant that is the parent of the Task associated with the /// resources to delete </param> /// <param name="pathTaskSid"> The SID of the [Task](https://www.twilio.com/docs/autopilot/api/task) resource /// associated with the Field resource to delete </param> /// <param name="pathSid"> The unique string that identifies the resource </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Field </returns> public static bool Delete(string pathAssistantSid, string pathTaskSid, string pathSid, ITwilioRestClient client = null) { var options = new DeleteFieldOptions(pathAssistantSid, pathTaskSid, pathSid); return Delete(options, client); } #if !NET35 /// <summary> /// delete /// </summary> /// <param name="pathAssistantSid"> The SID of the Assistant that is the parent of the Task associated with the /// resources to delete </param> /// <param name="pathTaskSid"> The SID of the [Task](https://www.twilio.com/docs/autopilot/api/task) resource /// associated with the Field resource to delete </param> /// <param name="pathSid"> The unique string that identifies the resource </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Field </returns> public static async System.Threading.Tasks.Task<bool> DeleteAsync(string pathAssistantSid, string pathTaskSid, string pathSid, ITwilioRestClient client = null) { var options = new DeleteFieldOptions(pathAssistantSid, pathTaskSid, pathSid); return await DeleteAsync(options, client); } #endif /// <summary> /// Converts a JSON string into a FieldResource object /// </summary> /// <param name="json"> Raw JSON string </param> /// <returns> FieldResource object represented by the provided JSON </returns> public static FieldResource FromJson(string json) { // Convert all checked exceptions to Runtime try { return JsonConvert.DeserializeObject<FieldResource>(json); } catch (JsonException e) { throw new ApiException(e.Message, e); } } /// <summary> /// The SID of the Account that created the resource /// </summary> [JsonProperty("account_sid")] public string AccountSid { get; private set; } /// <summary> /// The RFC 2822 date and time in GMT when the resource was created /// </summary> [JsonProperty("date_created")] public DateTime? DateCreated { get; private set; } /// <summary> /// The RFC 2822 date and time in GMT when the resource was last updated /// </summary> [JsonProperty("date_updated")] public DateTime? DateUpdated { get; private set; } /// <summary> /// The Field Type of the field /// </summary> [JsonProperty("field_type")] public string FieldType { get; private set; } /// <summary> /// The SID of the [Task](https://www.twilio.com/docs/autopilot/api/task) resource associated with this Field /// </summary> [JsonProperty("task_sid")] public string TaskSid { get; private set; } /// <summary> /// The SID of the Assistant that is the parent of the Task associated with the resource /// </summary> [JsonProperty("assistant_sid")] public string AssistantSid { get; private set; } /// <summary> /// The unique string that identifies the resource /// </summary> [JsonProperty("sid")] public string Sid { get; private set; } /// <summary> /// An application-defined string that uniquely identifies the resource /// </summary> [JsonProperty("unique_name")] public string UniqueName { get; private set; } /// <summary> /// The absolute URL of the Field resource /// </summary> [JsonProperty("url")] public Uri Url { get; private set; } private FieldResource() { } } }
using System; using System.Threading.Tasks; using Abp.Events.Bus.Factories; using Abp.Events.Bus.Handlers; namespace Abp.Events.Bus { /// <summary> /// Defines interface of the event bus. /// </summary> public interface IEventBus { #region Register /// <summary> /// Registers to an event. /// Given action is called for all event occurrences. /// </summary> /// <param name="action">Action to handle events</param> /// <typeparam name="TEventData">Event type</typeparam> IDisposable Register<TEventData>(Action<TEventData> action) where TEventData : IEventData; /// <summary> /// Registers to an event. /// Given action is called for all event occurrences. /// </summary> /// <param name="action">Action to handle events</param> /// <typeparam name="TEventData">Event type</typeparam> IDisposable AsyncRegister<TEventData>(Func<TEventData, Task> action) where TEventData : IEventData; /// <summary> /// Registers to an event. /// Same (given) instance of the handler is used for all event occurrences. /// </summary> /// <typeparam name="TEventData">Event type</typeparam> /// <param name="handler">Object to handle the event</param> IDisposable Register<TEventData>(IEventHandler<TEventData> handler) where TEventData : IEventData; /// <summary> /// Registers to an event. /// Same (given) instance of the async handler is used for all event occurrences. /// </summary> /// <typeparam name="TEventData">Event type</typeparam> /// <param name="handler">Object to handle the event</param> IDisposable AsyncRegister<TEventData>(IAsyncEventHandler<TEventData> handler) where TEventData : IEventData; /// <summary> /// Registers to an event. /// A new instance of <see cref="THandler"/> object is created for every event occurrence. /// </summary> /// <typeparam name="TEventData">Event type</typeparam> /// <typeparam name="THandler">Type of the event handler</typeparam> IDisposable Register<TEventData, THandler>() where TEventData : IEventData where THandler : IEventHandler, new(); /// <summary> /// Registers to an event. /// Same (given) instance of the handler is used for all event occurrences. /// </summary> /// <param name="eventType">Event type</param> /// <param name="handler">Object to handle the event</param> IDisposable Register(Type eventType, IEventHandler handler); /// <summary> /// Registers to an event. /// Given factory is used to create/release handlers /// </summary> /// <typeparam name="TEventData">Event type</typeparam> /// <param name="factory">A factory to create/release handlers</param> IDisposable Register<TEventData>(IEventHandlerFactory factory) where TEventData : IEventData; /// <summary> /// Registers to an event. /// </summary> /// <param name="eventType">Event type</param> /// <param name="factory">A factory to create/release handlers</param> IDisposable Register(Type eventType, IEventHandlerFactory factory); #endregion #region Unregister /// <summary> /// Unregisters from an event. /// </summary> /// <typeparam name="TEventData">Event type</typeparam> /// <param name="action"></param> void Unregister<TEventData>(Action<TEventData> action) where TEventData : IEventData; /// <summary> /// Unregisters from an event. /// </summary> /// <typeparam name="TEventData">Event type</typeparam> /// <param name="action"></param> void AsyncUnregister<TEventData>(Func<TEventData, Task> action) where TEventData : IEventData; /// <summary> /// Unregisters from an event. /// </summary> /// <typeparam name="TEventData">Event type</typeparam> /// <param name="handler">Handler object that is registered before</param> void Unregister<TEventData>(IEventHandler<TEventData> handler) where TEventData : IEventData; /// <summary> /// Unregisters from an event. /// </summary> /// <typeparam name="TEventData">Event type</typeparam> /// <param name="handler">Handler object that is registered before</param> void AsyncUnregister<TEventData>(IAsyncEventHandler<TEventData> handler) where TEventData : IEventData; /// <summary> /// Unregisters from an event. /// </summary> /// <param name="eventType">Event type</param> /// <param name="handler">Handler object that is registered before</param> void Unregister(Type eventType, IEventHandler handler); /// <summary> /// Unregisters from an event. /// </summary> /// <typeparam name="TEventData">Event type</typeparam> /// <param name="factory">Factory object that is registered before</param> void Unregister<TEventData>(IEventHandlerFactory factory) where TEventData : IEventData; /// <summary> /// Unregisters from an event. /// </summary> /// <param name="eventType">Event type</param> /// <param name="factory">Factory object that is registered before</param> void Unregister(Type eventType, IEventHandlerFactory factory); /// <summary> /// Unregisters all event handlers of given event type. /// </summary> /// <typeparam name="TEventData">Event type</typeparam> void UnregisterAll<TEventData>() where TEventData : IEventData; /// <summary> /// Unregisters all event handlers of given event type. /// </summary> /// <param name="eventType">Event type</param> void UnregisterAll(Type eventType); #endregion #region Trigger /// <summary> /// Triggers an event. /// </summary> /// <typeparam name="TEventData">Event type</typeparam> /// <param name="eventData">Related data for the event</param> void Trigger<TEventData>(TEventData eventData) where TEventData : IEventData; /// <summary> /// Triggers an event. /// </summary> /// <typeparam name="TEventData">Event type</typeparam> /// <param name="eventSource">The object which triggers the event</param> /// <param name="eventData">Related data for the event</param> void Trigger<TEventData>(object eventSource, TEventData eventData) where TEventData : IEventData; /// <summary> /// Triggers an event. /// </summary> /// <param name="eventType">Event type</param> /// <param name="eventData">Related data for the event</param> void Trigger(Type eventType, IEventData eventData); /// <summary> /// Triggers an event. /// </summary> /// <param name="eventType">Event type</param> /// <param name="eventSource">The object which triggers the event</param> /// <param name="eventData">Related data for the event</param> void Trigger(Type eventType, object eventSource, IEventData eventData); /// <summary> /// Triggers an event asynchronously. /// </summary> /// <typeparam name="TEventData">Event type</typeparam> /// <param name="eventData">Related data for the event</param> /// <returns>The task to handle async operation</returns> Task TriggerAsync<TEventData>(TEventData eventData) where TEventData : IEventData; /// <summary> /// Triggers an event asynchronously. /// </summary> /// <typeparam name="TEventData">Event type</typeparam> /// <param name="eventSource">The object which triggers the event</param> /// <param name="eventData">Related data for the event</param> /// <returns>The task to handle async operation</returns> Task TriggerAsync<TEventData>(object eventSource, TEventData eventData) where TEventData : IEventData; /// <summary> /// Triggers an event asynchronously. /// </summary> /// <param name="eventType">Event type</param> /// <param name="eventData">Related data for the event</param> /// <returns>The task to handle async operation</returns> Task TriggerAsync(Type eventType, IEventData eventData); /// <summary> /// Triggers an event asynchronously. /// </summary> /// <param name="eventType">Event type</param> /// <param name="eventSource">The object which triggers the event</param> /// <param name="eventData">Related data for the event</param> /// <returns>The task to handle async operation</returns> Task TriggerAsync(Type eventType, object eventSource, IEventData eventData); #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 copyrightD * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Reflection; using log4net; using OMV = OpenMetaverse; using OpenSim.Framework; using OpenSim.Region.Physics.Manager; namespace OpenSim.Region.Physics.BulletSPlugin { public sealed class BSCharacter : BSPhysObject { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private static readonly string LogHeader = "[BULLETS CHAR]"; // private bool _stopped; private OMV.Vector3 _size; private bool _grabbed; private bool _selected; private float _mass; private float _avatarVolume; private float _collisionScore; private OMV.Vector3 _acceleration; private int _physicsActorType; private bool _isPhysical; private bool _flying; private bool _setAlwaysRun; private bool _throttleUpdates; private bool _floatOnWater; private OMV.Vector3 _rotationalVelocity; private bool _kinematic; private float _buoyancy; private BSActorAvatarMove m_moveActor; private const string AvatarMoveActorName = "BSCharacter.AvatarMove"; private OMV.Vector3 _PIDTarget; private float _PIDTau; // public override OMV.Vector3 RawVelocity // { get { return base.RawVelocity; } // set { // if (value != base.RawVelocity) // Util.PrintCallStack(); // Console.WriteLine("Set rawvel to {0}", value); // base.RawVelocity = value; } // } // Avatars are always complete (in the physics engine sense) public override bool IsIncomplete { get { return false; } } public BSCharacter( uint localID, String avName, BSScene parent_scene, OMV.Vector3 pos, OMV.Vector3 vel, OMV.Vector3 size, bool isFlying) : base(parent_scene, localID, avName, "BSCharacter") { _physicsActorType = (int)ActorTypes.Agent; RawPosition = pos; _flying = isFlying; RawOrientation = OMV.Quaternion.Identity; RawVelocity = vel; _buoyancy = ComputeBuoyancyFromFlying(isFlying); Friction = BSParam.AvatarStandingFriction; Density = BSParam.AvatarDensity; // Old versions of ScenePresence passed only the height. If width and/or depth are zero, // replace with the default values. _size = size; if (_size.X == 0f) _size.X = BSParam.AvatarCapsuleDepth; if (_size.Y == 0f) _size.Y = BSParam.AvatarCapsuleWidth; // The dimensions of the physical capsule are kept in the scale. // Physics creates a unit capsule which is scaled by the physics engine. Scale = ComputeAvatarScale(_size); // set _avatarVolume and _mass based on capsule size, _density and Scale ComputeAvatarVolumeAndMass(); DetailLog( "{0},BSCharacter.create,call,size={1},scale={2},density={3},volume={4},mass={5},pos={6},vel={7}", LocalID, _size, Scale, Density, _avatarVolume, RawMass, pos, vel); // do actual creation in taint time PhysScene.TaintedObject(LocalID, "BSCharacter.create", delegate() { DetailLog("{0},BSCharacter.create,taint", LocalID); // New body and shape into PhysBody and PhysShape PhysScene.Shapes.GetBodyAndShape(true, PhysScene.World, this); // The avatar's movement is controlled by this motor that speeds up and slows down // the avatar seeking to reach the motor's target speed. // This motor runs as a prestep action for the avatar so it will keep the avatar // standing as well as moving. Destruction of the avatar will destroy the pre-step action. m_moveActor = new BSActorAvatarMove(PhysScene, this, AvatarMoveActorName); PhysicalActors.Add(AvatarMoveActorName, m_moveActor); SetPhysicalProperties(); IsInitialized = true; }); return; } // called when this character is being destroyed and the resources should be released public override void Destroy() { IsInitialized = false; base.Destroy(); DetailLog("{0},BSCharacter.Destroy", LocalID); PhysScene.TaintedObject(LocalID, "BSCharacter.destroy", delegate() { PhysScene.Shapes.DereferenceBody(PhysBody, null /* bodyCallback */); PhysBody.Clear(); PhysShape.Dereference(PhysScene); PhysShape = new BSShapeNull(); }); } private void SetPhysicalProperties() { PhysScene.PE.RemoveObjectFromWorld(PhysScene.World, PhysBody); ForcePosition = RawPosition; // Set the velocity if (m_moveActor != null) m_moveActor.SetVelocityAndTarget(RawVelocity, RawVelocity, false); ForceVelocity = RawVelocity; TargetVelocity = RawVelocity; // This will enable or disable the flying buoyancy of the avatar. // Needs to be reset especially when an avatar is recreated after crossing a region boundry. Flying = _flying; PhysScene.PE.SetRestitution(PhysBody, BSParam.AvatarRestitution); PhysScene.PE.SetMargin(PhysShape.physShapeInfo, PhysScene.Params.collisionMargin); PhysScene.PE.SetLocalScaling(PhysShape.physShapeInfo, Scale); PhysScene.PE.SetContactProcessingThreshold(PhysBody, BSParam.ContactProcessingThreshold); if (BSParam.CcdMotionThreshold > 0f) { PhysScene.PE.SetCcdMotionThreshold(PhysBody, BSParam.CcdMotionThreshold); PhysScene.PE.SetCcdSweptSphereRadius(PhysBody, BSParam.CcdSweptSphereRadius); } UpdatePhysicalMassProperties(RawMass, false); // Make so capsule does not fall over PhysScene.PE.SetAngularFactorV(PhysBody, OMV.Vector3.Zero); // The avatar mover sets some parameters. PhysicalActors.Refresh(); PhysScene.PE.AddToCollisionFlags(PhysBody, CollisionFlags.CF_CHARACTER_OBJECT); PhysScene.PE.AddObjectToWorld(PhysScene.World, PhysBody); // PhysicsScene.PE.ForceActivationState(PhysBody, ActivationState.ACTIVE_TAG); PhysScene.PE.ForceActivationState(PhysBody, ActivationState.DISABLE_DEACTIVATION); PhysScene.PE.UpdateSingleAabb(PhysScene.World, PhysBody); // Do this after the object has been added to the world if (BSParam.AvatarToAvatarCollisionsByDefault) PhysBody.collisionType = CollisionType.Avatar; else PhysBody.collisionType = CollisionType.PhantomToOthersAvatar; PhysBody.ApplyCollisionMask(PhysScene); } public override void RequestPhysicsterseUpdate() { base.RequestPhysicsterseUpdate(); } // No one calls this method so I don't know what it could possibly mean public override bool Stopped { get { return false; } } public override OMV.Vector3 Size { get { // Avatar capsule size is kept in the scale parameter. return _size; } set { // This is how much the avatar size is changing. Positive means getting bigger. // The avatar altitude must be adjusted for this change. float heightChange = value.Z - _size.Z; _size = value; // Old versions of ScenePresence passed only the height. If width and/or depth are zero, // replace with the default values. if (_size.X == 0f) _size.X = BSParam.AvatarCapsuleDepth; if (_size.Y == 0f) _size.Y = BSParam.AvatarCapsuleWidth; Scale = ComputeAvatarScale(_size); ComputeAvatarVolumeAndMass(); DetailLog("{0},BSCharacter.setSize,call,size={1},scale={2},density={3},volume={4},mass={5}", LocalID, _size, Scale, Density, _avatarVolume, RawMass); PhysScene.TaintedObject(LocalID, "BSCharacter.setSize", delegate() { if (PhysBody.HasPhysicalBody && PhysShape.physShapeInfo.HasPhysicalShape) { PhysScene.PE.SetLocalScaling(PhysShape.physShapeInfo, Scale); UpdatePhysicalMassProperties(RawMass, true); // Adjust the avatar's position to account for the increase/decrease in size ForcePosition = new OMV.Vector3(RawPosition.X, RawPosition.Y, RawPosition.Z + heightChange / 2f); // Make sure this change appears as a property update event PhysScene.PE.PushUpdate(PhysBody); } }); } } public override PrimitiveBaseShape Shape { set { BaseShape = value; } } public override bool Grabbed { set { _grabbed = value; } } public override bool Selected { set { _selected = value; } } public override bool IsSelected { get { return _selected; } } public override void CrossingFailure() { return; } public override void link(PhysicsActor obj) { return; } public override void delink() { return; } // Set motion values to zero. // Do it to the properties so the values get set in the physics engine. // Push the setting of the values to the viewer. // Called at taint time! public override void ZeroMotion(bool inTaintTime) { RawVelocity = OMV.Vector3.Zero; _acceleration = OMV.Vector3.Zero; _rotationalVelocity = OMV.Vector3.Zero; // Zero some other properties directly into the physics engine PhysScene.TaintedObject(inTaintTime, LocalID, "BSCharacter.ZeroMotion", delegate() { if (PhysBody.HasPhysicalBody) PhysScene.PE.ClearAllForces(PhysBody); }); } public override void ZeroAngularMotion(bool inTaintTime) { _rotationalVelocity = OMV.Vector3.Zero; PhysScene.TaintedObject(inTaintTime, LocalID, "BSCharacter.ZeroMotion", delegate() { if (PhysBody.HasPhysicalBody) { PhysScene.PE.SetInterpolationAngularVelocity(PhysBody, OMV.Vector3.Zero); PhysScene.PE.SetAngularVelocity(PhysBody, OMV.Vector3.Zero); // The next also get rid of applied linear force but the linear velocity is untouched. PhysScene.PE.ClearForces(PhysBody); } }); } public override void LockAngularMotion(OMV.Vector3 axis) { return; } public override OMV.Vector3 Position { get { // Don't refetch the position because this function is called a zillion times // RawPosition = PhysicsScene.PE.GetObjectPosition(Scene.World, LocalID); return RawPosition; } set { RawPosition = value; PhysScene.TaintedObject(LocalID, "BSCharacter.setPosition", delegate() { DetailLog("{0},BSCharacter.SetPosition,taint,pos={1},orient={2}", LocalID, RawPosition, RawOrientation); PositionSanityCheck(); ForcePosition = RawPosition; }); } } public override OMV.Vector3 ForcePosition { get { RawPosition = PhysScene.PE.GetPosition(PhysBody); return RawPosition; } set { RawPosition = value; if (PhysBody.HasPhysicalBody) { PhysScene.PE.SetTranslation(PhysBody, RawPosition, RawOrientation); } } } // Check that the current position is sane and, if not, modify the position to make it so. // Check for being below terrain or on water. // Returns 'true' of the position was made sane by some action. private bool PositionSanityCheck() { bool ret = false; // TODO: check for out of bounds if (!PhysScene.TerrainManager.IsWithinKnownTerrain(RawPosition)) { // The character is out of the known/simulated area. // Force the avatar position to be within known. ScenePresence will use the position // plus the velocity to decide if the avatar is moving out of the region. RawPosition = PhysScene.TerrainManager.ClampPositionIntoKnownTerrain(RawPosition); DetailLog("{0},BSCharacter.PositionSanityCheck,notWithinKnownTerrain,clampedPos={1}", LocalID, RawPosition); return true; } // If below the ground, move the avatar up float terrainHeight = PhysScene.TerrainManager.GetTerrainHeightAtXYZ(RawPosition); if (Position.Z < terrainHeight) { DetailLog("{0},BSCharacter.PositionSanityCheck,adjustForUnderGround,pos={1},terrain={2}", LocalID, RawPosition, terrainHeight); RawPosition = new OMV.Vector3(RawPosition.X, RawPosition.Y, terrainHeight + BSParam.AvatarBelowGroundUpCorrectionMeters); ret = true; } if ((CurrentCollisionFlags & CollisionFlags.BS_FLOATS_ON_WATER) != 0) { float waterHeight = PhysScene.TerrainManager.GetWaterLevelAtXYZ(RawPosition); if (Position.Z < waterHeight) { RawPosition = new OMV.Vector3(RawPosition.X, RawPosition.Y, waterHeight); ret = true; } } return ret; } // A version of the sanity check that also makes sure a new position value is // pushed back to the physics engine. This routine would be used by anyone // who is not already pushing the value. private bool PositionSanityCheck(bool inTaintTime) { bool ret = false; if (PositionSanityCheck()) { // The new position value must be pushed into the physics engine but we can't // just assign to "Position" because of potential call loops. PhysScene.TaintedObject(inTaintTime, LocalID, "BSCharacter.PositionSanityCheck", delegate() { DetailLog("{0},BSCharacter.PositionSanityCheck,taint,pos={1},orient={2}", LocalID, RawPosition, RawOrientation); ForcePosition = RawPosition; }); ret = true; } return ret; } public override float Mass { get { return _mass; } } // used when we only want this prim's mass and not the linkset thing public override float RawMass { get {return _mass; } } public override void UpdatePhysicalMassProperties(float physMass, bool inWorld) { OMV.Vector3 localInertia = PhysScene.PE.CalculateLocalInertia(PhysShape.physShapeInfo, physMass); PhysScene.PE.SetMassProps(PhysBody, physMass, localInertia); } public override OMV.Vector3 Force { get { return RawForce; } set { RawForce = value; // m_log.DebugFormat("{0}: Force = {1}", LogHeader, _force); PhysScene.TaintedObject(LocalID, "BSCharacter.SetForce", delegate() { DetailLog("{0},BSCharacter.setForce,taint,force={1}", LocalID, RawForce); if (PhysBody.HasPhysicalBody) PhysScene.PE.SetObjectForce(PhysBody, RawForce); }); } } // Avatars don't do vehicles public override int VehicleType { get { return (int)Vehicle.TYPE_NONE; } set { return; } } public override void VehicleFloatParam(int param, float value) { } public override void VehicleVectorParam(int param, OMV.Vector3 value) {} public override void VehicleRotationParam(int param, OMV.Quaternion rotation) { } public override void VehicleFlags(int param, bool remove) { } // Allows the detection of collisions with inherently non-physical prims. see llVolumeDetect for more public override void SetVolumeDetect(int param) { return; } public override bool IsVolumeDetect { get { return false; } } public override OMV.Vector3 GeometricCenter { get { return OMV.Vector3.Zero; } } public override OMV.Vector3 CenterOfMass { get { return OMV.Vector3.Zero; } } // Sets the target in the motor. This starts the changing of the avatar's velocity. public override OMV.Vector3 TargetVelocity { get { return base.m_targetVelocity; } set { DetailLog("{0},BSCharacter.setTargetVelocity,call,vel={1}", LocalID, value); m_targetVelocity = value; OMV.Vector3 targetVel = value; if (_setAlwaysRun && !_flying) targetVel *= new OMV.Vector3(BSParam.AvatarAlwaysRunFactor, BSParam.AvatarAlwaysRunFactor, 1f); if (m_moveActor != null) m_moveActor.SetVelocityAndTarget(RawVelocity, targetVel, false /* inTaintTime */); } } // Directly setting velocity means this is what the user really wants now. public override OMV.Vector3 Velocity { get { return RawVelocity; } set { RawVelocity = value; OMV.Vector3 vel = RawVelocity; DetailLog("{0}: set Velocity = {1}", LogHeader, value); PhysScene.TaintedObject(LocalID, "BSCharacter.setVelocity", delegate() { if (m_moveActor != null) m_moveActor.SetVelocityAndTarget(vel, vel, true /* inTaintTime */); DetailLog("{0},BSCharacter.setVelocity,taint,vel={1}", LocalID, vel); ForceVelocity = vel; }); } } public override OMV.Vector3 ForceVelocity { get { return RawVelocity; } set { PhysScene.AssertInTaintTime("BSCharacter.ForceVelocity"); // Util.PrintCallStack(); DetailLog("{0}: set ForceVelocity = {1}", LogHeader, value); RawVelocity = value; PhysScene.PE.SetLinearVelocity(PhysBody, RawVelocity); PhysScene.PE.Activate(PhysBody, true); } } public override OMV.Vector3 Torque { get { return RawTorque; } set { RawTorque = value; } } public override float CollisionScore { get { return _collisionScore; } set { _collisionScore = value; } } public override OMV.Vector3 Acceleration { get { return _acceleration; } set { _acceleration = value; } } public override OMV.Quaternion Orientation { get { return RawOrientation; } set { // Orientation is set zillions of times when an avatar is walking. It's like // the viewer doesn't trust us. if (RawOrientation != value) { RawOrientation = value; PhysScene.TaintedObject(LocalID, "BSCharacter.setOrientation", delegate() { // Bullet assumes we know what we are doing when forcing orientation // so it lets us go against all the rules and just compensates for them later. // This forces rotation to be only around the Z axis and doesn't change any of the other axis. // This keeps us from flipping the capsule over which the veiwer does not understand. float oRoll, oPitch, oYaw; RawOrientation.GetEulerAngles(out oRoll, out oPitch, out oYaw); OMV.Quaternion trimmedOrientation = OMV.Quaternion.CreateFromEulers(0f, 0f, oYaw); // DetailLog("{0},BSCharacter.setOrientation,taint,val={1},valDir={2},conv={3},convDir={4}", // LocalID, RawOrientation, OMV.Vector3.UnitX * RawOrientation, // trimmedOrientation, OMV.Vector3.UnitX * trimmedOrientation); ForceOrientation = trimmedOrientation; }); } } } // Go directly to Bullet to get/set the value. public override OMV.Quaternion ForceOrientation { get { RawOrientation = PhysScene.PE.GetOrientation(PhysBody); return RawOrientation; } set { RawOrientation = value; if (PhysBody.HasPhysicalBody) { // RawPosition = PhysicsScene.PE.GetPosition(BSBody); PhysScene.PE.SetTranslation(PhysBody, RawPosition, RawOrientation); } } } public override int PhysicsActorType { get { return _physicsActorType; } set { _physicsActorType = value; } } public override bool IsPhysical { get { return _isPhysical; } set { _isPhysical = value; } } public override bool IsSolid { get { return true; } } public override bool IsStatic { get { return false; } } public override bool IsPhysicallyActive { get { return true; } } public override bool Flying { get { return _flying; } set { _flying = value; // simulate flying by changing the effect of gravity Buoyancy = ComputeBuoyancyFromFlying(_flying); } } // Flying is implimented by changing the avatar's buoyancy. // Would this be done better with a vehicle type? private float ComputeBuoyancyFromFlying(bool ifFlying) { return ifFlying ? 1f : 0f; } public override bool SetAlwaysRun { get { return _setAlwaysRun; } set { _setAlwaysRun = value; } } public override bool ThrottleUpdates { get { return _throttleUpdates; } set { _throttleUpdates = value; } } public override bool FloatOnWater { set { _floatOnWater = value; PhysScene.TaintedObject(LocalID, "BSCharacter.setFloatOnWater", delegate() { if (PhysBody.HasPhysicalBody) { if (_floatOnWater) CurrentCollisionFlags = PhysScene.PE.AddToCollisionFlags(PhysBody, CollisionFlags.BS_FLOATS_ON_WATER); else CurrentCollisionFlags = PhysScene.PE.RemoveFromCollisionFlags(PhysBody, CollisionFlags.BS_FLOATS_ON_WATER); } }); } } public override OMV.Vector3 RotationalVelocity { get { return _rotationalVelocity; } set { _rotationalVelocity = value; } } public override OMV.Vector3 ForceRotationalVelocity { get { return _rotationalVelocity; } set { _rotationalVelocity = value; } } public override bool Kinematic { get { return _kinematic; } set { _kinematic = value; } } // neg=fall quickly, 0=1g, 1=0g, pos=float up public override float Buoyancy { get { return _buoyancy; } set { _buoyancy = value; PhysScene.TaintedObject(LocalID, "BSCharacter.setBuoyancy", delegate() { DetailLog("{0},BSCharacter.setBuoyancy,taint,buoy={1}", LocalID, _buoyancy); ForceBuoyancy = _buoyancy; }); } } public override float ForceBuoyancy { get { return _buoyancy; } set { PhysScene.AssertInTaintTime("BSCharacter.ForceBuoyancy"); _buoyancy = value; DetailLog("{0},BSCharacter.setForceBuoyancy,taint,buoy={1}", LocalID, _buoyancy); // Buoyancy is faked by changing the gravity applied to the object float grav = BSParam.Gravity * (1f - _buoyancy); Gravity = new OMV.Vector3(0f, 0f, grav); if (PhysBody.HasPhysicalBody) PhysScene.PE.SetGravity(PhysBody, Gravity); } } // Used for MoveTo public override OMV.Vector3 PIDTarget { set { _PIDTarget = value; } } public override bool PIDActive { get; set; } public override float PIDTau { set { _PIDTau = value; } } public override void AddForce(OMV.Vector3 force, bool pushforce) { // Since this force is being applied in only one step, make this a force per second. OMV.Vector3 addForce = force / PhysScene.LastTimeStep; AddForce(addForce, pushforce, false); } public override void AddForce(OMV.Vector3 force, bool pushforce, bool inTaintTime) { if (force.IsFinite()) { OMV.Vector3 addForce = Util.ClampV(force, BSParam.MaxAddForceMagnitude); // DetailLog("{0},BSCharacter.addForce,call,force={1}", LocalID, addForce); PhysScene.TaintedObject(inTaintTime, LocalID, "BSCharacter.AddForce", delegate() { // Bullet adds this central force to the total force for this tick // DetailLog("{0},BSCharacter.addForce,taint,force={1}", LocalID, addForce); if (PhysBody.HasPhysicalBody) { PhysScene.PE.ApplyCentralForce(PhysBody, addForce); } }); } else { m_log.WarnFormat("{0}: Got a NaN force applied to a character. LocalID={1}", LogHeader, LocalID); return; } } public override void AddAngularForce(OMV.Vector3 force, bool pushforce, bool inTaintTime) { } public override void SetMomentum(OMV.Vector3 momentum) { } private OMV.Vector3 ComputeAvatarScale(OMV.Vector3 size) { OMV.Vector3 newScale = size; // Bullet's capsule total height is the "passed height + radius * 2"; // The base capsule is 1 unit in diameter and 2 units in height (passed radius=0.5, passed height = 1) // The number we pass in for 'scaling' is the multiplier to get that base // shape to be the size desired. // So, when creating the scale for the avatar height, we take the passed height // (size.Z) and remove the caps. // An oddity of the Bullet capsule implementation is that it presumes the Y // dimension is the radius of the capsule. Even though some of the code allows // for a asymmetrical capsule, other parts of the code presume it is cylindrical. // Scale is multiplier of radius with one of "0.5" float heightAdjust = BSParam.AvatarHeightMidFudge; if (BSParam.AvatarHeightLowFudge != 0f || BSParam.AvatarHeightHighFudge != 0f) { const float AVATAR_LOW = 1.1f; const float AVATAR_MID = 1.775f; // 1.87f const float AVATAR_HI = 2.45f; // An avatar is between 1.1 and 2.45 meters. Midpoint is 1.775m. float midHeightOffset = size.Z - AVATAR_MID; if (midHeightOffset < 0f) { // Small avatar. Add the adjustment based on the distance from midheight heightAdjust += ((-1f * midHeightOffset) / (AVATAR_MID - AVATAR_LOW)) * BSParam.AvatarHeightLowFudge; } else { // Large avatar. Add the adjustment based on the distance from midheight heightAdjust += ((midHeightOffset) / (AVATAR_HI - AVATAR_MID)) * BSParam.AvatarHeightHighFudge; } } if (BSParam.AvatarShape == BSShapeCollection.AvatarShapeCapsule) { newScale.X = size.X / 2f; newScale.Y = size.Y / 2f; // The total scale height is the central cylindar plus the caps on the two ends. newScale.Z = (size.Z + (Math.Min(size.X, size.Y) * 2) + heightAdjust) / 2f; } else { newScale.Z = size.Z + heightAdjust; } // m_log.DebugFormat("{0} ComputeAvatarScale: size={1},adj={2},scale={3}", LogHeader, size, heightAdjust, newScale); // If smaller than the endcaps, just fake like we're almost that small if (newScale.Z < 0) newScale.Z = 0.1f; DetailLog("{0},BSCharacter.ComputerAvatarScale,size={1},lowF={2},midF={3},hiF={4},adj={5},newScale={6}", LocalID, size, BSParam.AvatarHeightLowFudge, BSParam.AvatarHeightMidFudge, BSParam.AvatarHeightHighFudge, heightAdjust, newScale); return newScale; } // set _avatarVolume and _mass based on capsule size, _density and Scale private void ComputeAvatarVolumeAndMass() { _avatarVolume = (float)( Math.PI * Size.X / 2f * Size.Y / 2f // the area of capsule cylinder * Size.Z // times height of capsule cylinder + 1.33333333f * Math.PI * Size.X / 2f * Math.Min(Size.X, Size.Y) / 2 * Size.Y / 2f // plus the volume of the capsule end caps ); _mass = Density * BSParam.DensityScaleFactor * _avatarVolume; } // The physics engine says that properties have updated. Update same and inform // the world that things have changed. public override void UpdateProperties(EntityProperties entprop) { // Let anyone (like the actors) modify the updated properties before they are pushed into the object and the simulator. TriggerPreUpdatePropertyAction(ref entprop); RawPosition = entprop.Position; RawOrientation = entprop.Rotation; // Smooth velocity. OpenSimulator is VERY sensitive to changes in velocity of the avatar // and will send agent updates to the clients if velocity changes by more than // 0.001m/s. Bullet introduces a lot of jitter in the velocity which causes many // extra updates. // // XXX: Contrary to the above comment, setting an update threshold here above 0.4 actually introduces jitter to // avatar movement rather than removes it. The larger the threshold, the bigger the jitter. // This is most noticeable in level flight and can be seen with // the "show updates" option in a viewer. With an update threshold, the RawVelocity cycles between a lower // bound and an upper bound, where the difference between the two is enough to trigger a large delta v update // and subsequently trigger an update in ScenePresence.SendTerseUpdateToAllClients(). The cause of this cycle (feedback?) // has not yet been identified. // // If there is a threshold below 0.4 or no threshold check at all (as in ODE), then RawVelocity stays constant and extra // updates are not triggered in ScenePresence.SendTerseUpdateToAllClients(). // if (!entprop.Velocity.ApproxEquals(RawVelocity, 0.1f)) RawVelocity = entprop.Velocity; _acceleration = entprop.Acceleration; _rotationalVelocity = entprop.RotationalVelocity; // Do some sanity checking for the avatar. Make sure it's above ground and inbounds. if (PositionSanityCheck(true)) { DetailLog("{0},BSCharacter.UpdateProperties,updatePosForSanity,pos={1}", LocalID, RawPosition); entprop.Position = RawPosition; } // remember the current and last set values LastEntityProperties = CurrentEntityProperties; CurrentEntityProperties = entprop; // Tell the linkset about value changes // Linkset.UpdateProperties(UpdatedProperties.EntPropUpdates, this); // Avatars don't report their changes the usual way. Changes are checked for in the heartbeat loop. // PhysScene.PostUpdate(this); DetailLog("{0},BSCharacter.UpdateProperties,call,pos={1},orient={2},vel={3},accel={4},rotVel={5}", LocalID, RawPosition, RawOrientation, RawVelocity, _acceleration, _rotationalVelocity); } } }
// 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.Dynamic.Utils; using System.Reflection; using System.Reflection.Emit; using System.Runtime.CompilerServices; using static System.Linq.Expressions.CachedReflectionInfo; namespace System.Linq.Expressions.Compiler { /// <summary> /// Dynamic Language Runtime Compiler. /// This part compiles lambdas. /// </summary> internal partial class LambdaCompiler { #if FEATURE_COMPILE_TO_METHODBUILDER private static int s_counter; #endif internal void EmitConstantArray<T>(T[] array) { #if FEATURE_COMPILE_TO_METHODBUILDER // Emit as runtime constant if possible // if not, emit into IL if (_method is DynamicMethod) #else Debug.Assert(_method is DynamicMethod); #endif { EmitConstant(array, typeof(T[])); } #if FEATURE_COMPILE_TO_METHODBUILDER else if (_typeBuilder != null) { // store into field in our type builder, we will initialize // the value only once. FieldBuilder fb = CreateStaticField("ConstantArray", typeof(T[])); Label l = _ilg.DefineLabel(); _ilg.Emit(OpCodes.Ldsfld, fb); _ilg.Emit(OpCodes.Ldnull); _ilg.Emit(OpCodes.Bne_Un, l); _ilg.EmitArray(array, this); _ilg.Emit(OpCodes.Stsfld, fb); _ilg.MarkLabel(l); _ilg.Emit(OpCodes.Ldsfld, fb); } else { _ilg.EmitArray(array, this); } #endif } private void EmitClosureCreation(LambdaCompiler inner) { bool closure = inner._scope.NeedsClosure; bool boundConstants = inner._boundConstants.Count > 0; if (!closure && !boundConstants) { _ilg.EmitNull(); return; } // new Closure(constantPool, currentHoistedLocals) if (boundConstants) { _boundConstants.EmitConstant(this, inner._boundConstants.ToArray(), typeof(object[])); } else { _ilg.EmitNull(); } if (closure) { _scope.EmitGet(_scope.NearestHoistedLocals.SelfVariable); } else { _ilg.EmitNull(); } _ilg.EmitNew(Closure_ObjectArray_ObjectArray); } /// <summary> /// Emits code which creates new instance of the delegateType delegate. /// /// Since the delegate is getting closed over the "Closure" argument, this /// cannot be used with virtual/instance methods (inner must be static method) /// </summary> private void EmitDelegateConstruction(LambdaCompiler inner) { Type delegateType = inner._lambda.Type; DynamicMethod dynamicMethod = inner._method as DynamicMethod; #if FEATURE_COMPILE_TO_METHODBUILDER if (dynamicMethod != null) #else Debug.Assert(dynamicMethod != null); #endif { // Emit MethodInfo.CreateDelegate instead because DynamicMethod is not in Windows 8 Profile _boundConstants.EmitConstant(this, dynamicMethod, typeof(MethodInfo)); _ilg.EmitType(delegateType); EmitClosureCreation(inner); _ilg.Emit(OpCodes.Callvirt, MethodInfo_CreateDelegate_Type_Object); _ilg.Emit(OpCodes.Castclass, delegateType); } #if FEATURE_COMPILE_TO_METHODBUILDER else { // new DelegateType(closure) EmitClosureCreation(inner); _ilg.Emit(OpCodes.Ldftn, inner._method); _ilg.Emit(OpCodes.Newobj, (ConstructorInfo)(delegateType.GetMember(".ctor")[0])); } #endif } /// <summary> /// Emits a delegate to the method generated for the LambdaExpression. /// May end up creating a wrapper to match the requested delegate type. /// </summary> /// <param name="lambda">Lambda for which to generate a delegate</param> /// private void EmitDelegateConstruction(LambdaExpression lambda) { // 1. Create the new compiler LambdaCompiler impl; #if FEATURE_COMPILE_TO_METHODBUILDER if (_method is DynamicMethod) #else Debug.Assert(_method is DynamicMethod); #endif { impl = new LambdaCompiler(_tree, lambda); } #if FEATURE_COMPILE_TO_METHODBUILDER else { // When the lambda does not have a name or the name is empty, generate a unique name for it. string name = String.IsNullOrEmpty(lambda.Name) ? GetUniqueMethodName() : lambda.Name; MethodBuilder mb = _typeBuilder.DefineMethod(name, MethodAttributes.Private | MethodAttributes.Static); impl = new LambdaCompiler(_tree, lambda, mb); } #endif // 2. emit the lambda // Since additional ILs are always emitted after the lambda's body, should not emit with tail call optimization. impl.EmitLambdaBody(_scope, false, CompilationFlags.EmitAsNoTail); // 3. emit the delegate creation in the outer lambda EmitDelegateConstruction(impl); } private static Type[] GetParameterTypes(LambdaExpression lambda, Type firstType) { int count = lambda.ParameterCount; Type[] result; int i; if (firstType != null) { result = new Type[count + 1]; result[0] = firstType; i = 1; } else { result = new Type[count]; i = 0; } for (var j = 0; j < count; j++, i++) { ParameterExpression p = lambda.GetParameter(j); result[i] = p.IsByRef ? p.Type.MakeByRefType() : p.Type; } return result; } #if FEATURE_COMPILE_TO_METHODBUILDER private static string GetUniqueMethodName() { return "<ExpressionCompilerImplementationDetails>{" + System.Threading.Interlocked.Increment(ref s_counter) + "}lambda_method"; } #endif private void EmitLambdaBody() { // The lambda body is the "last" expression of the lambda CompilationFlags tailCallFlag = _lambda.TailCall ? CompilationFlags.EmitAsTail : CompilationFlags.EmitAsNoTail; EmitLambdaBody(null, false, tailCallFlag); } /// <summary> /// Emits the lambda body. If inlined, the parameters should already be /// pushed onto the IL stack. /// </summary> /// <param name="parent">The parent scope.</param> /// <param name="inlined">true if the lambda is inlined; false otherwise.</param> /// <param name="flags"> /// The enum to specify if the lambda is compiled with the tail call optimization. /// </param> private void EmitLambdaBody(CompilerScope parent, bool inlined, CompilationFlags flags) { _scope.Enter(this, parent); if (inlined) { // The arguments were already pushed onto the IL stack. // Store them into locals, popping in reverse order. // // If any arguments were ByRef, the address is on the stack and // we'll be storing it into the variable, which has a ref type. for (int i = _lambda.ParameterCount - 1; i >= 0; i--) { _scope.EmitSet(_lambda.GetParameter(i)); } } // Need to emit the expression start for the lambda body flags = UpdateEmitExpressionStartFlag(flags, CompilationFlags.EmitExpressionStart); if (_lambda.ReturnType == typeof(void)) { EmitExpressionAsVoid(_lambda.Body, flags); } else { EmitExpression(_lambda.Body, flags); } // Return must be the last instruction in a CLI method. // But if we're inlining the lambda, we want to leave the return // value on the IL stack. if (!inlined) { _ilg.Emit(OpCodes.Ret); } _scope.Exit(); // Validate labels Debug.Assert(_labelBlock.Parent == null && _labelBlock.Kind == LabelScopeKind.Lambda); foreach (LabelInfo label in _labelInfo.Values) { label.ValidateFinish(); } } } }
/* * DocuSign REST API * * The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign. * * OpenAPI spec version: v2.1 * Contact: devcenter@docusign.com * Generated by: https://github.com/swagger-api/swagger-codegen.git */ using System; using System.Linq; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.ComponentModel.DataAnnotations; using SwaggerDateConverter = DocuSign.eSign.Client.SwaggerDateConverter; namespace DocuSign.eSign.Model { /// <summary> /// RecipientSignatureProviderOptions /// </summary> [DataContract] public partial class RecipientSignatureProviderOptions : IEquatable<RecipientSignatureProviderOptions>, IValidatableObject { public RecipientSignatureProviderOptions() { // Empty Constructor } /// <summary> /// Initializes a new instance of the <see cref="RecipientSignatureProviderOptions" /> class. /// </summary> /// <param name="CpfNumber">CpfNumber.</param> /// <param name="CpfNumberMetadata">CpfNumberMetadata.</param> /// <param name="OneTimePassword">OneTimePassword.</param> /// <param name="OneTimePasswordMetadata">OneTimePasswordMetadata.</param> /// <param name="SignerRole">SignerRole.</param> /// <param name="SignerRoleMetadata">SignerRoleMetadata.</param> /// <param name="Sms">Sms.</param> /// <param name="SmsMetadata">SmsMetadata.</param> public RecipientSignatureProviderOptions(string CpfNumber = default(string), PropertyMetadata CpfNumberMetadata = default(PropertyMetadata), string OneTimePassword = default(string), PropertyMetadata OneTimePasswordMetadata = default(PropertyMetadata), string SignerRole = default(string), PropertyMetadata SignerRoleMetadata = default(PropertyMetadata), string Sms = default(string), PropertyMetadata SmsMetadata = default(PropertyMetadata)) { this.CpfNumber = CpfNumber; this.CpfNumberMetadata = CpfNumberMetadata; this.OneTimePassword = OneTimePassword; this.OneTimePasswordMetadata = OneTimePasswordMetadata; this.SignerRole = SignerRole; this.SignerRoleMetadata = SignerRoleMetadata; this.Sms = Sms; this.SmsMetadata = SmsMetadata; } /// <summary> /// Gets or Sets CpfNumber /// </summary> [DataMember(Name="cpfNumber", EmitDefaultValue=false)] public string CpfNumber { get; set; } /// <summary> /// Gets or Sets CpfNumberMetadata /// </summary> [DataMember(Name="cpfNumberMetadata", EmitDefaultValue=false)] public PropertyMetadata CpfNumberMetadata { get; set; } /// <summary> /// Gets or Sets OneTimePassword /// </summary> [DataMember(Name="oneTimePassword", EmitDefaultValue=false)] public string OneTimePassword { get; set; } /// <summary> /// Gets or Sets OneTimePasswordMetadata /// </summary> [DataMember(Name="oneTimePasswordMetadata", EmitDefaultValue=false)] public PropertyMetadata OneTimePasswordMetadata { get; set; } /// <summary> /// Gets or Sets SignerRole /// </summary> [DataMember(Name="signerRole", EmitDefaultValue=false)] public string SignerRole { get; set; } /// <summary> /// Gets or Sets SignerRoleMetadata /// </summary> [DataMember(Name="signerRoleMetadata", EmitDefaultValue=false)] public PropertyMetadata SignerRoleMetadata { get; set; } /// <summary> /// Gets or Sets Sms /// </summary> [DataMember(Name="sms", EmitDefaultValue=false)] public string Sms { get; set; } /// <summary> /// Gets or Sets SmsMetadata /// </summary> [DataMember(Name="smsMetadata", EmitDefaultValue=false)] public PropertyMetadata SmsMetadata { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class RecipientSignatureProviderOptions {\n"); sb.Append(" CpfNumber: ").Append(CpfNumber).Append("\n"); sb.Append(" CpfNumberMetadata: ").Append(CpfNumberMetadata).Append("\n"); sb.Append(" OneTimePassword: ").Append(OneTimePassword).Append("\n"); sb.Append(" OneTimePasswordMetadata: ").Append(OneTimePasswordMetadata).Append("\n"); sb.Append(" SignerRole: ").Append(SignerRole).Append("\n"); sb.Append(" SignerRoleMetadata: ").Append(SignerRoleMetadata).Append("\n"); sb.Append(" Sms: ").Append(Sms).Append("\n"); sb.Append(" SmsMetadata: ").Append(SmsMetadata).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="obj">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object obj) { // credit: http://stackoverflow.com/a/10454552/677735 return this.Equals(obj as RecipientSignatureProviderOptions); } /// <summary> /// Returns true if RecipientSignatureProviderOptions instances are equal /// </summary> /// <param name="other">Instance of RecipientSignatureProviderOptions to be compared</param> /// <returns>Boolean</returns> public bool Equals(RecipientSignatureProviderOptions other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return ( this.CpfNumber == other.CpfNumber || this.CpfNumber != null && this.CpfNumber.Equals(other.CpfNumber) ) && ( this.CpfNumberMetadata == other.CpfNumberMetadata || this.CpfNumberMetadata != null && this.CpfNumberMetadata.Equals(other.CpfNumberMetadata) ) && ( this.OneTimePassword == other.OneTimePassword || this.OneTimePassword != null && this.OneTimePassword.Equals(other.OneTimePassword) ) && ( this.OneTimePasswordMetadata == other.OneTimePasswordMetadata || this.OneTimePasswordMetadata != null && this.OneTimePasswordMetadata.Equals(other.OneTimePasswordMetadata) ) && ( this.SignerRole == other.SignerRole || this.SignerRole != null && this.SignerRole.Equals(other.SignerRole) ) && ( this.SignerRoleMetadata == other.SignerRoleMetadata || this.SignerRoleMetadata != null && this.SignerRoleMetadata.Equals(other.SignerRoleMetadata) ) && ( this.Sms == other.Sms || this.Sms != null && this.Sms.Equals(other.Sms) ) && ( this.SmsMetadata == other.SmsMetadata || this.SmsMetadata != null && this.SmsMetadata.Equals(other.SmsMetadata) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { // credit: http://stackoverflow.com/a/263416/677735 unchecked // Overflow is fine, just wrap { int hash = 41; // Suitable nullity checks etc, of course :) if (this.CpfNumber != null) hash = hash * 59 + this.CpfNumber.GetHashCode(); if (this.CpfNumberMetadata != null) hash = hash * 59 + this.CpfNumberMetadata.GetHashCode(); if (this.OneTimePassword != null) hash = hash * 59 + this.OneTimePassword.GetHashCode(); if (this.OneTimePasswordMetadata != null) hash = hash * 59 + this.OneTimePasswordMetadata.GetHashCode(); if (this.SignerRole != null) hash = hash * 59 + this.SignerRole.GetHashCode(); if (this.SignerRoleMetadata != null) hash = hash * 59 + this.SignerRoleMetadata.GetHashCode(); if (this.Sms != null) hash = hash * 59 + this.Sms.GetHashCode(); if (this.SmsMetadata != null) hash = hash * 59 + this.SmsMetadata.GetHashCode(); return hash; } } public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) { yield break; } } }
using System.IO; using System.Threading.Tasks; using AssertExLib; using ExpectedObjects; using LightBlue.Standalone; using Microsoft.WindowsAzure.Storage; using Xunit; using Xunit.Extensions; namespace LightBlue.Tests.Standalone.BlobStorage { public class StandaloneAzureBlockBlobPropertiesTests : StandaloneAzureTestsBase { public StandaloneAzureBlockBlobPropertiesTests() : base(DirectoryType.Container) { var metadataDirectoryPath = Path.Combine(BasePath, ".meta"); Directory.CreateDirectory(metadataDirectoryPath); } [Theory] [PropertyData("BlobNames")] public void WillThrowOnSaveOfPropertiesIfBlobDoesNotExist(string blobName) { var blob = new StandaloneAzureBlockBlob(BasePath, blobName); Assert.Throws<StorageException>(() => blob.SetProperties()); } [Theory] [PropertyData("BlobNames")] public void WillThrowOnAsyncSaveOfPropertiesIfBlobDoesNotExist(string blobName) { var blob = new StandaloneAzureBlockBlob(BasePath, blobName); AssertEx.Throws<StorageException>(() => blob.SetPropertiesAsync()); } [Theory] [PropertyData("BlobNames")] public void CanPersistAndRetrieveProperties(string blobName) { var sourceBlob = new StandaloneAzureBlockBlob(BasePath, blobName); CreateBlobContent(sourceBlob); sourceBlob.Properties.ContentType = "something"; sourceBlob.SetProperties(); var loadedBlob = new StandaloneAzureBlockBlob(BasePath, blobName); loadedBlob.FetchAttributes(); new { Properties = new { ContentType = "something", Length = (long) 12 } }.ToExpectedObject().ShouldMatch(loadedBlob); } [Theory] [PropertyData("BlobNames")] public void DefaultsToOctetStreamWhenLoadingPropertiesWhenPreviouslyUnset(string blobName) { var blob = new StandaloneAzureBlockBlob(BasePath, blobName); CreateBlobContent(blob); blob.FetchAttributes(); new { Properties = new { ContentType = "application/octet-stream", Length = (long) 12 } }.ToExpectedObject().ShouldMatch(blob); } [Theory] [PropertyData("BlobNames")] public async Task CanPersistAndRetrievePropertiesAsync(string blobName) { var sourceBlob = new StandaloneAzureBlockBlob(BasePath, blobName); CreateBlobContent(sourceBlob); sourceBlob.Properties.ContentType = "something"; sourceBlob.SetProperties(); var loadedBlob = new StandaloneAzureBlockBlob(BasePath, blobName); await loadedBlob.FetchAttributesAsync(); new { Properties = new { ContentType = "something", Length = (long) 12 } }.ToExpectedObject().ShouldMatch(loadedBlob); } [Theory] [PropertyData("BlobNames")] public async Task DefaultsToOctetStreamWhenLoadingPropertiesWhenPreviouslyUnsetAsync(string blobName) { var blob = new StandaloneAzureBlockBlob(BasePath, blobName); CreateBlobContent(blob); await blob.FetchAttributesAsync(); new { Properties = new { ContentType = "application/octet-stream", Length = (long) 12 } }.ToExpectedObject().ShouldMatch(blob); } [Theory] [PropertyData("BlobNames")] public void CanPersistPropertiesAsync(string blobName) { var sourceBlob = new StandaloneAzureBlockBlob(BasePath, blobName); CreateBlobContent(sourceBlob); sourceBlob.Properties.ContentType = "something"; sourceBlob.SetPropertiesAsync().Wait(); var loadedBlob = new StandaloneAzureBlockBlob(BasePath, blobName); loadedBlob.FetchAttributes(); new { Properties = new { ContentType = "something", Length = (long) 12 } }.ToExpectedObject().ShouldMatch(loadedBlob); } [Theory] [PropertyData("BlobNames")] public void PropertiesNotPersistedUntilSet(string blobName) { var sourceBlob = new StandaloneAzureBlockBlob(BasePath, blobName); CreateBlobContent(sourceBlob); sourceBlob.Properties.ContentType = "something"; var loadedBlob = new StandaloneAzureBlockBlob(BasePath, blobName); loadedBlob.FetchAttributes(); new { Properties = new { ContentType = "application/octet-stream", } }.ToExpectedObject().ShouldMatch(loadedBlob); } [Theory] [PropertyData("BlobNames")] public void PropertiesCanBeSetRepeatedly(string blobName) { var sourceBlob = new StandaloneAzureBlockBlob(BasePath, blobName); CreateBlobContent(sourceBlob); sourceBlob.Properties.ContentType = "something"; sourceBlob.SetProperties(); sourceBlob.Properties.ContentType = "something else"; sourceBlob.SetProperties(); var loadedBlob = new StandaloneAzureBlockBlob(BasePath, blobName); loadedBlob.FetchAttributes(); new { Properties = new { ContentType = "something else" } }.ToExpectedObject().ShouldMatch(loadedBlob); } [Theory] [PropertyData("BlobNames")] public void FetchingAttributesOverwritesAnyUnsavedPropertyValues(string blobName) { var sourceBlob = new StandaloneAzureBlockBlob(BasePath, blobName); CreateBlobContent(sourceBlob); sourceBlob.Properties.ContentType = "something"; sourceBlob.SetProperties(); var loadedBlob = new StandaloneAzureBlockBlob(BasePath, blobName); loadedBlob.FetchAttributes(); sourceBlob.Properties.ContentType = "something else"; loadedBlob.FetchAttributes(); new { Properties = new { ContentType = "something", Length = (long)12 } }.ToExpectedObject().ShouldMatch(loadedBlob); } [Theory] [PropertyData("BlobNames")] [Trait("Category", "Slow")] public void WillThrowOnSaveOfMetadataWhenFileWriteRetriesExhausted(string blobName) { var metadataPath = Path.Combine(BasePath, ".meta", blobName); var sourceBlob = new StandaloneAzureBlockBlob(BasePath, blobName); CreateBlobContent(sourceBlob); sourceBlob.Properties.ContentType = "thing"; sourceBlob.SetProperties(); var loadedBlob = new StandaloneAzureBlockBlob(BasePath, blobName); loadedBlob.FetchAttributes(); loadedBlob.Properties.ContentType = "otherthing"; using (File.Open(metadataPath, FileMode.Open, FileAccess.ReadWrite, FileShare.None)) { Assert.Throws<StorageException>(() => loadedBlob.SetProperties()); } } } }
//------------------------------------------------------------------------------ // <copyright file="WebServiceHandlerFactory.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Web.Services.Protocols { using System.Diagnostics; using System; using Microsoft.Win32; //using System.Reflection; using System.Web.UI; using System.ComponentModel; // for CompModSwitches using System.IO; using System.Web.Services.Configuration; using System.Security.Permissions; using System.Threading; using System.Web.Services.Diagnostics; /// <include file='doc\WebServiceHandlerFactory.uex' path='docs/doc[@for="WebServiceHandlerFactory"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [PermissionSet(SecurityAction.InheritanceDemand, Name = "FullTrust")] public class WebServiceHandlerFactory : IHttpHandlerFactory { /* static WebServiceHandlerFactory() { Stream stream = new FileStream("c:\\out.txt", FileMode.OpenOrCreate, FileAccess.Write, FileShare.ReadWrite); //(FileMode.OpenOrCreate); TraceListener listener = new TextWriterTraceListener(stream); Debug.AutoFlush = true; Debug.Listeners.Add(listener); Debug.WriteLine("--------------"); } */ #if DEBUG void DumpRequest(HttpContext context) { HttpRequest request = context.Request; Debug.WriteLine("Process Request called."); Debug.WriteLine("Path = " + request.Path); Debug.WriteLine("PhysicalPath = " + request.PhysicalPath); Debug.WriteLine("Query = " + request.Url.Query); Debug.WriteLine("HttpMethod = " + request.HttpMethod); Debug.WriteLine("ContentType = " + request.ContentType); Debug.WriteLine("PathInfo = " + request.PathInfo); Debug.WriteLine("----Http request headers: ----"); System.Collections.Specialized.NameValueCollection headers = request.Headers; foreach (string name in headers) { string value = headers[name]; if (value != null && value.Length > 0) Debug.WriteLine(name + "=" + headers[name]); } } #endif /// <include file='doc\WebServiceHandlerFactory.uex' path='docs/doc[@for="WebServiceHandlerFactory.GetHandler"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public IHttpHandler GetHandler(HttpContext context, string verb, string url, string filePath) { TraceMethod method = Tracing.On ? new TraceMethod(this, "GetHandler") : null; if (Tracing.On) Tracing.Enter("IHttpHandlerFactory.GetHandler", method, Tracing.Details(context.Request)); new AspNetHostingPermission(AspNetHostingPermissionLevel.Minimal).Demand(); //if (CompModSwitches.Remote.TraceVerbose) DumpRequest(context); //System.Diagnostics.Debugger.Break(); #if DEBUG if (CompModSwitches.Remote.TraceVerbose) DumpRequest(context); #endif Type type = GetCompiledType(url, context); IHttpHandler handler = CoreGetHandler(type, context, context.Request, context.Response); if (Tracing.On) Tracing.Exit("IHttpHandlerFactory.GetHandler", method); return handler; } // Asserts security permission. // Reason: System.Web.UI.WebServiceParser.GetCompiledType() demands SecurityPermission. // Justification: The type returned is only used to get the IHttpHandler. [SecurityPermission(SecurityAction.Assert, Unrestricted = true)] private Type GetCompiledType(string url, HttpContext context) { return WebServiceParser.GetCompiledType(url, context); } internal IHttpHandler CoreGetHandler(Type type, HttpContext context, HttpRequest request, HttpResponse response) { TraceMethod caller = Tracing.On ? new TraceMethod(this, "CoreGetHandler") : null; ServerProtocolFactory[] protocolFactories = GetServerProtocolFactories(); ServerProtocol protocol = null; bool abort = false; for (int i = 0; i < protocolFactories.Length; i++) { try { protocol = protocolFactories[i].Create(type, context, request, response, out abort); if ((protocol != null && protocol.GetType() != typeof(UnsupportedRequestProtocol)) || abort) break; } catch (Exception e) { if (e is ThreadAbortException || e is StackOverflowException || e is OutOfMemoryException) { throw; } throw Tracing.ExceptionThrow(caller, new InvalidOperationException(Res.GetString(Res.FailedToHandleRequest0), e)); } } if (abort) return new NopHandler(); if (protocol == null) { if (request.PathInfo != null && request.PathInfo.Length != 0) { throw Tracing.ExceptionThrow(caller, new InvalidOperationException(Res.GetString(Res.WebUnrecognizedRequestFormatUrl, new object[] { request.PathInfo }))); } else { throw Tracing.ExceptionThrow(caller, new InvalidOperationException(Res.GetString(Res.WebUnrecognizedRequestFormat))); } } else if (protocol is UnsupportedRequestProtocol) { throw Tracing.ExceptionThrow(caller, new HttpException(((UnsupportedRequestProtocol)protocol).HttpCode, Res.GetString(Res.WebUnrecognizedRequestFormat))); } bool isAsync = protocol.MethodInfo.IsAsync; bool requiresSession = protocol.MethodAttribute.EnableSession; if (isAsync) { if (requiresSession) { return new AsyncSessionHandler(protocol); } else { return new AsyncSessionlessHandler(protocol); } } else { if (requiresSession) { return new SyncSessionHandler(protocol); } else { return new SyncSessionlessHandler(protocol); } } } // Asserts FullTrust permission. // Justification: FullTrust is used only to create the objects of type SoapServerProtocolFactory and for nothing else. [PermissionSet(SecurityAction.Assert, Name = "FullTrust")] private ServerProtocolFactory[] GetServerProtocolFactories() { return WebServicesSection.Current.ServerProtocolFactories; } /// <include file='doc\WebServiceHandlerFactory.uex' path='docs/doc[@for="WebServiceHandlerFactory.ReleaseHandler"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public void ReleaseHandler(IHttpHandler handler) { } } internal class UnsupportedRequestProtocol : ServerProtocol { int httpCode; internal UnsupportedRequestProtocol(int httpCode) { this.httpCode = httpCode; } internal int HttpCode { get { return httpCode; } } internal override bool Initialize() { return true; } internal override bool IsOneWay { get { return false; } } internal override LogicalMethodInfo MethodInfo { get { return null; } } internal override ServerType ServerType { get { return null; } } internal override object[] ReadParameters() { return new object[0]; } internal override void WriteReturns(object[] returnValues, Stream outputStream) { } internal override bool WriteException(Exception e, Stream outputStream) { return false; } } internal class NopHandler : IHttpHandler { /// <include file='doc\WebServiceHandlerFactory.uex' path='docs/doc[@for="NopHandler.IsReusable"]/*' /> /// <devdoc> /// IHttpHandler.IsReusable. /// </devdoc> public bool IsReusable { get { return false; } } /// <include file='doc\WebServiceHandlerFactory.uex' path='docs/doc[@for="NopHandler.ProcessRequest"]/*' /> /// <devdoc> /// IHttpHandler.ProcessRequest. /// </devdoc> public void ProcessRequest(HttpContext context) { } } }
using System; using System.IO; using System.Text; using System.Collections; namespace Zeus { /// <summary> /// Summary description for ZeusBodyParser. /// </summary> public class ZeusCodeParser { public static void ParseCode(ZeusCodeSegment segment) { StringReader reader; StringBuilder builder; IZeusScriptingEngine engine; segment.ExtraData.Clear(); // If this is a compiled template, don't try to parse it! if ((segment.Template.SourceType == ZeusConstants.SourceTypes.COMPILED) && (segment.CachedAssembly != null)) { return; } if (!segment.IsEmpty) { if (segment.Template.SourceType == ZeusConstants.SourceTypes.ENCRYPTED) { reader = new StringReader( ZeusEncryption.Decrypt(segment.CodeUnparsed) ); } else { reader = new StringReader(segment.CodeUnparsed); } builder = new StringBuilder(); engine = ZeusFactory.GetEngine(segment.Engine); if (segment.Mode == ZeusConstants.Modes.MARKUP) { ParseMarkup(engine, segment, reader, builder); } else { ParsePure(engine, segment, reader, builder); } segment.Code = builder.ToString(); } } #region Parse Markup Code protected static void ParseMarkup(IZeusScriptingEngine engine, ZeusCodeSegment segment, StringReader reader, StringBuilder builder) { string line, nextline; string tagStart = segment.Template.TagStart, tagSpecial = segment.Template.TagStartSpecial, tagShortcut = segment.Template.TagStartShortcut, tagEnd = segment.Template.TagEnd, language = segment.Language; ArrayList extraData = segment.ExtraData; int index; bool inBlock = false; bool isShortcut = false; bool isCustom = false; string nextTagToFind = string.Empty; IZeusCodeParser codeParser = engine.CodeParser; var sb = new StringBuilder(); int headerInsertIndex = builder.Length; line = reader.ReadLine(); int i = reader.Peek(); while (line != null) { nextline = reader.ReadLine(); index = line.IndexOf(inBlock ? tagEnd : tagStart); while (index >= 0) { if (inBlock) { inBlock = false; if (isShortcut) { sb.Append(line.Substring(0, index)); //TODO: ***If the line in the shortcut has more than one command (a semicolon) throw an exception. builder.Append( codeParser.BuildOutputCommand(language, sb.ToString() , false, false) ); sb.Clear(); isShortcut = false; } else if (isCustom) { //TODO: ***If the line in the include has more than one command (a semicolon) throw an exception. builder.Append( codeParser.ParseCustomTag(segment, line.Substring(0, index)) ); isCustom = false; } else { builder.Append(line.Substring(0, index).Trim() + "\r\n"); } line = line.Substring(index + tagEnd.Length); } else { inBlock = true; if (index > 0) { // Append the code before the open tag builder.Append( codeParser.BuildOutputCommand(language, line.Substring(0, index), true, false) ); } if (index == line.IndexOf(tagShortcut)) { isCustom = false; isShortcut = true; // Set the line to the actual code line = line.Substring(index + tagShortcut.Length); } else if (index == line.IndexOf(tagSpecial)) { isCustom = true; isShortcut = false; line = line.Substring(index + tagSpecial.Length); } else { isCustom = false; isShortcut = false; line = line.Substring(index + tagStart.Length); } } index = line.IndexOf(inBlock ? tagEnd : tagStart); } // Custom tags have to start and end on the same line! isCustom = false; if (isShortcut) { sb.Append(line.Trim() + "\r\n"); } else if (inBlock) { builder.Append(line.Trim() + "\r\n"); } else { if ( !((nextline == null) && (line == string.Empty)) ) { builder.Append( codeParser.BuildOutputCommand(language, line, true, true) ); } } line = nextline; } builder.Insert(headerInsertIndex, codeParser.GetCustomHeaderCode(segment, ZeusFactory.IntrinsicObjectsArray)); builder.Append(codeParser.GetCustomFooterCode(segment, ZeusFactory.IntrinsicObjectsArray)); } #endregion #region Parse Pure Code protected static void ParsePure(IZeusScriptingEngine engine, ZeusCodeSegment segment, StringReader reader, StringBuilder builder) { string line, nextline; string tagSpecial = segment.Template.TagStartSpecial, tagEnd = segment.Template.TagEnd, language = segment.Language; ArrayList extraData = segment.ExtraData; bool isGui = (segment.SegmentType == ZeusConstants.CodeSegmentTypes.GUI_SEGMENT); int index; bool inBlock = false; IZeusCodeParser codeParser = engine.CodeParser; line = reader.ReadLine(); int i = reader.Peek(); while (line != null) { nextline = reader.ReadLine(); index = line.IndexOf(inBlock ? tagEnd : tagSpecial); while (index >= 0) { if (inBlock) { inBlock = false; builder.Append( codeParser.ParseCustomTag(segment, line.Substring(0, index)) ); line = line.Substring(index + tagEnd.Length); } else { inBlock = true; if (index > 0) { builder.Append(line.Substring(0, index)); } line = line.Substring(index + tagSpecial.Length); } index = line.IndexOf(inBlock ? tagEnd : tagSpecial); } // with pure script mode, tags can NOT span more than one line! inBlock = false; builder.Append(line.Trim() + "\r\n"); line = nextline; } builder.Insert(0, codeParser.GetCustomHeaderCode(segment, ZeusFactory.IntrinsicObjectsArray)); builder.Append(codeParser.GetCustomFooterCode(segment, ZeusFactory.IntrinsicObjectsArray)); } #endregion } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. #nullable enable using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using NUnit.Framework; using osu.Framework.Allocation; using osu.Framework.Extensions; using osu.Game.Beatmaps; using osu.Game.Database; using osu.Game.Rulesets; using osu.Game.Tests.Resources; using Realms; namespace osu.Game.Tests.Database { [TestFixture] public class RealmSubscriptionRegistrationTests : RealmTest { [Test] public void TestSubscriptionCollectionAndPropertyChanges() { int collectionChanges = 0; int propertyChanges = 0; ChangeSet? lastChanges = null; RunTestWithRealm((realm, _) => { var registration = realm.RegisterForNotifications(r => r.All<BeatmapSetInfo>(), onChanged); realm.Run(r => r.Refresh()); realm.Write(r => r.Add(TestResources.CreateTestBeatmapSetInfo())); realm.Run(r => r.Refresh()); Assert.That(collectionChanges, Is.EqualTo(1)); Assert.That(propertyChanges, Is.EqualTo(0)); Assert.That(lastChanges?.InsertedIndices, Has.One.Items); Assert.That(lastChanges?.ModifiedIndices, Is.Empty); Assert.That(lastChanges?.NewModifiedIndices, Is.Empty); realm.Write(r => r.All<BeatmapSetInfo>().First().Beatmaps.First().CountdownOffset = 5); realm.Run(r => r.Refresh()); Assert.That(collectionChanges, Is.EqualTo(1)); Assert.That(propertyChanges, Is.EqualTo(1)); Assert.That(lastChanges?.InsertedIndices, Is.Empty); Assert.That(lastChanges?.ModifiedIndices, Has.One.Items); Assert.That(lastChanges?.NewModifiedIndices, Has.One.Items); registration.Dispose(); }); void onChanged(IRealmCollection<BeatmapSetInfo> sender, ChangeSet? changes, Exception error) { lastChanges = changes; if (changes == null) return; if (changes.HasCollectionChanges()) { Interlocked.Increment(ref collectionChanges); } else { Interlocked.Increment(ref propertyChanges); } } } [Test] public void TestSubscriptionWithAsyncWrite() { ChangeSet? lastChanges = null; RunTestWithRealm((realm, _) => { var registration = realm.RegisterForNotifications(r => r.All<BeatmapSetInfo>(), onChanged); realm.Run(r => r.Refresh()); // Without forcing the write onto its own thread, realm will internally run the operation synchronously, which can cause a deadlock with `WaitSafely`. Task.Run(async () => { await realm.WriteAsync(r => r.Add(TestResources.CreateTestBeatmapSetInfo())); }).WaitSafely(); realm.Run(r => r.Refresh()); Assert.That(lastChanges?.InsertedIndices, Has.One.Items); registration.Dispose(); }); void onChanged(IRealmCollection<BeatmapSetInfo> sender, ChangeSet? changes, Exception error) => lastChanges = changes; } [Test] public void TestPropertyChangedSubscription() { RunTestWithRealm((realm, _) => { bool? receivedValue = null; realm.Write(r => r.Add(TestResources.CreateTestBeatmapSetInfo())); using (realm.SubscribeToPropertyChanged(r => r.All<BeatmapSetInfo>().First(), setInfo => setInfo.Protected, val => receivedValue = val)) { Assert.That(receivedValue, Is.False); realm.Write(r => r.All<BeatmapSetInfo>().First().Protected = true); realm.Run(r => r.Refresh()); Assert.That(receivedValue, Is.True); } }); } [Test] public void TestSubscriptionWithContextLoss() { IEnumerable<BeatmapSetInfo>? resolvedItems = null; ChangeSet? lastChanges = null; RunTestWithRealm((realm, _) => { realm.Write(r => r.Add(TestResources.CreateTestBeatmapSetInfo())); var registration = realm.RegisterForNotifications(r => r.All<BeatmapSetInfo>(), onChanged); testEventsArriving(true); // All normal until here. // Now let's yank the main realm context. resolvedItems = null; lastChanges = null; using (realm.BlockAllOperations()) Assert.That(resolvedItems, Is.Empty); realm.Write(r => r.Add(TestResources.CreateTestBeatmapSetInfo())); testEventsArriving(true); // Now let's try unsubscribing. resolvedItems = null; lastChanges = null; registration.Dispose(); realm.Write(r => r.Add(TestResources.CreateTestBeatmapSetInfo())); testEventsArriving(false); // And make sure even after another context loss we don't get firings. using (realm.BlockAllOperations()) Assert.That(resolvedItems, Is.Null); realm.Write(r => r.Add(TestResources.CreateTestBeatmapSetInfo())); testEventsArriving(false); void testEventsArriving(bool shouldArrive) { realm.Run(r => r.Refresh()); if (shouldArrive) Assert.That(resolvedItems, Has.One.Items); else Assert.That(resolvedItems, Is.Null); realm.Write(r => { r.RemoveAll<BeatmapSetInfo>(); r.RemoveAll<RulesetInfo>(); }); realm.Run(r => r.Refresh()); if (shouldArrive) Assert.That(lastChanges?.DeletedIndices, Has.One.Items); else Assert.That(lastChanges, Is.Null); } }); void onChanged(IRealmCollection<BeatmapSetInfo> sender, ChangeSet? changes, Exception error) { if (changes == null) resolvedItems = sender; lastChanges = changes; } } [Test] public void TestCustomRegisterWithContextLoss() { RunTestWithRealm((realm, _) => { BeatmapSetInfo? beatmapSetInfo = null; realm.Write(r => r.Add(TestResources.CreateTestBeatmapSetInfo())); var subscription = realm.RegisterCustomSubscription(r => { beatmapSetInfo = r.All<BeatmapSetInfo>().First(); return new InvokeOnDisposal(() => beatmapSetInfo = null); }); Assert.That(beatmapSetInfo, Is.Not.Null); using (realm.BlockAllOperations()) { // custom disposal action fired when context lost. Assert.That(beatmapSetInfo, Is.Null); } // re-registration after context restore. realm.Run(r => r.Refresh()); Assert.That(beatmapSetInfo, Is.Not.Null); subscription.Dispose(); Assert.That(beatmapSetInfo, Is.Null); using (realm.BlockAllOperations()) Assert.That(beatmapSetInfo, Is.Null); realm.Run(r => r.Refresh()); Assert.That(beatmapSetInfo, Is.Null); }); } [Test] public void TestPropertyChangedSubscriptionWithContextLoss() { RunTestWithRealm((realm, _) => { bool? receivedValue = null; realm.Write(r => r.Add(TestResources.CreateTestBeatmapSetInfo())); var subscription = realm.SubscribeToPropertyChanged( r => r.All<BeatmapSetInfo>().First(), setInfo => setInfo.Protected, val => receivedValue = val); Assert.That(receivedValue, Is.Not.Null); receivedValue = null; using (realm.BlockAllOperations()) { } // re-registration after context restore. realm.Run(r => r.Refresh()); Assert.That(receivedValue, Is.Not.Null); subscription.Dispose(); receivedValue = null; using (realm.BlockAllOperations()) Assert.That(receivedValue, Is.Null); realm.Run(r => r.Refresh()); Assert.That(receivedValue, Is.Null); }); } } }
using System; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Text; // ReSharper disable MemberCanBePrivate.Global // ReSharper disable FieldCanBeMadeReadOnly.Global // ReSharper disable CommentTypo // ReSharper disable UnusedMember.Global // ReSharper disable IdentifierTypo // ReSharper disable NotAccessedField.Global // ReSharper disable UnusedMethodReturnValue.Global namespace Avalonia.X11 { internal unsafe static class XLib { const string libX11 = "libX11.so.6"; const string libX11Randr = "libXrandr.so.2"; const string libX11Ext = "libXext.so.6"; const string libXInput = "libXi.so.6"; [DllImport(libX11)] public static extern IntPtr XOpenDisplay(IntPtr display); [DllImport(libX11)] public static extern int XCloseDisplay(IntPtr display); [DllImport(libX11)] public static extern IntPtr XSynchronize(IntPtr display, bool onoff); [DllImport(libX11)] public static extern IntPtr XCreateWindow(IntPtr display, IntPtr parent, int x, int y, int width, int height, int border_width, int depth, int xclass, IntPtr visual, UIntPtr valuemask, ref XSetWindowAttributes attributes); [DllImport(libX11)] public static extern IntPtr XCreateSimpleWindow(IntPtr display, IntPtr parent, int x, int y, int width, int height, int border_width, IntPtr border, IntPtr background); [DllImport(libX11)] public static extern int XMapWindow(IntPtr display, IntPtr window); [DllImport(libX11)] public static extern int XUnmapWindow(IntPtr display, IntPtr window); [DllImport(libX11)] public static extern int XMapSubindows(IntPtr display, IntPtr window); [DllImport(libX11)] public static extern int XUnmapSubwindows(IntPtr display, IntPtr window); [DllImport(libX11)] public static extern IntPtr XRootWindow(IntPtr display, int screen_number); [DllImport(libX11)] public static extern IntPtr XDefaultRootWindow(IntPtr display); [DllImport(libX11)] public static extern IntPtr XNextEvent(IntPtr display, out XEvent xevent); [DllImport(libX11)] public static extern int XConnectionNumber(IntPtr diplay); [DllImport(libX11)] public static extern int XPending(IntPtr diplay); [DllImport(libX11)] public static extern IntPtr XSelectInput(IntPtr display, IntPtr window, IntPtr mask); [DllImport(libX11)] public static extern int XDestroyWindow(IntPtr display, IntPtr window); [DllImport(libX11)] public static extern int XReparentWindow(IntPtr display, IntPtr window, IntPtr parent, int x, int y); [DllImport(libX11)] public static extern int XMoveResizeWindow(IntPtr display, IntPtr window, int x, int y, int width, int height); [DllImport(libX11)] public static extern int XResizeWindow(IntPtr display, IntPtr window, int width, int height); [DllImport(libX11)] public static extern int XGetWindowAttributes(IntPtr display, IntPtr window, ref XWindowAttributes attributes); [DllImport(libX11)] public static extern int XFlush(IntPtr display); [DllImport(libX11)] public static extern int XSetWMName(IntPtr display, IntPtr window, ref XTextProperty text_prop); [DllImport(libX11)] public static extern int XStoreName(IntPtr display, IntPtr window, string window_name); [DllImport(libX11)] public static extern int XFetchName(IntPtr display, IntPtr window, ref IntPtr window_name); [DllImport(libX11)] public static extern int XSendEvent(IntPtr display, IntPtr window, bool propagate, IntPtr event_mask, ref XEvent send_event); [DllImport(libX11)] public static extern int XQueryTree(IntPtr display, IntPtr window, out IntPtr root_return, out IntPtr parent_return, out IntPtr children_return, out int nchildren_return); [DllImport(libX11)] public static extern int XFree(IntPtr data); [DllImport(libX11)] public static extern int XRaiseWindow(IntPtr display, IntPtr window); [DllImport(libX11)] public static extern uint XLowerWindow(IntPtr display, IntPtr window); [DllImport(libX11)] public static extern uint XConfigureWindow(IntPtr display, IntPtr window, ChangeWindowFlags value_mask, ref XWindowChanges values); public static uint XConfigureResizeWindow(IntPtr display, IntPtr window, PixelSize size) => XConfigureResizeWindow(display, window, size.Width, size.Height); public static uint XConfigureResizeWindow(IntPtr display, IntPtr window, int width, int height) { var changes = new XWindowChanges { width = width, height = height }; return XConfigureWindow(display, window, ChangeWindowFlags.CWHeight | ChangeWindowFlags.CWWidth, ref changes); } [DllImport(libX11)] public static extern IntPtr XInternAtom(IntPtr display, string atom_name, bool only_if_exists); [DllImport(libX11)] public static extern int XInternAtoms(IntPtr display, string[] atom_names, int atom_count, bool only_if_exists, IntPtr[] atoms); [DllImport(libX11)] public static extern IntPtr XGetAtomName(IntPtr display, IntPtr atom); public static string GetAtomName(IntPtr display, IntPtr atom) { var ptr = XGetAtomName(display, atom); if (ptr == IntPtr.Zero) return null; var s = Marshal.PtrToStringAnsi(ptr); XFree(ptr); return s; } [DllImport(libX11)] public static extern int XSetWMProtocols(IntPtr display, IntPtr window, IntPtr[] protocols, int count); [DllImport(libX11)] public static extern int XGrabPointer(IntPtr display, IntPtr window, bool owner_events, EventMask event_mask, GrabMode pointer_mode, GrabMode keyboard_mode, IntPtr confine_to, IntPtr cursor, IntPtr timestamp); [DllImport(libX11)] public static extern int XUngrabPointer(IntPtr display, IntPtr timestamp); [DllImport(libX11)] public static extern bool XQueryPointer(IntPtr display, IntPtr window, out IntPtr root, out IntPtr child, out int root_x, out int root_y, out int win_x, out int win_y, out int keys_buttons); [DllImport(libX11)] public static extern bool XTranslateCoordinates(IntPtr display, IntPtr src_w, IntPtr dest_w, int src_x, int src_y, out int intdest_x_return, out int dest_y_return, out IntPtr child_return); [DllImport(libX11)] public static extern bool XGetGeometry(IntPtr display, IntPtr window, out IntPtr root, out int x, out int y, out int width, out int height, out int border_width, out int depth); [DllImport(libX11)] public static extern bool XGetGeometry(IntPtr display, IntPtr window, IntPtr root, out int x, out int y, out int width, out int height, IntPtr border_width, IntPtr depth); [DllImport(libX11)] public static extern bool XGetGeometry(IntPtr display, IntPtr window, IntPtr root, out int x, out int y, IntPtr width, IntPtr height, IntPtr border_width, IntPtr depth); [DllImport(libX11)] public static extern bool XGetGeometry(IntPtr display, IntPtr window, IntPtr root, IntPtr x, IntPtr y, out int width, out int height, IntPtr border_width, IntPtr depth); [DllImport(libX11)] public static extern uint XWarpPointer(IntPtr display, IntPtr src_w, IntPtr dest_w, int src_x, int src_y, uint src_width, uint src_height, int dest_x, int dest_y); [DllImport(libX11)] public static extern int XClearWindow(IntPtr display, IntPtr window); [DllImport(libX11)] public static extern int XClearArea(IntPtr display, IntPtr window, int x, int y, int width, int height, bool exposures); // Colormaps [DllImport(libX11)] public static extern IntPtr XDefaultScreenOfDisplay(IntPtr display); [DllImport(libX11)] public static extern int XScreenNumberOfScreen(IntPtr display, IntPtr Screen); [DllImport(libX11)] public static extern IntPtr XDefaultVisual(IntPtr display, int screen_number); [DllImport(libX11)] public static extern uint XDefaultDepth(IntPtr display, int screen_number); [DllImport(libX11)] public static extern int XDefaultScreen(IntPtr display); [DllImport(libX11)] public static extern IntPtr XDefaultColormap(IntPtr display, int screen_number); [DllImport(libX11)] public static extern int XLookupColor(IntPtr display, IntPtr Colormap, string Coloranem, ref XColor exact_def_color, ref XColor screen_def_color); [DllImport(libX11)] public static extern int XAllocColor(IntPtr display, IntPtr Colormap, ref XColor colorcell_def); [DllImport(libX11)] public static extern int XSetTransientForHint(IntPtr display, IntPtr window, IntPtr parent); [DllImport(libX11)] public static extern int XChangeProperty(IntPtr display, IntPtr window, IntPtr property, IntPtr type, int format, PropertyMode mode, ref MotifWmHints data, int nelements); [DllImport(libX11)] public static extern int XChangeProperty(IntPtr display, IntPtr window, IntPtr property, IntPtr type, int format, PropertyMode mode, ref uint value, int nelements); [DllImport(libX11)] public static extern int XChangeProperty(IntPtr display, IntPtr window, IntPtr property, IntPtr type, int format, PropertyMode mode, ref IntPtr value, int nelements); [DllImport(libX11)] public static extern int XChangeProperty(IntPtr display, IntPtr window, IntPtr property, IntPtr type, int format, PropertyMode mode, byte[] data, int nelements); [DllImport(libX11)] public static extern int XChangeProperty(IntPtr display, IntPtr window, IntPtr property, IntPtr type, int format, PropertyMode mode, uint[] data, int nelements); [DllImport(libX11)] public static extern int XChangeProperty(IntPtr display, IntPtr window, IntPtr property, IntPtr type, int format, PropertyMode mode, int[] data, int nelements); [DllImport(libX11)] public static extern int XChangeProperty(IntPtr display, IntPtr window, IntPtr property, IntPtr type, int format, PropertyMode mode, IntPtr[] data, int nelements); [DllImport(libX11)] public static extern int XChangeProperty(IntPtr display, IntPtr window, IntPtr property, IntPtr type, int format, PropertyMode mode, void* data, int nelements); [DllImport(libX11)] public static extern int XChangeProperty(IntPtr display, IntPtr window, IntPtr property, IntPtr type, int format, PropertyMode mode, IntPtr atoms, int nelements); [DllImport(libX11, CharSet = CharSet.Ansi)] public static extern int XChangeProperty(IntPtr display, IntPtr window, IntPtr property, IntPtr type, int format, PropertyMode mode, string text, int text_length); [DllImport(libX11)] public static extern int XDeleteProperty(IntPtr display, IntPtr window, IntPtr property); // Drawing [DllImport(libX11)] public static extern IntPtr XCreateGC(IntPtr display, IntPtr window, IntPtr valuemask, ref XGCValues values); [DllImport(libX11)] public static extern int XFreeGC(IntPtr display, IntPtr gc); [DllImport(libX11)] public static extern int XSetFunction(IntPtr display, IntPtr gc, GXFunction function); [DllImport(libX11)] internal static extern int XSetLineAttributes(IntPtr display, IntPtr gc, int line_width, GCLineStyle line_style, GCCapStyle cap_style, GCJoinStyle join_style); [DllImport(libX11)] public static extern int XDrawLine(IntPtr display, IntPtr drawable, IntPtr gc, int x1, int y1, int x2, int y2); [DllImport(libX11)] public static extern int XDrawRectangle(IntPtr display, IntPtr drawable, IntPtr gc, int x1, int y1, int width, int height); [DllImport(libX11)] public static extern int XFillRectangle(IntPtr display, IntPtr drawable, IntPtr gc, int x1, int y1, int width, int height); [DllImport(libX11)] public static extern int XSetWindowBackground(IntPtr display, IntPtr window, IntPtr background); [DllImport(libX11)] public static extern int XCopyArea(IntPtr display, IntPtr src, IntPtr dest, IntPtr gc, int src_x, int src_y, int width, int height, int dest_x, int dest_y); [DllImport(libX11)] public static extern int XGetWindowProperty(IntPtr display, IntPtr window, IntPtr atom, IntPtr long_offset, IntPtr long_length, bool delete, IntPtr req_type, out IntPtr actual_type, out int actual_format, out IntPtr nitems, out IntPtr bytes_after, out IntPtr prop); [DllImport(libX11)] public static extern int XSetInputFocus(IntPtr display, IntPtr window, RevertTo revert_to, IntPtr time); [DllImport(libX11)] public static extern int XIconifyWindow(IntPtr display, IntPtr window, int screen_number); [DllImport(libX11)] public static extern int XDefineCursor(IntPtr display, IntPtr window, IntPtr cursor); [DllImport(libX11)] public static extern int XUndefineCursor(IntPtr display, IntPtr window); [DllImport(libX11)] public static extern int XFreeCursor(IntPtr display, IntPtr cursor); [DllImport(libX11)] public static extern IntPtr XCreateFontCursor(IntPtr display, CursorFontShape shape); [DllImport(libX11)] public static extern IntPtr XCreatePixmapCursor(IntPtr display, IntPtr source, IntPtr mask, ref XColor foreground_color, ref XColor background_color, int x_hot, int y_hot); [DllImport(libX11)] public static extern IntPtr XCreateBitmapFromData(IntPtr display, IntPtr drawable, byte[] data, int width, int height); [DllImport(libX11)] public static extern IntPtr XCreatePixmapFromBitmapData(IntPtr display, IntPtr drawable, byte[] data, int width, int height, IntPtr fg, IntPtr bg, int depth); [DllImport(libX11)] public static extern IntPtr XCreatePixmap(IntPtr display, IntPtr d, int width, int height, int depth); [DllImport(libX11)] public static extern IntPtr XFreePixmap(IntPtr display, IntPtr pixmap); [DllImport(libX11)] public static extern int XQueryBestCursor(IntPtr display, IntPtr drawable, int width, int height, out int best_width, out int best_height); [DllImport(libX11)] public static extern IntPtr XWhitePixel(IntPtr display, int screen_no); [DllImport(libX11)] public static extern IntPtr XBlackPixel(IntPtr display, int screen_no); [DllImport(libX11)] public static extern void XGrabServer(IntPtr display); [DllImport(libX11)] public static extern void XUngrabServer(IntPtr display); [DllImport(libX11)] public static extern void XGetWMNormalHints(IntPtr display, IntPtr window, ref XSizeHints hints, out IntPtr supplied_return); [DllImport(libX11)] public static extern void XSetWMNormalHints(IntPtr display, IntPtr window, ref XSizeHints hints); [DllImport(libX11)] public static extern void XSetZoomHints(IntPtr display, IntPtr window, ref XSizeHints hints); [DllImport(libX11)] public static extern void XSetWMHints(IntPtr display, IntPtr window, ref XWMHints wmhints); [DllImport(libX11)] public static extern int XGetIconSizes(IntPtr display, IntPtr window, out IntPtr size_list, out int count); [DllImport(libX11)] public static extern IntPtr XSetErrorHandler(XErrorHandler error_handler); [DllImport(libX11)] public static extern IntPtr XGetErrorText(IntPtr display, byte code, StringBuilder buffer, int length); [DllImport(libX11)] public static extern int XInitThreads(); [DllImport(libX11)] public static extern int XConvertSelection(IntPtr display, IntPtr selection, IntPtr target, IntPtr property, IntPtr requestor, IntPtr time); [DllImport(libX11)] public static extern IntPtr XGetSelectionOwner(IntPtr display, IntPtr selection); [DllImport(libX11)] public static extern int XSetSelectionOwner(IntPtr display, IntPtr selection, IntPtr owner, IntPtr time); [DllImport(libX11)] public static extern int XSetPlaneMask(IntPtr display, IntPtr gc, IntPtr mask); [DllImport(libX11)] public static extern int XSetForeground(IntPtr display, IntPtr gc, UIntPtr foreground); [DllImport(libX11)] public static extern int XSetBackground(IntPtr display, IntPtr gc, UIntPtr background); [DllImport(libX11)] public static extern int XBell(IntPtr display, int percent); [DllImport(libX11)] public static extern int XChangeActivePointerGrab(IntPtr display, EventMask event_mask, IntPtr cursor, IntPtr time); [DllImport(libX11)] public static extern bool XFilterEvent(ref XEvent xevent, IntPtr window); [DllImport(libX11)] public static extern void XkbSetDetectableAutoRepeat(IntPtr display, bool detectable, IntPtr supported); [DllImport(libX11)] public static extern void XPeekEvent(IntPtr display, out XEvent xevent); [DllImport(libX11)] public static extern void XMatchVisualInfo(IntPtr display, int screen, int depth, int klass, out XVisualInfo info); [DllImport(libX11)] public static extern IntPtr XLockDisplay(IntPtr display); [DllImport(libX11)] public static extern IntPtr XUnlockDisplay(IntPtr display); [DllImport(libX11)] public static extern IntPtr XCreateGC(IntPtr display, IntPtr drawable, ulong valuemask, IntPtr values); [DllImport(libX11)] public static extern int XInitImage(ref XImage image); [DllImport(libX11)] public static extern int XDestroyImage(ref XImage image); [DllImport(libX11)] public static extern int XPutImage(IntPtr display, IntPtr drawable, IntPtr gc, ref XImage image, int srcx, int srcy, int destx, int desty, uint width, uint height); [DllImport(libX11)] public static extern int XSync(IntPtr display, bool discard); [DllImport(libX11)] public static extern IntPtr XCreateColormap(IntPtr display, IntPtr window, IntPtr visual, int create); public enum XLookupStatus { XBufferOverflow = -1, XLookupNone = 1, XLookupChars = 2, XLookupKeySym = 3, XLookupBoth = 4 } [DllImport (libX11)] public static extern unsafe int XLookupString(ref XEvent xevent, void* buffer, int num_bytes, out IntPtr keysym, out IntPtr status); [DllImport (libX11)] public static extern unsafe int Xutf8LookupString(IntPtr xic, ref XEvent xevent, void* buffer, int num_bytes, out IntPtr keysym, out IntPtr status); [DllImport (libX11)] public static extern unsafe IntPtr XKeycodeToKeysym(IntPtr display, int keycode, int index); [DllImport (libX11)] public static extern unsafe IntPtr XSetLocaleModifiers(string modifiers); [DllImport (libX11)] public static extern IntPtr XOpenIM (IntPtr display, IntPtr rdb, IntPtr res_name, IntPtr res_class); [DllImport (libX11)] public static extern IntPtr XCreateIC (IntPtr xim, string name, XIMProperties im_style, string name2, IntPtr value2, IntPtr terminator); [DllImport (libX11)] public static extern IntPtr XCreateIC (IntPtr xim, string name, XIMProperties im_style, string name2, IntPtr value2, string name3, IntPtr value3, IntPtr terminator); [DllImport (libX11)] public static extern void XCloseIM (IntPtr xim); [DllImport (libX11)] public static extern void XDestroyIC (IntPtr xic); [DllImport(libX11)] public static extern bool XQueryExtension(IntPtr display, [MarshalAs(UnmanagedType.LPStr)] string name, out int majorOpcode, out int firstEvent, out int firstError); [DllImport(libX11)] public static extern bool XGetEventData(IntPtr display, void* cookie); [DllImport(libX11)] public static extern void XFreeEventData(IntPtr display, void* cookie); [DllImport(libX11Randr)] public static extern int XRRQueryExtension (IntPtr dpy, out int event_base_return, out int error_base_return); [DllImport(libX11Randr)] public static extern int XRRQueryVersion(IntPtr dpy, out int major_version_return, out int minor_version_return); [DllImport(libX11Randr)] public static extern XRRMonitorInfo* XRRGetMonitors(IntPtr dpy, IntPtr window, bool get_active, out int nmonitors); [DllImport(libX11Randr)] public static extern void XRRSelectInput(IntPtr dpy, IntPtr window, RandrEventMask mask); [DllImport(libXInput)] public static extern Status XIQueryVersion(IntPtr dpy, ref int major, ref int minor); [DllImport(libXInput)] public static extern IntPtr XIQueryDevice(IntPtr dpy, int deviceid, out int ndevices_return); [DllImport(libXInput)] public static extern void XIFreeDeviceInfo(XIDeviceInfo* info); public static void XISetMask(ref int mask, XiEventType ev) { mask |= (1 << (int)ev); } public static int XiEventMaskLen { get; } = 4; public static bool XIMaskIsSet(void* ptr, int shift) => (((byte*)(ptr))[(shift) >> 3] & (1 << (shift & 7))) != 0; [DllImport(libXInput)] public static extern Status XISelectEvents( IntPtr dpy, IntPtr win, XIEventMask* masks, int num_masks ); public static Status XiSelectEvents(IntPtr display, IntPtr window, Dictionary<int, List<XiEventType>> devices) { var masks = stackalloc int[devices.Count]; var emasks = stackalloc XIEventMask[devices.Count]; int c = 0; foreach (var d in devices) { foreach (var ev in d.Value) XISetMask(ref masks[c], ev); emasks[c] = new XIEventMask { Mask = &masks[c], Deviceid = d.Key, MaskLen = XiEventMaskLen }; c++; } return XISelectEvents(display, window, emasks, devices.Count); } public struct XGeometry { public IntPtr root; public int x; public int y; public int width; public int height; public int bw; public int d; } public static bool XGetGeometry(IntPtr display, IntPtr window, out XGeometry geo) { geo = new XGeometry(); return XGetGeometry(display, window, out geo.root, out geo.x, out geo.y, out geo.width, out geo.height, out geo.bw, out geo.d); } public static void QueryPointer (IntPtr display, IntPtr w, out IntPtr root, out IntPtr child, out int root_x, out int root_y, out int child_x, out int child_y, out int mask) { IntPtr c; XGrabServer (display); XQueryPointer(display, w, out root, out c, out root_x, out root_y, out child_x, out child_y, out mask); if (root != w) c = root; IntPtr child_last = IntPtr.Zero; while (c != IntPtr.Zero) { child_last = c; XQueryPointer(display, c, out root, out c, out root_x, out root_y, out child_x, out child_y, out mask); } XUngrabServer (display); XFlush (display); child = child_last; } public static (int x, int y) GetCursorPos(X11Info x11, IntPtr? handle = null) { IntPtr root; IntPtr child; int root_x; int root_y; int win_x; int win_y; int keys_buttons; QueryPointer(x11.Display, handle ?? x11.RootWindow, out root, out child, out root_x, out root_y, out win_x, out win_y, out keys_buttons); if (handle != null) { return (win_x, win_y); } else { return (root_x, root_y); } } public static IntPtr CreateEventWindow(AvaloniaX11Platform plat, Action<XEvent> handler) { var win = XCreateSimpleWindow(plat.Display, plat.Info.DefaultRootWindow, 0, 0, 1, 1, 0, IntPtr.Zero, IntPtr.Zero); plat.Windows[win] = handler; return win; } } }
#region Licence /**************************************************************************** Copyright 1999-2015 Vincent J. Jacquet. All rights reserved. Permission is granted to anyone to use this software for any purpose on any computer system, and to alter it and redistribute it, subject to the following restrictions: 1. The author is not responsible for the consequences of use of this software, no matter how awful, even if they arise from flaws in it. 2. The origin of this software must not be misrepresented, either by explicit claim or by omission. Since few users ever read sources, credits must appear in the documentation. 3. Altered versions must be plainly marked as such, and must not be misrepresented as being the original software. Since few users ever read sources, credits must appear in the documentation. 4. This notice may not be removed or altered. ****************************************************************************/ #endregion using System; using System.ComponentModel; using System.Drawing; using System.Linq; using System.Windows.Forms; using System.Windows.Forms.Design; using System.Windows.Forms.VisualStyles; namespace WmcSoft.Windows.Forms { [ToolStripItemDesignerAvailability(ToolStripItemDesignerAvailability.ContextMenuStrip | ToolStripItemDesignerAvailability.MenuStrip)] [System.ComponentModel.DesignerCategory("Code")] public class ToolStripRadioButton : ToolStripMenuItem , IBindableComponent { #region Lifecycle void Initialize() { CheckOnClick = true; } public ToolStripRadioButton() : base() { Initialize(); } public ToolStripRadioButton(string text) : base(text, null, (EventHandler)null) { Initialize(); } public ToolStripRadioButton(Image image) : base(null, image, (EventHandler)null) { Initialize(); } public ToolStripRadioButton(string text, Image image) : base(text, image, (EventHandler)null) { Initialize(); } public ToolStripRadioButton(string text, Image image, EventHandler onClick) : base(text, image, onClick) { Initialize(); } public ToolStripRadioButton(string text, Image image, EventHandler onClick, string name) : base(text, image, onClick, name) { Initialize(); } public ToolStripRadioButton(string text, Image image, params ToolStripItem[] dropDownItems) : base(text, image, dropDownItems) { Initialize(); } public ToolStripRadioButton(string text, Image image, EventHandler onClick, Keys shortcutKeys) : base(text, image, onClick) { Initialize(); this.ShortcutKeys = shortcutKeys; } #endregion #region Overrides protected override void OnCheckedChanged(EventArgs e) { base.OnCheckedChanged(e); // If this item is no longer in the checked state, do nothing. if (!Checked) return; // Clear the checked state for all siblings. foreach (var item in Parent.Items.OfType<ToolStripRadioButton>()) { if (item != this && item.Checked) { item.Checked = false; // Only one item can be selected at a time, // so there is no need to continue. return; } } } protected override void OnClick(EventArgs e) { // If the item is already in the checked state, do not call // the base method, which would toggle the value. if (Checked) return; base.OnClick(e); } // Let the item paint itself, and then paint the RadioButton // where the check mark is displayed, covering the check mark // if it is present. protected override void OnPaint(PaintEventArgs e) { base.OnPaint(e); // If the client sets the Image property, the selection behavior // remains unchanged, but the RadioButton is not displayed and the // selection is indicated only by the selection rectangle. if (Image != null) return; // Determine the correct state of the RadioButton. var buttonState = RadioButtonState.UncheckedNormal; if (Enabled) { if (mouseDownState) { if (Checked) buttonState = RadioButtonState.CheckedPressed; else buttonState = RadioButtonState.UncheckedPressed; } else if (mouseHoverState) { if (Checked) buttonState = RadioButtonState.CheckedHot; else buttonState = RadioButtonState.UncheckedHot; } else { if (Checked) buttonState = RadioButtonState.CheckedNormal; } } else { if (Checked) buttonState = RadioButtonState.CheckedDisabled; else buttonState = RadioButtonState.UncheckedDisabled; } // Calculate the position at which to display the RadioButton. var glyphSize = RadioButtonRenderer.GetGlyphSize(e.Graphics, buttonState); var offset = (ContentRectangle.Height - glyphSize.Height) / 2; var imageLocation = ContentRectangle.Location; imageLocation.Offset(4, offset); // If the item is selected and the RadioButton paints with partial // transparency, such as when theming is enabled, the check mark // shows through the RadioButton image. In this case, paint a // non-transparent background first to cover the check mark. if (Checked && RadioButtonRenderer.IsBackgroundPartiallyTransparent(buttonState)) { glyphSize.Height--; glyphSize.Width--; Rectangle backgroundRectangle = new Rectangle(imageLocation, glyphSize); e.Graphics.FillEllipse(SystemBrushes.Control, backgroundRectangle); } RadioButtonRenderer.DrawRadioButton(e.Graphics, imageLocation, buttonState); } private bool mouseHoverState = false; protected override void OnMouseEnter(EventArgs e) { mouseHoverState = true; // Force the item to repaint with the new RadioButton state. Invalidate(); base.OnMouseEnter(e); } protected override void OnMouseLeave(EventArgs e) { mouseHoverState = false; base.OnMouseLeave(e); } private bool mouseDownState = false; protected override void OnMouseDown(MouseEventArgs e) { mouseDownState = true; Invalidate(); base.OnMouseDown(e); } protected override void OnMouseUp(MouseEventArgs e) { mouseDownState = false; base.OnMouseUp(e); } // Enable the item only if its parent item is in the checked state // and its Enabled property has not been explicitly set to false. public override bool Enabled { get { // Use the base value in design mode to prevent the designer // from setting the base value to the calculated value. if (!DesignMode && ownerMenuItem != null && ownerMenuItem.CheckOnClick) { return base.Enabled && ownerMenuItem.Checked; } else { return base.Enabled; } } set { base.Enabled = value; } } // When OwnerItem becomes available, if it is a ToolStripMenuItem // with a CheckOnClick property value of true, subscribe to its // CheckedChanged event. protected override void OnOwnerChanged(EventArgs e) { if (ownerMenuItem != null) { ownerMenuItem.CheckedChanged -= OwnerMenuItem_CheckedChanged; } ownerMenuItem = OwnerItem as ToolStripMenuItem; if (ownerMenuItem != null && ownerMenuItem.CheckOnClick) { ownerMenuItem.CheckedChanged += OwnerMenuItem_CheckedChanged; } base.OnOwnerChanged(e); } ToolStripMenuItem ownerMenuItem; // When the checked state of the parent item changes, // repaint the item so that the new Enabled state is displayed. private void OwnerMenuItem_CheckedChanged(object sender, EventArgs e) { Invalidate(); } #endregion #region IBindableComponent Members private BindingContext bindingContext; private ControlBindingsCollection dataBindings; [Browsable(false)] public BindingContext BindingContext { get { if (bindingContext == null) { bindingContext = new BindingContext(); } return bindingContext; } set { bindingContext = value; } } [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] public ControlBindingsCollection DataBindings { get { if (dataBindings == null) { dataBindings = new ControlBindingsCollection(this); } return dataBindings; } } #endregion } }
using System; using System.Net; using System.Net.Sockets; using System.Collections.Generic; using System.Threading; using System.IO; using System.Linq; namespace RemoteLib.Net.UDP { public class UdpRemoteClient : RemoteClient { /// <summary> /// Gets or sets a value indicating whether this instance is running. /// </summary> /// <value> /// <c>true</c> if this instance is running; otherwise, <c>false</c>. /// </value> public bool IsRunning { get; set; } /// <summary> /// Gets the UDP client. /// </summary> /// <value> /// The UDP client. /// </value> public Socket Client { get; private set; } private byte[] currentPacketRead; // We skip the header // private int currentReadIndex = 1; private byte[] currentPacketSend = new byte[0]; /// <summary> /// Initializes a new instance of the <see cref="UdpRemoteClient"/> class. /// </summary> /// <param name="endPoint">The endpoint to connect to.</param> public UdpRemoteClient(IPEndPoint endPoint) { Client = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); Client.Connect(endPoint); PacketReader = new UdpPacketReader(this); PacketWriter = new UdpPacketWriter(this); } internal void StartClient() { IsRunning = true; PacketReader.StartReadAsync(); PacketWriter.StartWriteAsync(); OnClientJoined(); } public override void WriteByte(byte i) { byte[] data = new [] { i }; currentPacketSend = currentPacketSend.Concat(data).ToArray(); } public override void WriteShort(short i) { byte[] data = IOOperations.GetShort(i); currentPacketSend = currentPacketSend.Concat(data).ToArray(); } public override void WriteInt(int i) { byte[] data = IOOperations.GetInt(i); currentPacketSend = currentPacketSend.Concat(data).ToArray(); } public override void WriteLong(long i) { byte[] data = IOOperations.GetLong(i); currentPacketSend = currentPacketSend.Concat(data).ToArray(); } public override void WriteFloat(float i) { byte[] data = IOOperations.GetFloat(i); currentPacketSend = currentPacketSend.Concat(data).ToArray(); } public override void WriteDouble(double i) { byte[] data = IOOperations.GetDouble(i); currentPacketSend = currentPacketSend.Concat(data).ToArray(); } public override void WriteString(string s) { byte[] data = IOOperations.GetString(s); currentPacketSend = currentPacketSend.Concat(data).ToArray(); } public override void WriteBoolean(bool b) { byte[] data = IOOperations.GetBoolean(b); currentPacketSend = currentPacketSend.Concat(data).ToArray(); } public override byte ReadByte() { CheckBytesLoaded(); byte read = currentPacketRead[currentReadIndex]; currentReadIndex += 1; return read; } public override short ReadShort() { CheckBytesLoaded(); short read = IOOperations.ReadShort(currentPacketRead, currentReadIndex); currentReadIndex += 2; return read; } public override int ReadInt() { CheckBytesLoaded(); int read = IOOperations.ReadInt(currentPacketRead, currentReadIndex); currentReadIndex += 4; return read; } public override long ReadLong() { CheckBytesLoaded(); long read = IOOperations.ReadLong(currentPacketRead, currentReadIndex); currentReadIndex += 8; return read; } public override float ReadFloat() { CheckBytesLoaded(); float read = IOOperations.ReadFloat(currentPacketRead, currentReadIndex); currentReadIndex += 4; return read; } public override double ReadDouble() { CheckBytesLoaded(); double read = IOOperations.ReadDouble(currentPacketRead, currentReadIndex); currentReadIndex += 8; return read; } public override string ReadString() { CheckBytesLoaded(); int len = ReadInt(); string read = IOOperations.ReadString(currentPacketRead, currentReadIndex, len); currentReadIndex += len; return read; } public override bool ReadBoolean() { CheckBytesLoaded(); bool read = IOOperations.ReadBoolean(currentPacketRead, currentReadIndex); currentReadIndex += 1; return read; } /// <summary> /// Load bytes for client. The way that udp is set up you want to read the bytes you need instead of loading them from a stream. /// </summary> /// <param name="bytes">bytes to load into</param> public void LoadPacket(byte[] bytes) { currentPacketRead = bytes; currentReadIndex = 1; } /// <summary> /// Flushes the packet for this instance. /// </summary> public void SendPacket() { // Header (1 byte) + Payload (1024 bytes) // byte[] payloadPadded = new byte[1025]; if (payloadPadded.Length < currentPacketSend.Length) { Disconnect(); throw new IOException("Max buffer size exceeded. Max size: 1025"); } Array.Copy(currentPacketSend, payloadPadded, currentPacketSend.Length); Client.Send(payloadPadded); currentPacketSend = new byte[0]; } private void CheckBytesLoaded() { if(currentPacketRead == null) throw new IOException("You must load bytes before attempting to read them. Call LoadPacket(byte[]) to read data from them."); } /// <summary> /// Disconnects this instance from any open connections. /// </summary> public override void Disconnect() { IsRunning = false; PacketWriter.StopWrite(); PacketReader.StopRead(); OnClientLeft(); } } }
#region Copyright (c) 2003, newtelligence AG. All rights reserved. /* // Copyright (c) 2003, newtelligence AG. (http://www.newtelligence.com) // Original BlogX Source Code: Copyright (c) 2003, Chris Anderson (http://simplegeek.com) // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, are permitted // provided that the following conditions are met: // // (1) Redistributions of source code must retain the above copyright notice, this list of // conditions and the following disclaimer. // (2) Redistributions in binary form must reproduce the above copyright notice, this list of // conditions and the following disclaimer in the documentation and/or other materials // provided with the distribution. // (3) Neither the name of the newtelligence AG 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. // ------------------------------------------------------------------------- // // Original BlogX source code (c) 2003 by Chris Anderson (http://simplegeek.com) // // newtelligence is a registered trademark of newtelligence Aktiengesellschaft. // // For portions of this software, the some additional copyright notices may apply // which can either be found in the license.txt file included in the source distribution // or following this notice. // */ #endregion using System; using System.Collections; using System.Diagnostics; using System.Globalization; using System.IO; using System.Xml; using System.Xml.Serialization; using newtelligence.DasBlog.Runtime.Proxies; using newtelligence.DasBlog.Util; namespace newtelligence.DasBlog.Runtime { [Serializable] [XmlRoot(Namespace=Data.NamespaceURI)] [XmlType(Namespace=Data.NamespaceURI)] public class DayEntry : IDayEntry { private object entriesLock = new object(); //the entries collection is shared and must be protected private bool Loaded { [DebuggerStepThrough()] get { return _loaded; } [DebuggerStepThrough()] set { _loaded = value; } } private bool _loaded = false; public string FileName { get { // Use Invariant Culture, not host culture (or user override), for date formats. return DateUtc.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture) + ".dayentry.xml"; } } [XmlIgnore] public DateTime DateUtc { [DebuggerStepThrough()] get { return _date; } [DebuggerStepThrough()] set { _date = value.Date; } } private DateTime _date; [XmlElement("Date")] public DateTime DateLocalTime { get { return (DateUtc==DateTime.MinValue||DateUtc==DateTime.MaxValue)?DateUtc:DateUtc.ToLocalTime(); } set { DateUtc = (value==DateTime.MinValue||value==DateTime.MaxValue)?value:value.Date.ToUniversalTime(); } } [XmlArrayItem(typeof(Entry))] public EntryCollection Entries { [DebuggerStepThrough()] get { return _entries; } [DebuggerStepThrough()] set { _entries = value; } } private EntryCollection _entries = new EntryCollection(); [XmlAnyElement] public XmlElement[] anyElements; [XmlAnyAttribute] public XmlAttribute[] anyAttributes; public void Initialize() { DateUtc = DateTime.Now.ToUniversalTime().Date; } /// <summary> /// Return EntryCollection excluding the private entries if the caller /// is not in the admin role. /// </summary> public EntryCollection GetEntries() { return GetEntries(null); } /// <summary> /// Return EntryCollection with the number of entries limited by <see paramref="maxResults" /> /// excluding the private entries if the caller is not in the admin role. /// </summary> public EntryCollection GetEntries(int maxResults) { return GetEntries(null, maxResults); } /// <summary> /// Returns the entries that meet the include delegates criteria. /// </summary> /// <param name="include">The delegate indicating which items to include.</param> public EntryCollection GetEntries(Predicate<Entry> include) { return GetEntries(include, Int32.MaxValue); } /// <summary> /// Returns the entries that meet the include delegates criteria, /// with the number of entries limited by <see paramref="maxResults" />. /// </summary> /// <param name="include">The delegate indicating which items to include.</param> public EntryCollection GetEntries(Predicate<Entry> include, int maxResults) { lock(entriesLock) { Predicate<Entry> filter = null; if(!System.Threading.Thread.CurrentPrincipal.IsInRole("admin")) { filter += EntryCollectionFilter.DefaultFilters.IsPublic(); } if(include != null) { filter += include; } return EntryCollectionFilter.FindAll(Entries, filter, maxResults); } } /// <param name="entryTitle">An URL-encoded entry title</param> public Entry GetEntryByTitle(string entryTitle) { foreach (Entry entry in this.Entries) { string compressedTitle = entry.CompressedTitle.Replace("+", ""); if (CaseInsensitiveComparer.Default.Compare(compressedTitle,entryTitle) == 0) { return entry; } } return null; } internal void Load(DataManager data) { if ( Loaded ) { return; } lock(entriesLock) { if ( Loaded ) //SDH: standard thread-safe double check { return; } string fullPath = data.ResolvePath(FileName); FileStream fileStream = FileUtils.OpenForRead(fullPath); if ( fileStream != null ) { try { XmlSerializer ser = new XmlSerializer(typeof(DayEntry),Data.NamespaceURI); using (StreamReader reader = new StreamReader(fileStream)) { //XmlNamespaceUpgradeReader upg = new XmlNamespaceUpgradeReader( reader, "", Data.NamespaceURI ); DayEntry e = (DayEntry)ser.Deserialize(reader); Entries = e.Entries; } } catch(Exception e) { ErrorTrace.Trace(System.Diagnostics.TraceLevel.Error,e); } finally { fileStream.Close(); } } Entries.Sort((left,right) => right.CreatedUtc.CompareTo(left.CreatedUtc)); Loaded = true; } } internal void Save(DataManager data) { string fullPath = data.ResolvePath(FileName); // We use the internal list to circumvent ignoring // items where IsPublic is set to false. if ( Entries.Count == 0 ) { if ( File.Exists( fullPath ) ) { File.Delete( fullPath ); } } else { System.Security.Principal.WindowsImpersonationContext wi = Impersonation.Impersonate(); FileStream fileStream = FileUtils.OpenForWrite(fullPath); if ( fileStream != null ) { try { XmlSerializer ser = new XmlSerializer(typeof(DayEntry),Data.NamespaceURI); using (StreamWriter writer = new StreamWriter(fileStream)) { ser.Serialize(writer, this); } } catch(Exception e) { ErrorTrace.Trace(System.Diagnostics.TraceLevel.Error,e); } finally { fileStream.Close(); } } wi.Undo(); } } /// <summary> /// Returns true if the specified DayEntry occurs before the day specified. /// </summary> /// <param name="dayEntry">The DayEntry to check the date of.</param> /// <param name="dateTime">The date the DayEntry should occur before</param> /// <returns>Returns true if the dayEntry occurs before the specified date.</returns> public static bool OccursBefore(DayEntry dayEntry, DateTime dateTime) { return (dayEntry.DateUtc.Date <= dateTime); } public static bool OccursBetween(DayEntry dayEntry, TimeZone timeZone, DateTime startDateTime, DateTime endDateTime) { //return ((timeZone.ToLocalTime(dayEntry.DateUtc) >= startDateTime) // && (timeZone.ToLocalTime(dayEntry.DateUtc) <= endDateTime) ); return ((dayEntry.DateUtc >= startDateTime) && (dayEntry.DateUtc <= endDateTime) ); } /// <summary> /// Returns true if the specified DayEntry is within the same month as <c>month</c>; /// </summary> /// <param name="dayEntry"></param> /// <param name="timeZone"></param> /// <param name="month"></param> /// <returns></returns> public static bool OccursInMonth(DayEntry dayEntry, TimeZone timeZone, DateTime month) { DateTime startOfMonth = new DateTime(month.Year, month.Month, 1, 0, 0, 0); DateTime endOfMonth = new DateTime(month.Year, month.Month, 1, 0, 0, 0); endOfMonth = endOfMonth.AddMonths(1); endOfMonth = endOfMonth.AddSeconds(-1); TimeSpan offset = timeZone.GetUtcOffset(endOfMonth); endOfMonth = endOfMonth.AddHours(offset.Negate().Hours); return ( OccursBetween(dayEntry, timeZone, startOfMonth, endOfMonth) ); } } }
/* * Copyright (c) 2015, InWorldz Halcyon Developers * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of halcyon nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using OpenSim.Framework; using System; using System.Collections.Generic; using System.Text; using System.Threading; namespace OpenSim.Region.Framework.Scenes { /// <summary> /// Manages transactions to groups of prims. Prenvents state from being sent to the client until the transaction /// is finished, this way the client does not see an inconsistant view of what is going on. /// BeginTransaction is safe to call multiple times from the same thread /// as it will track the usage counts on a per thread basis using the thread id. /// </summary> public class SceneTransactionManager { /// <summary> /// This stores the current usage of scene objects by thread id /// The structure can be defined as Dictionary[ThreadId, Dictionary[localId, useCount]] /// </summary> private Dictionary<int, Dictionary<uint, int>> _threadsInTransactions = new Dictionary<int, Dictionary<uint, int>>(); /// <summary> /// The graph we are tracking for /// </summary> SceneGraph _parent; /// <summary> /// Creates a new manager /// </summary> public SceneTransactionManager(SceneGraph parent) { _parent = parent; } /// <summary> /// Waits on any transaction with the given local id in it /// </summary> /// <param name="localId"></param> public void WaitOnTransaction(uint localId) { //setting this to true gets us inside the loop bool foundIdAlreadyInTransaction = false; int currentThreadId = Thread.CurrentThread.ManagedThreadId; do { lock (_threadsInTransactions) { foundIdAlreadyInTransaction = false; //look through the thread list for object ids in use foreach (KeyValuePair<int, Dictionary<uint, int>> useCountsByThread in _threadsInTransactions) { //ignore this thread if (useCountsByThread.Key == currentThreadId) { continue; } if (useCountsByThread.Value.ContainsKey(localId)) { //we found an id in our list that is already part of a transaction //we have to wait for this to clear, so wait for a pulse and continue Monitor.Wait(_threadsInTransactions); foundIdAlreadyInTransaction = true; break; //break from each thread loop } } } } while (foundIdAlreadyInTransaction); } /// <summary> /// Begins a transaction with no extra params /// </summary> /// <param name="objectIds"></param> /// <returns></returns> public SceneTransaction BeginTransaction(uint id) { return this.BeginTransaction(new uint[] {id}, null); } /// <summary> /// Begins a transaction with no extra params /// </summary> /// <param name="objectIds"></param> /// <returns></returns> public SceneTransaction BeginTransaction(IEnumerable<uint> objectIds) { return this.BeginTransaction(objectIds, null); } /// <summary> /// Starts a transaction with the given list of object ids and one extra id /// </summary> /// <param name="objectIds"></param> public SceneTransaction BeginTransaction(IEnumerable<uint> objectIds, object extraId) { //setting this to true gets us inside the loop bool foundIdAlreadyInTransaction = true; int currentThreadId = Thread.CurrentThread.ManagedThreadId; //makes the code easier to read and write by including the extra id in a set List<uint> localObjectIds = new List<uint>(objectIds); if (extraId != null) localObjectIds.Add((uint)extraId); while (foundIdAlreadyInTransaction) { foundIdAlreadyInTransaction = false; lock (_threadsInTransactions) { //look through the thread list for object ids in use foreach (KeyValuePair<int, Dictionary<uint, int>> useCountsByThread in _threadsInTransactions) { //ignore this thread if (useCountsByThread.Key == currentThreadId) { continue; } //foreach object in use per thread foreach (uint id in localObjectIds) { if (useCountsByThread.Value.ContainsKey(id)) { //we found an id in our list that is already part of a transaction //we have to wait for this to clear, so wait for a pulse and continue Monitor.Wait(_threadsInTransactions); foundIdAlreadyInTransaction = true; break; } } if (foundIdAlreadyInTransaction) break; } //this is good news, we can run our transaction. we're already holding the lock //so insert our IDs and allow the loop to exit if (!foundIdAlreadyInTransaction) { //we're going to search for the IDs in the list again this.AddIdsToBusyList(localObjectIds, currentThreadId); } } } return new SceneTransaction(localObjectIds, this); } /// <summary> /// Adds the given IDs to the list of prims already in a transaction /// we MUST be already holding a lock /// </summary> /// <param name="objectIds"></param> private void AddIdsToBusyList(IEnumerable<uint> objectIds, int currentThreadId) { Dictionary<uint, int> threadIds = null; //do we have an entry for this thread? if (!_threadsInTransactions.ContainsKey(currentThreadId)) { threadIds = new Dictionary<uint,int>(); _threadsInTransactions.Add(currentThreadId, threadIds); } else { threadIds = _threadsInTransactions[currentThreadId]; } //insert each id and/or update it's count foreach (uint id in objectIds) { if (threadIds.ContainsKey(id)) { //already has the key, update the value threadIds[id] = threadIds[id] + 1; } else { //insert new object id threadIds.Add(id, 1); this.InformPrimOfTransactionStart(id); } } } private void InformPrimOfTransactionStart(uint id) { SceneObjectPart part = _parent.GetSceneObjectPart(id); if (part != null) { part.IsInTransaction = true; } } private void InformPrimOfTransactionEnd(uint id, bool postUpdates) { SceneObjectPart part = _parent.GetSceneObjectPart(id); if (part != null) { part.IsInTransaction = false; if (!part.ParentGroup.IsDeleted && postUpdates) part.ScheduleFullUpdate(PrimUpdateFlags.ForcedFullUpdate); } } /// <summary> /// Removes the given Ids from the transaction list /// </summary> /// <param name="sceneParts"></param> public void EndTransaction(List<uint> sceneParts, SceneTransaction transaction) { lock (_threadsInTransactions) { //the thread id MUST be in the collection at this point //since the transaction had to have started in order to end Dictionary<uint, int> threadIds = _threadsInTransactions[Thread.CurrentThread.ManagedThreadId]; foreach (uint id in sceneParts) { //the id must also exist or there is a bug somewhere int useCount = threadIds[id]; if (useCount == 1) { this.InformPrimOfTransactionEnd(id, transaction.PostGroupUpdatesUponCompletion); threadIds.Remove(id); } else { threadIds[id] = useCount - 1; } } //is our thread holding any more ids? if (threadIds.Count == 0) { // if not, remove us _threadsInTransactions.Remove(Thread.CurrentThread.ManagedThreadId); } Monitor.PulseAll(_threadsInTransactions); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Speech.Synthesis; using System.Windows.Forms; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Media; using SoundScape.Levels; using XNALib.Menus; using XNALib.Scenes; using Microsoft.Xna.Framework.Audio; using GameOptions = SoundScape.GameplayScene.GameOptions; namespace SoundScape { /// <summary> /// The game loop, which inherits from MICROSOFT.XNA.FRAMEWORK.GAME, /// handles directing the user to different scenes in the game as /// well as handling the input for the menus. It also provides access /// to shared resources such as fonts, menu sounds, the sprite batch /// and some GameScenes /// </summary> public class GameLoop : Game { private SoundEffect[] _menuEffects; private SpriteBatch _spriteBatch; private SpeechSynthesizer _speechSynthesizer; private StartScene _menu; private GameScene _howToPlay; private GameScene _help; private GameScene _highScore; private GameScene _newHighScore; private GameScene _credit; private Song _menuSong; private Song _gameSong; private MenuComponent<GameOptions> _gametypeMenu; public SpriteFont DefaultGameFont { get; private set; } public SpriteFont BigFont { get; private set; } public readonly VirtualController PlayerOne; public readonly VirtualController PlayerTwo; public GameLoop(string monitor = null) { PlayerOne = new VirtualController(this); PlayerOne.JsonUpdateObject("content/PlayerOneControlls.json"); PlayerTwo = new VirtualController(this, PlayerIndex.Two); PlayerTwo.JsonUpdateObject("content/PlayerTwoControlls.json"); GraphicsDeviceManager graphics; if (monitor == null) graphics = new GraphicsDeviceManager(this); else graphics = new TargetedGraphicsDeviceManager(this, monitor); Content.RootDirectory = "Content"; graphics.PreferredBackBufferWidth = GraphicsAdapter.Adapters.Last().CurrentDisplayMode.Width; graphics.PreferredBackBufferHeight = GraphicsAdapter.Adapters.Last().CurrentDisplayMode.Height; graphics.ApplyChanges(); // The next 4 lines are apparently the only way to get borderless in xna. IntPtr hWnd = Window.Handle; var control = Control.FromHandle(hWnd); var form = control.FindForm(); form.FormBorderStyle = FormBorderStyle.None; form.Left = 200; // End of xna borderless hack ( http://gamedev.stackexchange.com/questions/37109/ ) _speechSynthesizer = new SpeechSynthesizer(); } public SpriteBatch SpriteBatch { get { return _spriteBatch; } } public HighScoreScene HighScore { get { return _highScore as HighScoreScene; } } public GameScene Gameplay { get; set; } public GameScene NewHighScore { get { return _newHighScore; } } public void Speak(string textToSpeak) { _speechSynthesizer.SpeakAsyncCancelAll(); _speechSynthesizer.SpeakAsync(textToSpeak); } private void HideAllScene() { foreach (IGameComponent gc in Components) { var gs = gc as GameScene; if (gs != null) gs.Hide(); } } public void SetTitle(string title = null) { if (String.IsNullOrWhiteSpace(title)) Window.Title = "SoundScape"; else Window.Title = string.Format("SoundScape - {0}", title.Trim()); } /// <summary> /// Allows the game to perform any initialization it needs to before starting to run. /// This is where it can query for any required services and load any non-graphic /// related content. Calling base.Initialize will enumerate through any components /// and initialize them as well. /// </summary> protected override void Initialize() { // TODO: Add your initialization logic here SetTitle(); base.Initialize(); } /// <summary> /// LoadContent will be called once per game and is the place to load /// all of your content. /// </summary> protected override void LoadContent() { // Create a new SpriteBatch, which can be used to draw textures. _spriteBatch = new SpriteBatch(GraphicsDevice); _menuEffects = new[] { Content.Load<SoundEffect>("sounds/Beep2"), Content.Load<SoundEffect>("sounds/Beep4"), }; _menuSong = Content.Load<Song>("music/dream"); _gameSong = Content.Load<Song>("music/cavedrips"); MediaPlayer.Play(_menuSong); MediaPlayer.Volume = 0.5f; MediaPlayer.IsRepeating = true; Texture2D dimensions = Content.Load<Texture2D>("images/Help"); //All images for menus should have same size Vector2 centerScreen = new Vector2(GraphicsDevice.Viewport.Width / 2 - dimensions.Width / 2, GraphicsDevice.Viewport.Height / 2 - dimensions.Height / 2); DefaultGameFont = Content.Load<SpriteFont>("fonts/regularFont"); BigFont = Content.Load<SpriteFont>("fonts/bigFont"); Texture2D backGround = Content.Load<Texture2D>("images/back/earth"); Random r = new Random(); Components.Add(_menu = new StartScene(this, _spriteBatch, new[] { "One Player Game", "Two Player Game", "How To Play", "Help", "High Score", "Credits", "Quit" }) { Background = backGround }); Components.Add(_gametypeMenu = new MenuComponent<GameOptions>(this, _spriteBatch, Color.LightYellow, Color.Yellow, DefaultGameFont, DefaultGameFont, Vector2.One * 100 + Vector2.UnitX * 400) { {"Normal Mode", GameOptions.None}, {"Spectator Mode (Score not saved)", GameOptions.SpectatorMode} }); _gametypeMenu.Hide(); Components.Add(_help = new InfoScene(this, Content.Load<Texture2D>("images/Help"), backGround, centerScreen)); Components.Add(_howToPlay = new InfoScene(this, Content.Load<Texture2D>("images/HowToPlay"), backGround, centerScreen)); Components.Add(_credit = new InfoScene(this, Content.Load<Texture2D>("images/Credits"), backGround, centerScreen)); Components.Add(_highScore = new HighScoreScene(this, Content.Load<Texture2D>("images/HighScore"), backGround, centerScreen, Toolbox.JsonLoadObject<List<HighScoreSaved>>("content/highscores.json"))); Components.Add(_newHighScore = new NewHighscoreScene(this, SpriteBatch) { Background = backGround, BannerTexture = Content.Load<Texture2D>("images/BlackBanner"), SavingTexture = Content.Load<Texture2D>("images/Saving"), }); _newHighScore.Initialize(); Campaign.New(this); _menu.Show(); Components.Add(PlayerOne); Components.Add(PlayerTwo); } /// <summary> /// UnloadContent will be called once per game and is the place to unload /// all content. /// </summary> protected override void UnloadContent() { } /// <summary> /// Allows the game to run logic such as updating the world, /// checking for collisions, gathering input, and playing audio. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Update(GameTime gameTime) { AllowExit = !_newHighScore.Enabled; MainMenuInput(); base.Update(gameTime); } /// <summary> /// Handles the user input for the menu /// </summary> void MainMenuInput() { var inputs = new[] {PlayerOne, PlayerTwo}; if (_gametypeMenu.Enabled) { GameTypeMenuInput(inputs); return; } // Allows the game to exit if (AllowExit && inputs.Any(p => p.ActionBack)) { if (MediaPlayer.Queue.ActiveSong != _menuSong) MediaPlayer.Play(_menuSong); if (_menu.Enabled) { PlayMenuSound(0); Exit(); } else { PlayMenuSound(0); HideAllScene(); SetTitle(); _menu.Show(); inputs.ForEach(p => GamePad.SetVibration(p.PlayerIndex, 0, 0)); } } if (_menu.Enabled) { if (inputs.Any(p=>p.ActionSelect)) { switch (_menu.SelectedIndex) { case 0: _gametypeMenu.Show(); break; case 1: _gametypeMenu.Show(); break; case 2: HideAllScene(); SetTitle("How To Play"); _howToPlay.Show(); break; case 3: HideAllScene(); SetTitle("Help"); _help.Show(); break; case 4: HideAllScene(); SetTitle("High Score"); HighScore.Show(); break; case 5: HideAllScene(); SetTitle("Credit"); _credit.Show(); break; case 6: Exit(); break; default: SetTitle(_menu.SelectedItem.Component == null ? string.Format("\"{0}\" cannot be opened.", _menu.SelectedItem.Name) : _menu.SelectedItem.Name); break; } PlayMenuSound(1); } if (inputs.Any(p=>p.ActionMenuDown)) { _menu.SelectedIndex = Math.Min(_menu.SelectedIndex + 1, _menu.Count - 1); PlayMenuSound(0); } else if (inputs.Any(p=>p.ActionMenuUp)) { _menu.SelectedIndex = Math.Max(_menu.SelectedIndex - 1, 0); PlayMenuSound(0); } } } private void GameTypeMenuInput(VirtualController[] inputs) { var menu = _gametypeMenu; GameOptions options = _menu.SelectedIndex == 0 ? GameOptions.None : GameOptions.Multiplayer; if (inputs.Any(c => c.ActionMenuDown)) { menu.MenuIndex++; PlayMenuSound(0); } if (inputs.Any(c => c.ActionMenuUp)) { menu.MenuIndex += 1 + menu.MenuItems.Count; PlayMenuSound(0); } if (inputs.Any(c => c.ActionBack)) { menu.Hide(); PlayMenuSound(0); } if (inputs.Any(c => c.ActionSelect)) { menu.Hide(); PlayMenuSound(1); HideAllScene(); StartGame(options | menu.ActiveMenuItem.Component); } menu.MenuIndex %= menu.MenuItems.Count; } private void StartGame(GameOptions options) { SetTitle("Game thing"); if (Gameplay != null) { Components.Remove(Gameplay); Gameplay.Dispose(); } Gameplay = Campaign.New(options: options).NextLevel(); Components.Add(Gameplay); Gameplay.Show(); MediaPlayer.Play(_gameSong); } public void PlayMenuSound(int i) { var menuSound = _menuEffects[i.Mid(_menuEffects.Length - 1)]; menuSound.Play(); } /// <summary> /// This is called when the game should draw itself. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Draw(GameTime gameTime) { GraphicsDevice.Clear(Color.Black); base.Draw(gameTime); } public bool AllowExit { get; set; } } }
// 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 gcdv = Google.Cloud.DataCatalog.V1; using sys = System; namespace Google.Cloud.DataCatalog.V1 { /// <summary>Resource name for the <c>Tag</c> resource.</summary> public sealed partial class TagName : gax::IResourceName, sys::IEquatable<TagName> { /// <summary>The possible contents of <see cref="TagName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern /// <c>projects/{project}/locations/{location}/entryGroups/{entry_group}/entries/{entry}/tags/{tag}</c>. /// </summary> ProjectLocationEntryGroupEntryTag = 1, } private static gax::PathTemplate s_projectLocationEntryGroupEntryTag = new gax::PathTemplate("projects/{project}/locations/{location}/entryGroups/{entry_group}/entries/{entry}/tags/{tag}"); /// <summary>Creates a <see cref="TagName"/> 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="TagName"/> containing the provided <paramref name="unparsedResourceName"/>. /// </returns> public static TagName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new TagName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="TagName"/> with the pattern /// <c>projects/{project}/locations/{location}/entryGroups/{entry_group}/entries/{entry}/tags/{tag}</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="entryGroupId">The <c>EntryGroup</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="entryId">The <c>Entry</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="tagId">The <c>Tag</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="TagName"/> constructed from the provided ids.</returns> public static TagName FromProjectLocationEntryGroupEntryTag(string projectId, string locationId, string entryGroupId, string entryId, string tagId) => new TagName(ResourceNameType.ProjectLocationEntryGroupEntryTag, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), entryGroupId: gax::GaxPreconditions.CheckNotNullOrEmpty(entryGroupId, nameof(entryGroupId)), entryId: gax::GaxPreconditions.CheckNotNullOrEmpty(entryId, nameof(entryId)), tagId: gax::GaxPreconditions.CheckNotNullOrEmpty(tagId, nameof(tagId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="TagName"/> with pattern /// <c>projects/{project}/locations/{location}/entryGroups/{entry_group}/entries/{entry}/tags/{tag}</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="entryGroupId">The <c>EntryGroup</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="entryId">The <c>Entry</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="tagId">The <c>Tag</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="TagName"/> with pattern /// <c>projects/{project}/locations/{location}/entryGroups/{entry_group}/entries/{entry}/tags/{tag}</c>. /// </returns> public static string Format(string projectId, string locationId, string entryGroupId, string entryId, string tagId) => FormatProjectLocationEntryGroupEntryTag(projectId, locationId, entryGroupId, entryId, tagId); /// <summary> /// Formats the IDs into the string representation of this <see cref="TagName"/> with pattern /// <c>projects/{project}/locations/{location}/entryGroups/{entry_group}/entries/{entry}/tags/{tag}</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="entryGroupId">The <c>EntryGroup</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="entryId">The <c>Entry</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="tagId">The <c>Tag</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="TagName"/> with pattern /// <c>projects/{project}/locations/{location}/entryGroups/{entry_group}/entries/{entry}/tags/{tag}</c>. /// </returns> public static string FormatProjectLocationEntryGroupEntryTag(string projectId, string locationId, string entryGroupId, string entryId, string tagId) => s_projectLocationEntryGroupEntryTag.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(entryGroupId, nameof(entryGroupId)), gax::GaxPreconditions.CheckNotNullOrEmpty(entryId, nameof(entryId)), gax::GaxPreconditions.CheckNotNullOrEmpty(tagId, nameof(tagId))); /// <summary>Parses the given resource name string into a new <see cref="TagName"/> 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}/entryGroups/{entry_group}/entries/{entry}/tags/{tag}</c> /// </description> /// </item> /// </list> /// </remarks> /// <param name="tagName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="TagName"/> if successful.</returns> public static TagName Parse(string tagName) => Parse(tagName, false); /// <summary> /// Parses the given resource name string into a new <see cref="TagName"/> 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}/entryGroups/{entry_group}/entries/{entry}/tags/{tag}</c> /// </description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="tagName">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="TagName"/> if successful.</returns> public static TagName Parse(string tagName, bool allowUnparsed) => TryParse(tagName, allowUnparsed, out TagName 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="TagName"/> 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}/entryGroups/{entry_group}/entries/{entry}/tags/{tag}</c> /// </description> /// </item> /// </list> /// </remarks> /// <param name="tagName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="TagName"/>, 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 tagName, out TagName result) => TryParse(tagName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="TagName"/> 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}/entryGroups/{entry_group}/entries/{entry}/tags/{tag}</c> /// </description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="tagName">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="TagName"/>, 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 tagName, bool allowUnparsed, out TagName result) { gax::GaxPreconditions.CheckNotNull(tagName, nameof(tagName)); gax::TemplatedResourceName resourceName; if (s_projectLocationEntryGroupEntryTag.TryParseName(tagName, out resourceName)) { result = FromProjectLocationEntryGroupEntryTag(resourceName[0], resourceName[1], resourceName[2], resourceName[3], resourceName[4]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(tagName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private TagName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string entryId = null, string entryGroupId = null, string locationId = null, string projectId = null, string tagId = null) { Type = type; UnparsedResource = unparsedResourceName; EntryId = entryId; EntryGroupId = entryGroupId; LocationId = locationId; ProjectId = projectId; TagId = tagId; } /// <summary> /// Constructs a new instance of a <see cref="TagName"/> class from the component parts of pattern /// <c>projects/{project}/locations/{location}/entryGroups/{entry_group}/entries/{entry}/tags/{tag}</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="entryGroupId">The <c>EntryGroup</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="entryId">The <c>Entry</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="tagId">The <c>Tag</c> ID. Must not be <c>null</c> or empty.</param> public TagName(string projectId, string locationId, string entryGroupId, string entryId, string tagId) : this(ResourceNameType.ProjectLocationEntryGroupEntryTag, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), entryGroupId: gax::GaxPreconditions.CheckNotNullOrEmpty(entryGroupId, nameof(entryGroupId)), entryId: gax::GaxPreconditions.CheckNotNullOrEmpty(entryId, nameof(entryId)), tagId: gax::GaxPreconditions.CheckNotNullOrEmpty(tagId, nameof(tagId))) { } /// <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>Entry</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string EntryId { get; } /// <summary> /// The <c>EntryGroup</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string EntryGroupId { 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>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string ProjectId { get; } /// <summary> /// The <c>Tag</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string TagId { 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.ProjectLocationEntryGroupEntryTag: return s_projectLocationEntryGroupEntryTag.Expand(ProjectId, LocationId, EntryGroupId, EntryId, TagId); 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 TagName); /// <inheritdoc/> public bool Equals(TagName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(TagName a, TagName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(TagName a, TagName b) => !(a == b); } /// <summary>Resource name for the <c>TagTemplate</c> resource.</summary> public sealed partial class TagTemplateName : gax::IResourceName, sys::IEquatable<TagTemplateName> { /// <summary>The possible contents of <see cref="TagTemplateName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern <c>projects/{project}/locations/{location}/tagTemplates/{tag_template}</c>. /// </summary> ProjectLocationTagTemplate = 1, } private static gax::PathTemplate s_projectLocationTagTemplate = new gax::PathTemplate("projects/{project}/locations/{location}/tagTemplates/{tag_template}"); /// <summary>Creates a <see cref="TagTemplateName"/> 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="TagTemplateName"/> containing the provided /// <paramref name="unparsedResourceName"/>. /// </returns> public static TagTemplateName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new TagTemplateName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="TagTemplateName"/> with the pattern /// <c>projects/{project}/locations/{location}/tagTemplates/{tag_template}</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="tagTemplateId">The <c>TagTemplate</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="TagTemplateName"/> constructed from the provided ids.</returns> public static TagTemplateName FromProjectLocationTagTemplate(string projectId, string locationId, string tagTemplateId) => new TagTemplateName(ResourceNameType.ProjectLocationTagTemplate, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), tagTemplateId: gax::GaxPreconditions.CheckNotNullOrEmpty(tagTemplateId, nameof(tagTemplateId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="TagTemplateName"/> with pattern /// <c>projects/{project}/locations/{location}/tagTemplates/{tag_template}</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="tagTemplateId">The <c>TagTemplate</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="TagTemplateName"/> with pattern /// <c>projects/{project}/locations/{location}/tagTemplates/{tag_template}</c>. /// </returns> public static string Format(string projectId, string locationId, string tagTemplateId) => FormatProjectLocationTagTemplate(projectId, locationId, tagTemplateId); /// <summary> /// Formats the IDs into the string representation of this <see cref="TagTemplateName"/> with pattern /// <c>projects/{project}/locations/{location}/tagTemplates/{tag_template}</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="tagTemplateId">The <c>TagTemplate</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="TagTemplateName"/> with pattern /// <c>projects/{project}/locations/{location}/tagTemplates/{tag_template}</c>. /// </returns> public static string FormatProjectLocationTagTemplate(string projectId, string locationId, string tagTemplateId) => s_projectLocationTagTemplate.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(tagTemplateId, nameof(tagTemplateId))); /// <summary>Parses the given resource name string into a new <see cref="TagTemplateName"/> 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}/tagTemplates/{tag_template}</c></description> /// </item> /// </list> /// </remarks> /// <param name="tagTemplateName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="TagTemplateName"/> if successful.</returns> public static TagTemplateName Parse(string tagTemplateName) => Parse(tagTemplateName, false); /// <summary> /// Parses the given resource name string into a new <see cref="TagTemplateName"/> 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}/tagTemplates/{tag_template}</c></description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="tagTemplateName">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="TagTemplateName"/> if successful.</returns> public static TagTemplateName Parse(string tagTemplateName, bool allowUnparsed) => TryParse(tagTemplateName, allowUnparsed, out TagTemplateName 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="TagTemplateName"/> 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}/tagTemplates/{tag_template}</c></description> /// </item> /// </list> /// </remarks> /// <param name="tagTemplateName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="TagTemplateName"/>, 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 tagTemplateName, out TagTemplateName result) => TryParse(tagTemplateName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="TagTemplateName"/> 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}/tagTemplates/{tag_template}</c></description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="tagTemplateName">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="TagTemplateName"/>, 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 tagTemplateName, bool allowUnparsed, out TagTemplateName result) { gax::GaxPreconditions.CheckNotNull(tagTemplateName, nameof(tagTemplateName)); gax::TemplatedResourceName resourceName; if (s_projectLocationTagTemplate.TryParseName(tagTemplateName, out resourceName)) { result = FromProjectLocationTagTemplate(resourceName[0], resourceName[1], resourceName[2]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(tagTemplateName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private TagTemplateName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string locationId = null, string projectId = null, string tagTemplateId = null) { Type = type; UnparsedResource = unparsedResourceName; LocationId = locationId; ProjectId = projectId; TagTemplateId = tagTemplateId; } /// <summary> /// Constructs a new instance of a <see cref="TagTemplateName"/> class from the component parts of pattern /// <c>projects/{project}/locations/{location}/tagTemplates/{tag_template}</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="tagTemplateId">The <c>TagTemplate</c> ID. Must not be <c>null</c> or empty.</param> public TagTemplateName(string projectId, string locationId, string tagTemplateId) : this(ResourceNameType.ProjectLocationTagTemplate, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), tagTemplateId: gax::GaxPreconditions.CheckNotNullOrEmpty(tagTemplateId, nameof(tagTemplateId))) { } /// <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>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>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string ProjectId { get; } /// <summary> /// The <c>TagTemplate</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string TagTemplateId { 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.ProjectLocationTagTemplate: return s_projectLocationTagTemplate.Expand(ProjectId, LocationId, TagTemplateId); 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 TagTemplateName); /// <inheritdoc/> public bool Equals(TagTemplateName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(TagTemplateName a, TagTemplateName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(TagTemplateName a, TagTemplateName b) => !(a == b); } /// <summary>Resource name for the <c>TagTemplateField</c> resource.</summary> public sealed partial class TagTemplateFieldName : gax::IResourceName, sys::IEquatable<TagTemplateFieldName> { /// <summary>The possible contents of <see cref="TagTemplateFieldName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern /// <c>projects/{project}/locations/{location}/tagTemplates/{tag_template}/fields/{field}</c>. /// </summary> ProjectLocationTagTemplateField = 1, } private static gax::PathTemplate s_projectLocationTagTemplateField = new gax::PathTemplate("projects/{project}/locations/{location}/tagTemplates/{tag_template}/fields/{field}"); /// <summary>Creates a <see cref="TagTemplateFieldName"/> 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="TagTemplateFieldName"/> containing the provided /// <paramref name="unparsedResourceName"/>. /// </returns> public static TagTemplateFieldName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new TagTemplateFieldName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="TagTemplateFieldName"/> with the pattern /// <c>projects/{project}/locations/{location}/tagTemplates/{tag_template}/fields/{field}</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="tagTemplateId">The <c>TagTemplate</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="fieldId">The <c>Field</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="TagTemplateFieldName"/> constructed from the provided ids.</returns> public static TagTemplateFieldName FromProjectLocationTagTemplateField(string projectId, string locationId, string tagTemplateId, string fieldId) => new TagTemplateFieldName(ResourceNameType.ProjectLocationTagTemplateField, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), tagTemplateId: gax::GaxPreconditions.CheckNotNullOrEmpty(tagTemplateId, nameof(tagTemplateId)), fieldId: gax::GaxPreconditions.CheckNotNullOrEmpty(fieldId, nameof(fieldId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="TagTemplateFieldName"/> with pattern /// <c>projects/{project}/locations/{location}/tagTemplates/{tag_template}/fields/{field}</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="tagTemplateId">The <c>TagTemplate</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="fieldId">The <c>Field</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="TagTemplateFieldName"/> with pattern /// <c>projects/{project}/locations/{location}/tagTemplates/{tag_template}/fields/{field}</c>. /// </returns> public static string Format(string projectId, string locationId, string tagTemplateId, string fieldId) => FormatProjectLocationTagTemplateField(projectId, locationId, tagTemplateId, fieldId); /// <summary> /// Formats the IDs into the string representation of this <see cref="TagTemplateFieldName"/> with pattern /// <c>projects/{project}/locations/{location}/tagTemplates/{tag_template}/fields/{field}</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="tagTemplateId">The <c>TagTemplate</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="fieldId">The <c>Field</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="TagTemplateFieldName"/> with pattern /// <c>projects/{project}/locations/{location}/tagTemplates/{tag_template}/fields/{field}</c>. /// </returns> public static string FormatProjectLocationTagTemplateField(string projectId, string locationId, string tagTemplateId, string fieldId) => s_projectLocationTagTemplateField.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(tagTemplateId, nameof(tagTemplateId)), gax::GaxPreconditions.CheckNotNullOrEmpty(fieldId, nameof(fieldId))); /// <summary> /// Parses the given resource name string into a new <see cref="TagTemplateFieldName"/> 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}/tagTemplates/{tag_template}/fields/{field}</c> /// </description> /// </item> /// </list> /// </remarks> /// <param name="tagTemplateFieldName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="TagTemplateFieldName"/> if successful.</returns> public static TagTemplateFieldName Parse(string tagTemplateFieldName) => Parse(tagTemplateFieldName, false); /// <summary> /// Parses the given resource name string into a new <see cref="TagTemplateFieldName"/> 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}/tagTemplates/{tag_template}/fields/{field}</c> /// </description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="tagTemplateFieldName">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="TagTemplateFieldName"/> if successful.</returns> public static TagTemplateFieldName Parse(string tagTemplateFieldName, bool allowUnparsed) => TryParse(tagTemplateFieldName, allowUnparsed, out TagTemplateFieldName 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="TagTemplateFieldName"/> 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}/tagTemplates/{tag_template}/fields/{field}</c> /// </description> /// </item> /// </list> /// </remarks> /// <param name="tagTemplateFieldName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="TagTemplateFieldName"/>, 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 tagTemplateFieldName, out TagTemplateFieldName result) => TryParse(tagTemplateFieldName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="TagTemplateFieldName"/> 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}/tagTemplates/{tag_template}/fields/{field}</c> /// </description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="tagTemplateFieldName">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="TagTemplateFieldName"/>, 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 tagTemplateFieldName, bool allowUnparsed, out TagTemplateFieldName result) { gax::GaxPreconditions.CheckNotNull(tagTemplateFieldName, nameof(tagTemplateFieldName)); gax::TemplatedResourceName resourceName; if (s_projectLocationTagTemplateField.TryParseName(tagTemplateFieldName, out resourceName)) { result = FromProjectLocationTagTemplateField(resourceName[0], resourceName[1], resourceName[2], resourceName[3]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(tagTemplateFieldName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private TagTemplateFieldName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string fieldId = null, string locationId = null, string projectId = null, string tagTemplateId = null) { Type = type; UnparsedResource = unparsedResourceName; FieldId = fieldId; LocationId = locationId; ProjectId = projectId; TagTemplateId = tagTemplateId; } /// <summary> /// Constructs a new instance of a <see cref="TagTemplateFieldName"/> class from the component parts of pattern /// <c>projects/{project}/locations/{location}/tagTemplates/{tag_template}/fields/{field}</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="tagTemplateId">The <c>TagTemplate</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="fieldId">The <c>Field</c> ID. Must not be <c>null</c> or empty.</param> public TagTemplateFieldName(string projectId, string locationId, string tagTemplateId, string fieldId) : this(ResourceNameType.ProjectLocationTagTemplateField, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), tagTemplateId: gax::GaxPreconditions.CheckNotNullOrEmpty(tagTemplateId, nameof(tagTemplateId)), fieldId: gax::GaxPreconditions.CheckNotNullOrEmpty(fieldId, nameof(fieldId))) { } /// <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>Field</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string FieldId { 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>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string ProjectId { get; } /// <summary> /// The <c>TagTemplate</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string TagTemplateId { 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.ProjectLocationTagTemplateField: return s_projectLocationTagTemplateField.Expand(ProjectId, LocationId, TagTemplateId, FieldId); 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 TagTemplateFieldName); /// <inheritdoc/> public bool Equals(TagTemplateFieldName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(TagTemplateFieldName a, TagTemplateFieldName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(TagTemplateFieldName a, TagTemplateFieldName b) => !(a == b); } public partial class Tag { /// <summary> /// <see cref="gcdv::TagName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcdv::TagName TagName { get => string.IsNullOrEmpty(Name) ? null : gcdv::TagName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class TagTemplate { /// <summary> /// <see cref="gcdv::TagTemplateName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcdv::TagTemplateName TagTemplateName { get => string.IsNullOrEmpty(Name) ? null : gcdv::TagTemplateName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class TagTemplateField { /// <summary> /// <see cref="gcdv::TagTemplateFieldName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcdv::TagTemplateFieldName TagTemplateFieldName { get => string.IsNullOrEmpty(Name) ? null : gcdv::TagTemplateFieldName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 1.2.2.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.DataLake.Analytics { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Azure.Management.DataLake; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// ComputePoliciesOperations operations. /// </summary> internal partial class ComputePoliciesOperations : IServiceOperations<DataLakeAnalyticsAccountManagementClient>, IComputePoliciesOperations { /// <summary> /// Initializes a new instance of the ComputePoliciesOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal ComputePoliciesOperations(DataLakeAnalyticsAccountManagementClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the DataLakeAnalyticsAccountManagementClient /// </summary> public DataLakeAnalyticsAccountManagementClient Client { get; private set; } /// <summary> /// Creates or updates the specified compute policy. During update, the compute /// policy with the specified name will be replaced with this new compute /// policy. An account supports, at most, 50 policies /// </summary> /// <param name='resourceGroupName'> /// The name of the Azure resource group that contains the Data Lake Analytics /// account. /// </param> /// <param name='accountName'> /// The name of the Data Lake Analytics account to add or replace the compute /// policy. /// </param> /// <param name='computePolicyName'> /// The name of the compute policy to create or update. /// </param> /// <param name='parameters'> /// Parameters supplied to create or update the compute policy. The max degree /// of parallelism per job property, min priority per job property, or both /// must be present. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<ComputePolicy>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string accountName, string computePolicyName, ComputePolicyCreateOrUpdateParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (accountName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "accountName"); } if (computePolicyName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "computePolicyName"); } if (parameters == null) { throw new ValidationException(ValidationRules.CannotBeNull, "parameters"); } if (parameters != null) { parameters.Validate(); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("accountName", accountName); tracingParameters.Add("computePolicyName", computePolicyName); tracingParameters.Add("parameters", parameters); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "CreateOrUpdate", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataLakeAnalytics/accounts/{accountName}/computePolicies/{computePolicyName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{accountName}", System.Uri.EscapeDataString(accountName)); _url = _url.Replace("{computePolicyName}", System.Uri.EscapeDataString(computePolicyName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(parameters != null) { _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<ComputePolicy>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<ComputePolicy>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Updates the specified compute policy. /// </summary> /// <param name='resourceGroupName'> /// The name of the Azure resource group that contains the Data Lake Analytics /// account. /// </param> /// <param name='accountName'> /// The name of the Data Lake Analytics account to which to update the compute /// policy. /// </param> /// <param name='computePolicyName'> /// The name of the compute policy to update. /// </param> /// <param name='parameters'> /// Parameters supplied to update the compute policy. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<ComputePolicy>> UpdateWithHttpMessagesAsync(string resourceGroupName, string accountName, string computePolicyName, ComputePolicy parameters = default(ComputePolicy), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (accountName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "accountName"); } if (computePolicyName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "computePolicyName"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("accountName", accountName); tracingParameters.Add("computePolicyName", computePolicyName); tracingParameters.Add("parameters", parameters); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Update", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataLakeAnalytics/accounts/{accountName}/computePolicies/{computePolicyName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{accountName}", System.Uri.EscapeDataString(accountName)); _url = _url.Replace("{computePolicyName}", System.Uri.EscapeDataString(computePolicyName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PATCH"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(parameters != null) { _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<ComputePolicy>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<ComputePolicy>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Deletes the specified compute policy from the specified Data Lake Analytics /// account /// </summary> /// <param name='resourceGroupName'> /// The name of the Azure resource group that contains the Data Lake Analytics /// account. /// </param> /// <param name='accountName'> /// The name of the Data Lake Analytics account from which to delete the /// compute policy. /// </param> /// <param name='computePolicyName'> /// The name of the compute policy to delete. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string accountName, string computePolicyName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (accountName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "accountName"); } if (computePolicyName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "computePolicyName"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("accountName", accountName); tracingParameters.Add("computePolicyName", computePolicyName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Delete", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataLakeAnalytics/accounts/{accountName}/computePolicies/{computePolicyName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{accountName}", System.Uri.EscapeDataString(accountName)); _url = _url.Replace("{computePolicyName}", System.Uri.EscapeDataString(computePolicyName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("DELETE"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200 && (int)_statusCode != 204) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets the specified Data Lake Analytics compute policy. /// </summary> /// <param name='resourceGroupName'> /// The name of the Azure resource group that contains the Data Lake Analytics /// account. /// </param> /// <param name='accountName'> /// The name of the Data Lake Analytics account from which to get the compute /// policy. /// </param> /// <param name='computePolicyName'> /// The name of the compute policy to retrieve. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<ComputePolicy>> GetWithHttpMessagesAsync(string resourceGroupName, string accountName, string computePolicyName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (accountName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "accountName"); } if (computePolicyName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "computePolicyName"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("accountName", accountName); tracingParameters.Add("computePolicyName", computePolicyName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataLakeAnalytics/accounts/{accountName}/computePolicies/{computePolicyName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{accountName}", System.Uri.EscapeDataString(accountName)); _url = _url.Replace("{computePolicyName}", System.Uri.EscapeDataString(computePolicyName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<ComputePolicy>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<ComputePolicy>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Lists the Data Lake Analytics compute policies within the specified Data /// Lake Analytics account. An account supports, at most, 50 policies /// </summary> /// <param name='resourceGroupName'> /// The name of the Azure resource group that contains the Data Lake Analytics /// account. /// </param> /// <param name='accountName'> /// The name of the Data Lake Analytics account from which to get the compute /// policies. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<ComputePolicy>>> ListByAccountWithHttpMessagesAsync(string resourceGroupName, string accountName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (accountName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "accountName"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("accountName", accountName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListByAccount", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataLakeAnalytics/accounts/{accountName}/computePolicies").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{accountName}", System.Uri.EscapeDataString(accountName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<ComputePolicy>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<ComputePolicy>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Lists the Data Lake Analytics compute policies within the specified Data /// Lake Analytics account. An account supports, at most, 50 policies /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<ComputePolicy>>> ListByAccountNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListByAccountNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<ComputePolicy>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<ComputePolicy>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
using System; using System.Collections.Generic; using System.Text; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Graphics; using FlatRedBall; using FlatRedBall.Math; using FlatRedBall.Math.Geometry; using FlatRedBall.Graphics; namespace FlatRedBall.Input { public delegate void ModifyMouseState(ref MouseState mouseState); public class Mouse : IEquatable<Mouse>, IInputDevice { #region Enums public enum MouseButtons { LeftButton = 0, RightButton = 1, MiddleButton = 2, XButton1 = 3, XButton2 = 4 // Once extra buttons are added, modify the NumberOfButtons const below } #endregion #region Fields #region Static and Const Fields public const int NumberOfButtons = (int)MouseButtons.XButton2 + 1; public const float MaximumSecondsBetweenClickForDoubleClick = .25f; #endregion MouseState mMouseState; MouseState mLastFrameMouseState = new MouseState(); Dictionary<MouseButtons, DelegateBasedPressableInput> mButtons = new Dictionary<MouseButtons, DelegateBasedPressableInput>(); int mThisFrameRepositionX; int mThisFrameRepositionY; int mLastFrameRepositionX; int mLastFrameRepositionY; float mXVelocity; float mYVelocity; //bool mClearUntilNextClick = false; double[] mLastClickTime; double[] mLastPushTime; bool[] mDoubleClick; bool[] mDoublePush; bool mWindowsCursorVisible = true; #region XML docs /// <summary> /// The camera-relative X coordinate position of the Mouse at 100 units away. /// </summary> #endregion float mXAt100Units; float mYAt100Units; // Why do we have this instead of just relying on the last state? int mLastWheel; PositionedObject mGrabbedPositionedObject; float mGrabbedPositionedObjectRelativeX; float mGrabbedPositionedObjectRelativeY; bool mActive = true; bool mWasJustCleared = false; #endregion #region Properties public bool AnyButtonPushed() { bool valueToReturn = false; for (int i = 0; i < NumberOfButtons; i++) { valueToReturn |= ButtonPushed((MouseButtons)i); } return valueToReturn; } public MouseState MouseState => mMouseState; public bool Active { get { return mActive; } set { mActive = value; } } #region XML Docs /// <summary> /// Grabs a PositionedObject. The PositionedObject will automatically update /// its position according to mouse movement while the reference remains. /// </summary> #endregion public PositionedObject GrabbedPositionedObject { get { return mGrabbedPositionedObject; } set { if (value != null) { mGrabbedPositionedObjectRelativeX = value.X - WorldXAt(value.Z); mGrabbedPositionedObjectRelativeY = value.Y - WorldYAt(value.Z); } mGrabbedPositionedObject = value; } } DelegateBased1DInput scrollWheel; public I1DInput ScrollWheel { get { if(scrollWheel == null) { scrollWheel = new DelegateBased1DInput( () => mMouseState.ScrollWheelValue / 120.0f, () => ScrollWheelChange ); } return scrollWheel; } } public float ScrollWheelChange { get { #if MONODROID return InputManager.TouchScreen.PinchRatioChange; #else return (mMouseState.ScrollWheelValue - mLastWheel)/120.0f; #endif } } #if !MONOGAME public bool IsOwnerFocused { get { //bool value = false; System.Windows.Forms.Control control = FlatRedBallServices.Owner; bool returnValue = false; while (true) { if (control == null) { returnValue = false; break; } else if (control.Focused) { returnValue = true; break; } control = control.Parent; } return returnValue; } } #endif #region XML Docs /// <summary> /// Returns the client rectangle-relative X pixel coordinate of the cursor. /// </summary> #endregion public int X { get { #if FRB_MDX return mOwner.PointToClient( System.Windows.Forms.Cursor.Position ).X; #elif XBOX360 return 0; #else return mMouseState.X; #endif } } #region XML Docs /// <summary> /// Returns the client rectangle-Y pixel coordinate of the cursor. /// </summary> #endregion public int Y { get { #if FRB_MDX return mOwner.PointToClient( System.Windows.Forms.Cursor.Position ).Y; #elif XBOX360 return 0; #else return mMouseState.Y; #endif } } #region XML Docs /// <summary> /// The number of pixels that the mouse has moved on the /// X axis during the last frame. /// </summary> #endregion public int XChange { get { #if FRB_MDX return mMouseState.X; #else return mMouseState.X - mLastFrameMouseState.X + mLastFrameRepositionX; #endif } } #region XML Docs /// <summary> /// The number of pixels that the mouse has moved on the /// Y axis during the last frame. /// </summary> #endregion public int YChange { get { #if FRB_MDX return mMouseState.Y; #else return mMouseState.Y - mLastFrameMouseState.Y + mLastFrameRepositionY; #endif } } #region XML Docs /// <summary> /// The rate of change of the X property in /// pixels per second. /// </summary> #endregion public float XVelocity { get { return mXVelocity; } } #region XML Docs /// <summary> /// The rate of change of the Y property in /// pixels per second. /// </summary> #endregion public float YVelocity { get { return mYVelocity; } } I2DInput IInputDevice.Default2DInput => Zero2DInput.Instance; IPressableInput IInputDevice.DefaultUpPressable => FalsePressableInput.Instance; IPressableInput IInputDevice.DefaultDownPressable => FalsePressableInput.Instance; IPressableInput IInputDevice.DefaultLeftPressable => FalsePressableInput.Instance; IPressableInput IInputDevice.DefaultRightPressable => FalsePressableInput.Instance; I1DInput IInputDevice.DefaultHorizontalInput => Zero1DInput.Instance; I1DInput IInputDevice.DefaultVerticalInput => Zero1DInput.Instance; IPressableInput IInputDevice.DefaultPrimaryActionInput => FalsePressableInput.Instance; IPressableInput IInputDevice.DefaultSecondaryActionInput => FalsePressableInput.Instance; IPressableInput IInputDevice.DefaultConfirmInput => FalsePressableInput.Instance; IPressableInput IInputDevice.DefaultJoinInput => FalsePressableInput.Instance; IPressableInput IInputDevice.DefaultPauseInput => FalsePressableInput.Instance; IPressableInput IInputDevice.DefaultBackInput => FalsePressableInput.Instance; #endregion #region Events public static event ModifyMouseState ModifyMouseState; #endregion #region Methods #region Constructor/Initialize #if FRB_MDX internal Mouse(System.Windows.Forms.Control owner, bool useWindowsCursor) { // This is needed to hide and show the Windows cursor mOwner = owner; mLastClickTime = new double[NumberOfButtons]; mLastPushTime = new double[NumberOfButtons]; mDoubleClick = new bool[NumberOfButtons]; mDoublePush = new bool[NumberOfButtons]; mMouseButtonClicked = new bool[NumberOfButtons]; mMouseButtonPushed = new bool[NumberOfButtons]; mMouseOffset = new MouseOffset[NumberOfButtons]; mMouseOffset[(int)MouseButtons.LeftButton] = MouseOffset.Button0; mMouseOffset[(int)MouseButtons.RightButton] = MouseOffset.Button1; mMouseOffset[(int)MouseButtons.MiddleButton] = MouseOffset.Button2; mMouseOffset[(int)MouseButtons.XButton1] = MouseOffset.Button3; mMouseOffset[(int)MouseButtons.XButton2] = MouseOffset.Button4; mMouseDevice = new Device(SystemGuid.Mouse); mMouseDevice.SetDataFormat(DeviceDataFormat.Mouse); if (useWindowsCursor) { mWindowsCursorVisible = true; mMouseDevice.SetCooperativeLevel(owner, CooperativeLevelFlags.Foreground | CooperativeLevelFlags.NonExclusive); } else { mWindowsCursorVisible = false; mMouseDevice.SetCooperativeLevel(owner, CooperativeLevelFlags.Foreground | CooperativeLevelFlags.Exclusive); } try { mMouseDevice.Acquire(); } catch (InputLostException) { // return; } catch (OtherApplicationHasPriorityException) { // return; } catch (System.ArgumentException) { } // i don't know why this doesn't work, but input still works without it. mMouseDevice.Properties.BufferSize = 5; } #else internal Mouse(IntPtr windowHandle) { #if SILVERLIGHT //SilverArcade.SilverSprite.Input.Mouse.WindowHandle = windowHandle; mLastFrameMouseState = new MouseState(); mMouseState = new MouseState(); Microsoft.Xna.Framework.Input.Mouse.CreatesNewState = false; #elif !MONOGAME Microsoft.Xna.Framework.Input.Mouse.WindowHandle = windowHandle; #endif mLastClickTime = new double[NumberOfButtons]; mLastPushTime = new double[NumberOfButtons]; mDoubleClick = new bool[NumberOfButtons]; mDoublePush = new bool[NumberOfButtons]; } #endif internal void Initialize() { } #endregion #region Public Methods public IPressableInput GetButton(MouseButtons button) { if(mButtons.ContainsKey(button) == false) { mButtons[button] = new DelegateBasedPressableInput( () => this.ButtonDown(button), () => this.ButtonPushed(button), () => this.ButtonReleased(button) ); } return mButtons[button]; } #region Button state methods (pushed, down, released, double clicked) public bool ButtonPushed(MouseButtons button) { #if !XBOX360 //Removed checking for focus to keep consistent with the other mouse events. //Checking should now be done manually // bool isOwnerFocused = true; //#if !WINDOWS_PHONE && !SILVERLIGHT && !MONODROID // isOwnerFocused = IsOwnerFocused; //#endif if (mActive == false || InputManager.mIgnorePushesThisFrame) // || !isOwnerFocused) return false; #if FRB_MDX if (mMouseBufferedData != null) { foreach (Microsoft.DirectX.DirectInput.BufferedData d in mMouseBufferedData) { if (d.Offset == (int)mMouseOffset[(int)button]) { if ((d.Data & 0x80) != 0) { return true; } } } } return false; #else switch (button) { case MouseButtons.LeftButton: return !InputManager.CurrentFrameInputSuspended && mMouseState.LeftButton == ButtonState.Pressed && mLastFrameMouseState.LeftButton == ButtonState.Released; case MouseButtons.RightButton: return !InputManager.CurrentFrameInputSuspended && mMouseState.RightButton == ButtonState.Pressed && mLastFrameMouseState.RightButton == ButtonState.Released; #if !SILVERLIGHT case MouseButtons.MiddleButton: return !InputManager.CurrentFrameInputSuspended && mMouseState.MiddleButton == ButtonState.Pressed && mLastFrameMouseState.MiddleButton == ButtonState.Released; case MouseButtons.XButton1: return !InputManager.CurrentFrameInputSuspended && mMouseState.XButton1 == ButtonState.Pressed && mLastFrameMouseState.XButton1 == ButtonState.Released; case MouseButtons.XButton2: return !InputManager.CurrentFrameInputSuspended && mMouseState.XButton2 == ButtonState.Pressed && mLastFrameMouseState.XButton2 == ButtonState.Released; #endif default: return false; } #endif #else return false; #endif } public bool ButtonReleased(MouseButtons button) { bool isMouseStateNull = false; if (mActive == false || isMouseStateNull) return false; switch (button) { case MouseButtons.LeftButton: return !InputManager.CurrentFrameInputSuspended && mMouseState.LeftButton == ButtonState.Released && mLastFrameMouseState.LeftButton == ButtonState.Pressed; case MouseButtons.RightButton: return !InputManager.CurrentFrameInputSuspended && mMouseState.RightButton == ButtonState.Released && mLastFrameMouseState.RightButton == ButtonState.Pressed; case MouseButtons.MiddleButton: return !InputManager.CurrentFrameInputSuspended && mMouseState.MiddleButton == ButtonState.Released && mLastFrameMouseState.MiddleButton == ButtonState.Pressed; case MouseButtons.XButton1: return !InputManager.CurrentFrameInputSuspended && mMouseState.XButton1 == ButtonState.Released && mLastFrameMouseState.XButton1 == ButtonState.Pressed; case MouseButtons.XButton2: return !InputManager.CurrentFrameInputSuspended && mMouseState.XButton2 == ButtonState.Released && mLastFrameMouseState.XButton2 == ButtonState.Pressed; default: return false; } } public bool ButtonDown(MouseButtons button) { if (mActive == false) return false; switch (button) { case MouseButtons.LeftButton: return !InputManager.CurrentFrameInputSuspended && mMouseState.LeftButton == ButtonState.Pressed; case MouseButtons.RightButton: return !InputManager.CurrentFrameInputSuspended && mMouseState.RightButton == ButtonState.Pressed; case MouseButtons.MiddleButton: return !InputManager.CurrentFrameInputSuspended && mMouseState.MiddleButton == ButtonState.Pressed; case MouseButtons.XButton1: return !InputManager.CurrentFrameInputSuspended && mMouseState.XButton1 == ButtonState.Pressed; case MouseButtons.XButton2: return !InputManager.CurrentFrameInputSuspended && mMouseState.XButton2 == ButtonState.Pressed; default: return false; } } #if !XBOX360 public bool ButtonDoubleClicked(MouseButtons button) { return mActive && !InputManager.CurrentFrameInputSuspended && mDoubleClick[(int)button]; } public bool ButtonDoublePushed(MouseButtons button) { return mActive && !InputManager.CurrentFrameInputSuspended && mDoublePush[(int)button]; } #endif #endregion public void Clear() { mWasJustCleared = true; mMouseState = new MouseState(); mLastFrameMouseState = new MouseState(); mLastWheel = 0; } Vector3 mDefaultUpVector = new Vector3(0, 1, 0); public void ControlPositionedObjectOrbit(PositionedObject positionedObject, Vector3 orbitCenter, bool requireMiddleMouse) { ControlPositionedObjectOrbit(positionedObject, orbitCenter, requireMiddleMouse, mDefaultUpVector); } public void ControlPositionedObjectOrbit(PositionedObject positionedObject, Vector3 orbitCenter, bool requireMiddleMouse, Vector3 upVector) { const float coefficient = .00016f; if (!requireMiddleMouse || this.ButtonDown(MouseButtons.MiddleButton)) { if (XVelocity != 0) { float angleToRotateBy = -coefficient * XVelocity; Matrix rotationMatrix = Matrix.CreateFromAxisAngle(upVector, angleToRotateBy); positionedObject.Position -= orbitCenter; MathFunctions.TransformVector(ref positionedObject.Position, ref rotationMatrix); positionedObject.Position += orbitCenter; //float x = positionedObject.X; //float z = positionedObject.Z; //FlatRedBall.Math.MathFunctions.RotatePointAroundPoint( // orbitCenter.X, orbitCenter.Z, ref x, ref z, angleToRotateBy); //positionedObject.X = x; //positionedObject.Z = z; } if (YVelocity != 0) { Vector3 relativePosition = positionedObject.Position - orbitCenter; Matrix transformation = Matrix.CreateFromAxisAngle( positionedObject.RotationMatrix.Right, coefficient * -YVelocity); FlatRedBall.Math.MathFunctions.TransformVector( ref relativePosition, ref transformation); positionedObject.Position = relativePosition + orbitCenter; } } #if FRB_MDX Vector3 forward = Vector3.Normalize(orbitCenter - positionedObject.Position); Matrix matrix = positionedObject.RotationMatrix; matrix.M31 = forward.X; matrix.M32 = forward.Y; matrix.M33 = forward.Z; Vector3 right = Vector3.Normalize(Vector3.Cross(upVector, forward)); matrix.M11 = right.X; matrix.M12 = right.Y; matrix.M13 = right.Z; Vector3 up = Vector3.Normalize(Vector3.Cross(forward, right)); matrix.M21 = up.X; matrix.M22 = up.Y; matrix.M23 = up.Z; positionedObject.UpdateRotationValuesAccordingToMatrix(matrix); // to fix accumulation and weird math issues: positionedObject.RotationZ = positionedObject.RotationZ; #else Vector3 relativePositionForView = orbitCenter - positionedObject.Position; // Vic says: Why do we invert? Well, because the CreateLookAt matrix method creates // a matrix by which you multiply everything in the world to simulate the camera looking // at an object. But we don't want to rotate the world to look like the camera is looking // at a point - instead we want to rotate the camera so that it actually is looking at the point. // FlatRedBall will take care of the actual inverting when it goes to draw the world. positionedObject.RotationMatrix = Matrix.Invert(Matrix.CreateLookAt(new Vector3(), relativePositionForView, upVector)); #endif #if !SILVERLIGHT if (this.ScrollWheelChange != 0) { float scrollCoefficient = (positionedObject.Position - orbitCenter).Length() * .125f; #if FRB_MDX positionedObject.Position += scrollCoefficient * this.ScrollWheelChange * positionedObject.RotationMatrix.Forward(); #else positionedObject.Position += scrollCoefficient * this.ScrollWheelChange * positionedObject.RotationMatrix.Forward; #endif } #endif } public Ray GetMouseRay(Camera camera) { #if FRB_MDX // Not sure if this works for non-default Cameras return MathFunctions.GetRay(this.mXAt100Units, this.mYAt100Units, camera); #else return MathFunctions.GetRay(X, Y, 1, camera); //if (InputManager.Keyboard.KeyPushed(Keys.D)) //{ // int m = 3; //} //int screenX = X; //int screenY = Y; //Matrix matrix = Matrix.Invert(camera.TransformationMatrix); //Matrix transformationMatrix = Matrix.CreateTranslation(camera.Position); //Vector3 absoluteRayEnd = Renderer.GraphicsDevice.Viewport.Unproject(new Vector3(screenX, screenY, 1), // camera.GetProjectionMatrix(), camera.GetLookAtMatrix(false), Matrix.Identity); //Vector3 directionRay = absoluteRayEnd; ////Vector3 directionRay = absoluteRayEnd - camera.Position; //directionRay.Normalize(); //return new Ray(camera.Position, directionRay); #endif } public void HideNativeWindowsCursor() { #if FRB_MDX if (mWindowsCursorVisible) { System.Windows.Forms.Cursor.Hide(); mWindowsCursorVisible = false; try { mMouseDevice.Unacquire(); mMouseDevice.SetCooperativeLevel(mOwner, CooperativeLevelFlags.Foreground | CooperativeLevelFlags.Exclusive); mMouseDevice.Acquire(); } catch (Exception) { } } #endif } #region XML Docs /// <summary> /// Returns whether the Mouse is over the argument Circle. /// </summary> /// <param name="circle">The Circle to check.</param> /// <returns>Whether the mouse is over the argument Circle.</returns> #endregion public bool IsOn(Circle circle) { return circle.IsPointInside(WorldXAt(0), WorldYAt(0)); } public bool IsOn(Circle circle, Camera camera) { return circle.IsPointInside(WorldXAt(0, camera), WorldYAt(0, camera)); } public bool IsOn(Polygon polygon) { return polygon.IsPointInside(WorldXAt(polygon.Z), WorldYAt(polygon.Z)); } public bool IsOn(Polygon polygon, Camera camera) { return polygon.IsPointInside(WorldXAt(polygon.Z, camera), WorldYAt(polygon.Z, camera)); } public bool IsOn(AxisAlignedRectangle rectangle) { return rectangle.IsPointInside(WorldXAt(0), WorldYAt(0)); } public bool IsOn(AxisAlignedRectangle rectangle, Camera camera) { return rectangle.IsPointInside(WorldXAt(0, camera), WorldYAt(0, camera)); } public bool IsOn(Camera camera) { return X > camera.LeftDestination && X < camera.RightDestination && Y > camera.TopDestination && Y < camera.BottomDestination; } #if !XBOX360 public bool IsOn3D(FlatRedBall.Graphics.Text text, bool relativeToCamera) { Vector3 offset = new Vector3(); switch (text.HorizontalAlignment) { case FlatRedBall.Graphics.HorizontalAlignment.Left: offset.X = text.ScaleX; break; case FlatRedBall.Graphics.HorizontalAlignment.Right: offset.X = -text.ScaleX; break; } switch (text.VerticalAlignment) { case FlatRedBall.Graphics.VerticalAlignment.Top: offset.Y = -text.ScaleY; break; case FlatRedBall.Graphics.VerticalAlignment.Bottom: offset.Y = text.ScaleY; break; } text.Position += offset; bool value = IsOn3D<FlatRedBall.Graphics.Text>(text, relativeToCamera); text.Position -= offset; return value; } #endif #if !XBOX360 public bool IsOn3D<T>(T objectToTest, bool relativeToCamera) where T : IPositionable, IRotatable, IReadOnlyScalable { Vector3 temporaryVector = new Vector3(); return IsOn3D<T>(objectToTest, false, SpriteManager.Camera, out temporaryVector); } public bool IsOn3D<T>(T objectToTest, bool relativeToCamera, ref Vector3 intersectionPoint) where T : IPositionable, IRotatable, IReadOnlyScalable { return IsOn3D(objectToTest, relativeToCamera, SpriteManager.Camera, out intersectionPoint); } public bool IsOn3D<T>(T objectToTest, bool relativeToCamera, Camera camera) where T : IPositionable, IRotatable, IReadOnlyScalable { Vector3 temporaryVector = new Vector3(); return IsOn3D(objectToTest, relativeToCamera, camera, out temporaryVector); } /// <summary> /// Determines whether the Mouse is over the objectToTest argument. /// </summary> /// <remarks> /// If a Text object is passed this method will only work appropriately if /// the Text object has centered text. See the IsOn3D overload which takes a Text argument. /// </remarks> /// <typeparam name="T">The type of the first argument.</typeparam> /// <param name="objectToTest">The object to test if the mouse is on.</param> /// <param name="relativeToCamera">Whether the object's Position is relative to the Camera.</param> /// <param name="camera"></param> /// <param name="intersectionPoint">The point where the intersection between the ray casted from the /// mouse into the distance and the argument objectToTest occurred.</param> /// <returns>Whether the mouse is over the argument objectToTest</returns> public bool IsOn3D<T>(T objectToTest, bool relativeToCamera, Camera camera, out Vector3 intersectionPoint) where T : IPositionable, IRotatable, IReadOnlyScalable { if (camera == SpriteManager.Camera) { return MathFunctions.IsOn3D<T>( objectToTest, relativeToCamera, this.GetMouseRay(SpriteManager.Camera), camera, out intersectionPoint); } else { float xAt100Units = 0; float yAt100Units = 0; FlatRedBall.Math.MathFunctions.WindowToAbsolute( X - camera.DestinationRectangle.Left, Y - camera.DestinationRectangle.Top, ref xAt100Units, ref yAt100Units, FlatRedBall.Math.MathFunctions.ForwardVector3.Z * 100, camera, Camera.CoordinateRelativity.RelativeToCamera); return MathFunctions.IsOn3D<T>( objectToTest, relativeToCamera, this.GetMouseRay(SpriteManager.Camera), camera, out intersectionPoint); } } #endif public bool IsInGameWindow() { // Not sure why we do greater than 0 instead of greater than or equal to // 0. On W8 the cursor initially starts at 0,0 and that is in the window, // so we want to consider 0 inside. return X >= 0 && X < FlatRedBallServices.ClientWidth && Y >= 0 && Y < FlatRedBallServices.ClientHeight; } public void SetScreenPosition(int newX, int newY) { #if XNA // The velocity should not change when positions are set. mThisFrameRepositionX += newX - System.Windows.Forms.Cursor.Position.X; mThisFrameRepositionY += newY - System.Windows.Forms.Cursor.Position.Y; System.Windows.Forms.Cursor.Position = new System.Drawing.Point( newX, newY); #else // The velocity should not change when positions are set. MouseState currentState = Microsoft.Xna.Framework.Input.Mouse.GetState(); mThisFrameRepositionX += newX - currentState.X; mThisFrameRepositionY += newY - currentState.Y; Microsoft.Xna.Framework.Input.Mouse.SetPosition(newX, newY); #endif } public void ShowNativeWindowsCursor() { } public override string ToString() { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append("Internal MouseState:").Append(mMouseState.ToString()); stringBuilder.Append("\nWorldX at 100 units: ").Append(mXAt100Units); stringBuilder.Append("\nWorldY at 100 units: ").Append(mYAt100Units); stringBuilder.Append("\nScrollWheel: ").Append(ScrollWheelChange); return stringBuilder.ToString(); } #region World Values At public float WorldXAt(float zValue) { return WorldXAt(zValue, SpriteManager.Camera); } public float WorldXAt(float zValue, Camera camera) { if (camera.Orthogonal == false) { if (camera == SpriteManager.Camera) { return camera.X + FlatRedBall.Math.MathFunctions.ForwardVector3.Z * (zValue - camera.Z) * mXAt100Units / 100.0f; } else { float xAt100Units = 0; float yAt100Units = 0; #if !SILVERLIGHT FlatRedBall.Math.MathFunctions.WindowToAbsolute( X - camera.DestinationRectangle.Left, Y - camera.DestinationRectangle.Top, ref xAt100Units, ref yAt100Units, FlatRedBall.Math.MathFunctions.ForwardVector3.Z * 100, camera, Camera.CoordinateRelativity.RelativeToCamera); #endif return camera.X + FlatRedBall.Math.MathFunctions.ForwardVector3.Z * (zValue - camera.Z) * xAt100Units / 100.0f; } } else { return camera.X - camera.OrthogonalWidth / 2.0f + // left border ((X - camera.DestinationRectangle.Left) *camera.OrthogonalWidth/camera.DestinationRectangle.Width ); } } public float WorldYAt(float zValue) { return WorldYAt(zValue, SpriteManager.Camera); } public float WorldYAt(float zValue, Camera camera) { if (camera.Orthogonal == false) { if (camera == SpriteManager.Camera) { return camera.Y + FlatRedBall.Math.MathFunctions.ForwardVector3.Z * (zValue - camera.Z) * mYAt100Units / 100; } else { float xAt100Units = 0; float yAt100Units = 0; #if !SILVERLIGHT FlatRedBall.Math.MathFunctions.WindowToAbsolute( X - camera.DestinationRectangle.Left, Y - camera.DestinationRectangle.Top, ref xAt100Units, ref yAt100Units, FlatRedBall.Math.MathFunctions.ForwardVector3.Z * 100, camera, Camera.CoordinateRelativity.RelativeToCamera); #endif return camera.Y + FlatRedBall.Math.MathFunctions.ForwardVector3.Z * (zValue - camera.Z) * yAt100Units / 100; } } else { return camera.Y + camera.OrthogonalHeight / 2.0f - ((Y - camera.TopDestination) * camera.OrthogonalHeight / camera.DestinationRectangle.Height); } } #if !XBOX360 public float WorldXChangeAt(float zPosition) { int change = mMouseState.X - mLastFrameMouseState.X + mLastFrameRepositionX; float resultX; float dummy; MathFunctions.ScreenToAbsoluteDistance(change, 0, out resultX, out dummy, zPosition, SpriteManager.Camera); return resultX; } public float WorldYChangeAt(float zPosition) { int change = mMouseState.Y - mLastFrameMouseState.Y + mLastFrameRepositionY; float resultY; float dummy; MathFunctions.ScreenToAbsoluteDistance(0, change, out dummy, out resultY, zPosition, SpriteManager.Camera); return resultY; } #endif #endregion //#endif #endregion #region Internal Methods internal void Update(float secondDifference, double currentTime) { mLastFrameMouseState = mMouseState; mLastFrameRepositionX = mThisFrameRepositionX; mLastFrameRepositionY = mThisFrameRepositionY; mThisFrameRepositionX = 0; mThisFrameRepositionY = 0; XnaAndSilverlightSpecificUpdateLogic(secondDifference, currentTime); //if (mClearUntilNextClick) //{ // if (ButtonReleased(MouseButtons.LeftButton)) // { // mClearUntilNextClick = false; // } // Clear(); //} //else { FlatRedBall.Math.MathFunctions.WindowToAbsolute( X - SpriteManager.Camera.DestinationRectangle.Left, Y - SpriteManager.Camera.DestinationRectangle.Top, ref mXAt100Units, ref mYAt100Units, FlatRedBall.Math.MathFunctions.ForwardVector3.Z * 100, SpriteManager.Camera, Camera.CoordinateRelativity.RelativeToCamera); if (mGrabbedPositionedObject != null) { mGrabbedPositionedObject.X = WorldXAt(mGrabbedPositionedObject.Z) + mGrabbedPositionedObjectRelativeX; mGrabbedPositionedObject.Y = WorldYAt(mGrabbedPositionedObject.Z) + mGrabbedPositionedObjectRelativeY; } } } private void XnaAndSilverlightSpecificUpdateLogic(float secondDifference, double currentTime) { mLastWheel = mMouseState.ScrollWheelValue; mMouseState = Microsoft.Xna.Framework.Input.Mouse.GetState(); if(MouseState.LeftButton == ButtonState.Pressed) { int m = 3; } if (ModifyMouseState != null) { ModifyMouseState(ref mMouseState); } if (mWasJustCleared) { mLastWheel = mMouseState.ScrollWheelValue; mWasJustCleared = false; } #region Update Double Click/Push for (int i = 0; i < NumberOfButtons; i++) { mDoubleClick[i] = false; mDoublePush[i] = false; MouseButtons asMouseButton = (MouseButtons)i; if (ButtonReleased(asMouseButton)) { if (currentTime - mLastClickTime[i] < MaximumSecondsBetweenClickForDoubleClick) { mDoubleClick[i] = true; } mLastClickTime[i] = currentTime; } if (ButtonPushed(asMouseButton)) { if (currentTime - mLastPushTime[i] < MaximumSecondsBetweenClickForDoubleClick) { mDoublePush[i] = true; } mLastPushTime[i] = currentTime; } } #endregion if (secondDifference != 0) { // If it's 0, then it means that this is the first frame. Just skip over // setting velocity if that's the case. mXVelocity = (mMouseState.X - mLastFrameMouseState.X) / secondDifference; mYVelocity = (mMouseState.Y - mLastFrameMouseState.Y) / secondDifference; } } #endregion #endregion #region IEquatable<Mouse> Members bool IEquatable<Mouse>.Equals(Mouse other) { return this == other; } #endregion } }
// // OAuth framework for TweetStation // // Author; // Miguel de Icaza (miguel@gnome.org) // // Possible optimizations: // Instead of sorting every time, keep things sorted // Reuse the same dictionary, update the values // // Copyright 2010 Miguel de Icaza // // 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.Net; using System.Web; using System.Security.Cryptography; using ServiceStack.ServiceModel; using ServiceStack.Text; namespace ServiceStack.ServiceInterface.Auth { // // Configuration information for an OAuth client // //public class OAuthConfig { // keys, callbacks //public string ConsumerKey, Callback, ConsumerSecret; // Urls //public string RequestTokenUrl, AccessTokenUrl, AuthorizeUrl; //} // // The authorizer uses a provider and an optional xAuth user/password // to perform the OAuth authorization process as well as signing // outgoing http requests // // To get an access token, you use these methods in the workflow: // AcquireRequestToken // AuthorizeUser // // These static methods only require the access token: // AuthorizeRequest // AuthorizeTwitPic // public class OAuthAuthorizer { // Settable by the user public string xAuthUsername, xAuthPassword; OAuthProvider provider; public string RequestToken, RequestTokenSecret; public string AuthorizationToken, AuthorizationVerifier; public string AccessToken, AccessTokenSecret;//, AccessScreenName; //public long AccessId; public Dictionary<string, string> AuthInfo = new Dictionary<string, string>(); // Constructor for standard OAuth public OAuthAuthorizer(OAuthProvider provider) { this.provider = provider; } static Random random = new Random(); static DateTime UnixBaseTime = new DateTime(1970, 1, 1); // 16-byte lower-case or digit string static string MakeNonce() { var ret = new char[16]; for (int i = 0; i < ret.Length; i++) { int n = random.Next(35); if (n < 10) ret[i] = (char)(n + '0'); else ret[i] = (char)(n - 10 + 'a'); } return new string(ret); } static string MakeTimestamp() { return ((long)(DateTime.UtcNow - UnixBaseTime).TotalSeconds).ToString(); } // Makes an OAuth signature out of the HTTP method, the base URI and the headers static string MakeSignature(string method, string base_uri, Dictionary<string, string> headers) { var items = from k in headers.Keys orderby k select k + "%3D" + OAuthUtils.PercentEncode(headers[k]); return method + "&" + OAuthUtils.PercentEncode(base_uri) + "&" + string.Join("%26", items.ToArray()); } static string MakeSigningKey(string consumerSecret, string oauthTokenSecret) { return OAuthUtils.PercentEncode(consumerSecret) + "&" + (oauthTokenSecret != null ? OAuthUtils.PercentEncode(oauthTokenSecret) : ""); } static string MakeOAuthSignature(string compositeSigningKey, string signatureBase) { var sha1 = new HMACSHA1(Encoding.UTF8.GetBytes(compositeSigningKey)); return Convert.ToBase64String(sha1.ComputeHash(Encoding.UTF8.GetBytes(signatureBase))); } static string HeadersToOAuth(Dictionary<string, string> headers) { return "OAuth " + String.Join(",", (from x in headers.Keys select String.Format("{0}=\"{1}\"", x, headers[x])).ToArray()); } public bool AcquireRequestToken() { var headers = new Dictionary<string, string>() { { "oauth_callback", OAuthUtils.PercentEncode (provider.CallbackUrl) }, { "oauth_consumer_key", provider.ConsumerKey }, { "oauth_nonce", MakeNonce () }, { "oauth_signature_method", "HMAC-SHA1" }, { "oauth_timestamp", MakeTimestamp () }, { "oauth_version", "1.0" }}; var uri = new Uri(provider.RequestTokenUrl); var signatureHeaders = new Dictionary<string, string>(headers); var nvc = HttpUtility.ParseQueryString(uri.Query); foreach (string key in nvc) { if (key != null) signatureHeaders.Add(key, OAuthUtils.PercentEncode(nvc[key])); } string signature = MakeSignature("POST", uri.GetLeftPart(UriPartial.Path), signatureHeaders); string compositeSigningKey = MakeSigningKey(provider.ConsumerSecret, null); string oauth_signature = MakeOAuthSignature(compositeSigningKey, signature); var wc = new WebClient(); headers.Add("oauth_signature", OAuthUtils.PercentEncode(oauth_signature)); wc.Headers[HttpRequestHeader.Authorization] = HeadersToOAuth(headers); try { var result = HttpUtility.ParseQueryString(wc.UploadString(new Uri(provider.RequestTokenUrl), "")); if (result["oauth_callback_confirmed"] != null) { RequestToken = result["oauth_token"]; RequestTokenSecret = result["oauth_token_secret"]; return true; } } catch (Exception e) { Console.WriteLine(e); string responseBody = e.GetResponseBody(); responseBody.Print(); // fallthrough for errors } return false; } // Invoked after the user has authorized us // // TODO: this should return the stream error for invalid passwords instead of // just true/false. public bool AcquireAccessToken() { var headers = new Dictionary<string, string>() { { "oauth_consumer_key", provider.ConsumerKey }, { "oauth_nonce", MakeNonce () }, { "oauth_signature_method", "HMAC-SHA1" }, { "oauth_timestamp", MakeTimestamp () }, { "oauth_version", "1.0" }}; var content = ""; if (xAuthUsername == null) { headers.Add("oauth_token", OAuthUtils.PercentEncode(AuthorizationToken)); headers.Add("oauth_verifier", OAuthUtils.PercentEncode(AuthorizationVerifier)); } else { headers.Add("x_auth_username", OAuthUtils.PercentEncode(xAuthUsername)); headers.Add("x_auth_password", OAuthUtils.PercentEncode(xAuthPassword)); headers.Add("x_auth_mode", "client_auth"); content = String.Format("x_auth_mode=client_auth&x_auth_password={0}&x_auth_username={1}", OAuthUtils.PercentEncode(xAuthPassword), OAuthUtils.PercentEncode(xAuthUsername)); } string signature = MakeSignature("POST", provider.AccessTokenUrl, headers); string compositeSigningKey = MakeSigningKey(provider.ConsumerSecret, RequestTokenSecret); string oauth_signature = MakeOAuthSignature(compositeSigningKey, signature); var wc = new WebClient(); headers.Add("oauth_signature", OAuthUtils.PercentEncode(oauth_signature)); if (xAuthUsername != null) { headers.Remove("x_auth_username"); headers.Remove("x_auth_password"); headers.Remove("x_auth_mode"); } wc.Headers[HttpRequestHeader.Authorization] = HeadersToOAuth(headers); try { var result = HttpUtility.ParseQueryString(wc.UploadString(new Uri(provider.AccessTokenUrl), content)); if (result["oauth_token"] != null) { AccessToken = result["oauth_token"]; AccessTokenSecret = result["oauth_token_secret"]; AuthInfo = result.ToDictionary(); return true; } } catch (WebException e) { var x = e.Response.GetResponseStream(); var j = new System.IO.StreamReader(x); Console.WriteLine(j.ReadToEnd()); Console.WriteLine(e); // fallthrough for errors } return false; } // // Assign the result to the Authorization header, like this: // request.Headers [HttpRequestHeader.Authorization] = AuthorizeRequest (...) // public static string AuthorizeRequest(OAuthProvider provider, string oauthToken, string oauthTokenSecret, string method, Uri uri, string data) { var headers = new Dictionary<string, string>() { { "oauth_consumer_key", provider.ConsumerKey }, { "oauth_nonce", MakeNonce () }, { "oauth_signature_method", "HMAC-SHA1" }, { "oauth_timestamp", MakeTimestamp () }, { "oauth_token", oauthToken }, { "oauth_version", "1.0" }}; var signatureHeaders = new Dictionary<string, string>(headers); // Add the data and URL query string to the copy of the headers for computing the signature if (data != null && data != "") { var parsed = HttpUtility.ParseQueryString(data); foreach (string k in parsed.Keys) { signatureHeaders.Add(k, OAuthUtils.PercentEncode(parsed[k])); } } var nvc = HttpUtility.ParseQueryString(uri.Query); foreach (string key in nvc) { if (key != null) signatureHeaders.Add(key, OAuthUtils.PercentEncode(nvc[key])); } string signature = MakeSignature(method, uri.GetLeftPart(UriPartial.Path), signatureHeaders); string compositeSigningKey = MakeSigningKey(provider.ConsumerSecret, oauthTokenSecret); string oauth_signature = MakeOAuthSignature(compositeSigningKey, signature); headers.Add("oauth_signature", OAuthUtils.PercentEncode(oauth_signature)); return HeadersToOAuth(headers); } // // Used to authorize an HTTP request going to TwitPic // public static void AuthorizeTwitPic(OAuthProvider provider, HttpWebRequest wc, string oauthToken, string oauthTokenSecret) { var headers = new Dictionary<string, string>() { { "oauth_consumer_key", provider.ConsumerKey }, { "oauth_nonce", MakeNonce () }, { "oauth_signature_method", "HMAC-SHA1" }, { "oauth_timestamp", MakeTimestamp () }, { "oauth_token", oauthToken }, { "oauth_version", "1.0" }, //{ "realm", "http://api.twitter.com" } }; string signurl = "http://api.twitter.com/1/account/verify_credentials.xml"; // The signature is not done against the *actual* url, it is done against the verify_credentials.json one string signature = MakeSignature("GET", signurl, headers); string compositeSigningKey = MakeSigningKey(provider.ConsumerSecret, oauthTokenSecret); string oauth_signature = MakeOAuthSignature(compositeSigningKey, signature); headers.Add("oauth_signature", OAuthUtils.PercentEncode(oauth_signature)); //Util.Log ("Headers: " + HeadersToOAuth (headers)); wc.Headers.Add("X-Verify-Credentials-Authorization", HeadersToOAuth(headers)); wc.Headers.Add("X-Auth-Service-Provider", signurl); } } public static class OAuthUtils { // // This url encoder is different than regular Url encoding found in .NET // as it is used to compute the signature based on a url. Every document // on the web omits this little detail leading to wasting everyone's time. // // This has got to be one of the lamest specs and requirements ever produced // public static string PercentEncode(string s) { var sb = new StringBuilder(); foreach (byte c in Encoding.UTF8.GetBytes(s)) { if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '-' || c == '_' || c == '.' || c == '~') sb.Append((char)c); else { sb.AppendFormat("%{0:X2}", c); } } return sb.ToString(); } } }
// 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. #if ARM #define _TARGET_ARM_ #define CALLDESCR_ARGREGS // CallDescrWorker has ArgumentRegister parameter #define CALLDESCR_FPARGREGS // CallDescrWorker has FloatArgumentRegisters parameter #define CALLDESCR_FPARGREGSARERETURNREGS // The return value floating point registers are the same as the argument registers #define ENREGISTERED_RETURNTYPE_MAXSIZE #define ENREGISTERED_RETURNTYPE_INTEGER_MAXSIZE #define FEATURE_HFA #elif ARM64 #define _TARGET_ARM64_ #define CALLDESCR_ARGREGS // CallDescrWorker has ArgumentRegister parameter #define CALLDESCR_FPARGREGS // CallDescrWorker has FloatArgumentRegisters parameter #define CALLDESCR_FPARGREGSARERETURNREGS // The return value floating point registers are the same as the argument registers #define ENREGISTERED_RETURNTYPE_MAXSIZE #define ENREGISTERED_RETURNTYPE_INTEGER_MAXSIZE #define ENREGISTERED_PARAMTYPE_MAXSIZE #define FEATURE_HFA #elif X86 #define _TARGET_X86_ #define ENREGISTERED_RETURNTYPE_MAXSIZE #define ENREGISTERED_RETURNTYPE_INTEGER_MAXSIZE #define CALLDESCR_ARGREGS // CallDescrWorker has ArgumentRegister parameter #define CALLINGCONVENTION_CALLEE_POPS #elif AMD64 #if UNIXAMD64 #define UNIX_AMD64_ABI #define CALLDESCR_ARGREGS // CallDescrWorker has ArgumentRegister parameter #else #endif #define CALLDESCR_FPARGREGS // CallDescrWorker has FloatArgumentRegisters parameter #define _TARGET_AMD64_ #define CALLDESCR_FPARGREGSARERETURNREGS // The return value floating point registers are the same as the argument registers #define ENREGISTERED_RETURNTYPE_MAXSIZE #define ENREGISTERED_RETURNTYPE_INTEGER_MAXSIZE #define ENREGISTERED_PARAMTYPE_MAXSIZE #else #error Unknown architecture! #endif using System; using System.Collections.Generic; using System.Diagnostics; using Internal.Runtime.Augments; using System.Runtime; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using Internal.Runtime; using Internal.Runtime.CompilerServices; using Internal.NativeFormat; using Internal.TypeSystem; using Internal.Runtime.CallConverter; namespace Internal.Runtime.TypeLoader { public class CallConverterThunk { private static LowLevelList<IntPtr> s_allocatedThunks = new LowLevelList<IntPtr>(); private static object s_thunkPoolHeap; internal static IntPtr CommonInputThunkStub = IntPtr.Zero; #if CALLDESCR_FPARGREGSARERETURNREGS #else #if _TARGET_X86_ internal static IntPtr ReturnFloatingPointReturn4Thunk = IntPtr.Zero; internal static IntPtr ReturnFloatingPointReturn8Thunk = IntPtr.Zero; #endif #endif internal static IntPtr ReturnVoidReturnThunk = IntPtr.Zero; internal static IntPtr ReturnIntegerPointReturnThunk = IntPtr.Zero; #if _TARGET_X86_ // Correctness of using this data structure relies on thread static structs being allocated in a location which cannot be moved by the GC [ThreadStatic] internal static ReturnBlock t_NonArgRegisterReturnSpace; #endif // CallingConventionConverter_CommonCallingStub indirection information structure // This is filled in during the class constructor for this type, and holds data // that is constant across all uses of the call conversion thunks. A pointer to // this is passed to each invocation of the common calling stub. internal struct CallingConventionConverter_CommonCallingStub_PointerData { public IntPtr ManagedCallConverterThunk; public IntPtr UniversalThunk; } // Wrapper class used for reference type parameters passed byref in dynamic invoker thunks internal class DynamicInvokeByRefArgObjectWrapper { internal object _object; } internal static CallingConventionConverter_CommonCallingStub_PointerData s_commonStubData; [DllImport("*", ExactSpelling = true, EntryPoint = "CallingConventionConverter_GetStubs")] private extern static unsafe void CallingConventionConverter_GetStubs(out IntPtr returnVoidStub, out IntPtr returnIntegerStub, out IntPtr commonStub #if CALLDESCR_FPARGREGSARERETURNREGS #else , out IntPtr returnFloatingPointReturn4Thunk, out IntPtr returnFloatingPointReturn8Thunk #endif ); #if _TARGET_ARM_ [DllImport("*", ExactSpelling = true, EntryPoint = "CallingConventionConverter_SpecifyCommonStubData")] private extern static unsafe void CallingConventionConverter_SpecifyCommonStubData(IntPtr commonStubData); #endif static unsafe CallConverterThunk() { CallingConventionConverter_GetStubs(out ReturnVoidReturnThunk, out ReturnIntegerPointReturnThunk, out CommonInputThunkStub #if CALLDESCR_FPARGREGSARERETURNREGS #else , out ReturnFloatingPointReturn4Thunk, out ReturnFloatingPointReturn8Thunk #endif ); s_commonStubData.ManagedCallConverterThunk = Intrinsics.AddrOf<Func<IntPtr, IntPtr, IntPtr>>(CallConversionThunk); s_commonStubData.UniversalThunk = RuntimeAugments.GetUniversalTransitionThunk(); #if _TARGET_ARM_ fixed (CallingConventionConverter_CommonCallingStub_PointerData* commonStubData = &s_commonStubData) { CallingConventionConverter_SpecifyCommonStubData((IntPtr)commonStubData); } #endif } internal static bool GetByRefIndicatorAtIndex(int index, bool[] lookup) { if (lookup == null) return false; if (index < lookup.Length) return lookup[index]; return false; } public enum ThunkKind { StandardToStandardInstantiating, StandardToGenericInstantiating, StandardToGenericInstantiatingIfNotHasThis, StandardToGeneric, StandardToGenericPassthruInstantiating, StandardToGenericPassthruInstantiatingIfNotHasThis, GenericToStandard, StandardUnboxing, StandardUnboxingAndInstantiatingGeneric, GenericToStandardWithTargetPointerArg, GenericToStandardWithTargetPointerArgAndParamArg, GenericToStandardWithTargetPointerArgAndMaybeParamArg, DelegateInvokeOpenStaticThunk, DelegateInvokeClosedStaticThunk, DelegateInvokeOpenInstanceThunk, DelegateInvokeInstanceClosedOverGenericMethodThunk, DelegateMulticastThunk, DelegateObjectArrayThunk, DelegateDynamicInvokeThunk, ReflectionDynamicInvokeThunk, } // WARNING: These constants are also declared in System.Private.CoreLib\src\System\Delegate.cs // Do not change their values unless you change the values decalred in Delegate.cs private const int MulticastThunk = 0; private const int ClosedStaticThunk = 1; private const int OpenStaticThunk = 2; private const int ClosedInstanceThunkOverGenericMethod = 3; private const int DelegateInvokeThunk = 4; private const int OpenInstanceThunk = 5; private const int ReversePinvokeThunk = 6; private const int ObjectArrayThunk = 7; public static unsafe IntPtr MakeThunk(ThunkKind thunkKind, IntPtr targetPointer, IntPtr instantiatingArg, bool hasThis, RuntimeTypeHandle[] parameters, bool[] byRefParameters, bool[] paramsByRefForced) { // Build thunk data TypeHandle thReturnType = new TypeHandle(GetByRefIndicatorAtIndex(0, byRefParameters), parameters[0]); TypeHandle[] thParameters = null; if (parameters.Length > 1) { thParameters = new TypeHandle[parameters.Length - 1]; for (int i = 1; i < parameters.Length; i++) { thParameters[i - 1] = new TypeHandle(GetByRefIndicatorAtIndex(i, byRefParameters), parameters[i]); } } int callConversionInfo = CallConversionInfo.RegisterCallConversionInfo(thunkKind, targetPointer, instantiatingArg, hasThis, thReturnType, thParameters, paramsByRefForced); return FindExistingOrAllocateThunk(callConversionInfo); } public static unsafe IntPtr MakeThunk(ThunkKind thunkKind, IntPtr targetPointer, RuntimeSignature methodSignature, IntPtr instantiatingArg, RuntimeTypeHandle[] typeArgs, RuntimeTypeHandle[] methodArgs) { int callConversionInfo = CallConversionInfo.RegisterCallConversionInfo(thunkKind, targetPointer, methodSignature, instantiatingArg, typeArgs, methodArgs); return FindExistingOrAllocateThunk(callConversionInfo); } internal static unsafe IntPtr MakeThunk(ThunkKind thunkKind, IntPtr targetPointer, IntPtr instantiatingArg, ArgIteratorData argIteratorData, bool[] paramsByRefForced) { int callConversionInfo = CallConversionInfo.RegisterCallConversionInfo(thunkKind, targetPointer, instantiatingArg, argIteratorData, paramsByRefForced); return FindExistingOrAllocateThunk(callConversionInfo); } private static unsafe IntPtr FindExistingOrAllocateThunk(int callConversionInfo) { IntPtr thunk = IntPtr.Zero; lock (s_allocatedThunks) { if (callConversionInfo < s_allocatedThunks.Count) return s_allocatedThunks[callConversionInfo]; if (s_thunkPoolHeap == null) { s_thunkPoolHeap = RuntimeAugments.CreateThunksHeap(CommonInputThunkStub); Debug.Assert(s_thunkPoolHeap != null); } thunk = RuntimeAugments.AllocateThunk(s_thunkPoolHeap); Debug.Assert(thunk != IntPtr.Zero); fixed (CallingConventionConverter_CommonCallingStub_PointerData* commonStubData = &s_commonStubData) { RuntimeAugments.SetThunkData(s_thunkPoolHeap, thunk, new IntPtr(callConversionInfo), new IntPtr(commonStubData)); Debug.Assert(callConversionInfo == s_allocatedThunks.Count); s_allocatedThunks.Add(thunk); } } return thunk; } public static unsafe IntPtr GetDelegateThunk(Delegate delegateObject, int thunkKind) { if (thunkKind == ReversePinvokeThunk) { // Special unsupported thunk kind. Similar behavior to the thunks generated by the delegate ILTransform for this thunk kind RuntimeTypeHandle thDummy; bool isOpenResolverDummy; Action throwNotSupportedException = () => { throw new NotSupportedException(); }; return RuntimeAugments.GetDelegateLdFtnResult(throwNotSupportedException, out thDummy, out isOpenResolverDummy); } RuntimeTypeHandle delegateType = RuntimeAugments.GetRuntimeTypeHandleFromObjectReference(delegateObject); Debug.Assert(RuntimeAugments.IsGenericType(delegateType)); RuntimeTypeHandle[] typeArgs; RuntimeTypeHandle genericTypeDefHandle; genericTypeDefHandle = RuntimeAugments.GetGenericInstantiation(delegateType, out typeArgs); Debug.Assert(typeArgs != null && typeArgs.Length > 0); RuntimeSignature invokeMethodSignature; bool gotInvokeMethodSignature = TypeBuilder.TryGetDelegateInvokeMethodSignature(delegateType, out invokeMethodSignature); if (!gotInvokeMethodSignature) { Environment.FailFast("Unable to compute delegate invoke signature"); } switch (thunkKind) { case DelegateInvokeThunk: return CallConverterThunk.MakeThunk(CallConverterThunk.ThunkKind.DelegateDynamicInvokeThunk, IntPtr.Zero, invokeMethodSignature, IntPtr.Zero, typeArgs, null); case ObjectArrayThunk: return CallConverterThunk.MakeThunk(CallConverterThunk.ThunkKind.DelegateObjectArrayThunk, IntPtr.Zero, invokeMethodSignature, IntPtr.Zero, typeArgs, null); case MulticastThunk: return CallConverterThunk.MakeThunk(CallConverterThunk.ThunkKind.DelegateMulticastThunk, IntPtr.Zero, invokeMethodSignature, IntPtr.Zero, typeArgs, null); case OpenInstanceThunk: return CallConverterThunk.MakeThunk(CallConverterThunk.ThunkKind.DelegateInvokeOpenInstanceThunk, IntPtr.Zero, invokeMethodSignature, IntPtr.Zero, typeArgs, null); case ClosedInstanceThunkOverGenericMethod: return CallConverterThunk.MakeThunk(CallConverterThunk.ThunkKind.DelegateInvokeInstanceClosedOverGenericMethodThunk, IntPtr.Zero, invokeMethodSignature, IntPtr.Zero, typeArgs, null); case ClosedStaticThunk: return CallConverterThunk.MakeThunk(CallConverterThunk.ThunkKind.DelegateInvokeClosedStaticThunk, IntPtr.Zero, invokeMethodSignature, IntPtr.Zero, typeArgs, null); case OpenStaticThunk: return CallConverterThunk.MakeThunk(CallConverterThunk.ThunkKind.DelegateInvokeOpenStaticThunk, IntPtr.Zero, invokeMethodSignature, IntPtr.Zero, typeArgs, null); default: Environment.FailFast("Invalid delegate thunk kind"); return IntPtr.Zero; } } public static unsafe bool TryGetNonUnboxingFunctionPointerFromUnboxingAndInstantiatingStub(IntPtr potentialStub, RuntimeTypeHandle exactType, out IntPtr nonUnboxingMethod) { IntPtr callConversionId; IntPtr commonStubDataPtr; if (!RuntimeAugments.TryGetThunkData(s_thunkPoolHeap, potentialStub, out callConversionId, out commonStubDataPtr)) { // This isn't a call conversion stub nonUnboxingMethod = IntPtr.Zero; return false; } CallConversionInfo conversionInfo = CallConversionInfo.GetConverter(callConversionId.ToInt32()); if (conversionInfo.IsUnboxingThunk) { // In this case the call converter is serving as an unboxing/instantiating stub // This case is not yet handled, and we don't need support for it yet. throw NotImplemented.ByDesign; } IntPtr underlyingTargetMethod; IntPtr newInstantiatingArg; if (conversionInfo.CalleeHasParamType) { // In this case the call converter is an instantiating stub wrapping an unboxing thunk. // Use the redhawk GetCodeTarget to see through the unboxing stub and get the real underlying method // and the instantiation arg does not need changing. underlyingTargetMethod = RuntimeAugments.GetCodeTarget(conversionInfo.TargetFunctionPointer); newInstantiatingArg = conversionInfo.InstantiatingStubArgument; } else { // At this point we've got a standard to generic converter wrapping an unboxing and instantiating // stub. We need to convert that into a fat function pointer directly calling the underlying method // or a calling convention converter instantiating stub wrapping the underlying method IntPtr underlyingUnboxingAndInstantiatingMethod = RuntimeAugments.GetCodeTarget(conversionInfo.TargetFunctionPointer); if (!TypeLoaderEnvironment.TryGetTargetOfUnboxingAndInstantiatingStub(underlyingUnboxingAndInstantiatingMethod, out underlyingTargetMethod)) { // We aren't wrapping an unboxing and instantiating stub. This should never happen throw new NotSupportedException(); } newInstantiatingArg = exactType.ToIntPtr(); } Debug.Assert(conversionInfo.CallerForcedByRefData == null); bool canUseFatFunctionPointerInsteadOfThunk = true; if (conversionInfo.CalleeForcedByRefData != null) { foreach (bool forcedByRef in conversionInfo.CalleeForcedByRefData) { if (forcedByRef) { canUseFatFunctionPointerInsteadOfThunk = false; break; } } } if (canUseFatFunctionPointerInsteadOfThunk) { nonUnboxingMethod = FunctionPointerOps.GetGenericMethodFunctionPointer(underlyingTargetMethod, newInstantiatingArg); return true; } else { // Construct a new StandardToGenericInstantiating thunk around the underlyingTargetMethod nonUnboxingMethod = MakeThunk(ThunkKind.StandardToGenericInstantiating, underlyingTargetMethod, newInstantiatingArg, conversionInfo.ArgIteratorData, conversionInfo.CalleeForcedByRefData); return true; } } // This struct shares a layout with CallDescrData in the MRT codebase. internal unsafe struct CallDescrData { // // Input arguments // public void* pSrc; public int numStackSlots; public uint fpReturnSize; // Both of the following pointers are always present to reduce the spread of ifdefs in the C++ and ASM definitions of the struct public ArgumentRegisters* pArgumentRegisters; // Not used by AMD64 public FloatArgumentRegisters* pFloatArgumentRegisters; // Not used by X86 public void* pTarget; // // Return value // public void* pReturnBuffer; } // This function fills a piece of memory in a GC safe way. It makes the guarantee // that it will fill memory in at least pointer sized chunks whenever possible. // Unaligned memory at the beginning and remaining bytes at the end are written bytewise. // We must make this guarantee whenever we clear memory in the GC heap that could contain // object references. The GC or other user threads can read object references at any time, // clearing them bytewise can result in a read on another thread getting incorrect data. unsafe internal static void gcSafeMemzeroPointer(byte* pointer, int size) { byte* memBytes = pointer; byte* endBytes = (pointer + size); // handle unaligned bytes at the beginning while (!ArgIterator.IS_ALIGNED(new IntPtr(memBytes), (int)IntPtr.Size) && (memBytes < endBytes)) *memBytes++ = (byte)0; // now write pointer sized pieces long nPtrs = (endBytes - memBytes) / IntPtr.Size; IntPtr* memPtr = (IntPtr*)memBytes; for (int i = 0; i < nPtrs; i++) *memPtr++ = IntPtr.Zero; // handle remaining bytes at the end memBytes = (byte*)memPtr; while (memBytes < endBytes) *memBytes++ = (byte)0; } unsafe internal static void memzeroPointer(byte* pointer, int size) { for (int i = 0; i < size; i++) pointer[i] = 0; } unsafe internal static void memzeroPointerAligned(byte* pointer, int size) { size = ArgIterator.ALIGN_UP(size, IntPtr.Size); size /= IntPtr.Size; for (int i = 0; i < size; i++) { ((IntPtr*)pointer)[i] = IntPtr.Zero; } } unsafe private static bool isPointerAligned(void* pointer) { if (sizeof(IntPtr) == 4) { return ((int)pointer & 3) == 0; } Debug.Assert(sizeof(IntPtr) == 8); return ((long)pointer & 7) == 0; } #if CCCONVERTER_TRACE private static int s_numConversionsExecuted = 0; #endif private unsafe delegate void InvokeTargetDel(void* allocatedbuffer, ref CallConversionParameters conversionParams); [DebuggerGuidedStepThroughAttribute] unsafe private static IntPtr CallConversionThunk(IntPtr callerTransitionBlockParam, IntPtr callConversionId) { CallConversionParameters conversionParams = default(CallConversionParameters); try { conversionParams = new CallConversionParameters(CallConversionInfo.GetConverter(callConversionId.ToInt32()), callerTransitionBlockParam); #if CCCONVERTER_TRACE System.Threading.Interlocked.Increment(ref s_numConversionsExecuted); CallingConventionConverterLogger.WriteLine("CallConversionThunk executing... COUNT = " + s_numConversionsExecuted.LowLevelToString()); CallingConventionConverterLogger.WriteLine("Executing thunk of type " + conversionParams._conversionInfo.ThunkKindString() + ": "); #endif if (conversionParams._conversionInfo.IsMulticastDelegate) { MulticastDelegateInvoke(ref conversionParams); System.Diagnostics.DebugAnnotations.PreviousCallContainsDebuggerStepInCode(); } else { // Create a transition block on the stack. // Note that SizeOfFrameArgumentArray does overflow checks with sufficient margin to prevent overflows here int nStackBytes = conversionParams._calleeArgs.SizeOfFrameArgumentArray(); int dwAllocaSize = TransitionBlock.GetNegSpaceSize() + sizeof(TransitionBlock) + nStackBytes; IntPtr invokeTargetPtr = Intrinsics.AddrOf((InvokeTargetDel)InvokeTarget); RuntimeAugments.RunFunctionWithConservativelyReportedBuffer(dwAllocaSize, invokeTargetPtr, ref conversionParams); System.Diagnostics.DebugAnnotations.PreviousCallContainsDebuggerStepInCode(); } return conversionParams._invokeReturnValue; } finally { conversionParams.ResetPinnedObjects(); } } [DebuggerGuidedStepThroughAttribute] unsafe private static IntPtr MulticastDelegateInvoke(ref CallConversionParameters conversionParams) { // Create a transition block on the stack. // Note that SizeOfFrameArgumentArray does overflow checks with sufficient margin to prevent overflows here int nStackBytes = conversionParams._calleeArgs.SizeOfFrameArgumentArray(); int dwAllocaSize = TransitionBlock.GetNegSpaceSize() + sizeof(TransitionBlock) + nStackBytes; IntPtr invokeTargetPtr = Intrinsics.AddrOf((InvokeTargetDel)InvokeTarget); for (int i = 0; i < conversionParams.MulticastDelegateCallCount; i++) { conversionParams.PrepareNextMulticastDelegateCall(i); conversionParams._copyReturnValue = (i == (conversionParams.MulticastDelegateCallCount - 1)); RuntimeAugments.RunFunctionWithConservativelyReportedBuffer(dwAllocaSize, invokeTargetPtr, ref conversionParams); System.Diagnostics.DebugAnnotations.PreviousCallContainsDebuggerStepInCode(); } return conversionParams._invokeReturnValue; } [DebuggerGuidedStepThroughAttribute] unsafe private static void InvokeTarget(void* allocatedStackBuffer, ref CallConversionParameters conversionParams) { byte* callerTransitionBlock = conversionParams._callerTransitionBlock; byte* calleeTransitionBlock = ((byte*)allocatedStackBuffer) + TransitionBlock.GetNegSpaceSize(); // // Setup some of the special parameters on the output transition block // void* thisPointer = conversionParams.ThisPointer; void* callerRetBuffer = conversionParams.CallerReturnBuffer; void* VASigCookie = conversionParams.VarArgSigCookie; void* instantiatingStubArgument = (void*)conversionParams.InstantiatingStubArgument; { Debug.Assert((thisPointer != null && conversionParams._calleeArgs.HasThis()) || (thisPointer == null && !conversionParams._calleeArgs.HasThis())); if (thisPointer != null) { *((void**)(calleeTransitionBlock + ArgIterator.GetThisOffset())) = thisPointer; } Debug.Assert((callerRetBuffer != null && conversionParams._calleeArgs.HasRetBuffArg()) || (callerRetBuffer == null && !conversionParams._calleeArgs.HasRetBuffArg())); if (callerRetBuffer != null) { *((void**)(calleeTransitionBlock + conversionParams._calleeArgs.GetRetBuffArgOffset())) = callerRetBuffer; } Debug.Assert((VASigCookie != null && conversionParams._calleeArgs.IsVarArg()) || (VASigCookie == null && !conversionParams._calleeArgs.IsVarArg())); if (VASigCookie != null) { *((void**)(calleeTransitionBlock + conversionParams._calleeArgs.GetVASigCookieOffset())) = VASigCookie; } Debug.Assert((instantiatingStubArgument != null && conversionParams._calleeArgs.HasParamType()) || (instantiatingStubArgument == null && !conversionParams._calleeArgs.HasParamType())); if (instantiatingStubArgument != null) { *((void**)(calleeTransitionBlock + conversionParams._calleeArgs.GetParamTypeArgOffset())) = instantiatingStubArgument; } } #if CCCONVERTER_TRACE if (thisPointer != null) CallingConventionConverterLogger.WriteLine(" ThisPtr = " + new IntPtr(thisPointer).LowLevelToString()); if (callerRetBuffer != null) CallingConventionConverterLogger.WriteLine(" RetBuf = " + new IntPtr(callerRetBuffer).LowLevelToString()); if (VASigCookie != null) CallingConventionConverterLogger.WriteLine(" VASig = " + new IntPtr(VASigCookie).LowLevelToString()); if (instantiatingStubArgument != null) CallingConventionConverterLogger.WriteLine(" InstArg = " + new IntPtr(instantiatingStubArgument).LowLevelToString()); #endif object[] argumentsAsObjectArray = null; IntPtr pinnedResultObject = IntPtr.Zero; CallDescrData callDescrData = default(CallDescrData); IntPtr functionPointerToCall = conversionParams.FunctionPointerToCall; // // Setup the rest of the parameters on the ouput transition block by copying them from the input transition block // int ofsCallee; int ofsCaller; TypeHandle thDummy; TypeHandle thValueType; IntPtr argPtr; #if CALLDESCR_FPARGREGS FloatArgumentRegisters* pFloatArgumentRegisters = null; #endif { uint arg = 0; while (true) { // Setup argument offsets. ofsCallee = conversionParams._calleeArgs.GetNextOffset(); ofsCaller = int.MaxValue; // Check to see if we've handled all the arguments that we are to pass to the callee. if (TransitionBlock.InvalidOffset == ofsCallee) { if (!conversionParams._conversionInfo.IsAnyDynamicInvokerThunk) ofsCaller = conversionParams._callerArgs.GetNextOffset(); break; } #if CALLDESCR_FPARGREGS // Under CALLDESCR_FPARGREGS -ve offsets indicate arguments in floating point registers. If we // have at least one such argument we point the call worker at the floating point area of the // frame (we leave it null otherwise since the worker can perform a useful optimization if it // knows no floating point registers need to be set up). if ((ofsCallee < 0) && (pFloatArgumentRegisters == null)) pFloatArgumentRegisters = (FloatArgumentRegisters*)(calleeTransitionBlock + TransitionBlock.GetOffsetOfFloatArgumentRegisters()); #endif byte* pDest = calleeTransitionBlock + ofsCallee; byte* pSrc = null; int stackSizeCallee = int.MaxValue; int stackSizeCaller = int.MaxValue; bool isCalleeArgPassedByRef = false; bool isCallerArgPassedByRef = false; // // Compute size and pointer to caller's arg // { if (conversionParams._conversionInfo.IsClosedStaticDelegate) { if (arg == 0) { // Do not advance the caller's ArgIterator yet argPtr = conversionParams.ClosedStaticDelegateThisPointer; pSrc = (byte*)&argPtr; stackSizeCaller = IntPtr.Size; isCallerArgPassedByRef = false; } else { ofsCaller = conversionParams._callerArgs.GetNextOffset(); pSrc = callerTransitionBlock + ofsCaller; stackSizeCaller = conversionParams._callerArgs.GetArgSize(); isCallerArgPassedByRef = conversionParams._callerArgs.IsArgPassedByRef(); } stackSizeCallee = conversionParams._calleeArgs.GetArgSize(); isCalleeArgPassedByRef = conversionParams._calleeArgs.IsArgPassedByRef(); } else if (conversionParams._conversionInfo.IsAnyDynamicInvokerThunk) { // The caller's ArgIterator for delegate or reflection dynamic invoke thunks has a different (and special) signature than // the target method called by the delegate. We do not use it when setting up the callee's transition block. // Input arguments are not read from the caller's transition block, but form the dynamic invoke infrastructure. // Get all arguments info from the callee's ArgIterator instead. int index; InvokeUtils.DynamicInvokeParamLookupType paramLookupType; RuntimeTypeHandle argumentRuntimeTypeHandle; CorElementType argType = conversionParams._calleeArgs.GetArgType(out thValueType); if (argType == CorElementType.ELEMENT_TYPE_BYREF) { TypeHandle thByRefArgType; conversionParams._calleeArgs.GetByRefArgType(out thByRefArgType); Debug.Assert(!thByRefArgType.IsNull()); argumentRuntimeTypeHandle = thByRefArgType.GetRuntimeTypeHandle(); } else { argumentRuntimeTypeHandle = (thValueType.IsNull() ? typeof(object).TypeHandle : thValueType.GetRuntimeTypeHandle()); } object invokeParam = InvokeUtils.DynamicInvokeParamHelperCore( argumentRuntimeTypeHandle, out paramLookupType, out index, conversionParams._calleeArgs.IsArgPassedByRef() ? InvokeUtils.DynamicInvokeParamType.Ref : InvokeUtils.DynamicInvokeParamType.In); if (paramLookupType == InvokeUtils.DynamicInvokeParamLookupType.ValuetypeObjectReturned) { CallConversionParameters.s_pinnedGCHandles._dynamicInvokeArgHandle.Target = invokeParam; argPtr = RuntimeAugments.GetRawAddrOfPinnedObject((IntPtr)CallConversionParameters.s_pinnedGCHandles._dynamicInvokeArgHandle) + IntPtr.Size; } else { Debug.Assert(paramLookupType == InvokeUtils.DynamicInvokeParamLookupType.IndexIntoObjectArrayReturned); Debug.Assert((invokeParam is object[]) && index < ((object[])invokeParam).Length); CallConversionParameters.s_pinnedGCHandles._dynamicInvokeArgHandle.Target = ((object[])invokeParam)[index]; pinnedResultObject = RuntimeAugments.GetRawAddrOfPinnedObject((IntPtr)CallConversionParameters.s_pinnedGCHandles._dynamicInvokeArgHandle); if (conversionParams._calleeArgs.IsArgPassedByRef()) { // We need to keep track of the array of parameters used by the InvokeUtils infrastructure, so we can copy // back results of byref parameters conversionParams._dynamicInvokeParams = conversionParams._dynamicInvokeParams ?? (object[])invokeParam; // Use wrappers to pass objects byref (Wrappers can handle both null and non-null input byref parameters) conversionParams._dynamicInvokeByRefObjectArgs = conversionParams._dynamicInvokeByRefObjectArgs ?? new DynamicInvokeByRefArgObjectWrapper[conversionParams._dynamicInvokeParams.Length]; // The wrapper objects need to be pinned while we take the address of the byref'd object, and copy it to the callee // transition block (which is conservatively reported). Once the copy is done, we can safely unpin the wrapper object. if (pinnedResultObject == IntPtr.Zero) { // Input byref parameter has a null value conversionParams._dynamicInvokeByRefObjectArgs[index] = new DynamicInvokeByRefArgObjectWrapper(); CallConversionParameters.s_pinnedGCHandles._dynamicInvokeArgHandle.Target = conversionParams._dynamicInvokeByRefObjectArgs[index]; argPtr = RuntimeAugments.GetRawAddrOfPinnedObject((IntPtr)CallConversionParameters.s_pinnedGCHandles._dynamicInvokeArgHandle) + IntPtr.Size; } else { // Input byref parameter has a non-null value conversionParams._dynamicInvokeByRefObjectArgs[index] = new DynamicInvokeByRefArgObjectWrapper { _object = conversionParams._dynamicInvokeParams[index] }; CallConversionParameters.s_pinnedGCHandles._dynamicInvokeArgHandle.Target = conversionParams._dynamicInvokeByRefObjectArgs[index]; argPtr = RuntimeAugments.GetRawAddrOfPinnedObject((IntPtr)CallConversionParameters.s_pinnedGCHandles._dynamicInvokeArgHandle) + IntPtr.Size; } } else { argPtr = new IntPtr(&pinnedResultObject); } } if (conversionParams._calleeArgs.IsArgPassedByRef()) { pSrc = (byte*)&argPtr; } else { pSrc = (byte*)argPtr; } stackSizeCaller = stackSizeCallee = conversionParams._calleeArgs.GetArgSize(); isCallerArgPassedByRef = isCalleeArgPassedByRef = conversionParams._calleeArgs.IsArgPassedByRef(); } else { ofsCaller = conversionParams._callerArgs.GetNextOffset(); pSrc = callerTransitionBlock + ofsCaller; stackSizeCallee = conversionParams._calleeArgs.GetArgSize(); stackSizeCaller = conversionParams._callerArgs.GetArgSize(); isCalleeArgPassedByRef = conversionParams._calleeArgs.IsArgPassedByRef(); isCallerArgPassedByRef = conversionParams._callerArgs.IsArgPassedByRef(); } } Debug.Assert(stackSizeCallee == stackSizeCaller); if (conversionParams._conversionInfo.IsObjectArrayDelegateThunk) { // Box (if needed) and copy arguments to an object array instead of the callee's transition block argumentsAsObjectArray = argumentsAsObjectArray ?? new object[conversionParams._callerArgs.NumFixedArgs()]; conversionParams._callerArgs.GetArgType(out thValueType); if (thValueType.IsNull()) { Debug.Assert(!isCallerArgPassedByRef); Debug.Assert(conversionParams._callerArgs.GetArgSize() == IntPtr.Size); argumentsAsObjectArray[arg] = Unsafe.As<IntPtr, Object>(ref *(IntPtr*)pSrc); } else { if (isCallerArgPassedByRef) { argumentsAsObjectArray[arg] = RuntimeAugments.Box(thValueType.GetRuntimeTypeHandle(), new IntPtr(*((void**)pSrc))); } else { argumentsAsObjectArray[arg] = RuntimeAugments.Box(thValueType.GetRuntimeTypeHandle(), new IntPtr(pSrc)); } } } else { if (isCalleeArgPassedByRef == isCallerArgPassedByRef) { // Argument copies without adjusting calling convention. switch (stackSizeCallee) { case 1: case 2: case 4: *((int*)pDest) = *((int*)pSrc); break; case 8: *((long*)pDest) = *((long*)pSrc); break; default: if (isCalleeArgPassedByRef) { // even though this argument is passed by value, the actual calling convention // passes a pointer to the value of the argument. Debug.Assert(isCallerArgPassedByRef); // Copy the pointer from the incoming arguments to the outgoing arguments. *((void**)pDest) = *((void**)pSrc); } else { // In this case, the valuetype is passed directly on the stack, even though it is // a non-integral size. Buffer.MemoryCopy(pSrc, pDest, stackSizeCallee, stackSizeCallee); } break; } } else { // Calling convention adjustment. Used to handle conversion from universal shared generic form to standard // calling convention and vice versa if (isCalleeArgPassedByRef) { // Pass as the byref pointer a pointer to the position in the transition block of the input argument *((void**)pDest) = pSrc; } else { // Copy into the destination the data pointed at by the pointer in the source(caller) data. Buffer.MemoryCopy(*(byte**)pSrc, pDest, stackSizeCaller, stackSizeCaller); } } #if CCCONVERTER_TRACE CallingConventionConverterLogger.WriteLine(" Arg" + arg.LowLevelToString() + " " + (isCalleeArgPassedByRef ? "ref = " : " = ") + new IntPtr(*(void**)pDest).LowLevelToString() + " - RTTH = " + conversionParams._calleeArgs.GetEETypeDebugName((int)arg) + " - StackSize = " + stackSizeCallee.LowLevelToString()); #endif } if (conversionParams._conversionInfo.IsAnyDynamicInvokerThunk) { // The calleeTransitionBlock is GC-protected, so we can now safely unpin the return value of DynamicInvokeParamHelperCore, // since we just copied it to the callee TB. CallConversionParameters.s_pinnedGCHandles._dynamicInvokeArgHandle.Target = ""; } arg++; } } if (conversionParams._conversionInfo.IsAnyDynamicInvokerThunk) { IntPtr argSetupStatePtr = conversionParams.GetArgSetupStateDataPointer(); InvokeUtils.DynamicInvokeArgSetupPtrComplete(argSetupStatePtr); } uint fpReturnSize = conversionParams._calleeArgs.GetFPReturnSize(); if (conversionParams._conversionInfo.IsObjectArrayDelegateThunk) { Debug.Assert(conversionParams._callerArgs.HasRetBuffArg() == conversionParams._calleeArgs.HasRetBuffArg()); pinnedResultObject = conversionParams.InvokeObjectArrayDelegate(argumentsAsObjectArray); } else { if ((TransitionBlock.InvalidOffset != ofsCaller) != conversionParams._conversionInfo.CallerHasExtraParameterWhichIsFunctionTarget && !conversionParams._conversionInfo.IsAnyDynamicInvokerThunk) { // The condition on the loop above is only verifying that callee has reach the end of its arguments. // Here we check to see that caller has done so as well. Environment.FailFast("Argument mismatch between caller and callee"); } if (conversionParams._conversionInfo.CallerHasExtraParameterWhichIsFunctionTarget && !conversionParams._conversionInfo.CalleeMayHaveParamType) { int stackSizeCaller = conversionParams._callerArgs.GetArgSize(); Debug.Assert(stackSizeCaller == IntPtr.Size); void* pSrc = callerTransitionBlock + ofsCaller; functionPointerToCall = *((IntPtr*)pSrc); ofsCaller = conversionParams._callerArgs.GetNextOffset(); if (TransitionBlock.InvalidOffset != ofsCaller) { Environment.FailFast("Argument mismatch between caller and callee"); } } callDescrData.pSrc = calleeTransitionBlock + sizeof(TransitionBlock); callDescrData.numStackSlots = conversionParams._calleeArgs.SizeOfFrameArgumentArray() / ArchitectureConstants.STACK_ELEM_SIZE; #if CALLDESCR_ARGREGS callDescrData.pArgumentRegisters = (ArgumentRegisters*)(calleeTransitionBlock + TransitionBlock.GetOffsetOfArgumentRegisters()); #endif #if CALLDESCR_FPARGREGS callDescrData.pFloatArgumentRegisters = pFloatArgumentRegisters; #endif callDescrData.fpReturnSize = fpReturnSize; callDescrData.pTarget = (void*)functionPointerToCall; ReturnBlock returnBlockForIgnoredData = default(ReturnBlock); if (conversionParams._callerArgs.HasRetBuffArg() == conversionParams._calleeArgs.HasRetBuffArg()) { // If there is no return buffer explictly in use, return to a buffer which is conservatively reported // by the universal transition frame. // OR // If there IS a return buffer in use, the function doesn't really return anything in the normal // return value registers, but CallDescrThunk will always copy a pointer sized chunk into the // ret buf. Make that ok by giving it a valid location to stash bits. callDescrData.pReturnBuffer = (void*)(callerTransitionBlock + TransitionBlock.GetOffsetOfReturnValuesBlock()); } else if (conversionParams._calleeArgs.HasRetBuffArg()) { // This is the case when the caller doesn't have a return buffer argument, but the callee does. // In that case the return value captured by CallDescrWorker is ignored. // When CallDescrWorkerInternal is called, have it return values into a temporary unused buffer // In actuality its returning its return information into the return value block already, but that return buffer // was setup as a passed in argument instead of being filled in by the CallDescrWorker function directly. callDescrData.pReturnBuffer = (void*)&returnBlockForIgnoredData; } else { // If there is no return buffer explictly in use by the callee, return to a buffer which is conservatively reported // by the universal transition frame. // This is the case where HasRetBuffArg is false for the callee, but the caller has a return buffer. // In this case we need to capture the direct return value from callee into a buffer which may contain // a gc reference (or not), and then once the call is complete, copy the value into the return buffer // passed by the caller. (Do not directly use the return buffer provided by the caller, as CallDescrWorker // does not properly use a write barrier, and the actual return buffer provided may be on the GC heap.) callDescrData.pReturnBuffer = (void*)(callerTransitionBlock + TransitionBlock.GetOffsetOfReturnValuesBlock()); } ////////////////////////////////////////////////////////////// //// Call the Callee ////////////////////////////////////////////////////////////// RuntimeAugments.CallDescrWorker(new IntPtr(&callDescrData)); System.Diagnostics.DebugAnnotations.PreviousCallContainsDebuggerStepInCode(); } // For dynamic invoke thunks, we need to copy back values of reference type parameters that were passed byref if (conversionParams._conversionInfo.IsAnyDynamicInvokerThunk && conversionParams._dynamicInvokeParams != null) { for (int i = 0; i < conversionParams._dynamicInvokeParams.Length; i++) { if (conversionParams._dynamicInvokeByRefObjectArgs[i] == null) continue; object byrefObjectArgValue = conversionParams._dynamicInvokeByRefObjectArgs[i]._object; conversionParams._dynamicInvokeParams[i] = byrefObjectArgValue; } } if (!conversionParams._copyReturnValue) return; bool forceByRefUnused; CorElementType returnType; // Note that the caller's ArgIterator for delegate dynamic invoke thunks has a different (and special) signature than // the target method called by the delegate. Use the callee's ArgIterator instead to get the return type info if (conversionParams._conversionInfo.IsAnyDynamicInvokerThunk) { returnType = conversionParams._calleeArgs.GetReturnType(out thValueType, out forceByRefUnused); } else { returnType = conversionParams._callerArgs.GetReturnType(out thValueType, out forceByRefUnused); } int returnSize = TypeHandle.GetElemSize(returnType, thValueType); // Unbox result of object array delegate call if (conversionParams._conversionInfo.IsObjectArrayDelegateThunk && !thValueType.IsNull() && pinnedResultObject != IntPtr.Zero) pinnedResultObject += IntPtr.Size; // Process return values if ((conversionParams._callerArgs.HasRetBuffArg() && !conversionParams._calleeArgs.HasRetBuffArg()) || (conversionParams._callerArgs.HasRetBuffArg() && conversionParams._conversionInfo.IsObjectArrayDelegateThunk)) { // We should never get here for dynamic invoke thunks Debug.Assert(!conversionParams._conversionInfo.IsAnyDynamicInvokerThunk); // The CallDescrWorkerInternal function will have put the return value into the return buffer, as register return values are // extended to the size of a register, we can't just ask the CallDescrWorker to write directly into the return buffer. // Thus we copy only the correct amount of data here to the real target address byte* incomingRetBufPointer = *((byte**)(callerTransitionBlock + conversionParams._callerArgs.GetRetBuffArgOffset())); void* sourceBuffer = conversionParams._conversionInfo.IsObjectArrayDelegateThunk ? (void*)pinnedResultObject : callDescrData.pReturnBuffer; Debug.Assert(sourceBuffer != null || conversionParams._conversionInfo.IsObjectArrayDelegateThunk); if (sourceBuffer == null) { // object array delegate thunk result is a null object. We'll fill the return buffer with 'returnSize' zeros in that case gcSafeMemzeroPointer(incomingRetBufPointer, returnSize); } else { // Because we are copying into a caller provided buffer, we can't use a simple memory copy, we need to use a // gc protected copy as the actual return buffer may be on the heap. bool useGCSafeCopy = false; if ((returnType == CorElementType.ELEMENT_TYPE_CLASS) || !thValueType.IsNull()) { // The GC Safe copy assumes that memory pointers are pointer-aligned and copy length is a multiple of pointer-size if (isPointerAligned(incomingRetBufPointer) && isPointerAligned(sourceBuffer) && (returnSize % sizeof(IntPtr) == 0)) { useGCSafeCopy = true; } } if (useGCSafeCopy) { RuntimeAugments.BulkMoveWithWriteBarrier(new IntPtr(incomingRetBufPointer), new IntPtr(sourceBuffer), returnSize); } else { Buffer.MemoryCopy(sourceBuffer, incomingRetBufPointer, returnSize, returnSize); } } #if CALLINGCONVENTION_CALLEE_POPS // Don't setup the callee pop argument until after copying into the ret buff. We may be using the location // of the callee pop argument to keep track of the ret buff location SetupCallerPopArgument(callerTransitionBlock, conversionParams._callerArgs); #endif #if _TARGET_X86_ SetupCallerActualReturnData(callerTransitionBlock); // On X86 the return buffer pointer is returned in eax. t_NonArgRegisterReturnSpace.returnValue = new IntPtr(incomingRetBufPointer); conversionParams._invokeReturnValue = ReturnIntegerPointReturnThunk; return; #else // Because the return value was really returned on the heap, simply return as if void was returned. conversionParams._invokeReturnValue = ReturnVoidReturnThunk; return; #endif } else { #if CALLINGCONVENTION_CALLEE_POPS SetupCallerPopArgument(callerTransitionBlock, conversionParams._callerArgs); #endif // The CallDescrWorkerInternal function will have put the return value into the return buffer. // Here we copy the return buffer data into the argument registers for the return thunks. // // A return thunk takes an argument(by value) that is what is to be returned. // // The simplest case is the one where there is no return value bool dummyBool; if (conversionParams._callerArgs.GetReturnType(out thDummy, out dummyBool) == CorElementType.ELEMENT_TYPE_VOID) { conversionParams._invokeReturnValue = ReturnVoidReturnThunk; return; } // The second simplest case is when there is a return buffer argument for both the caller and callee // In that case, we simply treat this as if we are returning void #if _TARGET_X86_ // Except on X86 where the return buffer is returned in the eax register, and looks like an integer return #else if (conversionParams._callerArgs.HasRetBuffArg() && conversionParams._calleeArgs.HasRetBuffArg()) { Debug.Assert(!conversionParams._conversionInfo.IsObjectArrayDelegateThunk); Debug.Assert(!conversionParams._conversionInfo.IsAnyDynamicInvokerThunk); conversionParams._invokeReturnValue = ReturnVoidReturnThunk; return; } #endif void* returnValueToCopy = (void*)(callerTransitionBlock + TransitionBlock.GetOffsetOfReturnValuesBlock()); if (conversionParams._conversionInfo.IsObjectArrayDelegateThunk) { if (!thValueType.IsNull()) { returnValueToCopy = (void*)pinnedResultObject; #if _TARGET_X86_ Debug.Assert(returnSize <= sizeof(ReturnBlock)); if (returnValueToCopy == null) { // object array delegate thunk result is a null object. We'll fill the return buffer with 'returnSize' zeros in that case memzeroPointer((byte*)(&((TransitionBlock*)callerTransitionBlock)->m_returnBlock), returnSize); } else { if (isPointerAligned(&((TransitionBlock*)callerTransitionBlock)->m_returnBlock) && isPointerAligned(returnValueToCopy) && (returnSize % sizeof(IntPtr) == 0)) RuntimeAugments.BulkMoveWithWriteBarrier(new IntPtr(&((TransitionBlock*)callerTransitionBlock)->m_returnBlock), new IntPtr(returnValueToCopy), returnSize); else Buffer.MemoryCopy(returnValueToCopy, &((TransitionBlock*)callerTransitionBlock)->m_returnBlock, returnSize, returnSize); } #endif } else { returnValueToCopy = (void*)&pinnedResultObject; #if _TARGET_X86_ ((TransitionBlock*)callerTransitionBlock)->m_returnBlock.returnValue = pinnedResultObject; #endif } } else if (conversionParams._conversionInfo.IsAnyDynamicInvokerThunk && !thValueType.IsNull()) { Debug.Assert(returnValueToCopy != null); if (!conversionParams._callerArgs.HasRetBuffArg() && conversionParams._calleeArgs.HasRetBuffArg()) returnValueToCopy = (void*)(new IntPtr(*((void**)returnValueToCopy)) + IntPtr.Size); // Need to box value type before returning it object returnValue = RuntimeAugments.Box(thValueType.GetRuntimeTypeHandle(), new IntPtr(returnValueToCopy)); CallConversionParameters.s_pinnedGCHandles._returnObjectHandle.Target = returnValue; pinnedResultObject = RuntimeAugments.GetRawAddrOfPinnedObject((IntPtr)CallConversionParameters.s_pinnedGCHandles._returnObjectHandle); returnValueToCopy = (void*)&pinnedResultObject; #if _TARGET_X86_ ((TransitionBlock*)callerTransitionBlock)->m_returnBlock.returnValue = pinnedResultObject; #endif } // Handle floating point returns // The previous fpReturnSize was the callee fpReturnSize. Now reset to the caller return size to handle // returning to the caller. fpReturnSize = conversionParams._callerArgs.GetFPReturnSize(); if (fpReturnSize != 0) { // We should never get here for delegate dynamic invoke thunks (the return type is always a boxed object) Debug.Assert(!conversionParams._conversionInfo.IsAnyDynamicInvokerThunk); #if CALLDESCR_FPARGREGSARERETURNREGS Debug.Assert(fpReturnSize <= sizeof(FloatArgumentRegisters)); memzeroPointerAligned(calleeTransitionBlock + TransitionBlock.GetOffsetOfFloatArgumentRegisters(), sizeof(FloatArgumentRegisters)); if (returnValueToCopy == null) { // object array delegate thunk result is a null object. We'll fill the return buffer with 'returnSize' zeros in that case Debug.Assert(conversionParams._conversionInfo.IsObjectArrayDelegateThunk); memzeroPointer(callerTransitionBlock + TransitionBlock.GetOffsetOfFloatArgumentRegisters(), (int)fpReturnSize); } else { Buffer.MemoryCopy(returnValueToCopy, callerTransitionBlock + TransitionBlock.GetOffsetOfFloatArgumentRegisters(), (int)fpReturnSize, (int)fpReturnSize); } conversionParams._invokeReturnValue = ReturnVoidReturnThunk; return; #else #if CALLDESCR_FPARGREGS #error Case not yet handled #endif Debug.Assert(fpReturnSize <= sizeof(ArgumentRegisters)); #if _TARGET_X86_ SetupCallerActualReturnData(callerTransitionBlock); t_NonArgRegisterReturnSpace = ((TransitionBlock*)callerTransitionBlock)->m_returnBlock; #else #error Platform not implemented #endif if (fpReturnSize == 4) { conversionParams._invokeReturnValue = ReturnFloatingPointReturn4Thunk; } else { conversionParams._invokeReturnValue = ReturnFloatingPointReturn8Thunk; } return; #endif } #if _TARGET_X86_ SetupCallerActualReturnData(callerTransitionBlock); t_NonArgRegisterReturnSpace = ((TransitionBlock*)callerTransitionBlock)->m_returnBlock; conversionParams._invokeReturnValue = ReturnIntegerPointReturnThunk; return; #else // If we reach here, we are returning value in the integer registers. if (conversionParams._conversionInfo.IsObjectArrayDelegateThunk && (!thValueType.IsNull())) { if (returnValueToCopy == null) { // object array delegate thunk result is a null object. We'll fill the return buffer with 'returnSize' zeros in that case memzeroPointer(callerTransitionBlock + TransitionBlock.GetOffsetOfArgumentRegisters(), returnSize); } else { if (isPointerAligned(callerTransitionBlock + TransitionBlock.GetOffsetOfArgumentRegisters()) && isPointerAligned(returnValueToCopy) && (returnSize % sizeof(IntPtr) == 0)) RuntimeAugments.BulkMoveWithWriteBarrier(new IntPtr(callerTransitionBlock + TransitionBlock.GetOffsetOfArgumentRegisters()), new IntPtr(returnValueToCopy), returnSize); else Buffer.MemoryCopy(returnValueToCopy, callerTransitionBlock + TransitionBlock.GetOffsetOfArgumentRegisters(), returnSize, returnSize); } } else { Debug.Assert(returnValueToCopy != null); Buffer.MemoryCopy(returnValueToCopy, callerTransitionBlock + TransitionBlock.GetOffsetOfArgumentRegisters(), ArchitectureConstants.ENREGISTERED_RETURNTYPE_INTEGER_MAXSIZE_PRIMITIVE, ArchitectureConstants.ENREGISTERED_RETURNTYPE_INTEGER_MAXSIZE_PRIMITIVE); } conversionParams._invokeReturnValue = ReturnIntegerPointReturnThunk; #endif } } #if CALLINGCONVENTION_CALLEE_POPS private static unsafe void SetupCallerPopArgument(byte* callerTransitionBlock, ArgIterator callerArgs) { int argStackPopSize = callerArgs.CbStackPop(); #if _TARGET_X86_ // In a callee pops architecture, we must specify how much stack space to pop to reset the frame // to the ReturnValue thunk. ((TransitionBlock*)callerTransitionBlock)->m_argumentRegisters.ecx = new IntPtr(argStackPopSize); #else #error handling of how callee pop is handled is not yet implemented for this platform #endif } #endif #if _TARGET_X86_ unsafe internal static void SetupCallerActualReturnData(byte* callerTransitionBlock) { // X86 needs to pass callee pop information to the return value thunks, so, since it // only has 2 argument registers and may/may not need to return 8 bytes of data, put the return // data in a seperate thread local store passed in the other available register (edx) fixed (ReturnBlock* actualReturnDataStructAddress = &t_NonArgRegisterReturnSpace) { ((TransitionBlock*)callerTransitionBlock)->m_argumentRegisters.edx = new IntPtr(actualReturnDataStructAddress); } } #endif } internal static class CallingConventionConverterLogger { [Conditional("CCCONVERTER_TRACE")] public static void WriteLine(string message) { Debug.WriteLine(message); } } }
using System; using System.Collections.Generic; using Newtonsoft.Json.Linq; namespace TMAPIv4 { public class ActivityRevision { protected JObject backing; protected Activity activity; /// <summary> /// Contains revision XML content. This is typically set up in the TaguchiMail UI, /// and normally includes an XML document structure based on RSS. However, /// if UI access is not required, this content can have an arbitrary (valid) /// structure; the only requirement is that the transform associated with the /// template convert this content into a valid intermediate MIME document. /// </summary> public string Content { get { return (string)backing["content"]; } set { backing["content"] = new JValue(value); } } /// <summary> /// If 'deployed', this revision is publicly available, otherwise only test /// events may use this revision. /// </summary> public string ApprovalStatus { get { return (string)backing["approval_status"]; } set { backing["approval_status"] = new JValue(value); } } /// <summary> /// ID of the activity revision record in the database. /// </summary> public string RecordId { get { return backing["id"].ToString(); } } /// <summary> /// Create a new activity revision, given a parent Activity and a content document /// (aka Source Document). /// </summary> /// <param name="activity"> /// A <see cref="Activity"/> /// </param> /// <param name="content"> /// A <see cref="System.String"/> /// </param> public ActivityRevision (Activity activity, string content) { this.backing = new JObject(); this.activity = activity; this.Content = content; } public ActivityRevision (Activity activity, JObject revision) { this.backing = revision; this.activity = activity; } } public class Activity : Record { protected JArray existingRevisions; public Activity (Context context) : base(context) { this.resourceType = "activity"; } /// <summary> /// ID of the TaguchiMail activity record. /// </summary> public string RecordId { get { return backing["id"].ToString(); } } /// <summary> /// External ID/reference, intended to store external application primary keys. /// /// If not null, this field must be unique. /// </summary> public string Ref { get { return (string)backing["ref"]; } set { backing["ref"] = new JValue(value); } } /// <summary> /// Activity name /// </summary> public string Name { get { return (string)backing["name"]; } set { backing["name"] = new JValue(value); } } /// <summary> /// This is matched up with Template types to determine what /// to show the user in the Suggested Templates/Other Templates sections /// </summary> public string Type { get { return (string)backing["type"]; } set { backing["type"] = new JValue(value); } } /// <summary> /// This can be any application-defined value /// </summary> public string Subtype { get { return (string)backing["subtype"]; } set { backing["subtype"] = new JValue(value); } } /// <summary> /// An expression representing the activity's target subscriber set /// </summary> public string TargetExpression { get { return (string)backing["target_expression"]; } set { backing["target_expression"] = new JValue(value); } } /// <summary> /// Approval workflow status of the activity; JSON object containing /// a list of locked-in depoyment settings used by the queue command. /// </summary> public string ApprovalStatus { get { return (string)backing["approval_status"]; } set { backing["approval_status"] = new JValue(value); } } /// <summary> /// Date/time at which this activity was deployed (or is scheduled to deploy) /// </summary> public string DeployDateTime { get { return (string)backing["date"]; } set { backing["date"] = new JValue(value); } } /// <summary> /// The ID of the Template this activity uses /// </summary> public string TemplateId { get { return (string)backing["template_id"]; } set { backing["template_id"] = new JValue(value); } } /// <summary> /// The ID of the Campaign to which this activity belongs /// </summary> public string CampaignId { get { return (string)backing["campaign_id"]; } set { backing["campaign_id"] = new JValue(value); } } /// <summary> /// Maximum deployment rate of this message, in messages per minute. If 0, /// the activity is suspended. Web pages (and other pull messages) ignore this value. /// </summary> public int Throttle { get { return (int)backing["throttle"]; } set { backing["throttle"] = new JValue(value); } } /// <summary> /// Arbitrary application XML data store. /// </summary> public string XmlData { get { return (string)backing["data"]; } set { backing["data"] = new JValue(value); } } /// <summary> /// Activity status; leave null if not used /// </summary> public string Status { get { return (string)backing["status"]; } } /// <summary> /// Latest activity revision content. If set, a new revision will be /// created upon activity create/update. /// </summary> public ActivityRevision LatestRevision { get { if (((JArray)backing["revisions"]).Count > 0) { return new ActivityRevision(this, (JObject)backing["revisions"][0]); } else if (existingRevisions.Count > 0) { return new ActivityRevision(this, (JObject)existingRevisions[0]); } else { return null; } } set { JObject revision = new JObject(); revision["content"] = new JValue(value.Content); if (((JArray)backing["revisions"]).Count > 0) { backing["revisions"][0] = revision; } else { ((JArray)backing["revisions"]).Add(revision); } } } /// <summary> /// Save this activity to the TaguchiMail database. /// </summary> public override void Update() { base.Update(); // avoid re-saving existing revisions this.backing["revisions"] = new JArray(); } /// <summary> /// Create this activity in the TaguchiMail database. /// </summary> public override void Create() { base.Create(); // need to move the existing revisions to avoid re-creating the same // ones if this object is saved again this.existingRevisions = (JArray)this.backing["revisions"]; this.backing["revisions"] = new JArray(); } /// <summary> /// Sends a proof message for an activity record to the list with the specified ID. /// </summary> /// <param name="proofListId"> /// A <see cref="System.String"/> indicating List ID of the proof list to which the messages will be sent. /// </param> /// <param name="subjectTag"> /// A <see cref="System.String"/> to display at the start of the subject line. /// </param> /// <param name="customMessage"> /// A <see cref="System.String"/> with a custom message which will be included in the proof header. /// </param> public virtual void Proof(string proofListId, string subjectTag, string customMessage) { JArray data = new JArray(); data.Add(new JObject()); data[0]["id"] = new JValue(this.RecordId); data[0]["list_id"] = new JValue(proofListId); data[0]["tag"] = new JValue(subjectTag); data[0]["message"] = new JValue(customMessage); context.MakeRequest(this.resourceType, "PROOF", this.backing["id"].ToString(), data.ToString(), null, null); } /// <summary> /// Sends a proof message for an activity record to a specific list. /// </summary> /// <param name="proofList"> /// A <see cref="SubscriberList"/> indicating the list to which the messages will be sent. /// </param> /// <param name="subjectTag"> /// A <see cref="System.String"/> to display at the start of the subject line. /// </param> /// <param name="customMessage"> /// A <see cref="System.String"/> with a custom message which will be included in the proof header. /// </param> public virtual void Proof(SubscriberList proofList, string subjectTag, string customMessage) { this.Proof(proofList.RecordId, subjectTag, customMessage); } /// <summary> /// Sends an approval request for an activity record to the list with the specified ID. /// </summary> /// <param name="approvalListId"> /// A <see cref="System.String"/> indicating List ID of the approval list to which the approval request will be sent. /// </param> /// <param name="subjectTag"> /// A <see cref="System.String"/> to display at the start of the subject line. /// </param> /// <param name="customMessage"> /// A <see cref="System.String"/> with a custom message which will be included in the approval header. /// </param> public virtual void RequestApproval(string approvalListId, string subjectTag, string customMessage) { JArray data = new JArray(); data.Add(new JObject()); data[0]["id"] = new JValue(this.RecordId); data[0]["list_id"] = new JValue(approvalListId); data[0]["tag"] = new JValue(subjectTag); data[0]["message"] = new JValue(customMessage); context.MakeRequest(this.resourceType, "APPROVAL", this.backing["id"].ToString(), data.ToString(), null, null); } /// <summary> /// Sends an approval request for an activity record to a specific list. /// </summary> /// <param name="approvalList"> /// The <see cref="SubscriberList"/> to which the approval request will be sent. /// </param> /// <param name="subjectTag"> /// A <see cref="System.String"/> to display at the start of the subject line. /// </param> /// <param name="customMessage"> /// A <see cref="System.String"/> with a custom message which will be included in the approval header. /// </param> public virtual void RequestApproval(SubscriberList approvalList, string subjectTag, string customMessage) { this.RequestApproval(approvalList.RecordId, subjectTag, customMessage); } /// <summary> /// Sets the approved flag for the activity with current settings. /// </summary> public virtual void Approve() { JArray data = new JArray(); data.Add(new JObject()); data[0]["revision.id"] = new JValue(this.LatestRevision.RecordId); data[0]["target_expression"] = new JValue(this.TargetExpression); data[0]["date"] = new JValue(this.DeployDateTime); context.MakeRequest(this.resourceType, "APPROVE", this.backing["id"].ToString(), data.ToString(), null, null); } /// <summary> /// Queues an activity for broadcast. /// </summary> /// <param name="throttle"> /// A <see cref="System.Int32"/> indicating the maximum number of messages to send per minute. /// </param> public virtual void Queue(int throttle) { JArray data = new JArray(); data.Add(new JObject()); data[0]["throttle"] = new JValue(throttle); data[0]["method"] = new JValue("queue"); context.MakeRequest(this.resourceType, "QUEUE", this.backing["id"].ToString(), data.ToString(), null, null); } /// <summary> /// Triggers the activity, causing it to be delivered to a specified list of subscribers. /// </summary> /// <param name="subscriberIds"> /// A <see cref="System.String[]"/> containing subscriber IDs to whom the message should be delivered. /// </param> /// <param name="requestContent"> /// A <see cref="System.String"/> of XML or JSON content for message customization. The requestContent document /// is available to the activity template's stylesheet, in addition to the revision's content. Should be /// null if unused. /// </param> /// <param name="test"> /// A <see cref="System.Boolean"/> determining whether or not to treat this as a test send. /// </param> public virtual void Trigger(string[] subscriberIds, string requestContent, bool test) { JArray data = new JArray(); data.Add(new JObject()); data[0]["id"] = new JValue(this.RecordId); data[0]["test"] = new JValue(test ? 1 : 0); data[0]["request_content"] = new JValue(requestContent); data[0]["conditions"] = new JArray(subscriberIds); context.MakeRequest(this.resourceType, "TRIGGER", this.backing["id"].ToString(), data.ToString(), null, null); } /// <summary> /// Triggers the activity, causing it to be delivered to a specified list of subscribers. /// </summary> /// <param name="subscriberIds"> /// A <see cref="Subscriber[]"/> containing subscribers to whom the message should be delivered. /// </param> /// <param name="requestContent"> /// A <see cref="System.String"/> of XML or JSON content for message customization. The requestContent document /// is available to the activity template's stylesheet, in addition to the revision's content. Should be /// null if unused. /// </param> /// <param name="test"> /// A <see cref="System.Boolean"/> determining whether or not to treat this as a test send. /// </param> public virtual void Trigger(Subscriber[] subscribers, string requestContent, bool test) { List<string> subscriberIds = new List<string>(); foreach (Subscriber s in subscribers) { subscriberIds.Add(s.RecordId); } this.Trigger(subscriberIds.ToArray(), requestContent, test); } /// <summary> /// Triggers the activity, causing it to be delivered to all subscribers matching a target expression /// </summary> /// <param name="targetExpression"> /// A target expression <see cref="System.String"/> identifying the /// </param> /// <param name="requestContent"> /// A <see cref="System.String"/> of XML or JSON content for message customization. The requestContent document /// is available to the activity template's stylesheet, in addition to the revision's content. Should be /// null if unused. /// </param> /// <param name="test"> /// A <see cref="System.Boolean"/> determining whether or not to treat this as a test send. /// </param> public virtual void Trigger(string targetExpression, string requestContent, bool test) { JArray data = new JArray(); data.Add(new JObject()); data[0]["id"] = new JValue(this.RecordId); data[0]["test"] = new JValue(test ? 1 : 0); data[0]["request_content"] = new JValue(requestContent); data[0]["conditions"] = new JObject(); data[0]["conditions"]["expression"] = new JValue(targetExpression); context.MakeRequest(this.resourceType, "TRIGGER", this.backing["id"].ToString(), data.ToString(), null, null); } /// <summary> /// Retrieve a single Activity based on its TaguchiMail identifier. /// </summary> /// <param name="context"> /// A <see cref="Context"/> object determining the TM instance and organization to query. /// </param> /// <param name="recordId"> /// A <see cref="System.String"/> containing the list's unique TaguchiMail identifier. /// </param> /// <returns> /// The <see cref="Activity"/> with that ID. /// </returns> public static Activity Get(Context context, string recordId, Dictionary<string, string> parameters) { JArray results = JArray.Parse(context.MakeRequest("activity", "GET", recordId, null, parameters, null)); Activity rec = new Activity(context); rec.backing = (JObject)results[0]; rec.existingRevisions = (JArray)rec.backing["revisions"]; // clear out existing revisions so they're not sent back to the server on update rec.backing["revisions"] = new JArray(); return rec; } /// <summary> /// Retrieve a single Activity based on its TaguchiMail identifier, with its latest revision content. /// </summary> /// <param name="context"> /// A <see cref="Context"/> object determining the TM instance and organization to query. /// </param> /// <param name="recordId"> /// A <see cref="System.String"/> containing the activity's unique TaguchiMail identifier. /// </param> /// <returns> /// The <see cref="Activity"/> with that ID. /// </returns> public static Activity GetWithContent(Context context, string recordId, Dictionary<string, string> parameters) { Dictionary<string, string> newParams = new Dictionary<string, string>(parameters); newParams.Add("revisions", "latest"); return Activity.Get(context, recordId, newParams); } /// <summary> /// Retrieve a list of Activities based on a query. /// </summary> /// <param name="context"> /// A <see cref="Context"/> object determining the TM instance and organization to query. /// </param> /// <param name="sort"> /// A <see cref="System.String"/> indicating which of the record's fields should be used to /// sort the output. /// </param> /// <param name="order"> /// A <see cref="System.String"/> containing either 'asc' or 'desc', indicating whether the /// result list should be returned in ascending or descending order. /// </param> /// <param name="offset"> /// A <see cref="System.Int32"/> indicating the index of the first record to be returned in /// the list. /// </param> /// <param name="limit"> /// A <see cref="System.Int32"/> indicating the maximum number of records to return. /// </param> /// <param name="query"> /// An <see cref="System.String[]"/> of query predicates, each of the form: /// [field]-[operator]-[value] /// where [field] is one of the defined resource fields, [operator] is one of the below-listed comparison operators, /// and [value] is a string value to which the field should be compared. /// /// Supported operators: /// * eq: mapped to SQL '=', tests for equality between [field] and [value] (case-sensitive for strings); /// * neq: mapped to SQL '!=', tests for inequality between [field] and [value] (case-sensitive for strings); /// * lt: mapped to SQL '&lt;', tests if [field] is less than [value]; /// * gt: mapped to SQL '&gt;', tests if [field] is greater than [value]; /// * lte: mapped to SQL '&lt;=', tests if [field] is less than or equal to [value]; /// * gte: mapped to SQL '&gt;=', tests if [field] is greater than or equal to [value]; /// * re: mapped to PostgreSQL '~', interprets [value] as a POSIX regular expression and tests if [field] matches it; /// * rei: mapped to PostgreSQL '~*', performs a case-insensitive POSIX regular expression match; /// * like: mapped to SQL 'LIKE' (case-sensitive); /// * is: mapped to SQL 'IS', should be used to test for NULL values in the database as [field]-eq-null is always false; /// * nt: mapped to SQL 'IS NOT', should be used to test for NOT NULL values in the database as [field]-neq-null is always false. /// </param> /// <returns> /// A <see cref="Activity[]"/> matching the query. /// </returns> public static Activity[] Find(Context context, string sort, string order, int offset, int limit, string[] query) { Dictionary<string,string> parameters = new Dictionary<string, string>(); parameters["revisions"] = "latest"; parameters["sort"] = sort; parameters["order"] = order; parameters["offset"] = offset.ToString(); parameters["limit"] = limit.ToString(); JArray results = JArray.Parse(context.MakeRequest("activity", "GET", null, null, parameters, query)); List<Activity> recordSet = new List<Activity>(); foreach (var result in results) { Activity rec = new Activity(context); rec.backing = (JObject)result; rec.existingRevisions = (JArray)rec.backing["revisions"]; // clear out existing revisions so they're not sent back to the server on update rec.backing["revisions"] = new JArray(); recordSet.Add(rec); } return recordSet.ToArray(); } } }