context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// Copyright 2018 Esri. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. // You may obtain a copy of the License at: http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific // language governing permissions and limitations under the License. using Esri.ArcGISRuntime.Data; using Esri.ArcGISRuntime.Geometry; using Esri.ArcGISRuntime.Mapping; using Esri.ArcGISRuntime.Symbology; using Esri.ArcGISRuntime.Tasks.NetworkAnalysis; using Esri.ArcGISRuntime.UI; using System; using System.Collections.Generic; using System.Drawing; using System.Linq; namespace ArcGISRuntime.WPF.Samples.ClosestFacilityStatic { [ArcGISRuntime.Samples.Shared.Attributes.Sample( name: "Find closest facility to multiple incidents (service)", category: "Network analysis", description: "Find routes from several locations to the respective closest facility.", instructions: "Click the button to solve and display the route from each incident (fire) to the nearest facility (fire station).", tags: new[] { "incident", "network analysis", "route", "search" })] public partial class ClosestFacilityStatic { // Used to display route between incident and facility to mapview. private List<SimpleLineSymbol> _routeSymbols; // Solves task to find closest route between an incident and a facility. private ClosestFacilityTask _task; // Table of all facilities. private ServiceFeatureTable _facilityTable; // Table of all incidents. private ServiceFeatureTable _incidentTable; // Feature layer for facilities. private FeatureLayer _facilityLayer; // Feature layer for incidents. private FeatureLayer _incidentLayer; // Uri for facilities feature service. private Uri _facilityUri = new Uri("https://services2.arcgis.com/ZQgQTuoyBrtmoGdP/ArcGIS/rest/services/San_Diego_Facilities/FeatureServer/0"); // Uri for incident feature service. private Uri _incidentUri = new Uri("https://services2.arcgis.com/ZQgQTuoyBrtmoGdP/ArcGIS/rest/services/San_Diego_Incidents/FeatureServer/0"); // Uri for the closest facility service. private Uri _closestFacilityUri = new Uri("https://sampleserver6.arcgisonline.com/arcgis/rest/services/NetworkAnalysis/SanDiego/NAServer/ClosestFacility"); public ClosestFacilityStatic() { InitializeComponent(); // Create the map and graphics overlays. Initialize(); } private async void Initialize() { try { // Construct the map and set the MapView.Map property. MyMapView.Map = new Map(BasemapStyle.ArcGISLightGray); // Add a graphics overlay to MyMapView. (Will be used later to display routes) MyMapView.GraphicsOverlays.Add(new GraphicsOverlay()); // Create a ClosestFacilityTask using the San Diego Uri. _task = await ClosestFacilityTask.CreateAsync(_closestFacilityUri); // Create a symbol for displaying facilities. PictureMarkerSymbol facilitySymbol = new PictureMarkerSymbol(new Uri("https://static.arcgis.com/images/Symbols/SafetyHealth/FireStation.png")) { Height = 30, Width = 30 }; // Incident symbol. PictureMarkerSymbol incidentSymbol = new PictureMarkerSymbol(new Uri("https://static.arcgis.com/images/Symbols/SafetyHealth/esriCrimeMarker_56_Gradient.png")) { Height = 30, Width = 30 }; // Create a list of line symbols to show unique routes. Different colors help make different routes visually distinguishable. _routeSymbols = new List<SimpleLineSymbol>() { new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, Color.FromArgb(125, 25, 45, 85), 5.0f), new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, Color.FromArgb(125, 35, 65, 120), 5.0f), new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, Color.FromArgb(125, 55, 100, 190), 5.0f), new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, Color.FromArgb(125, 75, 140, 255), 5.0f) }; // Create a table for facilities using the FeatureServer. _facilityTable = new ServiceFeatureTable(_facilityUri); // Create a feature layer from the table. _facilityLayer = new FeatureLayer(_facilityTable) { Renderer = new SimpleRenderer(facilitySymbol) }; // Create a table for facilities using the FeatureServer. _incidentTable = new ServiceFeatureTable(_incidentUri); // Create a feature layer from the table. _incidentLayer = new FeatureLayer(_incidentTable) { Renderer = new SimpleRenderer(incidentSymbol) }; // Add the layers to the map. MyMapView.Map.OperationalLayers.Add(_facilityLayer); MyMapView.Map.OperationalLayers.Add(_incidentLayer); // Wait for both layers to load. await _facilityLayer.LoadAsync(); await _incidentLayer.LoadAsync(); // Zoom to the combined extent of both layers. Envelope fullExtent = GeometryEngine.CombineExtents(_facilityLayer.FullExtent, _incidentLayer.FullExtent); await MyMapView.SetViewpointGeometryAsync(fullExtent, 50); // Enable the solve button. SolveRoutesButton.IsEnabled = true; } catch (Exception exception) { System.Windows.MessageBox.Show("An exception has occurred.\n" + exception.Message, "Sample error"); } } private async void SolveRoutesClick(object sender, EventArgs e) { // Holds locations of hospitals around San Diego. List<Facility> facilities = new List<Facility>(); // Holds locations of hospitals around San Diego. List<Incident> incidents = new List<Incident>(); // Create query parameters to select all features. QueryParameters queryParams = new QueryParameters() { WhereClause = "1=1" }; // Query all features in the facility table. FeatureQueryResult facilityResult = await _facilityTable.QueryFeaturesAsync(queryParams); // Add all of the query results to facilities as new Facility objects. facilities.AddRange(facilityResult.ToList().Select(feature => new Facility((MapPoint)feature.Geometry))); // Query all features in the incident table. FeatureQueryResult incidentResult = await _incidentTable.QueryFeaturesAsync(queryParams); // Add all of the query results to facilities as new Incident objects. incidents.AddRange(incidentResult.ToList().Select(feature => new Incident((MapPoint)feature.Geometry))); // Set facilities and incident in parameters. ClosestFacilityParameters closestFacilityParameters = await _task.CreateDefaultParametersAsync(); closestFacilityParameters.SetFacilities(facilities); closestFacilityParameters.SetIncidents(incidents); try { // Use the task to solve for the closest facility. ClosestFacilityResult result = await _task.SolveClosestFacilityAsync(closestFacilityParameters); for (int i = 0; i < incidents.Count; i++) { // Get the index of the closest facility to incident. (i) is the index of the incident, [0] is the index of the closest facility. int closestFacility = result.GetRankedFacilityIndexes(i)[0]; // Get the route to the closest facility. ClosestFacilityRoute route = result.GetRoute(closestFacility, i); // Display the route on the graphics overlay. MyMapView.GraphicsOverlays[0].Graphics.Add(new Graphic(route.RouteGeometry, _routeSymbols[i % _routeSymbols.Count])); } // Disable the solve button. SolveRoutesButton.IsEnabled = false; // Enable the reset button. ResetButton.IsEnabled = true; } catch (Esri.ArcGISRuntime.Http.ArcGISWebException exception) { System.Windows.MessageBox.Show("An ArcGIS web exception occurred.\n" + exception.Message, "Sample error"); } } private void ResetClick(object sender, EventArgs e) { // Clear the route graphics. MyMapView.GraphicsOverlays[0].Graphics.Clear(); // Reset the buttons. SolveRoutesButton.IsEnabled = true; ResetButton.IsEnabled = false; } } }
namespace nHydrate.DslPackage.Forms { partial class DatabaseConnectionControl { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.grpConnectionString = new System.Windows.Forms.GroupBox(); this.lblConnectionString = new System.Windows.Forms.Label(); this.txtConnectionString = new nHydrate.DslPackage.Forms.CueTextBox(); this.opt2 = new System.Windows.Forms.RadioButton(); this.grpProperties = new System.Windows.Forms.GroupBox(); this.chkWinAuth = new System.Windows.Forms.CheckBox(); this.lblServer = new System.Windows.Forms.Label(); this.txtPWD = new nHydrate.DslPackage.Forms.CueTextBox(); this.opt1 = new System.Windows.Forms.RadioButton(); this.lblDatabase = new System.Windows.Forms.Label(); this.txtUID = new nHydrate.DslPackage.Forms.CueTextBox(); this.lblUID = new System.Windows.Forms.Label(); this.txtDatabase = new nHydrate.DslPackage.Forms.CueTextBox(); this.lblPWD = new System.Windows.Forms.Label(); this.txtServer = new nHydrate.DslPackage.Forms.CueTextBox(); this.grpConnectionString.SuspendLayout(); this.grpProperties.SuspendLayout(); this.SuspendLayout(); // // grpConnectionString // this.grpConnectionString.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.grpConnectionString.Controls.Add(this.lblConnectionString); this.grpConnectionString.Controls.Add(this.txtConnectionString); this.grpConnectionString.Controls.Add(this.opt2); this.grpConnectionString.Location = new System.Drawing.Point(5, 175); this.grpConnectionString.Name = "grpConnectionString"; this.grpConnectionString.Size = new System.Drawing.Size(395, 57); this.grpConnectionString.TabIndex = 20; this.grpConnectionString.TabStop = false; // // lblConnectionString // this.lblConnectionString.AutoSize = true; this.lblConnectionString.Location = new System.Drawing.Point(19, 27); this.lblConnectionString.Name = "lblConnectionString"; this.lblConnectionString.Size = new System.Drawing.Size(112, 13); this.lblConnectionString.TabIndex = 5; this.lblConnectionString.Text = "Database connection:"; // // txtConnectionString // this.txtConnectionString.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.txtConnectionString.Cue = "<Enter Connectionstring>"; this.txtConnectionString.Location = new System.Drawing.Point(136, 24); this.txtConnectionString.Name = "txtConnectionString"; this.txtConnectionString.Size = new System.Drawing.Size(245, 20); this.txtConnectionString.TabIndex = 8; // // opt2 // this.opt2.AutoSize = true; this.opt2.Location = new System.Drawing.Point(6, 0); this.opt2.Name = "opt2"; this.opt2.Size = new System.Drawing.Size(107, 17); this.opt2.TabIndex = 7; this.opt2.TabStop = true; this.opt2.Text = "Connection string"; this.opt2.UseVisualStyleBackColor = true; this.opt2.CheckedChanged += new System.EventHandler(this.opt2_CheckedChanged); // // grpProperties // this.grpProperties.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.grpProperties.Controls.Add(this.chkWinAuth); this.grpProperties.Controls.Add(this.lblServer); this.grpProperties.Controls.Add(this.txtPWD); this.grpProperties.Controls.Add(this.opt1); this.grpProperties.Controls.Add(this.lblDatabase); this.grpProperties.Controls.Add(this.txtUID); this.grpProperties.Controls.Add(this.lblUID); this.grpProperties.Controls.Add(this.txtDatabase); this.grpProperties.Controls.Add(this.lblPWD); this.grpProperties.Controls.Add(this.txtServer); this.grpProperties.Location = new System.Drawing.Point(5, 7); this.grpProperties.Name = "grpProperties"; this.grpProperties.Size = new System.Drawing.Size(395, 162); this.grpProperties.TabIndex = 19; this.grpProperties.TabStop = false; // // chkWinAuth // this.chkWinAuth.AutoSize = true; this.chkWinAuth.Checked = true; this.chkWinAuth.CheckState = System.Windows.Forms.CheckState.Checked; this.chkWinAuth.Location = new System.Drawing.Point(137, 132); this.chkWinAuth.Name = "chkWinAuth"; this.chkWinAuth.Size = new System.Drawing.Size(163, 17); this.chkWinAuth.TabIndex = 6; this.chkWinAuth.Text = "Use Windows Authentication"; this.chkWinAuth.UseVisualStyleBackColor = true; this.chkWinAuth.CheckedChanged += new System.EventHandler(this.chkWinAuth_CheckedChanged); // // lblServer // this.lblServer.AutoSize = true; this.lblServer.Location = new System.Drawing.Point(17, 28); this.lblServer.Name = "lblServer"; this.lblServer.Size = new System.Drawing.Size(41, 13); this.lblServer.TabIndex = 9; this.lblServer.Text = "Server:"; // // txtPWD // this.txtPWD.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.txtPWD.Cue = "<Enter Database Password>"; this.txtPWD.Location = new System.Drawing.Point(134, 105); this.txtPWD.Name = "txtPWD"; this.txtPWD.Size = new System.Drawing.Size(245, 20); this.txtPWD.TabIndex = 5; this.txtPWD.UseSystemPasswordChar = true; // // opt1 // this.opt1.AutoSize = true; this.opt1.Checked = true; this.opt1.Location = new System.Drawing.Point(6, 0); this.opt1.Name = "opt1"; this.opt1.Size = new System.Drawing.Size(120, 17); this.opt1.TabIndex = 0; this.opt1.TabStop = true; this.opt1.Text = "Database properties"; this.opt1.UseVisualStyleBackColor = true; this.opt1.CheckedChanged += new System.EventHandler(this.opt1_CheckedChanged); // // lblDatabase // this.lblDatabase.AutoSize = true; this.lblDatabase.Location = new System.Drawing.Point(17, 53); this.lblDatabase.Name = "lblDatabase"; this.lblDatabase.Size = new System.Drawing.Size(56, 13); this.lblDatabase.TabIndex = 10; this.lblDatabase.Text = "Database:"; // // txtUID // this.txtUID.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.txtUID.Cue = "<Enter Database User>"; this.txtUID.Location = new System.Drawing.Point(134, 79); this.txtUID.Name = "txtUID"; this.txtUID.Size = new System.Drawing.Size(245, 20); this.txtUID.TabIndex = 4; // // lblUID // this.lblUID.AutoSize = true; this.lblUID.Location = new System.Drawing.Point(17, 78); this.lblUID.Name = "lblUID"; this.lblUID.Size = new System.Drawing.Size(63, 13); this.lblUID.TabIndex = 11; this.lblUID.Text = "User Name:"; // // txtDatabase // this.txtDatabase.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.txtDatabase.Cue = "<Enter Database Name>"; this.txtDatabase.Location = new System.Drawing.Point(134, 53); this.txtDatabase.Name = "txtDatabase"; this.txtDatabase.Size = new System.Drawing.Size(245, 20); this.txtDatabase.TabIndex = 3; // // lblPWD // this.lblPWD.AutoSize = true; this.lblPWD.Location = new System.Drawing.Point(17, 108); this.lblPWD.Name = "lblPWD"; this.lblPWD.Size = new System.Drawing.Size(56, 13); this.lblPWD.TabIndex = 12; this.lblPWD.Text = "Password:"; // // txtServer // this.txtServer.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.txtServer.Cue = "<Enter Server Name/IP>"; this.txtServer.Location = new System.Drawing.Point(134, 28); this.txtServer.Name = "txtServer"; this.txtServer.Size = new System.Drawing.Size(245, 20); this.txtServer.TabIndex = 2; // // DatabaseConnectionControl // this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.None; this.Controls.Add(this.grpConnectionString); this.Controls.Add(this.grpProperties); this.Name = "DatabaseConnectionControl"; this.Size = new System.Drawing.Size(405, 242); this.grpConnectionString.ResumeLayout(false); this.grpConnectionString.PerformLayout(); this.grpProperties.ResumeLayout(false); this.grpProperties.PerformLayout(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.GroupBox grpConnectionString; private System.Windows.Forms.Label lblConnectionString; private nHydrate.DslPackage.Forms.CueTextBox txtConnectionString; private System.Windows.Forms.RadioButton opt2; private System.Windows.Forms.GroupBox grpProperties; private System.Windows.Forms.CheckBox chkWinAuth; private System.Windows.Forms.Label lblServer; private nHydrate.DslPackage.Forms.CueTextBox txtPWD; private System.Windows.Forms.RadioButton opt1; private System.Windows.Forms.Label lblDatabase; private nHydrate.DslPackage.Forms.CueTextBox txtUID; private System.Windows.Forms.Label lblUID; private nHydrate.DslPackage.Forms.CueTextBox txtDatabase; private System.Windows.Forms.Label lblPWD; private nHydrate.DslPackage.Forms.CueTextBox txtServer; } }
// Copyright (c) The Avalonia Project. All rights reserved. // Licensed under the MIT license. See licence.md file in the project root for full license information. using System; using System.Collections.Generic; using System.Linq; using System.Reactive.Disposables; using System.Reactive.Linq; using Avalonia.Layout; using Avalonia.VisualTree; namespace Avalonia.Interactivity { /// <summary> /// Base class for objects that raise routed events. /// </summary> public class Interactive : Layoutable, IInteractive { private Dictionary<RoutedEvent, List<EventSubscription>> _eventHandlers; /// <summary> /// Gets the interactive parent of the object for bubbling and tunnelling events. /// </summary> IInteractive IInteractive.InteractiveParent => ((IVisual)this).VisualParent as IInteractive; private Dictionary<RoutedEvent, List<EventSubscription>> EventHandlers { get { return _eventHandlers ?? (_eventHandlers = new Dictionary<RoutedEvent, List<EventSubscription>>()); } } /// <summary> /// Adds a handler for the specified routed event. /// </summary> /// <param name="routedEvent">The routed event.</param> /// <param name="handler">The handler.</param> /// <param name="routes">The routing strategies to listen to.</param> /// <param name="handledEventsToo">Whether handled events should also be listened for.</param> /// <returns>A disposable that terminates the event subscription.</returns> public IDisposable AddHandler( RoutedEvent routedEvent, Delegate handler, RoutingStrategies routes = RoutingStrategies.Direct | RoutingStrategies.Bubble, bool handledEventsToo = false) { Contract.Requires<ArgumentNullException>(routedEvent != null); Contract.Requires<ArgumentNullException>(handler != null); List<EventSubscription> subscriptions; if (!EventHandlers.TryGetValue(routedEvent, out subscriptions)) { subscriptions = new List<EventSubscription>(); EventHandlers.Add(routedEvent, subscriptions); } var sub = new EventSubscription { Handler = handler, Routes = routes, AlsoIfHandled = handledEventsToo, }; subscriptions.Add(sub); return Disposable.Create(() => subscriptions.Remove(sub)); } /// <summary> /// Adds a handler for the specified routed event. /// </summary> /// <typeparam name="TEventArgs">The type of the event's args.</typeparam> /// <param name="routedEvent">The routed event.</param> /// <param name="handler">The handler.</param> /// <param name="routes">The routing strategies to listen to.</param> /// <param name="handledEventsToo">Whether handled events should also be listened for.</param> /// <returns>A disposable that terminates the event subscription.</returns> public IDisposable AddHandler<TEventArgs>( RoutedEvent<TEventArgs> routedEvent, EventHandler<TEventArgs> handler, RoutingStrategies routes = RoutingStrategies.Direct | RoutingStrategies.Bubble, bool handledEventsToo = false) where TEventArgs : RoutedEventArgs { return AddHandler(routedEvent, (Delegate)handler, routes, handledEventsToo); } /// <summary> /// Removes a handler for the specified routed event. /// </summary> /// <param name="routedEvent">The routed event.</param> /// <param name="handler">The handler.</param> public void RemoveHandler(RoutedEvent routedEvent, Delegate handler) { Contract.Requires<ArgumentNullException>(routedEvent != null); Contract.Requires<ArgumentNullException>(handler != null); List<EventSubscription> subscriptions = null; if (_eventHandlers?.TryGetValue(routedEvent, out subscriptions) == true) { subscriptions.RemoveAll(x => x.Handler == handler); } } /// <summary> /// Removes a handler for the specified routed event. /// </summary> /// <typeparam name="TEventArgs">The type of the event's args.</typeparam> /// <param name="routedEvent">The routed event.</param> /// <param name="handler">The handler.</param> public void RemoveHandler<TEventArgs>(RoutedEvent<TEventArgs> routedEvent, EventHandler<TEventArgs> handler) where TEventArgs : RoutedEventArgs { RemoveHandler(routedEvent, (Delegate)handler); } /// <summary> /// Raises a routed event. /// </summary> /// <param name="e">The event args.</param> public void RaiseEvent(RoutedEventArgs e) { Contract.Requires<ArgumentNullException>(e != null); e.Source = e.Source ?? this; if (e.RoutedEvent.RoutingStrategies == RoutingStrategies.Direct) { e.Route = RoutingStrategies.Direct; RaiseEventImpl(e); e.RoutedEvent.InvokeRouteFinished(e); } if ((e.RoutedEvent.RoutingStrategies & RoutingStrategies.Tunnel) != 0) { TunnelEvent(e); e.RoutedEvent.InvokeRouteFinished(e); } if ((e.RoutedEvent.RoutingStrategies & RoutingStrategies.Bubble) != 0) { BubbleEvent(e); e.RoutedEvent.InvokeRouteFinished(e); } } /// <summary> /// Bubbles an event. /// </summary> /// <param name="e">The event args.</param> private void BubbleEvent(RoutedEventArgs e) { Contract.Requires<ArgumentNullException>(e != null); e.Route = RoutingStrategies.Bubble; foreach (var target in this.GetBubbleEventRoute()) { ((Interactive)target).RaiseEventImpl(e); } } /// <summary> /// Tunnels an event. /// </summary> /// <param name="e">The event args.</param> private void TunnelEvent(RoutedEventArgs e) { Contract.Requires<ArgumentNullException>(e != null); e.Route = RoutingStrategies.Tunnel; foreach (var target in this.GetTunnelEventRoute()) { ((Interactive)target).RaiseEventImpl(e); } } /// <summary> /// Carries out the actual invocation of an event on this object. /// </summary> /// <param name="e">The event args.</param> private void RaiseEventImpl(RoutedEventArgs e) { Contract.Requires<ArgumentNullException>(e != null); e.RoutedEvent.InvokeRaised(this, e); List<EventSubscription> subscriptions = null; if (_eventHandlers?.TryGetValue(e.RoutedEvent, out subscriptions) == true) { foreach (var sub in subscriptions.ToList()) { bool correctRoute = (e.Route & sub.Routes) != 0; bool notFinished = !e.Handled || sub.AlsoIfHandled; if (correctRoute && notFinished) { sub.Handler.DynamicInvoke(this, e); } } } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Xml; using OLEDB.Test.ModuleCore; namespace XmlReaderTest.Common { public partial class TCErrorCondition : TCXMLReaderBaseGeneral { // Type is XmlReaderTest.Common.TCErrorCondition // Test Case public override void AddChildren() { // for function v1 { this.AddChild(new CVariation(v1) { Attribute = new Variation("new XmlTextReader(null)") { Param = 17 } }); this.AddChild(new CVariation(v1) { Attribute = new Variation("XmlReader.Create((Stream)null, null, (XmlParserContext)null)") { Param = 9 } }); this.AddChild(new CVariation(v1) { Attribute = new Variation("XmlReader.Create((string)null, null, null)") { Param = 10 } }); this.AddChild(new CVariation(v1) { Attribute = new Variation("XmlReader.Create((TextReader)null, null, (string)null)") { Param = 11 } }); this.AddChild(new CVariation(v1) { Attribute = new Variation("XmlReader.Create((TextReader)null, null, (XmlParserContext)null)") { Param = 12 } }); this.AddChild(new CVariation(v1) { Attribute = new Variation("new XmlNamespaceManager(null)") { Param = 13 } }); this.AddChild(new CVariation(v1) { Attribute = new Variation("XmlReader.IsName(null)") { Param = 14 } }); this.AddChild(new CVariation(v1) { Attribute = new Variation("XmlReader.IsNameToken(null)") { Param = 15 } }); this.AddChild(new CVariation(v1) { Attribute = new Variation("new XmlValidatingReader(null)") { Param = 16 } }); this.AddChild(new CVariation(v1) { Attribute = new Variation("XmlReader.Create((string)null)") { Param = 1 } }); this.AddChild(new CVariation(v1) { Attribute = new Variation("new XmlNodeReader(null)") { Param = 18 } }); this.AddChild(new CVariation(v1) { Attribute = new Variation("XmlReader.Create((TextReader)null)") { Param = 2 } }); this.AddChild(new CVariation(v1) { Attribute = new Variation("XmlReader.Create((Stream)null)") { Param = 3 } }); this.AddChild(new CVariation(v1) { Attribute = new Variation("XmlReader.Create((string)null, null)") { Param = 4 } }); this.AddChild(new CVariation(v1) { Attribute = new Variation("XmlReader.Create((TextReader)null, null)") { Param = 5 } }); this.AddChild(new CVariation(v1) { Attribute = new Variation("XmlReader.Create((Stream)null, null)") { Param = 6 } }); this.AddChild(new CVariation(v1) { Attribute = new Variation("XmlReader.Create((XmlReader)null, null)") { Param = 7 } }); this.AddChild(new CVariation(v1) { Attribute = new Variation("XmlReader.Create((Stream)null, null, (string) null)") { Param = 8 } }); } // for function v1a { this.AddChild(new CVariation(v1a) { Attribute = new Variation("XmlReader.Create(String.Empty)") { Param = 1 } }); this.AddChild(new CVariation(v1a) { Attribute = new Variation("XmlReader.Create(String.Empty, null)") { Param = 2 } }); this.AddChild(new CVariation(v1a) { Attribute = new Variation("XmlReader.Create(String.Empty, null, (XmlParserContext)null)") { Param = 3 } }); } // for function v1b { this.AddChild(new CVariation(v1b) { Attribute = new Variation("XmlReader.Create(TextReader, XmlReaderSettings, XmlParserContext)") { Param = 12 } }); this.AddChild(new CVariation(v1b) { Attribute = new Variation("XmlReader.Create(String)") { Param = 2 } }); this.AddChild(new CVariation(v1b) { Attribute = new Variation("XmlReader.Create(TextReader)") { Param = 3 } }); this.AddChild(new CVariation(v1b) { Attribute = new Variation("XmlReader.Create(String, XmlReaderSettings)") { Param = 5 } }); this.AddChild(new CVariation(v1b) { Attribute = new Variation("XmlReader.Create(TextReader, XmlReaderSettings)") { Param = 6 } }); this.AddChild(new CVariation(v1b) { Attribute = new Variation("XmlReader.Create(XmlReader, XmlReaderSettings)") { Param = 7 } }); this.AddChild(new CVariation(v1b) { Attribute = new Variation("XmlReader.Create(String, XmlReaderSettings, XmlParserContext)") { Param = 10 } }); this.AddChild(new CVariation(v1b) { Attribute = new Variation("XmlReader.Create(TextReader, XmlReaderSettings, string)") { Param = 11 } }); } // for function v2 { this.AddChild(new CVariation(v2) { Attribute = new Variation("XmlReader.ReadContentAsBase64(null, 0, 0)") { Param = 7 } }); this.AddChild(new CVariation(v2) { Attribute = new Variation("XmlReader.ReadElementContentAsLong('a', null)") { Param = 26 } }); this.AddChild(new CVariation(v2) { Attribute = new Variation("XmlReader.ReadElementContentAsObject(null, null)") { Param = 27 } }); this.AddChild(new CVariation(v2) { Attribute = new Variation("XmlReader.ReadElementContentAsObject('a', null)") { Param = 28 } }); this.AddChild(new CVariation(v2) { Attribute = new Variation("XmlReader.ReadElementContentAsString(null, null)") { Param = 29 } }); this.AddChild(new CVariation(v2) { Attribute = new Variation("XmlReader.ReadElementContentAsString('a', null)") { Param = 30 } }); this.AddChild(new CVariation(v2) { Attribute = new Variation("XmlReader.ReadToDescendant(null)") { Param = 31 } }); this.AddChild(new CVariation(v2) { Attribute = new Variation("XmlReader.ReadToDescendant(null, null)") { Param = 32 } }); this.AddChild(new CVariation(v2) { Attribute = new Variation("XmlReader.ReadToDescendant('a', null)") { Param = 33 } }); this.AddChild(new CVariation(v2) { Attribute = new Variation("XmlReader.ReadToFollowing(null)") { Param = 34 } }); this.AddChild(new CVariation(v2) { Attribute = new Variation("XmlReader.ReadToFollowing(null, null)") { Param = 35 } }); this.AddChild(new CVariation(v2) { Attribute = new Variation("XmlReader.ReadToFollowing('a', null)") { Param = 36 } }); this.AddChild(new CVariation(v2) { Attribute = new Variation("XmlReader.ReadToNextSibling(null)") { Param = 37 } }); this.AddChild(new CVariation(v2) { Attribute = new Variation("XmlReader.ReadToNextSibling(null, null)") { Param = 38 } }); this.AddChild(new CVariation(v2) { Attribute = new Variation("XmlReader.ReadToNextSibling('a', null)") { Param = 39 } }); this.AddChild(new CVariation(v2) { Attribute = new Variation("XmlReader.ReadValueChunk(null, 0, 0)") { Param = 40 } }); this.AddChild(new CVariation(v2) { Attribute = new Variation("XmlReader.ReadContentAs(null, null)") { Param = 41 } }); this.AddChild(new CVariation(v2) { Attribute = new Variation("XmlReader.ReadContentAsBinHex(null, 0, 0)") { Param = 8 } }); this.AddChild(new CVariation(v2) { Attribute = new Variation("XmlReader.ReadElementContentAs(null, null, null, null)") { Param = 9 } }); this.AddChild(new CVariation(v2) { Attribute = new Variation("XmlReader.ReadElementContentAs(null, null, 'a', null)") { Param = 10 } }); this.AddChild(new CVariation(v2) { Attribute = new Variation("XmlReader.ReadElementContentAsBase64(null, 0, 0)") { Param = 11 } }); this.AddChild(new CVariation(v2) { Attribute = new Variation("XmlReader.ReadElementContentAsBinHex(null, 0, 0)") { Param = 12 } }); this.AddChild(new CVariation(v2) { Attribute = new Variation("XmlReader.ReadElementContentAsBoolean(null, null)") { Param = 13 } }); this.AddChild(new CVariation(v2) { Attribute = new Variation("XmlReader.ReadElementContentAsBoolean('a', null)") { Param = 14 } }); this.AddChild(new CVariation(v2) { Attribute = new Variation("XmlReader.ReadElementContentAsDecimal(null, null)") { Param = 17 } }); this.AddChild(new CVariation(v2) { Attribute = new Variation("XmlReader.ReadElementContentAsDecimal('a', null)") { Param = 18 } }); this.AddChild(new CVariation(v2) { Attribute = new Variation("XmlReader.ReadElementContentAsDouble(null, null)") { Param = 19 } }); this.AddChild(new CVariation(v2) { Attribute = new Variation("XmlReader.ReadElementContentAsDouble('a', null)") { Param = 20 } }); this.AddChild(new CVariation(v2) { Attribute = new Variation("XmlReader.ReadElementContentAsFloat(null, null)") { Param = 21 } }); this.AddChild(new CVariation(v2) { Attribute = new Variation("XmlReader.ReadElementContentAsFloat('a', null)") { Param = 22 } }); this.AddChild(new CVariation(v2) { Attribute = new Variation("XmlReader.ReadElementContentAsInt(null, null)") { Param = 23 } }); this.AddChild(new CVariation(v2) { Attribute = new Variation("XmlReader.ReadElementContentAsInt('a', null)") { Param = 24 } }); this.AddChild(new CVariation(v2) { Attribute = new Variation("XmlReader.ReadElementContentAsLong(null, null)") { Param = 25 } }); this.AddChild(new CVariation(v2) { Attribute = new Variation("XmlReader[null])") { Param = 1 } }); this.AddChild(new CVariation(v2) { Attribute = new Variation("XmlReader[null, null]") { Param = 2 } }); this.AddChild(new CVariation(v2) { Attribute = new Variation("XmlReader.GetAttribute(null)") { Param = 3 } }); this.AddChild(new CVariation(v2) { Attribute = new Variation("XmlReader.GetAttribute(null, null)") { Param = 4 } }); this.AddChild(new CVariation(v2) { Attribute = new Variation("XmlReader.MoveToAttribute(null)") { Param = 5 } }); this.AddChild(new CVariation(v2) { Attribute = new Variation("XmlReader.MoveToAttribute(null, null)") { Param = 6 } }); } // for function v3 { this.AddChild(new CVariation(v3) { Attribute = new Variation("XmlReader.GetAttribute(-1)") { Param = 3 } }); this.AddChild(new CVariation(v3) { Attribute = new Variation("XmlReader.GetAttribute(0)") { Param = 4 } }); this.AddChild(new CVariation(v3) { Attribute = new Variation("XmlReader.MoveToAttribute(-1)") { Param = 5 } }); this.AddChild(new CVariation(v3) { Attribute = new Variation("XmlReader.MoveToAttribute(0)") { Param = 6 } }); this.AddChild(new CVariation(v3) { Attribute = new Variation("XmlReader[0]") { Param = 2 } }); this.AddChild(new CVariation(v3) { Attribute = new Variation("XmlReader[-1]") { Param = 1 } }); } // for function v4 { this.AddChild(new CVariation(v4) { Attribute = new Variation("nsm.AddNamespace('p', null)") { Param = 1 } }); this.AddChild(new CVariation(v4) { Attribute = new Variation("nsm.RemoveNamespace('p', null)") { Param = 2 } }); } // for function v5 { this.AddChild(new CVariation(v5) { Attribute = new Variation("nsm.RemoveNamespace(null, 'ns1')") { Param = 2 } }); this.AddChild(new CVariation(v5) { Attribute = new Variation("nsm.AddNamespace(null, 'ns1')") { Param = 1 } }); } // for function v6 { this.AddChild(new CVariation(v6) { Attribute = new Variation("DataReader.ReadContentAs(null, nsm)") }); } // for function v7 { this.AddChild(new CVariation(v7) { Attribute = new Variation("nsm.AddNamespace('xml', 'ns1')") }); } // for function V8 { this.AddChild(new CVariation(V8) { Attribute = new Variation("Test Integrity of all values after Error") }); } // for function V9a { this.AddChild(new CVariation(V9a) { Attribute = new Variation("2.Test Integrity of all values after Dispose") }); } // for function v10 { this.AddChild(new CVariation(v10) { Attribute = new Variation("XmlCharType::IsName, IsNmToken") }); } // for function v11 { this.AddChild(new CVariation(v11) { Attribute = new Variation("XmlReader.ReadElementContentAs(String.Empty, String.Empty, String.Empty, String.Empty)") { Param = 9 } }); this.AddChild(new CVariation(v11) { Attribute = new Variation("XmlReader.ReadElementContentAsString('a', String.Empty)") { Param = 30 } }); this.AddChild(new CVariation(v11) { Attribute = new Variation("XmlReader.ReadToDescendant(String.Empty)") { Param = 31 } }); this.AddChild(new CVariation(v11) { Attribute = new Variation("XmlReader.ReadToDescendant(String.Empty, String.Empty)") { Param = 32 } }); this.AddChild(new CVariation(v11) { Attribute = new Variation("XmlReader.ReadToDescendant('a', String.Empty)") { Param = 33 } }); this.AddChild(new CVariation(v11) { Attribute = new Variation("XmlReader.ReadToFollowing(String.Empty)") { Param = 34 } }); this.AddChild(new CVariation(v11) { Attribute = new Variation("XmlReader.ReadToFollowing(String.Empty, String.Empty)") { Param = 35 } }); this.AddChild(new CVariation(v11) { Attribute = new Variation("XmlReader.ReadToFollowing('a', String.Empty)") { Param = 36 } }); this.AddChild(new CVariation(v11) { Attribute = new Variation("XmlReader.ReadToNextSibling(String.Empty)") { Param = 37 } }); this.AddChild(new CVariation(v11) { Attribute = new Variation("XmlReader.ReadToNextSibling(String.Empty, String.Empty)") { Param = 38 } }); this.AddChild(new CVariation(v11) { Attribute = new Variation("XmlReader.ReadToNextSibling('a', String.Empty)") { Param = 39 } }); this.AddChild(new CVariation(v11) { Attribute = new Variation("XmlReader.ReadElementContentAsString(String.Empty, String.Empty)") { Param = 29 } }); this.AddChild(new CVariation(v11) { Attribute = new Variation("XmlReader[String.Empty, String.Empty]") { Param = 2 } }); this.AddChild(new CVariation(v11) { Attribute = new Variation("XmlReader.GetAttribute(String.Empty)") { Param = 3 } }); this.AddChild(new CVariation(v11) { Attribute = new Variation("XmlReader.GetAttribute(String.Empty, String.Empty)") { Param = 4 } }); this.AddChild(new CVariation(v11) { Attribute = new Variation("XmlReader.MoveToAttribute(String.Empty)") { Param = 5 } }); this.AddChild(new CVariation(v11) { Attribute = new Variation("XmlReader.MoveToAttribute(String.Empty, String.Empty)") { Param = 6 } }); this.AddChild(new CVariation(v11) { Attribute = new Variation("XmlReader[String.Empty])") { Param = 1 } }); this.AddChild(new CVariation(v11) { Attribute = new Variation("XmlReader.ReadElementContentAs(String.Empty, String.Empty, 'a', String.Empty)") { Param = 10 } }); this.AddChild(new CVariation(v11) { Attribute = new Variation("XmlReader.ReadElementContentAsBoolean(String.Empty, String.Empty)") { Param = 13 } }); this.AddChild(new CVariation(v11) { Attribute = new Variation("XmlReader.ReadElementContentAsBoolean('a', String.Empty)") { Param = 14 } }); this.AddChild(new CVariation(v11) { Attribute = new Variation("XmlReader.ReadElementContentAsDecimal(String.Empty, String.Empty)") { Param = 17 } }); this.AddChild(new CVariation(v11) { Attribute = new Variation("XmlReader.ReadElementContentAsDecimal('a', String.Empty)") { Param = 18 } }); this.AddChild(new CVariation(v11) { Attribute = new Variation("XmlReader.ReadElementContentAsDouble(String.Empty, String.Empty)") { Param = 19 } }); this.AddChild(new CVariation(v11) { Attribute = new Variation("XmlReader.ReadElementContentAsDouble('a', String.Empty)") { Param = 20 } }); this.AddChild(new CVariation(v11) { Attribute = new Variation("XmlReader.ReadElementContentAsFloat(String.Empty, String.Empty)") { Param = 21 } }); this.AddChild(new CVariation(v11) { Attribute = new Variation("XmlReader.ReadElementContentAsFloat('a', String.Empty)") { Param = 22 } }); this.AddChild(new CVariation(v11) { Attribute = new Variation("XmlReader.ReadElementContentAsInt(String.Empty, String.Empty)") { Param = 23 } }); this.AddChild(new CVariation(v11) { Attribute = new Variation("XmlReader.ReadElementContentAsInt('a', String.Empty)") { Param = 24 } }); this.AddChild(new CVariation(v11) { Attribute = new Variation("XmlReader.ReadElementContentAsLong(String.Empty, String.Empty)") { Param = 25 } }); this.AddChild(new CVariation(v11) { Attribute = new Variation("XmlReader.ReadElementContentAsLong('a', String.Empty)") { Param = 26 } }); this.AddChild(new CVariation(v11) { Attribute = new Variation("XmlReader.ReadElementContentAsObject(String.Empty, String.Empty)") { Param = 27 } }); this.AddChild(new CVariation(v11) { Attribute = new Variation("XmlReader.ReadElementContentAsObject('a', String.Empty)") { Param = 28 } }); } // for function var13 { this.AddChild(new CVariation(var13) { Attribute = new Variation("XmlReaderSettings.LineNumberOffset - invalid values") { Param = 1 } }); this.AddChild(new CVariation(var13) { Attribute = new Variation("XmlReaderSettings.LinePositionOffset - invalid values") { Param = 2 } }); } // for function v14 { this.AddChild(new CVariation(v14) { Attribute = new Variation("XmlReader.ReadValueChunk(c, 0, -1)") { Param = 9 } }); this.AddChild(new CVariation(v14) { Attribute = new Variation("XmlReader.ReadElementContentAsBase64(b, -1, 0)") { Param = 7 } }); this.AddChild(new CVariation(v14) { Attribute = new Variation("XmlReader.ReadElementContentAsBinHex(b, -1, 0)") { Param = 8 } }); this.AddChild(new CVariation(v14) { Attribute = new Variation("XmlReader.ReadValueChunk(c, -1, 1)") { Param = 16 } }); this.AddChild(new CVariation(v14) { Attribute = new Variation("XmlReader.ReadContentAsBinHex(b, -1, 0)") { Param = 2 } }); this.AddChild(new CVariation(v14) { Attribute = new Variation("XmlReader.ReadContentAsBase64(b, 0, -1)") { Param = 3 } }); this.AddChild(new CVariation(v14) { Attribute = new Variation("XmlReader.ReadContentAsBinHex(b, 0, -1)") { Param = 4 } }); this.AddChild(new CVariation(v14) { Attribute = new Variation("XmlReader.ReadContentAsBase64(b, 0, 2)") { Param = 5 } }); this.AddChild(new CVariation(v14) { Attribute = new Variation("XmlReader.ReadContentAsBinHex(b, 0, 2)") { Param = 6 } }); this.AddChild(new CVariation(v14) { Attribute = new Variation("XmlReader.ReadContentAsBase64(b, -1, 0)") { Param = 1 } }); this.AddChild(new CVariation(v14) { Attribute = new Variation("XmlReader.ReadElementContentAsBase64(b, 0, -1)") { Param = 10 } }); this.AddChild(new CVariation(v14) { Attribute = new Variation("XmlReader.ReadElementContentAsBinHex(b, 0, -1)") { Param = 11 } }); this.AddChild(new CVariation(v14) { Attribute = new Variation("XmlReader.ReadValueChunk(c, 0, -1)") { Param = 12 } }); this.AddChild(new CVariation(v14) { Attribute = new Variation("XmlReader.ReadElementContentAsBase64(b, 0, 2)") { Param = 13 } }); this.AddChild(new CVariation(v14) { Attribute = new Variation("XmlReader.ReadElementContentAsBinHex(b, 0, 2)") { Param = 14 } }); this.AddChild(new CVariation(v14) { Attribute = new Variation("XmlReader.ReadValueChunk(c, 0, 2)") { Param = 15 } }); } // for function var15 { this.AddChild(new CVariation(var15) { Attribute = new Variation("DataReader.Settings.MaxCharactersFromEntities - readonly") { Param = 12 } }); this.AddChild(new CVariation(var15) { Attribute = new Variation("DataReader.Settings.IgnoreWhitespace - readonly") { Param = 8 } }); this.AddChild(new CVariation(var15) { Attribute = new Variation("DataReader.Settings.DtdProcessing - readonly") { Param = 13 } }); this.AddChild(new CVariation(var15) { Attribute = new Variation("DataReader.Settings.MaxCharactersInDocument - readonly") { Param = 9 } }); this.AddChild(new CVariation(var15) { Attribute = new Variation("DataReader.Settings.IgnoreComments - readonly") { Param = 6 } }); this.AddChild(new CVariation(var15) { Attribute = new Variation("DataReader.Settings.IgnoreProcessingInstructions - readonly") { Param = 7 } }); this.AddChild(new CVariation(var15) { Attribute = new Variation("DataReader.Settings.LineNumberOffset - readonly") { Param = 1 } }); this.AddChild(new CVariation(var15) { Attribute = new Variation("DataReader.Settings.LinePositionOffset - readonly") { Param = 2 } }); this.AddChild(new CVariation(var15) { Attribute = new Variation("DataReader.Settings.CheckCharacters - readonly") { Param = 3 } }); this.AddChild(new CVariation(var15) { Attribute = new Variation("DataReader.Settings.CloseInput - readonly") { Param = 4 } }); this.AddChild(new CVariation(var15) { Attribute = new Variation("DataReader.Settings.ConformanceLevel - readonly") { Param = 5 } }); } // for function V16 { this.AddChild(new CVariation(V16) { Attribute = new Variation("XmlReader.ReadElementContentAsLong(a,b)") { Param = 31 } }); this.AddChild(new CVariation(V16) { Attribute = new Variation("XmlReader.ReadElementContentAsDouble()") { Param = 26 } }); this.AddChild(new CVariation(V16) { Attribute = new Variation("XmlReader.ReadElementContentAsFloat(a,b)") { Param = 27 } }); this.AddChild(new CVariation(V16) { Attribute = new Variation("XmlReader.ReadElementContentAsFloat()") { Param = 28 } }); this.AddChild(new CVariation(V16) { Attribute = new Variation("XmlReader.ReadElementContentAsInt(a,b)") { Param = 29 } }); this.AddChild(new CVariation(V16) { Attribute = new Variation("XmlReader.ReadElementContentAsInt()") { Param = 30 } }); this.AddChild(new CVariation(V16) { Attribute = new Variation("Readcontentas in close state and call ReadContentAsBase64") { Param = 1 } }); this.AddChild(new CVariation(V16) { Attribute = new Variation("XmlReader.ReadElementContentAsLong()") { Param = 32 } }); this.AddChild(new CVariation(V16) { Attribute = new Variation("XmlReader.ReadElementContentAsObject(a,b)") { Param = 33 } }); this.AddChild(new CVariation(V16) { Attribute = new Variation("XmlReader.ReadElementContentAsString(a,b)") { Param = 34 } }); this.AddChild(new CVariation(V16) { Attribute = new Variation("XmlReader.ReadToDescendant(a)") { Param = 35 } }); this.AddChild(new CVariation(V16) { Attribute = new Variation("XmlReader.ReadToFollowing(a)") { Param = 36 } }); this.AddChild(new CVariation(V16) { Attribute = new Variation("XmlReader.ReadToNextSibling(a)") { Param = 37 } }); this.AddChild(new CVariation(V16) { Attribute = new Variation("XmlReader.ReadAttributeValue()") { Param = 38 } }); this.AddChild(new CVariation(V16) { Attribute = new Variation("XmlReader.ResolveEntity()") { Param = 39 } }); this.AddChild(new CVariation(V16) { Attribute = new Variation("XmlReader.ReadElementContentAs(typeof(String), null)") { Param = 12 } }); this.AddChild(new CVariation(V16) { Attribute = new Variation("XmlReader.ReadElementContentAsObject()") { Param = 13 } }); this.AddChild(new CVariation(V16) { Attribute = new Variation("XmlReader.ReadElementContentAsDouble(a,b)") { Param = 25 } }); this.AddChild(new CVariation(V16) { Attribute = new Variation("Readcontentas in close state and call ReadElementContentAsBase64") { Param = 3 } }); this.AddChild(new CVariation(V16) { Attribute = new Variation("Readcontentas in close state and call ReadElementContentAsBinHex") { Param = 4 } }); this.AddChild(new CVariation(V16) { Attribute = new Variation("Readcontentas in close state and call ReadValueChunk") { Param = 5 } }); this.AddChild(new CVariation(V16) { Attribute = new Variation("XmlReader[a])") { Param = 6 } }); this.AddChild(new CVariation(V16) { Attribute = new Variation("XmlReader[a, b]") { Param = 7 } }); this.AddChild(new CVariation(V16) { Attribute = new Variation("XmlReader.GetAttribute(a)") { Param = 8 } }); this.AddChild(new CVariation(V16) { Attribute = new Variation("XmlReader.GetAttribute(a, b)") { Param = 9 } }); this.AddChild(new CVariation(V16) { Attribute = new Variation("XmlReader.MoveToAttribute(a)") { Param = 10 } }); this.AddChild(new CVariation(V16) { Attribute = new Variation("XmlReader.MoveToAttribute(a, b)") { Param = 11 } }); this.AddChild(new CVariation(V16) { Attribute = new Variation("XmlReader.ReadElementContentAs(typeof(String), null)") { Param = 18 } }); this.AddChild(new CVariation(V16) { Attribute = new Variation("XmlReader.ReadElementContentAsDecimal()") { Param = 24 } }); this.AddChild(new CVariation(V16) { Attribute = new Variation("XmlReader.ReadElementContentAsString()") { Param = 14 } }); this.AddChild(new CVariation(V16) { Attribute = new Variation("XmlReader.ReadToDescendant(a, b)") { Param = 15 } }); this.AddChild(new CVariation(V16) { Attribute = new Variation("XmlReader.ReadToFollowing(a, b)") { Param = 16 } }); this.AddChild(new CVariation(V16) { Attribute = new Variation("XmlReader.ReadToNextSibling(a, b)") { Param = 17 } }); this.AddChild(new CVariation(V16) { Attribute = new Variation("Readcontentas in close state and call ReadContentAsBinHex") { Param = 2 } }); this.AddChild(new CVariation(V16) { Attribute = new Variation("XmlReader.ReadElementContentAsBoolean(a,b)") { Param = 19 } }); this.AddChild(new CVariation(V16) { Attribute = new Variation("XmlReader.ReadElementContentAsBoolean()") { Param = 20 } }); this.AddChild(new CVariation(V16) { Attribute = new Variation("XmlReader.ReadElementContentAsDecimal(a,b)") { Param = 23 } }); } } } }
using System; using System.ComponentModel.Composition; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; using NuGet.Common; namespace NuGet.Commands { [Export(typeof(HelpCommand))] [Command(typeof(NuGetResources), "help", "HelpCommandDescription", AltName = "?", MaxArgs = 1, UsageSummaryResourceName = "HelpCommandUsageSummary", UsageDescriptionResourceName = "HelpCommandUsageDescription", UsageExampleResourceName = "HelpCommandUsageExamples")] public class HelpCommand : Command { private readonly string _commandExe; private readonly ICommandManager _commandManager; private readonly string _helpUrl; private readonly string _productName; private string CommandName { get { if (Arguments != null && Arguments.Count > 0) { return Arguments[0]; } return null; } } [Option(typeof(NuGetResources), "HelpCommandAll")] public bool All { get; set; } [Option(typeof(NuGetResources), "HelpCommandMarkdown")] public bool Markdown { get; set; } [ImportingConstructor] public HelpCommand(ICommandManager commandManager) : this(commandManager, Assembly.GetExecutingAssembly().GetName().Name, Assembly.GetExecutingAssembly().GetName().Name, CommandLineConstants.NuGetDocsCommandLineReference) { } [SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", MessageId = "3#", Justification = "We don't use the Url for anything besides printing, so it's ok to represent it as a string.")] public HelpCommand(ICommandManager commandManager, string commandExe, string productName, string helpUrl) { _commandManager = commandManager; _commandExe = commandExe; _productName = productName; _helpUrl = helpUrl; } public override void ExecuteCommand() { if (!String.IsNullOrEmpty(CommandName)) { ViewHelpForCommand(CommandName); } else if (All && Markdown) { ViewMarkdownHelp(); } else if (All) { ViewHelpForAllCommands(); } else { ViewHelp(); } } public void ViewHelp() { Console.WriteLine("{0} Version: {1}", _productName, this.GetType().Assembly.GetName().Version); Console.WriteLine("usage: {0} <command> [args] [options] ", _commandExe); Console.WriteLine("Type '{0} help <command>' for help on a specific command.", _commandExe); Console.WriteLine(); Console.WriteLine("Available commands:"); Console.WriteLine(); var commands = from c in _commandManager.GetCommands() orderby c.CommandAttribute.CommandName select c.CommandAttribute; // Padding for printing int maxWidth = commands.Max(c => c.CommandName.Length + GetAltText(c.AltName).Length); foreach (var command in commands) { PrintCommand(maxWidth, command); } if (_helpUrl != null) { Console.WriteLine(); Console.WriteLine("For more information, visit {0}", _helpUrl); } } private void PrintCommand(int maxWidth, CommandAttribute commandAttribute) { // Write out the command name left justified with the max command's width's padding Console.Write(" {0, -" + maxWidth + "} ", GetCommandText(commandAttribute)); // Starting index of the description int descriptionPadding = maxWidth + 4; Console.PrintJustified(descriptionPadding, commandAttribute.Description); } private static string GetCommandText(CommandAttribute commandAttribute) { return commandAttribute.CommandName + GetAltText(commandAttribute.AltName); } public void ViewHelpForCommand(string commandName) { ICommand command = _commandManager.GetCommand(commandName); CommandAttribute attribute = command.CommandAttribute; Console.WriteLine("usage: {0} {1} {2}", _commandExe, attribute.CommandName, attribute.UsageSummary); Console.WriteLine(); if (!String.IsNullOrEmpty(attribute.AltName)) { Console.WriteLine("alias: {0}", attribute.AltName); Console.WriteLine(); } Console.WriteLine(attribute.Description); Console.WriteLine(); if (attribute.UsageDescription != null) { const int padding = 5; Console.PrintJustified(padding, attribute.UsageDescription); Console.WriteLine(); } var options = _commandManager.GetCommandOptions(command); if (options.Count > 0) { Console.WriteLine("options:"); Console.WriteLine(); // Get the max option width. +2 for showing + against multivalued properties int maxOptionWidth = options.Max(o => o.Value.Name.Length) + 2; // Get the max altname option width int maxAltOptionWidth = options.Max(o => (o.Key.AltName ?? String.Empty).Length); foreach (var o in options) { Console.Write(" -{0, -" + (maxOptionWidth + 2) + "}", o.Value.Name + (TypeHelper.IsMultiValuedProperty(o.Value) ? " +" : String.Empty)); Console.Write(" {0, -" + (maxAltOptionWidth + 4) + "}", GetAltText(o.Key.AltName)); Console.PrintJustified((10 + maxAltOptionWidth + maxOptionWidth), o.Key.Description); } if (_helpUrl != null) { Console.WriteLine(); Console.WriteLine("For more information, visit {0}", _helpUrl); } Console.WriteLine(); } } private void ViewHelpForAllCommands() { var commands = from c in _commandManager.GetCommands() orderby c.CommandAttribute.CommandName select c.CommandAttribute; TextInfo info = CultureInfo.CurrentCulture.TextInfo; foreach (var command in commands) { Console.WriteLine(info.ToTitleCase(command.CommandName) + " Command"); ViewHelpForCommand(command.CommandName); } } /// <summary> /// Prints help for all commands in markdown format. /// </summary> private void ViewMarkdownHelp() { var commands = from c in _commandManager.GetCommands() orderby c.CommandAttribute.CommandName select c; foreach (var command in commands) { var template = new HelpCommandMarkdownTemplate { CommandAttribute = command.CommandAttribute, Options = from item in _commandManager.GetCommandOptions(command) select new { Name = item.Value.Name, Description = item.Key.Description } }; Console.WriteLine(template.TransformText()); } } private static string GetAltText(string altNameText) { if (String.IsNullOrEmpty(altNameText)) { return String.Empty; } return String.Format(CultureInfo.CurrentCulture, " ({0})", altNameText); } } }
// 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.Buffers; using System.IO; using System.Runtime.InteropServices; using System.Security.Cryptography.Asn1; using Internal.Cryptography; namespace System.Security.Cryptography { public abstract partial class RSA : AsymmetricAlgorithm { public static new RSA Create(string algName) { return (RSA)CryptoConfig.CreateFromName(algName); } public static RSA Create(int keySizeInBits) { RSA rsa = Create(); try { rsa.KeySize = keySizeInBits; return rsa; } catch { rsa.Dispose(); throw; } } public static RSA Create(RSAParameters parameters) { RSA rsa = Create(); try { rsa.ImportParameters(parameters); return rsa; } catch { rsa.Dispose(); throw; } } public abstract RSAParameters ExportParameters(bool includePrivateParameters); public abstract void ImportParameters(RSAParameters parameters); public virtual byte[] Encrypt(byte[] data, RSAEncryptionPadding padding) => throw DerivedClassMustOverride(); public virtual byte[] Decrypt(byte[] data, RSAEncryptionPadding padding) => throw DerivedClassMustOverride(); public virtual byte[] SignHash(byte[] hash, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) => throw DerivedClassMustOverride(); public virtual bool VerifyHash(byte[] hash, byte[] signature, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) => throw DerivedClassMustOverride(); protected virtual byte[] HashData(byte[] data, int offset, int count, HashAlgorithmName hashAlgorithm) => throw DerivedClassMustOverride(); protected virtual byte[] HashData(Stream data, HashAlgorithmName hashAlgorithm) => throw DerivedClassMustOverride(); public virtual bool TryDecrypt(ReadOnlySpan<byte> data, Span<byte> destination, RSAEncryptionPadding padding, out int bytesWritten) { byte[] result = Decrypt(data.ToArray(), padding); if (destination.Length >= result.Length) { new ReadOnlySpan<byte>(result).CopyTo(destination); bytesWritten = result.Length; return true; } bytesWritten = 0; return false; } public virtual bool TryEncrypt(ReadOnlySpan<byte> data, Span<byte> destination, RSAEncryptionPadding padding, out int bytesWritten) { byte[] result = Encrypt(data.ToArray(), padding); if (destination.Length >= result.Length) { new ReadOnlySpan<byte>(result).CopyTo(destination); bytesWritten = result.Length; return true; } bytesWritten = 0; return false; } protected virtual bool TryHashData(ReadOnlySpan<byte> data, Span<byte> destination, HashAlgorithmName hashAlgorithm, out int bytesWritten) { byte[] result; byte[] array = ArrayPool<byte>.Shared.Rent(data.Length); try { data.CopyTo(array); result = HashData(array, 0, data.Length, hashAlgorithm); } finally { Array.Clear(array, 0, data.Length); ArrayPool<byte>.Shared.Return(array); } if (destination.Length >= result.Length) { new ReadOnlySpan<byte>(result).CopyTo(destination); bytesWritten = result.Length; return true; } bytesWritten = 0; return false; } public virtual bool TrySignHash(ReadOnlySpan<byte> hash, Span<byte> destination, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding, out int bytesWritten) { byte[] result = SignHash(hash.ToArray(), hashAlgorithm, padding); if (destination.Length >= result.Length) { new ReadOnlySpan<byte>(result).CopyTo(destination); bytesWritten = result.Length; return true; } bytesWritten = 0; return false; } public virtual bool VerifyHash(ReadOnlySpan<byte> hash, ReadOnlySpan<byte> signature, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) => VerifyHash(hash.ToArray(), signature.ToArray(), hashAlgorithm, padding); private static Exception DerivedClassMustOverride() => new NotImplementedException(SR.NotSupported_SubclassOverride); public virtual byte[] DecryptValue(byte[] rgb) => throw new NotSupportedException(SR.NotSupported_Method); // Same as Desktop public virtual byte[] EncryptValue(byte[] rgb) => throw new NotSupportedException(SR.NotSupported_Method); // Same as Desktop public byte[] SignData(byte[] data, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) { if (data == null) { throw new ArgumentNullException(nameof(data)); } return SignData(data, 0, data.Length, hashAlgorithm, padding); } public virtual byte[] SignData( byte[] data, int offset, int count, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) { if (data == null) throw new ArgumentNullException(nameof(data)); if (offset < 0 || offset > data.Length) throw new ArgumentOutOfRangeException(nameof(offset)); if (count < 0 || count > data.Length - offset) throw new ArgumentOutOfRangeException(nameof(count)); if (string.IsNullOrEmpty(hashAlgorithm.Name)) throw HashAlgorithmNameNullOrEmpty(); if (padding == null) throw new ArgumentNullException(nameof(padding)); byte[] hash = HashData(data, offset, count, hashAlgorithm); return SignHash(hash, hashAlgorithm, padding); } public virtual byte[] SignData(Stream data, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) { if (data == null) throw new ArgumentNullException(nameof(data)); if (string.IsNullOrEmpty(hashAlgorithm.Name)) throw HashAlgorithmNameNullOrEmpty(); if (padding == null) throw new ArgumentNullException(nameof(padding)); byte[] hash = HashData(data, hashAlgorithm); return SignHash(hash, hashAlgorithm, padding); } public virtual bool TrySignData(ReadOnlySpan<byte> data, Span<byte> destination, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding, out int bytesWritten) { if (string.IsNullOrEmpty(hashAlgorithm.Name)) { throw HashAlgorithmNameNullOrEmpty(); } if (padding == null) { throw new ArgumentNullException(nameof(padding)); } if (TryHashData(data, destination, hashAlgorithm, out int hashLength) && TrySignHash(destination.Slice(0, hashLength), destination, hashAlgorithm, padding, out bytesWritten)) { return true; } bytesWritten = 0; return false; } public bool VerifyData(byte[] data, byte[] signature, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) { if (data == null) throw new ArgumentNullException(nameof(data)); return VerifyData(data, 0, data.Length, signature, hashAlgorithm, padding); } public virtual bool VerifyData( byte[] data, int offset, int count, byte[] signature, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) { if (data == null) throw new ArgumentNullException(nameof(data)); if (offset < 0 || offset > data.Length) throw new ArgumentOutOfRangeException(nameof(offset)); if (count < 0 || count > data.Length - offset) throw new ArgumentOutOfRangeException(nameof(count)); if (signature == null) throw new ArgumentNullException(nameof(signature)); if (string.IsNullOrEmpty(hashAlgorithm.Name)) throw HashAlgorithmNameNullOrEmpty(); if (padding == null) throw new ArgumentNullException(nameof(padding)); byte[] hash = HashData(data, offset, count, hashAlgorithm); return VerifyHash(hash, signature, hashAlgorithm, padding); } public bool VerifyData(Stream data, byte[] signature, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) { if (data == null) throw new ArgumentNullException(nameof(data)); if (signature == null) throw new ArgumentNullException(nameof(signature)); if (string.IsNullOrEmpty(hashAlgorithm.Name)) throw HashAlgorithmNameNullOrEmpty(); if (padding == null) throw new ArgumentNullException(nameof(padding)); byte[] hash = HashData(data, hashAlgorithm); return VerifyHash(hash, signature, hashAlgorithm, padding); } public virtual bool VerifyData(ReadOnlySpan<byte> data, ReadOnlySpan<byte> signature, HashAlgorithmName hashAlgorithm, RSASignaturePadding padding) { if (string.IsNullOrEmpty(hashAlgorithm.Name)) { throw HashAlgorithmNameNullOrEmpty(); } if (padding == null) { throw new ArgumentNullException(nameof(padding)); } for (int i = 256; ; i = checked(i * 2)) { int hashLength = 0; byte[] hash = ArrayPool<byte>.Shared.Rent(i); try { if (TryHashData(data, hash, hashAlgorithm, out hashLength)) { return VerifyHash(new ReadOnlySpan<byte>(hash, 0, hashLength), signature, hashAlgorithm, padding); } } finally { Array.Clear(hash, 0, hashLength); ArrayPool<byte>.Shared.Return(hash); } } } public virtual byte[] ExportRSAPrivateKey() { using (AsnWriter pkcs1PrivateKey = WritePkcs1PrivateKey()) { return pkcs1PrivateKey.Encode(); } } public virtual bool TryExportRSAPrivateKey(Span<byte> destination, out int bytesWritten) { using (AsnWriter pkcs1PrivateKey = WritePkcs1PrivateKey()) { return pkcs1PrivateKey.TryEncode(destination, out bytesWritten); } } public virtual byte[] ExportRSAPublicKey() { using (AsnWriter pkcs1PublicKey = WritePkcs1PublicKey()) { return pkcs1PublicKey.Encode(); } } public virtual bool TryExportRSAPublicKey(Span<byte> destination, out int bytesWritten) { using (AsnWriter pkcs1PublicKey = WritePkcs1PublicKey()) { return pkcs1PublicKey.TryEncode(destination, out bytesWritten); } } public override unsafe bool TryExportSubjectPublicKeyInfo(Span<byte> destination, out int bytesWritten) { // The PKCS1 RSAPublicKey format is just the modulus (KeySize bits) and Exponent (usually 3 bytes), // with each field having up to 7 bytes of overhead and then up to 6 extra bytes of overhead for the // SEQUENCE tag. // // So KeySize / 4 is ideally enough to start. int rentSize = KeySize / 4; while (true) { byte[] rented = ArrayPool<byte>.Shared.Rent(rentSize); rentSize = rented.Length; int pkcs1Size = 0; fixed (byte* rentPtr = rented) { try { if (!TryExportRSAPublicKey(rented, out pkcs1Size)) { rentSize = checked(rentSize * 2); continue; } using (AsnWriter writer = RSAKeyFormatHelper.WriteSubjectPublicKeyInfo(rented.AsSpan(0, pkcs1Size))) { return writer.TryEncode(destination, out bytesWritten); } } finally { CryptographicOperations.ZeroMemory(rented.AsSpan(0, pkcs1Size)); ArrayPool<byte>.Shared.Return(rented); } } } } public override bool TryExportPkcs8PrivateKey(Span<byte> destination, out int bytesWritten) { using (AsnWriter writer = WritePkcs8PrivateKey()) { return writer.TryEncode(destination, out bytesWritten); } } private unsafe AsnWriter WritePkcs8PrivateKey() { // A PKCS1 RSAPrivateKey is the Modulus (KeySize bits), D (~KeySize bits) // P, Q, DP, DQ, InverseQ (all ~KeySize/2 bits) // Each field can have up to 7 bytes of overhead, and then another 9 bytes // of fixed overhead. // So it should fit in 5 * KeySizeInBytes, but Exponent is a wildcard. int rentSize = checked(5 * KeySize / 8); while (true) { byte[] rented = ArrayPool<byte>.Shared.Rent(rentSize); rentSize = rented.Length; int pkcs1Size = 0; fixed (byte* rentPtr = rented) { try { if (!TryExportRSAPrivateKey(rented, out pkcs1Size)) { rentSize = checked(rentSize * 2); continue; } return RSAKeyFormatHelper.WritePkcs8PrivateKey(rented.AsSpan(0, pkcs1Size)); } finally { CryptographicOperations.ZeroMemory(rented.AsSpan(0, pkcs1Size)); ArrayPool<byte>.Shared.Return(rented); } } } } public override bool TryExportEncryptedPkcs8PrivateKey( ReadOnlySpan<char> password, PbeParameters pbeParameters, Span<byte> destination, out int bytesWritten) { if (pbeParameters == null) throw new ArgumentNullException(nameof(pbeParameters)); PasswordBasedEncryption.ValidatePbeParameters( pbeParameters, password, ReadOnlySpan<byte>.Empty); using (AsnWriter pkcs8PrivateKey = WritePkcs8PrivateKey()) using (AsnWriter writer = KeyFormatHelper.WriteEncryptedPkcs8( password, pkcs8PrivateKey, pbeParameters)) { return writer.TryEncode(destination, out bytesWritten); } } public override bool TryExportEncryptedPkcs8PrivateKey( ReadOnlySpan<byte> passwordBytes, PbeParameters pbeParameters, Span<byte> destination, out int bytesWritten) { if (pbeParameters == null) throw new ArgumentNullException(nameof(pbeParameters)); PasswordBasedEncryption.ValidatePbeParameters( pbeParameters, ReadOnlySpan<char>.Empty, passwordBytes); using (AsnWriter pkcs8PrivateKey = WritePkcs8PrivateKey()) using (AsnWriter writer = KeyFormatHelper.WriteEncryptedPkcs8( passwordBytes, pkcs8PrivateKey, pbeParameters)) { return writer.TryEncode(destination, out bytesWritten); } } private AsnWriter WritePkcs1PublicKey() { RSAParameters rsaParameters = ExportParameters(false); return RSAKeyFormatHelper.WritePkcs1PublicKey(rsaParameters); } private unsafe AsnWriter WritePkcs1PrivateKey() { RSAParameters rsaParameters = ExportParameters(true); fixed (byte* dPin = rsaParameters.D) fixed (byte* pPin = rsaParameters.P) fixed (byte* qPin = rsaParameters.Q) fixed (byte* dpPin = rsaParameters.DP) fixed (byte* dqPin = rsaParameters.DQ) fixed (byte* qInvPin = rsaParameters.InverseQ) { try { return RSAKeyFormatHelper.WritePkcs1PrivateKey(rsaParameters); } finally { ClearPrivateParameters(rsaParameters); } } } public override unsafe void ImportSubjectPublicKeyInfo(ReadOnlySpan<byte> source, out int bytesRead) { fixed (byte* ptr = &MemoryMarshal.GetReference(source)) { using (MemoryManager<byte> manager = new PointerMemoryManager<byte>(ptr, source.Length)) { ReadOnlyMemory<byte> pkcs1 = RSAKeyFormatHelper.ReadSubjectPublicKeyInfo( manager.Memory, out int localRead); ImportRSAPublicKey(pkcs1.Span, out _); bytesRead = localRead; } } } public virtual unsafe void ImportRSAPublicKey(ReadOnlySpan<byte> source, out int bytesRead) { fixed (byte* ptr = &MemoryMarshal.GetReference(source)) { using (MemoryManager<byte> manager = new PointerMemoryManager<byte>(ptr, source.Length)) { AsnReader reader = new AsnReader(manager.Memory, AsnEncodingRules.BER); ReadOnlyMemory<byte> firstValue = reader.PeekEncodedValue(); int localRead = firstValue.Length; AlgorithmIdentifierAsn ignored = default; RSAKeyFormatHelper.ReadRsaPublicKey(firstValue, ignored, out RSAParameters rsaParameters); ImportParameters(rsaParameters); bytesRead = localRead; } } } public virtual unsafe void ImportRSAPrivateKey(ReadOnlySpan<byte> source, out int bytesRead) { fixed (byte* ptr = &MemoryMarshal.GetReference(source)) { using (MemoryManager<byte> manager = new PointerMemoryManager<byte>(ptr, source.Length)) { AsnReader reader = new AsnReader(manager.Memory, AsnEncodingRules.BER); ReadOnlyMemory<byte> firstValue = reader.PeekEncodedValue(); int localRead = firstValue.Length; AlgorithmIdentifierAsn ignored = default; RSAKeyFormatHelper.FromPkcs1PrivateKey(firstValue, ignored, out RSAParameters rsaParameters); fixed (byte* dPin = rsaParameters.D) fixed (byte* pPin = rsaParameters.P) fixed (byte* qPin = rsaParameters.Q) fixed (byte* dpPin = rsaParameters.DP) fixed (byte* dqPin = rsaParameters.DQ) fixed (byte* qInvPin = rsaParameters.InverseQ) { try { ImportParameters(rsaParameters); } finally { ClearPrivateParameters(rsaParameters); } } bytesRead = localRead; } } } public override unsafe void ImportPkcs8PrivateKey(ReadOnlySpan<byte> source, out int bytesRead) { fixed (byte* ptr = &MemoryMarshal.GetReference(source)) { using (MemoryManager<byte> manager = new PointerMemoryManager<byte>(ptr, source.Length)) { ReadOnlyMemory<byte> pkcs1 = RSAKeyFormatHelper.ReadPkcs8( manager.Memory, out int localRead); ImportRSAPrivateKey(pkcs1.Span, out _); bytesRead = localRead; } } } public override unsafe void ImportEncryptedPkcs8PrivateKey( ReadOnlySpan<byte> passwordBytes, ReadOnlySpan<byte> source, out int bytesRead) { RSAKeyFormatHelper.ReadEncryptedPkcs8( source, passwordBytes, out int localRead, out RSAParameters ret); fixed (byte* dPin = ret.D) fixed (byte* pPin = ret.P) fixed (byte* qPin = ret.Q) fixed (byte* dpPin = ret.DP) fixed (byte* dqPin = ret.DQ) fixed (byte* qInvPin = ret.InverseQ) { try { ImportParameters(ret); } finally { ClearPrivateParameters(ret); } } bytesRead = localRead; } public override unsafe void ImportEncryptedPkcs8PrivateKey( ReadOnlySpan<char> password, ReadOnlySpan<byte> source, out int bytesRead) { RSAKeyFormatHelper.ReadEncryptedPkcs8( source, password, out int localRead, out RSAParameters ret); fixed (byte* dPin = ret.D) fixed (byte* pPin = ret.P) fixed (byte* qPin = ret.Q) fixed (byte* dpPin = ret.DP) fixed (byte* dqPin = ret.DQ) fixed (byte* qInvPin = ret.InverseQ) { try { ImportParameters(ret); } finally { ClearPrivateParameters(ret); } } bytesRead = localRead; } private static void ClearPrivateParameters(in RSAParameters rsaParameters) { CryptographicOperations.ZeroMemory(rsaParameters.D); CryptographicOperations.ZeroMemory(rsaParameters.P); CryptographicOperations.ZeroMemory(rsaParameters.Q); CryptographicOperations.ZeroMemory(rsaParameters.DP); CryptographicOperations.ZeroMemory(rsaParameters.DQ); CryptographicOperations.ZeroMemory(rsaParameters.InverseQ); } public override string KeyExchangeAlgorithm => "RSA"; public override string SignatureAlgorithm => "RSA"; private static Exception HashAlgorithmNameNullOrEmpty() => new ArgumentException(SR.Cryptography_HashAlgorithmNameNullOrEmpty, "hashAlgorithm"); } }
using J2N.Text; using Lucene.Net.Documents; using Lucene.Net.Util; using NUnit.Framework; using System; using System.Collections.Generic; using System.Text; using Assert = Lucene.Net.TestFramework.Assert; using JCG = J2N.Collections.Generic; namespace Lucene.Net.Index { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using BytesRef = Lucene.Net.Util.BytesRef; using CharsRef = Lucene.Net.Util.CharsRef; using Directory = Lucene.Net.Store.Directory; using Document = Documents.Document; using Field = Field; using LuceneTestCase = Lucene.Net.Util.LuceneTestCase; using MockAnalyzer = Lucene.Net.Analysis.MockAnalyzer; using UnicodeUtil = Lucene.Net.Util.UnicodeUtil; [TestFixture] public class TestIndexWriterUnicode : LuceneTestCase { internal readonly string[] utf8Data = new string[] { "ab\udc17cd", "ab\ufffdcd", "\udc17abcd", "\ufffdabcd", "\udc17", "\ufffd", "ab\udc17\udc17cd", "ab\ufffd\ufffdcd", "\udc17\udc17abcd", "\ufffd\ufffdabcd", "\udc17\udc17", "\ufffd\ufffd", "ab\ud917cd", "ab\ufffdcd", "\ud917abcd", "\ufffdabcd", "\ud917", "\ufffd", "ab\ud917\ud917cd", "ab\ufffd\ufffdcd", "\ud917\ud917abcd", "\ufffd\ufffdabcd", "\ud917\ud917", "\ufffd\ufffd", "ab\udc17\ud917cd", "ab\ufffd\ufffdcd", "\udc17\ud917abcd", "\ufffd\ufffdabcd", "\udc17\ud917", "\ufffd\ufffd", "ab\udc17\ud917\udc17\ud917cd", "ab\ufffd\ud917\udc17\ufffdcd", "\udc17\ud917\udc17\ud917abcd", "\ufffd\ud917\udc17\ufffdabcd", "\udc17\ud917\udc17\ud917", "\ufffd\ud917\udc17\ufffd" }; private int NextInt(int lim) { return Random.Next(lim); } private int NextInt(int start, int end) { return start + NextInt(end - start); } private bool FillUnicode(char[] buffer, char[] expected, int offset, int count) { int len = offset + count; bool hasIllegal = false; if (offset > 0 && buffer[offset] >= 0xdc00 && buffer[offset] < 0xe000) // Don't start in the middle of a valid surrogate pair { offset--; } for (int i = offset; i < len; i++) { int t = NextInt(6); if (0 == t && i < len - 1) { // Make a surrogate pair // High surrogate expected[i] = buffer[i++] = (char)NextInt(0xd800, 0xdc00); // Low surrogate expected[i] = buffer[i] = (char)NextInt(0xdc00, 0xe000); } else if (t <= 1) { expected[i] = buffer[i] = (char)NextInt(0x80); } else if (2 == t) { expected[i] = buffer[i] = (char)NextInt(0x80, 0x800); } else if (3 == t) { expected[i] = buffer[i] = (char)NextInt(0x800, 0xd800); } else if (4 == t) { expected[i] = buffer[i] = (char)NextInt(0xe000, 0xffff); } else if (5 == t && i < len - 1) { // Illegal unpaired surrogate if (NextInt(10) == 7) { if (Random.NextBoolean()) { buffer[i] = (char)NextInt(0xd800, 0xdc00); } else { buffer[i] = (char)NextInt(0xdc00, 0xe000); } expected[i++] = (char)0xfffd; expected[i] = buffer[i] = (char)NextInt(0x800, 0xd800); hasIllegal = true; } else { expected[i] = buffer[i] = (char)NextInt(0x800, 0xd800); } } else { expected[i] = buffer[i] = ' '; } } return hasIllegal; } // both start & end are inclusive private int GetInt(Random r, int start, int end) { return start + r.Next(1 + end - start); } private string AsUnicodeChar(char c) { return "U+" + ((int)c).ToString("x"); } private string TermDesc(string s) { string s0; Assert.IsTrue(s.Length <= 2); if (s.Length == 1) { s0 = AsUnicodeChar(s[0]); } else { s0 = AsUnicodeChar(s[0]) + "," + AsUnicodeChar(s[1]); } return s0; } private void CheckTermsOrder(IndexReader r, ISet<string> allTerms, bool isTop) { TermsEnum terms = MultiFields.GetFields(r).GetTerms("f").GetEnumerator(); BytesRef last = new BytesRef(); ISet<string> seenTerms = new JCG.HashSet<string>(); while (terms.MoveNext()) { BytesRef term = terms.Term; Assert.IsTrue(last.CompareTo(term) < 0); last.CopyBytes(term); string s = term.Utf8ToString(); Assert.IsTrue(allTerms.Contains(s), "term " + TermDesc(s) + " was not added to index (count=" + allTerms.Count + ")"); seenTerms.Add(s); } if (isTop) { Assert.IsTrue(allTerms.SetEquals(seenTerms)); } // Test seeking: IEnumerator<string> it = seenTerms.GetEnumerator(); while (it.MoveNext()) { BytesRef tr = new BytesRef(it.Current); Assert.AreEqual(TermsEnum.SeekStatus.FOUND, terms.SeekCeil(tr), "seek failed for term=" + TermDesc(tr.Utf8ToString())); } } // LUCENE-510 [Test] public virtual void TestRandomUnicodeStrings() { char[] buffer = new char[20]; char[] expected = new char[20]; BytesRef utf8 = new BytesRef(20); CharsRef utf16 = new CharsRef(20); int num = AtLeast(100000); for (int iter = 0; iter < num; iter++) { bool hasIllegal = FillUnicode(buffer, expected, 0, 20); UnicodeUtil.UTF16toUTF8(buffer, 0, 20, utf8); if (!hasIllegal) { #pragma warning disable 612, 618 var b = (new string(buffer, 0, 20)).GetBytes(IOUtils.CHARSET_UTF_8); #pragma warning restore 612, 618 Assert.AreEqual(b.Length, utf8.Length); for (int i = 0; i < b.Length; i++) { Assert.AreEqual(b[i], utf8.Bytes[i]); } } UnicodeUtil.UTF8toUTF16(utf8.Bytes, 0, utf8.Length, utf16); Assert.AreEqual(utf16.Length, 20); for (int i = 0; i < 20; i++) { Assert.AreEqual(expected[i], utf16.Chars[i]); } } } // LUCENE-510 [Test] public virtual void TestAllUnicodeChars() { BytesRef utf8 = new BytesRef(10); CharsRef utf16 = new CharsRef(10); char[] chars = new char[2]; for (int ch = 0; ch < 0x0010FFFF; ch++) { if (ch == 0xd800) // Skip invalid code points { ch = 0xe000; } int len = 0; if (ch <= 0xffff) { chars[len++] = (char)ch; } else { chars[len++] = (char)(((ch - 0x0010000) >> 10) + UnicodeUtil.UNI_SUR_HIGH_START); chars[len++] = (char)(((ch - 0x0010000) & 0x3FFL) + UnicodeUtil.UNI_SUR_LOW_START); } UnicodeUtil.UTF16toUTF8(chars, 0, len, utf8); string s1 = new string(chars, 0, len); string s2 = Encoding.UTF8.GetString(utf8.Bytes, utf8.Offset, utf8.Length); Assert.AreEqual(s1, s2, "codepoint " + ch); UnicodeUtil.UTF8toUTF16(utf8.Bytes, 0, utf8.Length, utf16); Assert.AreEqual(s1, new string(utf16.Chars, 0, utf16.Length), "codepoint " + ch); var b = s1.GetBytes(Encoding.UTF8); Assert.AreEqual(utf8.Length, b.Length); for (int j = 0; j < utf8.Length; j++) { Assert.AreEqual(utf8.Bytes[j], b[j]); } } } [Test] public virtual void TestEmbeddedFFFF() { Directory d = NewDirectory(); IndexWriter w = new IndexWriter(d, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random))); Document doc = new Document(); doc.Add(NewTextField("field", "a a\uffffb", Field.Store.NO)); w.AddDocument(doc); doc = new Document(); doc.Add(NewTextField("field", "a", Field.Store.NO)); w.AddDocument(doc); IndexReader r = w.GetReader(); Assert.AreEqual(1, r.DocFreq(new Term("field", "a\uffffb"))); r.Dispose(); w.Dispose(); d.Dispose(); } // LUCENE-510 [Test] public virtual void TestInvalidUTF16() { Directory dir = NewDirectory(); IndexWriter w = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new TestIndexWriter.StringSplitAnalyzer())); Document doc = new Document(); int count = utf8Data.Length / 2; for (int i = 0; i < count; i++) { doc.Add(NewTextField("f" + i, utf8Data[2 * i], Field.Store.YES)); } w.AddDocument(doc); w.Dispose(); IndexReader ir = DirectoryReader.Open(dir); Document doc2 = ir.Document(0); for (int i = 0; i < count; i++) { Assert.AreEqual(1, ir.DocFreq(new Term("f" + i, utf8Data[2 * i + 1])), "field " + i + " was not indexed correctly"); Assert.AreEqual(utf8Data[2 * i + 1], doc2.GetField("f" + i).GetStringValue(), "field " + i + " is incorrect"); } ir.Dispose(); dir.Dispose(); } // Make sure terms, including ones with surrogate pairs, // sort in codepoint sort order by default [Test] public virtual void TestTermUTF16SortOrder() { Random rnd = Random; Directory dir = NewDirectory(); RandomIndexWriter writer = new RandomIndexWriter( #if FEATURE_INSTANCE_TESTDATA_INITIALIZATION this, #endif rnd, dir); Document d = new Document(); // Single segment Field f = NewStringField("f", "", Field.Store.NO); d.Add(f); char[] chars = new char[2]; ISet<string> allTerms = new JCG.HashSet<string>(); int num = AtLeast(200); for (int i = 0; i < num; i++) { string s; if (rnd.NextBoolean()) { // Single char if (rnd.NextBoolean()) { // Above surrogates chars[0] = (char)GetInt(rnd, 1 + UnicodeUtil.UNI_SUR_LOW_END, 0xffff); } else { // Below surrogates chars[0] = (char)GetInt(rnd, 0, UnicodeUtil.UNI_SUR_HIGH_START - 1); } s = new string(chars, 0, 1); } else { // Surrogate pair chars[0] = (char)GetInt(rnd, UnicodeUtil.UNI_SUR_HIGH_START, UnicodeUtil.UNI_SUR_HIGH_END); Assert.IsTrue(((int)chars[0]) >= UnicodeUtil.UNI_SUR_HIGH_START && ((int)chars[0]) <= UnicodeUtil.UNI_SUR_HIGH_END); chars[1] = (char)GetInt(rnd, UnicodeUtil.UNI_SUR_LOW_START, UnicodeUtil.UNI_SUR_LOW_END); s = new string(chars, 0, 2); } allTerms.Add(s); f.SetStringValue(s); writer.AddDocument(d); if ((1 + i) % 42 == 0) { writer.Commit(); } } IndexReader r = writer.GetReader(); // Test each sub-segment foreach (AtomicReaderContext ctx in r.Leaves) { CheckTermsOrder(ctx.Reader, allTerms, false); } CheckTermsOrder(r, allTerms, true); // Test multi segment r.Dispose(); writer.ForceMerge(1); // Test single segment r = writer.GetReader(); CheckTermsOrder(r, allTerms, true); r.Dispose(); writer.Dispose(); dir.Dispose(); } } }
using System; using NBitcoin.BouncyCastle.Crypto; using NBitcoin.BouncyCastle.Crypto.Parameters; namespace NBitcoin.BouncyCastle.Crypto.Macs { /** * implementation of GOST 28147-89 MAC */ public class Gost28147Mac : IMac { private const int blockSize = 8; private const int macSize = 4; private int bufOff; private byte[] buf; private byte[] mac; private bool firstStep = true; private int[] workingKey; // // This is default S-box - E_A. private byte[] S = { 0x9,0x6,0x3,0x2,0x8,0xB,0x1,0x7,0xA,0x4,0xE,0xF,0xC,0x0,0xD,0x5, 0x3,0x7,0xE,0x9,0x8,0xA,0xF,0x0,0x5,0x2,0x6,0xC,0xB,0x4,0xD,0x1, 0xE,0x4,0x6,0x2,0xB,0x3,0xD,0x8,0xC,0xF,0x5,0xA,0x0,0x7,0x1,0x9, 0xE,0x7,0xA,0xC,0xD,0x1,0x3,0x9,0x0,0x2,0xB,0x4,0xF,0x8,0x5,0x6, 0xB,0x5,0x1,0x9,0x8,0xD,0xF,0x0,0xE,0x4,0x2,0x3,0xC,0x7,0xA,0x6, 0x3,0xA,0xD,0xC,0x1,0x2,0x0,0xB,0x7,0x5,0x9,0x4,0x8,0xF,0xE,0x6, 0x1,0xD,0x2,0x9,0x7,0xA,0x6,0x0,0x8,0xC,0x4,0x5,0xF,0x3,0xB,0xE, 0xB,0xA,0xF,0x5,0x0,0xC,0xE,0x8,0x6,0x2,0x3,0x9,0x1,0x7,0xD,0x4 }; public Gost28147Mac() { mac = new byte[blockSize]; buf = new byte[blockSize]; bufOff = 0; } private static int[] generateWorkingKey( byte[] userKey) { if (userKey.Length != 32) throw new ArgumentException("Key length invalid. Key needs to be 32 byte - 256 bit!!!"); int[] key = new int[8]; for(int i=0; i!=8; i++) { key[i] = bytesToint(userKey,i*4); } return key; } public void Init( ICipherParameters parameters) { Reset(); buf = new byte[blockSize]; if (parameters is ParametersWithSBox) { ParametersWithSBox param = (ParametersWithSBox)parameters; // // Set the S-Box // param.GetSBox().CopyTo(this.S, 0); // // set key if there is one // if (param.Parameters != null) { workingKey = generateWorkingKey(((KeyParameter)param.Parameters).GetKey()); } } else if (parameters is KeyParameter) { workingKey = generateWorkingKey(((KeyParameter)parameters).GetKey()); } else { throw new ArgumentException("invalid parameter passed to Gost28147 init - " + parameters.GetType().Name); } } public string AlgorithmName { get { return "Gost28147Mac"; } } public int GetMacSize() { return macSize; } private int gost28147_mainStep(int n1, int key) { int cm = (key + n1); // CM1 // S-box replacing int om = S[ 0 + ((cm >> (0 * 4)) & 0xF)] << (0 * 4); om += S[ 16 + ((cm >> (1 * 4)) & 0xF)] << (1 * 4); om += S[ 32 + ((cm >> (2 * 4)) & 0xF)] << (2 * 4); om += S[ 48 + ((cm >> (3 * 4)) & 0xF)] << (3 * 4); om += S[ 64 + ((cm >> (4 * 4)) & 0xF)] << (4 * 4); om += S[ 80 + ((cm >> (5 * 4)) & 0xF)] << (5 * 4); om += S[ 96 + ((cm >> (6 * 4)) & 0xF)] << (6 * 4); om += S[112 + ((cm >> (7 * 4)) & 0xF)] << (7 * 4); // return om << 11 | om >>> (32-11); // 11-leftshift int omLeft = om << 11; int omRight = (int)(((uint) om) >> (32 - 11)); // Note: Casts required to get unsigned bit rotation return omLeft | omRight; } private void gost28147MacFunc( int[] workingKey, byte[] input, int inOff, byte[] output, int outOff) { int N1, N2, tmp; //tmp -> for saving N1 N1 = bytesToint(input, inOff); N2 = bytesToint(input, inOff + 4); for (int k = 0; k < 2; k++) // 1-16 steps { for (int j = 0; j < 8; j++) { tmp = N1; N1 = N2 ^ gost28147_mainStep(N1, workingKey[j]); // CM2 N2 = tmp; } } intTobytes(N1, output, outOff); intTobytes(N2, output, outOff + 4); } //array of bytes to type int private static int bytesToint( byte[] input, int inOff) { return (int)((input[inOff + 3] << 24) & 0xff000000) + ((input[inOff + 2] << 16) & 0xff0000) + ((input[inOff + 1] << 8) & 0xff00) + (input[inOff] & 0xff); } //int to array of bytes private static void intTobytes( int num, byte[] output, int outOff) { output[outOff + 3] = (byte)(num >> 24); output[outOff + 2] = (byte)(num >> 16); output[outOff + 1] = (byte)(num >> 8); output[outOff] = (byte)num; } private static byte[] CM5func( byte[] buf, int bufOff, byte[] mac) { byte[] sum = new byte[buf.Length - bufOff]; Array.Copy(buf, bufOff, sum, 0, mac.Length); for (int i = 0; i != mac.Length; i++) { sum[i] = (byte)(sum[i] ^ mac[i]); } return sum; } public void Update( byte input) { if (bufOff == buf.Length) { byte[] sumbuf = new byte[buf.Length]; Array.Copy(buf, 0, sumbuf, 0, mac.Length); if (firstStep) { firstStep = false; } else { sumbuf = CM5func(buf, 0, mac); } gost28147MacFunc(workingKey, sumbuf, 0, mac, 0); bufOff = 0; } buf[bufOff++] = input; } public void BlockUpdate( byte[] input, int inOff, int len) { if (len < 0) throw new ArgumentException("Can't have a negative input length!"); int gapLen = blockSize - bufOff; if (len > gapLen) { Array.Copy(input, inOff, buf, bufOff, gapLen); byte[] sumbuf = new byte[buf.Length]; Array.Copy(buf, 0, sumbuf, 0, mac.Length); if (firstStep) { firstStep = false; } else { sumbuf = CM5func(buf, 0, mac); } gost28147MacFunc(workingKey, sumbuf, 0, mac, 0); bufOff = 0; len -= gapLen; inOff += gapLen; while (len > blockSize) { sumbuf = CM5func(input, inOff, mac); gost28147MacFunc(workingKey, sumbuf, 0, mac, 0); len -= blockSize; inOff += blockSize; } } Array.Copy(input, inOff, buf, bufOff, len); bufOff += len; } public int DoFinal( byte[] output, int outOff) { //padding with zero while (bufOff < blockSize) { buf[bufOff++] = 0; } byte[] sumbuf = new byte[buf.Length]; Array.Copy(buf, 0, sumbuf, 0, mac.Length); if (firstStep) { firstStep = false; } else { sumbuf = CM5func(buf, 0, mac); } gost28147MacFunc(workingKey, sumbuf, 0, mac, 0); Array.Copy(mac, (mac.Length/2)-macSize, output, outOff, macSize); Reset(); return macSize; } public void Reset() { // Clear the buffer. Array.Clear(buf, 0, buf.Length); bufOff = 0; firstStep = true; } } }
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- using AutoMapper; using Microsoft.Azure.Commands.Network.Models; using Microsoft.Azure.Commands.ResourceManager.Common.ArgumentCompleters; using Microsoft.Azure.Commands.ResourceManager.Common.Tags; using Microsoft.Azure.Management.Network; using System.Collections; using System.Collections.Generic; using System.Management.Automation; using MNM = Microsoft.Azure.Management.Network.Models; namespace Microsoft.Azure.Commands.Network { [Cmdlet(VerbsCommon.New, "AzureRmApplicationGateway", SupportsShouldProcess = true), OutputType(typeof(PSApplicationGateway))] public class NewAzureApplicationGatewayCommand : ApplicationGatewayBaseCmdlet { [Alias("ResourceName")] [Parameter( Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The resource name.")] [ValidateNotNullOrEmpty] public virtual string Name { get; set; } [Parameter( Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The resource group name.")] [ResourceGroupCompleter] [ValidateNotNullOrEmpty] public virtual string ResourceGroupName { get; set; } [Parameter( Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "location.")] [LocationCompleter("Microsoft.Network/applicationGateways")] [ValidateNotNullOrEmpty] public virtual string Location { get; set; } [Parameter( Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The SKU of application gateway")] [ValidateNotNullOrEmpty] public virtual PSApplicationGatewaySku Sku { get; set; } [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The SSL policy of application gateway")] public virtual PSApplicationGatewaySslPolicy SslPolicy { get; set; } [Parameter( Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The list of IPConfiguration (subnet)")] [ValidateNotNullOrEmpty] public List<PSApplicationGatewayIPConfiguration> GatewayIPConfigurations { get; set; } [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The list of ssl certificates")] public List<PSApplicationGatewaySslCertificate> SslCertificates { get; set; } [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The list of authentication certificates")] public List<PSApplicationGatewayAuthenticationCertificate> AuthenticationCertificates { get; set; } [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The list of frontend IP config")] public List<PSApplicationGatewayFrontendIPConfiguration> FrontendIPConfigurations { get; set; } [Parameter( Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The list of frontend port")] public List<PSApplicationGatewayFrontendPort> FrontendPorts { get; set; } [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The list of probe")] public List<PSApplicationGatewayProbe> Probes { get; set; } [Parameter( Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The list of backend address pool")] public List<PSApplicationGatewayBackendAddressPool> BackendAddressPools { get; set; } [Parameter( Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The list of backend http settings")] public List<PSApplicationGatewayBackendHttpSettings> BackendHttpSettingsCollection { get; set; } [Parameter( Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The list of http listener")] public List<PSApplicationGatewayHttpListener> HttpListeners { get; set; } [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The list of UrlPathMap")] public List<PSApplicationGatewayUrlPathMap> UrlPathMaps { get; set; } [Parameter( Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The list of request routing rule")] public List<PSApplicationGatewayRequestRoutingRule> RequestRoutingRules { get; set; } [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The list of redirect configuration")] public List<PSApplicationGatewayRedirectConfiguration> RedirectConfigurations { get; set; } [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "Firewall configuration")] public virtual PSApplicationGatewayWebApplicationFirewallConfiguration WebApplicationFirewallConfiguration { get; set; } [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "A hashtable which represents resource tags.")] public Hashtable Tag { get; set; } [Parameter( Mandatory = false, HelpMessage = "Do not ask for confirmation if you want to overrite a resource")] public SwitchParameter Force { get; set; } [Parameter(Mandatory = false, HelpMessage = "Run cmdlet in the background")] public SwitchParameter AsJob { get; set; } public override void ExecuteCmdlet() { base.ExecuteCmdlet(); WriteWarning("The output object type of this cmdlet will be modified in a future release."); var present = this.IsApplicationGatewayPresent(this.ResourceGroupName, this.Name); ConfirmAction( Force.IsPresent, string.Format(Microsoft.Azure.Commands.Network.Properties.Resources.OverwritingResource, Name), Microsoft.Azure.Commands.Network.Properties.Resources.OverwritingResourceMessage, Name, () => { var applicationGateway = CreateApplicationGateway(); WriteObject(applicationGateway); }, () => present); } private PSApplicationGateway CreateApplicationGateway() { var applicationGateway = new PSApplicationGateway(); applicationGateway.Name = this.Name; applicationGateway.ResourceGroupName = this.ResourceGroupName; applicationGateway.Location = this.Location; applicationGateway.Sku = this.Sku; if (this.SslPolicy != null) { applicationGateway.SslPolicy = new PSApplicationGatewaySslPolicy(); applicationGateway.SslPolicy = this.SslPolicy; } if (this.GatewayIPConfigurations != null) { applicationGateway.GatewayIPConfigurations = this.GatewayIPConfigurations; } if (this.SslCertificates != null) { applicationGateway.SslCertificates = this.SslCertificates; } if (this.AuthenticationCertificates != null) { applicationGateway.AuthenticationCertificates = this.AuthenticationCertificates; } if (this.FrontendIPConfigurations != null) { applicationGateway.FrontendIPConfigurations = this.FrontendIPConfigurations; } if (this.FrontendPorts != null) { applicationGateway.FrontendPorts = this.FrontendPorts; } if (this.Probes != null) { applicationGateway.Probes = this.Probes; } if (this.BackendAddressPools != null) { applicationGateway.BackendAddressPools = this.BackendAddressPools; } if (this.BackendHttpSettingsCollection != null) { applicationGateway.BackendHttpSettingsCollection = this.BackendHttpSettingsCollection; } if (this.HttpListeners != null) { applicationGateway.HttpListeners = this.HttpListeners; } if (this.UrlPathMaps != null) { applicationGateway.UrlPathMaps = this.UrlPathMaps; } if (this.RequestRoutingRules != null) { applicationGateway.RequestRoutingRules = this.RequestRoutingRules; } if (this.RedirectConfigurations != null) { applicationGateway.RedirectConfigurations = this.RedirectConfigurations; } if (this.WebApplicationFirewallConfiguration != null) { applicationGateway.WebApplicationFirewallConfiguration = this.WebApplicationFirewallConfiguration; } // Normalize the IDs ApplicationGatewayChildResourceHelper.NormalizeChildResourcesId(applicationGateway); // Map to the sdk object var appGwModel = NetworkResourceManagerProfile.Mapper.Map<MNM.ApplicationGateway>(applicationGateway); appGwModel.Tags = TagsConversionHelper.CreateTagDictionary(this.Tag, validate: true); // Execute the Create ApplicationGateway call this.ApplicationGatewayClient.CreateOrUpdate(this.ResourceGroupName, this.Name, appGwModel); var getApplicationGateway = this.GetApplicationGateway(this.ResourceGroupName, this.Name); return getApplicationGateway; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.ServiceBus.Fluent { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; /// <summary> /// Extension methods for QueuesOperations. /// </summary> public static partial class QueuesOperationsExtensions { /// <summary> /// Gets the queues within a namespace. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639415.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The namespace name /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<QueueInner>> ListByNamespaceAsync(this IQueuesOperations operations, string resourceGroupName, string namespaceName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListByNamespaceWithHttpMessagesAsync(resourceGroupName, namespaceName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Creates or updates a Service Bus queue. This operation is idempotent. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639395.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The namespace name /// </param> /// <param name='queueName'> /// The queue name. /// </param> /// <param name='parameters'> /// Parameters supplied to create or update a queue resource. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<QueueInner> CreateOrUpdateAsync(this IQueuesOperations operations, string resourceGroupName, string namespaceName, string queueName, QueueInner parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, namespaceName, queueName, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Deletes a queue from the specified namespace in a resource group. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639411.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The namespace name /// </param> /// <param name='queueName'> /// The queue name. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task DeleteAsync(this IQueuesOperations operations, string resourceGroupName, string namespaceName, string queueName, CancellationToken cancellationToken = default(CancellationToken)) { (await operations.DeleteWithHttpMessagesAsync(resourceGroupName, namespaceName, queueName, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Returns a description for the specified queue. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639380.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The namespace name /// </param> /// <param name='queueName'> /// The queue name. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<QueueInner> GetAsync(this IQueuesOperations operations, string resourceGroupName, string namespaceName, string queueName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, namespaceName, queueName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets all authorization rules for a queue. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt705607.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The namespace name /// </param> /// <param name='queueName'> /// The queue name. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<SharedAccessAuthorizationRuleInner>> ListAuthorizationRulesAsync(this IQueuesOperations operations, string resourceGroupName, string namespaceName, string queueName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListAuthorizationRulesWithHttpMessagesAsync(resourceGroupName, namespaceName, queueName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Creates an authorization rule for a queue. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The namespace name /// </param> /// <param name='queueName'> /// The queue name. /// </param> /// <param name='authorizationRuleName'> /// The authorizationrule name. /// </param> /// <param name='rights'> /// The rights associated with the rule. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<SharedAccessAuthorizationRuleInner> CreateOrUpdateAuthorizationRuleAsync(this IQueuesOperations operations, string resourceGroupName, string namespaceName, string queueName, string authorizationRuleName, IList<AccessRights?> rights, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CreateOrUpdateAuthorizationRuleWithHttpMessagesAsync(resourceGroupName, namespaceName, queueName, authorizationRuleName, rights, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Deletes a queue authorization rule. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt705609.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The namespace name /// </param> /// <param name='queueName'> /// The queue name. /// </param> /// <param name='authorizationRuleName'> /// The authorizationrule name. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task DeleteAuthorizationRuleAsync(this IQueuesOperations operations, string resourceGroupName, string namespaceName, string queueName, string authorizationRuleName, CancellationToken cancellationToken = default(CancellationToken)) { (await operations.DeleteAuthorizationRuleWithHttpMessagesAsync(resourceGroupName, namespaceName, queueName, authorizationRuleName, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Gets an authorization rule for a queue by rule name. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt705611.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The namespace name /// </param> /// <param name='queueName'> /// The queue name. /// </param> /// <param name='authorizationRuleName'> /// The authorizationrule name. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<SharedAccessAuthorizationRuleInner> GetAuthorizationRuleAsync(this IQueuesOperations operations, string resourceGroupName, string namespaceName, string queueName, string authorizationRuleName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetAuthorizationRuleWithHttpMessagesAsync(resourceGroupName, namespaceName, queueName, authorizationRuleName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Primary and secondary connection strings to the queue. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt705608.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The namespace name /// </param> /// <param name='queueName'> /// The queue name. /// </param> /// <param name='authorizationRuleName'> /// The authorizationrule name. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<ResourceListKeysInner> ListKeysAsync(this IQueuesOperations operations, string resourceGroupName, string namespaceName, string queueName, string authorizationRuleName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListKeysWithHttpMessagesAsync(resourceGroupName, namespaceName, queueName, authorizationRuleName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Regenerates the primary or secondary connection strings to the queue. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt705606.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// Name of the Resource group within the Azure subscription. /// </param> /// <param name='namespaceName'> /// The namespace name /// </param> /// <param name='queueName'> /// The queue name. /// </param> /// <param name='authorizationRuleName'> /// The authorizationrule name. /// </param> /// <param name='policykey'> /// Key that needs to be regenerated. Possible values include: 'PrimaryKey', /// 'SecondaryKey' /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<ResourceListKeysInner> RegenerateKeysAsync(this IQueuesOperations operations, string resourceGroupName, string namespaceName, string queueName, string authorizationRuleName, Policykey? policykey = default(Policykey?), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.RegenerateKeysWithHttpMessagesAsync(resourceGroupName, namespaceName, queueName, authorizationRuleName, policykey, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets the queues within a namespace. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt639415.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<QueueInner>> ListByNamespaceNextAsync(this IQueuesOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListByNamespaceNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets all authorization rules for a queue. /// <see href="https://msdn.microsoft.com/en-us/library/azure/mt705607.aspx" /> /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<SharedAccessAuthorizationRuleInner>> ListAuthorizationRulesNextAsync(this IQueuesOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListAuthorizationRulesNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using LogShark.Containers; using LogShark.Shared.Extensions; using LogShark.Writers.Containers; namespace LogShark.Extensions { public static class RunSummaryExtensions { public static string ToStringReport(this RunSummary runSummary) { var sb = new StringBuilder(); GenerateSummarySection(sb, runSummary); if (runSummary.ProcessingNotificationsCollector != null) { GenerateProcessingErrorsSection(sb, runSummary); } if (runSummary.PublisherResults != null) { GeneratePublishingResultsSection(sb, runSummary); } if (runSummary.WorkbookGeneratorResults != null) { GenerateWorkbookGeneratorResultsSection(sb, runSummary); } if (runSummary.ProcessLogSetResult != null) { GenerateLogReadingStatisticsSection(sb, runSummary); } return sb.ToString().CleanControlCharacters(); } public static bool LogReadingCompletedSuccessfully(this RunSummary runSummary) { return runSummary?.ProcessLogSetResult != null && runSummary.ProcessLogSetResult.IsSuccessful; } public static bool HasProcessingErrors(this RunSummary runSummary) { return runSummary?.ProcessingNotificationsCollector != null && runSummary.ProcessingNotificationsCollector.TotalErrorsReported > 0; } public static bool HasWorkbookGeneratorErrors(this RunSummary runSummary) { return runSummary?.WorkbookGeneratorResults?.CompletedWorkbooks != null && runSummary.WorkbookGeneratorResults.CompletedWorkbooks.Any(result => !result.GeneratedSuccessfully); } public static bool HasNonSuccessfulPublishingResults(this RunSummary runSummary) { if (runSummary.PublisherResults == null) { return false; } var hasErrorsForIndividualWorkbooks = runSummary.PublisherResults.PublishedWorkbooksInfo != null && runSummary.PublisherResults.PublishedWorkbooksInfo.Any(result => result.PublishState != WorkbookPublishResult.WorkbookPublishState.Success); return !runSummary.PublisherResults.CreatedProjectSuccessfully || hasErrorsForIndividualWorkbooks; } public static string LogSetProcessingStatusReport(this RunSummary runSummary) { return runSummary.LogReadingCompletedSuccessfully() ? "LogShark successfully processed all logs" : $"Error occurred while processing logs: {runSummary.ProcessLogSetResult.ErrorMessage}"; } public static string ProcessingErrorsReport(this RunSummary runSummary) { if (!runSummary.HasProcessingErrors()) { return "No errors occurred while processing log set"; } var sb = new StringBuilder(); var errorsCollector = runSummary.ProcessingNotificationsCollector; sb.AppendLine($"{errorsCollector.TotalErrorsReported} errors occurred while processing log set:"); if (errorsCollector.TotalErrorsReported > errorsCollector.MaxErrorsWithDetails) { sb.AppendLine(); AddErrorsCountByReporterToStringBuilder(errorsCollector, sb); sb.AppendLine(); sb.AppendLine($"Details on first {errorsCollector.MaxErrorsWithDetails} reported errors:"); AppendDetailedErrorsToStringBuilder(errorsCollector, sb); } else { sb.AppendLine("Details of all reported errors:"); AppendDetailedErrorsToStringBuilder(errorsCollector, sb); } return sb.ToString(); } public static string WorkbookGeneratorErrorsReport(this RunSummary runSummary) { if (!runSummary.HasWorkbookGeneratorErrors()) { return "All workbooks were generated successfully"; } var sb = new StringBuilder(); sb.AppendLine("Errors occurred while generating workbooks:"); var errors = runSummary.WorkbookGeneratorResults.CompletedWorkbooks .Where(result => !result.GeneratedSuccessfully) .OrderBy(cwi => cwi.OriginalWorkbookName ?? "null") .Select(result => $"Failed to generate workbook `{result.OriginalWorkbookName ?? "(null)"}`. Exception: {result.Exception?.Message ?? "(null)"}"); sb.AppendLine(string.Join(Environment.NewLine, errors)); return sb.ToString(); } public static string WorkbookPublisherErrorsReport(this RunSummary runSummary) { if (!runSummary.HasNonSuccessfulPublishingResults()) { return "All workbooks were published successfully"; } if (!runSummary.PublisherResults.CreatedProjectSuccessfully) { return $"Publisher failed to connect to the Tableau Server or create project for the results. Exception message: {runSummary.PublisherResults.ExceptionCreatingProject?.Message ?? "(null)"}"; } var sb = new StringBuilder(); var failedWorkbooks = runSummary.PublisherResults.PublishedWorkbooksInfo .Where(result => result.PublishState == WorkbookPublishResult.WorkbookPublishState.Fail) .OrderBy(result => result.OriginalWorkbookName ?? "null") .Select(result => $"Failed to publish workbook `{result.OriginalWorkbookName ?? "(null)"}`. Exception: {result.Exception?.Message ?? "(null)"}") .ToList(); if (failedWorkbooks.Count > 0) { sb.AppendLine("Workbooks failed to publish:"); sb.AppendLine(string.Join(Environment.NewLine, failedWorkbooks)); } var timedOutWorkbooks = runSummary.PublisherResults.PublishedWorkbooksInfo .Where(result => result.PublishState == WorkbookPublishResult.WorkbookPublishState.Timeout) .Select(result => result.OriginalWorkbookName) .OrderBy(result => result) .ToList(); if (timedOutWorkbooks.Count > 0) { sb.AppendLine(); sb.AppendLine("Workbook(s) that timed out while publishing:"); sb.AppendLine(string.Join("; ", timedOutWorkbooks)); sb.AppendLine("Publishing timeout often happens if workbook is too large and Tableau Server takes a long time to generate thumbnails. In this case workbook will finish publishing on its own and should be available on Tableau Server after some time."); } return sb.ToString(); } private static void GenerateSummarySection(StringBuilder sb, RunSummary runSummary) { sb.AppendLine(GenerateTitle("Summary")); if (runSummary.IsSuccess) { sb.AppendLine($"Run ID {runSummary.RunId} completed successfully in {runSummary.Elapsed}"); } else { sb.AppendLine($"Run ID {runSummary.RunId} failed after running for {runSummary.Elapsed}. Reported problem: {runSummary.ReasonForFailure}"); sb.Append($"This problem is "); switch(runSummary.IsTransient) { case true: sb.AppendLine("a transient issue that may go away if LogShark is run again."); break; case false: sb.AppendLine("not transient and is unlikely to go away if LogShark is run again."); break; case null: default: sb.AppendLine("unexpected and it is not known whether or not it will go away if LogShark is run again."); break; } sb.AppendLine("Information below might contain more details on what exactly failed"); } var buildInfo = Assembly.GetExecutingAssembly().GetName().Version?.ToString() ?? "(null)"; sb.AppendLine($"LogShark version: {buildInfo}"); } private static void GenerateProcessingErrorsSection(StringBuilder sb, RunSummary runSummary) { sb.AppendLine(GenerateTitle("Processing errors")); sb.AppendLine(runSummary.ProcessingErrorsReport()); } private static void GeneratePublishingResultsSection(StringBuilder sb, RunSummary runSummary) { var publisherResults = runSummary.PublisherResults; sb.AppendLine(GenerateTitle("Published workbooks")); sb.AppendLine($"Used {publisherResults.TableauServerSite} site on {publisherResults.TableauServerUrl}"); sb.AppendLine($"Link to the published project: {publisherResults.PublishedProjectUrl ?? "N/A"}"); if (runSummary.HasNonSuccessfulPublishingResults()) { sb.AppendLine(runSummary.WorkbookPublisherErrorsReport()); } var successfullyPublishedWorkbooks = publisherResults.PublishedWorkbooksInfo? .Where(result => result.PublishState == WorkbookPublishResult.WorkbookPublishState.Success) .Select(result => result.PublishedWorkbookName) .OrderBy(workbookName => workbookName) .ToList(); if (successfullyPublishedWorkbooks?.Count > 0) { sb.AppendLine($"Successfully published workbooks: {GenerateHorizontalList(successfullyPublishedWorkbooks)}"); } var skippedWorkbooks = publisherResults.PublishedWorkbooksInfo? .Where(result => result.PublishState == WorkbookPublishResult.WorkbookPublishState.SkippedEmpty) .Select(result => result.OriginalWorkbookName) .OrderBy(workbookName => workbookName) .ToList(); if (skippedWorkbooks?.Count > 0) { sb.AppendLine($"Skipped publishing empty workbooks: {GenerateHorizontalList(skippedWorkbooks)}"); } } private static void GenerateWorkbookGeneratorResultsSection(StringBuilder sb, RunSummary runSummary) { sb.AppendLine(GenerateTitle("Generated workbooks")); var workbookTemplates = runSummary.WorkbookGeneratorResults.WorkbookTemplates ?? Enumerable.Empty<PackagedWorkbookTemplateInfo>(); var allAvailableTemplates = workbookTemplates.Select(template => template.Name).OrderBy(name => name); sb.AppendLine($"Workbook templates available: {string.Join("; ", allAvailableTemplates)}"); var completedWorkbooks = runSummary.WorkbookGeneratorResults.CompletedWorkbooks ?? Enumerable.Empty<CompletedWorkbookInfo>(); var successfullyGenerated = completedWorkbooks.Where(cwi => cwi.GeneratedSuccessfully).ToList(); var workbooksWithData = successfullyGenerated .Where(cwi => cwi.HasAnyData) .Select(cwi => cwi.OriginalWorkbookName) .OrderBy(workbookName => workbookName) .ToList(); if (workbooksWithData.Count > 0) { sb.AppendLine($"Successfully generated workbooks with data: {GenerateHorizontalList(workbooksWithData)}"); } var workbooksWithoutData = successfullyGenerated .Where(cwi => !cwi.HasAnyData) .Select(cwi => cwi.OriginalWorkbookName) .OrderBy(workbookName => workbookName) .ToList(); if (workbooksWithoutData.Count > 0) { sb.AppendLine($"Empty workbooks: {GenerateHorizontalList(workbooksWithoutData)}"); } if (runSummary.HasWorkbookGeneratorErrors()) { sb.AppendLine(runSummary.WorkbookGeneratorErrorsReport()); } } private static void GenerateLogReadingStatisticsSection(StringBuilder sb, RunSummary runSummary) { var processLogSetResult = runSummary.ProcessLogSetResult; sb.AppendLine(GenerateTitle("Log Reading Statistics")); if (!processLogSetResult.IsSuccessful) { sb.AppendLine($"Log processing did not complete successfully. Error message: {processLogSetResult.ErrorMessage ?? "(null)"}"); } var sizeMb = processLogSetResult.FullLogSetSizeBytes / 1024 / 1024; sb.AppendLine(processLogSetResult.IsDirectory ? $"Processed directory full size: {sizeMb:n0} MB" : $"Processed zip file compressed size: {sizeMb:n0} MB"); var pluginsExecutionResults = processLogSetResult.PluginsExecutionResults; if (pluginsExecutionResults != null) { var additionalTags = pluginsExecutionResults.GetSortedTagsFromAllPlugins(); if (additionalTags.Count > 0) { var wrappedTags = additionalTags.Select(tag => $"'{tag}'"); sb.Append("Additional tags returned by plugins: "); sb.AppendLine(string.Join(";", wrappedTags)); } } if (processLogSetResult.PluginsReceivedAnyData.Count > 0) { var pluginsReceivedAnyData = processLogSetResult.PluginsReceivedAnyData.OrderBy(pluginName => pluginName); sb.AppendLine($"Plugins that received any data: {string.Join(", ", pluginsReceivedAnyData)}"); sb.AppendLine(); var nonEmptyStatistics = processLogSetResult.LogProcessingStatistics .Where(pair => pair.Value.FilesProcessed > 0) .OrderBy(pair => pair.Key.ToString()); foreach (var (logType, logProcessingStatistics) in nonEmptyStatistics) { sb.AppendLine($"{logType.ToString().PadRight(50, ' ')}: {logProcessingStatistics}"); } } else { sb.AppendLine("No relevant log files found for plugins selected or all log types failed to process"); } GenerateWritersStatisticsSection(sb, processLogSetResult?.PluginsExecutionResults?.GetWritersStatistics()); } private static void GenerateWritersStatisticsSection(StringBuilder sb, WritersStatistics writersStatistics) { sb.AppendLine(GenerateTitle("Data Writers Statistics")); if (writersStatistics == null) { sb.AppendLine("No writer statistics generated"); return; } var receivedAnything = writersStatistics.DataSets .Where(pair => pair.Value.LinesPersisted > 0) .OrderBy(pair => pair.Key.ToString()) .Select(pair => $"{pair.Key.ToString().PadRight(50, ' ')}: {pair.Value.LinesPersisted} lines persisted") .ToList(); if (receivedAnything.Count > 0) { sb.AppendLine("Lines persisted per data set:"); sb.AppendLine(string.Join(Environment.NewLine, receivedAnything)); sb.AppendLine(); } var receivedNulls = writersStatistics.DataSets .Where(pair => pair.Value.NullLinesIgnored > 0) .OrderBy(pair => pair.Key.ToString()) .Select(pair => $"{pair.Key.ToString().PadRight(40, ' ')}: {pair.Value.NullLinesIgnored} null lines ignored") .ToList(); if (receivedNulls.Count > 0) { sb.AppendLine("Some writer(s) encountered null values. This is not a normal condition. Please contact LogShark owners for help."); sb.AppendLine("Counts per data set:"); sb.AppendLine(string.Join(Environment.NewLine, receivedNulls)); } } private static string GenerateTitle(string title) { return $"{Environment.NewLine}-----{title}-----"; } private static string GenerateHorizontalList(IEnumerable<string> list) { return string.Join("; ", list); } private static void AddErrorsCountByReporterToStringBuilder(ProcessingNotificationsCollector errorsCollector, StringBuilder report) { if (errorsCollector.ErrorCountByReporter == null) { return; } if (errorsCollector.ErrorCountByReporter.Count == 1) { report.AppendLine($"All errors reported by {errorsCollector.ErrorCountByReporter.First().Key}."); } else { report.AppendLine($"Error count by reporter:"); foreach (var (reporter, count) in errorsCollector.ErrorCountByReporter.OrderBy(kvp => kvp.Key)) { report.AppendLine($"{reporter?.PadRight(30, ' ') ?? "(null)"}: {count}"); } } } private static void AppendDetailedErrorsToStringBuilder(ProcessingNotificationsCollector errorsCollector, StringBuilder report) { foreach (var error in errorsCollector.ProcessingErrorsDetails ?? new List<ProcessingNotification>()) { report.AppendLine($"--> File: `{error.FilePath ?? "(null)"}`. Line: {error.LineNumber}. Reported by: `{error.ReportedBy ?? "(null)"}`. Error: `{error.Message ?? "(null)"}`"); } } } }
//----------------------------------------------------------------------------- // // <copyright file="VersionedStream.cs" company="Microsoft"> // Copyright (C) Microsoft Corporation. All rights reserved. // </copyright> // // Description: // This class provides file versioning support for streams provided by // IDataTransform implementations. // // History: // 02/21/2006: BruceMac: Initial implementation. // //----------------------------------------------------------------------------- using System; using System.IO; // for Stream using System.Windows; // ExceptionStringTable using System.Globalization; // for CultureInfo using MS.Internal.WindowsBase; namespace MS.Internal.IO.Packaging.CompoundFile { /// <summary> /// Maintains a FormatVersion for this stream and any number of sibling streams that semantically /// share the same version information (which is only persisted in one of the streams). /// </summary> internal class VersionedStream : Stream { //------------------------------------------------------ // // Public Methods // //------------------------------------------------------ #region Stream Methods /// <summary> /// Return the bytes requested from the container /// </summary> public override int Read(byte[] buffer, int offset, int count) { CheckDisposed(); // ReadAttempt accepts an optional boolean. If this is true, that means // we are expecting a legal FormatVersion to exist and that it is readable by our // code version. We do not want to force this check if we are empty. _versionOwner.ReadAttempt(_stream.Length > 0); return _stream.Read(buffer, offset, count); } /// <summary> /// Write /// </summary> public override void Write(byte[] buffer, int offset, int count) { CheckDisposed(); _versionOwner.WriteAttempt(); _stream.Write(buffer, offset, count); } /// <summary> /// ReadByte /// </summary> public override int ReadByte() { CheckDisposed(); // ReadAttempt accepts an optional boolean. If this is true, that means // we are expecting a legal FormatVersion to exist and that it is readable by our // code version. We do not want to force this check if we are empty. _versionOwner.ReadAttempt(_stream.Length > 0); return _stream.ReadByte(); } /// <summary> /// WriteByte /// </summary> public override void WriteByte(byte b) { CheckDisposed(); _versionOwner.WriteAttempt(); _stream.WriteByte(b); } /// <summary> /// Seek /// </summary> /// <param name="offset">offset</param> /// <param name="origin">origin</param> /// <returns>zero</returns> public override long Seek(long offset, SeekOrigin origin) { CheckDisposed(); return _stream.Seek(offset, origin); } /// <summary> /// SetLength /// </summary> public override void SetLength(long newLength) { CheckDisposed(); if (newLength < 0) throw new ArgumentOutOfRangeException("newLength"); _versionOwner.WriteAttempt(); _stream.SetLength(newLength); } /// <summary> /// Flush /// </summary> public override void Flush() { CheckDisposed(); _stream.Flush(); } #endregion Stream Methods //------------------------------------------------------ // // Public Properties // //------------------------------------------------------ #region Stream Properties /// <summary> /// Current logical position within the stream /// </summary> public override long Position { get { CheckDisposed(); return _stream.Position; } set { Seek(value, SeekOrigin.Begin); } } /// <summary> /// Length /// </summary> public override long Length { get { CheckDisposed(); return _stream.Length; } } /// <summary> /// Is stream readable? /// </summary> /// <remarks>returns false when called on disposed stream</remarks> public override bool CanRead { get { return (_stream != null) && _stream.CanRead && _versionOwner.IsReadable; } } /// <summary> /// Is stream seekable - should be handled by our owner /// </summary> /// <remarks>returns false when called on disposed stream</remarks> public override bool CanSeek { get { return (_stream != null) && _stream.CanSeek && _versionOwner.IsReadable; } } /// <summary> /// Is stream writeable? /// </summary> /// <remarks>returns false when called on disposed stream</remarks> public override bool CanWrite { get { return (_stream != null) && _stream.CanWrite && _versionOwner.IsUpdatable; } } #endregion //------------------------------------------------------ // // Internal Methods // //------------------------------------------------------ /// <summary> /// Constructor to use for any stream that shares versioning information with another stream /// but is not the one that houses the FormatVersion data itself. /// </summary> /// <param name="baseStream"></param> /// <param name="versionOwner"></param> internal VersionedStream(Stream baseStream, VersionedStreamOwner versionOwner) { if (baseStream == null) throw new ArgumentNullException("baseStream"); if (versionOwner == null) throw new ArgumentNullException("versionOwner"); _stream = baseStream; _versionOwner = versionOwner; } //------------------------------------------------------ // // Protected Methods // //------------------------------------------------------ /// <summary> /// Constructor for use by our subclass VersionedStreamOwner. /// </summary> /// <param name="baseStream"></param> protected VersionedStream(Stream baseStream) { if (baseStream == null) throw new ArgumentNullException("baseStream"); _stream = baseStream; // we are actually a VersionedStreamOwner _versionOwner = (VersionedStreamOwner)this; } /// <summary> /// Sometimes our subclass needs to read/write directly to the stream /// </summary> /// <remarks>Don't use CheckDisposed() here as we need to return null if we are disposed</remarks> protected Stream BaseStream { get { return _stream; } } /// <summary> /// Dispose(bool) /// </summary> /// <param name="disposing"></param> protected override void Dispose(bool disposing) { try { if (disposing && (_stream != null)) { _stream.Close(); } } finally { _stream = null; base.Dispose(disposing); } } /// <summary> /// Call this before accepting any public API call (except some Stream calls that /// are allowed to respond even when Closed /// </summary> protected void CheckDisposed() { if (_stream == null) throw new ObjectDisposedException(null, SR.Get(SRID.StreamObjectDisposed)); } //------------------------------------------------------ // // Private Fields // //------------------------------------------------------ private VersionedStreamOwner _versionOwner; private Stream _stream; // null indicates Disposed state } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using JetBrains.Annotations; namespace LinqToDB.SqlProvider { using SqlQuery; class JoinOptimizer { Dictionary<SqlSearchCondition,SqlSearchCondition> _additionalFilter; Dictionary<VirtualField,HashSet<Tuple<int,VirtualField>>> _equalityMap; Dictionary<Tuple<SqlTableSource,SqlTableSource>,List<FoundEquality>> _fieldPairCache; Dictionary<int,List<List<string>>> _keysCache; HashSet<int> _removedSources; Dictionary<VirtualField,VirtualField> _replaceMap; SelectQuery _selectQuery; SqlStatement _statement; static bool IsEqualTables(SqlTable table1, SqlTable table2) { var result = table1 != null && table2 != null && table1.ObjectType == table2.ObjectType && table1.Database == table2.Database && table1.Schema == table2.Schema && table1.Name == table2.Name && table1.PhysicalName == table2.PhysicalName; return result; } void FlattenJoins(SqlTableSource table) { for (var i = 0; i < table.Joins.Count; i++) { var j = table.Joins[i]; FlattenJoins(j.Table); if (j.JoinType == JoinType.Inner) for (var si = 0; si < j.Table.Joins.Count; si++) { var sj = j.Table.Joins[si]; if ((sj.JoinType == JoinType.Inner || sj.JoinType == JoinType.Left) && table != j.Table && !HasDependencyWithParent(j, sj)) { table.Joins.Insert(i + 1, sj); j.Table.Joins.RemoveAt(si); --si; } } } } bool IsDependedBetweenJoins(SqlTableSource table, SqlJoinedTable testedJoin) { var testedSources = new HashSet<int>(testedJoin.Table.GetTables().Select(t => t.SourceID)); foreach (var tableJoin in table.Joins) { if (testedSources.Contains(tableJoin.Table.SourceID)) continue; if (IsDependedOnJoin(table, tableJoin, testedSources)) return true; } return IsDependedExcludeJoins(testedSources); } bool IsDepended(SqlJoinedTable join, SqlJoinedTable toIgnore) { var testedSources = new HashSet<int>(join.Table.GetTables().Select(t => t.SourceID)); if (toIgnore != null) foreach (var sourceId in toIgnore.Table.GetTables().Select(t => t.SourceID)) testedSources.Add(sourceId); var dependent = false; new QueryVisitor().VisitParentFirst(_statement, e => { if (dependent) return false; // ignore non searchable parts if ( e.ElementType == QueryElementType.SelectClause || e.ElementType == QueryElementType.GroupByClause || e.ElementType == QueryElementType.OrderByClause) return false; if (e.ElementType == QueryElementType.JoinedTable) if (testedSources.Contains(((SqlJoinedTable) e).Table.SourceID)) return false; var expression = e as ISqlExpression; if (expression != null) { var field = GetUnderlayingField(expression); if (field != null) { var newField = GetNewField(field); var local = testedSources.Contains(newField.SourceID); if (local) dependent = !CanWeReplaceField(null, newField, testedSources, -1); } } return !dependent; }); return dependent; } bool IsDependedExcludeJoins(SqlJoinedTable join) { var testedSources = new HashSet<int>(join.Table.GetTables().Select(t => t.SourceID)); return IsDependedExcludeJoins(testedSources); } bool IsDependedExcludeJoins(HashSet<int> testedSources) { var dependent = false; bool CheckDependency(IQueryElement e) { if (dependent) return false; if (e.ElementType == QueryElementType.JoinedTable) return false; if (e is ISqlExpression expression) { var field = GetUnderlayingField(expression); if (field != null) { var newField = GetNewField(field); var local = testedSources.Contains(newField.SourceID); if (local) dependent = !CanWeReplaceField(null, newField, testedSources, -1); } } return !dependent; } //TODO: review dependency checking new QueryVisitor().VisitParentFirst(_selectQuery, CheckDependency); if (!dependent && _selectQuery.ParentSelect == null) new QueryVisitor().VisitParentFirst(_statement, CheckDependency); return dependent; } bool HasDependencyWithParent(SqlJoinedTable parent, SqlJoinedTable child) { var sources = new HashSet<int>(child.Table.GetTables().Select(t => t.SourceID)); var dependent = false; // check that parent has dependency on child new QueryVisitor().VisitParentFirst(parent, e => { if (dependent) return false; if (e == child) return false; if (e is ISqlExpression expression) { var field = GetUnderlayingField(expression); if (field != null) dependent = sources.Contains(field.SourceID); } return !dependent; }); return dependent; } bool IsDependedOnJoin(SqlTableSource table, SqlJoinedTable testedJoin, HashSet<int> testedSources) { var dependent = false; var currentSourceId = testedJoin.Table.SourceID; // check everyting that can be dependent on specific table new QueryVisitor().VisitParentFirst(testedJoin, e => { if (dependent) return false; if (e is ISqlExpression expression) { var field = GetUnderlayingField(expression); if (field != null) { var newField = GetNewField(field); var local = testedSources.Contains(newField.SourceID); if (local) dependent = !CanWeReplaceField(table, newField, testedSources, currentSourceId); } } return !dependent; }); return dependent; } bool CanWeReplaceFieldInternal( SqlTableSource table, VirtualField field, HashSet<int> excludeSourceIds, int testedSourceIndex, HashSet<VirtualField> visited) { if (visited.Contains(field)) return false; if (!excludeSourceIds.Contains(field.SourceID) && !IsSourceRemoved(field.SourceID)) return true; visited.Add(field); if (_equalityMap == null) return false; if (testedSourceIndex < 0) return false; if (_equalityMap.TryGetValue(field, out var sameFields)) foreach (var pair in sameFields) if ((testedSourceIndex == 0 || GetSourceIndex(table, pair.Item1) > testedSourceIndex) && CanWeReplaceFieldInternal(table, pair.Item2, excludeSourceIds, testedSourceIndex, visited)) return true; return false; } bool CanWeReplaceField(SqlTableSource table, VirtualField field, HashSet<int> excludeSourceId, int testedSourceId) { var visited = new HashSet<VirtualField>(); return CanWeReplaceFieldInternal(table, field, excludeSourceId, GetSourceIndex(table, testedSourceId), visited); } VirtualField GetNewField(VirtualField field) { if (_replaceMap == null) return field; if (_replaceMap.TryGetValue(field, out var newField)) { while (_replaceMap.TryGetValue(newField, out var fieldOther)) newField = fieldOther; } else { newField = field; } return newField; } VirtualField MapToSourceInternal(SqlTableSource fromTable, VirtualField field, int sourceId, HashSet<VirtualField> visited) { if (visited.Contains(field)) return null; if (field.SourceID == sourceId) return field; visited.Add(field); if (_equalityMap == null) return null; var sourceIndex = GetSourceIndex(fromTable, sourceId); HashSet<Tuple<int, VirtualField>> sameFields; if (_equalityMap.TryGetValue(field, out sameFields)) foreach (var pair in sameFields) { var itemIndex = GetSourceIndex(fromTable, pair.Item1); if (itemIndex >= 0 && (sourceIndex == 0 || itemIndex < sourceIndex)) { var newField = MapToSourceInternal(fromTable, pair.Item2, sourceId, visited); if (newField != null) return newField; } } return null; } VirtualField MapToSource(SqlTableSource table, VirtualField field, int sourceId) { var visited = new HashSet<VirtualField>(); return MapToSourceInternal(table, field, sourceId, visited); } void RemoveSource(SqlTableSource fromTable, SqlJoinedTable join) { if (_removedSources == null) _removedSources = new HashSet<int>(); _removedSources.Add(join.Table.SourceID); if (_equalityMap != null) { var keys = _equalityMap.Keys.Where(k => k.SourceID == join.Table.SourceID).ToArray(); foreach (var key in keys) { var newField = MapToSource(fromTable, key, fromTable.SourceID); if (newField != null) ReplaceField(key, newField); _equalityMap.Remove(key); } } ResetFieldSearchCache(join.Table); } bool IsSourceRemoved(int sourceId) { return _removedSources != null && _removedSources.Contains(sourceId); } void ReplaceField(VirtualField oldField, VirtualField newField) { if (_replaceMap == null) _replaceMap = new Dictionary<VirtualField, VirtualField>(); _replaceMap.Remove(oldField); _replaceMap.Add (oldField, newField); } void AddEqualFields(VirtualField field1, VirtualField field2, int levelSourceId) { if (_equalityMap == null) _equalityMap = new Dictionary<VirtualField, HashSet<Tuple<int, VirtualField>>>(); HashSet<Tuple<int, VirtualField>> set; if (!_equalityMap.TryGetValue(field1, out set)) { set = new HashSet<Tuple<int, VirtualField>>(); _equalityMap.Add(field1, set); } set.Add(Tuple.Create(levelSourceId, field2)); } bool CompareExpressions(SqlPredicate.ExprExpr expr1, SqlPredicate.ExprExpr expr2) { if (expr1.Operator != expr2.Operator) return false; if (expr1.ElementType != expr2.ElementType) return false; switch (expr1.ElementType) { case QueryElementType.ExprExprPredicate: { return CompareExpressions(expr1.Expr1, expr2.Expr1) == true && CompareExpressions(expr1.Expr2, expr2.Expr2) == true || CompareExpressions(expr1.Expr1, expr2.Expr2) == true && CompareExpressions(expr1.Expr2, expr2.Expr1) == true; } } return false; } bool? CompareExpressions(ISqlExpression expr1, ISqlExpression expr2) { if (expr1.ElementType != expr2.ElementType) return null; switch (expr1.ElementType) { case QueryElementType.Column: { return CompareExpressions(((SqlColumn) expr1).Expression, ((SqlColumn) expr2).Expression); } case QueryElementType.SqlField: { var field1 = GetNewField(new VirtualField((SqlField) expr1)); var field2 = GetNewField(new VirtualField((SqlField) expr2)); return field1.Equals(field2); } } return null; } bool CompareConditions(SqlCondition cond1, SqlCondition cond2) { if (cond1.ElementType != cond2.ElementType) return false; if (cond1.Predicate.ElementType != cond2.Predicate.ElementType) return false; switch (cond1.Predicate.ElementType) { case QueryElementType.IsNullPredicate: { var isNull1 = (SqlPredicate.IsNull) cond1.Predicate; var isNull2 = (SqlPredicate.IsNull) cond2.Predicate; return isNull1.IsNot == isNull2.IsNot && CompareExpressions(isNull1.Expr1, isNull2.Expr1) == true; } case QueryElementType.ExprExprPredicate: { var expr1 = (SqlPredicate.ExprExpr) cond1.Predicate; var expr2 = (SqlPredicate.ExprExpr) cond2.Predicate; return CompareExpressions(expr1, expr2); } } return false; } bool? EvaluateLogical(SqlCondition condition) { switch (condition.ElementType) { case QueryElementType.Condition: { if (condition.Predicate is SqlPredicate.ExprExpr expr && expr.Operator == SqlPredicate.Operator.Equal) return CompareExpressions(expr.Expr1, expr.Expr2); break; } } return null; } void OptimizeSearchCondition(SqlSearchCondition searchCondition) { var items = searchCondition.Conditions; if (items.Any(c => c.IsOr)) return; for (var i1 = 0; i1 < items.Count; i1++) { var c1 = items[i1]; var cmp = EvaluateLogical(c1); if (cmp != null) if (cmp.Value) { items.RemoveAt(i1); --i1; continue; } switch (c1.ElementType) { case QueryElementType.Condition: case QueryElementType.SearchCondition: { if (c1.Predicate is SqlSearchCondition search) { OptimizeSearchCondition(search); if (search.Conditions.Count == 0) { items.RemoveAt(i1); --i1; continue; } } break; } } for (var i2 = i1 + 1; i2 < items.Count; i2++) { var c2 = items[i2]; if (CompareConditions(c2, c1)) { searchCondition.Conditions.RemoveAt(i2); --i2; } } } } void AddSearchCondition(SqlSearchCondition search, SqlCondition condition) { AddSearchConditions(search, new[] {condition}); } void AddSearchConditions(SqlSearchCondition search, IEnumerable<SqlCondition> conditions) { if (_additionalFilter == null) _additionalFilter = new Dictionary<SqlSearchCondition, SqlSearchCondition>(); if (!_additionalFilter.TryGetValue(search, out var value)) { if (search.Conditions.Count > 0 && search.Precedence < Precedence.LogicalConjunction) { value = new SqlSearchCondition(); var prev = new SqlSearchCondition(); prev. Conditions.AddRange(search.Conditions); search.Conditions.Clear(); search.Conditions.Add(new SqlCondition(false, value, false)); search.Conditions.Add(new SqlCondition(false, prev, false)); } else { value = search; } _additionalFilter.Add(search, value); } value.Conditions.AddRange(conditions); } void OptimizeFilters() { if (_additionalFilter == null) return; foreach (var pair in _additionalFilter) { OptimizeSearchCondition(pair.Value); if (!ReferenceEquals(pair.Key, pair.Value) && pair.Value.Conditions.Count == 1) { // conditions can be optimized so we have to remove empty SearchCondition if (pair.Value.Conditions[0].Predicate is SqlSearchCondition searchCondition && searchCondition.Conditions.Count == 0) pair.Key.Conditions.Remove(pair.Value.Conditions[0]); } } } Dictionary<string, VirtualField> GetFields(ISqlTableSource source) { var res = new Dictionary<string, VirtualField>(); if (source is SqlTable table) foreach (var pair in table.Fields) res.Add(pair.Key, new VirtualField(pair.Value)); return res; } void ReplaceSource(SqlTableSource fromTable, SqlJoinedTable oldSource, SqlTableSource newSource) { var oldFields = GetFields(oldSource.Table.Source); var newFields = GetFields(newSource.Source); foreach (var old in oldFields) { var newField = newFields[old.Key]; ReplaceField(old.Value, newField); } RemoveSource(fromTable, oldSource); } void CorrectMappings() { if (_replaceMap != null && _replaceMap.Count > 0 || _removedSources != null) { ((ISqlExpressionWalkable)_statement) .Walk(false, element => { if (element is SqlField field) return GetNewField(new VirtualField(field)).Element; if (element is SqlColumn column) return GetNewField(new VirtualField(column)).Element; return element; }); } } int GetSourceIndex(SqlTableSource table, int sourceId) { if (table == null || table.SourceID == sourceId || sourceId == -1) return 0; var i = 0; while (i < table.Joins.Count) { if (table.Joins[i].Table.SourceID == sourceId) return i + 1; ++i; } return -1; } void CollectEqualFields(SqlJoinedTable join) { if (join.JoinType != JoinType.Inner) return; if (join.Condition.Conditions.Any(c => c.IsOr)) return; for (var i1 = 0; i1 < join.Condition.Conditions.Count; i1++) { var c = join.Condition.Conditions[i1]; if ( c.ElementType != QueryElementType.Condition || c.Predicate.ElementType != QueryElementType.ExprExprPredicate || ((SqlPredicate.ExprExpr) c.Predicate).Operator != SqlPredicate.Operator.Equal) continue; var predicate = (SqlPredicate.ExprExpr) c.Predicate; var field1 = GetUnderlayingField(predicate.Expr1); if (field1 == null) continue; var field2 = GetUnderlayingField(predicate.Expr2); if (field2 == null) continue; if (field1.Equals(field2)) continue; AddEqualFields(field1, field2, join.Table.SourceID); AddEqualFields(field2, field1, join.Table.SourceID); } } List<List<string>> GetKeysInternal(ISqlTableSource tableSource) { //TODO: needed mechanism to define unique indexes. Currently only primary key is used // only from tables we can get keys if (!(tableSource is SqlTable)) return null; var keys = tableSource.GetKeys(false); if (keys == null || keys.Count == 0) return null; var fields = keys.Select(GetUnderlayingField) .Where(f => f != null) .Select(f => f.Name).ToList(); if (fields.Count != keys.Count) return null; var knownKeys = new List<List<string>> { fields }; return knownKeys; } List<List<string>> GetKeys(ISqlTableSource tableSource) { if (_keysCache == null || !_keysCache.TryGetValue(tableSource.SourceID, out var keys)) { keys = GetKeysInternal(tableSource); if (_keysCache == null) _keysCache = new Dictionary<int, List<List<string>>>(); _keysCache.Add(tableSource.SourceID, keys); } return keys; } public void OptimizeJoins(SqlStatement statement, SelectQuery selectQuery) { _selectQuery = selectQuery; _statement = statement; for (var i = 0; i < selectQuery.From.Tables.Count; i++) { var fromTable = selectQuery.From.Tables[i]; FlattenJoins(fromTable); for (var i1 = 0; i1 < fromTable.Joins.Count; i1++) { var j1 = fromTable.Joins[i1]; CollectEqualFields(j1); // supported only INNER and LEFT joins if (j1.JoinType != JoinType.Inner && j1.JoinType != JoinType.Left) continue; // trying to remove join that is equal to FROM table if (IsEqualTables(fromTable.Source as SqlTable, j1.Table.Source as SqlTable)) { var keys = GetKeys(j1.Table.Source); if (keys != null && TryMergeWithTable(fromTable, j1, keys)) { fromTable.Joins.RemoveAt(i1); --i1; continue; } } for (var i2 = i1 + 1; i2 < fromTable.Joins.Count; i2++) { var j2 = fromTable.Joins[i2]; // we can merge LEFT and INNER joins together if (j2.JoinType != JoinType.Inner && j2.JoinType != JoinType.Left) continue; if (!IsEqualTables(j1.Table.Source as SqlTable, j2.Table.Source as SqlTable)) continue; var keys = GetKeys(j2.Table.Source); if (keys != null) { // try merge if joins are the same var merged = TryMergeJoins(fromTable, fromTable, j1, j2, keys); if (!merged) for (var im = 0; im < i2; im++) if (fromTable.Joins[im].JoinType == JoinType.Inner || j2.JoinType != JoinType.Left) { merged = TryMergeJoins(fromTable, fromTable.Joins[im].Table, j1, j2, keys); if (merged) break; } if (merged) { fromTable.Joins.RemoveAt(i2); --i2; } } } } // trying to remove joins that are not in projection for (var i1 = 0; i1 < fromTable.Joins.Count; i1++) { var j1 = fromTable.Joins[i1]; if (j1.JoinType == JoinType.Left || j1.JoinType == JoinType.Inner) { var keys = GetKeys(j1.Table.Source); if (keys != null && !IsDependedBetweenJoins(fromTable, j1)) { // try merge if joins are the same var removed = TryToRemoveIndependent(fromTable, fromTable, j1, keys); if (!removed) for (var im = 0; im < i1; im++) { var jm = fromTable.Joins[im]; if (jm.JoinType == JoinType.Inner || jm.JoinType != JoinType.Left) { removed = TryToRemoveIndependent(fromTable, jm.Table, j1, keys); if (removed) break; } } if (removed) { fromTable.Joins.RemoveAt(i1); --i1; } } } } // independent joins loop } // table loop OptimizeFilters(); CorrectMappings(); } static VirtualField GetUnderlayingField(ISqlExpression expr) { switch (expr.ElementType) { case QueryElementType.SqlField: return new VirtualField((SqlField) expr); case QueryElementType.Column: return new VirtualField((SqlColumn)expr); } return null; } void DetectField(SqlTableSource manySource, SqlTableSource oneSource, VirtualField field, FoundEquality equality) { field = GetNewField(field); if (oneSource.Source.SourceID == field.SourceID) equality.OneField = field; else if (manySource.Source.SourceID == field.SourceID) equality.ManyField = field; else equality.ManyField = MapToSource(manySource, field, manySource.Source.SourceID); } bool MatchFields(SqlTableSource manySource, SqlTableSource oneSource, VirtualField field1, VirtualField field2, FoundEquality equality) { if (field1 == null || field2 == null) return false; DetectField(manySource, oneSource, field1, equality); DetectField(manySource, oneSource, field2, equality); return equality.OneField != null && equality.ManyField != null; } void ResetFieldSearchCache(SqlTableSource table) { if (_fieldPairCache == null) return; var keys = _fieldPairCache.Keys.Where(k => k.Item2 == table || k.Item1 == table).ToArray(); foreach (var key in keys) _fieldPairCache.Remove(key); } List<FoundEquality> SearchForFields(SqlTableSource manySource, SqlJoinedTable join) { var key = Tuple.Create(manySource, join.Table); List<FoundEquality> found = null; if (_fieldPairCache != null && _fieldPairCache.TryGetValue(key, out found)) return found; for (var i1 = 0; i1 < join.Condition.Conditions.Count; i1++) { var c = join.Condition.Conditions[i1]; if (c.IsOr) { found = null; break; } if ( c.ElementType != QueryElementType.Condition || c.Predicate.ElementType != QueryElementType.ExprExprPredicate || ((SqlPredicate.ExprExpr) c.Predicate).Operator != SqlPredicate.Operator.Equal) continue; var predicate = (SqlPredicate.ExprExpr) c.Predicate; var equality = new FoundEquality(); if (!MatchFields(manySource, join.Table, GetUnderlayingField(predicate.Expr1), GetUnderlayingField(predicate.Expr2), equality)) continue; equality.OneCondition = c; if (found == null) found = new List<FoundEquality>(); found.Add(equality); } if (_fieldPairCache == null) _fieldPairCache = new Dictionary<Tuple<SqlTableSource, SqlTableSource>, List<FoundEquality>>(); _fieldPairCache.Add(key, found); return found; } bool TryMergeWithTable(SqlTableSource fromTable, SqlJoinedTable join, List<List<string>> uniqueKeys) { if (join.Table.Joins.Count != 0) return false; var hasLeftJoin = join.JoinType == JoinType.Left; var found = SearchForFields(fromTable, join); if (found == null) return false; // for removing join with same table fields should be equal found = found.Where(f => f.OneField.Name == f.ManyField.Name).ToList(); if (found.Count == 0) return false; if (hasLeftJoin) { if (join.Condition.Conditions.Count != found.Count) return false; // currently no dependencies in search condition allowed for left join if (IsDependedExcludeJoins(join)) return false; } HashSet<string> foundFields = new HashSet<string>(found.Select(f => f.OneField.Name)); HashSet<string> uniqueFields = null; for (var i = 0; i < uniqueKeys.Count; i++) { var keys = uniqueKeys[i]; if (keys.All(k => foundFields.Contains(k))) { if (uniqueFields == null) uniqueFields = new HashSet<string>(); foreach (var key in keys) uniqueFields.Add(key); } } if (uniqueFields != null) { foreach (var item in found) if (uniqueFields.Contains(item.OneField.Name)) { // remove unique key conditions join.Condition.Conditions.Remove(item.OneCondition); AddEqualFields(item.ManyField, item.OneField, fromTable.SourceID); } // move rest conditions to the Where section if (join.Condition.Conditions.Count > 0) { AddSearchConditions(_selectQuery.Where.SearchCondition, join.Condition.Conditions); join.Condition.Conditions.Clear(); } // add check that previously joined fields is not null foreach (var item in found) if (item.ManyField.CanBeNull) { var newField = MapToSource(fromTable, item.ManyField, fromTable.SourceID); AddSearchCondition(_selectQuery.Where.SearchCondition, new SqlCondition(false, new SqlPredicate.IsNull(newField.Element, true))); } // add mapping to new source ReplaceSource(fromTable, join, fromTable); return true; } return false; } bool TryMergeJoins(SqlTableSource fromTable, SqlTableSource manySource, SqlJoinedTable join1, SqlJoinedTable join2, List<List<string>> uniqueKeys) { var found1 = SearchForFields(manySource, join1); if (found1 == null) return false; var found2 = SearchForFields(manySource, join2); if (found2 == null) return false; var hasLeftJoin = join1.JoinType == JoinType.Left || join2.JoinType == JoinType.Left; // left join should match exactly if (hasLeftJoin) { if (join1.Condition.Conditions.Count != join2.Condition.Conditions.Count) return false; if (found1.Count != found2.Count) return false; if (join1.Table.Joins.Count != 0 || join2.Table.Joins.Count != 0) return false; } List<FoundEquality> found = null; for (var i1 = 0; i1 < found1.Count; i1++) { var f1 = found1[i1]; for (var i2 = 0; i2 < found2.Count; i2++) { var f2 = found2[i2]; if (f1.ManyField.Name == f2.ManyField.Name && f1.OneField.Name == f2.OneField.Name) { if (found == null) found = new List<FoundEquality>(); found.Add(f2); } } } if (found == null) return false; if (hasLeftJoin) { // for left join each expression should be used if (found.Count != join1.Condition.Conditions.Count) return false; // currently no dependencies in search condition allowed for left join if (IsDepended(join1, join2)) return false; } HashSet<string> foundFields = new HashSet<string>(found.Select(f => f.OneField.Name)); HashSet<string> uniqueFields = null; for (var i = 0; i < uniqueKeys.Count; i++) { var keys = uniqueKeys[i]; if (keys.All(k => foundFields.Contains(k))) { if (uniqueFields == null) uniqueFields = new HashSet<string>(); foreach (var key in keys) uniqueFields.Add(key); } } if (uniqueFields != null) { foreach (var item in found) if (uniqueFields.Contains(item.OneField.Name)) { // remove from second join2.Condition.Conditions.Remove(item.OneCondition); AddEqualFields(item.ManyField, item.OneField, fromTable.SourceID); } // move rest conditions to first if (join2.Condition.Conditions.Count > 0) { AddSearchConditions(join1.Condition, join2.Condition.Conditions); join2.Condition.Conditions.Clear(); } join1.Table.Joins.AddRange(join2.Table.Joins); // add mapping to new source ReplaceSource(fromTable, join2, join1.Table); return true; } return false; } // here we can deal with LEFT JOIN and INNER JOIN bool TryToRemoveIndependent( SqlTableSource fromTable, SqlTableSource manySource, SqlJoinedTable join, List<List<string>> uniqueKeys) { if (join.JoinType == JoinType.Inner) return false; var found = SearchForFields(manySource, join); if (found == null) return false; HashSet<string> foundFields = new HashSet<string>(found.Select(f => f.OneField.Name)); HashSet<string> uniqueFields = null; for (var i = 0; i < uniqueKeys.Count; i++) { var keys = uniqueKeys[i]; if (keys.All(k => foundFields.Contains(k))) { if (uniqueFields == null) uniqueFields = new HashSet<string>(); foreach (var key in keys) uniqueFields.Add(key); } } if (uniqueFields != null) { if (join.JoinType == JoinType.Inner) { foreach (var item in found) if (uniqueFields.Contains(item.OneField.Name)) { // remove from second join.Condition.Conditions.Remove(item.OneCondition); AddEqualFields(item.ManyField, item.OneField, fromTable.SourceID); } // move rest conditions to Where if (join.Condition.Conditions.Count > 0) { AddSearchConditions(_selectQuery.Where.SearchCondition, join.Condition.Conditions); join.Condition.Conditions.Clear(); } // add filer for nullable fileds because after INNER JOIN records with nulls disappear foreach (var item in found) if (item.ManyField.CanBeNull) AddSearchCondition(_selectQuery.Where.SearchCondition, new SqlCondition(false, new SqlPredicate.IsNull(item.ManyField.Element, true))); } RemoveSource(fromTable, join); return true; } return false; } [DebuggerDisplay("{ManyField.DisplayString()} -> {OneField.DisplayString()}")] class FoundEquality { public VirtualField ManyField; public SqlCondition OneCondition; public VirtualField OneField; } [DebuggerDisplay("{DisplayString()}")] class VirtualField { public VirtualField([NotNull] SqlField field) { Field = field ?? throw new ArgumentNullException(nameof(field)); } public VirtualField([NotNull] SqlColumn column) { Column = column ?? throw new ArgumentNullException(nameof(column)); } public SqlField Field { get; } public SqlColumn Column { get; } public string Name => Field == null ? Column.Alias : Field.Name; public int SourceID => Field == null ? Column.Parent.SourceID : Field.Table?.SourceID ?? -1; public bool CanBeNull => Field?.CanBeNull ?? Column.CanBeNull; public ISqlExpression Element { get { if (Field != null) return Field; return Column; } } protected bool Equals(VirtualField other) { return Equals(Field, other.Field) && Equals(Column, other.Column); } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; if (obj.GetType() != GetType()) return false; return Equals((VirtualField) obj); } string GetSourceString(ISqlTableSource source) { if (source is SqlTable table) { var res = $"({source.SourceID}).{table.Name}"; if (table.Alias != table.Name && !string.IsNullOrEmpty(table.Alias)) res = res + "(" + table.Alias + ")"; return res; } return $"({source.SourceID}).{source}"; } public string DisplayString() { if (Field != null) return $"F: '{GetSourceString(Field.Table)}.{Name}'"; return $"C: '{GetSourceString(Column.Parent)}.{Name}'"; } public override int GetHashCode() { unchecked { return ((Field != null ? Field.GetHashCode() : 0) * 397) ^ (Column != null ? Column.GetHashCode() : 0); } } } } }
// This file was created automatically, do not modify the contents of this file. // ReSharper disable InvalidXmlDocComment // ReSharper disable InconsistentNaming // ReSharper disable CheckNamespace // ReSharper disable MemberCanBePrivate.Global using System; using System.Runtime.InteropServices; // Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\AIModule\Classes\AITypes.h:489 namespace UnrealEngine { public partial class FAIMoveRequest : NativeStructWrapper { public FAIMoveRequest(IntPtr NativePointer, bool IsRef = false) : base(NativePointer, IsRef) { } public FAIMoveRequest() : base(E_CreateStruct_FAIMoveRequest(), false) { } public FAIMoveRequest(AActor inGoalActor) : base(E_CreateStruct_FAIMoveRequest_AActor(inGoalActor), false) { } public FAIMoveRequest(FVector inGoalLocation) : base(E_CreateStruct_FAIMoveRequest_FVector(inGoalLocation), false) { } #region DLLInmport [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr E_CreateStruct_FAIMoveRequest(); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr E_CreateStruct_FAIMoveRequest_AActor(IntPtr inGoalActor); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr E_CreateStruct_FAIMoveRequest_FVector(IntPtr inGoalLocation); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern bool E_FAIMoveRequest_CanStopOnOverlap(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern bool E_FAIMoveRequest_CanStrafe(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern float E_FAIMoveRequest_GetAcceptanceRadius(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr E_FAIMoveRequest_GetDestination(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern ObjectPointerDescription E_FAIMoveRequest_GetGoalActor(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr E_FAIMoveRequest_GetGoalLocation(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern int E_FAIMoveRequest_GetUserFlags(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern bool E_FAIMoveRequest_IsMoveToActorRequest(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern bool E_FAIMoveRequest_IsProjectingGoal(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern bool E_FAIMoveRequest_IsReachTestIncludingAgentRadius(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern bool E_FAIMoveRequest_IsReachTestIncludingGoalRadius(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern bool E_FAIMoveRequest_IsUsingPartialPaths(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern bool E_FAIMoveRequest_IsUsingPathfinding(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern bool E_FAIMoveRequest_IsValid(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr E_FAIMoveRequest_SetAcceptanceRadius(IntPtr self, float radius); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr E_FAIMoveRequest_SetAllowPartialPath(IntPtr self, bool bAllowPartial); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr E_FAIMoveRequest_SetCanStrafe(IntPtr self, bool bStrafe); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_FAIMoveRequest_SetGoalActor(IntPtr self, IntPtr inGoalActor); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_FAIMoveRequest_SetGoalLocation(IntPtr self, IntPtr inGoalLocation); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr E_FAIMoveRequest_SetProjectGoalLocation(IntPtr self, bool bProject); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr E_FAIMoveRequest_SetReachTestIncludesAgentRadius(IntPtr self, bool bIncludeRadius); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr E_FAIMoveRequest_SetReachTestIncludesGoalRadius(IntPtr self, bool bIncludeRadius); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr E_FAIMoveRequest_SetStopOnOverlap(IntPtr self, bool bStop); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr E_FAIMoveRequest_SetUsePathfinding(IntPtr self, bool bPathfinding); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr E_FAIMoveRequest_SetUserFlags(IntPtr self, int inUserFlags); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern StringWrapper E_FAIMoveRequest_ToString(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern bool E_FAIMoveRequest_UpdateGoalLocation(IntPtr self, IntPtr newLocation); #endregion #region ExternMethods public bool CanStopOnOverlap() => E_FAIMoveRequest_CanStopOnOverlap(this); public bool CanStrafe() => E_FAIMoveRequest_CanStrafe(this); public float GetAcceptanceRadius() => E_FAIMoveRequest_GetAcceptanceRadius(this); /// <summary> /// retrieves request's requested destination location, GoalActor's location /// <para>or GoalLocation, depending on the request itself </para> /// </summary> public FVector GetDestination() => E_FAIMoveRequest_GetDestination(this); public AActor GetGoalActor() => E_FAIMoveRequest_GetGoalActor(this); public FVector GetGoalLocation() => E_FAIMoveRequest_GetGoalLocation(this); public int GetUserFlags() => E_FAIMoveRequest_GetUserFlags(this); public bool IsMoveToActorRequest() => E_FAIMoveRequest_IsMoveToActorRequest(this); public bool IsProjectingGoal() => E_FAIMoveRequest_IsProjectingGoal(this); public bool IsReachTestIncludingAgentRadius() => E_FAIMoveRequest_IsReachTestIncludingAgentRadius(this); public bool IsReachTestIncludingGoalRadius() => E_FAIMoveRequest_IsReachTestIncludingGoalRadius(this); public bool IsUsingPartialPaths() => E_FAIMoveRequest_IsUsingPartialPaths(this); public bool IsUsingPathfinding() => E_FAIMoveRequest_IsUsingPathfinding(this); /// <summary> /// the request should be either set up to move to a location, of go to a valid actor /// </summary> public bool IsValid() => E_FAIMoveRequest_IsValid(this); public FAIMoveRequest SetAcceptanceRadius(float radius) => E_FAIMoveRequest_SetAcceptanceRadius(this, radius); public FAIMoveRequest SetAllowPartialPath(bool bAllowPartial) => E_FAIMoveRequest_SetAllowPartialPath(this, bAllowPartial); public FAIMoveRequest SetCanStrafe(bool bStrafe) => E_FAIMoveRequest_SetCanStrafe(this, bStrafe); public void SetGoalActor(AActor inGoalActor) => E_FAIMoveRequest_SetGoalActor(this, inGoalActor); public void SetGoalLocation(FVector inGoalLocation) => E_FAIMoveRequest_SetGoalLocation(this, inGoalLocation); public FAIMoveRequest SetProjectGoalLocation(bool bProject) => E_FAIMoveRequest_SetProjectGoalLocation(this, bProject); public FAIMoveRequest SetReachTestIncludesAgentRadius(bool bIncludeRadius) => E_FAIMoveRequest_SetReachTestIncludesAgentRadius(this, bIncludeRadius); public FAIMoveRequest SetReachTestIncludesGoalRadius(bool bIncludeRadius) => E_FAIMoveRequest_SetReachTestIncludesGoalRadius(this, bIncludeRadius); public FAIMoveRequest SetStopOnOverlap(bool bStop) => E_FAIMoveRequest_SetStopOnOverlap(this, bStop); public FAIMoveRequest SetUsePathfinding(bool bPathfinding) => E_FAIMoveRequest_SetUsePathfinding(this, bPathfinding); public FAIMoveRequest SetUserFlags(int inUserFlags) => E_FAIMoveRequest_SetUserFlags(this, inUserFlags); public override string ToString() => E_FAIMoveRequest_ToString(this); public bool UpdateGoalLocation(FVector newLocation) => E_FAIMoveRequest_UpdateGoalLocation(this, newLocation); #endregion public static implicit operator IntPtr(FAIMoveRequest self) { return self?.NativePointer ?? IntPtr.Zero; } public static implicit operator FAIMoveRequest(IntPtr adress) { return adress == IntPtr.Zero ? null : new FAIMoveRequest(adress, false); } } }
// ========================================================================= // Copyright (C) Harbor 2008. All Rights Reserved. Confidential // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // File: SudokuSolver.cs // Project: // Author: harbor // Creation date: 09.11.2007 // based on // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // D e s c r i p t i o n : // // Sudoku-Solver // // E n d D e s c r i p t i o n // ========================================================================= // ######################################################################### // using // ######################################################################### using System; using System.Collections.Generic; using System.Text; using System.IO; using System.Globalization; // ######################################################################### // basic data types // ######################################################################### //bool //char //16bit unicode //float //double //decimal //string //object //typedef byte Bitf8; //typedef ushort Bitf16; //typedef uint Bitf32; //typedef sbyte Int8; //typedef short Int16; //typedef int Int32; //typedef long Int64; //typedef byte Uint8; //typedef ushort Uint16; //typedef uint Uint32; //typedef ulong Uint64; // ######################################################################### // namespace // ######################################################################### namespace Sudoku { // ######################################################################### // class // ######################################################################### public sealed class BitSet { private BitSet() { } public static void Include(ref ulong bitValue, int value) { bitValue |= (ulong)(1L << (value & 63)); } public static void Include(ref uint bitValue, int value) { bitValue |= (uint)(1 << (value & 31)); } public static void Include(ref ushort bitValue, int value) { bitValue |= (ushort)(1 << (value & 15)); } public static void Include(ref byte bitValue, int value) { bitValue |= (byte)(1 << (value & 7)); } public static void Exclude(ref ulong bitValue, int value) { bitValue &= (ulong)~(1L << (value & 63)); } public static void Exclude(ref uint bitValue, int value) { bitValue &= (uint)~(1 << (value & 31)); } public static void Exclude(ref ushort bitValue, int value) { bitValue &= (ushort)~(1 << (value & 15)); } public static void Exclude(ref byte bitValue, int value) { bitValue &= (byte)~(1 << (value & 7)); } public static bool IsInBitset(ulong bitValue, int value) { if ((bitValue & (ulong)(1L << (value & 63))) != 0) { return true; } else { return false; } } public static bool IsInBitset(uint bitValue, int value) { if ((bitValue & (1 << (value & 31))) != 0) { return true; } else { return false; } } public static bool IsInBitset(ushort bitValue, int value) { if ((bitValue & (1 << (value & 15))) != 0) { return true; } else { return false; } } public static bool IsInBitset(byte bitValue, int value) { if ((bitValue & (1 << (value & 7))) != 0) { return true; } else { return false; } } } [Flags] public enum SudokuOption { None, WithFile = 1, AddonInFile = 2, WithFileAddon = WithFile | AddonInFile }; public enum SudokuError { None, WrongInput, FewValues, Aborted }; // ######################################################################### // class // ######################################################################### public sealed class SudokuSolver : IDisposable { // ######################################################################### // constants // ######################################################################### public const uint Max = 9; private const uint Min = 1; private const uint CarreeMax = 3; //(uint)Math.Sqrt(Max); private const uint MinInputValues = 15; private const string Try = "**********Try*********"; private const string TryNotOk = "*** Try not OK ***"; private const string TryIsPossible = "*** Try is possible ***"; private const string TryInRowColumn = "*** Try in [Row, Column] "; //public enum tValue { 0 .. Max }; //public enum tIndex { 0 .. (Max-1) }; // ######################################################################### // data types // ######################################################################### private struct ValueType { public uint Occupied; //Bitset public uint Number; //tValue //public override bool Equals(object obj) { // return base.Equals(obj); //} //public override int GetHashCode() { // return base.GetHashCode(); //} } private class TryValueType { public uint Occupied; public uint Number; //tValue public uint Row; //tIndex public uint Column; //tIndex } // ######################################################################### // variables // ######################################################################### private bool fileOpen; private bool fileOpenForAll; private StreamWriter streamWriter; private bool[,] pass2Checked = new bool[Max, Max]; //array[tIndex,tIndex]; private uint[] m_smallField = new uint[Max]; private bool m_abort; // ######################################################################### // class // ######################################################################### private class SolveHelper { // ######################################################################### // constants // ######################################################################### //private const string PossibleResults = "moegliche Ergebnisse [Zeile, Spalte]"; //private const string EvaluateText = "Bewerten"; //private const string RowTest = "Zeilentest"; //private const string ColumnTest = "Spaltentest"; //private const string CarreeTest = "Carreetest"; //private const string Inputs = "Eingabe:"; //private const string Result = "Ergebnis:"; //private const string Insert = "Fuege "; //private const string To = " in "; //private const string Ein = " ein"; //private const string Row = "Zeile "; //private const string Column = "Spalte "; //private const string Carree = "Carree "; //private const string Finished = " fertig"; private const string PossibleResults = "Possible results [Row, Column]"; private const string EvaluateText = "Evaluate"; private const string RowTest = "Testing rows"; private const string ColumnTest = "Testing columns"; private const string CarreeTest = "Testing carrees"; private const string Inputs = "Inputs:"; private const string Result = "Result:"; private const string Insert = "Insert "; private const string To = " to "; private const string Ein = ""; private const string Row = "row "; private const string Column = "column "; private const string Carree = "carree "; private const string Finished = " finished"; // ######################################################################### // variables // ######################################################################### public uint[,] board = new uint[Max, Max]; // Playing board //tBoard = array[tIndex,tIndex] of tValue; public ValueType[,] boardEstimation = new ValueType[Max, Max]; //array[tIndex,tIndex] of ValueType; public TryValueType tryValue = new TryValueType(); private bool m_reCalc; private uint[,] sudokuBoard = new uint[Max, Max]; //sudokuBoard : tBoard; private ValueType[] columns = new ValueType[Max]; //array[tIndex]; private ValueType[] rows = new ValueType[Max]; //array[tIndex]; private ValueType[] carrees = new ValueType[Max]; //array[tIndex]; private SudokuSolver sudoku; //private bool m_startValuesSet; private int m_validationCounter; private int m_newValCalculated; // ######################################################################### // functions // ######################################################################### public SolveHelper(SudokuSolver sudoku) { this.sudoku = sudoku; } public bool ReCalc { set { m_reCalc = value; } } public bool SetStartValues(uint[,] matrix) { uint row, column; uint value; bool result; result = true; for (row = 0; row < Max; row++) { for (column = 0; column < Max; column++) { value = matrix[row, column]; if ((value < 0) || (value > Max)) { result = false; } sudokuBoard[row, column] = value; } } //m_startValuesSet = result; return result; } public uint[,] GetResultValues() { return board; } private static uint CarreePos(uint aRow, uint aColumn) { return ((aColumn / CarreeMax) + (CarreeMax * (aRow / CarreeMax))); } private void InsertValColumn(uint aColumn, uint value) { if ((value < Min) || (value > Max)) { return; } BitSet.Include(ref columns[aColumn].Occupied, (int)value); columns[aColumn].Number++; } private void InsertValRow(uint aRow, uint value) { if ((value < Min) || (value > Max)) { return; } BitSet.Include(ref rows[aRow].Occupied, (int)value); rows[aRow].Number++; } private void InsertValCarree(uint aCarree, uint value) { if ((value < Min) || (value > Max)) { return; } BitSet.Include(ref carrees[aCarree].Occupied, (int)value); carrees[aCarree].Number++; } private void InsertValue(uint aRow, uint aColumn, uint value) { board[aRow, aColumn] = value; InsertValColumn(aColumn, value); InsertValRow(aRow, value); InsertValCarree(CarreePos(aRow, aColumn), value); m_newValCalculated++; } private void BoardOutput(uint[,] board) { uint row, column; if (sudoku.fileOpen) { for (row = 0; row < Max; row++) { for (column = 0; column < Max; column++) { sudoku.streamWriter.Write(String.Format(CultureInfo.InvariantCulture, "{0,4}", board[row, column].ToString(CultureInfo.InvariantCulture))); } sudoku.streamWriter.WriteLine(); } sudoku.streamWriter.WriteLine(); } } //returns a single value of the set, otherwise 0 private static uint SingleValueFromSet(uint aSet) { uint i; uint count; uint result = 0; if (aSet == 0) { return result; } count = 0; for (i = Min; i <= Max; i++) { if (BitSet.IsInBitset(aSet, (int)i)) { count++; result = i; } } if (count > 1) { result = 0; } return result; } private ValueType Evaluate(uint aRow, uint aColumn) { uint i; ValueType result = new ValueType(); m_validationCounter++; result.Number = 0; result.Occupied = 0; if (board[aRow, aColumn] == 0) { result.Occupied = rows[aRow].Occupied | columns[aColumn].Occupied | carrees[CarreePos(aRow, aColumn)].Occupied; for (i = Min; i <= Max; i++) { if (BitSet.IsInBitset(result.Occupied, (int)i)) { BitSet.Exclude(ref result.Occupied, (int)i); } else { result.Number++; BitSet.Include(ref result.Occupied, (int)i); } } } return result; } public bool BoardCheck() { uint row, column; ValueType estimate; uint i; bool result = true; tryValue.Number = 0; if (sudoku.fileOpenForAll) { sudoku.streamWriter.WriteLine(PossibleResults); } for (row = 0; row < Max; row++) { for (column = 0; column < Max; column++) { estimate = boardEstimation[row, column]; if ((estimate.Number > tryValue.Number) && !(sudoku.pass2Checked[row, column])) { tryValue.Number = estimate.Number; tryValue.Occupied = estimate.Occupied; tryValue.Row = row; tryValue.Column = column; } if (sudoku.fileOpenForAll) { StringBuilder possibleResults = new StringBuilder(32); for (i = Min; i <= Max; i++) { if (BitSet.IsInBitset(boardEstimation[row, column].Occupied, (int)i)) { possibleResults.Append(i.ToString(CultureInfo.InvariantCulture)); possibleResults.Append(", "); } } if (possibleResults.Length > 0) { possibleResults.Length -= 2; sudoku.streamWriter.WriteLine("[" + (row + 1).ToString(CultureInfo.InvariantCulture) + ", " + (column + 1).ToString(CultureInfo.InvariantCulture) + "] : " + possibleResults); } } if ((estimate.Number != 0) || (board[row, column] == 0)) { result = false; } } } return result; } private bool BoardEvaluation() { uint row, column, value; bool result; if (sudoku.fileOpenForAll) { sudoku.streamWriter.WriteLine(EvaluateText); } do { result = true; for (row = 0; row < Max; row++) { for (column = 0; column < Max; column++) { if (!m_reCalc) { boardEstimation[row, column] = Evaluate(row, column); } if (boardEstimation[row, column].Number == 1) { result = false; for (value = Min; value <= Max; value++) { if (BitSet.IsInBitset(boardEstimation[row, column].Occupied, (int)value)) { if (sudoku.fileOpenForAll) { sudoku.streamWriter.WriteLine(Insert + value.ToString(CultureInfo.InvariantCulture) + To + "[" + (row + 1).ToString(CultureInfo.InvariantCulture) + "," + (column + 1).ToString(CultureInfo.InvariantCulture) + "]" + Ein); } InsertValue(row, column, value); break; } } } } } } while (!result); return result; } private bool BoardEvaluationRows() { uint row, column; uint i; uint value; uint testSet; bool result; if (sudoku.fileOpenForAll) { sudoku.streamWriter.WriteLine(RowTest); } result = true; for (row = 0; row < Max; row++) { if (rows[row].Number < Max) { for (column = 0; column < Max; column++) { testSet = 0; for (i = 0; i < Max; i++) { if (i != column) { testSet = testSet | boardEstimation[row, i].Occupied; } } testSet = boardEstimation[row, column].Occupied & (~(testSet)); value = SingleValueFromSet(testSet); if (value != 0) { if (sudoku.fileOpenForAll) { sudoku.streamWriter.WriteLine(Insert + value.ToString(CultureInfo.InvariantCulture) + To + "[" + (row + 1).ToString(CultureInfo.InvariantCulture) + "," + (column + 1).ToString(CultureInfo.InvariantCulture) + "]" + Ein); } InsertValue(row, column, value); result = false; } } } // if (rows[row].Number < Max) else { if (sudoku.fileOpenForAll) { sudoku.streamWriter.WriteLine(Row + (row + 1).ToString(CultureInfo.InvariantCulture) + Finished); } } } // for row BoardEvaluation(); return result; } private bool BoardEvaluationColumns() { uint row, column; uint i; uint value; uint testSet; bool result; if (sudoku.fileOpenForAll) { sudoku.streamWriter.WriteLine(ColumnTest); } result = true; for (column = 0; column < Max; column++) { if (columns[column].Number < Max) { for (row = 0; row < Max; row++) { testSet = 0; for (i = 0; i < Max; i++) { if (i != row) { testSet = testSet | boardEstimation[i, column].Occupied; } } testSet = boardEstimation[row, column].Occupied & (~(testSet)); value = SingleValueFromSet(testSet); if (value != 0) { if (sudoku.fileOpenForAll) { sudoku.streamWriter.WriteLine(Insert + value.ToString(CultureInfo.InvariantCulture) + To + "[" + (row + 1).ToString(CultureInfo.InvariantCulture) + "," + (column + 1).ToString(CultureInfo.InvariantCulture) + "]" + Ein); } InsertValue(row, column, value); result = false; } } } else { if (sudoku.fileOpenForAll) { sudoku.streamWriter.WriteLine(Column + (column + 1).ToString(CultureInfo.InvariantCulture) + Finished); } } } BoardEvaluation(); return result; } private bool BoardEvaluationCarrees() { uint row, column, carree; uint i, j, hRow, hColumn; uint value; uint testSet = 0; bool result; if (sudoku.fileOpenForAll) { sudoku.streamWriter.WriteLine(CarreeTest); } result = true; for (carree = 0; carree < Max; carree++) { row = (carree / CarreeMax) * CarreeMax; column = (carree * CarreeMax) % Max; if (carrees[carree].Number < Max) { for (hRow = 0; hRow < CarreeMax; hRow++) { for (hColumn = 0; hColumn < CarreeMax; hColumn++) { testSet = 0; for (i = 0; i < CarreeMax; i++) { for (j = 0; j < CarreeMax; j++) { if (!((i == hRow) && (j == hColumn))) testSet = testSet | boardEstimation[row + i, column + j].Occupied; } } testSet = boardEstimation[row + hRow, column + hColumn].Occupied & ~testSet; value = SingleValueFromSet(testSet); if (value != 0) { if (sudoku.fileOpenForAll) { sudoku.streamWriter.WriteLine(Insert + value.ToString(CultureInfo.InvariantCulture) + To + "[" + (row + hRow + 1).ToString(CultureInfo.InvariantCulture) + "," + (column + hColumn + 1).ToString(CultureInfo.InvariantCulture) + "]" + Ein); } InsertValue(row + hRow, column + hColumn, value); result = false; } } } } else { if (sudoku.fileOpenForAll) { sudoku.streamWriter.WriteLine(Carree + (carree + 1).ToString(CultureInfo.InvariantCulture) + Finished); } } } BoardEvaluation(); return result; } public bool Evaluation() { bool ready; do { m_newValCalculated = 0; do { } while (!BoardEvaluationRows()); do { } while (!BoardEvaluationColumns()); do { } while (!BoardEvaluationCarrees()); ready = BoardCheck(); } while (!(ready || (m_newValCalculated == 0))); return ready; } public bool Calculate() { uint row, column; bool ready; rows.Initialize(); columns.Initialize(); carrees.Initialize(); board.Initialize(); boardEstimation.Initialize(); if (sudoku.fileOpen) { sudoku.streamWriter.WriteLine(Inputs); BoardOutput(sudokuBoard); } for (row = 0; row < Max; row++) { for (column = 0; column < Max; column++) { InsertValue(row, column, sudokuBoard[row, column]); } } BoardEvaluation(); m_validationCounter = 0; ready = Evaluation(); if (sudoku.fileOpen) { sudoku.streamWriter.WriteLine(Result); BoardOutput(board); } return ready; } } // ######################################################################### // functions in class SudokuSolver // ######################################################################### public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } private void Dispose(bool disposing) { if (disposing) { if (fileOpen) { streamWriter.Dispose(); } } } private bool CompareBoardFields(SolveHelper mainSudoku, SolveHelper helperSudoku) { uint row, column; uint mainValue, helperValue; //tValue; bool result = true; for (row = 0; row < Max; row++) { for (column = 0; column < Max; column++) { helperValue = helperSudoku.board[row, column]; if (helperValue != 0) { mainValue = mainSudoku.board[row, column]; if (mainValue != 0) { if (mainValue != helperValue) { result = false; } } else { if (!(BitSet.IsInBitset(mainSudoku.boardEstimation[row, column].Occupied, (int)helperValue))) { result = false; } } } else { if (helperSudoku.boardEstimation[row, column].Number == 0) { result = false; } if (!(pass2Checked[row, column])) { if (!(mainSudoku.boardEstimation[row, column].Occupied >= helperSudoku.boardEstimation[row, column].Occupied)) { result = false; } } } } } return result; } private static int GetNumber(uint occupied) { int i; int result = 0; for (i = (int)Min; i <= (int)Max; i++) { if (BitSet.IsInBitset(occupied, i)) { result = i; break; } } return result; } private bool CheckRow(uint aRow, uint[,] inVal) { uint i; for (i = 0; i < Max; i++) { m_smallField[i] = inVal[aRow, i]; } return CheckSmallField(); } private bool CheckColumn(uint aColumn, uint[,] inVal) { uint i; for (i = 0; i < Max; i++) { m_smallField[i] = inVal[i, aColumn]; } return CheckSmallField(); } private bool CheckCarree(uint carree, uint[,] inVal) { uint row, column; uint i, hRow, hColumn; row = (carree / CarreeMax) * CarreeMax; column = (carree * CarreeMax) % Max; i = 0; for (hRow = 0; hRow < CarreeMax; hRow++) { for (hColumn = 0; hColumn < CarreeMax; hColumn++) { m_smallField[i] = inVal[row + hRow, column + hColumn]; i++; } } return CheckSmallField(); } private bool CheckSmallField() { uint column, i; uint value; bool result = true; for (column = 0; column < Max; column++) { value = m_smallField[column]; if ((column < Max) && (value > 0)) { for (i = column + 1; i < Max; i++) { if (value == m_smallField[i]) { result = false; } } } } return result; } private SudokuError InputCheck(uint[,] inVal) { uint row, column, i; uint value; SudokuError result = SudokuError.None; int inputNumber = 0; for (row = 0; row < Max; row++) { for (column = 0; column < Max; column++) { value = inVal[row, column]; if ((value < 0) || (value > Max)) { result = SudokuError.WrongInput; } else { if (value > 0) { inputNumber++; } } } } if (inputNumber < MinInputValues) { result = SudokuError.FewValues; return result; } for (i = 0; i < Max; i++) { if (!(CheckRow(i, inVal))) { result = SudokuError.WrongInput; } } for (i = 0; i < Max; i++) { if (!(CheckColumn(i, inVal))) { result = SudokuError.WrongInput; } } for (i = 0; i < Max; i++) { if (!(CheckCarree(i, inVal))) { result = SudokuError.WrongInput; } } return result; } private bool TryExecute(SolveHelper mainSudoku, ref uint[,] outVal) { uint[,] tryField = new uint[Max, Max]; uint[,] field = new uint[Max, Max]; ValueType[,] fieldEstimation = new ValueType[Max, Max]; int testNumber; string streamString; bool abort = false; bool result = false; mainSudoku.ReCalc = true; if (fileOpenForAll) { streamWriter.WriteLine(Try); streamWriter.WriteLine(); } do { tryField = (uint[,])mainSudoku.board.Clone(); uint tryNumber = mainSudoku.tryValue.Number; uint tryRow = mainSudoku.tryValue.Row; uint tryColumn = mainSudoku.tryValue.Column; for (int i = 0; i < tryNumber; i++) { testNumber = GetNumber(mainSudoku.tryValue.Occupied); tryField[tryRow, tryColumn] = (uint)testNumber; if (fileOpenForAll) { streamWriter.Write(TryInRowColumn); streamWriter.WriteLine("[" + (tryRow + 1).ToString(CultureInfo.InvariantCulture) + ", " + (tryColumn + 1).ToString(CultureInfo.InvariantCulture) + "] : " + testNumber.ToString(CultureInfo.InvariantCulture)); } SolveHelper helperSudoku = new SolveHelper(this); helperSudoku.SetStartValues(tryField); if (helperSudoku.Calculate()) { outVal = helperSudoku.GetResultValues(); result = true; } else { //Change variables in mainSudoku for next run if (!CompareBoardFields(mainSudoku, helperSudoku)) { BitSet.Exclude(ref mainSudoku.boardEstimation[tryRow, tryColumn].Occupied, testNumber); mainSudoku.boardEstimation[tryRow, tryColumn].Number--; streamString = TryNotOk; } else { field = (uint[,])helperSudoku.board.Clone(); fieldEstimation = (ValueType[,])helperSudoku.boardEstimation.Clone(); streamString = TryIsPossible; } if (fileOpenForAll) { streamWriter.WriteLine(streamString); streamWriter.WriteLine(); } BitSet.Exclude(ref mainSudoku.tryValue.Occupied, testNumber); if (mainSudoku.boardEstimation[tryRow, tryColumn].Number == 0) { abort = true; } if (mainSudoku.boardEstimation[tryRow, tryColumn].Number == 1) { mainSudoku.board = (uint[,])field.Clone(); mainSudoku.boardEstimation = (ValueType[,])fieldEstimation.Clone(); } else { pass2Checked[tryRow, tryColumn] = true; } } if (result || abort) break; //leave for } if (!result && !abort) { result = mainSudoku.Evaluation(); if (result) { outVal = mainSudoku.GetResultValues(); } } } while (!(result || abort || m_abort)); return result; } public bool Abort { get { return m_abort; } set { m_abort = value; } } public void Execute(Parameter parameter) { bool result; uint[,] outVal; SudokuError errorCode; result = Execute(parameter.InputValues, out outVal, parameter.Option, out errorCode); parameter.OutputValues = outVal; parameter.ErrorCode = errorCode; parameter.IsCalculated = result; } public bool Execute(uint[,] inVal, out uint[,] outVal, SudokuOption option, out SudokuError errorCode) { SolveHelper mainSudoku; bool result = false; pass2Checked.Initialize(); m_smallField.Initialize(); fileOpen = false; fileOpenForAll = false; if ((option & SudokuOption.WithFile) != 0) { fileOpen = true; if ((option & SudokuOption.AddonInFile) != 0) { fileOpenForAll = true; } } outVal = (uint[,])inVal.Clone(); errorCode = InputCheck(inVal); if (errorCode != 0) { return result; } mainSudoku = new SolveHelper(this); try { if (mainSudoku.SetStartValues(inVal)) { if (fileOpen) { string path = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) + Path.DirectorySeparatorChar + "Sudoku"; if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } string fileName = path + Path.DirectorySeparatorChar + "SudokuSolver.txt"; streamWriter = new StreamWriter(fileName, false, Encoding.UTF8); } result = mainSudoku.Calculate(); } if (result) { outVal = mainSudoku.GetResultValues(); } else { result = TryExecute(mainSudoku, ref outVal); if (m_abort) { if (fileOpen) { streamWriter.WriteLine("Aborted"); } errorCode = SudokuError.Aborted; } } if (fileOpen) { streamWriter.Flush(); } } finally { if (fileOpen) { streamWriter.Close(); fileOpen = false; } m_abort = false; } return result; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Reflection; using System.Diagnostics; using System.Globalization; using System.Collections.Generic; using System.Runtime.Serialization; using System.Runtime.CompilerServices; using System.Reflection.Runtime.General; using System.Reflection.Runtime.TypeInfos; using System.Reflection.Runtime.CustomAttributes; using System.Reflection.Runtime.BindingFlagSupport; using Internal.Reflection.Core; using Internal.Reflection.Core.Execution; using Internal.Reflection.Tracing; namespace System.Reflection.Runtime.FieldInfos { // // The Runtime's implementation of fields. // [Serializable] [DebuggerDisplay("{_debugName}")] internal abstract partial class RuntimeFieldInfo : FieldInfo, ISerializable, ITraceableTypeMember { // // contextType - the type that supplies the type context (i.e. substitutions for generic parameters.) Though you // get your raw information from "definingType", you report "contextType" as your DeclaringType property. // // For example: // // typeof(Foo<>).GetTypeInfo().DeclaredMembers // // The definingType and contextType are both Foo<> // // typeof(Foo<int,String>).GetTypeInfo().DeclaredMembers // // The definingType is "Foo<,>" // The contextType is "Foo<int,String>" // // We don't report any DeclaredMembers for arrays or generic parameters so those don't apply. // protected RuntimeFieldInfo(RuntimeTypeInfo contextTypeInfo, RuntimeTypeInfo reflectedType) { _contextTypeInfo = contextTypeInfo; _reflectedType = reflectedType; } public sealed override Type DeclaringType { get { #if ENABLE_REFLECTION_TRACE if (ReflectionTrace.Enabled) ReflectionTrace.FieldInfo_DeclaringType(this); #endif return _contextTypeInfo; } } public sealed override Type FieldType { get { return this.FieldRuntimeType; } } public void GetObjectData(SerializationInfo info, StreamingContext context) { if (info == null) throw new ArgumentNullException(nameof(info)); MemberInfoSerializationHolder.GetSerializationInfo(info, this); } public abstract override Type[] GetOptionalCustomModifiers(); public abstract override Type[] GetRequiredCustomModifiers(); public sealed override Object GetValue(Object obj) { #if ENABLE_REFLECTION_TRACE if (ReflectionTrace.Enabled) ReflectionTrace.FieldInfo_GetValue(this, obj); #endif FieldAccessor fieldAccessor = this.FieldAccessor; return fieldAccessor.GetField(obj); } public sealed override Module Module { get { return DefiningType.Module; } } public sealed override Type ReflectedType { get { return _reflectedType; } } public sealed override void SetValue(object obj, object value, BindingFlags invokeAttr, Binder binder, CultureInfo culture) { #if ENABLE_REFLECTION_TRACE if (ReflectionTrace.Enabled) ReflectionTrace.FieldInfo_SetValue(this, obj, value); #endif FieldAccessor fieldAccessor = this.FieldAccessor; BinderBundle binderBundle = binder.ToBinderBundle(invokeAttr, culture); fieldAccessor.SetField(obj, value, binderBundle); } Type ITraceableTypeMember.ContainingType { get { return _contextTypeInfo; } } /// <summary> /// Override to provide the metadata based name of a field. (Different from the Name /// property in that it does not go into the reflection trace logic.) /// </summary> protected abstract string MetadataName { get; } public sealed override String Name { get { #if ENABLE_REFLECTION_TRACE if (ReflectionTrace.Enabled) ReflectionTrace.FieldInfo_Name(this); #endif return MetadataName; } } String ITraceableTypeMember.MemberName { get { return MetadataName; } } // Types that derive from RuntimeFieldInfo must implement the following public surface area members public abstract override IEnumerable<CustomAttributeData> CustomAttributes { get; } public abstract override FieldAttributes Attributes { get; } public abstract override int MetadataToken { get; } public abstract override String ToString(); public abstract override bool Equals(Object obj); public abstract override int GetHashCode(); public abstract override RuntimeFieldHandle FieldHandle { get; } /// <summary> /// Get the default value if exists for a field by parsing metadata. Return false if there is no default value. /// </summary> protected abstract bool TryGetDefaultValue(out object defaultValue); /// <summary> /// Return a FieldAccessor object for accessing the value of a non-literal field. May rely on metadata to create correct accessor. /// </summary> protected abstract FieldAccessor TryGetFieldAccessor(); private FieldAccessor FieldAccessor { get { FieldAccessor fieldAccessor = _lazyFieldAccessor; if (fieldAccessor == null) { if (this.IsLiteral) { // Legacy: ECMA335 does not require that the metadata literal match the type of the field that declares it. // For desktop compat, we return the metadata literal as is and do not attempt to convert or validate against the Field type. Object defaultValue; if (!TryGetDefaultValue(out defaultValue)) { throw new BadImageFormatException(); // Field marked literal but has no default value. } _lazyFieldAccessor = fieldAccessor = new LiteralFieldAccessor(defaultValue); } else { _lazyFieldAccessor = fieldAccessor = TryGetFieldAccessor(); if (fieldAccessor == null) throw ReflectionCoreExecution.ExecutionDomain.CreateNonInvokabilityException(this); } } return fieldAccessor; } } /// <summary> /// Return the type of the field by parsing metadata. /// </summary> protected abstract RuntimeTypeInfo FieldRuntimeType { get; } protected RuntimeFieldInfo WithDebugName() { bool populateDebugNames = DeveloperExperienceState.DeveloperExperienceModeEnabled; #if DEBUG populateDebugNames = true; #endif if (!populateDebugNames) return this; if (_debugName == null) { _debugName = "Constructing..."; // Protect against any inadvertent reentrancy. _debugName = ((ITraceableTypeMember)this).MemberName; } return this; } /// <summary> /// Return the DefiningTypeInfo as a RuntimeTypeInfo (instead of as a format specific type info) /// </summary> protected abstract RuntimeTypeInfo DefiningType { get; } protected readonly RuntimeTypeInfo _contextTypeInfo; protected readonly RuntimeTypeInfo _reflectedType; private volatile FieldAccessor _lazyFieldAccessor = null; private String _debugName; } }
using UnityEngine; using UnityEditor; using System.Collections; using System.Collections.Generic; using System.IO; // In order to compatiblity with Unity4.0 // which dose not surpport CustomEditor(type, bool) overload // I have to strip out the GUI logic of BundleEditor into BundleEditorDrawer, // And create two more editor class for asset bundle and scene bundle. public static class BundleEditorDrawer { public static Editor CurrentBundleEditor = null; static SceneBundleInpectorObj sbInspectorObj = null; static AssetBundleInspectorObj abInpsectorObj = null; static BundleData currentBundle = null; static Vector2 m_ScrollViewPosition = Vector2.zero; static bool m_FoldoutIncludes = true; static bool m_FoldoutMetaFiles = true; static string m_CurSelectAsset = ""; static bool m_IsMetaListSelect = false; static double m_LastClickTime = 0; // public static void ShowBundle(BundleData newBundle) { // Show dummy object in inspector if(sbInspectorObj == null) { sbInspectorObj = ScriptableObject.CreateInstance<SceneBundleInpectorObj>(); sbInspectorObj.hideFlags = HideFlags.DontSave; } if(abInpsectorObj == null) { abInpsectorObj = ScriptableObject.CreateInstance<AssetBundleInspectorObj>(); abInpsectorObj.hideFlags = HideFlags.DontSave; } if(newBundle != null) Selection.activeObject = newBundle.sceneBundle? (Object)sbInspectorObj : (Object)abInpsectorObj; else Selection.activeObject = null; // Update bundle if(newBundle == currentBundle) return; currentBundle = newBundle; Refresh(); } public static void Refresh() { if(currentBundle != null && Selection.activeObject != null) Selection.activeObject.name = currentBundle.name; if(CurrentBundleEditor != null) CurrentBundleEditor.Repaint(); } public static void DrawInspector() { if(currentBundle == null) { GUILayout.FlexibleSpace(); GUILayout.Label("Select bundle to check its content."); GUILayout.FlexibleSpace(); return; } m_ScrollViewPosition = EditorGUILayout.BeginScrollView(m_ScrollViewPosition); { // Bundle type and version BundleBuildState buildStates = BundleManager.GetBuildStateOfBundle(currentBundle.name); EditorGUILayout.BeginHorizontal(); { GUILayout.Label(currentBundle.sceneBundle ? "Scene bundle" : "Asset bundle", BMGUIStyles.GetStyle("BoldLabel")); GUILayout.FlexibleSpace(); GUILayout.Label("Version " + buildStates.version, BMGUIStyles.GetStyle("BoldLabel")); } EditorGUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); { string sizeStr = "Build Size " + (buildStates.size == -1 ? "Unkown" : Mathf.CeilToInt(buildStates.size / 1024f) + " KB"); GUILayout.Label(sizeStr, BMGUIStyles.GetStyle("BoldLabel")); GUILayout.FlexibleSpace(); GUILayout.Label("Priority", EditorStyles.boldLabel); currentBundle.priority = EditorGUILayout.Popup(currentBundle.priority, new string[]{"0","1","2","3","4","5","6","7","8","9"}, GUILayout.MaxWidth(40)); } GUILayout.EndHorizontal(); GUILayout.Space(5); EditorGUILayout.BeginVertical(BMGUIStyles.GetStyle("Wizard Box")); { GUI_Inlcudes(); GUI_DependencyList(); } EditorGUILayout.EndVertical(); } EditorGUILayout.EndScrollView(); GUILayout.BeginHorizontal(); { GUILayout.FlexibleSpace(); if(GUILayout.Button("Refresh") && currentBundle != null) { BundleManager.RefreshBundleDependencies(currentBundle); BMDataAccessor.SaveBundleData(); } } GUILayout.EndHorizontal(); } static bool HasFocuse() { if(EditorWindow.focusedWindow == null) return false; else return EditorWindow.focusedWindow.title == "UnityEditor.InspectorWindow"; } static void GUI_Inlcudes() { if(currentBundle.includeGUIDs.Count > 0) { #if !(UNITY_4_2 || UNITY_4_1 || UNITY_4_0) m_FoldoutIncludes = EditorGUILayout.Foldout(m_FoldoutIncludes, "INCLUDE", BMGUIStyles.GetStyle("CFoldout")); #else m_FoldoutIncludes = EditorGUILayout.Foldout(m_FoldoutIncludes, "INCLUDE"); #endif } else { GUILayout.Label("INCLUDE", BMGUIStyles.GetStyle("UnfoldableTitle")); } if(!m_FoldoutIncludes) return; EditorGUILayout.BeginVertical(); { foreach(var guid in currentBundle.includeGUIDs) { string assetPath = AssetDatabase.GUIDToAssetPath(guid); bool isCurrentPathSelect = m_CurSelectAsset == guid && !m_IsMetaListSelect; AssetItemState itemState = GUI_AssetItem(assetPath, isCurrentPathSelect, GetSharedIconOfInlucde(guid)); if(itemState != AssetItemState.None) { if(!isCurrentPathSelect) { m_IsMetaListSelect = false; m_CurSelectAsset = guid; } else if(itemState != AssetItemState.RClicked) // Only left click can disable selection { if(EditorApplication.timeSinceStartup - m_LastClickTime < 2f) { // Double clicked EditorGUIUtility.PingObject(AssetDatabase.LoadAssetAtPath(assetPath, typeof( Object ))); } else { m_CurSelectAsset = ""; } } m_LastClickTime = EditorApplication.timeSinceStartup; Refresh(); // Right click if(itemState == AssetItemState.RClicked) { GenericMenu rightClickMenu = new GenericMenu(); rightClickMenu.AddItem(new GUIContent("Delete"), false, GUI_DeleteMenuCallback); rightClickMenu.DropDown(new Rect( Event.current.mousePosition.x, Event.current.mousePosition.y, 0, 0) ); } } } }EditorGUILayout.EndVertical(); } static void GUI_DependencyList() { if(currentBundle.dependGUIDs.Count > 0) { #if !(UNITY_4_2 || UNITY_4_1 || UNITY_4_0) m_FoldoutMetaFiles = EditorGUILayout.Foldout(m_FoldoutMetaFiles, "DEPEND", BMGUIStyles.GetStyle("CFoldout")); #else m_FoldoutMetaFiles = EditorGUILayout.Foldout(m_FoldoutMetaFiles, "DEPEND"); #endif } else { GUILayout.Label("DEPEND", BMGUIStyles.GetStyle("UnfoldableTitle")); return; } if(m_FoldoutMetaFiles) { EditorGUILayout.BeginVertical(); { foreach(string guid in currentBundle.dependGUIDs) { string assetPath = AssetDatabase.GUIDToAssetPath(guid); bool isCurrentPathSelect = m_CurSelectAsset == guid && m_IsMetaListSelect; if( GUI_AssetItem( assetPath, isCurrentPathSelect, GetSharedIconOfDepend(guid) ) != AssetItemState.None ) { if(!isCurrentPathSelect) { m_IsMetaListSelect = true; m_CurSelectAsset = guid; } else { if(EditorApplication.timeSinceStartup - m_LastClickTime < 2f) { // Double clicked EditorGUIUtility.PingObject(AssetDatabase.LoadAssetAtPath(assetPath, typeof( Object ))); } else { m_CurSelectAsset = ""; } } m_LastClickTime = EditorApplication.timeSinceStartup; Refresh(); } } }EditorGUILayout.EndVertical(); } } enum AssetItemState{None, RClicked, LClicked}; static AssetItemState GUI_AssetItem(string assetPath, bool isSelect) { return GUI_AssetItem(assetPath, isSelect, null); } static AssetItemState GUI_AssetItem(string assetPath, bool isSelect, Texture shareStateIcon) { GUIContent assetContent = new GUIContent(Path.GetFileNameWithoutExtension(assetPath), AssetDatabase.GetCachedIcon(assetPath)); EditorGUIUtility.SetIconSize(new Vector2( 16f, 16f)); if(assetPath == "") assetContent.text = "Missing"; GUILayout.BeginHorizontal(GetItemStyle(isSelect, HasFocuse())); { GUILayout.Space(20); GUIStyle labelStyel = GetLabelStyle(isSelect, assetContent.image != null); GUILayout.Label(assetContent, labelStyel, GUILayout.MaxHeight(18), GUILayout.ExpandWidth(true)); GUILayout.FlexibleSpace(); if(shareStateIcon != null) { EditorGUIUtility.SetIconSize(new Vector2( 27f, 12f)); GUILayout.Label(shareStateIcon); } } GUILayout.EndHorizontal(); EditorGUIUtility.SetIconSize(Vector2.zero); bool mouseBtnClicked = Event.current.type == EventType.MouseUp && GUILayoutUtility.GetLastRect().Contains(Event.current.mousePosition); if(mouseBtnClicked) { #if UNITY_EDITOR_OSX if((Event.current.button == 0 && Event.current.control == true) || Event.current.button == 1) return AssetItemState.RClicked; else return AssetItemState.LClicked; #else if(Event.current.button == 1) return AssetItemState.RClicked; else return AssetItemState.LClicked; #endif } else return AssetItemState.None; } static void GUI_DeleteMenuCallback() { BundleManager.RemoveAssetFromBundle(m_CurSelectAsset, currentBundle.name); Refresh(); } static GUIStyle GetLabelStyle(bool selected, bool exist) { if(!exist) return BMGUIStyles.GetStyle("CAssetLabelRed"); if(selected) return BMGUIStyles.GetStyle("CAssetLabelActive"); else return BMGUIStyles.GetStyle("CAssetLabelNormal"); } static GUIStyle GetItemStyle(bool selected, bool focused) { if(!selected) { return BMGUIStyles.GetStyle("TreeItemUnSelect"); } else { if(focused) return BMGUIStyles.GetStyle("TreeItemSelectBlue"); else return BMGUIStyles.GetStyle("TreeItemSelectGray"); } } static Texture2D GetSharedIconOfDepend(string guid) { var bundleList = BundleManager.GetIncludeBundles(guid); if(bundleList != null && bundleList.Count > 0) { foreach(BundleData bundle in bundleList) { if(bundle.name == currentBundle.name) continue; if( BundleManager.IsBundleDependOn(currentBundle.name, bundle.name) ) return BMGUIStyles.GetIcon("sharedAsset"); } } bundleList = BundleManager.GetRelatedBundles(guid); if(bundleList != null && bundleList.Count > 1) { foreach(BundleData bundle in bundleList) { if(bundle.name == currentBundle.name) continue; if( !BundleManager.IsBundleDependOn(bundle.name, currentBundle.name) && !BundleManager.IsBundleDependOn(currentBundle.name, bundle.name)) return BMGUIStyles.GetIcon("duplicatedDepend"); } } return null; } static Texture2D GetSharedIconOfInlucde(string guid) { var includeBundleList = BundleManager.GetIncludeBundles(guid); if(includeBundleList != null && includeBundleList.Count > 1) { foreach(BundleData bundle in includeBundleList) { if(bundle.name == currentBundle.name) continue; if(BundleManager.IsBundleDependOn(currentBundle.name, bundle.name)) return BMGUIStyles.GetIcon("sharedAsset"); else if(!BundleManager.IsBundleDependOn(bundle.name, currentBundle.name)) return BMGUIStyles.GetIcon("duplicatedInclude"); } } var dependBundleList = BundleManager.GetRelatedBundles(guid); if(dependBundleList != null && dependBundleList.Count > 0) { foreach(BundleData bundle in dependBundleList) { if(bundle.name == currentBundle.name) continue; if( BundleManager.IsBundleDependOn(bundle.name, currentBundle.name) ) return BMGUIStyles.GetIcon("dependedAsset"); } } return null; } }
/* ==================================================================== 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.XSSF.UserModel { using System.IO; using System.Xml; using NPOI.OpenXml4Net.OPC; using NPOI.OpenXmlFormats.Spreadsheet; using NPOI.SS.UserModel; using NPOI.SS.Util; using System; using NPOI.SS; public class XSSFPivotCacheDefinition : POIXMLDocumentPart { private CT_PivotCacheDefinition ctPivotCacheDefinition; public XSSFPivotCacheDefinition() : base() { ctPivotCacheDefinition = new CT_PivotCacheDefinition(); CreateDefaultValues(); } /** * Creates an XSSFPivotCacheDefintion representing the given package part and relationship. * Should only be called when Reading in an existing file. * * @param part - The package part that holds xml data representing this pivot cache defInition. * @param rel - the relationship of the given package part in the underlying OPC package */ protected XSSFPivotCacheDefinition(PackagePart part) : base(part) { ReadFrom(part.GetInputStream()); } [Obsolete("deprecated in POI 3.14, scheduled for removal in POI 3.16")] protected XSSFPivotCacheDefinition(PackagePart part, PackageRelationship rel) : this(part) { } public void ReadFrom(Stream is1) { try { //XmlOptions options = new XmlOptions(DEFAULT_XML_OPTIONS); ////Removing root element //options.LoadReplaceDocumentElement=(/*setter*/null); XmlDocument xmldoc = ConvertStreamToXml(is1); ctPivotCacheDefinition = CT_PivotCacheDefinition.Parse(xmldoc.DocumentElement, NamespaceManager); } catch (XmlException e) { throw new IOException(e.Message); } } public CT_PivotCacheDefinition GetCTPivotCacheDefinition() { return ctPivotCacheDefinition; } private void CreateDefaultValues() { ctPivotCacheDefinition.createdVersion = (byte)XSSFPivotTable.CREATED_VERSION; ctPivotCacheDefinition.minRefreshableVersion = (byte)XSSFPivotTable.MIN_REFRESHABLE_VERSION; ctPivotCacheDefinition.refreshedVersion = (byte)XSSFPivotTable.UPDATED_VERSION; ctPivotCacheDefinition.refreshedBy = (/*setter*/"NPOI"); ctPivotCacheDefinition.refreshedDate = DateTime.Now.ToOADate(); ctPivotCacheDefinition.refreshOnLoad = (/*setter*/true); } protected internal override void Commit() { PackagePart part = GetPackagePart(); Stream out1 = part.GetOutputStream(); //XmlOptions xmlOptions = new XmlOptions(DEFAULT_XML_OPTIONS); //Sets the pivotCacheDefInition tag //xmlOptions.SetSaveSyntheticDocumentElement(new QName(CTPivotCacheDefInition.type.Name. // GetNamespaceURI(), "pivotCacheDefInition")); //// ensure the fields have names //if (ctPivotCacheDefinition.cacheFields != null) //{ // CT_CacheFields cFields = ctPivotCacheDefinition.cacheFields; // foreach (CT_CacheField cf in cFields.cacheField) // { // if (cf.name == null || cf.name.Equals("")) // { // cf.name = "A"; // } // } //} ctPivotCacheDefinition.Save(out1); out1.Close(); } /** * Find the 2D base data area for the pivot table, either from its direct reference or named table/range. * @return AreaReference representing the current area defined by the pivot table * @ if the ref1 attribute is not contiguous or the name attribute is not found. */ public AreaReference GetPivotArea(IWorkbook wb) { CT_WorksheetSource wsSource = ctPivotCacheDefinition.cacheSource.worksheetSource; String ref1 = wsSource.@ref; String name = wsSource.name; if (ref1 == null && name == null) throw new ArgumentException("Pivot cache must reference an area, named range, or table."); // this is the XML format, so tell the reference that. if (ref1 != null) return new AreaReference(ref1, SpreadsheetVersion.EXCEL2007); if (name != null) { // named range or table? IName range = wb.GetName(name); if (range != null) return new AreaReference(range.RefersToFormula, SpreadsheetVersion.EXCEL2007); // not a named range, check for a table. // do this second, as tables are sheet-specific, but named ranges are not, and may not have a sheet name given. XSSFSheet sheet = (XSSFSheet)wb.GetSheet(wsSource.sheet); foreach (XSSFTable table in sheet.GetTables()) { if (table.Name.Equals(name)) { //case-sensitive? return new AreaReference(table.StartCellReference, table.EndCellReference); } } } throw new ArgumentException("Name '" + name + "' was not found."); } /** * Generates a cache field for each column in the reference area for the pivot table. * @param sheet The sheet where the data i collected from */ protected internal void CreateCacheFields(ISheet sheet) { //Get values for start row, start and end column AreaReference ar = GetPivotArea(sheet.Workbook); CellReference firstCell = ar.FirstCell; CellReference lastCell = ar.LastCell; int columnStart = firstCell.Col; int columnEnd = lastCell.Col; IRow row = sheet.GetRow(firstCell.Row); CT_CacheFields cFields; if (ctPivotCacheDefinition.cacheFields != null) { cFields = ctPivotCacheDefinition.cacheFields; } else { cFields = ctPivotCacheDefinition.AddNewCacheFields(); } //For each column, create a cache field and give it en empty sharedItems for (int i = columnStart; i <= columnEnd; i++) { CT_CacheField cf = cFields.AddNewCacheField(); if (i == columnEnd) { cFields.count = (/*setter*/cFields.SizeOfCacheFieldArray()); } //General number format cf.numFmtId = (/*setter*/0); ICell cell = row.GetCell(i); cell.SetCellType(CellType.String); String stringCellValue = cell.StringCellValue; cf.name = stringCellValue; cf.AddNewSharedItems(); } } } }
// 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 static System.Linq.Expressions.CachedReflectionInfo; namespace System.Linq.Expressions.Compiler { internal static class ILGen { internal static void Emit(this ILGenerator il, OpCode opcode, MethodBase methodBase) { Debug.Assert(methodBase is MethodInfo || methodBase is ConstructorInfo); var ctor = methodBase as ConstructorInfo; if ((object)ctor != null) { il.Emit(opcode, ctor); } else { il.Emit(opcode, (MethodInfo)methodBase); } } #region Instruction helpers internal static void EmitLoadArg(this ILGenerator il, int index) { Debug.Assert(index >= 0); Debug.Assert(index < ushort.MaxValue); switch (index) { case 0: il.Emit(OpCodes.Ldarg_0); break; case 1: il.Emit(OpCodes.Ldarg_1); break; case 2: il.Emit(OpCodes.Ldarg_2); break; case 3: il.Emit(OpCodes.Ldarg_3); break; default: if (index <= byte.MaxValue) { il.Emit(OpCodes.Ldarg_S, (byte)index); } else { // cast to short, result is correct ushort. il.Emit(OpCodes.Ldarg, (short)index); } break; } } internal static void EmitLoadArgAddress(this ILGenerator il, int index) { Debug.Assert(index >= 0); Debug.Assert(index < ushort.MaxValue); if (index <= byte.MaxValue) { il.Emit(OpCodes.Ldarga_S, (byte)index); } else { // cast to short, result is correct ushort. il.Emit(OpCodes.Ldarga, (short)index); } } internal static void EmitStoreArg(this ILGenerator il, int index) { Debug.Assert(index >= 0); Debug.Assert(index < ushort.MaxValue); if (index <= byte.MaxValue) { il.Emit(OpCodes.Starg_S, (byte)index); } else { // cast to short, result is correct ushort. il.Emit(OpCodes.Starg, (short)index); } } /// <summary> /// Emits a Ldind* instruction for the appropriate type /// </summary> internal static void EmitLoadValueIndirect(this ILGenerator il, Type type) { Debug.Assert(type != null); switch (type.GetTypeCode()) { case TypeCode.Byte: il.Emit(OpCodes.Ldind_I1); break; case TypeCode.Boolean: case TypeCode.SByte: il.Emit(OpCodes.Ldind_U1); break; case TypeCode.Int16: il.Emit(OpCodes.Ldind_I2); break; case TypeCode.Char: case TypeCode.UInt16: il.Emit(OpCodes.Ldind_U2); break; case TypeCode.Int32: il.Emit(OpCodes.Ldind_I4); break; case TypeCode.UInt32: il.Emit(OpCodes.Ldind_U4); break; case TypeCode.Int64: case TypeCode.UInt64: il.Emit(OpCodes.Ldind_I8); break; case TypeCode.Single: il.Emit(OpCodes.Ldind_R4); break; case TypeCode.Double: il.Emit(OpCodes.Ldind_R8); break; default: if (type.IsValueType) { il.Emit(OpCodes.Ldobj, type); } else { il.Emit(OpCodes.Ldind_Ref); } break; } } /// <summary> /// Emits a Stind* instruction for the appropriate type. /// </summary> internal static void EmitStoreValueIndirect(this ILGenerator il, Type type) { Debug.Assert(type != null); switch (type.GetTypeCode()) { case TypeCode.Boolean: case TypeCode.Byte: case TypeCode.SByte: il.Emit(OpCodes.Stind_I1); break; case TypeCode.Char: case TypeCode.Int16: case TypeCode.UInt16: il.Emit(OpCodes.Stind_I2); break; case TypeCode.Int32: case TypeCode.UInt32: il.Emit(OpCodes.Stind_I4); break; case TypeCode.Int64: case TypeCode.UInt64: il.Emit(OpCodes.Stind_I8); break; case TypeCode.Single: il.Emit(OpCodes.Stind_R4); break; case TypeCode.Double: il.Emit(OpCodes.Stind_R8); break; default: if (type.IsValueType) { il.Emit(OpCodes.Stobj, type); } else { il.Emit(OpCodes.Stind_Ref); } break; } } // Emits the Ldelem* instruction for the appropriate type internal static void EmitLoadElement(this ILGenerator il, Type type) { Debug.Assert(type != null); if (!type.IsValueType) { il.Emit(OpCodes.Ldelem_Ref); } else { switch (type.GetTypeCode()) { case TypeCode.Boolean: case TypeCode.SByte: il.Emit(OpCodes.Ldelem_I1); break; case TypeCode.Byte: il.Emit(OpCodes.Ldelem_U1); break; case TypeCode.Int16: il.Emit(OpCodes.Ldelem_I2); break; case TypeCode.Char: case TypeCode.UInt16: il.Emit(OpCodes.Ldelem_U2); break; case TypeCode.Int32: il.Emit(OpCodes.Ldelem_I4); break; case TypeCode.UInt32: il.Emit(OpCodes.Ldelem_U4); break; case TypeCode.Int64: case TypeCode.UInt64: il.Emit(OpCodes.Ldelem_I8); break; case TypeCode.Single: il.Emit(OpCodes.Ldelem_R4); break; case TypeCode.Double: il.Emit(OpCodes.Ldelem_R8); break; default: il.Emit(OpCodes.Ldelem, type); break; } } } /// <summary> /// Emits a Stelem* instruction for the appropriate type. /// </summary> internal static void EmitStoreElement(this ILGenerator il, Type type) { Debug.Assert(type != null); switch (type.GetTypeCode()) { case TypeCode.Boolean: case TypeCode.SByte: case TypeCode.Byte: il.Emit(OpCodes.Stelem_I1); break; case TypeCode.Char: case TypeCode.Int16: case TypeCode.UInt16: il.Emit(OpCodes.Stelem_I2); break; case TypeCode.Int32: case TypeCode.UInt32: il.Emit(OpCodes.Stelem_I4); break; case TypeCode.Int64: case TypeCode.UInt64: il.Emit(OpCodes.Stelem_I8); break; case TypeCode.Single: il.Emit(OpCodes.Stelem_R4); break; case TypeCode.Double: il.Emit(OpCodes.Stelem_R8); break; default: if (type.IsValueType) { il.Emit(OpCodes.Stelem, type); } else { il.Emit(OpCodes.Stelem_Ref); } break; } } internal static void EmitType(this ILGenerator il, Type type) { Debug.Assert(type != null); il.Emit(OpCodes.Ldtoken, type); il.Emit(OpCodes.Call, Type_GetTypeFromHandle); } #endregion #region Fields, properties and methods internal static void EmitFieldAddress(this ILGenerator il, FieldInfo fi) { Debug.Assert(fi != null); il.Emit(fi.IsStatic ? OpCodes.Ldsflda : OpCodes.Ldflda, fi); } internal static void EmitFieldGet(this ILGenerator il, FieldInfo fi) { Debug.Assert(fi != null); il.Emit(fi.IsStatic ? OpCodes.Ldsfld : OpCodes.Ldfld, fi); } internal static void EmitFieldSet(this ILGenerator il, FieldInfo fi) { Debug.Assert(fi != null); il.Emit(fi.IsStatic ? OpCodes.Stsfld : OpCodes.Stfld, fi); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")] internal static void EmitNew(this ILGenerator il, ConstructorInfo ci) { Debug.Assert(ci != null); Debug.Assert(!ci.DeclaringType.ContainsGenericParameters); il.Emit(OpCodes.Newobj, ci); } #endregion #region Constants internal static void EmitNull(this ILGenerator il) { il.Emit(OpCodes.Ldnull); } internal static void EmitString(this ILGenerator il, string value) { Debug.Assert(value != null); il.Emit(OpCodes.Ldstr, value); } internal static void EmitPrimitive(this ILGenerator il, bool value) { il.Emit(value ? OpCodes.Ldc_I4_1 : OpCodes.Ldc_I4_0); } internal static void EmitPrimitive(this ILGenerator il, int value) { OpCode c; switch (value) { case -1: c = OpCodes.Ldc_I4_M1; break; case 0: c = OpCodes.Ldc_I4_0; break; case 1: c = OpCodes.Ldc_I4_1; break; case 2: c = OpCodes.Ldc_I4_2; break; case 3: c = OpCodes.Ldc_I4_3; break; case 4: c = OpCodes.Ldc_I4_4; break; case 5: c = OpCodes.Ldc_I4_5; break; case 6: c = OpCodes.Ldc_I4_6; break; case 7: c = OpCodes.Ldc_I4_7; break; case 8: c = OpCodes.Ldc_I4_8; break; default: if (value >= sbyte.MinValue && value <= sbyte.MaxValue) { il.Emit(OpCodes.Ldc_I4_S, (sbyte)value); } else { il.Emit(OpCodes.Ldc_I4, value); } return; } il.Emit(c); } private static void EmitPrimitive(this ILGenerator il, uint value) { il.EmitPrimitive(unchecked((int)value)); } private static void EmitPrimitive(this ILGenerator il, long value) { if (int.MinValue <= value & value <= uint.MaxValue) { il.EmitPrimitive(unchecked((int)value)); // While often not of consequence depending on what follows, there are cases where this // casting matters. Values [0, int.MaxValue] can use either safely, but negative values // must use conv.i8 and those (int.MaxValue, uint.MaxValue] must use conv.u8, or else // the higher bits will be wrong. il.Emit(value > 0 ? OpCodes.Conv_U8 : OpCodes.Conv_I8); } else { il.Emit(OpCodes.Ldc_I8, value); } } private static void EmitPrimitive(this ILGenerator il, ulong value) { il.EmitPrimitive(unchecked((long)value)); } private static void EmitPrimitive(this ILGenerator il, double value) { il.Emit(OpCodes.Ldc_R8, value); } private static void EmitPrimitive(this ILGenerator il, float value) { il.Emit(OpCodes.Ldc_R4, value); } // matches TryEmitConstant internal static bool CanEmitConstant(object value, Type type) { if (value == null || CanEmitILConstant(type)) { return true; } Type t = value as Type; if (t != null) { return ShouldLdtoken(t); } MethodBase mb = value as MethodBase; return mb != null && ShouldLdtoken(mb); } // matches TryEmitILConstant private static bool CanEmitILConstant(Type type) { switch (type.GetNonNullableType().GetTypeCode()) { case TypeCode.Boolean: case TypeCode.SByte: case TypeCode.Int16: case TypeCode.Int32: case TypeCode.Int64: case TypeCode.Single: case TypeCode.Double: case TypeCode.Char: case TypeCode.Byte: case TypeCode.UInt16: case TypeCode.UInt32: case TypeCode.UInt64: case TypeCode.Decimal: case TypeCode.String: return true; } return false; } // // Note: we support emitting more things as IL constants than // Linq does internal static bool TryEmitConstant(this ILGenerator il, object value, Type type, ILocalCache locals) { if (value == null) { // Smarter than the Linq implementation which uses the initobj // pattern for all value types (works, but requires a local and // more IL) il.EmitDefault(type, locals); return true; } // Handle the easy cases if (il.TryEmitILConstant(value, type)) { return true; } // Check for a few more types that we support emitting as constants Type t = value as Type; if (t != null) { if (ShouldLdtoken(t)) { il.EmitType(t); if (type != typeof(Type)) { il.Emit(OpCodes.Castclass, type); } return true; } return false; } MethodBase mb = value as MethodBase; if (mb != null && ShouldLdtoken(mb)) { il.Emit(OpCodes.Ldtoken, mb); Type dt = mb.DeclaringType; if (dt != null && dt.IsGenericType) { il.Emit(OpCodes.Ldtoken, dt); il.Emit(OpCodes.Call, MethodBase_GetMethodFromHandle_RuntimeMethodHandle_RuntimeTypeHandle); } else { il.Emit(OpCodes.Call, MethodBase_GetMethodFromHandle_RuntimeMethodHandle); } if (type != typeof(MethodBase)) { il.Emit(OpCodes.Castclass, type); } return true; } return false; } private static bool ShouldLdtoken(Type t) { // If CompileToMethod is re-enabled, t is TypeBuilder should also return // true when not compiling to a DynamicMethod return t.IsGenericParameter || t.IsVisible; } internal static bool ShouldLdtoken(MethodBase mb) { // Can't ldtoken on a DynamicMethod if (mb is DynamicMethod) { return false; } Type dt = mb.DeclaringType; return dt == null || ShouldLdtoken(dt); } private static bool TryEmitILConstant(this ILGenerator il, object value, Type type) { Debug.Assert(value != null); if (type.IsNullableType()) { Type nonNullType = type.GetNonNullableType(); if (TryEmitILConstant(il, value, nonNullType)) { il.Emit(OpCodes.Newobj, type.GetConstructor(new[] { nonNullType })); return true; } return false; } switch (type.GetTypeCode()) { case TypeCode.Boolean: il.EmitPrimitive((bool)value); return true; case TypeCode.SByte: il.EmitPrimitive((sbyte)value); return true; case TypeCode.Int16: il.EmitPrimitive((short)value); return true; case TypeCode.Int32: il.EmitPrimitive((int)value); return true; case TypeCode.Int64: il.EmitPrimitive((long)value); return true; case TypeCode.Single: il.EmitPrimitive((float)value); return true; case TypeCode.Double: il.EmitPrimitive((double)value); return true; case TypeCode.Char: il.EmitPrimitive((char)value); return true; case TypeCode.Byte: il.EmitPrimitive((byte)value); return true; case TypeCode.UInt16: il.EmitPrimitive((ushort)value); return true; case TypeCode.UInt32: il.EmitPrimitive((uint)value); return true; case TypeCode.UInt64: il.EmitPrimitive((ulong)value); return true; case TypeCode.Decimal: il.EmitDecimal((decimal)value); return true; case TypeCode.String: il.EmitString((string)value); return true; default: return false; } } #endregion #region Linq Conversions internal static void EmitConvertToType(this ILGenerator il, Type typeFrom, Type typeTo, bool isChecked, ILocalCache locals) { if (TypeUtils.AreEquivalent(typeFrom, typeTo)) { return; } Debug.Assert(typeFrom != typeof(void) && typeTo != typeof(void)); bool isTypeFromNullable = typeFrom.IsNullableType(); bool isTypeToNullable = typeTo.IsNullableType(); Type nnExprType = typeFrom.GetNonNullableType(); Type nnType = typeTo.GetNonNullableType(); if (typeFrom.IsInterface || // interface cast typeTo.IsInterface || typeFrom == typeof(object) || // boxing cast typeTo == typeof(object) || typeFrom == typeof(System.Enum) || typeFrom == typeof(System.ValueType) || TypeUtils.IsLegalExplicitVariantDelegateConversion(typeFrom, typeTo)) { il.EmitCastToType(typeFrom, typeTo); } else if (isTypeFromNullable || isTypeToNullable) { il.EmitNullableConversion(typeFrom, typeTo, isChecked, locals); } else if (!(typeFrom.IsConvertible() && typeTo.IsConvertible()) // primitive runtime conversion && (nnExprType.IsAssignableFrom(nnType) || // down cast nnType.IsAssignableFrom(nnExprType))) // up cast { il.EmitCastToType(typeFrom, typeTo); } else if (typeFrom.IsArray && typeTo.IsArray) // reference conversion from one array type to another via castclass { il.EmitCastToType(typeFrom, typeTo); } else { il.EmitNumericConversion(typeFrom, typeTo, isChecked); } } private static void EmitCastToType(this ILGenerator il, Type typeFrom, Type typeTo) { if (typeFrom.IsValueType) { Debug.Assert(!typeTo.IsValueType); il.Emit(OpCodes.Box, typeFrom); if (typeTo != typeof(object)) { il.Emit(OpCodes.Castclass, typeTo); } } else { il.Emit(typeTo.IsValueType ? OpCodes.Unbox_Any : OpCodes.Castclass, typeTo); } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")] private static void EmitNumericConversion(this ILGenerator il, Type typeFrom, Type typeTo, bool isChecked) { TypeCode tc = typeTo.GetTypeCode(); TypeCode tf = typeFrom.GetTypeCode(); if (tc == tf) { // Between enums of same underlying type, or between such an enum and the underlying type itself. // Includes bool-backed enums, which is the only valid conversion to or from bool. // Just leave the value on the stack, and treat it as the wanted type. return; } bool isFromUnsigned = tf.IsUnsigned(); OpCode convCode; switch (tc) { case TypeCode.Single: if (isFromUnsigned) il.Emit(OpCodes.Conv_R_Un); convCode = OpCodes.Conv_R4; break; case TypeCode.Double: if (isFromUnsigned) il.Emit(OpCodes.Conv_R_Un); convCode = OpCodes.Conv_R8; break; case TypeCode.Decimal: // NB: TypeUtils.IsImplicitNumericConversion makes the promise that implicit conversions // from various integral types and char to decimal are possible. Coalesce allows the // conversion lambda to be omitted in these cases, so we have to handle this case in // here as well, by using the op_Implicit operator implementation on System.Decimal // because there are no opcodes for System.Decimal. Debug.Assert(typeFrom != typeTo); MethodInfo method = tf switch { TypeCode.Byte => Decimal_op_Implicit_Byte, TypeCode.SByte => Decimal_op_Implicit_SByte, TypeCode.Int16 => Decimal_op_Implicit_Int16, TypeCode.UInt16 => Decimal_op_Implicit_UInt16, TypeCode.Int32 => Decimal_op_Implicit_Int32, TypeCode.UInt32 => Decimal_op_Implicit_UInt32, TypeCode.Int64 => Decimal_op_Implicit_Int64, TypeCode.UInt64 => Decimal_op_Implicit_UInt64, TypeCode.Char => Decimal_op_Implicit_Char, _ => throw ContractUtils.Unreachable, }; il.Emit(OpCodes.Call, method); return; case TypeCode.SByte: if (isChecked) { convCode = isFromUnsigned ? OpCodes.Conv_Ovf_I1_Un : OpCodes.Conv_Ovf_I1; } else { if (tf == TypeCode.Byte) { return; } convCode = OpCodes.Conv_I1; } break; case TypeCode.Byte: if (isChecked) { convCode = isFromUnsigned ? OpCodes.Conv_Ovf_U1_Un : OpCodes.Conv_Ovf_U1; } else { if (tf == TypeCode.SByte) { return; } convCode = OpCodes.Conv_U1; } break; case TypeCode.Int16: switch (tf) { case TypeCode.SByte: case TypeCode.Byte: return; case TypeCode.Char: case TypeCode.UInt16: if (!isChecked) { return; } break; } convCode = isChecked ? (isFromUnsigned ? OpCodes.Conv_Ovf_I2_Un : OpCodes.Conv_Ovf_I2) : OpCodes.Conv_I2; break; case TypeCode.Char: case TypeCode.UInt16: switch (tf) { case TypeCode.Byte: case TypeCode.Char: case TypeCode.UInt16: return; case TypeCode.SByte: case TypeCode.Int16: if (!isChecked) { return; } break; } convCode = isChecked ? (isFromUnsigned ? OpCodes.Conv_Ovf_U2_Un : OpCodes.Conv_Ovf_U2) : OpCodes.Conv_U2; break; case TypeCode.Int32: switch (tf) { case TypeCode.Byte: case TypeCode.SByte: case TypeCode.Int16: case TypeCode.UInt16: return; case TypeCode.UInt32: if (!isChecked) { return; } break; } convCode = isChecked ? (isFromUnsigned ? OpCodes.Conv_Ovf_I4_Un : OpCodes.Conv_Ovf_I4) : OpCodes.Conv_I4; break; case TypeCode.UInt32: switch (tf) { case TypeCode.Byte: case TypeCode.Char: case TypeCode.UInt16: return; case TypeCode.SByte: case TypeCode.Int16: case TypeCode.Int32: if (!isChecked) { return; } break; } convCode = isChecked ? (isFromUnsigned ? OpCodes.Conv_Ovf_U4_Un : OpCodes.Conv_Ovf_U4) : OpCodes.Conv_U4; break; case TypeCode.Int64: if (!isChecked && tf == TypeCode.UInt64) { return; } convCode = isChecked ? (isFromUnsigned ? OpCodes.Conv_Ovf_I8_Un : OpCodes.Conv_Ovf_I8) : (isFromUnsigned ? OpCodes.Conv_U8 : OpCodes.Conv_I8); break; case TypeCode.UInt64: if (!isChecked && tf == TypeCode.Int64) { return; } convCode = isChecked ? (isFromUnsigned || tf.IsFloatingPoint() ? OpCodes.Conv_Ovf_U8_Un : OpCodes.Conv_Ovf_U8) : (isFromUnsigned || tf.IsFloatingPoint() ? OpCodes.Conv_U8 : OpCodes.Conv_I8); break; default: throw ContractUtils.Unreachable; } il.Emit(convCode); } private static void EmitNullableToNullableConversion(this ILGenerator il, Type typeFrom, Type typeTo, bool isChecked, ILocalCache locals) { Debug.Assert(typeFrom.IsNullableType()); Debug.Assert(typeTo.IsNullableType()); Label labIfNull; Label labEnd; LocalBuilder locFrom = locals.GetLocal(typeFrom); il.Emit(OpCodes.Stloc, locFrom); // test for null il.Emit(OpCodes.Ldloca, locFrom); il.EmitHasValue(typeFrom); labIfNull = il.DefineLabel(); il.Emit(OpCodes.Brfalse_S, labIfNull); il.Emit(OpCodes.Ldloca, locFrom); locals.FreeLocal(locFrom); il.EmitGetValueOrDefault(typeFrom); Type nnTypeFrom = typeFrom.GetNonNullableType(); Type nnTypeTo = typeTo.GetNonNullableType(); il.EmitConvertToType(nnTypeFrom, nnTypeTo, isChecked, locals); // construct result type ConstructorInfo ci = typeTo.GetConstructor(new Type[] { nnTypeTo }); il.Emit(OpCodes.Newobj, ci); labEnd = il.DefineLabel(); il.Emit(OpCodes.Br_S, labEnd); // if null then create a default one il.MarkLabel(labIfNull); LocalBuilder locTo = locals.GetLocal(typeTo); il.Emit(OpCodes.Ldloca, locTo); il.Emit(OpCodes.Initobj, typeTo); il.Emit(OpCodes.Ldloc, locTo); locals.FreeLocal(locTo); il.MarkLabel(labEnd); } private static void EmitNonNullableToNullableConversion(this ILGenerator il, Type typeFrom, Type typeTo, bool isChecked, ILocalCache locals) { Debug.Assert(!typeFrom.IsNullableType()); Debug.Assert(typeTo.IsNullableType()); Type nnTypeTo = typeTo.GetNonNullableType(); il.EmitConvertToType(typeFrom, nnTypeTo, isChecked, locals); ConstructorInfo ci = typeTo.GetConstructor(new Type[] { nnTypeTo }); il.Emit(OpCodes.Newobj, ci); } private static void EmitNullableToNonNullableConversion(this ILGenerator il, Type typeFrom, Type typeTo, bool isChecked, ILocalCache locals) { Debug.Assert(typeFrom.IsNullableType()); Debug.Assert(!typeTo.IsNullableType()); if (typeTo.IsValueType) il.EmitNullableToNonNullableStructConversion(typeFrom, typeTo, isChecked, locals); else il.EmitNullableToReferenceConversion(typeFrom); } private static void EmitNullableToNonNullableStructConversion(this ILGenerator il, Type typeFrom, Type typeTo, bool isChecked, ILocalCache locals) { Debug.Assert(typeFrom.IsNullableType()); Debug.Assert(!typeTo.IsNullableType()); Debug.Assert(typeTo.IsValueType); LocalBuilder locFrom = locals.GetLocal(typeFrom); il.Emit(OpCodes.Stloc, locFrom); il.Emit(OpCodes.Ldloca, locFrom); locals.FreeLocal(locFrom); il.EmitGetValue(typeFrom); Type nnTypeFrom = typeFrom.GetNonNullableType(); il.EmitConvertToType(nnTypeFrom, typeTo, isChecked, locals); } private static void EmitNullableToReferenceConversion(this ILGenerator il, Type typeFrom) { Debug.Assert(typeFrom.IsNullableType()); // We've got a conversion from nullable to Object, ValueType, Enum, etc. Just box it so that // we get the nullable semantics. il.Emit(OpCodes.Box, typeFrom); } private static void EmitNullableConversion(this ILGenerator il, Type typeFrom, Type typeTo, bool isChecked, ILocalCache locals) { bool isTypeFromNullable = typeFrom.IsNullableType(); bool isTypeToNullable = typeTo.IsNullableType(); Debug.Assert(isTypeFromNullable || isTypeToNullable); if (isTypeFromNullable && isTypeToNullable) il.EmitNullableToNullableConversion(typeFrom, typeTo, isChecked, locals); else if (isTypeFromNullable) il.EmitNullableToNonNullableConversion(typeFrom, typeTo, isChecked, locals); else il.EmitNonNullableToNullableConversion(typeFrom, typeTo, isChecked, locals); } internal static void EmitHasValue(this ILGenerator il, Type nullableType) { MethodInfo mi = nullableType.GetMethod("get_HasValue", BindingFlags.Instance | BindingFlags.Public); Debug.Assert(nullableType.IsValueType); il.Emit(OpCodes.Call, mi); } internal static void EmitGetValue(this ILGenerator il, Type nullableType) { MethodInfo mi = nullableType.GetMethod("get_Value", BindingFlags.Instance | BindingFlags.Public); Debug.Assert(nullableType.IsValueType); il.Emit(OpCodes.Call, mi); } internal static void EmitGetValueOrDefault(this ILGenerator il, Type nullableType) { MethodInfo mi = nullableType.GetMethod("GetValueOrDefault", System.Type.EmptyTypes); Debug.Assert(nullableType.IsValueType); il.Emit(OpCodes.Call, mi); } #endregion #region Arrays #if FEATURE_COMPILE_TO_METHODBUILDER /// <summary> /// Emits an array of constant values provided in the given array. /// The array is strongly typed. /// </summary> internal static void EmitArray<T>(this ILGenerator il, T[] items, ILocalCache locals) { Debug.Assert(items != null); il.EmitPrimitive(items.Length); il.Emit(OpCodes.Newarr, typeof(T)); for (int i = 0; i < items.Length; i++) { il.Emit(OpCodes.Dup); il.EmitPrimitive(i); il.TryEmitConstant(items[i], typeof(T), locals); il.EmitStoreElement(typeof(T)); } } #endif /// <summary> /// Emits an array of values of count size. /// </summary> internal static void EmitArray(this ILGenerator il, Type elementType, int count) { Debug.Assert(elementType != null); Debug.Assert(count >= 0); il.EmitPrimitive(count); il.Emit(OpCodes.Newarr, elementType); } /// <summary> /// Emits an array construction code. /// The code assumes that bounds for all dimensions /// are already emitted. /// </summary> internal static void EmitArray(this ILGenerator il, Type arrayType) { Debug.Assert(arrayType != null); Debug.Assert(arrayType.IsArray); if (arrayType.IsSZArray) { il.Emit(OpCodes.Newarr, arrayType.GetElementType()); } else { Type[] types = new Type[arrayType.GetArrayRank()]; for (int i = 0; i < types.Length; i++) { types[i] = typeof(int); } ConstructorInfo ci = arrayType.GetConstructor(types); Debug.Assert(ci != null); il.EmitNew(ci); } } #endregion #region Support for emitting constants private static void EmitDecimal(this ILGenerator il, decimal value) { int[] bits = decimal.GetBits(value); int scale = (bits[3] & int.MaxValue) >> 16; if (scale == 0) { if (int.MinValue <= value) { if (value <= int.MaxValue) { int intValue = decimal.ToInt32(value); switch (intValue) { case -1: il.Emit(OpCodes.Ldsfld, Decimal_MinusOne); return; case 0: il.EmitDefault(typeof(decimal), locals: null); // locals won't be used. return; case 1: il.Emit(OpCodes.Ldsfld, Decimal_One); return; default: il.EmitPrimitive(intValue); il.EmitNew(Decimal_Ctor_Int32); return; } } if (value <= uint.MaxValue) { il.EmitPrimitive(decimal.ToUInt32(value)); il.EmitNew(Decimal_Ctor_UInt32); return; } } if (long.MinValue <= value) { if (value <= long.MaxValue) { il.EmitPrimitive(decimal.ToInt64(value)); il.EmitNew(Decimal_Ctor_Int64); return; } if (value <= ulong.MaxValue) { il.EmitPrimitive(decimal.ToUInt64(value)); il.EmitNew(Decimal_Ctor_UInt64); return; } if (value == decimal.MaxValue) { il.Emit(OpCodes.Ldsfld, Decimal_MaxValue); return; } } else if (value == decimal.MinValue) { il.Emit(OpCodes.Ldsfld, Decimal_MinValue); return; } } il.EmitPrimitive(bits[0]); il.EmitPrimitive(bits[1]); il.EmitPrimitive(bits[2]); il.EmitPrimitive((bits[3] & 0x80000000) != 0); il.EmitPrimitive(unchecked((byte)scale)); il.EmitNew(Decimal_Ctor_Int32_Int32_Int32_Bool_Byte); } /// <summary> /// Emits default(T) /// Semantics match C# compiler behavior /// </summary> internal static void EmitDefault(this ILGenerator il, Type type, ILocalCache locals) { switch (type.GetTypeCode()) { case TypeCode.DateTime: il.Emit(OpCodes.Ldsfld, DateTime_MinValue); break; case TypeCode.Object: if (type.IsValueType) { // Type.GetTypeCode on an enum returns the underlying // integer TypeCode, so we won't get here. Debug.Assert(!type.IsEnum); // This is the IL for default(T) if T is a generic type // parameter, so it should work for any type. It's also // the standard pattern for structs. LocalBuilder lb = locals.GetLocal(type); il.Emit(OpCodes.Ldloca, lb); il.Emit(OpCodes.Initobj, type); il.Emit(OpCodes.Ldloc, lb); locals.FreeLocal(lb); break; } goto case TypeCode.Empty; case TypeCode.Empty: case TypeCode.String: case TypeCode.DBNull: il.Emit(OpCodes.Ldnull); break; case TypeCode.Boolean: case TypeCode.Char: case TypeCode.SByte: case TypeCode.Byte: case TypeCode.Int16: case TypeCode.UInt16: case TypeCode.Int32: case TypeCode.UInt32: il.Emit(OpCodes.Ldc_I4_0); break; case TypeCode.Int64: case TypeCode.UInt64: il.Emit(OpCodes.Ldc_I4_0); il.Emit(OpCodes.Conv_I8); break; case TypeCode.Single: il.Emit(OpCodes.Ldc_R4, default(float)); break; case TypeCode.Double: il.Emit(OpCodes.Ldc_R8, default(double)); break; case TypeCode.Decimal: il.Emit(OpCodes.Ldsfld, Decimal_Zero); break; default: throw ContractUtils.Unreachable; } } #endregion } }
using System; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Text.RegularExpressions; namespace DataBoss { public class PowerArgs : IEnumerable<KeyValuePair<string, string>> { static readonly ConcurrentDictionary<Type, Action<object, string>> AddItemCache = new ConcurrentDictionary<Type, Action<object, string>>(); readonly Dictionary<string, string> args = new Dictionary<string, string>(); readonly List<string> commands = new List<string>(); public int Count => args.Count; public string this[string arg] => args[arg]; public IReadOnlyList<string> Commands => commands.AsReadOnly(); public static PowerArgs Parse(params string[] args) => Parse((IEnumerable<string>)args); public static PowerArgs Parse(IEnumerable<string> args) { var result = new PowerArgs(); using(var it = args.GetEnumerator()) { for(string item = null; it.MoveNext();) { if(item != null && result.args[item].EndsWith(",") || it.Current.StartsWith(",")) { result.args[item] = result.args[item] + it.Current; } else if(MatchArg(it.Current, out item)) { if(!it.MoveNext() || IsArg(it.Current)) throw new InvalidOperationException("No value given for '" + item + "'"); result.Add(item, it.Current); } else { result.commands.Add(it.Current); } } } return result; } public static void Validate(object obj) { var errors = new List<PowerArgsValidationResult>(); foreach (var field in obj.GetType().GetFields()) { var validations = field.GetCustomAttributes<ValidationAttribute>(); var value = field.GetValue(obj); foreach(var item in validations) if(!item.IsValid(value)) errors.Add(new PowerArgsValidationResult(field.Name, field.FieldType, value, item)); } foreach (var prop in obj.GetType().GetProperties()) { var validations = prop.GetCustomAttributes<ValidationAttribute>(); var value = prop.GetValue(obj); foreach(var item in validations) if(!item.IsValid(value)) errors.Add(new PowerArgsValidationResult(prop.Name, prop.PropertyType, value, item)); } if(errors.Count > 0) throw new PowerArgsValidationException(errors); } public static List<PowerArg> Describe(Type argsType) { var args = argsType.GetFields() .Cast<MemberInfo>() .Concat(argsType.GetProperties()) .Select(x => new PowerArg(x)) .ToList(); args.Sort((a, b) => { if(a.Order.HasValue) return b.Order.HasValue ? a.Order.Value - b.Order.Value : -1; return b.Order.HasValue ? 1 : 0; }); return args; } static bool MatchArg(string item, out string result) { if(Regex.IsMatch(item , "^-[^0-9]")) { result = item.Substring(1); return true; } result = null; return false; } static bool IsArg(string input) { string ignored; return MatchArg(input, out ignored); } void Add(string arg, string value) => args.Add(arg, value); public bool TryGetArg(string name, out string value) => args.TryGetValue(name, out value); public T Into<T>() where T : new() => Into(new T()); public T Into<T>(T target) { var parseFailures = new List<PowerArgsParseException.ParseFailure>(); FillFields(target, parseFailures.Add); FillProps(target, parseFailures.Add); if(parseFailures.Count != 0) throw new PowerArgsParseException(parseFailures); return target; } private void FillFields(object target, Action<PowerArgsParseException.ParseFailure> onFailure) { foreach (var field in target.GetType().GetFields()) { object value; if (TryGetArgWithDefault(field, field.FieldType, onFailure, out value)) field.SetValue(target, value); } } private void FillProps(object target, Action<PowerArgsParseException.ParseFailure> onFailure) { foreach (var prop in target.GetType().GetProperties()) { object value; if (TryGetArgWithDefault(prop, prop.PropertyType, onFailure, out value)) prop.SetValue(target, value); } } private bool TryGetArgWithDefault(MemberInfo member, Type targetType, Action<PowerArgsParseException.ParseFailure> onFailure, out object value) { string argValue; if(TryGetArg(member.Name, out argValue) && TryParse(member.Name, argValue, targetType, onFailure, out value)) return true; var defalt = member.GetCustomAttribute<DefaultValueAttribute>(); if(defalt != null) { value = defalt.Value; return true; } value = null; return false; } bool TryParse(string name, string input, Type targetType, Action<PowerArgsParseException.ParseFailure> onFailure, out object result) { if(targetType == typeof(string)) { result = input; return true; } if(TryGetParse(targetType, out var parse)) { try { result = parse.Invoke(null, new[]{ input }); return true; } catch(Exception ex) { result = null; ReportFailure(input, ex); return false; } } if(targetType.TryGetNullableTargetType(out var t)) { object inner; if(TryParse(name, input, t, onFailure, out inner)) { result = targetType.GetConstructor(new[] { t }).Invoke(new[] { inner }); return true; } } Action<object, string> addItem; if(TryGetAddItem(targetType, out addItem)) { result = targetType.GetConstructor(Type.EmptyTypes).Invoke(new object[0]); foreach(var item in input.Split(',')) try { addItem(result, item); } catch(Exception ex) { ReportFailure(item, ex); } return true; } result = null; return false; void ReportFailure(string s, Exception ex) => onFailure(new PowerArgsParseException.ParseFailure { ArgumentName = name, ArgumentType = targetType, Input = s, Error = ex, }); } static bool TryGetParse(Type type, out MethodInfo parse) { if(type.IsEnum) { parse = typeof(PowerArgs).GetMethod(nameof(ParseEnum), BindingFlags.Static | BindingFlags.NonPublic).MakeGenericMethod(type); return true; } parse = type.GetMethod("Parse", new[] { typeof(string) }); if(parse != null && !parse.IsStatic) parse = null; return parse != null; } static T ParseEnum<T>(string input) => (T)Enum.Parse(typeof(T), input); static bool TryGetAddItem(Type targetType, out Action<object, string> output) { output = AddItemCache.GetOrAdd(targetType, targetTyp => { var adder = targetType .GetMethods(BindingFlags.Instance | BindingFlags.Public) .Where(x => x.Name == "Add") .Select(x => new { Add = x, Parameters = x.GetParameters() }) .FirstOrDefault(x => x.Parameters.Length == 1); if(adder == null || !TryGetParse(adder.Parameters[0].ParameterType, out var parse)) return null; var target = Expression.Parameter(typeof(object)); var value = Expression.Parameter(typeof(string)); return Expression.Lambda<Action<object,string>>( Expression.Call( Expression.Convert(target, targetType), adder.Add, Expression.Call(parse, value)), target, value) .Compile(); }); return output != null; } public IEnumerator<KeyValuePair<string, string>> GetEnumerator() { return args.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return args.GetEnumerator(); } } }
// $Id$ // // Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. // using System; using Org.Apache.Etch.Bindings.Csharp.Msg; using Org.Apache.Etch.Bindings.Csharp.Support; using Org.Apache.Etch.Bindings.Csharp.Util; namespace Org.Apache.Etch.Bindings.Csharp.Transport.Filter { public class KeepAlive : AbstractMessageFilter, AlarmListener { public const String DELAY = "KeepAlive.delay"; public const String COUNT = "KeepAlive.count"; public KeepAlive(TransportMessage transport, URL uri, Resources resources) : base(transport, uri, resources) { delay = uri.GetIntegerTerm(DELAY, 15); if (delay <= 0) throw new ArgumentException("delay <= 0"); count = uri.GetIntegerTerm(COUNT, 4); if (count <= 0) throw new ArgumentException("count <= 0"); server = (Boolean) transport.TransportQuery(TransportConsts.IS_SERVER); // Log.report( "KeepAliveInstalled", // "delay", delay, "count", count, "server", server ); vf = (ValueFactory)resources.Get(TransportConsts.VALUE_FACTORY); mf_delay = new Field("delay"); mf_count = new Field("count"); mt_request = new XType("_Etch_KeepAliveReq"); mt_request.PutValidator(mf_delay, Validator_int.Get(0)); mt_request.PutValidator(mf_count, Validator_int.Get(0)); vf.AddType(mt_request); mt_response = new XType("_Etch_KeepAliveResp"); vf.AddType(mt_response); mt_request.SetResult(mt_response); } private int delay; private int count; private readonly bool server; private readonly ValueFactory vf; private readonly Field mf_delay; private readonly Field mf_count; private readonly XType mt_request; private readonly XType mt_response; public int GetDelay() { return delay; } public int GetCount() { return count; } public bool GetServer() { return server; } public override bool SessionMessage(Who sender, Message msg) { if (msg.IsType(mt_request)) { handleRequest(msg); return true; } if (msg.IsType(mt_response)) { handleResponse(msg); return true; } return base.SessionMessage(sender, msg); } protected override bool SessionUp() { // Log.report( "KeepAliveSessionUp", "server", server ); up = true; AlarmManager.staticAdd(this, null, delay * 1000); tickle(); return true; } protected override bool SessionDown() { // Log.report( "KeepAliveSessionDown", "server", server ); up = false; AlarmManager.staticRemove(this); return true; } private bool up; private void handleRequest(Message msg) { if (!server) { // we're a client that got a request, likely we're talking to a // server that is confused. return; } //Log.report( "GotKeepAliveReq", "msg", msg ); // Console.WriteLine("GotKeepAliveReq:Msg " + msg); int? d = (int?)msg.Get(mf_delay); if (d != null && d.Value > 0) { //Console.WriteLine("KeepAliveResetDelay delay " + d ); delay = d.Value; } int? c = (int?)msg.Get(mf_count); if (c != null && c.Value > 0) { // Console.WriteLine( "KeepAliveResetCount count " + c ); count = c.Value; } tickle(); sendKeepAliveResp(msg); } private void handleResponse(Message msg) { if (server) { // we're a server that got a response, which means either we sent // a request (but we shouldn't do that if we're a server) or the // client is confused. return; } //Log.report( "GotKeepAliveResp", "msg", msg ); //Console.WriteLine(" GotKeepAliveResp: msg " + msg); tickle(); } private void tickle() { // lastTickle = Timer.GetNanos(); // lastTickle = HPTimer.Now(); lastTickle = HPTimer.Now(); } private long lastTickle; private void checkTickle() { long ms = HPTimer.MillisSince(lastTickle); // Log.report( "KeepAliveIdle", "ms", ms, "server", server ); if (ms >= count * delay * 1000) { try { // Log.report( "KeepAliveReset", "server", server ); session.SessionNotify("KeepAlive resetting dead connection"); transport.TransportControl(TransportConsts.RESET, 0); } catch (Exception e) { reportError(e); } } } private void sendKeepAliveReq() { Message msg = new Message(mt_request, vf); msg.Add(mf_delay, delay); msg.Add(mf_count, count); try { // Log.report( "SendKeepAliveReq", "msg", msg ); transport.TransportMessage(null, msg); } catch (Exception e) { reportError(e); } } private void sendKeepAliveResp(Message msg) { Message rmsg = msg.Reply(); try { //Log.report( "SendKeepAliveResp", "rmsg", rmsg ); transport.TransportMessage(null, rmsg); } catch (Exception e) { reportError(e); } } public int Wakeup(AlarmManager manager, Object state, long due) { // Log.report( "KeepAliveWakeup", "server", server ); if (!up) return 0; if (!server) { TodoManager.AddTodo(new MyTodo(sendKeepAliveReq, reportError)); } checkTickle(); return delay * 1000; } private void reportError(Exception e) { try { session.SessionNotify(e); } catch (Exception e1) { Console.WriteLine(e1); } } public override string ToString() { return "KeepAlive/" + transport; } } public class MyTodo : Todo { public delegate void doit(); public delegate void report(Exception e); public MyTodo(doit d, report r) { this.d = d; this.r = r; } private readonly doit d; private readonly report r; public void Doit(TodoManager mgr) { d(); } public void Exception(TodoManager mgr, Exception e) { r(e); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Microsoft.Azure.Devices.Common { using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.Contracts; /*============================================================ ** ** Class: ReadOnlyDictionary<TKey, TValue> ** ** <OWNER>gpaperin</OWNER> ** ** Purpose: Read-only wrapper for another generic dictionary. ** ===========================================================*/ #if !WINDOWS_UWP [Serializable] #endif [DebuggerDisplay("Count = {Count}")] public sealed class ReadOnlyDictionary45<TKey, TValue> : IDictionary<TKey, TValue>, IDictionary //, IReadOnlyDictionary<TKey, TValue> { readonly IDictionary<TKey, TValue> m_dictionary; #if !WINDOWS_UWP [NonSerialized] #endif Object m_syncRoot; #if !WINDOWS_UWP [NonSerialized] #endif KeyCollection m_keys; #if !WINDOWS_UWP [NonSerialized] #endif ValueCollection m_values; #if !WINDOWS_UWP [NonSerialized] #endif IReadOnlyIndicator m_readOnlyIndicator; public ReadOnlyDictionary45(IDictionary<TKey, TValue> dictionary) : this(dictionary, new AlwaysReadOnlyIndicator()) { } internal ReadOnlyDictionary45(IDictionary<TKey, TValue> dictionary, IReadOnlyIndicator readOnlyIndicator) { if (dictionary == null) { throw new ArgumentNullException("dictionary"); } Contract.EndContractBlock(); m_dictionary = dictionary; m_readOnlyIndicator = readOnlyIndicator; } protected IDictionary<TKey, TValue> Dictionary { get { return m_dictionary; } } public KeyCollection Keys { get { Contract.Ensures(Contract.Result<KeyCollection>() != null); if (m_keys == null) { m_keys = new KeyCollection(m_dictionary.Keys, this.m_readOnlyIndicator); } return m_keys; } } public ValueCollection Values { get { Contract.Ensures(Contract.Result<ValueCollection>() != null); if (m_values == null) { m_values = new ValueCollection(m_dictionary.Values, this.m_readOnlyIndicator); } return m_values; } } #region IDictionary<TKey, TValue> Members public bool ContainsKey(TKey key) { return m_dictionary.ContainsKey(key); } ICollection<TKey> IDictionary<TKey, TValue>.Keys { get { return Keys; } } public bool TryGetValue(TKey key, out TValue value) { return m_dictionary.TryGetValue(key, out value); } ICollection<TValue> IDictionary<TKey, TValue>.Values { get { return Values; } } public TValue this[TKey key] { get { return m_dictionary[key]; } } void IDictionary<TKey, TValue>.Add(TKey key, TValue value) { if (this.m_readOnlyIndicator.IsReadOnly) { throw Fx.Exception.AsError(new NotSupportedException(Resources.ObjectIsReadOnly)); } m_dictionary.Add(key, value); } bool IDictionary<TKey, TValue>.Remove(TKey key) { if (this.m_readOnlyIndicator.IsReadOnly) { throw Fx.Exception.AsError(new NotSupportedException(Resources.ObjectIsReadOnly)); } return m_dictionary.Remove(key); } TValue IDictionary<TKey, TValue>.this[TKey key] { get { return m_dictionary[key]; } set { if (this.m_readOnlyIndicator.IsReadOnly) { throw Fx.Exception.AsError(new NotSupportedException(Resources.ObjectIsReadOnly)); } m_dictionary[key] = value; } } #endregion #region ICollection<KeyValuePair<TKey, TValue>> Members public int Count { get { return m_dictionary.Count; } } bool ICollection<KeyValuePair<TKey, TValue>>.Contains(KeyValuePair<TKey, TValue> item) { return m_dictionary.Contains(item); } void ICollection<KeyValuePair<TKey, TValue>>.CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex) { m_dictionary.CopyTo(array, arrayIndex); } bool ICollection<KeyValuePair<TKey, TValue>>.IsReadOnly { get { return true; } } void ICollection<KeyValuePair<TKey, TValue>>.Add(KeyValuePair<TKey, TValue> item) { if (this.m_readOnlyIndicator.IsReadOnly) { throw Fx.Exception.AsError(new NotSupportedException(Resources.ObjectIsReadOnly)); } m_dictionary.Add(item); } void ICollection<KeyValuePair<TKey, TValue>>.Clear() { if (this.m_readOnlyIndicator.IsReadOnly) { throw Fx.Exception.AsError(new NotSupportedException(Resources.ObjectIsReadOnly)); } m_dictionary.Clear(); } bool ICollection<KeyValuePair<TKey, TValue>>.Remove(KeyValuePair<TKey, TValue> item) { if (this.m_readOnlyIndicator.IsReadOnly) { throw Fx.Exception.AsError(new NotSupportedException(Resources.ObjectIsReadOnly)); } return m_dictionary.Remove(item); } #endregion #region IEnumerable<KeyValuePair<TKey, TValue>> Members public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator() { return m_dictionary.GetEnumerator(); } #endregion #region IEnumerable Members System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return ((IEnumerable)m_dictionary).GetEnumerator(); } #endregion #region IDictionary Members private static bool IsCompatibleKey(object key) { if (key == null) { throw Fx.Exception.ArgumentNull("key"); } return key is TKey; } void IDictionary.Add(object key, object value) { if (this.m_readOnlyIndicator.IsReadOnly) { throw Fx.Exception.AsError(new NotSupportedException(Resources.ObjectIsReadOnly)); } m_dictionary.Add((TKey)key, (TValue)value); } void IDictionary.Clear() { if (this.m_readOnlyIndicator.IsReadOnly) { throw Fx.Exception.AsError(new NotSupportedException(Resources.ObjectIsReadOnly)); } m_dictionary.Clear(); } bool IDictionary.Contains(object key) { return IsCompatibleKey(key) && ContainsKey((TKey)key); } IDictionaryEnumerator IDictionary.GetEnumerator() { IDictionary d = m_dictionary as IDictionary; if (d != null) { return d.GetEnumerator(); } return new DictionaryEnumerator(m_dictionary); } bool IDictionary.IsFixedSize { get { return true; } } bool IDictionary.IsReadOnly { get { return true; } } ICollection IDictionary.Keys { get { return Keys; } } void IDictionary.Remove(object key) { if (this.m_readOnlyIndicator.IsReadOnly) { throw Fx.Exception.AsError(new NotSupportedException(Resources.ObjectIsReadOnly)); } m_dictionary.Remove((TKey)key); } ICollection IDictionary.Values { get { return Values; } } object IDictionary.this[object key] { get { if (IsCompatibleKey(key)) { return this[(TKey)key]; } return null; } set { if (this.m_readOnlyIndicator.IsReadOnly) { throw Fx.Exception.AsError(new NotSupportedException(Resources.ObjectIsReadOnly)); } m_dictionary[(TKey)key] = (TValue)value; } } void ICollection.CopyTo(Array array, int index) { if (array == null) { Fx.Exception.ArgumentNull("array"); } if (array.Rank != 1 || array.GetLowerBound(0) != 0) { throw Fx.Exception.Argument("array", Resources.InvalidBufferSize); } if (index < 0 || index > array.Length) { throw Fx.Exception.ArgumentOutOfRange("index", index, Resources.ValueMustBeNonNegative); } if (array.Length - index < Count) { throw Fx.Exception.Argument("array", Resources.InvalidBufferSize); } KeyValuePair<TKey, TValue>[] pairs = array as KeyValuePair<TKey, TValue>[]; if (pairs != null) { m_dictionary.CopyTo(pairs, index); } else { DictionaryEntry[] dictEntryArray = array as DictionaryEntry[]; if (dictEntryArray != null) { foreach (var item in m_dictionary) { dictEntryArray[index++] = new DictionaryEntry(item.Key, item.Value); } } else { object[] objects = array as object[]; if (objects == null) { throw Fx.Exception.Argument("array", Resources.InvalidBufferSize); } try { foreach (var item in m_dictionary) { objects[index++] = new KeyValuePair<TKey, TValue>(item.Key, item.Value); } } catch (ArrayTypeMismatchException) { throw Fx.Exception.Argument("array", Resources.InvalidBufferSize); } } } } bool ICollection.IsSynchronized { get { return false; } } object ICollection.SyncRoot { get { if (m_syncRoot == null) { ICollection c = m_dictionary as ICollection; if (c != null) { m_syncRoot = c.SyncRoot; } else { System.Threading.Interlocked.CompareExchange<Object>(ref m_syncRoot, new Object(), null); } } return m_syncRoot; } } #if !WINDOWS_UWP [Serializable] #endif private struct DictionaryEnumerator : IDictionaryEnumerator { private readonly IDictionary<TKey, TValue> m_dictionary; private IEnumerator<KeyValuePair<TKey, TValue>> m_enumerator; public DictionaryEnumerator(IDictionary<TKey, TValue> dictionary) { m_dictionary = dictionary; m_enumerator = m_dictionary.GetEnumerator(); } public DictionaryEntry Entry { get { return new DictionaryEntry(m_enumerator.Current.Key, m_enumerator.Current.Value); } } public object Key { get { return m_enumerator.Current.Key; } } public object Value { get { return m_enumerator.Current.Value; } } public object Current { get { return Entry; } } public bool MoveNext() { return m_enumerator.MoveNext(); } public void Reset() { m_enumerator.Reset(); } } #endregion [DebuggerDisplay("Count = {Count}")] #if !WINDOWS_UWP [Serializable] #endif public sealed class KeyCollection : ICollection<TKey>, ICollection { private readonly ICollection<TKey> m_collection; #if !WINDOWS_UWP [NonSerialized] #endif private Object m_syncRoot; #if !WINDOWS_UWP [NonSerialized] #endif private readonly IReadOnlyIndicator m_readOnlyIndicator; internal KeyCollection(ICollection<TKey> collection, IReadOnlyIndicator readOnlyIndicator) { if (collection == null) { throw Fx.Exception.ArgumentNull("collection"); } m_collection = collection; m_readOnlyIndicator = readOnlyIndicator; } #region ICollection<T> Members void ICollection<TKey>.Add(TKey item) { if (this.m_readOnlyIndicator.IsReadOnly) { throw Fx.Exception.AsError(new NotSupportedException(Resources.ObjectIsReadOnly)); } m_collection.Add(item); } void ICollection<TKey>.Clear() { if (this.m_readOnlyIndicator.IsReadOnly) { throw Fx.Exception.AsError(new NotSupportedException(Resources.ObjectIsReadOnly)); } m_collection.Clear(); } bool ICollection<TKey>.Contains(TKey item) { return m_collection.Contains(item); } public void CopyTo(TKey[] array, int arrayIndex) { m_collection.CopyTo(array, arrayIndex); } public int Count { get { return m_collection.Count; } } bool ICollection<TKey>.IsReadOnly { get { return true; } } bool ICollection<TKey>.Remove(TKey item) { if (this.m_readOnlyIndicator.IsReadOnly) { throw Fx.Exception.AsError(new NotSupportedException(Resources.ObjectIsReadOnly)); } return m_collection.Remove(item); } #endregion #region IEnumerable<T> Members public IEnumerator<TKey> GetEnumerator() { return m_collection.GetEnumerator(); } #endregion #region IEnumerable Members System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return ((IEnumerable)m_collection).GetEnumerator(); } #endregion #region ICollection Members void ICollection.CopyTo(Array array, int index) { throw Fx.Exception.AsError(new NotImplementedException()); } bool ICollection.IsSynchronized { get { return false; } } object ICollection.SyncRoot { get { if (m_syncRoot == null) { ICollection c = m_collection as ICollection; if (c != null) { m_syncRoot = c.SyncRoot; } else { System.Threading.Interlocked.CompareExchange<Object>(ref m_syncRoot, new Object(), null); } } return m_syncRoot; } } #endregion } [DebuggerDisplay("Count = {Count}")] #if !WINDOWS_UWP [Serializable] #endif public sealed class ValueCollection : ICollection<TValue>, ICollection { private readonly ICollection<TValue> m_collection; #if !WINDOWS_UWP [NonSerialized] #endif private Object m_syncRoot; #if !WINDOWS_UWP [NonSerialized] #endif private readonly IReadOnlyIndicator m_readOnlyIndicator; internal ValueCollection(ICollection<TValue> collection, IReadOnlyIndicator readOnlyIndicator) { if (collection == null) { throw Fx.Exception.ArgumentNull("collection"); } m_collection = collection; m_readOnlyIndicator = readOnlyIndicator; } #region ICollection<T> Members void ICollection<TValue>.Add(TValue item) { if (this.m_readOnlyIndicator.IsReadOnly) { throw Fx.Exception.AsError(new NotSupportedException(Resources.ObjectIsReadOnly)); } m_collection.Add(item); } void ICollection<TValue>.Clear() { if (this.m_readOnlyIndicator.IsReadOnly) { throw Fx.Exception.AsError(new NotSupportedException(Resources.ObjectIsReadOnly)); } m_collection.Clear(); } bool ICollection<TValue>.Contains(TValue item) { return m_collection.Contains(item); } public void CopyTo(TValue[] array, int arrayIndex) { m_collection.CopyTo(array, arrayIndex); } public int Count { get { return m_collection.Count; } } bool ICollection<TValue>.IsReadOnly { get { return true; } } bool ICollection<TValue>.Remove(TValue item) { if (this.m_readOnlyIndicator.IsReadOnly) { throw Fx.Exception.AsError(new NotSupportedException(Resources.ObjectIsReadOnly)); } return m_collection.Remove(item); } #endregion #region IEnumerable<T> Members public IEnumerator<TValue> GetEnumerator() { return m_collection.GetEnumerator(); } #endregion #region IEnumerable Members System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return ((IEnumerable)m_collection).GetEnumerator(); } #endregion #region ICollection Members void ICollection.CopyTo(Array array, int index) { throw Fx.Exception.AsError(new NotImplementedException()); } bool ICollection.IsSynchronized { get { return false; } } object ICollection.SyncRoot { get { if (m_syncRoot == null) { ICollection c = m_collection as ICollection; if (c != null) { m_syncRoot = c.SyncRoot; } else { System.Threading.Interlocked.CompareExchange<Object>(ref m_syncRoot, new Object(), null); } } return m_syncRoot; } } #endregion ICollection Members } class AlwaysReadOnlyIndicator : IReadOnlyIndicator { public bool IsReadOnly { get { return true; } } } } internal interface IReadOnlyIndicator { bool IsReadOnly { get; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Search { using System; using System.Linq; using System.Collections.Generic; 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> /// DataSourcesOperations operations. /// </summary> internal partial class DataSourcesOperations : IServiceOperations<SearchServiceClient>, IDataSourcesOperations { /// <summary> /// Initializes a new instance of the DataSourcesOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal DataSourcesOperations(SearchServiceClient client) { if (client == null) { throw new ArgumentNullException("client"); } this.Client = client; } /// <summary> /// Gets a reference to the SearchServiceClient /// </summary> public SearchServiceClient Client { get; private set; } /// <summary> /// Creates a new Azure Search datasource or updates a datasource if it /// already exists. /// </summary> /// <param name='dataSourceName'> /// The name of the datasource to create or update. /// </param> /// <param name='dataSource'> /// The definition of the datasource to create or update. /// </param> /// <param name='searchRequestOptions'> /// Additional parameters for the operation /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<DataSource>> CreateOrUpdateWithHttpMessagesAsync(string dataSourceName, DataSource dataSource, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (dataSourceName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "dataSourceName"); } if (dataSource == null) { throw new ValidationException(ValidationRules.CannotBeNull, "dataSource"); } if (dataSource != null) { dataSource.Validate(); } if (this.Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } Guid? clientRequestId = default(Guid?); if (searchRequestOptions != null) { clientRequestId = searchRequestOptions.ClientRequestId; } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("dataSourceName", dataSourceName); tracingParameters.Add("dataSource", dataSource); tracingParameters.Add("clientRequestId", clientRequestId); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "CreateOrUpdate", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "datasources('{dataSourceName}')").ToString(); _url = _url.Replace("{dataSourceName}", Uri.EscapeDataString(dataSourceName)); List<string> _queryParameters = new List<string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (clientRequestId != null) { if (_httpRequest.Headers.Contains("client-request-id")) { _httpRequest.Headers.Remove("client-request-id"); } _httpRequest.Headers.TryAddWithoutValidation("client-request-id", SafeJsonConvert.SerializeObject(clientRequestId, this.Client.SerializationSettings).Trim('"')); } 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(dataSource != null) { _requestContent = SafeJsonConvert.SerializeObject(dataSource, this.Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.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 != 201) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.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("request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<DataSource>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<DataSource>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } // Deserialize Response if ((int)_statusCode == 201) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<DataSource>(_responseContent, this.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 an Azure Search datasource. /// </summary> /// <param name='dataSourceName'> /// The name of the datasource to delete. /// </param> /// <param name='searchRequestOptions'> /// Additional parameters for the operation /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string dataSourceName, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (dataSourceName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "dataSourceName"); } if (this.Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } Guid? clientRequestId = default(Guid?); if (searchRequestOptions != null) { clientRequestId = searchRequestOptions.ClientRequestId; } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("dataSourceName", dataSourceName); tracingParameters.Add("clientRequestId", clientRequestId); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Delete", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "datasources('{dataSourceName}')").ToString(); _url = _url.Replace("{dataSourceName}", Uri.EscapeDataString(dataSourceName)); List<string> _queryParameters = new List<string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("DELETE"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (clientRequestId != null) { if (_httpRequest.Headers.Contains("client-request-id")) { _httpRequest.Headers.Remove("client-request-id"); } _httpRequest.Headers.TryAddWithoutValidation("client-request-id", SafeJsonConvert.SerializeObject(clientRequestId, this.Client.SerializationSettings).Trim('"')); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.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 != 204 && (int)_statusCode != 404) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("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("request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Retrieves a datasource definition from Azure Search. /// </summary> /// <param name='dataSourceName'> /// The name of the datasource to retrieve. /// </param> /// <param name='searchRequestOptions'> /// Additional parameters for the operation /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<DataSource>> GetWithHttpMessagesAsync(string dataSourceName, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (dataSourceName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "dataSourceName"); } if (this.Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } Guid? clientRequestId = default(Guid?); if (searchRequestOptions != null) { clientRequestId = searchRequestOptions.ClientRequestId; } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("dataSourceName", dataSourceName); tracingParameters.Add("clientRequestId", clientRequestId); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "datasources('{dataSourceName}')").ToString(); _url = _url.Replace("{dataSourceName}", Uri.EscapeDataString(dataSourceName)); List<string> _queryParameters = new List<string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (clientRequestId != null) { if (_httpRequest.Headers.Contains("client-request-id")) { _httpRequest.Headers.Remove("client-request-id"); } _httpRequest.Headers.TryAddWithoutValidation("client-request-id", SafeJsonConvert.SerializeObject(clientRequestId, this.Client.SerializationSettings).Trim('"')); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.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 = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.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("request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<DataSource>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<DataSource>(_responseContent, this.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 all datasources available for an Azure Search service. /// </summary> /// <param name='searchRequestOptions'> /// Additional parameters for the operation /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<DataSourceListResult>> ListWithHttpMessagesAsync(SearchRequestOptions searchRequestOptions = default(SearchRequestOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (this.Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } Guid? clientRequestId = default(Guid?); if (searchRequestOptions != null) { clientRequestId = searchRequestOptions.ClientRequestId; } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("clientRequestId", clientRequestId); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "datasources").ToString(); List<string> _queryParameters = new List<string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (clientRequestId != null) { if (_httpRequest.Headers.Contains("client-request-id")) { _httpRequest.Headers.Remove("client-request-id"); } _httpRequest.Headers.TryAddWithoutValidation("client-request-id", SafeJsonConvert.SerializeObject(clientRequestId, this.Client.SerializationSettings).Trim('"')); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.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 = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.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("request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<DataSourceListResult>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<DataSourceListResult>(_responseContent, this.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> /// Creates a new Azure Search datasource. /// </summary> /// <param name='dataSource'> /// The definition of the datasource to create. /// </param> /// <param name='searchRequestOptions'> /// Additional parameters for the operation /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<DataSource>> CreateWithHttpMessagesAsync(DataSource dataSource, SearchRequestOptions searchRequestOptions = default(SearchRequestOptions), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (dataSource == null) { throw new ValidationException(ValidationRules.CannotBeNull, "dataSource"); } if (dataSource != null) { dataSource.Validate(); } if (this.Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } Guid? clientRequestId = default(Guid?); if (searchRequestOptions != null) { clientRequestId = searchRequestOptions.ClientRequestId; } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("dataSource", dataSource); tracingParameters.Add("clientRequestId", clientRequestId); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Create", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "datasources").ToString(); List<string> _queryParameters = new List<string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("POST"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (clientRequestId != null) { if (_httpRequest.Headers.Contains("client-request-id")) { _httpRequest.Headers.Remove("client-request-id"); } _httpRequest.Headers.TryAddWithoutValidation("client-request-id", SafeJsonConvert.SerializeObject(clientRequestId, this.Client.SerializationSettings).Trim('"')); } 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(dataSource != null) { _requestContent = SafeJsonConvert.SerializeObject(dataSource, this.Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.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 != 201) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.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("request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<DataSource>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 201) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<DataSource>(_responseContent, this.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; } } }
#if !SILVERLIGHT using System; using System.Reflection; using System.Reflection.Emit; namespace DataGenerator.Reflection { internal static class DynamicMethodFactory { public static Func<object, object[], object> CreateMethod(MethodInfo methodInfo) { if (methodInfo == null) throw new ArgumentNullException(nameof(methodInfo)); var dynamicMethod = CreateDynamicMethod( "Dynamic" + methodInfo.Name, typeof(object), new[] { typeof(object), typeof(object[]) }, methodInfo.DeclaringType); var generator = dynamicMethod.GetILGenerator(); var parameters = methodInfo.GetParameters(); var paramTypes = new Type[parameters.Length]; for (int i = 0; i < paramTypes.Length; i++) { var parameterInfo = parameters[i]; if (parameterInfo.ParameterType.IsByRef) paramTypes[i] = parameterInfo.ParameterType.GetElementType(); else paramTypes[i] = parameterInfo.ParameterType; } var locals = new LocalBuilder[paramTypes.Length]; for (int i = 0; i < paramTypes.Length; i++) locals[i] = generator.DeclareLocal(paramTypes[i], true); for (int i = 0; i < paramTypes.Length; i++) { generator.Emit(OpCodes.Ldarg_1); generator.FastInt(i); generator.Emit(OpCodes.Ldelem_Ref); generator.UnboxIfNeeded(paramTypes[i]); generator.Emit(OpCodes.Stloc, locals[i]); } if (!methodInfo.IsStatic) generator.Emit(OpCodes.Ldarg_0); for (int i = 0; i < paramTypes.Length; i++) { if (parameters[i].ParameterType.IsByRef) generator.Emit(OpCodes.Ldloca_S, locals[i]); else generator.Emit(OpCodes.Ldloc, locals[i]); } if (methodInfo.IsStatic) generator.EmitCall(OpCodes.Call, methodInfo, null); else generator.EmitCall(OpCodes.Callvirt, methodInfo, null); if (methodInfo.ReturnType == typeof(void)) generator.Emit(OpCodes.Ldnull); else generator.BoxIfNeeded(methodInfo.ReturnType); for (int i = 0; i < paramTypes.Length; i++) { if (!parameters[i].ParameterType.IsByRef) continue; generator.Emit(OpCodes.Ldarg_1); generator.FastInt(i); generator.Emit(OpCodes.Ldloc, locals[i]); var localType = locals[i].LocalType; if (localType.GetTypeInfo().IsValueType) generator.Emit(OpCodes.Box, localType); generator.Emit(OpCodes.Stelem_Ref); } generator.Emit(OpCodes.Ret); return dynamicMethod.CreateDelegate(typeof(Func<object, object[], object>)) as Func<object, object[], object>; } public static Func<object> CreateConstructor(Type type) { if (type == null) throw new ArgumentNullException(nameof(type)); var dynamicMethod = CreateDynamicMethod( "Create" + type.FullName, typeof(object), Type.EmptyTypes, type); dynamicMethod.InitLocals = true; var generator = dynamicMethod.GetILGenerator(); var typeInfo = type.GetTypeInfo(); if (typeInfo.IsValueType) { generator.DeclareLocal(type); generator.Emit(OpCodes.Ldloc_0); generator.Emit(OpCodes.Box, type); } else { #if NETSTANDARD1_3 var constructorInfo = typeInfo.DeclaredConstructors.FirstOrDefault(c => c.GetParameters().Length == 0); #else var constructorInfo = typeInfo.GetConstructor(Type.EmptyTypes); #endif if (constructorInfo == null) throw new InvalidOperationException($"Could not get constructor for {type}."); generator.Emit(OpCodes.Newobj, constructorInfo); } generator.Return(); return dynamicMethod.CreateDelegate(typeof(Func<object>)) as Func<object>; } public static Func<object, object> CreateGet(PropertyInfo propertyInfo) { if (propertyInfo == null) throw new ArgumentNullException(nameof(propertyInfo)); if (!propertyInfo.CanRead) return null; var methodInfo = propertyInfo.GetGetMethod(true); if (methodInfo == null) return null; var dynamicMethod = CreateDynamicMethod( "Get" + propertyInfo.Name, typeof(object), new[] { typeof(object) }, propertyInfo.DeclaringType); var generator = dynamicMethod.GetILGenerator(); if (!methodInfo.IsStatic) generator.PushInstance(propertyInfo.DeclaringType); generator.CallMethod(methodInfo); generator.BoxIfNeeded(propertyInfo.PropertyType); generator.Return(); return dynamicMethod.CreateDelegate(typeof(Func<object, object>)) as Func<object, object>; } public static Func<object, object> CreateGet(FieldInfo fieldInfo) { if (fieldInfo == null) throw new ArgumentNullException(nameof(fieldInfo)); var dynamicMethod = CreateDynamicMethod( "Get" + fieldInfo.Name, typeof(object), new[] { typeof(object) }, fieldInfo.DeclaringType); var generator = dynamicMethod.GetILGenerator(); if (fieldInfo.IsStatic) generator.Emit(OpCodes.Ldsfld, fieldInfo); else generator.PushInstance(fieldInfo.DeclaringType); generator.Emit(OpCodes.Ldfld, fieldInfo); generator.BoxIfNeeded(fieldInfo.FieldType); generator.Return(); return dynamicMethod.CreateDelegate(typeof(Func<object, object>)) as Func<object, object>; } public static Action<object, object> CreateSet(PropertyInfo propertyInfo) { if (propertyInfo == null) throw new ArgumentNullException(nameof(propertyInfo)); if (!propertyInfo.CanWrite) return null; var methodInfo = propertyInfo.GetSetMethod(true); if (methodInfo == null) return null; var dynamicMethod = CreateDynamicMethod( "Set" + propertyInfo.Name, null, new[] { typeof(object), typeof(object) }, propertyInfo.DeclaringType); var generator = dynamicMethod.GetILGenerator(); if (!methodInfo.IsStatic) generator.PushInstance(propertyInfo.DeclaringType); generator.Emit(OpCodes.Ldarg_1); generator.UnboxIfNeeded(propertyInfo.PropertyType); generator.CallMethod(methodInfo); generator.Return(); return dynamicMethod.CreateDelegate(typeof(Action<object, object>)) as Action<object, object>; } public static Action<object, object> CreateSet(FieldInfo fieldInfo) { if (fieldInfo == null) throw new ArgumentNullException(nameof(fieldInfo)); var dynamicMethod = CreateDynamicMethod( "Set" + fieldInfo.Name, null, new[] { typeof(object), typeof(object) }, fieldInfo.DeclaringType); var generator = dynamicMethod.GetILGenerator(); if (fieldInfo.IsStatic) generator.Emit(OpCodes.Ldsfld, fieldInfo); else generator.PushInstance(fieldInfo.DeclaringType); generator.Emit(OpCodes.Ldarg_1); generator.UnboxIfNeeded(fieldInfo.FieldType); generator.Emit(OpCodes.Stfld, fieldInfo); generator.Return(); return dynamicMethod.CreateDelegate(typeof(Action<object, object>)) as Action<object, object>; } private static DynamicMethod CreateDynamicMethod(string name, Type returnType, Type[] parameterTypes, Type owner) { var typeInfo = owner.GetTypeInfo(); return !typeInfo.IsInterface ? new DynamicMethod(name, returnType, parameterTypes, owner, true) : new DynamicMethod(name, returnType, parameterTypes, typeInfo.Assembly.ManifestModule, true); } } } #endif
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for Additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ namespace TestCases.SS.UserModel { using System; using NUnit.Framework; using NPOI.SS; using NPOI.SS.Util; using NPOI.SS.UserModel; using System.Collections; using NPOI.HSSF.UserModel; /** * Common superclass for Testing {@link NPOI.xssf.UserModel.XSSFCell} and * {@link NPOI.HSSF.UserModel.HSSFCell} */ [TestFixture] public class BaseTestSheet { private static int ROW_COUNT = 40000; private ITestDataProvider _testDataProvider; public BaseTestSheet() : this(TestCases.HSSF.HSSFITestDataProvider.Instance) { } protected BaseTestSheet(ITestDataProvider TestDataProvider) { _testDataProvider = TestDataProvider; } [Test] public void TestCreateRow() { IWorkbook workbook = _testDataProvider.CreateWorkbook(); ISheet sheet = workbook.CreateSheet(); Assert.AreEqual(0, sheet.PhysicalNumberOfRows); //Test that we Get null for undefined rownumber Assert.IsNull(sheet.GetRow(1)); // Test row creation with consecutive indexes IRow row1 = sheet.CreateRow(0); IRow row2 = sheet.CreateRow(1); Assert.AreEqual(0, row1.RowNum); Assert.AreEqual(1, row2.RowNum); IEnumerator it = sheet.GetRowEnumerator(); Assert.IsTrue(it.MoveNext()); Assert.AreSame(row1, it.Current); Assert.IsTrue(it.MoveNext()); Assert.AreSame(row2, it.Current); Assert.AreEqual(1, sheet.LastRowNum); // Test row creation with non consecutive index IRow row101 = sheet.CreateRow(100); Assert.IsNotNull(row101); Assert.AreEqual(100, sheet.LastRowNum); Assert.AreEqual(3, sheet.PhysicalNumberOfRows); // Test overwriting an existing row IRow row2_ovrewritten = sheet.CreateRow(1); ICell cell = row2_ovrewritten.CreateCell(0); cell.SetCellValue(100); IEnumerator it2 = sheet.GetRowEnumerator(); Assert.IsTrue(it2.MoveNext()); Assert.AreSame(row1, it2.Current); Assert.IsTrue(it2.MoveNext()); IRow row2_ovrewritten_ref = (IRow)it2.Current; Assert.AreSame(row2_ovrewritten, row2_ovrewritten_ref); Assert.AreEqual(100.0, row2_ovrewritten_ref.GetCell(0).NumericCellValue, 0.0); } [Test] public void TestRemoveRow() { IWorkbook workbook = _testDataProvider.CreateWorkbook(); ISheet sheet1 = workbook.CreateSheet(); Assert.AreEqual(0, sheet1.PhysicalNumberOfRows); Assert.AreEqual(0, sheet1.FirstRowNum); Assert.AreEqual(0, sheet1.LastRowNum); IRow row0 = sheet1.CreateRow(0); Assert.AreEqual(1, sheet1.PhysicalNumberOfRows); Assert.AreEqual(0, sheet1.FirstRowNum); Assert.AreEqual(0, sheet1.LastRowNum); sheet1.RemoveRow(row0); Assert.AreEqual(0, sheet1.PhysicalNumberOfRows); Assert.AreEqual(0, sheet1.FirstRowNum); Assert.AreEqual(0, sheet1.LastRowNum); sheet1.CreateRow(1); IRow row2 = sheet1.CreateRow(2); Assert.AreEqual(2, sheet1.PhysicalNumberOfRows); Assert.AreEqual(1, sheet1.FirstRowNum); Assert.AreEqual(2, sheet1.LastRowNum); Assert.IsNotNull(sheet1.GetRow(1)); Assert.IsNotNull(sheet1.GetRow(2)); sheet1.RemoveRow(row2); Assert.IsNotNull(sheet1.GetRow(1)); Assert.IsNull(sheet1.GetRow(2)); Assert.AreEqual(1, sheet1.PhysicalNumberOfRows); Assert.AreEqual(1, sheet1.FirstRowNum); Assert.AreEqual(1, sheet1.LastRowNum); IRow row3 = sheet1.CreateRow(3); ISheet sheet2 = workbook.CreateSheet(); try { sheet2.RemoveRow(row3); Assert.Fail("Expected exception"); } catch (ArgumentException e) { Assert.AreEqual("Specified row does not belong to this sheet", e.Message); } } [Test] public void TestCloneSheet() { IWorkbook workbook = _testDataProvider.CreateWorkbook(); ICreationHelper factory = workbook.GetCreationHelper(); ISheet sheet = workbook.CreateSheet("Test Clone"); IRow row = sheet.CreateRow(0); ICell cell = row.CreateCell(0); ICell cell2 = row.CreateCell(1); cell.SetCellValue(factory.CreateRichTextString("Clone_test")); cell2.CellFormula = (/*setter*/"SIN(1)"); ISheet clonedSheet = workbook.CloneSheet(0); IRow clonedRow = clonedSheet.GetRow(0); //Check for a good clone Assert.AreEqual(clonedRow.GetCell(0).RichStringCellValue.String, "Clone_test"); //Check that the cells are not somehow linked cell.SetCellValue(factory.CreateRichTextString("Difference Check")); cell2.CellFormula = (/*setter*/"cos(2)"); if ("Difference Check".Equals(clonedRow.GetCell(0).RichStringCellValue.String)) { Assert.Fail("string cell not properly Cloned"); } if ("COS(2)".Equals(clonedRow.GetCell(1).CellFormula)) { Assert.Fail("formula cell not properly Cloned"); } Assert.AreEqual(clonedRow.GetCell(0).RichStringCellValue.String, "Clone_test"); Assert.AreEqual(clonedRow.GetCell(1).CellFormula, "SIN(1)"); } /** Tests that the sheet name for multiple Clones of the same sheet is unique * BUG 37416 */ [Test] public void TestCloneSheetMultipleTimes() { IWorkbook workbook = _testDataProvider.CreateWorkbook(); ICreationHelper factory = workbook.GetCreationHelper(); ISheet sheet = workbook.CreateSheet("Test Clone"); IRow row = sheet.CreateRow(0); ICell cell = row.CreateCell(0); cell.SetCellValue(factory.CreateRichTextString("Clone_test")); //Clone the sheet multiple times workbook.CloneSheet(0); workbook.CloneSheet(0); Assert.IsNotNull(workbook.GetSheet("Test Clone")); Assert.IsNotNull(workbook.GetSheet("Test Clone (2)")); Assert.AreEqual("Test Clone (3)", workbook.GetSheetName(2)); Assert.IsNotNull(workbook.GetSheet("Test Clone (3)")); workbook.RemoveSheetAt(0); workbook.RemoveSheetAt(0); workbook.RemoveSheetAt(0); workbook.CreateSheet("abc ( 123)"); workbook.CloneSheet(0); Assert.AreEqual("abc (124)", workbook.GetSheetName(1)); } /** * Setting landscape and portrait stuff on new sheets */ [Test] public void TestPrintSetupLandscapeNew() { IWorkbook workbook = _testDataProvider.CreateWorkbook(); ISheet sheetL = workbook.CreateSheet("LandscapeS"); ISheet sheetP = workbook.CreateSheet("LandscapeP"); // Check two aspects of the print Setup Assert.IsFalse(sheetL.PrintSetup.Landscape); Assert.IsFalse(sheetP.PrintSetup.Landscape); Assert.AreEqual(1, sheetL.PrintSetup.Copies); Assert.AreEqual(1, sheetP.PrintSetup.Copies); // Change one on each sheetL.PrintSetup.Landscape = (/*setter*/true); sheetP.PrintSetup.Copies = (/*setter*/(short)3); // Check taken Assert.IsTrue(sheetL.PrintSetup.Landscape); Assert.IsFalse(sheetP.PrintSetup.Landscape); Assert.AreEqual(1, sheetL.PrintSetup.Copies); Assert.AreEqual(3, sheetP.PrintSetup.Copies); // Save and re-load, and check still there workbook = _testDataProvider.WriteOutAndReadBack(workbook); sheetL = workbook.GetSheet("LandscapeS"); sheetP = workbook.GetSheet("LandscapeP"); Assert.IsTrue(sheetL.PrintSetup.Landscape); Assert.IsFalse(sheetP.PrintSetup.Landscape); Assert.AreEqual(1, sheetL.PrintSetup.Copies); Assert.AreEqual(3, sheetP.PrintSetup.Copies); } /** * Test Adding merged regions. If the region's bounds are outside of the allowed range * then an ArgumentException should be thrown * */ [Test] public void TestAddMerged() { IWorkbook wb = _testDataProvider.CreateWorkbook(); ISheet sheet = wb.CreateSheet(); Assert.AreEqual(0, sheet.NumMergedRegions); SpreadsheetVersion ssVersion = _testDataProvider.GetSpreadsheetVersion(); CellRangeAddress region = new CellRangeAddress(0, 1, 0, 1); sheet.AddMergedRegion(region); Assert.AreEqual(1, sheet.NumMergedRegions); try { region = new CellRangeAddress(-1, -1, -1, -1); sheet.AddMergedRegion(region); Assert.Fail("Expected exception"); } catch (ArgumentException) { // TODO Assert.AreEqual("Minimum row number is 0.", e.Message); } try { region = new CellRangeAddress(0, 0, 0, ssVersion.LastColumnIndex + 1); sheet.AddMergedRegion(region); Assert.Fail("Expected exception"); } catch (ArgumentException e) { Assert.AreEqual("Maximum column number is " + ssVersion.LastColumnIndex, e.Message); } try { region = new CellRangeAddress(0, ssVersion.LastRowIndex + 1, 0, 1); sheet.AddMergedRegion(region); Assert.Fail("Expected exception"); } catch (ArgumentException e) { Assert.AreEqual("Maximum row number is " + ssVersion.LastRowIndex, e.Message); } Assert.AreEqual(1, sheet.NumMergedRegions); } /** * When removing one merged region, it would break * */ [Test] public void TestRemoveMerged() { IWorkbook wb = _testDataProvider.CreateWorkbook(); ISheet sheet = wb.CreateSheet(); CellRangeAddress region = new CellRangeAddress(0, 1, 0, 1); sheet.AddMergedRegion(region); region = new CellRangeAddress(1, 2, 0, 1); sheet.AddMergedRegion(region); sheet.RemoveMergedRegion(0); region = sheet.GetMergedRegion(0); Assert.AreEqual(1, region.FirstRow, "Left over region should be starting at row 1"); sheet.RemoveMergedRegion(0); Assert.AreEqual(0, sheet.NumMergedRegions, "there should be no merged regions left!"); //an, Add, Remove, Get(0) would null pointer sheet.AddMergedRegion(region); Assert.AreEqual(1, sheet.NumMergedRegions, "there should now be one merged region!"); sheet.RemoveMergedRegion(0); Assert.AreEqual(0, sheet.NumMergedRegions, "there should now be zero merged regions!"); //add it again! region.LastRow = (/*setter*/4); sheet.AddMergedRegion(region); Assert.AreEqual(1, sheet.NumMergedRegions, "there should now be one merged region!"); //should exist now! Assert.IsTrue(1 <= sheet.NumMergedRegions, "there isn't more than one merged region in there"); region = sheet.GetMergedRegion(0); Assert.AreEqual(4, region.LastRow, "the merged row to doesnt match the one we Put in "); } [Test] public void TestShiftMerged() { IWorkbook wb = _testDataProvider.CreateWorkbook(); ICreationHelper factory = wb.GetCreationHelper(); ISheet sheet = wb.CreateSheet(); IRow row = sheet.CreateRow(0); ICell cell = row.CreateCell(0); cell.SetCellValue(factory.CreateRichTextString("first row, first cell")); row = sheet.CreateRow(1); cell = row.CreateCell(1); cell.SetCellValue(factory.CreateRichTextString("second row, second cell")); CellRangeAddress region = new CellRangeAddress(1, 1, 0, 1); sheet.AddMergedRegion(region); sheet.ShiftRows(1, 1, 1); region = sheet.GetMergedRegion(0); Assert.AreEqual(2, region.FirstRow, "Merged region not Moved over to row 2"); } /** * Tests the display of gridlines, formulas, and rowcolheadings. * @author Shawn Laubach (slaubach at apache dot org) */ [Test] public void TestDisplayOptions() { IWorkbook wb = _testDataProvider.CreateWorkbook(); ISheet sheet = wb.CreateSheet(); Assert.AreEqual(sheet.DisplayGridlines, true); Assert.AreEqual(sheet.DisplayRowColHeadings, true); Assert.AreEqual(sheet.DisplayFormulas, false); Assert.AreEqual(sheet.DisplayZeros, true); sheet.DisplayGridlines = (/*setter*/false); sheet.DisplayRowColHeadings = (/*setter*/false); sheet.DisplayFormulas = (/*setter*/true); sheet.DisplayZeros = (/*setter*/false); wb = _testDataProvider.WriteOutAndReadBack(wb); sheet = wb.GetSheetAt(0); Assert.AreEqual(sheet.DisplayGridlines, false); Assert.AreEqual(sheet.DisplayRowColHeadings, false); Assert.AreEqual(sheet.DisplayFormulas, true); Assert.AreEqual(sheet.DisplayZeros, false); } [Test] public void TestColumnWidth() { IWorkbook wb = _testDataProvider.CreateWorkbook(); ISheet sheet = wb.CreateSheet(); //default column width measured in characters sheet.DefaultColumnWidth = (/*setter*/10); Assert.AreEqual(10, sheet.DefaultColumnWidth); //columns A-C have default width Assert.AreEqual(256 * 10, sheet.GetColumnWidth(0)); Assert.AreEqual(256 * 10, sheet.GetColumnWidth(1)); Assert.AreEqual(256 * 10, sheet.GetColumnWidth(2)); //set custom width for D-F for (char i = 'D'; i <= 'F'; i++) { //Sheet#setColumnWidth accepts the width in units of 1/256th of a character width int w = 256 * 12; sheet.SetColumnWidth(/*setter*/i, w); Assert.AreEqual(w, sheet.GetColumnWidth(i)); } //reset the default column width, columns A-C Change, D-F still have custom width sheet.DefaultColumnWidth = (/*setter*/20); Assert.AreEqual(20, sheet.DefaultColumnWidth); Assert.AreEqual(256 * 20, sheet.GetColumnWidth(0)); Assert.AreEqual(256 * 20, sheet.GetColumnWidth(1)); Assert.AreEqual(256 * 20, sheet.GetColumnWidth(2)); for (char i = 'D'; i <= 'F'; i++) { int w = 256 * 12; Assert.AreEqual(w, sheet.GetColumnWidth(i)); } // check for 16-bit signed/unsigned error: sheet.SetColumnWidth(/*setter*/10, 40000); Assert.AreEqual(40000, sheet.GetColumnWidth(10)); //The maximum column width for an individual cell is 255 characters try { sheet.SetColumnWidth(/*setter*/9, 256 * 256); Assert.Fail("expected exception"); } catch (ArgumentException e) { Assert.AreEqual("The maximum column width for an individual cell is 255 characters.", e.Message); } //serialize and read again wb = _testDataProvider.WriteOutAndReadBack(wb); sheet = wb.GetSheetAt(0); Assert.AreEqual(20, sheet.DefaultColumnWidth); //columns A-C have default width Assert.AreEqual(256 * 20, sheet.GetColumnWidth(0)); Assert.AreEqual(256 * 20, sheet.GetColumnWidth(1)); Assert.AreEqual(256 * 20, sheet.GetColumnWidth(2)); //columns D-F have custom width for (char i = 'D'; i <= 'F'; i++) { short w = (256 * 12); Assert.AreEqual(w, sheet.GetColumnWidth(i)); } Assert.AreEqual(40000, sheet.GetColumnWidth(10)); } [Test] public void TestDefaultRowHeight() { IWorkbook workbook = _testDataProvider.CreateWorkbook(); ISheet sheet = workbook.CreateSheet(); sheet.DefaultRowHeightInPoints = (/*setter*/15); Assert.AreEqual((short)300, sheet.DefaultRowHeight); Assert.AreEqual(15.0F, sheet.DefaultRowHeightInPoints, 0.01F); IRow row = sheet.CreateRow(1); // new row inherits default height from the sheet Assert.AreEqual(sheet.DefaultRowHeight, row.Height); // Set a new default row height in twips and Test Getting the value in points sheet.DefaultRowHeight = (/*setter*/(short)360); Assert.AreEqual(18.0f, sheet.DefaultRowHeightInPoints, 0.01F); Assert.AreEqual((short)360, sheet.DefaultRowHeight); // Test that defaultRowHeight is a tRuncated short: E.G. 360inPoints -> 18; 361inPoints -> 18 sheet.DefaultRowHeight = (/*setter*/(short)361); Assert.AreEqual((float)361 / 20, sheet.DefaultRowHeightInPoints, 0.01F); Assert.AreEqual((short)361, sheet.DefaultRowHeight); // Set a new default row height in points and Test Getting the value in twips sheet.DefaultRowHeightInPoints = (/*setter*/17.5f); Assert.AreEqual(17.5f, sheet.DefaultRowHeightInPoints, 0.01F); Assert.AreEqual((short)(17.5f * 20), sheet.DefaultRowHeight); } /** cell with formula becomes null on cloning a sheet*/ [Test] public void Test35084() { IWorkbook wb = _testDataProvider.CreateWorkbook(); ISheet s = wb.CreateSheet("Sheet1"); IRow r = s.CreateRow(0); r.CreateCell(0).SetCellValue(1); r.CreateCell(1).CellFormula = (/*setter*/"A1*2"); ISheet s1 = wb.CloneSheet(0); r = s1.GetRow(0); Assert.AreEqual(r.GetCell(0).NumericCellValue, 1, 0, "double"); // sanity check Assert.IsNotNull(r.GetCell(1)); Assert.AreEqual(r.GetCell(1).CellFormula, "A1*2", "formula"); } /** Test that new default column styles Get applied */ [Test] public virtual void TestDefaultColumnStyle() { IWorkbook wb = _testDataProvider.CreateWorkbook(); ICellStyle style = wb.CreateCellStyle(); ISheet sheet = wb.CreateSheet(); sheet.SetDefaultColumnStyle(/*setter*/0, style); Assert.IsNotNull(sheet.GetColumnStyle(0)); Assert.AreEqual(style.Index, sheet.GetColumnStyle(0).Index); IRow row = sheet.CreateRow(0); ICell cell = row.CreateCell(0); ICellStyle style2 = cell.CellStyle; Assert.IsNotNull(style2); Assert.AreEqual(style.Index, style2.Index, "style should match"); } [Test] public void TestOutlineProperties() { IWorkbook wb = _testDataProvider.CreateWorkbook(); ISheet sheet = wb.CreateSheet(); //TODO defaults are different in HSSF and XSSF //Assert.IsTrue(sheet.RowSumsBelow); //Assert.IsTrue(sheet.RowSumsRight); sheet.RowSumsBelow = (/*setter*/false); sheet.RowSumsRight = (/*setter*/false); Assert.IsFalse(sheet.RowSumsBelow); Assert.IsFalse(sheet.RowSumsRight); sheet.RowSumsBelow = (/*setter*/true); sheet.RowSumsRight = (/*setter*/true); Assert.IsTrue(sheet.RowSumsBelow); Assert.IsTrue(sheet.RowSumsRight); wb = _testDataProvider.WriteOutAndReadBack(wb); sheet = wb.GetSheetAt(0); Assert.IsTrue(sheet.RowSumsBelow); Assert.IsTrue(sheet.RowSumsRight); } /** * Test basic display properties */ [Test] public void TestSheetProperties() { IWorkbook wb = _testDataProvider.CreateWorkbook(); ISheet sheet = wb.CreateSheet(); Assert.IsFalse(sheet.HorizontallyCenter); sheet.HorizontallyCenter = (/*setter*/true); Assert.IsTrue(sheet.HorizontallyCenter); sheet.HorizontallyCenter = (/*setter*/false); Assert.IsFalse(sheet.HorizontallyCenter); Assert.IsFalse(sheet.VerticallyCenter); sheet.VerticallyCenter = (/*setter*/true); Assert.IsTrue(sheet.VerticallyCenter); sheet.VerticallyCenter = (/*setter*/false); Assert.IsFalse(sheet.VerticallyCenter); Assert.IsFalse(sheet.IsPrintGridlines); sheet.IsPrintGridlines = (/*setter*/true); Assert.IsTrue(sheet.IsPrintGridlines); Assert.IsFalse(sheet.DisplayFormulas); sheet.DisplayFormulas = (/*setter*/true); Assert.IsTrue(sheet.DisplayFormulas); Assert.IsTrue(sheet.DisplayGridlines); sheet.DisplayGridlines = (/*setter*/false); Assert.IsFalse(sheet.DisplayGridlines); //TODO: default "guts" is different in HSSF and XSSF //Assert.IsTrue(sheet.DisplayGuts); sheet.DisplayGuts = (/*setter*/false); Assert.IsFalse(sheet.DisplayGuts); Assert.IsTrue(sheet.DisplayRowColHeadings); sheet.DisplayRowColHeadings = (/*setter*/false); Assert.IsFalse(sheet.DisplayRowColHeadings); //TODO: default "autobreaks" is different in HSSF and XSSF //Assert.IsTrue(sheet.Autobreaks); sheet.Autobreaks = (/*setter*/false); Assert.IsFalse(sheet.Autobreaks); Assert.IsFalse(sheet.ScenarioProtect); //TODO: default "fit-to-page" is different in HSSF and XSSF //Assert.IsFalse(sheet.FitToPage); sheet.FitToPage = (/*setter*/true); Assert.IsTrue(sheet.FitToPage); sheet.FitToPage = (/*setter*/false); Assert.IsFalse(sheet.FitToPage); } public void BaseTestGetSetMargin(double[] defaultMargins) { double marginLeft = defaultMargins[0]; double marginRight = defaultMargins[1]; double marginTop = defaultMargins[2]; double marginBottom = defaultMargins[3]; double marginHeader = defaultMargins[4]; double marginFooter = defaultMargins[5]; IWorkbook workbook = _testDataProvider.CreateWorkbook(); ISheet sheet = workbook.CreateSheet("Sheet 1"); Assert.AreEqual(marginLeft, sheet.GetMargin(MarginType.LeftMargin), 0.0); sheet.SetMargin(MarginType.LeftMargin, 10.0); //left margin is custom, all others are default Assert.AreEqual(10.0, sheet.GetMargin(MarginType.LeftMargin), 0.0); Assert.AreEqual(marginRight, sheet.GetMargin(MarginType.RightMargin), 0.0); Assert.AreEqual(marginTop, sheet.GetMargin(MarginType.TopMargin), 0.0); Assert.AreEqual(marginBottom, sheet.GetMargin(MarginType.BottomMargin), 0.0); sheet.SetMargin(/*setter*/MarginType.RightMargin, 11.0); Assert.AreEqual(11.0, sheet.GetMargin(MarginType.RightMargin), 0.0); sheet.SetMargin(/*setter*/MarginType.TopMargin, 12.0); Assert.AreEqual(12.0, sheet.GetMargin(MarginType.TopMargin), 0.0); sheet.SetMargin(/*setter*/MarginType.BottomMargin, 13.0); Assert.AreEqual(13.0, sheet.GetMargin(MarginType.BottomMargin), 0.0); sheet.SetMargin(MarginType.FooterMargin, 5.6); Assert.AreEqual(5.6, sheet.GetMargin(MarginType.FooterMargin), 0.0); sheet.SetMargin(MarginType.HeaderMargin, 11.5); Assert.AreEqual(11.5, sheet.GetMargin(MarginType.HeaderMargin), 0.0); // incorrect margin constant try { sheet.SetMargin((MarginType)65, 15); Assert.Fail("Expected exception"); } catch (InvalidOperationException e) { Assert.AreEqual("Unknown margin constant: 65", e.Message); } } [Test] public void TestRowBreaks() { IWorkbook workbook = _testDataProvider.CreateWorkbook(); ISheet sheet = workbook.CreateSheet(); //Sheet#getRowBreaks() returns an empty array if no row breaks are defined Assert.IsNotNull(sheet.RowBreaks); Assert.AreEqual(0, sheet.RowBreaks.Length); sheet.SetRowBreak(1); Assert.AreEqual(1, sheet.RowBreaks.Length); sheet.SetRowBreak(15); Assert.AreEqual(2, sheet.RowBreaks.Length); Assert.AreEqual(1, sheet.RowBreaks[0]); Assert.AreEqual(15, sheet.RowBreaks[1]); sheet.SetRowBreak(1); Assert.AreEqual(2, sheet.RowBreaks.Length); Assert.IsTrue(sheet.IsRowBroken(1)); Assert.IsTrue(sheet.IsRowBroken(15)); //now remove the Created breaks sheet.RemoveRowBreak(1); Assert.AreEqual(1, sheet.RowBreaks.Length); sheet.RemoveRowBreak(15); Assert.AreEqual(0, sheet.RowBreaks.Length); Assert.IsFalse(sheet.IsRowBroken(1)); Assert.IsFalse(sheet.IsRowBroken(15)); } [Test] public void TestColumnBreaks() { IWorkbook workbook = _testDataProvider.CreateWorkbook(); ISheet sheet = workbook.CreateSheet(); Assert.IsNotNull(sheet.ColumnBreaks); Assert.AreEqual(0, sheet.ColumnBreaks.Length); Assert.IsFalse(sheet.IsColumnBroken(0)); sheet.SetColumnBreak(11); Assert.IsNotNull(sheet.ColumnBreaks); Assert.AreEqual(11, sheet.ColumnBreaks[0]); sheet.SetColumnBreak(12); Assert.AreEqual(2, sheet.ColumnBreaks.Length); Assert.IsTrue(sheet.IsColumnBroken(11)); Assert.IsTrue(sheet.IsColumnBroken(12)); sheet.RemoveColumnBreak((short)11); Assert.AreEqual(1, sheet.ColumnBreaks.Length); sheet.RemoveColumnBreak((short)15); //remove non-existing Assert.AreEqual(1, sheet.ColumnBreaks.Length); sheet.RemoveColumnBreak((short)12); Assert.AreEqual(0, sheet.ColumnBreaks.Length); Assert.IsFalse(sheet.IsColumnBroken(11)); Assert.IsFalse(sheet.IsColumnBroken(12)); } [Test] public void TestGetFirstLastRowNum() { IWorkbook workbook = _testDataProvider.CreateWorkbook(); ISheet sheet = workbook.CreateSheet("Sheet 1"); sheet.CreateRow(9); sheet.CreateRow(0); sheet.CreateRow(1); Assert.AreEqual(0, sheet.FirstRowNum); Assert.AreEqual(9, sheet.LastRowNum); } [Test] public void TestGetFooter() { IWorkbook workbook = _testDataProvider.CreateWorkbook(); ISheet sheet = workbook.CreateSheet("Sheet 1"); Assert.IsNotNull(sheet.Footer); sheet.Footer.Center = (/*setter*/"test center footer"); Assert.AreEqual("test center footer", sheet.Footer.Center); } [Test] public void TestGetSetColumnHidden() { IWorkbook workbook = _testDataProvider.CreateWorkbook(); ISheet sheet = workbook.CreateSheet("Sheet 1"); sheet.SetColumnHidden(2, true); Assert.IsTrue(sheet.IsColumnHidden(2)); } [Test] public void TestProtectSheet() { IWorkbook wb = _testDataProvider.CreateWorkbook(); ISheet sheet = wb.CreateSheet(); Assert.IsFalse(sheet.Protect); sheet.ProtectSheet("Test"); Assert.IsTrue(sheet.Protect); sheet.ProtectSheet(null); Assert.IsFalse(sheet.Protect); } [Test] public void TestCreateFreezePane() { IWorkbook wb = _testDataProvider.CreateWorkbook(); // create a workbook ISheet sheet = wb.CreateSheet(); Assert.IsNull(sheet.PaneInformation); sheet.CreateFreezePane(0, 0); // still null Assert.IsNull(sheet.PaneInformation); sheet.CreateFreezePane(2, 3); PaneInformation info = sheet.PaneInformation; Assert.AreEqual(PaneInformation.PANE_LOWER_RIGHT, info.ActivePane); Assert.AreEqual(3, info.HorizontalSplitPosition); Assert.AreEqual(3, info.HorizontalSplitTopRow); Assert.AreEqual(2, info.VerticalSplitLeftColumn); Assert.AreEqual(2, info.VerticalSplitPosition); sheet.CreateFreezePane(0, 0); // If both colSplit and rowSplit are zero then the existing freeze pane is Removed Assert.IsNull(sheet.PaneInformation); sheet.CreateFreezePane(0, 3); info = sheet.PaneInformation; Assert.AreEqual(PaneInformation.PANE_LOWER_LEFT, info.ActivePane); Assert.AreEqual(3, info.HorizontalSplitPosition); Assert.AreEqual(3, info.HorizontalSplitTopRow); Assert.AreEqual(0, info.VerticalSplitLeftColumn); Assert.AreEqual(0, info.VerticalSplitPosition); sheet.CreateFreezePane(3, 0); info = sheet.PaneInformation; Assert.AreEqual(PaneInformation.PANE_UPPER_RIGHT, info.ActivePane); Assert.AreEqual(0, info.HorizontalSplitPosition); Assert.AreEqual(0, info.HorizontalSplitTopRow); Assert.AreEqual(3, info.VerticalSplitLeftColumn); Assert.AreEqual(3, info.VerticalSplitPosition); sheet.CreateFreezePane(0, 0); // If both colSplit and rowSplit are zero then the existing freeze pane is Removed Assert.IsNull(sheet.PaneInformation); } [Test] public void TestGetRepeatingRowsAndColumns() { IWorkbook wb = _testDataProvider.OpenSampleWorkbook( "RepeatingRowsCols." + _testDataProvider.StandardFileNameExtension); CheckRepeatingRowsAndColumns(wb.GetSheetAt(0), null, null); CheckRepeatingRowsAndColumns(wb.GetSheetAt(1), "1:1", null); CheckRepeatingRowsAndColumns(wb.GetSheetAt(2), null, "A:A"); CheckRepeatingRowsAndColumns(wb.GetSheetAt(3), "2:3", "A:B"); } [Test] public void TestSetRepeatingRowsAndColumnsBug47294() { IWorkbook wb = _testDataProvider.CreateWorkbook(); ISheet sheet1 = wb.CreateSheet(); sheet1.RepeatingRows = (CellRangeAddress.ValueOf("1:4")); Assert.AreEqual("1:4", sheet1.RepeatingRows.FormatAsString()); //must handle sheets with quotas, see Bugzilla #47294 ISheet sheet2 = wb.CreateSheet("My' Sheet"); sheet2.RepeatingRows = (CellRangeAddress.ValueOf("1:4")); Assert.AreEqual("1:4", sheet2.RepeatingRows.FormatAsString()); } [Test] public void TestSetRepeatingRowsAndColumns() { IWorkbook wb = _testDataProvider.CreateWorkbook(); ISheet sheet1 = wb.CreateSheet("Sheet1"); ISheet sheet2 = wb.CreateSheet("Sheet2"); ISheet sheet3 = wb.CreateSheet("Sheet3"); CheckRepeatingRowsAndColumns(sheet1, null, null); sheet1.RepeatingRows = (CellRangeAddress.ValueOf("4:5")); sheet2.RepeatingColumns = (CellRangeAddress.ValueOf("A:C")); sheet3.RepeatingRows = (CellRangeAddress.ValueOf("1:4")); sheet3.RepeatingColumns = (CellRangeAddress.ValueOf("A:A")); CheckRepeatingRowsAndColumns(sheet1, "4:5", null); CheckRepeatingRowsAndColumns(sheet2, null, "A:C"); CheckRepeatingRowsAndColumns(sheet3, "1:4", "A:A"); // write out, read back, and test refrain... wb = _testDataProvider.WriteOutAndReadBack(wb); sheet1 = wb.GetSheetAt(0); sheet2 = wb.GetSheetAt(1); sheet3 = wb.GetSheetAt(2); CheckRepeatingRowsAndColumns(sheet1, "4:5", null); CheckRepeatingRowsAndColumns(sheet2, null, "A:C"); CheckRepeatingRowsAndColumns(sheet3, "1:4", "A:A"); // check removing repeating rows and columns sheet3.RepeatingRows = (null); CheckRepeatingRowsAndColumns(sheet3, null, "A:A"); sheet3.RepeatingColumns = (null); CheckRepeatingRowsAndColumns(sheet3, null, null); } private void CheckRepeatingRowsAndColumns( ISheet s, String expectedRows, String expectedCols) { if (expectedRows == null) { Assert.IsNull(s.RepeatingRows); } else { Assert.AreEqual(expectedRows, s.RepeatingRows.FormatAsString()); } if (expectedCols == null) { Assert.IsNull(s.RepeatingColumns); } else { Assert.AreEqual(expectedCols, s.RepeatingColumns.FormatAsString()); } } [Test] public void TestBaseZoom() { IWorkbook wb = _testDataProvider.CreateWorkbook(); ISheet sheet = wb.CreateSheet(); // here we can only verify that setting some zoom values works, range-checking is different between the implementations sheet.SetZoom(3, 4); } [Test] public void TestBaseShowInPane() { IWorkbook wb = _testDataProvider.CreateWorkbook(); ISheet sheet = wb.CreateSheet(); sheet.ShowInPane(2, 3); } [Test] public void TestBug55723() { IWorkbook wb = _testDataProvider.CreateWorkbook(); ISheet sheet = wb.CreateSheet(); CellRangeAddress range = CellRangeAddress.ValueOf("A:B"); IAutoFilter filter = sheet.SetAutoFilter(range); Assert.IsNotNull(filter); // there seems to be currently no generic way to check the Setting... range = CellRangeAddress.ValueOf("B:C"); filter = sheet.SetAutoFilter(range); Assert.IsNotNull(filter); // there seems to be currently no generic way to check the Setting... } [Test] public void TestBug55723_Rows() { IWorkbook wb = _testDataProvider.CreateWorkbook(); ISheet sheet = wb.CreateSheet(); CellRangeAddress range = CellRangeAddress.ValueOf("A4:B55000"); IAutoFilter filter = sheet.SetAutoFilter(range); Assert.IsNotNull(filter); wb.Close(); } [Test] public void TestBug55723d_RowsOver65k() { IWorkbook wb = _testDataProvider.CreateWorkbook(); ISheet sheet = wb.CreateSheet(); CellRangeAddress range = CellRangeAddress.ValueOf("A4:B75000"); IAutoFilter filter = sheet.SetAutoFilter(range); Assert.IsNotNull(filter); wb.Close(); } /** * XSSFSheet autoSizeColumn() on empty RichTextString fails * @ */ [Test] public void Bug48325() { IWorkbook wb = _testDataProvider.CreateWorkbook(); ISheet sheet = wb.CreateSheet("Test"); ICreationHelper factory = wb.GetCreationHelper(); IRow row = sheet.CreateRow(0); ICell cell = row.CreateCell(0); IFont font = wb.CreateFont(); IRichTextString rts = factory.CreateRichTextString(""); rts.ApplyFont(font); cell.SetCellValue(rts); sheet.AutoSizeColumn(0); Assert.IsNotNull(_testDataProvider.WriteOutAndReadBack(wb)); wb.Close(); } [Test] public void GetCellComment() { IWorkbook workbook = _testDataProvider.CreateWorkbook(); ISheet sheet = workbook.CreateSheet(); IDrawing dg = sheet.CreateDrawingPatriarch(); IComment comment = dg.CreateCellComment(workbook.GetCreationHelper().CreateClientAnchor()); ICell cell = sheet.CreateRow(9).CreateCell(2); comment.Author = (/*setter*/"test C10 author"); cell.CellComment = (/*setter*/comment); Assert.IsNotNull(sheet.GetCellComment(9, 2)); Assert.AreEqual("test C10 author", sheet.GetCellComment(9, 2).Author); Assert.IsNotNull(_testDataProvider.WriteOutAndReadBack(workbook)); workbook.Close(); } [Test] public void newMergedRegionAt() { IWorkbook workbook = _testDataProvider.CreateWorkbook(); ISheet sheet = workbook.CreateSheet(); CellRangeAddress region = CellRangeAddress.ValueOf("B2:D4"); sheet.AddMergedRegion(region); Assert.AreEqual("B2:D4", sheet.GetMergedRegion(0).FormatAsString()); Assert.AreEqual(1, sheet.NumMergedRegions); Assert.IsNotNull(_testDataProvider.WriteOutAndReadBack(workbook)); workbook.Close(); } [Test] public void ShowInPaneManyRowsBug55248() { IWorkbook workbook = _testDataProvider.CreateWorkbook(); ISheet sheet = workbook.CreateSheet("Sheet 1"); sheet.ShowInPane(0, 0); int i; for (i = ROW_COUNT / 2; i < ROW_COUNT; i++) { sheet.CreateRow(i); sheet.ShowInPane(i, 0); // this one fails: sheet.ShowInPane((short)i, 0); } i = 0; sheet.ShowInPane(i, i); IWorkbook wb = _testDataProvider.WriteOutAndReadBack(workbook); CheckRowCount(wb); } private void CheckRowCount(IWorkbook wb) { Assert.IsNotNull(wb); ISheet sh = wb.GetSheet("Sheet 1"); Assert.IsNotNull(sh); Assert.AreEqual(ROW_COUNT - 1, sh.LastRowNum); } [Test] public void TestRightToLeft() { IWorkbook wb = _testDataProvider.CreateWorkbook(); ISheet sheet = wb.CreateSheet(); Assert.IsFalse(sheet.IsRightToLeft); sheet.IsRightToLeft = (/*setter*/true); Assert.IsTrue(sheet.IsRightToLeft); sheet.IsRightToLeft = (/*setter*/false); Assert.IsFalse(sheet.IsRightToLeft); wb.Close(); } } }
/* * Farseer Physics Engine: * Copyright (c) 2012 Ian Qvist * * Original source Box2D: * Copyright (c) 2006-2011 Erin Catto http://www.box2d.org * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. */ using System.Diagnostics; using FarseerPhysics.Common; using Microsoft.Xna.Framework; namespace FarseerPhysics.Dynamics.Joints { /// <summary> /// A motor joint is used to control the relative motion /// between two bodies. A typical usage is to control the movement /// of a dynamic body with respect to the ground. /// </summary> public class MotorJoint : Joint { // Solver shared private Vector2 _linearOffset; private float _angularOffset; private Vector2 _linearImpulse; private float _angularImpulse; private float _maxForce; private float _maxTorque; // Solver temp private int _indexA; private int _indexB; private Vector2 _rA; private Vector2 _rB; private Vector2 _localCenterA; private Vector2 _localCenterB; private Vector2 _linearError; private float _angularError; private float _invMassA; private float _invMassB; private float _invIA; private float _invIB; private Mat22 _linearMass; private float _angularMass; internal MotorJoint() { JointType = JointType.Motor; } /// <summary> /// Constructor for MotorJoint. /// </summary> /// <param name="bodyA">The first body</param> /// <param name="bodyB">The second body</param> /// <param name="useWorldCoordinates">Set to true if you are using world coordinates as anchors.</param> public MotorJoint(Body bodyA, Body bodyB, bool useWorldCoordinates = false) : base(bodyA, bodyB) { JointType = JointType.Motor; Vector2 xB = BodyB.Position; if (useWorldCoordinates) _linearOffset = BodyA.GetLocalPoint(xB); else _linearOffset = xB; //Defaults _angularOffset = 0.0f; _maxForce = 1.0f; _maxTorque = 1.0f; CorrectionFactor = 0.3f; _angularOffset = BodyB.Rotation - BodyA.Rotation; } public override Vector2 WorldAnchorA { get { return BodyA.Position; } set { Debug.Assert(false, "You can't set the world anchor on this joint type."); } } public override Vector2 WorldAnchorB { get { return BodyB.Position; } set { Debug.Assert(false, "You can't set the world anchor on this joint type."); } } /// <summary> /// The maximum amount of force that can be applied to BodyA /// </summary> public float MaxForce { set { Debug.Assert(MathUtils.IsValid(value) && value >= 0.0f); _maxForce = value; } get { return _maxForce; } } /// <summary> /// The maximum amount of torque that can be applied to BodyA /// </summary> public float MaxTorque { set { Debug.Assert(MathUtils.IsValid(value) && value >= 0.0f); _maxTorque = value; } get { return _maxTorque; } } /// <summary> /// The linear (translation) offset. /// </summary> public Vector2 LinearOffset { set { if (_linearOffset.X != value.X || _linearOffset.Y != value.Y) { WakeBodies(); _linearOffset = value; } } get { return _linearOffset; } } /// <summary> /// Get or set the angular offset. /// </summary> public float AngularOffset { set { if (_angularOffset != value) { WakeBodies(); _angularOffset = value; } } get { return _angularOffset; } } //FPE note: Used for serialization. internal float CorrectionFactor { get; set; } public override Vector2 GetReactionForce(float invDt) { return invDt * _linearImpulse; } public override float GetReactionTorque(float invDt) { return invDt * _angularImpulse; } internal override void InitVelocityConstraints(ref SolverData data) { _indexA = BodyA.IslandIndex; _indexB = BodyB.IslandIndex; _localCenterA = BodyA._sweep.LocalCenter; _localCenterB = BodyB._sweep.LocalCenter; _invMassA = BodyA._invMass; _invMassB = BodyB._invMass; _invIA = BodyA._invI; _invIB = BodyB._invI; Vector2 cA = data.positions[_indexA].c; float aA = data.positions[_indexA].a; Vector2 vA = data.velocities[_indexA].v; float wA = data.velocities[_indexA].w; Vector2 cB = data.positions[_indexB].c; float aB = data.positions[_indexB].a; Vector2 vB = data.velocities[_indexB].v; float wB = data.velocities[_indexB].w; Rot qA = new Rot(aA); Rot qB = new Rot(aB); // Compute the effective mass matrix. _rA = MathUtils.Mul(qA, -_localCenterA); _rB = MathUtils.Mul(qB, -_localCenterB); // J = [-I -r1_skew I r2_skew] // [ 0 -1 0 1] // r_skew = [-ry; rx] // Matlab // K = [ mA+r1y^2*iA+mB+r2y^2*iB, -r1y*iA*r1x-r2y*iB*r2x, -r1y*iA-r2y*iB] // [ -r1y*iA*r1x-r2y*iB*r2x, mA+r1x^2*iA+mB+r2x^2*iB, r1x*iA+r2x*iB] // [ -r1y*iA-r2y*iB, r1x*iA+r2x*iB, iA+iB] float mA = _invMassA, mB = _invMassB; float iA = _invIA, iB = _invIB; Mat22 K = new Mat22(); K.ex.X = mA + mB + iA * _rA.Y * _rA.Y + iB * _rB.Y * _rB.Y; K.ex.Y = -iA * _rA.X * _rA.Y - iB * _rB.X * _rB.Y; K.ey.X = K.ex.Y; K.ey.Y = mA + mB + iA * _rA.X * _rA.X + iB * _rB.X * _rB.X; _linearMass = K.Inverse; _angularMass = iA + iB; if (_angularMass > 0.0f) { _angularMass = 1.0f / _angularMass; } _linearError = cB + _rB - cA - _rA - MathUtils.Mul(qA, _linearOffset); _angularError = aB - aA - _angularOffset; if (Settings.EnableWarmstarting) { // Scale impulses to support a variable time step. _linearImpulse *= data.step.dtRatio; _angularImpulse *= data.step.dtRatio; Vector2 P = new Vector2(_linearImpulse.X, _linearImpulse.Y); vA -= mA * P; wA -= iA * (MathUtils.Cross(_rA, P) + _angularImpulse); vB += mB * P; wB += iB * (MathUtils.Cross(_rB, P) + _angularImpulse); } else { _linearImpulse = Vector2.Zero; _angularImpulse = 0.0f; } data.velocities[_indexA].v = vA; data.velocities[_indexA].w = wA; data.velocities[_indexB].v = vB; data.velocities[_indexB].w = wB; } internal override void SolveVelocityConstraints(ref SolverData data) { Vector2 vA = data.velocities[_indexA].v; float wA = data.velocities[_indexA].w; Vector2 vB = data.velocities[_indexB].v; float wB = data.velocities[_indexB].w; float mA = _invMassA, mB = _invMassB; float iA = _invIA, iB = _invIB; float h = data.step.dt; float inv_h = data.step.inv_dt; // Solve angular friction { float Cdot = wB - wA + inv_h * CorrectionFactor * _angularError; float impulse = -_angularMass * Cdot; float oldImpulse = _angularImpulse; float maxImpulse = h * _maxTorque; _angularImpulse = MathUtils.Clamp(_angularImpulse + impulse, -maxImpulse, maxImpulse); impulse = _angularImpulse - oldImpulse; wA -= iA * impulse; wB += iB * impulse; } // Solve linear friction { Vector2 Cdot = vB + MathUtils.Cross(wB, _rB) - vA - MathUtils.Cross(wA, _rA) + inv_h * CorrectionFactor * _linearError; Vector2 impulse = -MathUtils.Mul(ref _linearMass, ref Cdot); Vector2 oldImpulse = _linearImpulse; _linearImpulse += impulse; float maxImpulse = h * _maxForce; if (_linearImpulse.LengthSquared() > maxImpulse * maxImpulse) { _linearImpulse.Normalize(); _linearImpulse *= maxImpulse; } impulse = _linearImpulse - oldImpulse; vA -= mA * impulse; wA -= iA * MathUtils.Cross(_rA, impulse); vB += mB * impulse; wB += iB * MathUtils.Cross(_rB, impulse); } data.velocities[_indexA].v = vA; data.velocities[_indexA].w = wA; data.velocities[_indexB].v = vB; data.velocities[_indexB].w = wB; } internal override bool SolvePositionConstraints(ref SolverData data) { return true; } } }
// Copyright 2007-2010 Portland State University, University of Wisconsin-Madison // Author: Robert Scheller, Ben Sulman //using Landis.Cohorts; using Landis.Core; using Landis.SpatialModeling; using Edu.Wisc.Forest.Flel.Util; using System.IO; using System; using Landis.Library.Metadata; using System.Data; using System.Collections.Generic; using System.Collections; namespace Landis.Extension.Succession.NetEcosystemCN { public class Outputs { public static StreamWriter CalibrateLog; public static MetadataTable<MonthlyLog> monthlyLog; public static MetadataTable<PrimaryLog> primaryLog; public static MetadataTable<PrimaryLogShort> primaryLogShort; //--------------------------------------------------------------------- public static void WriteShortPrimaryLogFile(int CurrentTime) { double avgNEEc = 0.0; double avgSOMtc = 0.0; double avgAGB = 0.0; double avgAGNPPtc = 0.0; double avgMineralN = 0.0; double avgDeadWoodC = 0.0; foreach (ActiveSite site in PlugIn.ModelCore.Landscape) { avgNEEc += SiteVars.AnnualNEE[site] / PlugIn.ModelCore.Landscape.ActiveSiteCount; avgSOMtc += GetOrganicCarbon(site) / PlugIn.ModelCore.Landscape.ActiveSiteCount; avgAGB += Main.ComputeLivingBiomass(SiteVars.Cohorts[site]) / PlugIn.ModelCore.Landscape.ActiveSiteCount; avgAGNPPtc += SiteVars.AGNPPcarbon[site] / PlugIn.ModelCore.Landscape.ActiveSiteCount; avgMineralN += SiteVars.MineralN[site] / PlugIn.ModelCore.Landscape.ActiveSiteCount; avgDeadWoodC += SiteVars.SurfaceDeadWood[site].Carbon / PlugIn.ModelCore.Landscape.ActiveSiteCount; } primaryLogShort.Clear(); PrimaryLogShort pl = new PrimaryLogShort(); pl.Time = CurrentTime; pl.NEEC = avgNEEc; pl.SOMTC = avgSOMtc; pl.AGB = avgAGB; pl.AG_NPPC = avgAGNPPtc; pl.MineralN = avgMineralN; pl.C_DeadWood = avgDeadWoodC; primaryLogShort.AddObject(pl); primaryLogShort.WriteToFile(); } //--------------------------------------------------------------------- public static void WritePrimaryLogFile(int CurrentTime) { double[] avgAnnualPPT = new double[PlugIn.ModelCore.Ecoregions.Count]; double[] avgJJAtemp = new double[PlugIn.ModelCore.Ecoregions.Count]; double[] avgNEEc = new double[PlugIn.ModelCore.Ecoregions.Count]; double[] avgSOMtc = new double[PlugIn.ModelCore.Ecoregions.Count]; double[] avgAGB = new double[PlugIn.ModelCore.Ecoregions.Count]; double[] avgAGNPPtc = new double[PlugIn.ModelCore.Ecoregions.Count]; double[] avgBGNPPtc = new double[PlugIn.ModelCore.Ecoregions.Count]; double[] avgLittertc = new double[PlugIn.ModelCore.Ecoregions.Count]; double[] avgWoodMortality = new double[PlugIn.ModelCore.Ecoregions.Count]; double[] avgMineralN = new double[PlugIn.ModelCore.Ecoregions.Count]; double[] avgGrossMin = new double[PlugIn.ModelCore.Ecoregions.Count]; double[] avgTotalN = new double[PlugIn.ModelCore.Ecoregions.Count]; double[] avgCohortLeafC = new double[PlugIn.ModelCore.Ecoregions.Count]; double[] avgCohortFRootC = new double[PlugIn.ModelCore.Ecoregions.Count]; double[] avgCohortWoodC = new double[PlugIn.ModelCore.Ecoregions.Count]; double[] avgWoodC = new double[PlugIn.ModelCore.Ecoregions.Count]; double[] avgCohortCRootC = new double[PlugIn.ModelCore.Ecoregions.Count]; double[] avgCRootC = new double[PlugIn.ModelCore.Ecoregions.Count]; double[] avgCohortLeafN = new double[PlugIn.ModelCore.Ecoregions.Count]; double[] avgCohortFRootN = new double[PlugIn.ModelCore.Ecoregions.Count]; double[] avgCohortWoodN = new double[PlugIn.ModelCore.Ecoregions.Count]; double[] avgCohortCRootN = new double[PlugIn.ModelCore.Ecoregions.Count]; double[] avgWoodN = new double[PlugIn.ModelCore.Ecoregions.Count]; double[] avgCRootN = new double[PlugIn.ModelCore.Ecoregions.Count]; double[] avgSurfStrucC = new double[PlugIn.ModelCore.Ecoregions.Count]; double[] avgSurfMetaC = new double[PlugIn.ModelCore.Ecoregions.Count]; double[] avgSoilStrucC = new double[PlugIn.ModelCore.Ecoregions.Count]; double[] avgSoilMetaC = new double[PlugIn.ModelCore.Ecoregions.Count]; double[] avgSurfStrucN = new double[PlugIn.ModelCore.Ecoregions.Count]; double[] avgSurfMetaN = new double[PlugIn.ModelCore.Ecoregions.Count]; double[] avgSoilStrucN = new double[PlugIn.ModelCore.Ecoregions.Count]; double[] avgSoilMetaN = new double[PlugIn.ModelCore.Ecoregions.Count]; double[] avgSurfStrucNetMin = new double[PlugIn.ModelCore.Ecoregions.Count]; double[] avgSurfMetaNetMin = new double[PlugIn.ModelCore.Ecoregions.Count]; double[] avgSoilStrucNetMin = new double[PlugIn.ModelCore.Ecoregions.Count]; double[] avgSoilMetaNetMin = new double[PlugIn.ModelCore.Ecoregions.Count]; double[] avgSOM1surfC = new double[PlugIn.ModelCore.Ecoregions.Count]; double[] avgSOM1soilC = new double[PlugIn.ModelCore.Ecoregions.Count]; double[] avgSOM2C = new double[PlugIn.ModelCore.Ecoregions.Count]; double[] avgSOM3C = new double[PlugIn.ModelCore.Ecoregions.Count]; double[] avgSOM1surfN = new double[PlugIn.ModelCore.Ecoregions.Count]; double[] avgSOM1soilN = new double[PlugIn.ModelCore.Ecoregions.Count]; double[] avgSOM2N = new double[PlugIn.ModelCore.Ecoregions.Count]; double[] avgSOM3N = new double[PlugIn.ModelCore.Ecoregions.Count]; double[] avgSOM1surfNetMin = new double[PlugIn.ModelCore.Ecoregions.Count]; double[] avgSOM1soilNetMin = new double[PlugIn.ModelCore.Ecoregions.Count]; double[] avgSOM2NetMin = new double[PlugIn.ModelCore.Ecoregions.Count]; double[] avgSOM3NetMin = new double[PlugIn.ModelCore.Ecoregions.Count]; double[] avgStreamC = new double[PlugIn.ModelCore.Ecoregions.Count]; double[] avgStreamN = new double[PlugIn.ModelCore.Ecoregions.Count]; double[] avgFireCEfflux = new double[PlugIn.ModelCore.Ecoregions.Count]; double[] avgFireNEfflux = new double[PlugIn.ModelCore.Ecoregions.Count]; double[] avgNvol = new double[PlugIn.ModelCore.Ecoregions.Count]; double[] avgNresorbed = new double[PlugIn.ModelCore.Ecoregions.Count]; double[] avgTotalSoilN = new double[PlugIn.ModelCore.Ecoregions.Count]; double[] avgNuptake = new double[PlugIn.ModelCore.Ecoregions.Count]; double[] avgfrassC = new double[PlugIn.ModelCore.Ecoregions.Count]; double[] avglai = new double[PlugIn.ModelCore.Ecoregions.Count]; foreach (IEcoregion ecoregion in PlugIn.ModelCore.Ecoregions) { avgAnnualPPT[ecoregion.Index] = 0.0; avgJJAtemp[ecoregion.Index] = 0.0; avgNEEc[ecoregion.Index] = 0.0; avgSOMtc[ecoregion.Index] = 0.0; avgAGB[ecoregion.Index] = 0.0; avgAGNPPtc[ecoregion.Index] = 0.0; avgBGNPPtc[ecoregion.Index] = 0.0; avgLittertc[ecoregion.Index] = 0.0; avgWoodMortality[ecoregion.Index] = 0.0; avgMineralN[ecoregion.Index] = 0.0; avgGrossMin[ecoregion.Index] = 0.0; avgTotalN[ecoregion.Index] = 0.0; avgCohortLeafC[ecoregion.Index] = 0.0; avgCohortFRootC[ecoregion.Index] = 0.0; avgCohortWoodC[ecoregion.Index] = 0.0; avgCohortCRootC[ecoregion.Index] = 0.0; avgWoodC[ecoregion.Index] = 0.0; avgCRootC[ecoregion.Index] = 0.0; avgSurfStrucC[ecoregion.Index] = 0.0; avgSurfMetaC[ecoregion.Index] = 0.0; avgSoilStrucC[ecoregion.Index] = 0.0; avgSoilMetaC[ecoregion.Index] = 0.0; avgCohortLeafN[ecoregion.Index] = 0.0; avgCohortFRootN[ecoregion.Index] = 0.0; avgCohortWoodN[ecoregion.Index] = 0.0; avgCohortCRootN[ecoregion.Index] = 0.0; avgWoodN[ecoregion.Index] = 0.0; avgCRootN[ecoregion.Index] = 0.0; avgSurfStrucN[ecoregion.Index] = 0.0; avgSurfMetaN[ecoregion.Index] = 0.0; avgSoilStrucN[ecoregion.Index] = 0.0; avgSoilMetaN[ecoregion.Index] = 0.0; avgSurfStrucNetMin[ecoregion.Index] = 0.0; avgSurfMetaNetMin[ecoregion.Index] = 0.0; avgSoilStrucNetMin[ecoregion.Index] = 0.0; avgSoilMetaNetMin[ecoregion.Index] = 0.0; avgSOM1surfC[ecoregion.Index] = 0.0; avgSOM1soilC[ecoregion.Index] = 0.0; avgSOM2C[ecoregion.Index] = 0.0; avgSOM3C[ecoregion.Index] = 0.0; avgSOM1surfN[ecoregion.Index] = 0.0; avgSOM1soilN[ecoregion.Index] = 0.0; avgSOM2N[ecoregion.Index] = 0.0; avgSOM3N[ecoregion.Index] = 0.0; avgSOM1surfNetMin[ecoregion.Index] = 0.0; avgSOM1soilNetMin[ecoregion.Index] = 0.0; avgSOM2NetMin[ecoregion.Index] = 0.0; avgSOM3NetMin[ecoregion.Index] = 0.0; //avgNDeposition[ecoregion.Index] = 0.0; avgStreamC[ecoregion.Index] = 0.0; avgStreamN[ecoregion.Index] = 0.0; avgFireCEfflux[ecoregion.Index] = 0.0; avgFireNEfflux[ecoregion.Index] = 0.0; avgNuptake[ecoregion.Index] = 0.0; avgNresorbed[ecoregion.Index] = 0.0; avgTotalSoilN[ecoregion.Index] = 0.0; avgNvol[ecoregion.Index] = 0.0; avgfrassC[ecoregion.Index] = 0.0; } foreach (ActiveSite site in PlugIn.ModelCore.Landscape) { IEcoregion ecoregion = PlugIn.ModelCore.Ecoregion[site]; avgNEEc[ecoregion.Index] += SiteVars.AnnualNEE[site]; avgSOMtc[ecoregion.Index] += GetOrganicCarbon(site); avgAGB[ecoregion.Index] += Main.ComputeLivingBiomass(SiteVars.Cohorts[site]); avgAGNPPtc[ecoregion.Index] += SiteVars.AGNPPcarbon[site]; avgBGNPPtc[ecoregion.Index] += SiteVars.BGNPPcarbon[site]; avgLittertc[ecoregion.Index] += SiteVars.LitterfallC[site]; avgWoodMortality[ecoregion.Index] += SiteVars.WoodMortality[site] * 0.47; avgMineralN[ecoregion.Index] += SiteVars.MineralN[site]; avgTotalN[ecoregion.Index] += GetTotalNitrogen(site); avgGrossMin[ecoregion.Index] += SiteVars.GrossMineralization[site]; avgCohortLeafC[ecoregion.Index] += SiteVars.CohortLeafC[site]; avgCohortFRootC[ecoregion.Index] += SiteVars.CohortFRootC[site]; avgCohortWoodC[ecoregion.Index] += SiteVars.CohortWoodC[site]; avgCohortCRootC[ecoregion.Index] += SiteVars.CohortCRootC[site]; avgWoodC[ecoregion.Index] += SiteVars.SurfaceDeadWood[site].Carbon; avgCRootC[ecoregion.Index] += SiteVars.SoilDeadWood[site].Carbon; avgSurfStrucC[ecoregion.Index] += SiteVars.SurfaceStructural[site].Carbon; avgSurfMetaC[ecoregion.Index] += SiteVars.SurfaceMetabolic[site].Carbon; avgSoilStrucC[ecoregion.Index] += SiteVars.SoilStructural[site].Carbon; avgSoilMetaC[ecoregion.Index] += SiteVars.SoilMetabolic[site].Carbon; avgSOM1surfC[ecoregion.Index] += SiteVars.SOM1surface[site].Carbon; avgSOM1soilC[ecoregion.Index] += SiteVars.SOM1soil[site].Carbon; avgSOM2C[ecoregion.Index] += SiteVars.SOM2[site].Carbon; avgSOM3C[ecoregion.Index] += SiteVars.SOM3[site].Carbon; avgCohortLeafN[ecoregion.Index] += SiteVars.CohortLeafN[site]; avgCohortFRootN[ecoregion.Index] += SiteVars.CohortFRootN[site]; avgCohortWoodN[ecoregion.Index] += SiteVars.CohortWoodN[site]; avgCohortCRootN[ecoregion.Index] += SiteVars.CohortCRootN[site]; avgWoodN[ecoregion.Index] += SiteVars.SurfaceDeadWood[site].Nitrogen; avgCRootN[ecoregion.Index] += SiteVars.SoilDeadWood[site].Nitrogen; avgSurfStrucN[ecoregion.Index] += SiteVars.SurfaceStructural[site].Nitrogen; avgSurfMetaN[ecoregion.Index] += SiteVars.SurfaceMetabolic[site].Nitrogen; avgSoilStrucN[ecoregion.Index] += SiteVars.SoilStructural[site].Nitrogen; avgSoilMetaN[ecoregion.Index] += SiteVars.SoilMetabolic[site].Nitrogen; avgSOM1surfN[ecoregion.Index] += SiteVars.SOM1surface[site].Nitrogen; avgSOM1soilN[ecoregion.Index] += SiteVars.SOM1soil[site].Nitrogen; avgSOM2N[ecoregion.Index] += SiteVars.SOM2[site].Nitrogen; avgSOM3N[ecoregion.Index] += SiteVars.SOM3[site].Nitrogen; avgTotalSoilN[ecoregion.Index] += GetTotalSoilNitrogen(site); avgSurfStrucNetMin[ecoregion.Index] += SiteVars.SurfaceStructural[site].NetMineralization; avgSurfMetaNetMin[ecoregion.Index] += SiteVars.SurfaceMetabolic[site].NetMineralization; avgSoilStrucNetMin[ecoregion.Index] += SiteVars.SoilStructural[site].NetMineralization; avgSoilMetaNetMin[ecoregion.Index] += SiteVars.SoilMetabolic[site].NetMineralization; avgSOM1surfNetMin[ecoregion.Index] += SiteVars.SOM1surface[site].NetMineralization; avgSOM1soilNetMin[ecoregion.Index] += SiteVars.SOM1soil[site].NetMineralization; avgSOM2NetMin[ecoregion.Index] += SiteVars.SOM2[site].NetMineralization; avgSOM3NetMin[ecoregion.Index] += SiteVars.SOM3[site].NetMineralization; //avgNDeposition[ecoregion.Index] = EcoregionData.AnnualNDeposition[ecoregion]; avgStreamC[ecoregion.Index] += SiteVars.Stream[site].Carbon; avgStreamN[ecoregion.Index] += SiteVars.Stream[site].Nitrogen; avgFireCEfflux[ecoregion.Index] += SiteVars.FireCEfflux[site]; avgFireNEfflux[ecoregion.Index] += SiteVars.FireNEfflux[site]; avgNresorbed[ecoregion.Index] += SiteVars.ResorbedN[site]; avgNuptake[ecoregion.Index] += GetSoilNuptake(site); avgNvol[ecoregion.Index] += SiteVars.Nvol[site]; avgfrassC[ecoregion.Index] += SiteVars.FrassC[site]; } foreach (IEcoregion ecoregion in PlugIn.ModelCore.Ecoregions) { if (!ecoregion.Active) continue; primaryLog.Clear(); PrimaryLog pl = new PrimaryLog(); pl.Time = CurrentTime; pl.EcoregionName = ecoregion.Name; pl.EcoregionIndex = ecoregion.Index; pl.NumSites = EcoregionData.ActiveSiteCount[ecoregion]; pl.NEEC = (avgNEEc[ecoregion.Index] / (double) EcoregionData.ActiveSiteCount[ecoregion]); pl.SOMTC = (avgSOMtc[ecoregion.Index] / (double) EcoregionData.ActiveSiteCount[ecoregion]); pl.AGB = (avgAGB[ecoregion.Index] / (double) EcoregionData.ActiveSiteCount[ecoregion]); pl.AG_NPPC = (avgAGNPPtc[ecoregion.Index] / (double)EcoregionData.ActiveSiteCount[ecoregion]); pl.BG_NPPC = (avgBGNPPtc[ecoregion.Index] / (double)EcoregionData.ActiveSiteCount[ecoregion]); pl.Litterfall = (avgLittertc[ecoregion.Index] / (double)EcoregionData.ActiveSiteCount[ecoregion]); pl.AgeMortality = (avgWoodMortality[ecoregion.Index] / (double)EcoregionData.ActiveSiteCount[ecoregion]); pl.MineralN = (avgMineralN[ecoregion.Index] / (double) EcoregionData.ActiveSiteCount[ecoregion]); pl.TotalN = (avgTotalN[ecoregion.Index] / (double) EcoregionData.ActiveSiteCount[ecoregion]); pl.GrossMineralization = (avgGrossMin[ecoregion.Index] / (double)EcoregionData.ActiveSiteCount[ecoregion]); pl.TotalNdep = (EcoregionData.AnnualNDeposition[ecoregion] / (double) EcoregionData.ActiveSiteCount[ecoregion]); pl.C_Leaf = (avgCohortLeafC[ecoregion.Index] / (double) EcoregionData.ActiveSiteCount[ecoregion]); pl.C_FRoot = (avgCohortFRootC[ecoregion.Index] / (double)EcoregionData.ActiveSiteCount[ecoregion]); pl.C_Wood = (avgCohortWoodC[ecoregion.Index] / (double) EcoregionData.ActiveSiteCount[ecoregion]); pl.C_CRoot = (avgCohortCRootC[ecoregion.Index] / (double)EcoregionData.ActiveSiteCount[ecoregion]); pl.C_DeadWood = (avgWoodC[ecoregion.Index] / (double) EcoregionData.ActiveSiteCount[ecoregion]); pl.C_DeadCRoot = (avgCRootC[ecoregion.Index] / (double)EcoregionData.ActiveSiteCount[ecoregion]); pl.C_DeadLeaf_Struc = (avgSurfStrucC[ecoregion.Index] / (double) EcoregionData.ActiveSiteCount[ecoregion]); pl.C_DeadLeaf_Meta = (avgSurfMetaC[ecoregion.Index] / (double) EcoregionData.ActiveSiteCount[ecoregion]); pl.C_DeadFRoot_Struc = (avgSoilStrucC[ecoregion.Index] / (double) EcoregionData.ActiveSiteCount[ecoregion]); pl.C_DeadFRoot_Meta = (avgSoilMetaC[ecoregion.Index] / (double) EcoregionData.ActiveSiteCount[ecoregion]); pl.C_SOM1surf = (avgSOM1surfC[ecoregion.Index] / (double) EcoregionData.ActiveSiteCount[ecoregion]); pl.C_SOM1soil = (avgSOM1soilC[ecoregion.Index] / (double) EcoregionData.ActiveSiteCount[ecoregion]); pl.C_SOM2 = (avgSOM2C[ecoregion.Index] / (double) EcoregionData.ActiveSiteCount[ecoregion]); pl.C_SOM3 = (avgSOM3C[ecoregion.Index] / (double) EcoregionData.ActiveSiteCount[ecoregion]); pl.N_Leaf = (avgCohortLeafN[ecoregion.Index] / (double) EcoregionData.ActiveSiteCount[ecoregion]); pl.N_FRoot = (avgCohortFRootN[ecoregion.Index] / (double)EcoregionData.ActiveSiteCount[ecoregion]); pl.N_Wood = (avgCohortWoodN[ecoregion.Index] / (double) EcoregionData.ActiveSiteCount[ecoregion]); pl.N_CRoot = (avgCohortCRootN[ecoregion.Index] / (double)EcoregionData.ActiveSiteCount[ecoregion]); pl.N_DeadWood = (avgWoodN[ecoregion.Index] / (double) EcoregionData.ActiveSiteCount[ecoregion]); pl.N_DeadCRoot = (avgCRootN[ecoregion.Index] / (double) EcoregionData.ActiveSiteCount[ecoregion]); pl.N_DeadLeaf_Struc = (avgSurfStrucN[ecoregion.Index] / (double) EcoregionData.ActiveSiteCount[ecoregion]); pl.N_DeadLeaf_Meta = (avgSurfMetaN[ecoregion.Index] / (double)EcoregionData.ActiveSiteCount[ecoregion]); pl.N_DeadFRoot_Struc = (avgSoilStrucN[ecoregion.Index] / (double)EcoregionData.ActiveSiteCount[ecoregion]); pl.N_DeadFRoot_Meta = (avgSoilMetaN[ecoregion.Index] / (double)EcoregionData.ActiveSiteCount[ecoregion]); pl.N_SOM1surf = (avgSOM1surfN[ecoregion.Index] / (double) EcoregionData.ActiveSiteCount[ecoregion]); pl.N_SOM1soil = (avgSOM1soilN[ecoregion.Index] / (double) EcoregionData.ActiveSiteCount[ecoregion]); pl.N_SOM2 = (avgSOM2N[ecoregion.Index] / (double) EcoregionData.ActiveSiteCount[ecoregion]); pl.N_SOM3 = (avgSOM3N[ecoregion.Index] / (double) EcoregionData.ActiveSiteCount[ecoregion]); pl.SurfStrucNetMin = (avgSurfStrucNetMin[ecoregion.Index] / (double) EcoregionData.ActiveSiteCount[ecoregion]); pl.SurfMetaNetMin = (avgSurfMetaNetMin[ecoregion.Index] / (double) EcoregionData.ActiveSiteCount[ecoregion]); pl.SoilStrucNetMin = (avgSoilStrucNetMin[ecoregion.Index] / (double) EcoregionData.ActiveSiteCount[ecoregion]); pl.SoilMetaNetMin = (avgSoilMetaNetMin[ecoregion.Index] / (double) EcoregionData.ActiveSiteCount[ecoregion]); pl.SOM1surfNetMin = (avgSOM1surfNetMin[ecoregion.Index] / (double) EcoregionData.ActiveSiteCount[ecoregion]); pl.SOM1soilNetMin = (avgSOM1soilNetMin[ecoregion.Index] / (double) EcoregionData.ActiveSiteCount[ecoregion]); pl.SOM2NetMin = (avgSOM2NetMin[ecoregion.Index] / (double) EcoregionData.ActiveSiteCount[ecoregion]); pl.SOM3NetMin = (avgSOM3NetMin[ecoregion.Index] / (double) EcoregionData.ActiveSiteCount[ecoregion]); pl.StreamC = (avgStreamC[ecoregion.Index] / (double) EcoregionData.ActiveSiteCount[ecoregion]); pl.StreamN = (avgStreamN[ecoregion.Index] / (double) EcoregionData.ActiveSiteCount[ecoregion]); pl.FireCEfflux = (avgFireCEfflux[ecoregion.Index] / (double) EcoregionData.ActiveSiteCount[ecoregion]); pl.FireNEfflux = (avgFireNEfflux[ecoregion.Index] / (double)EcoregionData.ActiveSiteCount[ecoregion]); pl.Nuptake = (avgNuptake[ecoregion.Index] / (double)EcoregionData.ActiveSiteCount[ecoregion]); pl.Nresorbed = (avgNresorbed[ecoregion.Index] / (double)EcoregionData.ActiveSiteCount[ecoregion]); pl.TotalSoilN = (avgTotalSoilN[ecoregion.Index] / (double)EcoregionData.ActiveSiteCount[ecoregion]); pl.Nvol = (avgNvol[ecoregion.Index] / (double)EcoregionData.ActiveSiteCount[ecoregion]); pl.FrassC = (avgfrassC[ecoregion.Index] / (double)EcoregionData.ActiveSiteCount[ecoregion]); primaryLog.AddObject(pl); primaryLog.WriteToFile(); } //Reset back to zero: //These are being reset here because fire effects are handled in the first year of the //growth loop but the reporting doesn't happen until after all growth is finished. SiteVars.FireCEfflux.ActiveSiteValues = 0.0; SiteVars.FireNEfflux.ActiveSiteValues = 0.0; } public static void WriteMonthlyLogFile(int month) { double[] ppt = new double[PlugIn.ModelCore.Ecoregions.Count]; double[] airtemp = new double[PlugIn.ModelCore.Ecoregions.Count]; double[] avgNPPtc = new double[PlugIn.ModelCore.Ecoregions.Count]; double[] avgResp = new double[PlugIn.ModelCore.Ecoregions.Count]; double[] avgNEE = new double[PlugIn.ModelCore.Ecoregions.Count]; double[] Ndep = new double[PlugIn.ModelCore.Ecoregions.Count]; double[] StreamN = new double[PlugIn.ModelCore.Ecoregions.Count]; foreach (IEcoregion ecoregion in PlugIn.ModelCore.Ecoregions) { ppt[ecoregion.Index] = 0.0; airtemp[ecoregion.Index] = 0.0; avgNPPtc[ecoregion.Index] = 0.0; avgResp[ecoregion.Index] = 0.0; avgNEE[ecoregion.Index] = 0.0; Ndep[ecoregion.Index] = 0.0; StreamN[ecoregion.Index] = 0.0; } foreach (ActiveSite site in PlugIn.ModelCore.Landscape) { IEcoregion ecoregion = PlugIn.ModelCore.Ecoregion[site]; ppt[ecoregion.Index] = EcoregionData.AnnualWeather[ecoregion].MonthlyPrecip[month]; airtemp[ecoregion.Index] = EcoregionData.AnnualWeather[ecoregion].MonthlyTemp[month]; avgNPPtc[ecoregion.Index] += SiteVars.MonthlyAGNPPcarbon[site][month] + SiteVars.MonthlyBGNPPcarbon[site][month]; avgResp[ecoregion.Index] += SiteVars.MonthlyResp[site][month]; avgNEE[ecoregion.Index] += SiteVars.MonthlyNEE[site][month]; SiteVars.AnnualNEE[site] += SiteVars.MonthlyNEE[site][month]; Ndep[ecoregion.Index] = EcoregionData.MonthlyNDeposition[ecoregion][month]; StreamN[ecoregion.Index] += SiteVars.MonthlyStreamN[site][month]; } foreach (IEcoregion ecoregion in PlugIn.ModelCore.Ecoregions) { if (EcoregionData.ActiveSiteCount[ecoregion] > 0) { monthlyLog.Clear(); MonthlyLog ml = new MonthlyLog(); ml.Time = PlugIn.ModelCore.CurrentTime; ml.Month = month + 1; ml.EcoregionName = ecoregion.Name; ml.EcoregionIndex = ecoregion.Index; ml.NumSites = Convert.ToInt32(EcoregionData.ActiveSiteCount[ecoregion]); ml.ppt = EcoregionData.AnnualWeather[ecoregion].MonthlyPrecip[month]; ml.airtemp = EcoregionData.AnnualWeather[ecoregion].MonthlyTemp[month]; ml.avgNPPtc = (avgNPPtc[ecoregion.Index] / (double)EcoregionData.ActiveSiteCount[ecoregion]); ml.avgResp = (avgResp[ecoregion.Index] / (double)EcoregionData.ActiveSiteCount[ecoregion]); ml.avgNEE = (avgNEE[ecoregion.Index] / (double)EcoregionData.ActiveSiteCount[ecoregion]); ml.Ndep = Ndep[ecoregion.Index]; ml.StreamN = (StreamN[ecoregion.Index] / (double)EcoregionData.ActiveSiteCount[ecoregion]); monthlyLog.AddObject(ml); monthlyLog.WriteToFile(); } } } //Write log file for growth and limits public static void CreateCalibrateLogFile() { string logFileName = "NECN-calibrate-log.csv"; PlugIn.ModelCore.UI.WriteLine(" Opening NECN calibrate log file \"{0}\" ...", logFileName); try { CalibrateLog = new StreamWriter(logFileName); } catch (Exception err) { string mesg = string.Format("{0}", err.Message); throw new System.ApplicationException(mesg); } CalibrateLog.AutoFlush = true; CalibrateLog.Write("Year, Month, EcoregionIndex, SpeciesName, CohortAge, CohortWoodB, CohortLeafB, "); // from ComputeChange CalibrateLog.Write("MortalityAGEwood, MortalityAGEleaf, "); // from ComputeAgeMortality CalibrateLog.Write("MortalityBIOwood, MortalityBIOleaf, "); // from ComputeGrowthMortality CalibrateLog.Write("availableWater,"); //from Water_limit CalibrateLog.Write("LAI,tlai,rlai,"); // from ComputeChange CalibrateLog.Write("mineralNalloc, resorbedNalloc, "); // from calculateN_Limit CalibrateLog.Write("limitLAI, limitH20, limitT, limitN, "); //from ComputeActualANPP CalibrateLog.Write("maxNPP, Bmax, Bsite, Bcohort, soilTemp, "); //from ComputeActualANPP CalibrateLog.Write("actualWoodNPP, actualLeafNPP, "); //from ComputeActualANPP CalibrateLog.Write("NPPwood, NPPleaf, "); //from ComputeNPPcarbon CalibrateLog.Write("resorbedNused, mineralNused, Ndemand,"); // from AdjustAvailableN CalibrateLog.WriteLine("deltaWood, deltaLeaf, totalMortalityWood, totalMortalityLeaf, "); // from ComputeChange } //--------------------------------------------------------------------- private static double GetTotalNitrogen(Site site) { double totalN = + SiteVars.CohortLeafN[site] + SiteVars.CohortFRootN[site] + SiteVars.CohortWoodN[site] + SiteVars.CohortCRootN[site] + SiteVars.MineralN[site] + SiteVars.SurfaceDeadWood[site].Nitrogen + SiteVars.SoilDeadWood[site].Nitrogen + SiteVars.SurfaceStructural[site].Nitrogen + SiteVars.SoilStructural[site].Nitrogen + SiteVars.SurfaceMetabolic[site].Nitrogen + SiteVars.SoilMetabolic[site].Nitrogen + SiteVars.SOM1surface[site].Nitrogen + SiteVars.SOM1soil[site].Nitrogen + SiteVars.SOM2[site].Nitrogen + SiteVars.SOM3[site].Nitrogen ; return totalN; } private static double GetTotalSoilNitrogen(Site site) { double totalsoilN = +SiteVars.MineralN[site] + SiteVars.SurfaceStructural[site].Nitrogen + SiteVars.SoilStructural[site].Nitrogen + SiteVars.SurfaceMetabolic[site].Nitrogen +SiteVars.SoilMetabolic[site].Nitrogen + SiteVars.SOM1surface[site].Nitrogen + SiteVars.SOM1soil[site].Nitrogen + SiteVars.SOM2[site].Nitrogen + SiteVars.SOM3[site].Nitrogen; ; return totalsoilN; } //--------------------------------------------------------------------- public static double GetOrganicCarbon(Site site) { double totalC = SiteVars.SOM1surface[site].Carbon + SiteVars.SOM1soil[site].Carbon + SiteVars.SOM2[site].Carbon + SiteVars.SOM3[site].Carbon ; return totalC; } //--------------------------------------------------------------------- private static double GetSoilNuptake(ActiveSite site) { double soilNuptake = SiteVars.TotalNuptake[site] ; return soilNuptake; } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using osu.Framework.Allocation; using osu.Framework.Extensions.Color4Extensions; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Shapes; using osu.Framework.Graphics.Sprites; using osu.Game.Graphics; using osu.Game.Graphics.Cursor; using osu.Game.Graphics.Sprites; using osu.Game.Online.Chat; using osuTK.Graphics; namespace osu.Game.Overlays.Chat { public class DrawableChannel : Container { public readonly Channel Channel; protected FillFlowContainer ChatLineFlow; private ChannelScrollContainer scroll; private bool scrollbarVisible = true; public bool ScrollbarVisible { set { if (scrollbarVisible == value) return; scrollbarVisible = value; if (scroll != null) scroll.ScrollbarVisible = value; } } [Resolved] private OsuColour colours { get; set; } public DrawableChannel(Channel channel) { Channel = channel; RelativeSizeAxes = Axes.Both; } [BackgroundDependencyLoader] private void load() { Child = new OsuContextMenuContainer { RelativeSizeAxes = Axes.Both, Masking = true, Child = scroll = new ChannelScrollContainer { ScrollbarVisible = scrollbarVisible, RelativeSizeAxes = Axes.Both, // Some chat lines have effects that slightly protrude to the bottom, // which we do not want to mask away, hence the padding. Padding = new MarginPadding { Bottom = 5 }, Child = ChatLineFlow = new FillFlowContainer { Padding = new MarginPadding { Left = 20, Right = 20 }, RelativeSizeAxes = Axes.X, AutoSizeAxes = Axes.Y, Direction = FillDirection.Vertical, } }, }; newMessagesArrived(Channel.Messages); Channel.NewMessagesArrived += newMessagesArrived; Channel.MessageRemoved += messageRemoved; Channel.PendingMessageResolved += pendingMessageResolved; } protected override void Dispose(bool isDisposing) { base.Dispose(isDisposing); Channel.NewMessagesArrived -= newMessagesArrived; Channel.MessageRemoved -= messageRemoved; Channel.PendingMessageResolved -= pendingMessageResolved; } protected virtual ChatLine CreateChatLine(Message m) => new ChatLine(m); protected virtual DaySeparator CreateDaySeparator(DateTimeOffset time) => new DaySeparator(time) { Margin = new MarginPadding { Vertical = 10 }, Colour = colours.ChatBlue.Lighten(0.7f), }; private void newMessagesArrived(IEnumerable<Message> newMessages) => Schedule(() => { if (newMessages.Min(m => m.Id) < chatLines.Max(c => c.Message.Id)) { // there is a case (on initial population) that we may receive past messages and need to reorder. // easiest way is to just combine messages and recreate drawables (less worrying about day separators etc.) newMessages = newMessages.Concat(chatLines.Select(c => c.Message)).OrderBy(m => m.Id).ToList(); ChatLineFlow.Clear(); } // Add up to last Channel.MAX_HISTORY messages var displayMessages = newMessages.Skip(Math.Max(0, newMessages.Count() - Channel.MAX_HISTORY)); Message lastMessage = chatLines.LastOrDefault()?.Message; foreach (var message in displayMessages) { if (lastMessage == null || lastMessage.Timestamp.ToLocalTime().Date != message.Timestamp.ToLocalTime().Date) ChatLineFlow.Add(CreateDaySeparator(message.Timestamp)); ChatLineFlow.Add(CreateChatLine(message)); lastMessage = message; } var staleMessages = chatLines.Where(c => c.LifetimeEnd == double.MaxValue).ToArray(); int count = staleMessages.Length - Channel.MAX_HISTORY; if (count > 0) { void expireAndAdjustScroll(Drawable d) { scroll.OffsetScrollPosition(-d.DrawHeight); d.Expire(); } for (int i = 0; i < count; i++) expireAndAdjustScroll(staleMessages[i]); // remove all adjacent day separators after stale message removal for (int i = 0; i < ChatLineFlow.Count - 1; i++) { if (!(ChatLineFlow[i] is DaySeparator)) break; if (!(ChatLineFlow[i + 1] is DaySeparator)) break; expireAndAdjustScroll(ChatLineFlow[i]); } } // due to the scroll adjusts from old messages removal above, a scroll-to-end must be enforced, // to avoid making the container think the user has scrolled back up and unwantedly disable auto-scrolling. if (newMessages.Any(m => m is LocalMessage)) scroll.ScrollToEnd(); }); private void pendingMessageResolved(Message existing, Message updated) => Schedule(() => { var found = chatLines.LastOrDefault(c => c.Message == existing); if (found != null) { Trace.Assert(updated.Id.HasValue, "An updated message was returned with no ID."); ChatLineFlow.Remove(found); found.Message = updated; ChatLineFlow.Add(found); } }); private void messageRemoved(Message removed) => Schedule(() => { chatLines.FirstOrDefault(c => c.Message == removed)?.FadeColour(Color4.Red, 400).FadeOut(600).Expire(); }); private IEnumerable<ChatLine> chatLines => ChatLineFlow.Children.OfType<ChatLine>(); public class DaySeparator : Container { public float TextSize { get => text.Font.Size; set => text.Font = text.Font.With(size: value); } private float lineHeight = 2; public float LineHeight { get => lineHeight; set => lineHeight = leftBox.Height = rightBox.Height = value; } private readonly SpriteText text; private readonly Box leftBox; private readonly Box rightBox; public DaySeparator(DateTimeOffset time) { RelativeSizeAxes = Axes.X; AutoSizeAxes = Axes.Y; Child = new GridContainer { RelativeSizeAxes = Axes.X, AutoSizeAxes = Axes.Y, ColumnDimensions = new[] { new Dimension(), new Dimension(GridSizeMode.AutoSize), new Dimension(), }, RowDimensions = new[] { new Dimension(GridSizeMode.AutoSize), }, Content = new[] { new Drawable[] { leftBox = new Box { Anchor = Anchor.Centre, Origin = Anchor.Centre, RelativeSizeAxes = Axes.X, Height = lineHeight, }, text = new OsuSpriteText { Margin = new MarginPadding { Horizontal = 10 }, Text = time.ToLocalTime().ToString("dd MMM yyyy"), }, rightBox = new Box { Anchor = Anchor.Centre, Origin = Anchor.Centre, RelativeSizeAxes = Axes.X, Height = lineHeight, }, } } }; } } } }
using System.Collections.Generic; using NUnit.Framework; using SIL.Annotations; using SIL.TestUtilities; using SIL.Text; namespace SIL.Tests.Text { [TestFixture] public class LanguageFormCloneableTests:CloneableTests<Annotatable> { public override Annotatable CreateNewCloneable() { return new LanguageForm(); } public override string ExceptionList { //_parent: We are doing top down clones. Children shouldn't make clones of their parents, but parents of their children. get { return "|_parent|"; } } public override string EqualsExceptionList { //_spans: is a List<T> which doesn't compare well with Equals (two separate empty lists are deemed different for example) get { return "|_spans|"; } } protected override List<ValuesToSet> DefaultValuesForTypes { get { return new List<ValuesToSet> { new ValuesToSet("string", "not string"), new ValuesToSet(new Annotation{IsOn = false}, new Annotation{IsOn = true}), new ValuesToSet(new List<LanguageForm.FormatSpan>(), new List<LanguageForm.FormatSpan>{new LanguageForm.FormatSpan()}) }; } } } [TestFixture] public class LanguageFormTest { LanguageForm _languageFormToCompare; LanguageForm _languageForm; [SetUp] public void Setup() { _languageFormToCompare = new LanguageForm(); _languageForm = new LanguageForm(); } [Test] public void CompareTo_Null_ReturnsGreater() { _languageFormToCompare = null; Assert.AreEqual(1, _languageForm.CompareTo(_languageFormToCompare)); } [Test] public void CompareTo_AlphabeticallyEarlierWritingSystemIdWithIdenticalForm_ReturnsLess() { _languageForm.WritingSystemId = "de"; _languageForm.Form = "Word1"; _languageFormToCompare.WritingSystemId = "en"; _languageFormToCompare.Form = "Word1"; Assert.AreEqual(-1, _languageForm.CompareTo(_languageFormToCompare)); } [Test] public void CompareTo_AlpahbeticallyLaterWritingSystemIdWithIdenticalForm_ReturnsGreater() { _languageForm.WritingSystemId = "en"; _languageForm.Form = "Word1"; _languageFormToCompare.WritingSystemId = "de"; _languageFormToCompare.Form = "Word1"; Assert.AreEqual(1, _languageForm.CompareTo(_languageFormToCompare)); } [Test] public void CompareTo_IdenticalWritingSystemIdWithIdenticalForm_Returns_Equal() { _languageForm.WritingSystemId = "de"; _languageForm.Form = "Word1"; _languageFormToCompare.WritingSystemId = "de"; _languageFormToCompare.Form = "Word1"; Assert.AreEqual(0, _languageForm.CompareTo(_languageFormToCompare)); } [Test] public void CompareTo_AlphabeticallyEarlierFormWithIdenticalWritingSystem_ReturnsLess() { _languageForm.WritingSystemId = "de"; _languageForm.Form = "Word1"; _languageFormToCompare.WritingSystemId = "de"; _languageFormToCompare.Form = "Word2"; Assert.AreEqual(-1, _languageForm.CompareTo(_languageFormToCompare)); } [Test] public void CompareTo_AlphabeticallyLaterFormWithIdenticalWritingSystem_ReturnsGreater() { _languageForm.WritingSystemId = "de"; _languageForm.Form = "Word2"; _languageFormToCompare.WritingSystemId = "de"; _languageFormToCompare.Form = "Word1"; Assert.AreEqual(1, _languageForm.CompareTo(_languageFormToCompare)); } [Test] public void CompareTo_IdenticalFormWithIdenticalWritingSystem_ReturnsEqual() { _languageForm.WritingSystemId = "de"; _languageForm.Form = "Word1"; _languageFormToCompare.WritingSystemId = "de"; _languageFormToCompare.Form = "Word1"; Assert.AreEqual(0, _languageForm.CompareTo(_languageFormToCompare)); } [Test] public void CompareTo_AlphabeticallyEarlierWritingSystemAlphabeticallyLaterForm_ReturnsLess() { _languageForm.WritingSystemId = "de"; _languageForm.Form = "Word2"; _languageFormToCompare.WritingSystemId = "en"; _languageFormToCompare.Form = "Word1"; Assert.AreEqual(-1, _languageForm.CompareTo(_languageFormToCompare)); } [Test] public void CompareTo_AlphabeticallyEarlierFormAlphabeticallyLaterWritingSystem_ReturnsGreater() { _languageForm.WritingSystemId = "en"; _languageForm.Form = "Word1"; _languageFormToCompare.WritingSystemId = "de"; _languageFormToCompare.Form = "Word2"; Assert.AreEqual(1, _languageForm.CompareTo(_languageFormToCompare)); } [Test] public void Equals_SameObject_True() { var form = new LanguageForm(); Assert.That(form.Equals(form), Is.True); } [Test] public void Equals_OneStarredOtherIsNot_False() { var form1 = new LanguageForm(); var form2 = new LanguageForm(); form1.IsStarred = true; Assert.That(form1.Equals(form2), Is.False); } [Test] public void Equals_OneContainsWritingSystemOtherDoesNot_False() { var form1 = new LanguageForm{WritingSystemId = "en"}; var form2 = new LanguageForm{WritingSystemId = "de"}; Assert.That(form1.Equals(form2), Is.False); } [Test] public void Equals_OneContainsFormInWritingSystemOtherDoesNot_False() { var form1 = new LanguageForm { WritingSystemId = "en", Form = "form1"}; var form2 = new LanguageForm { WritingSystemId = "en", Form = "form2" }; Assert.That(form1.Equals(form2), Is.False); } [Test] public void Equals_StarredWritingSystemAndFormAreIdentical_True() { var form1 = new LanguageForm { IsStarred = true, WritingSystemId = "en", Form = "form1" }; var form2 = new LanguageForm { IsStarred = true, WritingSystemId = "en", Form = "form1" }; Assert.That(form1.Equals(form2), Is.True); } [Test] public void Equals_Null_False() { var form1 = new LanguageForm { IsStarred = true, WritingSystemId = "en", Form = "form1" }; LanguageForm form2 = null; Assert.That(form1.Equals(form2), Is.False); } [Test] public void ObjectEquals_SameObject_True() { var form = new LanguageForm(); Assert.That(form.Equals((object) form), Is.True); } [Test] public void ObjectEquals_OneStarredOtherIsNot_False() { var form1 = new LanguageForm(); var form2 = new LanguageForm(); form1.IsStarred = true; Assert.That(form1.Equals((object)form2), Is.False); } [Test] public void ObjectEquals_OneContainsWritingSystemOtherDoesNot_False() { var form1 = new LanguageForm { WritingSystemId = "en" }; var form2 = new LanguageForm { WritingSystemId = "de" }; Assert.That(form1.Equals((object)form2), Is.False); } [Test] public void ObjectEquals_OneContainsFormInWritingSystemOtherDoesNot_False() { var form1 = new LanguageForm { WritingSystemId = "en", Form = "form1" }; var form2 = new LanguageForm { WritingSystemId = "en", Form = "form2" }; Assert.That(form1.Equals((object)form2), Is.False); } [Test] public void ObjectEquals_StarredWritingSystemAndFormAreIdentical_True() { var form1 = new LanguageForm { IsStarred = true, WritingSystemId = "en", Form = "form1" }; var form2 = new LanguageForm { IsStarred = true, WritingSystemId = "en", Form = "form1" }; Assert.That(form1.Equals((object)form2), Is.True); } [Test] public void ObjectEquals_Null_False() { var form1 = new LanguageForm { IsStarred = true, WritingSystemId = "en", Form = "form1" }; LanguageForm form2 = null; Assert.That(form1.Equals((object)form2), Is.False); } [Test] public void UpdateSpans_Insert() { // In these tests, we're testing (inserting) edits to the formatted string // "This is a <span class='Strong'>test</span> of <span class='Weak'>something</span> or other." // See http://jira.palaso.org/issues/browse/WS-34799 for a discussion of what we want to achieve. List<LanguageForm.FormatSpan> spans = new List<LanguageForm.FormatSpan>(); string oldString = "This is a test of something or other."; // before any spans (add 3 characters) var expected = CreateSpans(spans, 3, 0, 3, 0); LanguageForm.AdjustSpansForTextChange(oldString, "This isn't a test of something or other.", spans); VerifySpans(expected, spans); // before any spans, but right next to the first span (add 5 characters) expected = CreateSpans(spans, 5, 0, 5, 0); LanguageForm.AdjustSpansForTextChange(oldString, "This is a good test of something or other.", spans); VerifySpans(expected, spans); // after any spans (add 5 characters, but spans don't change) expected = CreateSpans(spans, 0, 0, 0, 0); LanguageForm.AdjustSpansForTextChange(oldString, "This is a test of something else or other.", spans); VerifySpans(expected, spans); // inside the first span (increase its length by 2) expected = CreateSpans(spans, 0, 2, 2, 0); LanguageForm.AdjustSpansForTextChange(oldString, "This is a tessst of something or other.", spans); VerifySpans(expected, spans); // after the first span, but right next to it (increase its length by 3) expected = CreateSpans(spans, 0, 3, 3, 0); LanguageForm.AdjustSpansForTextChange(oldString, "This is a testing of something or other.", spans); VerifySpans(expected, spans); // inside the second span (increase its length by 9) expected = CreateSpans(spans, 0, 0, 0, 9); LanguageForm.AdjustSpansForTextChange(oldString, "This is a test of some kind of thing or other.", spans); VerifySpans(expected, spans); // between the two spans (effectively add 1 character) expected = CreateSpans(spans, 0, 0, 1, 0); LanguageForm.AdjustSpansForTextChange(oldString, "This is a test for something or other.", spans); VerifySpans(expected, spans); } [Test] public void AdjustSpans_Delete() { // In these tests, we're testing (deleting) edits to the formatted string // "This is a <span class='Strong'>test</span> of <span class='Weak'>something</span> or other." // See http://jira.palaso.org/issues/browse/WS-34799 for a discussion of what we want to achieve. List<LanguageForm.FormatSpan> spans = new List<LanguageForm.FormatSpan>(); string oldString = "This is a test of something or other."; // before any spans (remove 3 characters) var expected = CreateSpans(spans, -3, 0, -3, 0); LanguageForm.AdjustSpansForTextChange(oldString, "This a test of something or other.", spans); VerifySpans(expected, spans); // before any spans, but next to first span (remove 2 characters) expected = CreateSpans(spans, -2, 0, -2, 0); LanguageForm.AdjustSpansForTextChange(oldString, "This is test of something or other.", spans); VerifySpans(expected, spans); // start before any spans, but including part of first span (remove 2 before and 2 inside span) expected = CreateSpans(spans, -2, -2, -4, 0); LanguageForm.AdjustSpansForTextChange(oldString, "This is st of something or other.", spans); VerifySpans(expected, spans); // start before any spans, but extending past first span (remove 2 before, 4 inside, and 4 after/between) // The span length going negative is okay, and the same as going to zero: the span is ignored thereafter. expected = CreateSpans(spans, -2, -8, -10, 0); LanguageForm.AdjustSpansForTextChange(oldString, "This is something or other.", spans); VerifySpans(expected, spans); // delete exactly the first span (remove 4 inside) expected = CreateSpans(spans, 0, -4, -4, 0); LanguageForm.AdjustSpansForTextChange(oldString, "This is a of something or other.", spans); VerifySpans(expected, spans); // after any spans (effectively no change) expected = CreateSpans(spans, 0, 0, 0, 0); LanguageForm.AdjustSpansForTextChange(oldString, "This is a test of something or other", spans); VerifySpans(expected, spans); // after any spans, but adjacent to last span (effectively no change) expected = CreateSpans(spans, 0, 0, 0, 0); LanguageForm.AdjustSpansForTextChange(oldString, "This is a test of somethingther.", spans); VerifySpans(expected, spans); // delete from middle of first span to middle of second span expected = CreateSpans(spans, 0, -2, -6, -7); LanguageForm.AdjustSpansForTextChange(oldString, "This is a teng or other.", spans); VerifySpans(expected, spans); // change text without changing length of string // (alas, we can't handle this kind of wholesale change, so effectively no change to the spans) expected = CreateSpans(spans, 0, 0, 0, 0); LanguageForm.AdjustSpansForTextChange(oldString, "That is a joke of some other topic!!!", spans); VerifySpans(expected, spans); } static List<LanguageForm.FormatSpan> CreateSpans(List<LanguageForm.FormatSpan> spans, int deltaloc1, int deltalen1, int deltaloc2, int deltalen2) { spans.Clear(); spans.Add(new LanguageForm.FormatSpan { Index = 10, Length = 4, Class = "Strong" }); spans.Add(new LanguageForm.FormatSpan { Index = 18, Length = 9, Class = "Weak" }); var expected = new List<LanguageForm.FormatSpan>(); expected.Add(new LanguageForm.FormatSpan { Index = 10 + deltaloc1, Length = 4 + deltalen1, Class = "Strong" }); expected.Add(new LanguageForm.FormatSpan { Index = 18 + deltaloc2, Length = 9 + deltalen2, Class = "Weak" }); return expected; } void VerifySpans (List<LanguageForm.FormatSpan> expected, List<LanguageForm.FormatSpan> spans) { Assert.AreEqual(expected[0].Index, spans[0].Index, "first span index wrong"); Assert.AreEqual(expected[0].Length, spans[0].Length, "first span length wrong"); Assert.AreEqual(expected[0].Class, spans[0].Class, "first span class wrong"); Assert.AreEqual(expected[1].Index, spans[1].Index, "second span index wrong"); Assert.AreEqual(expected[1].Length, spans[1].Length, "second span length wrong"); Assert.AreEqual(expected[1].Class, spans[1].Class, "second span class wrong"); } } }
// // (C) Copyright 2003-2011 by Autodesk, Inc. // // Permission to use, copy, modify, and distribute this software in // object code form for any purpose and without fee is hereby granted, // provided that the above copyright notice appears in all copies and // that both that copyright notice and the limited warranty and // restricted rights notice below appear in all supporting // documentation. // // AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS. // AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF // MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC. // DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE // UNINTERRUPTED OR ERROR FREE. // // Use, duplication, or disclosure by the U.S. Government is subject to // restrictions set forth in FAR 52.227-19 (Commercial Computer // Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii) // (Rights in Technical Data and Computer Software), as applicable. // using System; using System.Collections.Generic; using System.Text; using System.Windows.Forms; using Autodesk.Revit; using Autodesk.Revit.DB; using Autodesk.Revit.UI; namespace Revit.SDK.Samples.SharedCoordinateSystem.CS { /// <summary> /// this class is used to get, set and manage information about Location /// </summary> public class CoordinateSystemData { ExternalCommandData m_command; // the ExternalCommandData reference Autodesk.Revit.UI.UIApplication m_application; //the revit application reference const double Modulus = 0.0174532925199433; //a modulus for degree convert to pi const int Precision = 3; //default precision string m_currentLocationName; //the location of the active project; List<string> m_locationnames = new List<string>(); //a list to store all the location name double m_angle; //Angle from True North double m_eastWest; //East to West offset double m_northSouth; //North to South offset double m_elevation; //Elevation above ground level /// <summary> /// the value of the angle form true north /// </summary> public double AngleOffset { get { return m_angle; } } /// <summary> /// return the East to West offset /// </summary> public double EastWestOffset { get { return m_eastWest; } } /// <summary> /// return the North to South offset /// </summary> public double NorthSouthOffset { get { return m_northSouth; } } /// <summary> /// return the Elevation above ground level /// </summary> public double PositionElevation { get { return m_elevation; } } /// <summary> /// get and set the current project location name of the project /// </summary> public string LocationName { get { return m_currentLocationName; } set { m_currentLocationName = value; } } /// <summary> /// get all the project locations' name of the project /// </summary> public List<string> LocationNames { get { return m_locationnames; } } /// <summary> /// constructor /// </summary> /// <param name="commandData">the ExternalCommandData reference</param> public CoordinateSystemData(ExternalCommandData commandData) { m_command = commandData; m_application = m_command.Application; } /// <summary> /// get the shared coordinate system data of the project /// </summary> public void GatData() { this.GetLocationData(); } /// <summary> /// get the information of all the project locations associated with this project /// </summary> public void GetLocationData() { m_locationnames.Clear(); ProjectLocation currentLocation = m_application.ActiveUIDocument.Document.ActiveProjectLocation; //get the current location name m_currentLocationName = currentLocation.Name; //Retrieve all the project locations associated with this project ProjectLocationSet locations = m_application.ActiveUIDocument.Document.ProjectLocations; ProjectLocationSetIterator iter = locations.ForwardIterator(); iter.Reset(); while (iter.MoveNext()) { ProjectLocation locationTransform = iter.Current as ProjectLocation; string transformName = locationTransform.Name; m_locationnames.Add(transformName); //add the location's name to the list } } /// <summary> /// duplicate a new project location /// </summary> /// <param name="locationName">old location name</param> /// <param name="newLocationName">new location name</param> public void DuplicateLocation(string locationName, string newLocationName) { ProjectLocationSet locationSet = m_application.ActiveUIDocument.Document.ProjectLocations; foreach (ProjectLocation projectLocation in locationSet) { if (projectLocation.Name == locationName || projectLocation.Name + " (current)" == locationName) { //duplicate a new project location projectLocation.Duplicate(newLocationName); break; } } } /// <summary> /// change the current project location /// </summary> /// <param name="locationName"></param> public void ChangeCurrentLocation(string locationName) { ProjectLocationSet locations = m_application.ActiveUIDocument.Document.ProjectLocations; foreach (ProjectLocation projectLocation in locations) { //find the project location which is selected by user and //set it to the current projecte location if (projectLocation.Name == locationName) { m_application.ActiveUIDocument.Document.ActiveProjectLocation = projectLocation; m_currentLocationName = locationName; break; } } } /// <summary> /// get the offset values of the project position /// </summary> /// <param name="locationName"></param> public void GetOffset(string locationName) { ProjectLocationSet locationSet = m_application.ActiveUIDocument.Document.ProjectLocations; foreach (ProjectLocation projectLocation in locationSet) { if (projectLocation.Name == locationName || projectLocation.Name + " (current)" == locationName) { Autodesk.Revit.DB.XYZ origin = new Autodesk.Revit.DB.XYZ (0, 0, 0); //get the project position ProjectPosition pp = projectLocation.get_ProjectPosition(origin); m_angle = (pp.Angle /= Modulus); //convert to unit degree m_eastWest = pp.EastWest; //East to West offset m_northSouth = pp.NorthSouth; //north to south offset m_elevation = pp.Elevation; //Elevation above ground level break; } } this.ChangePrecision(); } /// <summary> /// change the offset value for the project position /// </summary> /// <param name="locationName">location name</param> /// <param name="newAngle">angle from true north</param> /// <param name="newEast">East to West offset</param> /// <param name="newNorth">north to south offset</param> /// <param name="newElevation">Elevation above ground level</param> public void EditPosition(string locationName, double newAngle, double newEast, double newNorth, double newElevation) { ProjectLocationSet locationSet = m_application.ActiveUIDocument.Document.ProjectLocations; foreach (ProjectLocation location in locationSet) { if (location.Name == locationName || location.Name + " (current)" == locationName) { //get the project position Autodesk.Revit.DB.XYZ origin = new Autodesk.Revit.DB.XYZ (0, 0, 0); ProjectPosition projectPosition = location.get_ProjectPosition(origin); //change the offset value of the project position projectPosition.Angle = newAngle * Modulus; //convert the unit projectPosition.EastWest = newEast; projectPosition.NorthSouth = newNorth; projectPosition.Elevation = newElevation; //set the value of the project position location.set_ProjectPosition(origin, projectPosition); } } } /// <summary> /// change the Precision of the value /// </summary> private void ChangePrecision() { m_angle = UnitConversion.DealPrecision(m_angle, Precision); m_eastWest = UnitConversion.DealPrecision(m_eastWest, Precision); m_northSouth = UnitConversion.DealPrecision(m_northSouth, Precision); m_elevation = UnitConversion.DealPrecision(m_elevation, Precision); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 0.14.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.ResourceManager { using System; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; public static partial class FeaturesOperationsExtensions { /// <summary> /// Gets a list of previewed features for all the providers in the current /// subscription. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static IPage<FeatureResult> ListAll(this IFeaturesOperations operations) { return Task.Factory.StartNew(s => ((IFeaturesOperations)s).ListAllAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets a list of previewed features for all the providers in the current /// subscription. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<FeatureResult>> ListAllAsync( this IFeaturesOperations operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListAllWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets a list of previewed features of a resource provider. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceProviderNamespace'> /// The namespace of the resource provider. /// </param> public static IPage<FeatureResult> List(this IFeaturesOperations operations, string resourceProviderNamespace) { return Task.Factory.StartNew(s => ((IFeaturesOperations)s).ListAsync(resourceProviderNamespace), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets a list of previewed features of a resource provider. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceProviderNamespace'> /// The namespace of the resource provider. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<FeatureResult>> ListAsync( this IFeaturesOperations operations, string resourceProviderNamespace, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListWithHttpMessagesAsync(resourceProviderNamespace, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Get all features under the subscription. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceProviderNamespace'> /// Namespace of the resource provider. /// </param> /// <param name='featureName'> /// Previewed feature name in the resource provider. /// </param> public static FeatureResult Get(this IFeaturesOperations operations, string resourceProviderNamespace, string featureName) { return Task.Factory.StartNew(s => ((IFeaturesOperations)s).GetAsync(resourceProviderNamespace, featureName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get all features under the subscription. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceProviderNamespace'> /// Namespace of the resource provider. /// </param> /// <param name='featureName'> /// Previewed feature name in the resource provider. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<FeatureResult> GetAsync( this IFeaturesOperations operations, string resourceProviderNamespace, string featureName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetWithHttpMessagesAsync(resourceProviderNamespace, featureName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Registers for a previewed feature of a resource provider. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceProviderNamespace'> /// Namespace of the resource provider. /// </param> /// <param name='featureName'> /// Previewed feature name in the resource provider. /// </param> public static FeatureResult Register(this IFeaturesOperations operations, string resourceProviderNamespace, string featureName) { return Task.Factory.StartNew(s => ((IFeaturesOperations)s).RegisterAsync(resourceProviderNamespace, featureName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Registers for a previewed feature of a resource provider. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceProviderNamespace'> /// Namespace of the resource provider. /// </param> /// <param name='featureName'> /// Previewed feature name in the resource provider. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<FeatureResult> RegisterAsync( this IFeaturesOperations operations, string resourceProviderNamespace, string featureName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.RegisterWithHttpMessagesAsync(resourceProviderNamespace, featureName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets a list of previewed features for all the providers in the current /// subscription. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> public static IPage<FeatureResult> ListAllNext(this IFeaturesOperations operations, string nextPageLink) { return Task.Factory.StartNew(s => ((IFeaturesOperations)s).ListAllNextAsync(nextPageLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets a list of previewed features for all the providers in the current /// subscription. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<FeatureResult>> ListAllNextAsync( this IFeaturesOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListAllNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets a list of previewed features of a resource provider. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> public static IPage<FeatureResult> ListNext(this IFeaturesOperations operations, string nextPageLink) { return Task.Factory.StartNew(s => ((IFeaturesOperations)s).ListNextAsync(nextPageLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets a list of previewed features of a resource provider. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<FeatureResult>> ListNextAsync( this IFeaturesOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using Microsoft.Azure.Management.ResourceManager; using Microsoft.Azure.Management.ResourceManager.Models; using Microsoft.Azure.Management.StreamAnalytics; using Microsoft.Azure.Management.StreamAnalytics.Models; using Microsoft.Rest.Azure; using Microsoft.Rest.ClientRuntime.Azure.TestFramework; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Threading.Tasks; using Xunit; namespace StreamAnalytics.Tests { public class FunctionTests : TestBase { [Fact(Skip = "ReRecord due to CR change")] public async Task FunctionOperationsTest_Scalar_AzureMLWebService() { using (MockContext context = MockContext.Start(this.GetType())) { string resourceGroupName = TestUtilities.GenerateName("sjrg"); string jobName = TestUtilities.GenerateName("sj"); string functionName = TestUtilities.GenerateName("function"); var resourceManagementClient = this.GetResourceManagementClient(context); var streamAnalyticsManagementClient = this.GetStreamAnalyticsManagementClient(context); string expectedFunctionType = TestHelper.GetFullRestOnlyResourceType(TestHelper.FunctionsResourceType); string expectedFunctionResourceId = TestHelper.GetRestOnlyResourceId(streamAnalyticsManagementClient.SubscriptionId, resourceGroupName, jobName, TestHelper.FunctionsResourceType, functionName); resourceManagementClient.ResourceGroups.CreateOrUpdate(resourceGroupName, new ResourceGroup { Location = TestHelper.DefaultLocation }); var expectedFunction = new Function() { Properties = new ScalarFunctionProperties() { Inputs = new List<FunctionInput>() { new FunctionInput() { DataType = @"nvarchar(max)", IsConfigurationParameter = null } }, Output = new FunctionOutput() { DataType = @"nvarchar(max)" }, Binding = new AzureMachineLearningWebServiceFunctionBinding() { Endpoint = TestHelper.ExecuteEndpoint, ApiKey = null, Inputs = new AzureMachineLearningWebServiceInputs() { Name = "input1", ColumnNames = new AzureMachineLearningWebServiceInputColumn[] { new AzureMachineLearningWebServiceInputColumn() { Name = "tweet", DataType = "string", MapTo = 0 } } }, Outputs = new List<AzureMachineLearningWebServiceOutputColumn>() { new AzureMachineLearningWebServiceOutputColumn() { Name = "Sentiment", DataType = "string" } }, BatchSize = 1000 } } }; // PUT job streamAnalyticsManagementClient.StreamingJobs.CreateOrReplace(TestHelper.GetDefaultStreamingJob(), resourceGroupName, jobName); // Retrieve default definition AzureMachineLearningWebServiceFunctionRetrieveDefaultDefinitionParameters retrieveDefaultDefinitionParameters = new AzureMachineLearningWebServiceFunctionRetrieveDefaultDefinitionParameters() { UdfType = UdfType.Scalar, ExecuteEndpoint = TestHelper.ExecuteEndpoint }; var function = streamAnalyticsManagementClient.Functions.RetrieveDefaultDefinition(resourceGroupName, jobName, functionName, retrieveDefaultDefinitionParameters); Assert.Equal(functionName, function.Name); Assert.Null(function.Id); Assert.Null(function.Type); ValidationHelper.ValidateFunctionProperties(expectedFunction.Properties, function.Properties, false); // PUT function ((AzureMachineLearningWebServiceFunctionBinding)((ScalarFunctionProperties)function.Properties).Binding).ApiKey = TestHelper.ApiKey; var putResponse = await streamAnalyticsManagementClient.Functions.CreateOrReplaceWithHttpMessagesAsync(function, resourceGroupName, jobName, functionName); ((AzureMachineLearningWebServiceFunctionBinding)((ScalarFunctionProperties)function.Properties).Binding).ApiKey = null; // Null out because secrets are not returned in responses ValidationHelper.ValidateFunction(function, putResponse.Body, false); Assert.Equal(expectedFunctionResourceId, putResponse.Body.Id); Assert.Equal(functionName, putResponse.Body.Name); Assert.Equal(expectedFunctionType, putResponse.Body.Type); // Verify GET request returns expected function var getResponse = await streamAnalyticsManagementClient.Functions.GetWithHttpMessagesAsync(resourceGroupName, jobName, functionName); ValidationHelper.ValidateFunction(putResponse.Body, getResponse.Body, true); // ETag should be the same Assert.Equal(putResponse.Headers.ETag, getResponse.Headers.ETag); // Test Function var testResult = streamAnalyticsManagementClient.Functions.Test(resourceGroupName, jobName, functionName); Assert.Equal("TestSucceeded", testResult.Status); Assert.Null(testResult.Error); // PATCH function var functionPatch = new Function() { Properties = new ScalarFunctionProperties() { Binding = new AzureMachineLearningWebServiceFunctionBinding() { BatchSize = 5000 } } }; ((AzureMachineLearningWebServiceFunctionBinding)((ScalarFunctionProperties)putResponse.Body.Properties).Binding).BatchSize = ((AzureMachineLearningWebServiceFunctionBinding)((ScalarFunctionProperties)functionPatch.Properties).Binding).BatchSize; var patchResponse = await streamAnalyticsManagementClient.Functions.UpdateWithHttpMessagesAsync(functionPatch, resourceGroupName, jobName, functionName); ValidationHelper.ValidateFunction(putResponse.Body, patchResponse.Body, true); // ETag should be different after a PATCH operation Assert.NotEqual(putResponse.Headers.ETag, patchResponse.Headers.ETag); // Run another GET function to verify that it returns the newly updated properties as well getResponse = await streamAnalyticsManagementClient.Functions.GetWithHttpMessagesAsync(resourceGroupName, jobName, functionName); ValidationHelper.ValidateFunction(putResponse.Body, getResponse.Body, true); // ETag should be different after a PATCH operation Assert.NotEqual(putResponse.Headers.ETag, getResponse.Headers.ETag); Assert.Equal(patchResponse.Headers.ETag, getResponse.Headers.ETag); // List function and verify that the function shows up in the list var listResult = streamAnalyticsManagementClient.Functions.ListByStreamingJob(resourceGroupName, jobName); Assert.Single(listResult); ValidationHelper.ValidateFunction(putResponse.Body, listResult.Single(), true); Assert.Equal(getResponse.Headers.ETag, listResult.Single().Properties.Etag); // Get job with function expanded and verify that the function shows up var getJobResponse = streamAnalyticsManagementClient.StreamingJobs.Get(resourceGroupName, jobName, "functions"); Assert.Single(getJobResponse.Functions); ValidationHelper.ValidateFunction(putResponse.Body, getJobResponse.Functions.Single(), true); Assert.Equal(getResponse.Headers.ETag, getJobResponse.Functions.Single().Properties.Etag); // Delete function streamAnalyticsManagementClient.Functions.Delete(resourceGroupName, jobName, functionName); // Verify that list operation returns an empty list after deleting the function listResult = streamAnalyticsManagementClient.Functions.ListByStreamingJob(resourceGroupName, jobName); Assert.Empty(listResult); // Get job with function expanded and verify that there are no functions after deleting the function getJobResponse = streamAnalyticsManagementClient.StreamingJobs.Get(resourceGroupName, jobName, "functions"); Assert.Empty(getJobResponse.Functions); } } [Fact] public async Task FunctionOperationsTest_Scalar_JavaScript() { using (MockContext context = MockContext.Start(this.GetType())) { string resourceGroupName = TestUtilities.GenerateName("sjrg"); string jobName = TestUtilities.GenerateName("sj"); string functionName = TestUtilities.GenerateName("function"); var resourceManagementClient = this.GetResourceManagementClient(context); var streamAnalyticsManagementClient = this.GetStreamAnalyticsManagementClient(context); string expectedFunctionType = TestHelper.GetFullRestOnlyResourceType(TestHelper.FunctionsResourceType); string expectedFunctionResourceId = TestHelper.GetRestOnlyResourceId(streamAnalyticsManagementClient.SubscriptionId, resourceGroupName, jobName, TestHelper.FunctionsResourceType, functionName); resourceManagementClient.ResourceGroups.CreateOrUpdate(resourceGroupName, new ResourceGroup { Location = TestHelper.DefaultLocation }); string javaScriptFunctionCode = @"function (x, y) { return x + y; }"; var function = new Function() { Properties = new ScalarFunctionProperties() { Inputs = new List<FunctionInput>() { new FunctionInput() { DataType = @"Any", IsConfigurationParameter = null } }, Output = new FunctionOutput() { DataType = @"Any" }, Binding = new JavaScriptFunctionBinding() { Script = javaScriptFunctionCode } } }; // PUT job streamAnalyticsManagementClient.StreamingJobs.CreateOrReplace(TestHelper.GetDefaultStreamingJob(), resourceGroupName, jobName); // Retrieve default definition JavaScriptFunctionRetrieveDefaultDefinitionParameters retrieveDefaultDefinitionParameters = new JavaScriptFunctionRetrieveDefaultDefinitionParameters() { UdfType = UdfType.Scalar, Script = javaScriptFunctionCode }; ErrorException errorException = Assert.Throws<ErrorException>( () => streamAnalyticsManagementClient.Functions.RetrieveDefaultDefinition(resourceGroupName, jobName, functionName, retrieveDefaultDefinitionParameters)); Assert.Equal(HttpStatusCode.InternalServerError, errorException.Response.StatusCode); Assert.Contains(@"Retrieve default definition is not supported for function type: Microsoft.StreamAnalytics/JavascriptUdf", errorException.Response.Content); // PUT function var putResponse = await streamAnalyticsManagementClient.Functions.CreateOrReplaceWithHttpMessagesAsync(function, resourceGroupName, jobName, functionName); ValidationHelper.ValidateFunction(function, putResponse.Body, false); Assert.Equal(expectedFunctionResourceId, putResponse.Body.Id); Assert.Equal(functionName, putResponse.Body.Name); Assert.Equal(expectedFunctionType, putResponse.Body.Type); // Verify GET request returns expected function var getResponse = await streamAnalyticsManagementClient.Functions.GetWithHttpMessagesAsync(resourceGroupName, jobName, functionName); ValidationHelper.ValidateFunction(putResponse.Body, getResponse.Body, true); // ETag should be the same Assert.Equal(putResponse.Headers.ETag, getResponse.Headers.ETag); // Test Function var testResult = streamAnalyticsManagementClient.Functions.Test(resourceGroupName, jobName, functionName); Assert.Equal("TestFailed", testResult.Status); Assert.NotNull(testResult.Error); Assert.Equal("BadRequest", testResult.Error.Code); Assert.Equal(@"Test operation is not supported for function type: Microsoft.StreamAnalytics/JavascriptUdf", testResult.Error.Message); // PATCH function var functionPatch = new Function() { Properties = new ScalarFunctionProperties() { Binding = new JavaScriptFunctionBinding() { Script = @"function (a, b) { return a * b; }" } } }; ((JavaScriptFunctionBinding)((ScalarFunctionProperties)putResponse.Body.Properties).Binding).Script = ((JavaScriptFunctionBinding)((ScalarFunctionProperties)functionPatch.Properties).Binding).Script; var patchResponse = await streamAnalyticsManagementClient.Functions.UpdateWithHttpMessagesAsync(functionPatch, resourceGroupName, jobName, functionName); ValidationHelper.ValidateFunction(putResponse.Body, patchResponse.Body, true); // ETag should be different after a PATCH operation Assert.NotEqual(putResponse.Headers.ETag, patchResponse.Headers.ETag); // Run another GET function to verify that it returns the newly updated properties as well getResponse = await streamAnalyticsManagementClient.Functions.GetWithHttpMessagesAsync(resourceGroupName, jobName, functionName); ValidationHelper.ValidateFunction(putResponse.Body, getResponse.Body, true); // ETag should be different after a PATCH operation Assert.NotEqual(putResponse.Headers.ETag, getResponse.Headers.ETag); Assert.Equal(patchResponse.Headers.ETag, getResponse.Headers.ETag); // List function and verify that the function shows up in the list var listResult = streamAnalyticsManagementClient.Functions.ListByStreamingJob(resourceGroupName, jobName); Assert.Single(listResult); ValidationHelper.ValidateFunction(putResponse.Body, listResult.Single(), true); Assert.Equal(getResponse.Headers.ETag, listResult.Single().Properties.Etag); // Get job with function expanded and verify that the function shows up var getJobResponse = streamAnalyticsManagementClient.StreamingJobs.Get(resourceGroupName, jobName, "functions"); Assert.Single(getJobResponse.Functions); ValidationHelper.ValidateFunction(putResponse.Body, getJobResponse.Functions.Single(), true); Assert.Equal(getResponse.Headers.ETag, getJobResponse.Functions.Single().Properties.Etag); // Delete function streamAnalyticsManagementClient.Functions.Delete(resourceGroupName, jobName, functionName); // Verify that list operation returns an empty list after deleting the function listResult = streamAnalyticsManagementClient.Functions.ListByStreamingJob(resourceGroupName, jobName); Assert.Empty(listResult); // Get job with function expanded and verify that there are no functions after deleting the function getJobResponse = streamAnalyticsManagementClient.StreamingJobs.Get(resourceGroupName, jobName, "functions"); Assert.Empty(getJobResponse.Functions); } } } }
/* Copyright (C) 2008-2015 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov * * 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.Diagnostics.CodeAnalysis; using System.IO; using System.Security; using System.Text; namespace Alphaleonis.Win32.Filesystem { /// <summary>Contains Shell32 information about a file.</summary> [SerializableAttribute] [SecurityCritical] public sealed class Shell32Info { #region Constructors /// <summary>Initializes a Shell32Info instance. /// <remarks>Shell32 is limited to MAX_PATH length.</remarks> /// <remarks>This constructor does not check if a file exists. This constructor is a placeholder for a string that is used to access the file in subsequent operations.</remarks> /// </summary> /// <param name="fileName">The fully qualified name of the new file, or the relative file name. Do not end the path with the directory separator character.</param> public Shell32Info(string fileName) : this(fileName, PathFormat.RelativePath) { } /// <summary>Initializes a Shell32Info instance. /// <remarks>Shell32 is limited to MAX_PATH length.</remarks> /// <remarks>This constructor does not check if a file exists. This constructor is a placeholder for a string that is used to access the file in subsequent operations.</remarks> /// </summary> /// <param name="fileName">The fully qualified name of the new file, or the relative file name. Do not end the path with the directory separator character.</param> /// <param name="pathFormat">Indicates the format of the path parameter(s).</param> public Shell32Info(string fileName, PathFormat pathFormat) { if (Utils.IsNullOrWhiteSpace(fileName)) throw new ArgumentNullException("fileName"); // Shell32 is limited to MAX_PATH length. // Get a full path of regular format. FullPath = Path.GetExtendedLengthPathCore(null, fileName, pathFormat, GetFullPathOptions.RemoveTrailingDirectorySeparator | GetFullPathOptions.FullCheck); Initialize(); } #endregion // Constructors #region Methods #region GetIcon /// <summary>Gets an <see cref="IntPtr"/> handle to the Shell icon that represents the file.</summary> /// <param name="iconAttributes">Icon size <see cref="Shell32.FileAttributes.SmallIcon"/> or <see cref="Shell32.FileAttributes.LargeIcon"/>. Can also be combined with <see cref="Shell32.FileAttributes.AddOverlays"/> and others.</param> /// <returns>An <see cref="IntPtr"/> handle to the Shell icon that represents the file.</returns> /// <remarks>Caller is responsible for destroying this handle with DestroyIcon() when no longer needed.</remarks> [SecurityCritical] public IntPtr GetIcon(Shell32.FileAttributes iconAttributes) { return Shell32.GetFileIcon(FullPath, iconAttributes); } #endregion // GetIcon #region GetVerbCommand /// <summary>Gets the Shell command association from the registry.</summary> /// <param name="shellVerb">The shell verb.</param> /// <returns> /// Returns the associated file- or protocol-related Shell command from the registry or <c>string.Empty</c> if no association can be /// found. /// </returns> [SecurityCritical] public string GetVerbCommand(string shellVerb) { return GetString(_iQaNone, Shell32.AssociationString.Command, shellVerb); } #endregion // GetVerbCommand #region GetString [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] [SecurityCritical] private static string GetString(NativeMethods.IQueryAssociations iQa, Shell32.AssociationString assocString, string shellVerb) { // GetString() throws Exceptions. try { // Use a large buffer to prevent calling this function twice. int size = NativeMethods.DefaultFileBufferSize; var buffer = new StringBuilder(size); iQa.GetString(Shell32.AssociationAttributes.NoTruncate | Shell32.AssociationAttributes.RemapRunDll, assocString, shellVerb, buffer, out size); return buffer.ToString(); } catch { return string.Empty; } } #endregion // GetString #region Initialize private NativeMethods.IQueryAssociations _iQaNone; // Retrieve info from Shell. private NativeMethods.IQueryAssociations _iQaByExe; // Retrieve info from exe file. [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] [SecurityCritical] private void Initialize() { if (Initialized) return; Guid iidIQueryAssociations = new Guid(NativeMethods.QueryAssociationsGuid); if (NativeMethods.AssocCreate(NativeMethods.ClsidQueryAssociations, ref iidIQueryAssociations, out _iQaNone) == Win32Errors.S_OK) { try { _iQaNone.Init(Shell32.AssociationAttributes.None, FullPath, IntPtr.Zero, IntPtr.Zero); if (NativeMethods.AssocCreate(NativeMethods.ClsidQueryAssociations, ref iidIQueryAssociations, out _iQaByExe) == Win32Errors.S_OK) { _iQaByExe.Init(Shell32.AssociationAttributes.InitByExeName, FullPath, IntPtr.Zero, IntPtr.Zero); Initialized = true; } } catch { } } } #endregion // Initialize #region Refresh /// <summary>Refreshes the state of the object.</summary> [SecurityCritical] public void Refresh() { Association = Command = ContentType = DdeApplication = DefaultIcon = FriendlyAppName = FriendlyDocName = OpenWithAppName = null; Attributes = Shell32.GetAttributesOf.None; Initialized = false; Initialize(); } #endregion // Refresh #region ToString /// <summary>Returns the path as a string.</summary> /// <returns>The path.</returns> public override string ToString() { return FullPath; } #endregion // ToString #endregion // Methods #region Properties #region Association private string _association; /// <summary>Gets the Shell file or protocol association from the registry.</summary> public string Association { get { if (_association == null) _association = GetString(_iQaNone, Shell32.AssociationString.Executable, null); return _association; } private set { _association = value; } } #endregion // Association #region Attributes private Shell32.GetAttributesOf _attributes; /// <summary>The attributes of the file object.</summary> public Shell32.GetAttributesOf Attributes { get { if (_attributes == Shell32.GetAttributesOf.None) { Shell32.FileInfo fileInfo = Shell32.GetFileInfoCore(FullPath, FileAttributes.Normal, Shell32.FileAttributes.Attributes, false, true); _attributes = fileInfo.Attributes; } return _attributes; } private set { _attributes = value; } } #endregion // Attributes #region Command private string _command; /// <summary>Gets the Shell command association from the registry.</summary> public string Command { get { if (_command == null) _command = GetString(_iQaNone, Shell32.AssociationString.Command, null); return _command; } private set { _command = value; } } #endregion // Command #region ContentType private string _contentType; /// <summary>Gets the Shell command association from the registry.</summary> public string ContentType { get { if (_contentType == null) _contentType = GetString(_iQaNone, Shell32.AssociationString.ContentType, null); return _contentType; } private set { _contentType = value; } } #endregion // ContentType #region DdeApplication private string _ddeApplication; /// <summary>Gets the Shell DDE association from the registry.</summary> [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Dde")] public string DdeApplication { get { if (_ddeApplication == null) _ddeApplication = GetString(_iQaNone, Shell32.AssociationString.DdeApplication, null); return _ddeApplication; } private set { _ddeApplication = value; } } #endregion // DdeApplication #region DefaultIcon private string _defaultIcon; /// <summary>Gets the Shell default icon association from the registry.</summary> public string DefaultIcon { get { if (_defaultIcon == null) _defaultIcon = GetString(_iQaNone, Shell32.AssociationString.DefaultIcon, null); return _defaultIcon; } private set { _defaultIcon = value; } } #endregion // DefaultIcon #region FullPath /// <summary>Represents the fully qualified path of the file.</summary> public string FullPath { get; private set; } #endregion // FullPath #region FriendlyAppName private string _friendlyAppName; /// <summary>Gets the Shell friendly application name association from the registry.</summary> public string FriendlyAppName { get { if (_friendlyAppName == null) _friendlyAppName = GetString(_iQaByExe, Shell32.AssociationString.FriendlyAppName, null); return _friendlyAppName; } private set { _friendlyAppName = value; } } #endregion // FriendlyAppName #region FriendlyDocName private string _friendlyDocName; /// <summary>Gets the Shell friendly document name association from the registry.</summary> public string FriendlyDocName { get { if (_friendlyDocName == null) _friendlyDocName = GetString(_iQaNone, Shell32.AssociationString.FriendlyDocName, null); return _friendlyDocName; } private set { _friendlyDocName = value; } } #endregion // FriendlyDocName #region Initialized /// <summary>Reflects the initialization state of the instance.</summary> internal bool Initialized { get; set; } #endregion // Initialized #region OpenWithAppName private string _openWithAppName; /// <summary>Gets the Shell "Open With" command association from the registry.</summary> public string OpenWithAppName { get { if (_openWithAppName == null) _openWithAppName = GetString(_iQaNone, Shell32.AssociationString.FriendlyAppName, null); return _openWithAppName; } private set { _openWithAppName = value; } } #endregion // OpenWithAppName #endregion // Properties } }
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 TimeForInsurance.Backend.API.Areas.HelpPage.ModelDescriptions; using TimeForInsurance.Backend.API.Areas.HelpPage.Models; namespace TimeForInsurance.Backend.API.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } // Example: // [TypeConverter(typeof(PointConverter))] // public class Point // { // public Point(int x, int y) // { // X = x; // Y = y; // } // public int X { get; set; } // public int Y { get; set; } // } // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. // // public class Point // { // public int X { get; set; } // public int Y { get; set; } // } // Regular complex class Point will have properties X and Y added to UriParameters collection. if (complexTypeDescription != null && !IsBindableWithTypeConverter(parameterType)) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
//! \file GarExtract.cs //! \date Fri Jul 25 05:52:27 2014 //! \brief Extract archive frontend. // // Copyright (C) 2014-2015 by morkt // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. // using System; using System.IO; using System.Linq; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Windows; using System.Windows.Input; using System.Windows.Media.Imaging; using Ookii.Dialogs.Wpf; using GameRes; using GameRes.Strings; using GARbro.GUI.Strings; using GARbro.GUI.Properties; namespace GARbro.GUI { public partial class MainWindow : Window { /// <summary> /// Handle "Extract item" command. /// </summary> private void ExtractItemExec (object sender, ExecutedRoutedEventArgs e) { var entry = CurrentDirectory.SelectedItem as EntryViewModel; if (null == entry && !ViewModel.IsArchive) { SetStatusText (guiStrings.MsgChooseFiles); return; } GarExtract extractor = null; try { string destination = Settings.Default.appLastDestination; if (!Directory.Exists (destination)) destination = ""; var vm = ViewModel; if (vm.IsArchive) { if (string.IsNullOrEmpty (destination)) destination = Path.GetDirectoryName (vm.Path.First()); var archive_name = vm.Path[vm.Path.Count-2]; extractor = new GarExtract (this, archive_name, VFS.Top as ArchiveFileSystem); if (null == entry || (entry.Name == ".." && string.IsNullOrEmpty (vm.Path.Last()))) // root entry extractor.ExtractAll (destination); else extractor.Extract (entry, destination); } else if (!entry.IsDirectory) { var source = entry.Source.Name; SetBusyState(); if (string.IsNullOrEmpty (destination)) { // extract into directory named after archive if (!string.IsNullOrEmpty (Path.GetExtension (entry.Name))) destination = Path.GetFileNameWithoutExtension (source); else destination = vm.Path.First(); } extractor = new GarExtract (this, source); extractor.ExtractAll (destination); } } catch (OperationCanceledException X) { SetStatusText (X.Message); } catch (Exception X) { PopupError (X.Message, guiStrings.MsgErrorExtracting); } finally { if (null != extractor && !extractor.IsActive) extractor.Dispose(); } } } sealed internal class GarExtract : IDisposable { private MainWindow m_main; private string m_arc_name; private ArchiveFileSystem m_fs; private readonly bool m_should_ascend; private bool m_skip_images = false; private bool m_skip_script = false; private bool m_skip_audio = false; private bool m_adjust_image_offset = false; private bool m_convert_audio; private ImageFormat m_image_format; private int m_extract_count; private bool m_extract_in_progress = false; private ProgressDialog m_progress_dialog; private Exception m_pending_error; public bool IsActive { get { return m_extract_in_progress; } } public GarExtract (MainWindow parent, string source) { m_arc_name = Path.GetFileName (source); try { VFS.ChDir (source); m_should_ascend = true; } catch (Exception X) { throw new OperationCanceledException (string.Format ("{1}: {0}", X.Message, m_arc_name)); } m_fs = VFS.Top as ArchiveFileSystem; m_main = parent; } public GarExtract (MainWindow parent, string source, ArchiveFileSystem fs) { if (null == fs) throw new UnknownFormatException(); m_fs = fs; m_main = parent; m_arc_name = Path.GetFileName (source); m_should_ascend = false; } private void PrepareDestination (string destination) { bool stop_watch = !m_main.ViewModel.IsArchive; if (stop_watch) m_main.StopWatchDirectoryChanges(); try { Directory.CreateDirectory (destination); Directory.SetCurrentDirectory (destination); Settings.Default.appLastDestination = destination; } finally { if (stop_watch) m_main.ResumeWatchDirectoryChanges(); } } public void ExtractAll (string destination) { var file_list = m_fs.GetFilesRecursive(); if (!file_list.Any()) { m_main.SetStatusText (string.Format ("{1}: {0}", guiStrings.MsgEmptyArchive, m_arc_name)); return; } var extractDialog = new ExtractArchiveDialog (m_arc_name, destination); extractDialog.Owner = m_main; var result = extractDialog.ShowDialog(); if (!result.Value) return; destination = extractDialog.Destination; if (!string.IsNullOrEmpty (destination)) { destination = Path.GetFullPath (destination); PrepareDestination (destination); } else destination = "."; m_skip_images = !extractDialog.ExtractImages.IsChecked.Value; m_skip_script = !extractDialog.ExtractText.IsChecked.Value; m_skip_audio = !extractDialog.ExtractAudio.IsChecked.Value; if (!m_skip_images) m_image_format = extractDialog.GetImageFormat (extractDialog.ImageConversionFormat); m_main.SetStatusText (string.Format(guiStrings.MsgExtractingTo, m_arc_name, destination)); ExtractFilesFromArchive (string.Format (guiStrings.MsgExtractingArchive, m_arc_name), file_list); } public void Extract (EntryViewModel entry, string destination) { var view_model = m_main.ViewModel; var selected = m_main.CurrentDirectory.SelectedItems.Cast<EntryViewModel>(); if (!selected.Any() && entry.Name == "..") selected = view_model; IEnumerable<Entry> file_list = selected.Select (e => e.Source); if (m_fs is TreeArchiveFileSystem) file_list = (m_fs as TreeArchiveFileSystem).GetFilesRecursive (file_list); if (!file_list.Any()) { m_main.SetStatusText (guiStrings.MsgChooseFiles); return; } ExtractDialog extractDialog; bool multiple_files = file_list.Skip (1).Any(); if (multiple_files) extractDialog = new ExtractArchiveDialog (m_arc_name, destination); else extractDialog = new ExtractFile (entry, destination); extractDialog.Owner = m_main; var result = extractDialog.ShowDialog(); if (!result.Value) return; if (multiple_files) { m_skip_images = !Settings.Default.appExtractImages; m_skip_script = !Settings.Default.appExtractText; m_skip_audio = !Settings.Default.appExtractAudio; } destination = extractDialog.Destination; if (!string.IsNullOrEmpty (destination)) { destination = Path.GetFullPath (destination); PrepareDestination (destination); } if (!m_skip_images) m_image_format = FormatCatalog.Instance.ImageFormats.FirstOrDefault (f => f.Tag.Equals (Settings.Default.appImageFormat)); ExtractFilesFromArchive (string.Format (guiStrings.MsgExtractingFile, m_arc_name), file_list); } private void ExtractFilesFromArchive (string text, IEnumerable<Entry> file_list) { if (file_list.Skip (1).Any() // file_list.Count() > 1 && (m_skip_images || m_skip_script || m_skip_audio)) file_list = file_list.Where (f => !(m_skip_images && f.Type == "image") && !(m_skip_script && f.Type == "script") && !(m_skip_audio && f.Type == "audio")); if (!file_list.Any()) { m_main.SetStatusText (string.Format ("{1}: {0}", guiStrings.MsgNoFiles, m_arc_name)); return; } file_list = file_list.OrderBy (e => e.Offset); m_progress_dialog = new ProgressDialog () { WindowTitle = guiStrings.TextTitle, Text = text, Description = "", MinimizeBox = true, }; if (!file_list.Skip (1).Any()) // 1 == file_list.Count() { m_progress_dialog.Description = file_list.First().Name; m_progress_dialog.ProgressBarStyle = ProgressBarStyle.MarqueeProgressBar; } m_convert_audio = !m_skip_audio && Settings.Default.appConvertAudio; m_extract_count = 0; m_pending_error = null; m_progress_dialog.DoWork += (s, e) => ExtractWorker (file_list); m_progress_dialog.RunWorkerCompleted += OnExtractComplete; m_progress_dialog.ShowDialog (m_main); m_extract_in_progress = true; } void ExtractWorker (IEnumerable<Entry> file_list) { try { var arc = m_fs.Source; int total = file_list.Count(); foreach (var entry in file_list) { if (m_progress_dialog.CancellationPending) break; if (total > 1) m_progress_dialog.ReportProgress (m_extract_count*100/total, null, entry.Name); if (null != m_image_format && entry.Type == "image") ExtractImage (arc, entry, m_image_format); else if (m_convert_audio && entry.Type == "audio") ExtractAudio (arc, entry); else arc.Extract (entry); ++m_extract_count; } } catch (Exception X) { m_pending_error = X; } } void ExtractImage (ArcFile arc, Entry entry, ImageFormat target_format) { using (var file = arc.OpenSeekableEntry (entry)) { var src_format = ImageFormat.FindFormat (file, entry.Name); if (null == src_format) throw new InvalidFormatException (string.Format ("{1}: {0}", guiStrings.MsgUnableInterpretImage, entry.Name)); file.Position = 0; string target_ext = target_format.Extensions.First(); string outname = FindUniqueFileName (entry.Name, target_ext); if (src_format.Item1 == target_format) { // source format is the same as a target, copy file as is using (var output = ArchiveFormat.CreateFile (outname)) file.CopyTo (output); return; } ImageData image = src_format.Item1.Read (file, src_format.Item2); if (m_adjust_image_offset) { image = AdjustImageOffset (image); } using (var outfile = ArchiveFormat.CreateFile (outname)) { target_format.Write (outfile, image); } } } static ImageData AdjustImageOffset (ImageData image) { if (0 == image.OffsetX && 0 == image.OffsetY) return image; int width = (int)image.Width + image.OffsetX; int height = (int)image.Height + image.OffsetY; if (width <= 0 || height <= 0) return image; int x = Math.Max (image.OffsetX, 0); int y = Math.Max (image.OffsetY, 0); int src_x = image.OffsetX < 0 ? Math.Abs (image.OffsetX) : 0; int src_y = image.OffsetY < 0 ? Math.Abs (image.OffsetY) : 0; int src_stride = (int)image.Width * (image.BPP+7) / 8; int dst_stride = width * (image.BPP+7) / 8; var pixels = new byte[height*dst_stride]; int offset = y * dst_stride + x * image.BPP / 8; Int32Rect rect = new Int32Rect (src_x, src_y, (int)image.Width - src_x, 1); for (int row = src_y; row < image.Height; ++row) { rect.Y = row; image.Bitmap.CopyPixels (rect, pixels, src_stride, offset); offset += dst_stride; } var bitmap = BitmapSource.Create (width, height, image.Bitmap.DpiX, image.Bitmap.DpiY, image.Bitmap.Format, image.Bitmap.Palette, pixels, dst_stride); return new ImageData (bitmap); } static void ExtractAudio (ArcFile arc, Entry entry) { using (var file = arc.OpenEntry (entry)) using (var sound = AudioFormat.Read (file)) { if (null == sound) throw new InvalidFormatException (string.Format ("{1}: {0}", guiStrings.MsgUnableInterpretAudio, entry.Name)); ConvertAudio (entry.Name, sound); } } public static void ConvertAudio (string entry_name, SoundInput input) { string source_format = input.SourceFormat; if (GarConvertMedia.CommonAudioFormats.Contains (source_format)) { string output_name = FindUniqueFileName (entry_name, source_format); using (var output = ArchiveFormat.CreateFile (output_name)) { input.Source.Position = 0; input.Source.CopyTo (output); } } else { string output_name = FindUniqueFileName (entry_name, "wav"); using (var output = ArchiveFormat.CreateFile (output_name)) AudioFormat.Wav.Write (input, output); } } public static string FindUniqueFileName (string source_filename, string target_ext) { string ext = target_ext; for (int attempt = 1; attempt < 100; ++attempt) { string filename = Path.ChangeExtension (source_filename, ext); if (!File.Exists (filename)) return filename; ext = string.Format ("{0}.{1}", attempt, target_ext); } throw new IOException ("File aready exists"); } void OnExtractComplete (object sender, RunWorkerCompletedEventArgs e) { m_extract_in_progress = false; m_progress_dialog.Dispose(); m_main.Activate(); if (!m_main.ViewModel.IsArchive) { m_main.Dispatcher.Invoke (m_main.RefreshView); } m_main.SetStatusText (Localization.Format ("MsgExtractedFiles", m_extract_count)); if (null != m_pending_error) { if (m_pending_error is OperationCanceledException) m_main.SetStatusText (m_pending_error.Message); else { string message = string.Format (guiStrings.TextErrorExtracting, m_progress_dialog.Description, m_pending_error.Message); m_main.PopupError (message, guiStrings.MsgErrorExtracting); } } this.Dispose(); } #region IDisposable Members bool disposed = false; public void Dispose () { if (!disposed) { if (m_should_ascend) { VFS.ChDir (".."); } disposed = true; } GC.SuppressFinalize (this); } #endregion } }
/* ==================================================================== Licensed To the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for Additional information regarding copyright ownership. The ASF licenses this file To You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed To in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ namespace NPOI.SS.Formula { using System; using NPOI.SS.Formula.Eval; /** * Performance optimisation for {@link HSSFFormulaEvaluator}. This class stores previously * calculated values of already visited cells, To avoid unnecessary re-calculation when the * same cells are referenced multiple times * * * @author Josh Micich */ public class EvaluationCache { private PlainCellCache _plainCellCache; private FormulaCellCache _formulaCellCache; /** only used for testing. <c>null</c> otherwise */ IEvaluationListener _evaluationListener; /* package */ public EvaluationCache(IEvaluationListener evaluationListener) { _evaluationListener = evaluationListener; _plainCellCache = new PlainCellCache(); _formulaCellCache = new FormulaCellCache(); } public void NotifyUpdateCell(int bookIndex, int sheetIndex, IEvaluationCell cell) { FormulaCellCacheEntry fcce = _formulaCellCache.Get(cell); int rowIndex = cell.RowIndex; int columnIndex = cell.ColumnIndex; Loc loc = new Loc(bookIndex, sheetIndex, cell.RowIndex, cell.ColumnIndex); PlainValueCellCacheEntry pcce = _plainCellCache.Get(loc); if (cell.CellType == NPOI.SS.UserModel.CellType.Formula) { if (fcce == null) { fcce = new FormulaCellCacheEntry(); if (pcce == null) { if (_evaluationListener != null) { _evaluationListener.OnChangeFromBlankValue(sheetIndex, rowIndex, columnIndex, cell, fcce); } UpdateAnyBlankReferencingFormulas(bookIndex, sheetIndex, rowIndex, columnIndex); } _formulaCellCache.Put(cell, fcce); } else { fcce.RecurseClearCachedFormulaResults(_evaluationListener); fcce.ClearFormulaEntry(); } if (pcce == null) { // was formula cell before - no Change of type } else { // changing from plain cell To formula cell pcce.RecurseClearCachedFormulaResults(_evaluationListener); _plainCellCache.Remove(loc); } } else { ValueEval value = WorkbookEvaluator.GetValueFromNonFormulaCell(cell); if (pcce == null) { if (value != BlankEval.instance) { pcce = new PlainValueCellCacheEntry(value); if (fcce == null) { if (_evaluationListener != null) { _evaluationListener.OnChangeFromBlankValue(sheetIndex, rowIndex, columnIndex, cell, pcce); } UpdateAnyBlankReferencingFormulas(bookIndex, sheetIndex, rowIndex, columnIndex); } _plainCellCache.Put(loc, pcce); } } else { if (pcce.UpdateValue(value)) { pcce.RecurseClearCachedFormulaResults(_evaluationListener); } if (value == BlankEval.instance) { _plainCellCache.Remove(loc); } } if (fcce == null) { // was plain cell before - no Change of type } else { // was formula cell before - now a plain value _formulaCellCache.Remove(cell); fcce.SetSensitiveInputCells(null); fcce.RecurseClearCachedFormulaResults(_evaluationListener); } } } public class EntryOperation : IEntryOperation { BookSheetKey bsk; int rowIndex, columnIndex; IEvaluationListener evaluationListener; public EntryOperation(BookSheetKey bsk, int rowIndex, int columnIndex, IEvaluationListener evaluationListener) { this.bsk = bsk; this.evaluationListener = evaluationListener; this.rowIndex = rowIndex; this.columnIndex = columnIndex; } public void ProcessEntry(FormulaCellCacheEntry entry) { entry.NotifyUpdatedBlankCell(bsk, rowIndex, columnIndex, evaluationListener); } } private void UpdateAnyBlankReferencingFormulas(int bookIndex, int sheetIndex, int rowIndex, int columnIndex) { BookSheetKey bsk = new BookSheetKey(bookIndex, sheetIndex); _formulaCellCache.ApplyOperation(new EntryOperation(bsk,rowIndex,columnIndex,_evaluationListener)); } public PlainValueCellCacheEntry GetPlainValueEntry(int bookIndex, int sheetIndex, int rowIndex, int columnIndex, ValueEval value) { Loc loc = new Loc(bookIndex, sheetIndex, rowIndex, columnIndex); PlainValueCellCacheEntry result = _plainCellCache.Get(loc); if (result == null) { result = new PlainValueCellCacheEntry(value); _plainCellCache.Put(loc, result); if (_evaluationListener != null) { _evaluationListener.OnReadPlainValue(sheetIndex, rowIndex, columnIndex, result); } } else { // TODO - if we are confident that this sanity check is not required, we can Remove 'value' from plain value cache entry if (!AreValuesEqual(result.GetValue(), value)) { throw new InvalidOperationException("value changed"); } if (_evaluationListener != null) { _evaluationListener.OnCacheHit(sheetIndex, rowIndex, columnIndex, value); } } return result; } private bool AreValuesEqual(ValueEval a, ValueEval b) { if (a == null) { return false; } Type cls = a.GetType(); if (cls != b.GetType()) { // value type is changing return false; } if (a == BlankEval.instance) { return b == a; } if (cls == typeof(NumberEval)) { return ((NumberEval)a).NumberValue == ((NumberEval)b).NumberValue; } if (cls == typeof(StringEval)) { return ((StringEval)a).StringValue.Equals(((StringEval)b).StringValue); } if (cls == typeof(BoolEval)) { return ((BoolEval)a).BooleanValue == ((BoolEval)b).BooleanValue; } if (cls == typeof(ErrorEval)) { return ((ErrorEval)a).ErrorCode == ((ErrorEval)b).ErrorCode; } throw new InvalidOperationException("Unexpected value class (" + cls.Name + ")"); } public FormulaCellCacheEntry GetOrCreateFormulaCellEntry(IEvaluationCell cell) { FormulaCellCacheEntry result = _formulaCellCache.Get(cell); if (result == null) { result = new FormulaCellCacheEntry(); _formulaCellCache.Put(cell, result); } return result; } /** * Should be called whenever there are Changes To input cells in the evaluated workbook. */ public void Clear() { if (_evaluationListener != null) { _evaluationListener.OnClearWholeCache(); } _plainCellCache.Clear(); _formulaCellCache.Clear(); } public void NotifyDeleteCell(int bookIndex, int sheetIndex, IEvaluationCell cell) { if (cell.CellType == NPOI.SS.UserModel.CellType.Formula) { FormulaCellCacheEntry fcce = _formulaCellCache.Remove(cell); if (fcce == null) { // formula cell Has not been evaluated yet } else { fcce.SetSensitiveInputCells(null); fcce.RecurseClearCachedFormulaResults(_evaluationListener); } } else { Loc loc = new Loc(bookIndex, sheetIndex, cell.RowIndex, cell.ColumnIndex); PlainValueCellCacheEntry pcce = _plainCellCache.Get(loc); if (pcce == null) { // cache entry doesn't exist. nothing To do } else { pcce.RecurseClearCachedFormulaResults(_evaluationListener); } } } } }
/****************************************************************************** * 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 System; using System.Collections.Generic; using UnityEngine; using UnityEngine.Rendering; using Leap.Unity.Query; using Leap.Unity.Attributes; namespace Leap.Unity.GraphicalRenderer { /// <summary> /// A class that contains mapping information that specifies how a texture /// is packed into an atlas. /// </summary> [Serializable] public class AtlasUvs { [Serializable] public class TextureToRect : SerializableDictionary<UnityEngine.Object, Rect> { } [SerializeField] private TextureToRect _channel0 = new TextureToRect(); [SerializeField] private TextureToRect _channel1 = new TextureToRect(); [SerializeField] private TextureToRect _channel2 = new TextureToRect(); [SerializeField] private TextureToRect _channel3 = new TextureToRect(); [SerializeField] private Rect[] _nullRects = new Rect[4]; /// <summary> /// Given a texture object and a uv channel, return the rect that /// this texture occupies within the atlas. If the key is not /// present in the atlas, the default rect is returned. If a null /// texture is passed in, the rect for the empty texture (which is valid!) /// is returned. /// </summary> public Rect GetRect(int channel, UnityEngine.Object key) { if (key == null) { return _nullRects[channel]; } else { Rect r; getChannel(channel).TryGetValue(key, out r); return r; } } /// <summary> /// Given a texture object and a uv channel, store into this data /// structure the rect that the texture takes up inside of the atlas. /// A null texture object is valid, and represents the empty texture. /// </summary> public void SetRect(int channel, UnityEngine.Object key, Rect rect) { if (key == null) { _nullRects[channel] = rect; } else { getChannel(channel)[key] = rect; } } private TextureToRect getChannel(int channel) { switch (channel) { case 0: return _channel0; case 1: return _channel1; case 2: return _channel2; case 3: return _channel3; default: throw new Exception(); } } } [Serializable] public class AtlasBuilder { [Tooltip("When non-zero, extends each texture by a certain number of pixels, filling in the space with texture data based on the texture wrap mode.")] [MinValue(0)] [EditTimeOnly, SerializeField] private int _border = 0; [Tooltip("When non-zero, adds an amount of empty space between each texture.")] [MinValue(0)] [EditTimeOnly, SerializeField] private int _padding = 0; [Tooltip("Should the atlas have mip maps?")] [EditTimeOnly, SerializeField] private bool _mipMap = true; [Tooltip("The filter mode that should be used for the atlas.")] [EditTimeOnly, SerializeField] private FilterMode _filterMode = FilterMode.Bilinear; [Tooltip("The texture format that should be used for the atlas.")] [EditTimeOnly, SerializeField] private TextureFormat _format = TextureFormat.ARGB32; [Tooltip("The maximum atlas size in pixels.")] [MinValue(16)] [MaxValue(8192)] [EditTimeOnly, SerializeField] private int _maxAtlasSize = 4096; [Tooltip("Add textures to this array to ensure that they are always present in the atlas.")] [SerializeField] private TextureReference[] _extraTextures; /// <summary> /// Returns whether or not the results built by this atlas have become invalid. /// </summary> public bool isDirty { get { return _currHash != _atlasHash; } } private static Material _cachedBlitMaterial = null; private static void enableBlitPass(Texture tex) { if (_cachedBlitMaterial == null) { _cachedBlitMaterial = new Material(Shader.Find("Hidden/Leap Motion/Graphic Renderer/InternalPack")); _cachedBlitMaterial.hideFlags = HideFlags.HideAndDontSave; } _cachedBlitMaterial.mainTexture = tex; _cachedBlitMaterial.SetPass(0); } private List<LeapTextureFeature> _features = new List<LeapTextureFeature>(); private Hash _atlasHash = 1; private Hash _currHash = 0; /// <summary> /// Updates the internal list of textures given some texture features to build an atlas for. /// This method does not do any atlas work, but must be called before RebuildAtlas is called. /// Once this method is called, you can check the isDirty flag to see if a rebuild is needed. /// </summary> public void UpdateTextureList(List<LeapTextureFeature> textureFeatures) { _features.Clear(); _features.AddRange(textureFeatures); _currHash = new Hash() { _border, _padding, _mipMap, _filterMode, _format, _maxAtlasSize }; if (_extraTextures == null) { _extraTextures = new TextureReference[0]; } for (int i = 0; i < _extraTextures.Length; i++) { switch (_extraTextures[i].channel) { case UVChannelFlags.UV0: case UVChannelFlags.UV1: case UVChannelFlags.UV2: case UVChannelFlags.UV3: break; default: _extraTextures[i].channel = UVChannelFlags.UV0; break; } } foreach (var extra in _extraTextures) { _currHash.Add(extra.texture); _currHash.Add(extra.channel); } foreach (var feature in _features) { _currHash.Add(feature.channel); foreach (var dataObj in feature.featureData) { _currHash.Add(dataObj.texture); } } } /// <summary> /// Actually perform the build for the atlas. This method outputs the atlas textures, and the atlas /// uvs that map textures into the atlas. This method takes in a progress bar so that the atlas /// process can be tracked visually, since it can take quite a bit of time when there are a lot of /// textures to pack. /// </summary> public void RebuildAtlas(ProgressBar progress, out Texture2D[] packedTextures, out AtlasUvs channelMapping) { if (!Utils.IsCompressible(_format)) { Debug.LogWarning("Format " + _format + " is not compressible! Using ARGB32 instead."); _format = TextureFormat.ARGB32; } _atlasHash = _currHash; packedTextures = new Texture2D[_features.Count]; channelMapping = new AtlasUvs(); mainProgressLoop(progress, packedTextures, channelMapping); //Clear cache foreach (var texture in _cachedProcessedTextures.Values) { UnityEngine.Object.DestroyImmediate(texture); } _cachedProcessedTextures.Clear(); foreach (var texture in _cachedDefaultTextures.Values) { UnityEngine.Object.DestroyImmediate(texture); } _cachedDefaultTextures.Clear(); } private void mainProgressLoop(ProgressBar progress, Texture2D[] packedTextures, AtlasUvs channelMapping) { progress.Begin(5, "", "", () => { foreach (var channel in MeshUtil.allUvChannels) { progress.Begin(1, "", channel + ": ", () => { doPerChannelPack(progress, channel, packedTextures, channelMapping); }); } finalizeTextures(progress, packedTextures); }); } private void doPerChannelPack(ProgressBar progress, UVChannelFlags channel, Texture2D[] packedTextures, AtlasUvs channelMapping) { var mainTextureFeature = _features.Query().FirstOrDefault(f => f.channel == channel); if (mainTextureFeature == null) return; Texture2D defaultTexture, packedTexture; Texture2D[] rawTextureArray, processedTextureArray; progress.Step("Prepare " + channel); prepareForPacking(mainTextureFeature, out defaultTexture, out packedTexture, out rawTextureArray, out processedTextureArray); progress.Step("Pack " + channel); var packedRects = packedTexture.PackTextures(processedTextureArray, _padding, _maxAtlasSize, makeNoLongerReadable: false); packedTexture.Apply(updateMipmaps: true, makeNoLongerReadable: true); packedTextures[_features.IndexOf(mainTextureFeature)] = packedTexture; packSecondaryTextures(progress, channel, mainTextureFeature, packedTexture, packedRects, packedTextures); //Correct uvs to account for the added border for (int i = 0; i < packedRects.Length; i++) { float dx = 1.0f / packedTexture.width; float dy = 1.0f / packedTexture.height; Rect r = packedRects[i]; if (processedTextureArray[i] != defaultTexture) { dx *= _border; dy *= _border; } r.x += dx; r.y += dy; r.width -= dx * 2; r.height -= dy * 2; packedRects[i] = r; } for (int i = 0; i < rawTextureArray.Length; i++) { channelMapping.SetRect(channel.Index(), rawTextureArray[i], packedRects[i]); } } private void packSecondaryTextures(ProgressBar progress, UVChannelFlags channel, LeapTextureFeature mainFeature, Texture2D packedTexture, Rect[] packedRects, Texture2D[] packedTextures) { //All texture features that are NOT the main texture do not get their own atlas step //They are simply copied into a new texture var nonMainFeatures = _features.Query().Where(f => f.channel == channel).Skip(1).ToList(); progress.Begin(nonMainFeatures.Count, "", "Copying secondary textures: ", () => { foreach (var secondaryFeature in nonMainFeatures) { RenderTexture secondaryRT = new RenderTexture(packedTexture.width, packedTexture.height, 0, RenderTextureFormat.ARGB32, RenderTextureReadWrite.Linear); RenderTexture.active = secondaryRT; GL.Clear(clearDepth: false, clearColor: true, backgroundColor: Color.black); GL.LoadPixelMatrix(0, 1, 0, 1); progress.Begin(secondaryFeature.featureData.Count, "", secondaryFeature.propertyName, () => { for (int i = 0; i < secondaryFeature.featureData.Count; i++) { var mainTexture = mainFeature.featureData[i].texture; if (mainTexture == null) { progress.Step(); continue; } var secondaryTexture = secondaryFeature.featureData[i].texture; if (secondaryTexture == null) { progress.Step(); continue; } progress.Step(secondaryTexture.name); Rect rect = packedRects[i]; //Use mainTexture instead of secondaryTexture here to calculate correct border to line up with main texture float borderDX = _border / (float)mainTexture.width; float borderDY = _border / (float)mainTexture.height; drawTexture(secondaryTexture, secondaryRT, rect, borderDX, borderDY); } }); packedTextures[_features.IndexOf(secondaryFeature)] = convertToTexture2D(secondaryRT, mipmap: false); } }); } private void finalizeTextures(ProgressBar progress, Texture2D[] packedTextures) { progress.Begin(packedTextures.Length, "", "Finalizing ", () => { for (int i = 0; i < packedTextures.Length; i++) { progress.Begin(2, "", _features[i].propertyName + ": ", () => { Texture2D tex = packedTextures[i]; RenderTexture rt = new RenderTexture(tex.width, tex.height, 0, RenderTextureFormat.ARGB32, RenderTextureReadWrite.Linear); GL.LoadPixelMatrix(0, 1, 0, 1); drawTexture(tex, rt, new Rect(0, 0, 1, 1), 0, 0); progress.Step("Copying Texture"); tex = convertToTexture2D(rt, _mipMap); progress.Step("Compressing Texture"); #if UNITY_EDITOR UnityEditor.EditorUtility.CompressTexture(tex, _format, TextureCompressionQuality.Best); #endif tex.filterMode = _filterMode; progress.Step("Updating Texture"); //keep the texture as readable because the user might want to do things with the texture! tex.Apply(updateMipmaps: true, makeNoLongerReadable: false); packedTextures[i] = tex; }); } }); } private void prepareForPacking(LeapTextureFeature feature, out Texture2D defaultTexture, out Texture2D packedTexture, out Texture2D[] rawTextureArray, out Texture2D[] processedTextureArray) { if (_extraTextures == null) { _extraTextures = new TextureReference[0]; } rawTextureArray = feature.featureData.Query(). Select(dataObj => dataObj.texture). Concat(_extraTextures.Query(). Where(p => p.channel == feature.channel). Select(p => p.texture)). ToArray(); processedTextureArray = rawTextureArray.Query(). Select(t => processTexture(t)). ToArray(); defaultTexture = getDefaultTexture(Color.white); //TODO, pull color from feature data for (int i = 0; i < processedTextureArray.Length; i++) { if (processedTextureArray[i] == null) { processedTextureArray[i] = defaultTexture; } } packedTexture = new Texture2D(1, 1, TextureFormat.ARGB32, mipmap: false, linear: true); packedTexture.filterMode = _filterMode; } private Dictionary<Texture2D, Texture2D> _cachedProcessedTextures = new Dictionary<Texture2D, Texture2D>(); private Texture2D processTexture(Texture2D source) { using (new ProfilerSample("Process Texture")) { if (source == null) { return null; } Texture2D processed; if (_cachedProcessedTextures.TryGetValue(source, out processed)) { return processed; } RenderTexture destRT = new RenderTexture(source.width + _border * 2, source.height + _border * 2, 0, RenderTextureFormat.ARGB32, RenderTextureReadWrite.Linear); GL.LoadPixelMatrix(0, 1, 0, 1); drawTexture(source, destRT, new Rect(0, 0, 1, 1), _border / (float)source.width, _border / (float)source.height); processed = convertToTexture2D(destRT, mipmap: false); _cachedProcessedTextures[source] = processed; return processed; } } private void drawTexture(Texture2D source, RenderTexture dst, Rect rect, float borderDX, float borderDY) { enableBlitPass(source); RenderTexture.active = dst; GL.Begin(GL.QUADS); GL.TexCoord(new Vector2(0 - borderDX, 0 - borderDY)); GL.Vertex(rect.Corner00()); GL.TexCoord(new Vector2(1 + borderDX, 0 - borderDY)); GL.Vertex(rect.Corner10()); GL.TexCoord(new Vector2(1 + borderDX, 1 + borderDY)); GL.Vertex(rect.Corner11()); GL.TexCoord(new Vector2(0 - borderDX, 1 + borderDY)); GL.Vertex(rect.Corner01()); GL.End(); } private Texture2D convertToTexture2D(RenderTexture source, bool mipmap) { Texture2D tex = new Texture2D(source.width, source.height, TextureFormat.ARGB32, mipmap, linear: true); RenderTexture.active = source; tex.ReadPixels(new Rect(0, 0, tex.width, tex.height), 0, 0); tex.Apply(updateMipmaps: false, makeNoLongerReadable: false); RenderTexture.active = null; source.Release(); UnityEngine.Object.DestroyImmediate(source); return tex; } private Dictionary<Color, Texture2D> _cachedDefaultTextures = new Dictionary<Color, Texture2D>(); private Texture2D getDefaultTexture(Color color) { Texture2D texture; if (!_cachedDefaultTextures.TryGetValue(color, out texture)) { texture = new Texture2D(3, 3, TextureFormat.ARGB32, mipmap: false); texture.SetPixels(new Color[3 * 3].Fill(color)); _cachedDefaultTextures[color] = texture; } return texture; } [Serializable] public class TextureReference { public Texture2D texture; public UVChannelFlags channel = UVChannelFlags.UV0; } } }
//----------------------------------------------------------------------- // <copyright file="Timed.cs" company="Akka.NET Project"> // Copyright (C) 2015-2016 Lightbend Inc. <http://www.lightbend.com> // Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net> // </copyright> //----------------------------------------------------------------------- using System; using System.Diagnostics; using Akka.Streams.Dsl; using Akka.Streams.Implementation.Fusing; using Akka.Streams.Stage; using static Akka.Streams.Extra.Timed; namespace Akka.Streams.Extra { /// <summary> /// INTERNAL API /// /// Provides operations needed to implement the <see cref="TimedFlowDsl"/> and <see cref="TimedSourceDsl"/> /// </summary> internal static class TimedOps { /// <summary> /// INTERNAL API /// /// Measures time from receiving the first element and completion events - one for each subscriber of this <see cref="IFlow{TOut,TMat}"/>. /// </summary> /// <typeparam name="TIn">TBD</typeparam> /// <typeparam name="TOut">TBD</typeparam> /// <typeparam name="TMat">TBD</typeparam> /// <typeparam name="TMat2">TBD</typeparam> /// <param name="source">TBD</param> /// <param name="measuredOps">TBD</param> /// <param name="onComplete">TBD</param> /// <returns>TBD</returns> public static Source<TOut, TMat2> Timed<TIn, TOut, TMat, TMat2>(Source<TIn, TMat> source, Func<Source<TIn, TMat>, Source<TOut, TMat2>> measuredOps, Action<TimeSpan> onComplete) { var ctx = new TimedFlowContext(); var startTimed = Flow.Create<TIn>().Via(new StartTimed<TIn>(ctx)).Named("startTimed"); var stopTimed = Flow.Create<TOut>().Via(new StopTime<TOut>(ctx, onComplete)).Named("stopTimed"); return measuredOps(source.Via(startTimed)).Via(stopTimed); } /// <summary> /// INTERNAL API /// /// Measures time from receiving the first element and completion events - one for each subscriber of this <see cref="IFlow{TOut,TMat}"/>. /// </summary> /// <typeparam name="TIn">TBD</typeparam> /// <typeparam name="TOut">TBD</typeparam> /// <typeparam name="TOut2">TBD</typeparam> /// <typeparam name="TMat">TBD</typeparam> /// <typeparam name="TMat2">TBD</typeparam> /// <param name="flow">TBD</param> /// <param name="measuredOps">TBD</param> /// <param name="onComplete">TBD</param> /// <returns>TBD</returns> public static Flow<TIn, TOut2, TMat2> Timed<TIn, TOut, TOut2, TMat, TMat2>(Flow<TIn, TOut, TMat> flow, Func<Flow<TIn, TOut, TMat>, Flow<TIn, TOut2, TMat2>> measuredOps, Action<TimeSpan> onComplete) { // todo is there any other way to provide this for Flow, without duplicating impl? // they do share a super-type (FlowOps), but all operations of FlowOps return path dependant type var ctx = new TimedFlowContext(); var startTimed = Flow.Create<TOut>().Via(new StartTimed<TOut>(ctx)).Named("startTimed"); var stopTimed = Flow.Create<TOut2>().Via(new StopTime<TOut2>(ctx, onComplete)).Named("stopTimed"); return measuredOps(flow.Via(startTimed)).Via(stopTimed); } } /// <summary> /// INTERNAL API /// /// Provides operations needed to implement the <see cref="TimedFlowDsl"/> and <see cref="TimedSourceDsl"/> /// </summary> internal static class TimedIntervalBetweenOps { /// <summary> /// INTERNAL API /// /// Measures rolling interval between immediately subsequent `matching(o: O)` elements. /// </summary> /// <typeparam name="TIn">TBD</typeparam> /// <typeparam name="TMat">TBD</typeparam> /// <param name="flow">TBD</param> /// <param name="matching">TBD</param> /// <param name="onInterval">TBD</param> /// <returns>TBD</returns> public static IFlow<TIn, TMat> TimedIntervalBetween<TIn, TMat>(IFlow<TIn, TMat> flow, Func<TIn, bool> matching, Action<TimeSpan> onInterval) { var timedInterval = Flow.Create<TIn>() .Via(new TimedIntervall<TIn>(matching, onInterval)) .Named("timedInterval"); return flow.Via(timedInterval); } } /// <summary> /// TBD /// </summary> internal static class Timed { /// <summary> /// TBD /// </summary> internal sealed class TimedFlowContext { private readonly Stopwatch _stopwatch = new Stopwatch(); /// <summary> /// TBD /// </summary> public void Start() => _stopwatch.Start(); /// <summary> /// TBD /// </summary> /// <returns>TBD</returns> public TimeSpan Stop() { _stopwatch.Stop(); return _stopwatch.Elapsed; } } /// <summary> /// TBD /// </summary> /// <typeparam name="T">TBD</typeparam> internal sealed class StartTimed<T> : SimpleLinearGraphStage<T> { #region Loigc private sealed class Logic : InAndOutGraphStageLogic { private readonly StartTimed<T> _stage; private bool _started; public Logic(StartTimed<T> stage) : base(stage.Shape) { _stage = stage; SetHandler(stage.Outlet, this); SetHandler(stage.Inlet, this); } public override void OnPush() { if (!_started) { _stage._timedContext.Start(); _started = true; } Push(_stage.Outlet, Grab(_stage.Inlet)); } public override void OnPull() => Pull(_stage.Inlet); } #endregion private readonly TimedFlowContext _timedContext; /// <summary> /// TBD /// </summary> /// <param name="timedContext">TBD</param> public StartTimed(TimedFlowContext timedContext) { _timedContext = timedContext; } /// <summary> /// TBD /// </summary> /// <param name="inheritedAttributes">TBD</param> /// <returns>TBD</returns> protected override GraphStageLogic CreateLogic(Attributes inheritedAttributes) => new Logic(this); } /// <summary> /// TBD /// </summary> /// <typeparam name="T">TBD</typeparam> internal sealed class StopTime<T> : SimpleLinearGraphStage<T> { #region Loigc private sealed class Logic : InAndOutGraphStageLogic { private readonly StopTime<T> _stage; public Logic(StopTime<T> stage) : base(stage.Shape) { _stage = stage; SetHandler(stage.Outlet, this); SetHandler(stage.Inlet, this); } public override void OnPush() => Push(_stage.Outlet, Grab(_stage.Inlet)); public override void OnUpstreamFinish() { StopTime(); CompleteStage(); } public override void OnUpstreamFailure(Exception e) { StopTime(); FailStage(e); } public override void OnPull() => Pull(_stage.Inlet); private void StopTime() { var d = _stage._timedContext.Stop(); _stage._onComplete(d); } } #endregion private readonly TimedFlowContext _timedContext; private readonly Action<TimeSpan> _onComplete; /// <summary> /// TBD /// </summary> /// <param name="timedContext">TBD</param> /// <param name="onComplete">TBD</param> public StopTime(TimedFlowContext timedContext, Action<TimeSpan> onComplete) { _timedContext = timedContext; _onComplete = onComplete; } /// <summary> /// TBD /// </summary> /// <param name="inheritedAttributes">TBD</param> /// <returns>TBD</returns> protected override GraphStageLogic CreateLogic(Attributes inheritedAttributes) => new Logic(this); } /// <summary> /// TBD /// </summary> /// <typeparam name="T">TBD</typeparam> internal sealed class TimedIntervall<T> : SimpleLinearGraphStage<T> { #region Loigc private sealed class Logic : InAndOutGraphStageLogic { private readonly TimedIntervall<T> _stage; private long _previousTicks; private long _matched; public Logic(TimedIntervall<T> stage) : base(stage.Shape) { _stage = stage; SetHandler(stage.Outlet, this); SetHandler(stage.Inlet, this); } public override void OnPush() { var element = Grab(_stage.Inlet); if (_stage._matching(element)) { var d = UpdateInterval(); if (_matched > 1) _stage._onInterval(d); } Push(_stage.Outlet, element); } public override void OnPull() => Pull(_stage.Inlet); private TimeSpan UpdateInterval() { _matched += 1; var nowTicks = DateTime.Now.Ticks; var d = nowTicks - _previousTicks; _previousTicks = nowTicks; return TimeSpan.FromTicks(d); } } #endregion private readonly Func<T, bool> _matching; private readonly Action<TimeSpan> _onInterval; /// <summary> /// TBD /// </summary> /// <param name="matching">TBD</param> /// <param name="onInterval">TBD</param> public TimedIntervall(Func<T, bool> matching, Action<TimeSpan> onInterval) { _matching = matching; _onInterval = onInterval; } /// <summary> /// TBD /// </summary> /// <param name="inheritedAttributes">TBD</param> /// <returns>TBD</returns> protected override GraphStageLogic CreateLogic(Attributes inheritedAttributes) => new Logic(this); } } }
//---------------------------------------------------------------------------- // Anti-Grain Geometry - Version 2.4 // Copyright (C) 2002-2005 Maxim Shemanarev (http://www.antigrain.com) // // C# Port port by: Lars Brubaker // larsbrubaker@gmail.com // Copyright (C) 2007 // // Permission to copy, use, modify, sell and distribute this software // is granted provided this copyright notice appears in all copies. // This software is provided "as is" without express or implied // warranty, and with no claim as to its suitability for any purpose. // //---------------------------------------------------------------------------- // Contact: mcseem@antigrain.com // mcseemagg@yahoo.com // http://www.antigrain.com //---------------------------------------------------------------------------- // // Adaptation for high precision colors has been sponsored by // Liberty Technology Systems, Inc., visit http://lib-sys.com // // Liberty Technology Systems, Inc. is the provider of // PostScript and PDF technology for software developers. // //---------------------------------------------------------------------------- #define USE_UNSAFE_CODE using MatterHackers.Agg.Image; using MatterHackers.VectorMath; using System; using image_filter_scale_e = MatterHackers.Agg.ImageFilterLookUpTable.image_filter_scale_e; using image_subpixel_scale_e = MatterHackers.Agg.ImageFilterLookUpTable.image_subpixel_scale_e; namespace MatterHackers.Agg { // it should be easy to write a 90 rotating or mirroring filter too. LBB 2012/01/14 public class span_image_filter_rgba_nn_stepXby1 : span_image_filter { private const int base_shift = 8; private const int base_scale = (int)(1 << base_shift); private const int base_mask = base_scale - 1; public span_image_filter_rgba_nn_stepXby1(IImageBufferAccessor sourceAccessor, ISpanInterpolator spanInterpolator) : base(sourceAccessor, spanInterpolator, null) { } public override void generate(RGBA_Bytes[] span, int spanIndex, int x, int y, int len) { ImageBuffer SourceRenderingBuffer = (ImageBuffer)GetImageBufferAccessor().SourceImage; if (SourceRenderingBuffer.BitDepth != 32) { throw new NotSupportedException("The source is expected to be 32 bit."); } ISpanInterpolator spanInterpolator = interpolator(); spanInterpolator.begin(x + filter_dx_dbl(), y + filter_dy_dbl(), len); int x_hr; int y_hr; spanInterpolator.coordinates(out x_hr, out y_hr); int x_lr = x_hr >> (int)image_subpixel_scale_e.image_subpixel_shift; int y_lr = y_hr >> (int)image_subpixel_scale_e.image_subpixel_shift; int bufferIndex; bufferIndex = SourceRenderingBuffer.GetBufferOffsetXY(x_lr, y_lr); byte[] fg_ptr = SourceRenderingBuffer.GetBuffer(); #if USE_UNSAFE_CODE unsafe { fixed (byte* pSource = fg_ptr) { do { span[spanIndex++] = *(RGBA_Bytes*)&(pSource[bufferIndex]); bufferIndex += 4; } while (--len != 0); } } #else RGBA_Bytes color = new RGBA_Bytes(); do { color.blue = fg_ptr[bufferIndex++]; color.green = fg_ptr[bufferIndex++]; color.red = fg_ptr[bufferIndex++]; color.alpha = fg_ptr[bufferIndex++]; span[spanIndex++] = color; } while (--len != 0); #endif } } //==============================================span_image_filter_rgba_nn public class span_image_filter_rgba_nn : span_image_filter { private const int baseShift = 8; private const int baseScale = (int)(1 << baseShift); private const int baseMask = baseScale - 1; public span_image_filter_rgba_nn(IImageBufferAccessor sourceAccessor, ISpanInterpolator spanInterpolator) : base(sourceAccessor, spanInterpolator, null) { } public override void generate(RGBA_Bytes[] span, int spanIndex, int x, int y, int len) { ImageBuffer SourceRenderingBuffer = (ImageBuffer)GetImageBufferAccessor().SourceImage; if (SourceRenderingBuffer.BitDepth != 32) { throw new NotSupportedException("The source is expected to be 32 bit."); } ISpanInterpolator spanInterpolator = interpolator(); spanInterpolator.begin(x + filter_dx_dbl(), y + filter_dy_dbl(), len); byte[] fg_ptr = SourceRenderingBuffer.GetBuffer(); do { int x_hr; int y_hr; spanInterpolator.coordinates(out x_hr, out y_hr); int x_lr = x_hr >> (int)image_subpixel_scale_e.image_subpixel_shift; int y_lr = y_hr >> (int)image_subpixel_scale_e.image_subpixel_shift; int bufferIndex; bufferIndex = SourceRenderingBuffer.GetBufferOffsetXY(x_lr, y_lr); RGBA_Bytes color; color.blue = fg_ptr[bufferIndex++]; color.green = fg_ptr[bufferIndex++]; color.red = fg_ptr[bufferIndex++]; color.alpha = fg_ptr[bufferIndex++]; span[spanIndex] = color; spanIndex++; spanInterpolator.Next(); } while (--len != 0); } }; public class span_image_filter_rgba_bilinear : span_image_filter { private const int base_shift = 8; private const int base_scale = (int)(1 << base_shift); private const int base_mask = base_scale - 1; public span_image_filter_rgba_bilinear(IImageBufferAccessor src, ISpanInterpolator inter) : base(src, inter, null) { } #if false public void generate(out RGBA_Bytes destPixel, int x, int y) { base.interpolator().begin(x + base.filter_dx_dbl(), y + base.filter_dy_dbl(), 1); int* fg = stackalloc int[4]; byte* fg_ptr; IImage imageSource = base.source().DestImage; int maxx = (int)imageSource.Width() - 1; int maxy = (int)imageSource.Height() - 1; ISpanInterpolator spanInterpolator = base.interpolator(); unchecked { int x_hr; int y_hr; spanInterpolator.coordinates(out x_hr, out y_hr); x_hr -= base.filter_dx_int(); y_hr -= base.filter_dy_int(); int x_lr = x_hr >> (int)image_subpixel_scale_e.image_subpixel_shift; int y_lr = y_hr >> (int)image_subpixel_scale_e.image_subpixel_shift; int weight; fg[0] = fg[1] = fg[2] = fg[3] = (int)image_subpixel_scale_e.image_subpixel_scale * (int)image_subpixel_scale_e.image_subpixel_scale / 2; x_hr &= (int)image_subpixel_scale_e.image_subpixel_mask; y_hr &= (int)image_subpixel_scale_e.image_subpixel_mask; fg_ptr = imageSource.GetPixelPointerY(y_lr) + (x_lr * 4); weight = (int)(((int)image_subpixel_scale_e.image_subpixel_scale - x_hr) * ((int)image_subpixel_scale_e.image_subpixel_scale - y_hr)); fg[0] += weight * fg_ptr[0]; fg[1] += weight * fg_ptr[1]; fg[2] += weight * fg_ptr[2]; fg[3] += weight * fg_ptr[3]; weight = (int)(x_hr * ((int)image_subpixel_scale_e.image_subpixel_scale - y_hr)); fg[0] += weight * fg_ptr[4]; fg[1] += weight * fg_ptr[5]; fg[2] += weight * fg_ptr[6]; fg[3] += weight * fg_ptr[7]; ++y_lr; fg_ptr = imageSource.GetPixelPointerY(y_lr) + (x_lr * 4); weight = (int)(((int)image_subpixel_scale_e.image_subpixel_scale - x_hr) * y_hr); fg[0] += weight * fg_ptr[0]; fg[1] += weight * fg_ptr[1]; fg[2] += weight * fg_ptr[2]; fg[3] += weight * fg_ptr[3]; weight = (int)(x_hr * y_hr); fg[0] += weight * fg_ptr[4]; fg[1] += weight * fg_ptr[5]; fg[2] += weight * fg_ptr[6]; fg[3] += weight * fg_ptr[7]; fg[0] >>= (int)image_subpixel_scale_e.image_subpixel_shift * 2; fg[1] >>= (int)image_subpixel_scale_e.image_subpixel_shift * 2; fg[2] >>= (int)image_subpixel_scale_e.image_subpixel_shift * 2; fg[3] >>= (int)image_subpixel_scale_e.image_subpixel_shift * 2; destPixel.m_R = (byte)fg[OrderR]; destPixel.m_G = (byte)fg[OrderG]; destPixel.m_B = (byte)fg[ImageBuffer.OrderB]; destPixel.m_A = (byte)fg[OrderA]; } } #endif public override void generate(RGBA_Bytes[] span, int spanIndex, int x, int y, int len) { base.interpolator().begin(x + base.filter_dx_dbl(), y + base.filter_dy_dbl(), len); ImageBuffer SourceRenderingBuffer = (ImageBuffer)base.GetImageBufferAccessor().SourceImage; ISpanInterpolator spanInterpolator = base.interpolator(); int bufferIndex; byte[] fg_ptr = SourceRenderingBuffer.GetBuffer(out bufferIndex); unchecked { do { int tempR; int tempG; int tempB; int tempA; int x_hr; int y_hr; spanInterpolator.coordinates(out x_hr, out y_hr); x_hr -= base.filter_dx_int(); y_hr -= base.filter_dy_int(); int x_lr = x_hr >> (int)image_subpixel_scale_e.image_subpixel_shift; int y_lr = y_hr >> (int)image_subpixel_scale_e.image_subpixel_shift; int weight; tempR = tempG = tempB = tempA = (int)image_subpixel_scale_e.image_subpixel_scale * (int)image_subpixel_scale_e.image_subpixel_scale / 2; x_hr &= (int)image_subpixel_scale_e.image_subpixel_mask; y_hr &= (int)image_subpixel_scale_e.image_subpixel_mask; bufferIndex = SourceRenderingBuffer.GetBufferOffsetXY(x_lr, y_lr); weight = (((int)image_subpixel_scale_e.image_subpixel_scale - x_hr) * ((int)image_subpixel_scale_e.image_subpixel_scale - y_hr)); tempR += weight * fg_ptr[bufferIndex + ImageBuffer.OrderR]; tempG += weight * fg_ptr[bufferIndex + ImageBuffer.OrderG]; tempB += weight * fg_ptr[bufferIndex + ImageBuffer.OrderB]; tempA += weight * fg_ptr[bufferIndex + ImageBuffer.OrderA]; bufferIndex += 4; weight = (x_hr * ((int)image_subpixel_scale_e.image_subpixel_scale - y_hr)); tempR += weight * fg_ptr[bufferIndex + ImageBuffer.OrderR]; tempG += weight * fg_ptr[bufferIndex + ImageBuffer.OrderG]; tempB += weight * fg_ptr[bufferIndex + ImageBuffer.OrderB]; tempA += weight * fg_ptr[bufferIndex + ImageBuffer.OrderA]; y_lr++; bufferIndex = SourceRenderingBuffer.GetBufferOffsetXY(x_lr, y_lr); weight = (((int)image_subpixel_scale_e.image_subpixel_scale - x_hr) * y_hr); tempR += weight * fg_ptr[bufferIndex + ImageBuffer.OrderR]; tempG += weight * fg_ptr[bufferIndex + ImageBuffer.OrderG]; tempB += weight * fg_ptr[bufferIndex + ImageBuffer.OrderB]; tempA += weight * fg_ptr[bufferIndex + ImageBuffer.OrderA]; bufferIndex += 4; weight = (x_hr * y_hr); tempR += weight * fg_ptr[bufferIndex + ImageBuffer.OrderR]; tempG += weight * fg_ptr[bufferIndex + ImageBuffer.OrderG]; tempB += weight * fg_ptr[bufferIndex + ImageBuffer.OrderB]; tempA += weight * fg_ptr[bufferIndex + ImageBuffer.OrderA]; tempR >>= (int)image_subpixel_scale_e.image_subpixel_shift * 2; tempG >>= (int)image_subpixel_scale_e.image_subpixel_shift * 2; tempB >>= (int)image_subpixel_scale_e.image_subpixel_shift * 2; tempA >>= (int)image_subpixel_scale_e.image_subpixel_shift * 2; RGBA_Bytes color; color.red = (byte)tempR; color.green = (byte)tempG; color.blue = (byte)tempB; color.alpha = (byte)255;// tempA; span[spanIndex] = color; spanIndex++; spanInterpolator.Next(); } while (--len != 0); } } } public class span_image_filter_rgba_bilinear_float : span_image_filter_float { public span_image_filter_rgba_bilinear_float(IImageBufferAccessorFloat src, ISpanInterpolatorFloat inter) : base(src, inter, null) { } public override void generate(RGBA_Floats[] span, int spanIndex, int x, int y, int len) { base.interpolator().begin(x + base.filter_dx_dbl(), y + base.filter_dy_dbl(), len); ImageBufferFloat SourceRenderingBuffer = (ImageBufferFloat)base.source().SourceImage; ISpanInterpolatorFloat spanInterpolator = base.interpolator(); int bufferIndex; float[] fg_ptr = SourceRenderingBuffer.GetBuffer(out bufferIndex); unchecked { do { float tempR; float tempG; float tempB; float tempA; float x_hr; float y_hr; spanInterpolator.coordinates(out x_hr, out y_hr); x_hr -= base.filter_dx_dbl(); y_hr -= base.filter_dy_dbl(); int x_lr = (int)x_hr; int y_lr = (int)y_hr; float weight; tempR = tempG = tempB = tempA = 0; x_hr -= x_lr; y_hr -= y_lr; bufferIndex = SourceRenderingBuffer.GetBufferOffsetXY(x_lr, y_lr); #if false unsafe { fixed (float* pSource = fg_ptr) { Vector4f tempFinal = new Vector4f(0.0f, 0.0f, 0.0f, 0.0f); Vector4f color0 = Vector4f.LoadAligned((Vector4f*)&pSource[bufferIndex + 0]); weight = (1.0f - x_hr) * (1.0f - y_hr); Vector4f weight4f = new Vector4f(weight, weight, weight, weight); tempFinal = tempFinal + weight4f * color0; Vector4f color1 = Vector4f.LoadAligned((Vector4f*)&pSource[bufferIndex + 4]); weight = (x_hr) * (1.0f - y_hr); weight4f = new Vector4f(weight, weight, weight, weight); tempFinal = tempFinal + weight4f * color1; y_lr++; bufferIndex = SourceRenderingBuffer.GetBufferOffsetXY(x_lr, y_lr); Vector4f color2 = Vector4f.LoadAligned((Vector4f*)&pSource[bufferIndex + 0]); weight = (1.0f - x_hr) * (y_hr); weight4f = new Vector4f(weight, weight, weight, weight); tempFinal = tempFinal + weight4f * color2; Vector4f color3 = Vector4f.LoadAligned((Vector4f*)&pSource[bufferIndex + 4]); weight = (x_hr) * (y_hr); weight4f = new Vector4f(weight, weight, weight, weight); tempFinal = tempFinal + weight4f * color3; RGBA_Floats color; color.m_B = tempFinal.X; color.m_G = tempFinal.Y; color.m_R = tempFinal.Z; color.m_A = tempFinal.W; span[spanIndex] = color; } } #else weight = (1.0f - x_hr) * (1.0f - y_hr); tempR += weight * fg_ptr[bufferIndex + ImageBuffer.OrderR]; tempG += weight * fg_ptr[bufferIndex + ImageBuffer.OrderG]; tempB += weight * fg_ptr[bufferIndex + ImageBuffer.OrderB]; tempA += weight * fg_ptr[bufferIndex + ImageBuffer.OrderA]; bufferIndex += 4; weight = (x_hr) * (1.0f - y_hr); tempR += weight * fg_ptr[bufferIndex + ImageBuffer.OrderR]; tempG += weight * fg_ptr[bufferIndex + ImageBuffer.OrderG]; tempB += weight * fg_ptr[bufferIndex + ImageBuffer.OrderB]; tempA += weight * fg_ptr[bufferIndex + ImageBuffer.OrderA]; y_lr++; bufferIndex = SourceRenderingBuffer.GetBufferOffsetXY(x_lr, y_lr); weight = (1.0f - x_hr) * (y_hr); tempR += weight * fg_ptr[bufferIndex + ImageBuffer.OrderR]; tempG += weight * fg_ptr[bufferIndex + ImageBuffer.OrderG]; tempB += weight * fg_ptr[bufferIndex + ImageBuffer.OrderB]; tempA += weight * fg_ptr[bufferIndex + ImageBuffer.OrderA]; bufferIndex += 4; weight = (x_hr) * (y_hr); tempR += weight * fg_ptr[bufferIndex + ImageBuffer.OrderR]; tempG += weight * fg_ptr[bufferIndex + ImageBuffer.OrderG]; tempB += weight * fg_ptr[bufferIndex + ImageBuffer.OrderB]; tempA += weight * fg_ptr[bufferIndex + ImageBuffer.OrderA]; RGBA_Floats color; color.red = tempR; color.green = tempG; color.blue = tempB; color.alpha = tempA; span[spanIndex] = color; #endif spanIndex++; spanInterpolator.Next(); } while (--len != 0); } } }; //====================================span_image_filter_rgba_bilinear_clip public class span_image_filter_rgba_bilinear_clip : span_image_filter { private RGBA_Bytes m_OutsideSourceColor; private const int base_shift = 8; private const int base_scale = (int)(1 << base_shift); private const int base_mask = base_scale - 1; public span_image_filter_rgba_bilinear_clip(IImageBufferAccessor src, IColorType back_color, ISpanInterpolator inter) : base(src, inter, null) { m_OutsideSourceColor = back_color.GetAsRGBA_Bytes(); } public IColorType background_color() { return m_OutsideSourceColor; } public void background_color(IColorType v) { m_OutsideSourceColor = v.GetAsRGBA_Bytes(); } public override void generate(RGBA_Bytes[] span, int spanIndex, int x, int y, int len) { ImageBuffer SourceRenderingBuffer = (ImageBuffer)base.GetImageBufferAccessor().SourceImage; int bufferIndex; byte[] fg_ptr; if (base.m_interpolator.GetType() == typeof(MatterHackers.Agg.span_interpolator_linear) && ((MatterHackers.Agg.span_interpolator_linear)base.m_interpolator).transformer().GetType() == typeof(MatterHackers.Agg.Transform.Affine) && ((MatterHackers.Agg.Transform.Affine)((MatterHackers.Agg.span_interpolator_linear)base.m_interpolator).transformer()).is_identity()) { fg_ptr = SourceRenderingBuffer.GetPixelPointerXY(x, y, out bufferIndex); //unsafe { #if true do { span[spanIndex].blue = (byte)fg_ptr[bufferIndex++]; span[spanIndex].green = (byte)fg_ptr[bufferIndex++]; span[spanIndex].red = (byte)fg_ptr[bufferIndex++]; span[spanIndex].alpha = (byte)fg_ptr[bufferIndex++]; ++spanIndex; } while (--len != 0); #else fixed (byte* pSource = &fg_ptr[bufferIndex]) { int* pSourceInt = (int*)pSource; fixed (RGBA_Bytes* pDest = &span[spanIndex]) { int* pDestInt = (int*)pDest; do { *pDestInt++ = *pSourceInt++; } while (--len != 0); } } #endif } return; } base.interpolator().begin(x + base.filter_dx_dbl(), y + base.filter_dy_dbl(), len); int[] accumulatedColor = new int[4]; int back_r = m_OutsideSourceColor.red; int back_g = m_OutsideSourceColor.green; int back_b = m_OutsideSourceColor.blue; int back_a = m_OutsideSourceColor.alpha; int distanceBetweenPixelsInclusive = base.GetImageBufferAccessor().SourceImage.GetBytesBetweenPixelsInclusive(); int maxx = (int)SourceRenderingBuffer.Width - 1; int maxy = (int)SourceRenderingBuffer.Height - 1; ISpanInterpolator spanInterpolator = base.interpolator(); unchecked { do { int x_hr; int y_hr; spanInterpolator.coordinates(out x_hr, out y_hr); x_hr -= base.filter_dx_int(); y_hr -= base.filter_dy_int(); int x_lr = x_hr >> (int)image_subpixel_scale_e.image_subpixel_shift; int y_lr = y_hr >> (int)image_subpixel_scale_e.image_subpixel_shift; int weight; if (x_lr >= 0 && y_lr >= 0 && x_lr < maxx && y_lr < maxy) { accumulatedColor[0] = accumulatedColor[1] = accumulatedColor[2] = accumulatedColor[3] = (int)image_subpixel_scale_e.image_subpixel_scale * (int)image_subpixel_scale_e.image_subpixel_scale / 2; x_hr &= (int)image_subpixel_scale_e.image_subpixel_mask; y_hr &= (int)image_subpixel_scale_e.image_subpixel_mask; fg_ptr = SourceRenderingBuffer.GetPixelPointerXY(x_lr, y_lr, out bufferIndex); weight = (((int)image_subpixel_scale_e.image_subpixel_scale - x_hr) * ((int)image_subpixel_scale_e.image_subpixel_scale - y_hr)); if (weight > base_mask) { accumulatedColor[0] += weight * fg_ptr[bufferIndex + ImageBuffer.OrderR]; accumulatedColor[1] += weight * fg_ptr[bufferIndex + ImageBuffer.OrderG]; accumulatedColor[2] += weight * fg_ptr[bufferIndex + ImageBuffer.OrderB]; accumulatedColor[3] += weight * fg_ptr[bufferIndex + ImageBuffer.OrderA]; } weight = (x_hr * ((int)image_subpixel_scale_e.image_subpixel_scale - y_hr)); if (weight > base_mask) { bufferIndex += distanceBetweenPixelsInclusive; accumulatedColor[0] += weight * fg_ptr[bufferIndex + ImageBuffer.OrderR]; accumulatedColor[1] += weight * fg_ptr[bufferIndex + ImageBuffer.OrderG]; accumulatedColor[2] += weight * fg_ptr[bufferIndex + ImageBuffer.OrderB]; accumulatedColor[3] += weight * fg_ptr[bufferIndex + ImageBuffer.OrderA]; } weight = (((int)image_subpixel_scale_e.image_subpixel_scale - x_hr) * y_hr); if (weight > base_mask) { ++y_lr; fg_ptr = SourceRenderingBuffer.GetPixelPointerXY(x_lr, y_lr, out bufferIndex); accumulatedColor[0] += weight * fg_ptr[bufferIndex + ImageBuffer.OrderR]; accumulatedColor[1] += weight * fg_ptr[bufferIndex + ImageBuffer.OrderG]; accumulatedColor[2] += weight * fg_ptr[bufferIndex + ImageBuffer.OrderB]; accumulatedColor[3] += weight * fg_ptr[bufferIndex + ImageBuffer.OrderA]; } weight = (x_hr * y_hr); if (weight > base_mask) { bufferIndex += distanceBetweenPixelsInclusive; accumulatedColor[0] += weight * fg_ptr[bufferIndex + ImageBuffer.OrderR]; accumulatedColor[1] += weight * fg_ptr[bufferIndex + ImageBuffer.OrderG]; accumulatedColor[2] += weight * fg_ptr[bufferIndex + ImageBuffer.OrderB]; accumulatedColor[3] += weight * fg_ptr[bufferIndex + ImageBuffer.OrderA]; } accumulatedColor[0] >>= (int)image_subpixel_scale_e.image_subpixel_shift * 2; accumulatedColor[1] >>= (int)image_subpixel_scale_e.image_subpixel_shift * 2; accumulatedColor[2] >>= (int)image_subpixel_scale_e.image_subpixel_shift * 2; accumulatedColor[3] >>= (int)image_subpixel_scale_e.image_subpixel_shift * 2; } else { if (x_lr < -1 || y_lr < -1 || x_lr > maxx || y_lr > maxy) { accumulatedColor[0] = back_r; accumulatedColor[1] = back_g; accumulatedColor[2] = back_b; accumulatedColor[3] = back_a; } else { accumulatedColor[0] = accumulatedColor[1] = accumulatedColor[2] = accumulatedColor[3] = (int)image_subpixel_scale_e.image_subpixel_scale * (int)image_subpixel_scale_e.image_subpixel_scale / 2; x_hr &= (int)image_subpixel_scale_e.image_subpixel_mask; y_hr &= (int)image_subpixel_scale_e.image_subpixel_mask; weight = (((int)image_subpixel_scale_e.image_subpixel_scale - x_hr) * ((int)image_subpixel_scale_e.image_subpixel_scale - y_hr)); if (weight > base_mask) { BlendInFilterPixel(accumulatedColor, back_r, back_g, back_b, back_a, SourceRenderingBuffer, maxx, maxy, x_lr, y_lr, weight); } x_lr++; weight = (x_hr * ((int)image_subpixel_scale_e.image_subpixel_scale - y_hr)); if (weight > base_mask) { BlendInFilterPixel(accumulatedColor, back_r, back_g, back_b, back_a, SourceRenderingBuffer, maxx, maxy, x_lr, y_lr, weight); } x_lr--; y_lr++; weight = (((int)image_subpixel_scale_e.image_subpixel_scale - x_hr) * y_hr); if (weight > base_mask) { BlendInFilterPixel(accumulatedColor, back_r, back_g, back_b, back_a, SourceRenderingBuffer, maxx, maxy, x_lr, y_lr, weight); } x_lr++; weight = (x_hr * y_hr); if (weight > base_mask) { BlendInFilterPixel(accumulatedColor, back_r, back_g, back_b, back_a, SourceRenderingBuffer, maxx, maxy, x_lr, y_lr, weight); } accumulatedColor[0] >>= (int)image_subpixel_scale_e.image_subpixel_shift * 2; accumulatedColor[1] >>= (int)image_subpixel_scale_e.image_subpixel_shift * 2; accumulatedColor[2] >>= (int)image_subpixel_scale_e.image_subpixel_shift * 2; accumulatedColor[3] >>= (int)image_subpixel_scale_e.image_subpixel_shift * 2; } } span[spanIndex].red = (byte)accumulatedColor[0]; span[spanIndex].green = (byte)accumulatedColor[1]; span[spanIndex].blue = (byte)accumulatedColor[2]; span[spanIndex].alpha = (byte)accumulatedColor[3]; ++spanIndex; spanInterpolator.Next(); } while (--len != 0); } } private void BlendInFilterPixel(int[] accumulatedColor, int back_r, int back_g, int back_b, int back_a, IImageByte SourceRenderingBuffer, int maxx, int maxy, int x_lr, int y_lr, int weight) { byte[] fg_ptr; unchecked { if ((uint)x_lr <= (uint)maxx && (uint)y_lr <= (uint)maxy) { int bufferIndex = SourceRenderingBuffer.GetBufferOffsetXY(x_lr, y_lr); fg_ptr = SourceRenderingBuffer.GetBuffer(); accumulatedColor[0] += weight * fg_ptr[bufferIndex + ImageBuffer.OrderR]; accumulatedColor[1] += weight * fg_ptr[bufferIndex + ImageBuffer.OrderG]; accumulatedColor[2] += weight * fg_ptr[bufferIndex + ImageBuffer.OrderB]; accumulatedColor[3] += weight * fg_ptr[bufferIndex + ImageBuffer.OrderA]; } else { accumulatedColor[0] += back_r * weight; accumulatedColor[1] += back_g * weight; accumulatedColor[2] += back_b * weight; accumulatedColor[3] += back_a * weight; } } } }; /* //==============================================span_image_filter_rgba_2x2 //template<class Source, class Interpolator> public class span_image_filter_rgba_2x2 : span_image_filter//<Source, Interpolator> { //typedef Source source_type; //typedef typename source_type::color_type color_type; //typedef typename source_type::order_type order_type; //typedef Interpolator interpolator_type; //typedef span_image_filter<source_type, interpolator_type> base_type; //typedef typename color_type::value_type value_type; //typedef typename color_type::calc_type calc_type; enum base_scale_e { base_shift = 8, //color_type::base_shift, base_mask = 255,//color_type::base_mask }; //-------------------------------------------------------------------- public span_image_filter_rgba_2x2() {} public span_image_filter_rgba_2x2(pixfmt_alpha_blend_bgra32 src, interpolator_type inter, ImageFilterLookUpTable filter) : base(src, inter, filter) {} //-------------------------------------------------------------------- public void generate(color_type* span, int x, int y, unsigned len) { base.interpolator().begin(x + base.filter_dx_dbl(), y + base.filter_dy_dbl(), len); calc_type fg[4]; byte *fg_ptr; int16* weight_array = base.filter().weight_array() + ((base.filter().diameter()/2 - 1) << image_subpixel_shift); do { int x_hr; int y_hr; base.interpolator().coordinates(&x_hr, &y_hr); x_hr -= base.filter_dx_int(); y_hr -= base.filter_dy_int(); int x_lr = x_hr >> image_subpixel_shift; int y_lr = y_hr >> image_subpixel_shift; unsigned weight; fg[0] = fg[1] = fg[2] = fg[3] = (int)image_filter_scale_e.image_filter_scale / 2; x_hr &= image_subpixel_mask; y_hr &= image_subpixel_mask; fg_ptr = base.source().span(x_lr, y_lr, 2); weight = (weight_array[x_hr + image_subpixel_scale] * weight_array[y_hr + image_subpixel_scale] + (int)image_filter_scale_e.image_filter_scale / 2) >> image_filter_shift; fg[0] += weight * *fg_ptr++; fg[1] += weight * *fg_ptr++; fg[2] += weight * *fg_ptr++; fg[3] += weight * *fg_ptr; fg_ptr = base.source().next_x(); weight = (weight_array[x_hr] * weight_array[y_hr + image_subpixel_scale] + (int)image_filter_scale_e.image_filter_scale / 2) >> image_filter_shift; fg[0] += weight * *fg_ptr++; fg[1] += weight * *fg_ptr++; fg[2] += weight * *fg_ptr++; fg[3] += weight * *fg_ptr; fg_ptr = base.source().next_y(); weight = (weight_array[x_hr + image_subpixel_scale] * weight_array[y_hr] + (int)image_filter_scale_e.image_filter_scale / 2) >> image_filter_shift; fg[0] += weight * *fg_ptr++; fg[1] += weight * *fg_ptr++; fg[2] += weight * *fg_ptr++; fg[3] += weight * *fg_ptr; fg_ptr = base.source().next_x(); weight = (weight_array[x_hr] * weight_array[y_hr] + (int)image_filter_scale_e.image_filter_scale / 2) >> image_filter_shift; fg[0] += weight * *fg_ptr++; fg[1] += weight * *fg_ptr++; fg[2] += weight * *fg_ptr++; fg[3] += weight * *fg_ptr; fg[0] >>= image_filter_shift; fg[1] >>= image_filter_shift; fg[2] >>= image_filter_shift; fg[3] >>= image_filter_shift; if(fg[ImageBuffer.OrderA] > base_mask) fg[ImageBuffer.OrderA] = base_mask; if(fg[ImageBuffer.OrderR] > fg[ImageBuffer.OrderA]) fg[ImageBuffer.OrderR] = fg[ImageBuffer.OrderA]; if(fg[ImageBuffer.OrderG] > fg[ImageBuffer.OrderA]) fg[ImageBuffer.OrderG] = fg[ImageBuffer.OrderA]; if(fg[ImageBuffer.OrderB] > fg[ImageBuffer.OrderA]) fg[ImageBuffer.OrderB] = fg[ImageBuffer.OrderA]; span->r = (byte)fg[ImageBuffer.OrderR]; span->g = (byte)fg[ImageBuffer.OrderG]; span->b = (byte)fg[ImageBuffer.OrderB]; span->a = (byte)fg[ImageBuffer.OrderA]; ++span; ++base.interpolator(); } while(--len); } }; */ public class span_image_filter_rgba : span_image_filter { private const int base_mask = 255; //-------------------------------------------------------------------- public span_image_filter_rgba(IImageBufferAccessor src, ISpanInterpolator inter, ImageFilterLookUpTable filter) : base(src, inter, filter) { if (src.SourceImage.GetBytesBetweenPixelsInclusive() != 4) { throw new System.NotSupportedException("span_image_filter_rgba must have a 32 bit DestImage"); } } public override void generate(RGBA_Bytes[] span, int spanIndex, int x, int y, int len) { base.interpolator().begin(x + base.filter_dx_dbl(), y + base.filter_dy_dbl(), len); int f_r, f_g, f_b, f_a; byte[] fg_ptr; int diameter = m_filter.diameter(); int start = m_filter.start(); int[] weight_array = m_filter.weight_array(); int x_count; int weight_y; ISpanInterpolator spanInterpolator = base.interpolator(); IImageBufferAccessor sourceAccessor = GetImageBufferAccessor(); do { spanInterpolator.coordinates(out x, out y); x -= base.filter_dx_int(); y -= base.filter_dy_int(); int x_hr = x; int y_hr = y; int x_lr = x_hr >> (int)image_subpixel_scale_e.image_subpixel_shift; int y_lr = y_hr >> (int)image_subpixel_scale_e.image_subpixel_shift; f_b = f_g = f_r = f_a = (int)image_filter_scale_e.image_filter_scale / 2; int x_fract = x_hr & (int)image_subpixel_scale_e.image_subpixel_mask; int y_count = diameter; y_hr = (int)image_subpixel_scale_e.image_subpixel_mask - (y_hr & (int)image_subpixel_scale_e.image_subpixel_mask); int bufferIndex; fg_ptr = sourceAccessor.span(x_lr + start, y_lr + start, diameter, out bufferIndex); for (; ; ) { x_count = (int)diameter; weight_y = weight_array[y_hr]; x_hr = (int)image_subpixel_scale_e.image_subpixel_mask - x_fract; for (; ; ) { int weight = (weight_y * weight_array[x_hr] + (int)image_filter_scale_e.image_filter_scale / 2) >> (int)image_filter_scale_e.image_filter_shift; f_b += weight * fg_ptr[bufferIndex + ImageBuffer.OrderR]; f_g += weight * fg_ptr[bufferIndex + ImageBuffer.OrderG]; f_r += weight * fg_ptr[bufferIndex + ImageBuffer.OrderB]; f_a += weight * fg_ptr[bufferIndex + ImageBuffer.OrderA]; if (--x_count == 0) break; x_hr += (int)image_subpixel_scale_e.image_subpixel_scale; sourceAccessor.next_x(out bufferIndex); } if (--y_count == 0) break; y_hr += (int)image_subpixel_scale_e.image_subpixel_scale; fg_ptr = sourceAccessor.next_y(out bufferIndex); } f_b >>= (int)image_filter_scale_e.image_filter_shift; f_g >>= (int)image_filter_scale_e.image_filter_shift; f_r >>= (int)image_filter_scale_e.image_filter_shift; f_a >>= (int)image_filter_scale_e.image_filter_shift; unchecked { if ((uint)f_b > base_mask) { if (f_b < 0) f_b = 0; if (f_b > base_mask) f_b = (int)base_mask; } if ((uint)f_g > base_mask) { if (f_g < 0) f_g = 0; if (f_g > base_mask) f_g = (int)base_mask; } if ((uint)f_r > base_mask) { if (f_r < 0) f_r = 0; if (f_r > base_mask) f_r = (int)base_mask; } if ((uint)f_a > base_mask) { if (f_a < 0) f_a = 0; if (f_a > base_mask) f_a = (int)base_mask; } } span[spanIndex].red = (byte)f_b; span[spanIndex].green = (byte)f_g; span[spanIndex].blue = (byte)f_r; span[spanIndex].alpha = (byte)f_a; spanIndex++; spanInterpolator.Next(); } while (--len != 0); } }; public class span_image_filter_rgba_float : span_image_filter_float { public span_image_filter_rgba_float(IImageBufferAccessorFloat src, ISpanInterpolatorFloat inter, IImageFilterFunction filterFunction) : base(src, inter, filterFunction) { if (src.SourceImage.GetFloatsBetweenPixelsInclusive() != 4) { throw new System.NotSupportedException("span_image_filter_rgba must have a 32 bit DestImage"); } } public override void generate(RGBA_Floats[] span, int spanIndex, int xInt, int yInt, int len) { base.interpolator().begin(xInt + base.filter_dx_dbl(), yInt + base.filter_dy_dbl(), len); float f_r, f_g, f_b, f_a; float[] fg_ptr; int radius = (int)m_filterFunction.radius(); int diameter = radius * 2; int start = -(int)(diameter / 2 - 1); int x_count; ISpanInterpolatorFloat spanInterpolator = base.interpolator(); IImageBufferAccessorFloat sourceAccessor = source(); do { float x = xInt; float y = yInt; spanInterpolator.coordinates(out x, out y); //x -= (float)base.filter_dx_dbl(); //y -= (float)base.filter_dy_dbl(); int sourceXInt = (int)x; int sourceYInt = (int)y; Vector2 sourceOrigin = new Vector2(x, y); Vector2 sourceSample = new Vector2(sourceXInt + start, sourceYInt + start); f_b = f_g = f_r = f_a = 0; int y_count = diameter; int bufferIndex; fg_ptr = sourceAccessor.span(sourceXInt + start, sourceYInt + start, diameter, out bufferIndex); float totalWeight = 0.0f; for (; ; ) { float yweight = (float)m_filterFunction.calc_weight(System.Math.Sqrt((sourceSample.y - sourceOrigin.y) * (sourceSample.y - sourceOrigin.y))); x_count = (int)diameter; for (; ; ) { float xweight = (float)m_filterFunction.calc_weight(System.Math.Sqrt((sourceSample.x - sourceOrigin.x) * (sourceSample.x - sourceOrigin.x))); float weight = xweight * yweight; f_r += weight * fg_ptr[bufferIndex + ImageBuffer.OrderR]; f_g += weight * fg_ptr[bufferIndex + ImageBuffer.OrderG]; f_b += weight * fg_ptr[bufferIndex + ImageBuffer.OrderB]; f_a += weight * fg_ptr[bufferIndex + ImageBuffer.OrderA]; totalWeight += weight; sourceSample.x += 1; if (--x_count == 0) break; sourceAccessor.next_x(out bufferIndex); } sourceSample.x -= diameter; if (--y_count == 0) break; sourceSample.y += 1; fg_ptr = sourceAccessor.next_y(out bufferIndex); } if (f_b < 0) f_b = 0; if (f_b > 1) f_b = 1; if (f_r < 0) f_r = 0; if (f_r > 1) f_r = 1; if (f_g < 0) f_g = 0; if (f_g > 1) f_g = 1; span[spanIndex].red = f_r; span[spanIndex].green = f_g; span[spanIndex].blue = f_b; span[spanIndex].alpha = 1;// f_a; spanIndex++; spanInterpolator.Next(); } while (--len != 0); } }; /* //========================================span_image_resample_rgba_affine public class span_image_resample_rgba_affine : span_image_resample_affine { //typedef Source source_type; //typedef typename source_type::color_type color_type; //typedef typename source_type::order_type order_type; //typedef span_image_resample_affine<source_type> base_type; //typedef typename base.interpolator_type interpolator_type; //typedef typename color_type::value_type value_type; //typedef typename color_type::long_type long_type; enum base_scale_e { base_shift = 8, //color_type::base_shift, base_mask = 255,//color_type::base_mask, downscale_shift = image_filter_shift }; //-------------------------------------------------------------------- public span_image_resample_rgba_affine() {} public span_image_resample_rgba_affine(pixfmt_alpha_blend_bgra32 src, interpolator_type inter, ImageFilterLookUpTable filter) : base(src, inter, filter) {} //-------------------------------------------------------------------- public void generate(color_type* span, int x, int y, unsigned len) { base.interpolator().begin(x + base.filter_dx_dbl(), y + base.filter_dy_dbl(), len); long_type fg[4]; int diameter = base.filter().diameter(); int filter_scale = diameter << image_subpixel_shift; int radius_x = (diameter * base.m_rx) >> 1; int radius_y = (diameter * base.m_ry) >> 1; int len_x_lr = (diameter * base.m_rx + image_subpixel_mask) >> image_subpixel_shift; int16* weight_array = base.filter().weight_array(); do { base.interpolator().coordinates(&x, &y); x += base.filter_dx_int() - radius_x; y += base.filter_dy_int() - radius_y; fg[0] = fg[1] = fg[2] = fg[3] = (int)image_filter_scale_e.image_filter_scale / 2; int y_lr = y >> image_subpixel_shift; int y_hr = ((image_subpixel_mask - (y & image_subpixel_mask)) * base.m_ry_inv) >> image_subpixel_shift; int total_weight = 0; int x_lr = x >> image_subpixel_shift; int x_hr = ((image_subpixel_mask - (x & image_subpixel_mask)) * base.m_rx_inv) >> image_subpixel_shift; int x_hr2 = x_hr; byte* fg_ptr = base.source().span(x_lr, y_lr, len_x_lr); for(;;) { int weight_y = weight_array[y_hr]; x_hr = x_hr2; for(;;) { int weight = (weight_y * weight_array[x_hr] + (int)image_filter_scale_e.image_filter_scale / 2) >> downscale_shift; fg[0] += *fg_ptr++ * weight; fg[1] += *fg_ptr++ * weight; fg[2] += *fg_ptr++ * weight; fg[3] += *fg_ptr++ * weight; total_weight += weight; x_hr += base.m_rx_inv; if(x_hr >= filter_scale) break; fg_ptr = base.source().next_x(); } y_hr += base.m_ry_inv; if(y_hr >= filter_scale) break; fg_ptr = base.source().next_y(); } fg[0] /= total_weight; fg[1] /= total_weight; fg[2] /= total_weight; fg[3] /= total_weight; if(fg[0] < 0) fg[0] = 0; if(fg[1] < 0) fg[1] = 0; if(fg[2] < 0) fg[2] = 0; if(fg[3] < 0) fg[3] = 0; if(fg[ImageBuffer.OrderA] > base_mask) fg[ImageBuffer.OrderA] = base_mask; if(fg[ImageBuffer.OrderR] > fg[ImageBuffer.OrderA]) fg[ImageBuffer.OrderR] = fg[ImageBuffer.OrderA]; if(fg[ImageBuffer.OrderG] > fg[ImageBuffer.OrderA]) fg[ImageBuffer.OrderG] = fg[ImageBuffer.OrderA]; if(fg[ImageBuffer.OrderB] > fg[ImageBuffer.OrderA]) fg[ImageBuffer.OrderB] = fg[ImageBuffer.OrderA]; span->r = (byte)fg[ImageBuffer.OrderR]; span->g = (byte)fg[ImageBuffer.OrderG]; span->b = (byte)fg[ImageBuffer.OrderB]; span->a = (byte)fg[ImageBuffer.OrderA]; ++span; ++base.interpolator(); } while(--len); } }; */ //==============================================span_image_resample_rgba public class span_image_resample_rgba : span_image_resample { private const int base_mask = 255; private const int downscale_shift = (int)ImageFilterLookUpTable.image_filter_scale_e.image_filter_shift; //-------------------------------------------------------------------- public span_image_resample_rgba(IImageBufferAccessor src, ISpanInterpolator inter, ImageFilterLookUpTable filter) : base(src, inter, filter) { if (src.SourceImage.GetRecieveBlender().NumPixelBits != 32) { throw new System.FormatException("You have to use a rgba blender with span_image_resample_rgba"); } } //-------------------------------------------------------------------- public override void generate(RGBA_Bytes[] span, int spanIndex, int x, int y, int len) { ISpanInterpolator spanInterpolator = base.interpolator(); spanInterpolator.begin(x + base.filter_dx_dbl(), y + base.filter_dy_dbl(), len); int[] fg = new int[4]; byte[] fg_ptr; int[] weightArray = filter().weight_array(); int diameter = (int)base.filter().diameter(); int filter_scale = diameter << (int)image_subpixel_scale_e.image_subpixel_shift; int[] weight_array = weightArray; do { int rx; int ry; int rx_inv = (int)image_subpixel_scale_e.image_subpixel_scale; int ry_inv = (int)image_subpixel_scale_e.image_subpixel_scale; spanInterpolator.coordinates(out x, out y); spanInterpolator.local_scale(out rx, out ry); base.adjust_scale(ref rx, ref ry); rx_inv = (int)image_subpixel_scale_e.image_subpixel_scale * (int)image_subpixel_scale_e.image_subpixel_scale / rx; ry_inv = (int)image_subpixel_scale_e.image_subpixel_scale * (int)image_subpixel_scale_e.image_subpixel_scale / ry; int radius_x = (diameter * rx) >> 1; int radius_y = (diameter * ry) >> 1; int len_x_lr = (diameter * rx + (int)image_subpixel_scale_e.image_subpixel_mask) >> (int)(int)image_subpixel_scale_e.image_subpixel_shift; x += base.filter_dx_int() - radius_x; y += base.filter_dy_int() - radius_y; fg[0] = fg[1] = fg[2] = fg[3] = (int)image_filter_scale_e.image_filter_scale / 2; int y_lr = y >> (int)(int)image_subpixel_scale_e.image_subpixel_shift; int y_hr = (((int)image_subpixel_scale_e.image_subpixel_mask - (y & (int)image_subpixel_scale_e.image_subpixel_mask)) * ry_inv) >> (int)(int)image_subpixel_scale_e.image_subpixel_shift; int total_weight = 0; int x_lr = x >> (int)(int)image_subpixel_scale_e.image_subpixel_shift; int x_hr = (((int)image_subpixel_scale_e.image_subpixel_mask - (x & (int)image_subpixel_scale_e.image_subpixel_mask)) * rx_inv) >> (int)(int)image_subpixel_scale_e.image_subpixel_shift; int x_hr2 = x_hr; int sourceIndex; fg_ptr = base.GetImageBufferAccessor().span(x_lr, y_lr, len_x_lr, out sourceIndex); for (; ; ) { int weight_y = weight_array[y_hr]; x_hr = x_hr2; for (; ; ) { int weight = (weight_y * weight_array[x_hr] + (int)image_filter_scale_e.image_filter_scale / 2) >> downscale_shift; fg[0] += fg_ptr[sourceIndex + ImageBuffer.OrderR] * weight; fg[1] += fg_ptr[sourceIndex + ImageBuffer.OrderG] * weight; fg[2] += fg_ptr[sourceIndex + ImageBuffer.OrderB] * weight; fg[3] += fg_ptr[sourceIndex + ImageBuffer.OrderA] * weight; total_weight += weight; x_hr += rx_inv; if (x_hr >= filter_scale) break; fg_ptr = base.GetImageBufferAccessor().next_x(out sourceIndex); } y_hr += ry_inv; if (y_hr >= filter_scale) { break; } fg_ptr = base.GetImageBufferAccessor().next_y(out sourceIndex); } fg[0] /= total_weight; fg[1] /= total_weight; fg[2] /= total_weight; fg[3] /= total_weight; if (fg[0] < 0) fg[0] = 0; if (fg[1] < 0) fg[1] = 0; if (fg[2] < 0) fg[2] = 0; if (fg[3] < 0) fg[3] = 0; if (fg[0] > base_mask) fg[0] = base_mask; if (fg[1] > base_mask) fg[1] = base_mask; if (fg[2] > base_mask) fg[2] = base_mask; if (fg[3] > base_mask) fg[3] = base_mask; span[spanIndex].red = (byte)fg[0]; span[spanIndex].green = (byte)fg[1]; span[spanIndex].blue = (byte)fg[2]; span[spanIndex].alpha = (byte)fg[3]; spanIndex++; interpolator().Next(); } while (--len != 0); } /* ISpanInterpolator spanInterpolator = base.interpolator(); spanInterpolator.begin(x + base.filter_dx_dbl(), y + base.filter_dy_dbl(), len); int* fg = stackalloc int[4]; byte* fg_ptr; fixed (int* pWeightArray = filter().weight_array()) { int diameter = (int)base.filter().diameter(); int filter_scale = diameter << (int)image_subpixel_scale_e.image_subpixel_shift; int* weight_array = pWeightArray; do { int rx; int ry; int rx_inv = (int)image_subpixel_scale_e.image_subpixel_scale; int ry_inv = (int)image_subpixel_scale_e.image_subpixel_scale; spanInterpolator.coordinates(out x, out y); spanInterpolator.local_scale(out rx, out ry); base.adjust_scale(ref rx, ref ry); rx_inv = (int)image_subpixel_scale_e.image_subpixel_scale * (int)image_subpixel_scale_e.image_subpixel_scale / rx; ry_inv = (int)image_subpixel_scale_e.image_subpixel_scale * (int)image_subpixel_scale_e.image_subpixel_scale / ry; int radius_x = (diameter * rx) >> 1; int radius_y = (diameter * ry) >> 1; int len_x_lr = (diameter * rx + (int)image_subpixel_scale_e.image_subpixel_mask) >> (int)(int)image_subpixel_scale_e.image_subpixel_shift; x += base.filter_dx_int() - radius_x; y += base.filter_dy_int() - radius_y; fg[0] = fg[1] = fg[2] = fg[3] = (int)image_filter_scale_e.image_filter_scale / 2; int y_lr = y >> (int)(int)image_subpixel_scale_e.image_subpixel_shift; int y_hr = (((int)image_subpixel_scale_e.image_subpixel_mask - (y & (int)image_subpixel_scale_e.image_subpixel_mask)) * ry_inv) >> (int)(int)image_subpixel_scale_e.image_subpixel_shift; int total_weight = 0; int x_lr = x >> (int)(int)image_subpixel_scale_e.image_subpixel_shift; int x_hr = (((int)image_subpixel_scale_e.image_subpixel_mask - (x & (int)image_subpixel_scale_e.image_subpixel_mask)) * rx_inv) >> (int)(int)image_subpixel_scale_e.image_subpixel_shift; int x_hr2 = x_hr; fg_ptr = base.source().span(x_lr, y_lr, (int)len_x_lr); for(;;) { int weight_y = weight_array[y_hr]; x_hr = x_hr2; for(;;) { int weight = (weight_y * weight_array[x_hr] + (int)image_filter_scale_e.image_filter_scale / 2) >> downscale_shift; fg[0] += *fg_ptr++ * weight; fg[1] += *fg_ptr++ * weight; fg[2] += *fg_ptr++ * weight; fg[3] += *fg_ptr++ * weight; total_weight += weight; x_hr += rx_inv; if(x_hr >= filter_scale) break; fg_ptr = base.source().next_x(); } y_hr += ry_inv; if (y_hr >= filter_scale) { break; } fg_ptr = base.source().next_y(); } fg[0] /= total_weight; fg[1] /= total_weight; fg[2] /= total_weight; fg[3] /= total_weight; if(fg[0] < 0) fg[0] = 0; if(fg[1] < 0) fg[1] = 0; if(fg[2] < 0) fg[2] = 0; if(fg[3] < 0) fg[3] = 0; if(fg[0] > fg[0]) fg[0] = fg[0]; if(fg[1] > fg[1]) fg[1] = fg[1]; if(fg[2] > fg[2]) fg[2] = fg[2]; if (fg[3] > base_mask) fg[3] = base_mask; span->R_Byte = (byte)fg[ImageBuffer.OrderR]; span->G_Byte = (byte)fg[ImageBuffer.OrderG]; span->B_Byte = (byte)fg[ImageBuffer.OrderB]; span->A_Byte = (byte)fg[ImageBuffer.OrderA]; ++span; interpolator().Next(); } while(--len != 0); } */ }; } //#endif
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace RestfulApi.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { private const int DefaultCollectionSize = 3; 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); } } } }
namespace OpenTK.Graphics { using System; using System.Runtime.InteropServices; #pragma warning disable 3019 #pragma warning disable 1591 static partial class Glu { public static void BeginCurve(IntPtr nurb) { Delegates.gluBeginCurve((IntPtr)nurb); } public static void BeginPolygon(IntPtr tess) { Delegates.gluBeginPolygon((IntPtr)tess); } public static void BeginSurface(IntPtr nurb) { Delegates.gluBeginSurface((IntPtr)nurb); } public static void BeginTrim(IntPtr nurb) { Delegates.gluBeginTrim((IntPtr)nurb); } public static Int32 Build1DMipmapLevel(TextureTarget target, Int32 internalFormat, Int32 width, PixelFormat format, PixelType type, Int32 level, Int32 @base, Int32 max, IntPtr data) { unsafe { return Delegates.gluBuild1DMipmapLevels((TextureTarget)target, (Int32)internalFormat, (Int32)width, (PixelFormat)format, (PixelType)type, (Int32)level, (Int32)@base, (Int32)max, (IntPtr)data); } } public static Int32 Build1DMipmapLevel(TextureTarget target, Int32 internalFormat, Int32 width, PixelFormat format, PixelType type, Int32 level, Int32 @base, Int32 max, [In, Out] object data) { unsafe { System.Runtime.InteropServices.GCHandle data_ptr = System.Runtime.InteropServices.GCHandle.Alloc(data, System.Runtime.InteropServices.GCHandleType.Pinned); try { return Delegates.gluBuild1DMipmapLevels((TextureTarget)target, (Int32)internalFormat, (Int32)width, (PixelFormat)format, (PixelType)type, (Int32)level, (Int32)@base, (Int32)max, (IntPtr)data_ptr.AddrOfPinnedObject()); } finally { data_ptr.Free(); } } } public static Int32 Build1DMipmap(TextureTarget target, Int32 internalFormat, Int32 width, PixelFormat format, PixelType type, IntPtr data) { unsafe { return Delegates.gluBuild1DMipmaps((TextureTarget)target, (Int32)internalFormat, (Int32)width, (PixelFormat)format, (PixelType)type, (IntPtr)data); } } public static Int32 Build1DMipmap(TextureTarget target, Int32 internalFormat, Int32 width, PixelFormat format, PixelType type, [In, Out] object data) { unsafe { System.Runtime.InteropServices.GCHandle data_ptr = System.Runtime.InteropServices.GCHandle.Alloc(data, System.Runtime.InteropServices.GCHandleType.Pinned); try { return Delegates.gluBuild1DMipmaps((TextureTarget)target, (Int32)internalFormat, (Int32)width, (PixelFormat)format, (PixelType)type, (IntPtr)data_ptr.AddrOfPinnedObject()); } finally { data_ptr.Free(); } } } public static Int32 Build2DMipmapLevel(TextureTarget target, Int32 internalFormat, Int32 width, Int32 height, PixelFormat format, PixelType type, Int32 level, Int32 @base, Int32 max, IntPtr data) { unsafe { return Delegates.gluBuild2DMipmapLevels((TextureTarget)target, (Int32)internalFormat, (Int32)width, (Int32)height, (PixelFormat)format, (PixelType)type, (Int32)level, (Int32)@base, (Int32)max, (IntPtr)data); } } public static Int32 Build2DMipmapLevel(TextureTarget target, Int32 internalFormat, Int32 width, Int32 height, PixelFormat format, PixelType type, Int32 level, Int32 @base, Int32 max, [In, Out] object data) { unsafe { System.Runtime.InteropServices.GCHandle data_ptr = System.Runtime.InteropServices.GCHandle.Alloc(data, System.Runtime.InteropServices.GCHandleType.Pinned); try { return Delegates.gluBuild2DMipmapLevels((TextureTarget)target, (Int32)internalFormat, (Int32)width, (Int32)height, (PixelFormat)format, (PixelType)type, (Int32)level, (Int32)@base, (Int32)max, (IntPtr)data_ptr.AddrOfPinnedObject()); } finally { data_ptr.Free(); } } } public static Int32 Build2DMipmap(TextureTarget target, Int32 internalFormat, Int32 width, Int32 height, PixelFormat format, PixelType type, IntPtr data) { unsafe { return Delegates.gluBuild2DMipmaps((TextureTarget)target, (Int32)internalFormat, (Int32)width, (Int32)height, (PixelFormat)format, (PixelType)type, (IntPtr)data); } } public static Int32 Build2DMipmap(TextureTarget target, Int32 internalFormat, Int32 width, Int32 height, PixelFormat format, PixelType type, [In, Out] object data) { unsafe { System.Runtime.InteropServices.GCHandle data_ptr = System.Runtime.InteropServices.GCHandle.Alloc(data, System.Runtime.InteropServices.GCHandleType.Pinned); try { return Delegates.gluBuild2DMipmaps((TextureTarget)target, (Int32)internalFormat, (Int32)width, (Int32)height, (PixelFormat)format, (PixelType)type, (IntPtr)data_ptr.AddrOfPinnedObject()); } finally { data_ptr.Free(); } } } public static Int32 Build3DMipmapLevel(TextureTarget target, Int32 internalFormat, Int32 width, Int32 height, Int32 depth, PixelFormat format, PixelType type, Int32 level, Int32 @base, Int32 max, IntPtr data) { unsafe { return Delegates.gluBuild3DMipmapLevels((TextureTarget)target, (Int32)internalFormat, (Int32)width, (Int32)height, (Int32)depth, (PixelFormat)format, (PixelType)type, (Int32)level, (Int32)@base, (Int32)max, (IntPtr)data); } } public static Int32 Build3DMipmapLevel(TextureTarget target, Int32 internalFormat, Int32 width, Int32 height, Int32 depth, PixelFormat format, PixelType type, Int32 level, Int32 @base, Int32 max, [In, Out] object data) { unsafe { System.Runtime.InteropServices.GCHandle data_ptr = System.Runtime.InteropServices.GCHandle.Alloc(data, System.Runtime.InteropServices.GCHandleType.Pinned); try { return Delegates.gluBuild3DMipmapLevels((TextureTarget)target, (Int32)internalFormat, (Int32)width, (Int32)height, (Int32)depth, (PixelFormat)format, (PixelType)type, (Int32)level, (Int32)@base, (Int32)max, (IntPtr)data_ptr.AddrOfPinnedObject()); } finally { data_ptr.Free(); } } } public static Int32 Build3DMipmap(TextureTarget target, Int32 internalFormat, Int32 width, Int32 height, Int32 depth, PixelFormat format, PixelType type, IntPtr data) { unsafe { return Delegates.gluBuild3DMipmaps((TextureTarget)target, (Int32)internalFormat, (Int32)width, (Int32)height, (Int32)depth, (PixelFormat)format, (PixelType)type, (IntPtr)data); } } public static Int32 Build3DMipmap(TextureTarget target, Int32 internalFormat, Int32 width, Int32 height, Int32 depth, PixelFormat format, PixelType type, [In, Out] object data) { unsafe { System.Runtime.InteropServices.GCHandle data_ptr = System.Runtime.InteropServices.GCHandle.Alloc(data, System.Runtime.InteropServices.GCHandleType.Pinned); try { return Delegates.gluBuild3DMipmaps((TextureTarget)target, (Int32)internalFormat, (Int32)width, (Int32)height, (Int32)depth, (PixelFormat)format, (PixelType)type, (IntPtr)data_ptr.AddrOfPinnedObject()); } finally { data_ptr.Free(); } } } public static bool CheckExtension(Byte[] extName, Byte[] extString) { unsafe { fixed (Byte* extName_ptr = extName) fixed (Byte* extString_ptr = extString) { return Delegates.gluCheckExtension((Byte*)extName_ptr, (Byte*)extString_ptr); } } } public static bool CheckExtension(ref Byte extName, ref Byte extString) { unsafe { fixed (Byte* extName_ptr = &extName) fixed (Byte* extString_ptr = &extString) { return Delegates.gluCheckExtension((Byte*)extName_ptr, (Byte*)extString_ptr); } } } [System.CLSCompliant(false)] public static unsafe bool CheckExtension(Byte* extName, Byte* extString) { return Delegates.gluCheckExtension((Byte*)extName, (Byte*)extString); } public static void Cylinder(IntPtr quad, double @base, double top, double height, Int32 slices, Int32 stacks) { Delegates.gluCylinder((IntPtr)quad, (double)@base, (double)top, (double)height, (Int32)slices, (Int32)stacks); } public static void DeleteNurbsRenderer(IntPtr nurb) { Delegates.gluDeleteNurbsRenderer((IntPtr)nurb); } public static void DeleteQuadric(IntPtr quad) { Delegates.gluDeleteQuadric((IntPtr)quad); } public static void DeleteTess(IntPtr tess) { Delegates.gluDeleteTess((IntPtr)tess); } public static void Disk(IntPtr quad, double inner, double outer, Int32 slices, Int32 loops) { Delegates.gluDisk((IntPtr)quad, (double)inner, (double)outer, (Int32)slices, (Int32)loops); } public static void EndCurve(IntPtr nurb) { Delegates.gluEndCurve((IntPtr)nurb); } public static void EndPolygon(IntPtr tess) { Delegates.gluEndPolygon((IntPtr)tess); } public static void EndSurface(IntPtr nurb) { Delegates.gluEndSurface((IntPtr)nurb); } public static void EndTrim(IntPtr nurb) { Delegates.gluEndTrim((IntPtr)nurb); } public static string ErrorString(OpenTK.Graphics.GluErrorCode error) { unsafe { return System.Runtime.InteropServices.Marshal.PtrToStringAnsi(Delegates.gluErrorString((OpenTK.Graphics.GluErrorCode)error)); } } public static string GetString(OpenTK.Graphics.GluStringName name) { unsafe { return System.Runtime.InteropServices.Marshal.PtrToStringAnsi(Delegates.gluGetString((OpenTK.Graphics.GluStringName)name)); } } public static void GetNurbsProperty(IntPtr nurb, OpenTK.Graphics.NurbsProperty property, [Out] float[] data) { unsafe { fixed (float* data_ptr = data) { Delegates.gluGetNurbsProperty((IntPtr)nurb, (OpenTK.Graphics.NurbsProperty)property, (float*)data_ptr); } } } public static void GetNurbsProperty(IntPtr nurb, OpenTK.Graphics.NurbsProperty property, [Out] out float data) { unsafe { fixed (float* data_ptr = &data) { Delegates.gluGetNurbsProperty((IntPtr)nurb, (OpenTK.Graphics.NurbsProperty)property, (float*)data_ptr); data = *data_ptr; } } } [System.CLSCompliant(false)] public static unsafe void GetNurbsProperty(IntPtr nurb, OpenTK.Graphics.NurbsProperty property, [Out] float* data) { Delegates.gluGetNurbsProperty((IntPtr)nurb, (OpenTK.Graphics.NurbsProperty)property, (float*)data); } public static void GetTessProperty(IntPtr tess, OpenTK.Graphics.TessParameter which, [Out] double[] data) { unsafe { fixed (double* data_ptr = data) { Delegates.gluGetTessProperty((IntPtr)tess, (OpenTK.Graphics.TessParameter)which, (double*)data_ptr); } } } public static void GetTessProperty(IntPtr tess, OpenTK.Graphics.TessParameter which, [Out] out double data) { unsafe { fixed (double* data_ptr = &data) { Delegates.gluGetTessProperty((IntPtr)tess, (OpenTK.Graphics.TessParameter)which, (double*)data_ptr); data = *data_ptr; } } } [System.CLSCompliant(false)] public static unsafe void GetTessProperty(IntPtr tess, OpenTK.Graphics.TessParameter which, [Out] double* data) { Delegates.gluGetTessProperty((IntPtr)tess, (OpenTK.Graphics.TessParameter)which, (double*)data); } public static void LoadSamplingMatrices(IntPtr nurb, float[] model, float[] perspective, Int32[] view) { unsafe { fixed (float* model_ptr = model) fixed (float* perspective_ptr = perspective) fixed (Int32* view_ptr = view) { Delegates.gluLoadSamplingMatrices((IntPtr)nurb, (float*)model_ptr, (float*)perspective_ptr, (Int32*)view_ptr); } } } public static void LoadSamplingMatrices(IntPtr nurb, ref float model, ref float perspective, ref Int32 view) { unsafe { fixed (float* model_ptr = &model) fixed (float* perspective_ptr = &perspective) fixed (Int32* view_ptr = &view) { Delegates.gluLoadSamplingMatrices((IntPtr)nurb, (float*)model_ptr, (float*)perspective_ptr, (Int32*)view_ptr); } } } [System.CLSCompliant(false)] public static unsafe void LoadSamplingMatrices(IntPtr nurb, float* model, float* perspective, Int32* view) { Delegates.gluLoadSamplingMatrices((IntPtr)nurb, (float*)model, (float*)perspective, (Int32*)view); } public static void LookAt(double eyeX, double eyeY, double eyeZ, double centerX, double centerY, double centerZ, double upX, double upY, double upZ) { Delegates.gluLookAt((double)eyeX, (double)eyeY, (double)eyeZ, (double)centerX, (double)centerY, (double)centerZ, (double)upX, (double)upY, (double)upZ); } public static IntPtr NewNurbsRenderer() { return Delegates.gluNewNurbsRenderer(); } public static IntPtr NewQuadric() { return Delegates.gluNewQuadric(); } public static IntPtr NewTess() { return Delegates.gluNewTess(); } public static void NextContour(IntPtr tess, OpenTK.Graphics.TessContour type) { Delegates.gluNextContour((IntPtr)tess, (OpenTK.Graphics.TessContour)type); } public static void NurbsCallback(IntPtr nurb, OpenTK.Graphics.NurbsCallback which, Delegate CallBackFunc) { Delegates.gluNurbsCallback((IntPtr)nurb, (OpenTK.Graphics.NurbsCallback)which, (Delegate)CallBackFunc); } public static void NurbsCallbackData(IntPtr nurb, IntPtr userData) { unsafe { Delegates.gluNurbsCallbackData((IntPtr)nurb, (IntPtr)userData); } } public static void NurbsCallbackData(IntPtr nurb, [In, Out] object userData) { unsafe { System.Runtime.InteropServices.GCHandle userData_ptr = System.Runtime.InteropServices.GCHandle.Alloc(userData, System.Runtime.InteropServices.GCHandleType.Pinned); try { Delegates.gluNurbsCallbackData((IntPtr)nurb, (IntPtr)userData_ptr.AddrOfPinnedObject()); } finally { userData_ptr.Free(); } } } public static void NurbsCurve(IntPtr nurb, Int32 knotCount, [Out] float[] knots, Int32 stride, [Out] float[] control, Int32 order, MapTarget type) { unsafe { fixed (float* knots_ptr = knots) fixed (float* control_ptr = control) { Delegates.gluNurbsCurve((IntPtr)nurb, (Int32)knotCount, (float*)knots_ptr, (Int32)stride, (float*)control_ptr, (Int32)order, (MapTarget)type); } } } public static void NurbsCurve(IntPtr nurb, Int32 knotCount, [Out] out float knots, Int32 stride, [Out] out float control, Int32 order, MapTarget type) { unsafe { fixed (float* knots_ptr = &knots) fixed (float* control_ptr = &control) { Delegates.gluNurbsCurve((IntPtr)nurb, (Int32)knotCount, (float*)knots_ptr, (Int32)stride, (float*)control_ptr, (Int32)order, (MapTarget)type); knots = *knots_ptr; control = *control_ptr; } } } [System.CLSCompliant(false)] public static unsafe void NurbsCurve(IntPtr nurb, Int32 knotCount, [Out] float* knots, Int32 stride, [Out] float* control, Int32 order, MapTarget type) { Delegates.gluNurbsCurve((IntPtr)nurb, (Int32)knotCount, (float*)knots, (Int32)stride, (float*)control, (Int32)order, (MapTarget)type); } public static void NurbsProperty(IntPtr nurb, OpenTK.Graphics.NurbsProperty property, float value) { Delegates.gluNurbsProperty((IntPtr)nurb, (OpenTK.Graphics.NurbsProperty)property, (float)value); } public static void NurbsSurface(IntPtr nurb, Int32 sKnotCount, float[] sKnots, Int32 tKnotCount, float[] tKnots, Int32 sStride, Int32 tStride, float[] control, Int32 sOrder, Int32 tOrder, MapTarget type) { unsafe { fixed (float* sKnots_ptr = sKnots) fixed (float* tKnots_ptr = tKnots) fixed (float* control_ptr = control) { Delegates.gluNurbsSurface((IntPtr)nurb, (Int32)sKnotCount, (float*)sKnots_ptr, (Int32)tKnotCount, (float*)tKnots_ptr, (Int32)sStride, (Int32)tStride, (float*)control_ptr, (Int32)sOrder, (Int32)tOrder, (MapTarget)type); } } } public static void NurbsSurface(IntPtr nurb, Int32 sKnotCount, ref float sKnots, Int32 tKnotCount, ref float tKnots, Int32 sStride, Int32 tStride, ref float control, Int32 sOrder, Int32 tOrder, MapTarget type) { unsafe { fixed (float* sKnots_ptr = &sKnots) fixed (float* tKnots_ptr = &tKnots) fixed (float* control_ptr = &control) { Delegates.gluNurbsSurface((IntPtr)nurb, (Int32)sKnotCount, (float*)sKnots_ptr, (Int32)tKnotCount, (float*)tKnots_ptr, (Int32)sStride, (Int32)tStride, (float*)control_ptr, (Int32)sOrder, (Int32)tOrder, (MapTarget)type); } } } [System.CLSCompliant(false)] public static unsafe void NurbsSurface(IntPtr nurb, Int32 sKnotCount, float* sKnots, Int32 tKnotCount, float* tKnots, Int32 sStride, Int32 tStride, float* control, Int32 sOrder, Int32 tOrder, MapTarget type) { Delegates.gluNurbsSurface((IntPtr)nurb, (Int32)sKnotCount, (float*)sKnots, (Int32)tKnotCount, (float*)tKnots, (Int32)sStride, (Int32)tStride, (float*)control, (Int32)sOrder, (Int32)tOrder, (MapTarget)type); } public static void Ortho2D(double left, double right, double bottom, double top) { Delegates.gluOrtho2D((double)left, (double)right, (double)bottom, (double)top); } public static void PartialDisk(IntPtr quad, double inner, double outer, Int32 slices, Int32 loops, double start, double sweep) { Delegates.gluPartialDisk((IntPtr)quad, (double)inner, (double)outer, (Int32)slices, (Int32)loops, (double)start, (double)sweep); } public static void Perspective(double fovy, double aspect, double zNear, double zFar) { Delegates.gluPerspective((double)fovy, (double)aspect, (double)zNear, (double)zFar); } public static void PickMatrix(double x, double y, double delX, double delY, [Out] Int32[] viewport) { unsafe { fixed (Int32* viewport_ptr = viewport) { Delegates.gluPickMatrix((double)x, (double)y, (double)delX, (double)delY, (Int32*)viewport_ptr); } } } public static void PickMatrix(double x, double y, double delX, double delY, [Out] out Int32 viewport) { unsafe { fixed (Int32* viewport_ptr = &viewport) { Delegates.gluPickMatrix((double)x, (double)y, (double)delX, (double)delY, (Int32*)viewport_ptr); viewport = *viewport_ptr; } } } [System.CLSCompliant(false)] public static unsafe void PickMatrix(double x, double y, double delX, double delY, [Out] Int32* viewport) { Delegates.gluPickMatrix((double)x, (double)y, (double)delX, (double)delY, (Int32*)viewport); } public static Int32 Project(double objX, double objY, double objZ, double[] model, double[] proj, Int32[] view, double[] winX, double[] winY, double[] winZ) { unsafe { fixed (double* model_ptr = model) fixed (double* proj_ptr = proj) fixed (Int32* view_ptr = view) fixed (double* winX_ptr = winX) fixed (double* winY_ptr = winY) fixed (double* winZ_ptr = winZ) { return Delegates.gluProject((double)objX, (double)objY, (double)objZ, (double*)model_ptr, (double*)proj_ptr, (Int32*)view_ptr, (double*)winX_ptr, (double*)winY_ptr, (double*)winZ_ptr); } } } public static Int32 Project(double objX, double objY, double objZ, ref double model, ref double proj, ref Int32 view, ref double winX, ref double winY, ref double winZ) { unsafe { fixed (double* model_ptr = &model) fixed (double* proj_ptr = &proj) fixed (Int32* view_ptr = &view) fixed (double* winX_ptr = &winX) fixed (double* winY_ptr = &winY) fixed (double* winZ_ptr = &winZ) { return Delegates.gluProject((double)objX, (double)objY, (double)objZ, (double*)model_ptr, (double*)proj_ptr, (Int32*)view_ptr, (double*)winX_ptr, (double*)winY_ptr, (double*)winZ_ptr); } } } [System.CLSCompliant(false)] public static unsafe Int32 Project(double objX, double objY, double objZ, double* model, double* proj, Int32* view, double* winX, double* winY, double* winZ) { return Delegates.gluProject((double)objX, (double)objY, (double)objZ, (double*)model, (double*)proj, (Int32*)view, (double*)winX, (double*)winY, (double*)winZ); } public static void PwlCurve(IntPtr nurb, Int32 count, float[] data, Int32 stride, OpenTK.Graphics.NurbsTrim type) { unsafe { fixed (float* data_ptr = data) { Delegates.gluPwlCurve((IntPtr)nurb, (Int32)count, (float*)data_ptr, (Int32)stride, (OpenTK.Graphics.NurbsTrim)type); } } } public static void PwlCurve(IntPtr nurb, Int32 count, ref float data, Int32 stride, OpenTK.Graphics.NurbsTrim type) { unsafe { fixed (float* data_ptr = &data) { Delegates.gluPwlCurve((IntPtr)nurb, (Int32)count, (float*)data_ptr, (Int32)stride, (OpenTK.Graphics.NurbsTrim)type); } } } [System.CLSCompliant(false)] public static unsafe void PwlCurve(IntPtr nurb, Int32 count, float* data, Int32 stride, OpenTK.Graphics.NurbsTrim type) { Delegates.gluPwlCurve((IntPtr)nurb, (Int32)count, (float*)data, (Int32)stride, (OpenTK.Graphics.NurbsTrim)type); } public static void QuadricCallback(IntPtr quad, OpenTK.Graphics.QuadricCallback which, Delegate CallBackFunc) { Delegates.gluQuadricCallback((IntPtr)quad, (OpenTK.Graphics.QuadricCallback)which, (Delegate)CallBackFunc); } public static void QuadricDrawStyle(IntPtr quad, OpenTK.Graphics.QuadricDrawStyle draw) { Delegates.gluQuadricDrawStyle((IntPtr)quad, (OpenTK.Graphics.QuadricDrawStyle)draw); } public static void QuadricNormal(IntPtr quad, OpenTK.Graphics.QuadricNormal normal) { Delegates.gluQuadricNormals((IntPtr)quad, (OpenTK.Graphics.QuadricNormal)normal); } public static void QuadricOrientation(IntPtr quad, OpenTK.Graphics.QuadricOrientation orientation) { Delegates.gluQuadricOrientation((IntPtr)quad, (OpenTK.Graphics.QuadricOrientation)orientation); } public static void QuadricTexture(IntPtr quad, bool texture) { Delegates.gluQuadricTexture((IntPtr)quad, (bool)texture); } public static Int32 ScaleImage(PixelFormat format, Int32 wIn, Int32 hIn, PixelType typeIn, IntPtr dataIn, Int32 wOut, Int32 hOut, PixelType typeOut, [Out] IntPtr dataOut) { unsafe { return Delegates.gluScaleImage((PixelFormat)format, (Int32)wIn, (Int32)hIn, (PixelType)typeIn, (IntPtr)dataIn, (Int32)wOut, (Int32)hOut, (PixelType)typeOut, (IntPtr)dataOut); } } public static Int32 ScaleImage(PixelFormat format, Int32 wIn, Int32 hIn, PixelType typeIn, [In, Out] object dataIn, Int32 wOut, Int32 hOut, PixelType typeOut, [In, Out] object dataOut) { unsafe { System.Runtime.InteropServices.GCHandle dataIn_ptr = System.Runtime.InteropServices.GCHandle.Alloc(dataIn, System.Runtime.InteropServices.GCHandleType.Pinned); System.Runtime.InteropServices.GCHandle dataOut_ptr = System.Runtime.InteropServices.GCHandle.Alloc(dataOut, System.Runtime.InteropServices.GCHandleType.Pinned); try { return Delegates.gluScaleImage((PixelFormat)format, (Int32)wIn, (Int32)hIn, (PixelType)typeIn, (IntPtr)dataIn_ptr.AddrOfPinnedObject(), (Int32)wOut, (Int32)hOut, (PixelType)typeOut, (IntPtr)dataOut_ptr.AddrOfPinnedObject()); } finally { dataIn_ptr.Free(); dataOut_ptr.Free(); } } } public static void Sphere(IntPtr quad, double radius, Int32 slices, Int32 stacks) { Delegates.gluSphere((IntPtr)quad, (double)radius, (Int32)slices, (Int32)stacks); } public static void TessBeginContour(IntPtr tess) { Delegates.gluTessBeginContour((IntPtr)tess); } public static void TessBeginPolygon(IntPtr tess, IntPtr data) { unsafe { Delegates.gluTessBeginPolygon((IntPtr)tess, (IntPtr)data); } } public static void TessBeginPolygon(IntPtr tess, [In, Out] object data) { unsafe { System.Runtime.InteropServices.GCHandle data_ptr = System.Runtime.InteropServices.GCHandle.Alloc(data, System.Runtime.InteropServices.GCHandleType.Pinned); try { Delegates.gluTessBeginPolygon((IntPtr)tess, (IntPtr)data_ptr.AddrOfPinnedObject()); } finally { data_ptr.Free(); } } } public static void TessCallback(IntPtr tess, OpenTK.Graphics.TessCallback which, Delegate CallBackFunc) { Delegates.gluTessCallback((IntPtr)tess, (OpenTK.Graphics.TessCallback)which, (Delegate)CallBackFunc); } public static void TessEndContour(IntPtr tess) { Delegates.gluTessEndContour((IntPtr)tess); } public static void TessEndPolygon(IntPtr tess) { Delegates.gluTessEndPolygon((IntPtr)tess); } public static void TessNormal(IntPtr tess, double valueX, double valueY, double valueZ) { Delegates.gluTessNormal((IntPtr)tess, (double)valueX, (double)valueY, (double)valueZ); } public static void TessProperty(IntPtr tess, OpenTK.Graphics.TessParameter which, double data) { Delegates.gluTessProperty((IntPtr)tess, (OpenTK.Graphics.TessParameter)which, (double)data); } public static void TessVertex(IntPtr tess, double[] location, IntPtr data) { unsafe { fixed (double* location_ptr = location) { Delegates.gluTessVertex((IntPtr)tess, (double*)location_ptr, (IntPtr)data); } } } public static void TessVertex(IntPtr tess, double[] location, [In, Out] object data) { unsafe { fixed (double* location_ptr = location) { System.Runtime.InteropServices.GCHandle data_ptr = System.Runtime.InteropServices.GCHandle.Alloc(data, System.Runtime.InteropServices.GCHandleType.Pinned); try { Delegates.gluTessVertex((IntPtr)tess, (double*)location_ptr, (IntPtr)data_ptr.AddrOfPinnedObject()); } finally { data_ptr.Free(); } } } } public static void TessVertex(IntPtr tess, ref double location, IntPtr data) { unsafe { fixed (double* location_ptr = &location) { Delegates.gluTessVertex((IntPtr)tess, (double*)location_ptr, (IntPtr)data); } } } public static void TessVertex(IntPtr tess, ref double location, [In, Out] object data) { unsafe { fixed (double* location_ptr = &location) { System.Runtime.InteropServices.GCHandle data_ptr = System.Runtime.InteropServices.GCHandle.Alloc(data, System.Runtime.InteropServices.GCHandleType.Pinned); try { Delegates.gluTessVertex((IntPtr)tess, (double*)location_ptr, (IntPtr)data_ptr.AddrOfPinnedObject()); } finally { data_ptr.Free(); } } } } [System.CLSCompliant(false)] public static unsafe void TessVertex(IntPtr tess, double* location, IntPtr data) { Delegates.gluTessVertex((IntPtr)tess, (double*)location, (IntPtr)data); } [System.CLSCompliant(false)] public static unsafe void TessVertex(IntPtr tess, double* location, [In, Out] object data) { System.Runtime.InteropServices.GCHandle data_ptr = System.Runtime.InteropServices.GCHandle.Alloc(data, System.Runtime.InteropServices.GCHandleType.Pinned); try { Delegates.gluTessVertex((IntPtr)tess, (double*)location, (IntPtr)data_ptr.AddrOfPinnedObject()); } finally { data_ptr.Free(); } } public static Int32 UnProject(double winX, double winY, double winZ, double[] model, double[] proj, Int32[] view, double[] objX, double[] objY, double[] objZ) { unsafe { fixed (double* model_ptr = model) fixed (double* proj_ptr = proj) fixed (Int32* view_ptr = view) fixed (double* objX_ptr = objX) fixed (double* objY_ptr = objY) fixed (double* objZ_ptr = objZ) { return Delegates.gluUnProject((double)winX, (double)winY, (double)winZ, (double*)model_ptr, (double*)proj_ptr, (Int32*)view_ptr, (double*)objX_ptr, (double*)objY_ptr, (double*)objZ_ptr); } } } public static Int32 UnProject(double winX, double winY, double winZ, ref double model, ref double proj, ref Int32 view, ref double objX, ref double objY, ref double objZ) { unsafe { fixed (double* model_ptr = &model) fixed (double* proj_ptr = &proj) fixed (Int32* view_ptr = &view) fixed (double* objX_ptr = &objX) fixed (double* objY_ptr = &objY) fixed (double* objZ_ptr = &objZ) { return Delegates.gluUnProject((double)winX, (double)winY, (double)winZ, (double*)model_ptr, (double*)proj_ptr, (Int32*)view_ptr, (double*)objX_ptr, (double*)objY_ptr, (double*)objZ_ptr); } } } [System.CLSCompliant(false)] public static unsafe Int32 UnProject(double winX, double winY, double winZ, double* model, double* proj, Int32* view, double* objX, double* objY, double* objZ) { return Delegates.gluUnProject((double)winX, (double)winY, (double)winZ, (double*)model, (double*)proj, (Int32*)view, (double*)objX, (double*)objY, (double*)objZ); } public static Int32 UnProject4(double winX, double winY, double winZ, double clipW, double[] model, double[] proj, Int32[] view, double near, double far, double[] objX, double[] objY, double[] objZ, double[] objW) { unsafe { fixed (double* model_ptr = model) fixed (double* proj_ptr = proj) fixed (Int32* view_ptr = view) fixed (double* objX_ptr = objX) fixed (double* objY_ptr = objY) fixed (double* objZ_ptr = objZ) fixed (double* objW_ptr = objW) { return Delegates.gluUnProject4((double)winX, (double)winY, (double)winZ, (double)clipW, (double*)model_ptr, (double*)proj_ptr, (Int32*)view_ptr, (double)near, (double)far, (double*)objX_ptr, (double*)objY_ptr, (double*)objZ_ptr, (double*)objW_ptr); } } } public static Int32 UnProject4(double winX, double winY, double winZ, double clipW, ref double model, ref double proj, ref Int32 view, double near, double far, ref double objX, ref double objY, ref double objZ, ref double objW) { unsafe { fixed (double* model_ptr = &model) fixed (double* proj_ptr = &proj) fixed (Int32* view_ptr = &view) fixed (double* objX_ptr = &objX) fixed (double* objY_ptr = &objY) fixed (double* objZ_ptr = &objZ) fixed (double* objW_ptr = &objW) { return Delegates.gluUnProject4((double)winX, (double)winY, (double)winZ, (double)clipW, (double*)model_ptr, (double*)proj_ptr, (Int32*)view_ptr, (double)near, (double)far, (double*)objX_ptr, (double*)objY_ptr, (double*)objZ_ptr, (double*)objW_ptr); } } } [System.CLSCompliant(false)] public static unsafe Int32 UnProject4(double winX, double winY, double winZ, double clipW, double* model, double* proj, Int32* view, double near, double far, double* objX, double* objY, double* objZ, double* objW) { return Delegates.gluUnProject4((double)winX, (double)winY, (double)winZ, (double)clipW, (double*)model, (double*)proj, (Int32*)view, (double)near, (double)far, (double*)objX, (double*)objY, (double*)objZ, (double*)objW); } public static partial class Ext { public static void NurbsCallbackData(IntPtr nurb, IntPtr userData) { unsafe { Delegates.gluNurbsCallbackDataEXT((IntPtr)nurb, (IntPtr)userData); } } public static void NurbsCallbackData(IntPtr nurb, [In, Out] object userData) { unsafe { System.Runtime.InteropServices.GCHandle userData_ptr = System.Runtime.InteropServices.GCHandle.Alloc(userData, System.Runtime.InteropServices.GCHandleType.Pinned); try { Delegates.gluNurbsCallbackDataEXT((IntPtr)nurb, (IntPtr)userData_ptr.AddrOfPinnedObject()); } finally { userData_ptr.Free(); } } } } public static partial class Sgi { public static Int32 TexFilterFunc(TextureTarget target, SgisTextureFilter4 filtertype, float[] parms, Int32 n, [Out] float[] weights) { unsafe { fixed (float* parms_ptr = parms) fixed (float* weights_ptr = weights) { return Delegates.gluTexFilterFuncSGI((TextureTarget)target, (SgisTextureFilter4)filtertype, (float*)parms_ptr, (Int32)n, (float*)weights_ptr); } } } public static Int32 TexFilterFunc(TextureTarget target, SgisTextureFilter4 filtertype, ref float parms, Int32 n, [Out] out float weights) { unsafe { fixed (float* parms_ptr = &parms) fixed (float* weights_ptr = &weights) { Int32 retval = Delegates.gluTexFilterFuncSGI((TextureTarget)target, (SgisTextureFilter4)filtertype, (float*)parms_ptr, (Int32)n, (float*)weights_ptr); weights = *weights_ptr; return retval; } } } [System.CLSCompliant(false)] public static unsafe Int32 TexFilterFunc(TextureTarget target, SgisTextureFilter4 filtertype, float* parms, Int32 n, [Out] float* weights) { return Delegates.gluTexFilterFuncSGI((TextureTarget)target, (SgisTextureFilter4)filtertype, (float*)parms, (Int32)n, (float*)weights); } } } }
// 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 defines an internal class used to throw exceptions in BCL code. // The main purpose is to reduce code size. // // The old way to throw an exception generates quite a lot IL code and assembly code. // Following is an example: // C# source // throw new ArgumentNullException(nameof(key), SR.ArgumentNull_Key); // IL code: // IL_0003: ldstr "key" // IL_0008: ldstr "ArgumentNull_Key" // IL_000d: call string System.Environment::GetResourceString(string) // IL_0012: newobj instance void System.ArgumentNullException::.ctor(string,string) // IL_0017: throw // which is 21bytes in IL. // // So we want to get rid of the ldstr and call to Environment.GetResource in IL. // In order to do that, I created two enums: ExceptionResource, ExceptionArgument to represent the // argument name and resource name in a small integer. The source code will be changed to // ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key, ExceptionResource.ArgumentNull_Key); // // The IL code will be 7 bytes. // IL_0008: ldc.i4.4 // IL_0009: ldc.i4.4 // IL_000a: call void System.ThrowHelper::ThrowArgumentNullException(valuetype System.ExceptionArgument) // IL_000f: ldarg.0 // // This will also reduce the Jitted code size a lot. // // It is very important we do this for generic classes because we can easily generate the same code // multiple times for different instantiation. // using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Runtime.Serialization; using System.Diagnostics; namespace System { [StackTraceHidden] internal static class ThrowHelper { internal static void ThrowArrayTypeMismatchException() { throw new ArrayTypeMismatchException(); } internal static void ThrowInvalidTypeWithPointersNotSupported(Type targetType) { throw new ArgumentException(SR.Format(SR.Argument_InvalidTypeWithPointersNotSupported, targetType)); } internal static void ThrowIndexOutOfRangeException() { throw new IndexOutOfRangeException(); } internal static void ThrowArgumentOutOfRangeException() { throw new ArgumentOutOfRangeException(); } internal static void ThrowArgumentException_DestinationTooShort() { throw new ArgumentException(SR.Argument_DestinationTooShort); } internal static void ThrowArgumentOutOfRange_IndexException() { throw GetArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_Index); } internal static void ThrowIndexArgumentOutOfRange_NeedNonNegNumException() { throw GetArgumentOutOfRangeException(ExceptionArgument.index, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); } internal static void ThrowLengthArgumentOutOfRange_ArgumentOutOfRange_NeedNonNegNum() { throw GetArgumentOutOfRangeException(ExceptionArgument.length, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); } internal static void ThrowStartIndexArgumentOutOfRange_ArgumentOutOfRange_Index() { throw GetArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index); } internal static void ThrowCountArgumentOutOfRange_ArgumentOutOfRange_Count() { throw GetArgumentOutOfRangeException(ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_Count); } internal static void ThrowWrongKeyTypeArgumentException(object key, Type targetType) { throw GetWrongKeyTypeArgumentException(key, targetType); } internal static void ThrowWrongValueTypeArgumentException(object value, Type targetType) { throw GetWrongValueTypeArgumentException(value, targetType); } private static ArgumentException GetAddingDuplicateWithKeyArgumentException(object key) { return new ArgumentException(SR.Format(SR.Argument_AddingDuplicateWithKey, key)); } internal static void ThrowAddingDuplicateWithKeyArgumentException(object key) { throw GetAddingDuplicateWithKeyArgumentException(key); } internal static void ThrowKeyNotFoundException() { throw new KeyNotFoundException(); } internal static void ThrowArgumentException(ExceptionResource resource) { throw GetArgumentException(resource); } internal static void ThrowArgumentException(ExceptionResource resource, ExceptionArgument argument) { throw GetArgumentException(resource, argument); } private static ArgumentNullException GetArgumentNullException(ExceptionArgument argument) { return new ArgumentNullException(GetArgumentName(argument)); } internal static void ThrowArgumentNullException(ExceptionArgument argument) { throw GetArgumentNullException(argument); } internal static void ThrowArgumentNullException(ExceptionResource resource) { throw new ArgumentNullException(GetResourceString(resource)); } internal static void ThrowArgumentNullException(ExceptionArgument argument, ExceptionResource resource) { throw new ArgumentNullException(GetArgumentName(argument), GetResourceString(resource)); } internal static void ThrowArgumentOutOfRangeException(ExceptionArgument argument) { throw new ArgumentOutOfRangeException(GetArgumentName(argument)); } internal static void ThrowArgumentOutOfRangeException(ExceptionArgument argument, ExceptionResource resource) { throw GetArgumentOutOfRangeException(argument, resource); } internal static void ThrowArgumentOutOfRangeException(ExceptionArgument argument, int paramNumber, ExceptionResource resource) { throw GetArgumentOutOfRangeException(argument, paramNumber, resource); } internal static void ThrowInvalidOperationException(ExceptionResource resource) { throw GetInvalidOperationException(resource); } internal static void ThrowInvalidOperationException(ExceptionResource resource, Exception e) { throw new InvalidOperationException(GetResourceString(resource), e); } internal static void ThrowSerializationException(ExceptionResource resource) { throw new SerializationException(GetResourceString(resource)); } internal static void ThrowSecurityException(ExceptionResource resource) { throw new System.Security.SecurityException(GetResourceString(resource)); } internal static void ThrowRankException(ExceptionResource resource) { throw new RankException(GetResourceString(resource)); } internal static void ThrowNotSupportedException(ExceptionResource resource) { throw new NotSupportedException(GetResourceString(resource)); } internal static void ThrowUnauthorizedAccessException(ExceptionResource resource) { throw new UnauthorizedAccessException(GetResourceString(resource)); } internal static void ThrowObjectDisposedException(string objectName, ExceptionResource resource) { throw new ObjectDisposedException(objectName, GetResourceString(resource)); } internal static void ThrowObjectDisposedException(ExceptionResource resource) { throw new ObjectDisposedException(null, GetResourceString(resource)); } internal static void ThrowNotSupportedException() { throw new NotSupportedException(); } internal static void ThrowAggregateException(List<Exception> exceptions) { throw new AggregateException(exceptions); } internal static void ThrowOutOfMemoryException() { throw new OutOfMemoryException(); } internal static void ThrowArgumentException_Argument_InvalidArrayType() { throw GetArgumentException(ExceptionResource.Argument_InvalidArrayType); } internal static void ThrowInvalidOperationException_InvalidOperation_EnumNotStarted() { throw GetInvalidOperationException(ExceptionResource.InvalidOperation_EnumNotStarted); } internal static void ThrowInvalidOperationException_InvalidOperation_EnumEnded() { throw GetInvalidOperationException(ExceptionResource.InvalidOperation_EnumEnded); } internal static void ThrowInvalidOperationException_EnumCurrent(int index) { throw GetInvalidOperationException_EnumCurrent(index); } internal static void ThrowInvalidOperationException_InvalidOperation_EnumFailedVersion() { throw GetInvalidOperationException(ExceptionResource.InvalidOperation_EnumFailedVersion); } internal static void ThrowInvalidOperationException_InvalidOperation_EnumOpCantHappen() { throw GetInvalidOperationException(ExceptionResource.InvalidOperation_EnumOpCantHappen); } internal static void ThrowArraySegmentCtorValidationFailedExceptions(Array array, int offset, int count) { throw GetArraySegmentCtorValidationFailedException(array, offset, count); } private static Exception GetArraySegmentCtorValidationFailedException(Array array, int offset, int count) { if (array == null) return GetArgumentNullException(ExceptionArgument.array); if (offset < 0) return GetArgumentOutOfRangeException(ExceptionArgument.offset, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); if (count < 0) return GetArgumentOutOfRangeException(ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); Debug.Assert(array.Length - offset < count); return GetArgumentException(ExceptionResource.Argument_InvalidOffLen); } private static ArgumentException GetArgumentException(ExceptionResource resource) { return new ArgumentException(GetResourceString(resource)); } internal static InvalidOperationException GetInvalidOperationException(ExceptionResource resource) { return new InvalidOperationException(GetResourceString(resource)); } private static ArgumentException GetWrongKeyTypeArgumentException(object key, Type targetType) { return new ArgumentException(SR.Format(SR.Arg_WrongType, key, targetType), nameof(key)); } private static ArgumentException GetWrongValueTypeArgumentException(object value, Type targetType) { return new ArgumentException(SR.Format(SR.Arg_WrongType, value, targetType), nameof(value)); } internal static ArgumentOutOfRangeException GetArgumentOutOfRangeException(ExceptionArgument argument, ExceptionResource resource) { return new ArgumentOutOfRangeException(GetArgumentName(argument), GetResourceString(resource)); } private static ArgumentException GetArgumentException(ExceptionResource resource, ExceptionArgument argument) { return new ArgumentException(GetResourceString(resource), GetArgumentName(argument)); } private static ArgumentOutOfRangeException GetArgumentOutOfRangeException(ExceptionArgument argument, int paramNumber, ExceptionResource resource) { return new ArgumentOutOfRangeException(GetArgumentName(argument) + "[" + paramNumber.ToString() + "]", GetResourceString(resource)); } private static InvalidOperationException GetInvalidOperationException_EnumCurrent(int index) { return GetInvalidOperationException( index < 0 ? ExceptionResource.InvalidOperation_EnumNotStarted : ExceptionResource.InvalidOperation_EnumEnded); } // Allow nulls for reference types and Nullable<U>, but not for value types. // Aggressively inline so the jit evaluates the if in place and either drops the call altogether // Or just leaves null test and call to the Non-returning ThrowHelper.ThrowArgumentNullException [MethodImpl(MethodImplOptions.AggressiveInlining)] internal static void IfNullAndNullsAreIllegalThenThrow<T>(object value, ExceptionArgument argName) { // Note that default(T) is not equal to null for value types except when T is Nullable<U>. if (!(default(T) == null) && value == null) ThrowHelper.ThrowArgumentNullException(argName); } // This function will convert an ExceptionArgument enum value to the argument name string. [MethodImpl(MethodImplOptions.NoInlining)] private static string GetArgumentName(ExceptionArgument argument) { Debug.Assert(Enum.IsDefined(typeof(ExceptionArgument), argument), "The enum value is not defined, please check the ExceptionArgument Enum."); return argument.ToString(); } // This function will convert an ExceptionResource enum value to the resource string. [MethodImpl(MethodImplOptions.NoInlining)] private static string GetResourceString(ExceptionResource resource) { Debug.Assert(Enum.IsDefined(typeof(ExceptionResource), resource), "The enum value is not defined, please check the ExceptionResource Enum."); return SR.GetResourceString(resource.ToString()); } } // // The convention for this enum is using the argument name as the enum name // internal enum ExceptionArgument { obj, dictionary, array, info, key, collection, list, match, converter, capacity, index, startIndex, value, count, arrayIndex, name, item, options, view, sourceBytesToCopy, action, comparison, offset, newSize, elementType, length, length1, length2, length3, lengths, len, lowerBounds, sourceArray, destinationArray, sourceIndex, destinationIndex, indices, index1, index2, index3, other, comparer, endIndex, keys, creationOptions, timeout, tasks, scheduler, continuationFunction, millisecondsTimeout, millisecondsDelay, function, exceptions, exception, cancellationToken, delay, asyncResult, endMethod, endFunction, beginMethod, continuationOptions, continuationAction, concurrencyLevel, text, callBack, type, stateMachine, pHandle, values, task, s, keyValuePair, input, ownedMemory, pointer } // // The convention for this enum is using the resource name as the enum name // internal enum ExceptionResource { Argument_ImplementIComparable, Argument_InvalidType, Argument_InvalidArgumentForComparison, Argument_InvalidRegistryKeyPermissionCheck, ArgumentOutOfRange_NeedNonNegNum, Arg_ArrayPlusOffTooSmall, Arg_NonZeroLowerBound, Arg_RankMultiDimNotSupported, Arg_RegKeyDelHive, Arg_RegKeyStrLenBug, Arg_RegSetStrArrNull, Arg_RegSetMismatchedKind, Arg_RegSubKeyAbsent, Arg_RegSubKeyValueAbsent, Argument_AddingDuplicate, Serialization_InvalidOnDeser, Serialization_MissingKeys, Serialization_NullKey, Argument_InvalidArrayType, NotSupported_KeyCollectionSet, NotSupported_ValueCollectionSet, ArgumentOutOfRange_SmallCapacity, ArgumentOutOfRange_Index, Argument_InvalidOffLen, Argument_ItemNotExist, ArgumentOutOfRange_Count, ArgumentOutOfRange_InvalidThreshold, ArgumentOutOfRange_ListInsert, NotSupported_ReadOnlyCollection, InvalidOperation_CannotRemoveFromStackOrQueue, InvalidOperation_EmptyQueue, InvalidOperation_EnumOpCantHappen, InvalidOperation_EnumFailedVersion, InvalidOperation_EmptyStack, ArgumentOutOfRange_BiggerThanCollection, InvalidOperation_EnumNotStarted, InvalidOperation_EnumEnded, NotSupported_SortedListNestedWrite, InvalidOperation_NoValue, InvalidOperation_RegRemoveSubKey, Security_RegistryPermission, UnauthorizedAccess_RegistryNoWrite, ObjectDisposed_RegKeyClosed, NotSupported_InComparableType, Argument_InvalidRegistryOptionsCheck, Argument_InvalidRegistryViewCheck, InvalidOperation_NullArray, Arg_MustBeType, Arg_NeedAtLeast1Rank, ArgumentOutOfRange_HugeArrayNotSupported, Arg_RanksAndBounds, Arg_RankIndices, Arg_Need1DArray, Arg_Need2DArray, Arg_Need3DArray, NotSupported_FixedSizeCollection, ArgumentException_OtherNotArrayOfCorrectLength, Rank_MultiDimNotSupported, InvalidOperation_IComparerFailed, ArgumentOutOfRange_EndIndexStartIndex, Arg_LowerBoundsMustMatch, Arg_BogusIComparer, Task_WaitMulti_NullTask, Task_ThrowIfDisposed, Task_Start_TaskCompleted, Task_Start_Promise, Task_Start_ContinuationTask, Task_Start_AlreadyStarted, Task_RunSynchronously_TaskCompleted, Task_RunSynchronously_Continuation, Task_RunSynchronously_Promise, Task_RunSynchronously_AlreadyStarted, Task_MultiTaskContinuation_NullTask, Task_MultiTaskContinuation_EmptyTaskList, Task_Dispose_NotCompleted, Task_Delay_InvalidMillisecondsDelay, Task_Delay_InvalidDelay, Task_ctor_LRandSR, Task_ContinueWith_NotOnAnything, Task_ContinueWith_ESandLR, TaskT_TransitionToFinal_AlreadyCompleted, TaskCompletionSourceT_TrySetException_NullException, TaskCompletionSourceT_TrySetException_NoExceptions, Memory_ThrowIfDisposed, Memory_OutstandingReferences, InvalidOperation_WrongAsyncResultOrEndCalledMultiple, ConcurrentDictionary_ConcurrencyLevelMustBePositive, ConcurrentDictionary_CapacityMustNotBeNegative, ConcurrentDictionary_TypeOfValueIncorrect, ConcurrentDictionary_TypeOfKeyIncorrect, ConcurrentDictionary_KeyAlreadyExisted, ConcurrentDictionary_ItemKeyIsNull, ConcurrentDictionary_IndexIsNegative, ConcurrentDictionary_ArrayNotLargeEnough, ConcurrentDictionary_ArrayIncorrectType, ConcurrentCollection_SyncRoot_NotSupported, ArgumentOutOfRange_Enum, InvalidOperation_HandleIsNotInitialized, AsyncMethodBuilder_InstanceNotInitialized, ArgumentNull_SafeHandle, } }
//----------------------------------------------------------------------------- // Copyright (c) 2012 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. //----------------------------------------------------------------------------- // ForestEditorGui Script Methods function ForestEditorGui::setActiveTool( %this, %tool ) { if ( %tool == ForestTools->BrushTool ) ForestEditTabBook.selectPage(0); Parent::setActiveTool( %this, %tool ); } /// This is called by the editor when the active forest has /// changed giving us a chance to update the GUI. function ForestEditorGui::onActiveForestUpdated( %this, %forest, %createNew ) { %gotForest = isObject( %forest ); // Give the user a chance to add a forest. if ( !%gotForest && %createNew ) { MessageBoxYesNo( "Forest", "There is not a Forest in this mission. Do you want to add one?", %this @ ".createForest();", "" ); return; } } /// Called from a message box when a forest is not found. function ForestEditorGui::createForest( %this ) { if ( isObject( theForest ) ) { error( "Cannot create a second 'theForest' Forest!" ); return; } // Allocate the Forest and make it undoable. new Forest( theForest ) { dataFile = ""; parentGroup = "MissionGroup"; }; MECreateUndoAction::submit( theForest ); ForestEditorInspector.inspect( theForest ); EWorldEditor.isDirty = true; } function ForestEditorGui::newBrush( %this ) { %internalName = getUniqueInternalName( "Brush", ForestBrushGroup, true ); %brush = new ForestBrush() { internalName = %internalName; parentGroup = ForestBrushGroup; }; MECreateUndoAction::submit( %brush ); ForestEditBrushTree.open( ForestBrushGroup ); ForestEditBrushTree.buildVisibleTree(true); %item = ForestEditBrushTree.findItemByObjectId( %brush ); ForestEditBrushTree.clearSelection(); ForestEditBrushTree.addSelection( %item ); ForestEditBrushTree.scrollVisible( %item ); ForestEditorPlugin.dirty = true; } function ForestEditorGui::newElement( %this ) { %sel = ForestEditBrushTree.getSelectedObject(); if ( !isObject( %sel ) ) %parentGroup = ForestBrushGroup; else { if ( %sel.getClassName() $= "ForestBrushElement" ) %parentGroup = %sel.parentGroup; else %parentGroup = %sel; } %internalName = getUniqueInternalName( "Element", ForestBrushGroup, true ); %element = new ForestBrushElement() { internalName = %internalName; parentGroup = %parentGroup; }; MECreateUndoAction::submit( %element ); ForestEditBrushTree.clearSelection(); ForestEditBrushTree.buildVisibleTree( true ); %item = ForestEditBrushTree.findItemByObjectId( %element.getId() ); ForestEditBrushTree.scrollVisible( %item ); ForestEditBrushTree.addSelection( %item ); ForestEditorPlugin.dirty = true; } function ForestEditorGui::deleteBrushOrElement( %this ) { ForestEditBrushTree.deleteSelection(); ForestEditorPlugin.dirty = true; } function ForestEditorGui::newMesh( %this ) { %spec = "All Mesh Files|*.dts;*.dae|DTS|*.dts|DAE|*.dae"; %dlg = new OpenFileDialog() { Filters = %spec; DefaultPath = $Pref::WorldEditor::LastPath; DefaultFile = ""; ChangePath = true; }; %ret = %dlg.Execute(); if ( %ret ) { $Pref::WorldEditor::LastPath = filePath( %dlg.FileName ); %fullPath = makeRelativePath( %dlg.FileName, getMainDotCSDir() ); %file = fileBase( %fullPath ); } %dlg.delete(); if ( !%ret ) return; %name = getUniqueName( %file ); %str = "datablock TSForestItemData( " @ %name @ " ) { shapeFile = \"" @ %fullPath @ "\"; };"; eval( %str ); if ( isObject( %name ) ) { ForestEditMeshTree.clearSelection(); ForestEditMeshTree.buildVisibleTree( true ); %item = ForestEditMeshTree.findItemByObjectId( %name.getId() ); ForestEditMeshTree.scrollVisible( %item ); ForestEditMeshTree.addSelection( %item ); ForestDataManager.setDirty( %name, "art/forest/managedItemData.cs" ); %element = new ForestBrushElement() { internalName = %name; forestItemData = %name; parentGroup = ForestBrushGroup; }; ForestEditBrushTree.clearSelection(); ForestEditBrushTree.buildVisibleTree( true ); %item = ForestEditBrushTree.findItemByObjectId( %element.getId() ); ForestEditBrushTree.scrollVisible( %item ); ForestEditBrushTree.addSelection( %item ); pushInstantGroup(); %action = new MECreateUndoAction() { actionName = "Create TSForestItemData"; }; popInstantGroup(); %action.addObject( %name ); %action.addObject( %element ); %action.addToManager( Editor.getUndoManager() ); ForestEditorPlugin.dirty = true; } } function ForestEditorGui::deleteMesh( %this ) { %obj = ForestEditMeshTree.getSelectedObject(); // Can't delete itemData's that are in use without // crashing at the moment... if ( isObject( %obj ) ) { MessageBoxOKCancel( "Warning", "Deleting this mesh will also delete BrushesElements and ForestItems referencing it.", "ForestEditorGui.okDeleteMesh(" @ %obj @ ");", "" ); } } function ForestEditorGui::okDeleteMesh( %this, %mesh ) { // Remove mesh from file ForestDataManager.removeObjectFromFile( %mesh, "art/forest/managedItemData.cs" ); // Submitting undo actions is handled in code. %this.deleteMeshSafe( %mesh ); // Update TreeViews. ForestEditBrushTree.buildVisibleTree( true ); ForestEditMeshTree.buildVisibleTree( true ); ForestEditorPlugin.dirty = true; } function ForestEditorGui::validateBrushSize( %this ) { %minBrushSize = 1; %maxBrushSize = getWord(ETerrainEditor.maxBrushSize, 0); %val = $ThisControl.getText(); if(%val < %minBrushSize) $ThisControl.setValue(%minBrushSize); else if(%val > %maxBrushSize) $ThisControl.setValue(%maxBrushSize); } // Child-control Script Methods function ForestEditMeshTree::onSelect( %this, %obj ) { ForestEditorInspector.inspect( %obj ); } function ForestEditBrushTree::onRemoveSelection( %this, %obj ) { %this.buildVisibleTree( true ); ForestTools->BrushTool.collectElements(); if ( %this.getSelectedItemsCount() == 1 ) ForestEditorInspector.inspect( %obj ); else ForestEditorInspector.inspect( "" ); } function ForestEditBrushTree::onAddSelection( %this, %obj ) { %this.buildVisibleTree( true ); ForestTools->BrushTool.collectElements(); if ( %this.getSelectedItemsCount() == 1 ) ForestEditorInspector.inspect( %obj ); else ForestEditorInspector.inspect( "" ); } function ForestEditTabBook::onTabSelected( %this, %text, %idx ) { %bbg = ForestEditorPalleteWindow.findObjectByInternalName("BrushButtonGroup"); %mbg = ForestEditorPalleteWindow.findObjectByInternalName("MeshButtonGroup"); %bbg.setVisible( false ); %mbg.setVisible( false ); if ( %text $= "Brushes" ) { %bbg.setVisible( true ); %obj = ForestEditBrushTree.getSelectedObject(); ForestEditorInspector.inspect( %obj ); } else if ( %text $= "Meshes" ) { %mbg.setVisible( true ); %obj = ForestEditMeshTree.getSelectedObject(); ForestEditorInspector.inspect( %obj ); } } function ForestEditBrushTree::onDeleteSelection( %this ) { %list = ForestEditBrushTree.getSelectedObjectList(); MEDeleteUndoAction::submit( %list, true ); ForestEditorPlugin.dirty = true; } function ForestEditBrushTree::onDragDropped( %this ) { ForestEditorPlugin.dirty = true; } function ForestEditMeshTree::onDragDropped( %this ) { ForestEditorPlugin.dirty = true; } function ForestEditMeshTree::onDeleteObject( %this, %obj ) { // return true - skip delete. return true; } function ForestEditMeshTree::onDoubleClick( %this ) { %obj = %this.getSelectedObject(); %name = getUniqueInternalName( %obj.getName(), ForestBrushGroup, true ); %element = new ForestBrushElement() { internalName = %name; forestItemData = %obj.getName(); parentGroup = ForestBrushGroup; }; //ForestDataManager.setDirty( %element, "art/forest/brushes.cs" ); ForestEditBrushTree.clearSelection(); ForestEditBrushTree.buildVisibleTree( true ); %item = ForestEditBrushTree.findItemByObjectId( %element ); ForestEditBrushTree.scrollVisible( %item ); ForestEditBrushTree.addSelection( %item ); ForestEditorPlugin.dirty = true; } function ForestEditBrushTree::handleRenameObject( %this, %name, %obj ) { if ( %name !$= "" ) { %found = ForestBrushGroup.findObjectByInternalName( %name ); if ( isObject( %found ) && %found.getId() != %obj.getId() ) { MessageBoxOK( "Error", "Brush or Element with that name already exists.", "" ); // true as in, we handled it, don't rename the object. return true; } } // Since we aren't showing any groups whens inspecting a ForestBrushGroup // we can't push this event off to the inspector to handle. //return GuiTreeViewCtrl::handleRenameObject( %this, %name, %obj ); // The instant group will try to add our // UndoAction if we don't disable it. pushInstantGroup(); %nameOrClass = %obj.getName(); if ( %nameOrClass $= "" ) %nameOrClass = %obj.getClassname(); %action = new InspectorFieldUndoAction() { actionName = %nameOrClass @ "." @ "internalName" @ " Change"; objectId = %obj.getId(); fieldName = "internalName"; fieldValue = %obj.internalName; arrayIndex = 0; inspectorGui = ""; }; // Restore the instant group. popInstantGroup(); %action.addToManager( Editor.getUndoManager() ); EWorldEditor.isDirty = true; return false; } function ForestEditorInspector::inspect( %this, %obj ) { if ( isObject( %obj ) ) %class = %obj.getClassName(); %this.showObjectName = false; %this.showCustomFields = false; switch$ ( %class ) { case "ForestBrush": %this.groupFilters = "+NOTHING,-Ungrouped"; case "ForestBrushElement": %this.groupFilters = "+ForestBrushElement,-Ungrouped"; case "TSForestItemData": %this.groupFilters = "+Media,+Wind"; default: %this.groupFilters = ""; } Parent::inspect( %this, %obj ); } function ForestEditorInspector::onInspectorFieldModified( %this, %object, %fieldName, %oldValue, %newValue ) { // The instant group will try to add our // UndoAction if we don't disable it. %instantGroup = $InstantGroup; $InstantGroup = 0; %nameOrClass = %object.getName(); if ( %nameOrClass $= "" ) %nameOrClass = %object.getClassname(); %action = new InspectorFieldUndoAction() { actionName = %nameOrClass @ "." @ %fieldName @ " Change"; objectId = %object.getId(); fieldName = %fieldName; fieldValue = %oldValue; inspectorGui = %this; }; // Restore the instant group. $InstantGroup = %instantGroup; %action.addToManager( Editor.getUndoManager() ); if ( %object.getClassName() $= "TSForestItemData" ) ForestDataManager.setDirty( %object ); ForestEditorPlugin.dirty = true; } function ForestEditorInspector::onFieldSelected( %this, %fieldName, %fieldTypeStr, %fieldDoc ) { //FieldInfoControl.setText( "<font:ArialBold:14>" @ %fieldName @ "<font:ArialItalic:14> (" @ %fieldTypeStr @ ") " NL "<font:Arial:14>" @ %fieldDoc ); } function ForestBrushSizeSliderCtrlContainer::onWake(%this) { %this-->slider.range = "1" SPC getWord(ETerrainEditor.maxBrushSize, 0); %this-->slider.setValue(ForestBrushSizeTextEditContainer-->textEdit.getValue()); }
// 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.Reflection; using System.Globalization; using System.Diagnostics; namespace System.Runtime.Serialization.Formatters.Binary { internal static class Converter { internal static readonly Type s_typeofISerializable = typeof(ISerializable); internal static readonly Type s_typeofString = typeof(string); internal static readonly Type s_typeofConverter = typeof(Converter); internal static readonly Type s_typeofBoolean = typeof(bool); internal static readonly Type s_typeofByte = typeof(byte); internal static readonly Type s_typeofChar = typeof(char); internal static readonly Type s_typeofDecimal = typeof(decimal); internal static readonly Type s_typeofDouble = typeof(double); internal static readonly Type s_typeofInt16 = typeof(short); internal static readonly Type s_typeofInt32 = typeof(int); internal static readonly Type s_typeofInt64 = typeof(long); internal static readonly Type s_typeofSByte = typeof(sbyte); internal static readonly Type s_typeofSingle = typeof(float); internal static readonly Type s_typeofTimeSpan = typeof(TimeSpan); internal static readonly Type s_typeofDateTime = typeof(DateTime); internal static readonly Type s_typeofUInt16 = typeof(ushort); internal static readonly Type s_typeofUInt32 = typeof(uint); internal static readonly Type s_typeofUInt64 = typeof(ulong); internal static readonly Type s_typeofObject = typeof(object); internal static readonly Type s_typeofSystemVoid = typeof(void); // In netfx the default assembly is mscorlib.dll --> typeof(string).Assembly. // In Core type string lives in System.Private.Corelib.dll which doesn't // contain all the types which are living in mscorlib in netfx. Therefore we // use our mscorlib facade which also contains manual type forwards for deserialization. internal static readonly Assembly s_urtAssembly = Assembly.Load("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"); internal static readonly string s_urtAssemblyString = s_urtAssembly.FullName; internal static readonly Assembly s_urtAlternativeAssembly = s_typeofString.Assembly; internal static readonly string s_urtAlternativeAssemblyString = s_urtAlternativeAssembly.FullName; // Arrays internal static readonly Type s_typeofTypeArray = typeof(Type[]); internal static readonly Type s_typeofObjectArray = typeof(object[]); internal static readonly Type s_typeofStringArray = typeof(string[]); internal static readonly Type s_typeofBooleanArray = typeof(bool[]); internal static readonly Type s_typeofByteArray = typeof(byte[]); internal static readonly Type s_typeofCharArray = typeof(char[]); internal static readonly Type s_typeofDecimalArray = typeof(decimal[]); internal static readonly Type s_typeofDoubleArray = typeof(double[]); internal static readonly Type s_typeofInt16Array = typeof(short[]); internal static readonly Type s_typeofInt32Array = typeof(int[]); internal static readonly Type s_typeofInt64Array = typeof(long[]); internal static readonly Type s_typeofSByteArray = typeof(sbyte[]); internal static readonly Type s_typeofSingleArray = typeof(float[]); internal static readonly Type s_typeofTimeSpanArray = typeof(TimeSpan[]); internal static readonly Type s_typeofDateTimeArray = typeof(DateTime[]); internal static readonly Type s_typeofUInt16Array = typeof(ushort[]); internal static readonly Type s_typeofUInt32Array = typeof(uint[]); internal static readonly Type s_typeofUInt64Array = typeof(ulong[]); internal static readonly Type s_typeofMarshalByRefObject = typeof(MarshalByRefObject); private const int PrimitiveTypeEnumLength = 17; //Number of PrimitiveTypeEnums private static volatile Type[] s_typeA; private static volatile Type[] s_arrayTypeA; private static volatile string[] s_valueA; private static volatile TypeCode[] s_typeCodeA; private static volatile InternalPrimitiveTypeE[] s_codeA; internal static InternalPrimitiveTypeE ToCode(Type type) => type == null ? ToPrimitiveTypeEnum(TypeCode.Empty) : type.IsPrimitive ? ToPrimitiveTypeEnum(Type.GetTypeCode(type)) : ReferenceEquals(type, s_typeofDateTime) ? InternalPrimitiveTypeE.DateTime : ReferenceEquals(type, s_typeofTimeSpan) ? InternalPrimitiveTypeE.TimeSpan : ReferenceEquals(type, s_typeofDecimal) ? InternalPrimitiveTypeE.Decimal : InternalPrimitiveTypeE.Invalid; internal static bool IsWriteAsByteArray(InternalPrimitiveTypeE code) { switch (code) { case InternalPrimitiveTypeE.Boolean: case InternalPrimitiveTypeE.Char: case InternalPrimitiveTypeE.Byte: case InternalPrimitiveTypeE.Double: case InternalPrimitiveTypeE.Int16: case InternalPrimitiveTypeE.Int32: case InternalPrimitiveTypeE.Int64: case InternalPrimitiveTypeE.SByte: case InternalPrimitiveTypeE.Single: case InternalPrimitiveTypeE.UInt16: case InternalPrimitiveTypeE.UInt32: case InternalPrimitiveTypeE.UInt64: return true; default: return false; } } internal static int TypeLength(InternalPrimitiveTypeE code) { switch (code) { case InternalPrimitiveTypeE.Boolean: return 1; case InternalPrimitiveTypeE.Char: return 2; case InternalPrimitiveTypeE.Byte: return 1; case InternalPrimitiveTypeE.Double: return 8; case InternalPrimitiveTypeE.Int16: return 2; case InternalPrimitiveTypeE.Int32: return 4; case InternalPrimitiveTypeE.Int64: return 8; case InternalPrimitiveTypeE.SByte: return 1; case InternalPrimitiveTypeE.Single: return 4; case InternalPrimitiveTypeE.UInt16: return 2; case InternalPrimitiveTypeE.UInt32: return 4; case InternalPrimitiveTypeE.UInt64: return 8; default: return 0; } } internal static InternalNameSpaceE GetNameSpaceEnum(InternalPrimitiveTypeE code, Type type, WriteObjectInfo objectInfo, out string typeName) { InternalNameSpaceE nameSpaceEnum = InternalNameSpaceE.None; typeName = null; if (code != InternalPrimitiveTypeE.Invalid) { switch (code) { case InternalPrimitiveTypeE.Boolean: case InternalPrimitiveTypeE.Char: case InternalPrimitiveTypeE.Byte: case InternalPrimitiveTypeE.Double: case InternalPrimitiveTypeE.Int16: case InternalPrimitiveTypeE.Int32: case InternalPrimitiveTypeE.Int64: case InternalPrimitiveTypeE.SByte: case InternalPrimitiveTypeE.Single: case InternalPrimitiveTypeE.UInt16: case InternalPrimitiveTypeE.UInt32: case InternalPrimitiveTypeE.UInt64: case InternalPrimitiveTypeE.DateTime: case InternalPrimitiveTypeE.TimeSpan: nameSpaceEnum = InternalNameSpaceE.XdrPrimitive; typeName = "System." + ToComType(code); break; case InternalPrimitiveTypeE.Decimal: nameSpaceEnum = InternalNameSpaceE.UrtSystem; typeName = "System." + ToComType(code); break; } } if ((nameSpaceEnum == InternalNameSpaceE.None) && type != null) { if (ReferenceEquals(type, s_typeofString)) { nameSpaceEnum = InternalNameSpaceE.XdrString; } else { if (objectInfo == null) { typeName = type.FullName; nameSpaceEnum = type.Assembly == s_urtAssembly ? InternalNameSpaceE.UrtSystem : InternalNameSpaceE.UrtUser; } else { typeName = objectInfo.GetTypeFullName(); nameSpaceEnum = objectInfo.GetAssemblyString().Equals(s_urtAssemblyString) ? InternalNameSpaceE.UrtSystem : InternalNameSpaceE.UrtUser; } } } return nameSpaceEnum; } internal static Type ToArrayType(InternalPrimitiveTypeE code) { if (s_arrayTypeA == null) { InitArrayTypeA(); } return s_arrayTypeA[(int)code]; } private static void InitTypeA() { var typeATemp = new Type[PrimitiveTypeEnumLength]; typeATemp[(int)InternalPrimitiveTypeE.Invalid] = null; typeATemp[(int)InternalPrimitiveTypeE.Boolean] = s_typeofBoolean; typeATemp[(int)InternalPrimitiveTypeE.Byte] = s_typeofByte; typeATemp[(int)InternalPrimitiveTypeE.Char] = s_typeofChar; typeATemp[(int)InternalPrimitiveTypeE.Decimal] = s_typeofDecimal; typeATemp[(int)InternalPrimitiveTypeE.Double] = s_typeofDouble; typeATemp[(int)InternalPrimitiveTypeE.Int16] = s_typeofInt16; typeATemp[(int)InternalPrimitiveTypeE.Int32] = s_typeofInt32; typeATemp[(int)InternalPrimitiveTypeE.Int64] = s_typeofInt64; typeATemp[(int)InternalPrimitiveTypeE.SByte] = s_typeofSByte; typeATemp[(int)InternalPrimitiveTypeE.Single] = s_typeofSingle; typeATemp[(int)InternalPrimitiveTypeE.TimeSpan] = s_typeofTimeSpan; typeATemp[(int)InternalPrimitiveTypeE.DateTime] = s_typeofDateTime; typeATemp[(int)InternalPrimitiveTypeE.UInt16] = s_typeofUInt16; typeATemp[(int)InternalPrimitiveTypeE.UInt32] = s_typeofUInt32; typeATemp[(int)InternalPrimitiveTypeE.UInt64] = s_typeofUInt64; s_typeA = typeATemp; } private static void InitArrayTypeA() { var arrayTypeATemp = new Type[PrimitiveTypeEnumLength]; arrayTypeATemp[(int)InternalPrimitiveTypeE.Invalid] = null; arrayTypeATemp[(int)InternalPrimitiveTypeE.Boolean] = s_typeofBooleanArray; arrayTypeATemp[(int)InternalPrimitiveTypeE.Byte] = s_typeofByteArray; arrayTypeATemp[(int)InternalPrimitiveTypeE.Char] = s_typeofCharArray; arrayTypeATemp[(int)InternalPrimitiveTypeE.Decimal] = s_typeofDecimalArray; arrayTypeATemp[(int)InternalPrimitiveTypeE.Double] = s_typeofDoubleArray; arrayTypeATemp[(int)InternalPrimitiveTypeE.Int16] = s_typeofInt16Array; arrayTypeATemp[(int)InternalPrimitiveTypeE.Int32] = s_typeofInt32Array; arrayTypeATemp[(int)InternalPrimitiveTypeE.Int64] = s_typeofInt64Array; arrayTypeATemp[(int)InternalPrimitiveTypeE.SByte] = s_typeofSByteArray; arrayTypeATemp[(int)InternalPrimitiveTypeE.Single] = s_typeofSingleArray; arrayTypeATemp[(int)InternalPrimitiveTypeE.TimeSpan] = s_typeofTimeSpanArray; arrayTypeATemp[(int)InternalPrimitiveTypeE.DateTime] = s_typeofDateTimeArray; arrayTypeATemp[(int)InternalPrimitiveTypeE.UInt16] = s_typeofUInt16Array; arrayTypeATemp[(int)InternalPrimitiveTypeE.UInt32] = s_typeofUInt32Array; arrayTypeATemp[(int)InternalPrimitiveTypeE.UInt64] = s_typeofUInt64Array; s_arrayTypeA = arrayTypeATemp; } internal static Type ToType(InternalPrimitiveTypeE code) { if (s_typeA == null) { InitTypeA(); } return s_typeA[(int)code]; } internal static Array CreatePrimitiveArray(InternalPrimitiveTypeE code, int length) { switch (code) { case InternalPrimitiveTypeE.Boolean: return new bool[length]; case InternalPrimitiveTypeE.Byte: return new byte[length]; case InternalPrimitiveTypeE.Char: return new char[length]; case InternalPrimitiveTypeE.Decimal: return new decimal[length]; case InternalPrimitiveTypeE.Double: return new double[length]; case InternalPrimitiveTypeE.Int16: return new short[length]; case InternalPrimitiveTypeE.Int32: return new int[length]; case InternalPrimitiveTypeE.Int64: return new long[length]; case InternalPrimitiveTypeE.SByte: return new sbyte[length]; case InternalPrimitiveTypeE.Single: return new float[length]; case InternalPrimitiveTypeE.TimeSpan: return new TimeSpan[length]; case InternalPrimitiveTypeE.DateTime: return new DateTime[length]; case InternalPrimitiveTypeE.UInt16: return new ushort[length]; case InternalPrimitiveTypeE.UInt32: return new uint[length]; case InternalPrimitiveTypeE.UInt64: return new ulong[length]; default: return null; } } internal static bool IsPrimitiveArray(Type type, out object typeInformation) { bool bIsPrimitive = true; if (ReferenceEquals(type, s_typeofBooleanArray)) typeInformation = InternalPrimitiveTypeE.Boolean; else if (ReferenceEquals(type, s_typeofByteArray)) typeInformation = InternalPrimitiveTypeE.Byte; else if (ReferenceEquals(type, s_typeofCharArray)) typeInformation = InternalPrimitiveTypeE.Char; else if (ReferenceEquals(type, s_typeofDoubleArray)) typeInformation = InternalPrimitiveTypeE.Double; else if (ReferenceEquals(type, s_typeofInt16Array)) typeInformation = InternalPrimitiveTypeE.Int16; else if (ReferenceEquals(type, s_typeofInt32Array)) typeInformation = InternalPrimitiveTypeE.Int32; else if (ReferenceEquals(type, s_typeofInt64Array)) typeInformation = InternalPrimitiveTypeE.Int64; else if (ReferenceEquals(type, s_typeofSByteArray)) typeInformation = InternalPrimitiveTypeE.SByte; else if (ReferenceEquals(type, s_typeofSingleArray)) typeInformation = InternalPrimitiveTypeE.Single; else if (ReferenceEquals(type, s_typeofUInt16Array)) typeInformation = InternalPrimitiveTypeE.UInt16; else if (ReferenceEquals(type, s_typeofUInt32Array)) typeInformation = InternalPrimitiveTypeE.UInt32; else if (ReferenceEquals(type, s_typeofUInt64Array)) typeInformation = InternalPrimitiveTypeE.UInt64; else { typeInformation = null; bIsPrimitive = false; } return bIsPrimitive; } private static void InitValueA() { var valueATemp = new string[PrimitiveTypeEnumLength]; valueATemp[(int)InternalPrimitiveTypeE.Invalid] = null; valueATemp[(int)InternalPrimitiveTypeE.Boolean] = "Boolean"; valueATemp[(int)InternalPrimitiveTypeE.Byte] = "Byte"; valueATemp[(int)InternalPrimitiveTypeE.Char] = "Char"; valueATemp[(int)InternalPrimitiveTypeE.Decimal] = "Decimal"; valueATemp[(int)InternalPrimitiveTypeE.Double] = "Double"; valueATemp[(int)InternalPrimitiveTypeE.Int16] = "Int16"; valueATemp[(int)InternalPrimitiveTypeE.Int32] = "Int32"; valueATemp[(int)InternalPrimitiveTypeE.Int64] = "Int64"; valueATemp[(int)InternalPrimitiveTypeE.SByte] = "SByte"; valueATemp[(int)InternalPrimitiveTypeE.Single] = "Single"; valueATemp[(int)InternalPrimitiveTypeE.TimeSpan] = "TimeSpan"; valueATemp[(int)InternalPrimitiveTypeE.DateTime] = "DateTime"; valueATemp[(int)InternalPrimitiveTypeE.UInt16] = "UInt16"; valueATemp[(int)InternalPrimitiveTypeE.UInt32] = "UInt32"; valueATemp[(int)InternalPrimitiveTypeE.UInt64] = "UInt64"; s_valueA = valueATemp; } internal static string ToComType(InternalPrimitiveTypeE code) { if (s_valueA == null) { InitValueA(); } return s_valueA[(int)code]; } private static void InitTypeCodeA() { var typeCodeATemp = new TypeCode[PrimitiveTypeEnumLength]; typeCodeATemp[(int)InternalPrimitiveTypeE.Invalid] = TypeCode.Object; typeCodeATemp[(int)InternalPrimitiveTypeE.Boolean] = TypeCode.Boolean; typeCodeATemp[(int)InternalPrimitiveTypeE.Byte] = TypeCode.Byte; typeCodeATemp[(int)InternalPrimitiveTypeE.Char] = TypeCode.Char; typeCodeATemp[(int)InternalPrimitiveTypeE.Decimal] = TypeCode.Decimal; typeCodeATemp[(int)InternalPrimitiveTypeE.Double] = TypeCode.Double; typeCodeATemp[(int)InternalPrimitiveTypeE.Int16] = TypeCode.Int16; typeCodeATemp[(int)InternalPrimitiveTypeE.Int32] = TypeCode.Int32; typeCodeATemp[(int)InternalPrimitiveTypeE.Int64] = TypeCode.Int64; typeCodeATemp[(int)InternalPrimitiveTypeE.SByte] = TypeCode.SByte; typeCodeATemp[(int)InternalPrimitiveTypeE.Single] = TypeCode.Single; typeCodeATemp[(int)InternalPrimitiveTypeE.TimeSpan] = TypeCode.Object; typeCodeATemp[(int)InternalPrimitiveTypeE.DateTime] = TypeCode.DateTime; typeCodeATemp[(int)InternalPrimitiveTypeE.UInt16] = TypeCode.UInt16; typeCodeATemp[(int)InternalPrimitiveTypeE.UInt32] = TypeCode.UInt32; typeCodeATemp[(int)InternalPrimitiveTypeE.UInt64] = TypeCode.UInt64; s_typeCodeA = typeCodeATemp; } // Returns a System.TypeCode from a InternalPrimitiveTypeE internal static TypeCode ToTypeCode(InternalPrimitiveTypeE code) { if (s_typeCodeA == null) { InitTypeCodeA(); } return s_typeCodeA[(int)code]; } private static void InitCodeA() { var codeATemp = new InternalPrimitiveTypeE[19]; codeATemp[(int)TypeCode.Empty] = InternalPrimitiveTypeE.Invalid; codeATemp[(int)TypeCode.Object] = InternalPrimitiveTypeE.Invalid; codeATemp[(int)TypeCode.DBNull] = InternalPrimitiveTypeE.Invalid; codeATemp[(int)TypeCode.Boolean] = InternalPrimitiveTypeE.Boolean; codeATemp[(int)TypeCode.Char] = InternalPrimitiveTypeE.Char; codeATemp[(int)TypeCode.SByte] = InternalPrimitiveTypeE.SByte; codeATemp[(int)TypeCode.Byte] = InternalPrimitiveTypeE.Byte; codeATemp[(int)TypeCode.Int16] = InternalPrimitiveTypeE.Int16; codeATemp[(int)TypeCode.UInt16] = InternalPrimitiveTypeE.UInt16; codeATemp[(int)TypeCode.Int32] = InternalPrimitiveTypeE.Int32; codeATemp[(int)TypeCode.UInt32] = InternalPrimitiveTypeE.UInt32; codeATemp[(int)TypeCode.Int64] = InternalPrimitiveTypeE.Int64; codeATemp[(int)TypeCode.UInt64] = InternalPrimitiveTypeE.UInt64; codeATemp[(int)TypeCode.Single] = InternalPrimitiveTypeE.Single; codeATemp[(int)TypeCode.Double] = InternalPrimitiveTypeE.Double; codeATemp[(int)TypeCode.Decimal] = InternalPrimitiveTypeE.Decimal; codeATemp[(int)TypeCode.DateTime] = InternalPrimitiveTypeE.DateTime; codeATemp[17] = InternalPrimitiveTypeE.Invalid; codeATemp[(int)TypeCode.String] = InternalPrimitiveTypeE.Invalid; s_codeA = codeATemp; } // Returns a InternalPrimitiveTypeE from a System.TypeCode internal static InternalPrimitiveTypeE ToPrimitiveTypeEnum(TypeCode typeCode) { if (s_codeA == null) { InitCodeA(); } return s_codeA[(int)typeCode]; } // Translates a string into an Object internal static object FromString(string value, InternalPrimitiveTypeE code) { // InternalPrimitiveTypeE needs to be a primitive type Debug.Assert((code != InternalPrimitiveTypeE.Invalid), "[Converter.FromString]!InternalPrimitiveTypeE.Invalid "); return code != InternalPrimitiveTypeE.Invalid ? Convert.ChangeType(value, ToTypeCode(code), CultureInfo.InvariantCulture) : value; } } }
using System.Diagnostics.CodeAnalysis; using System.IO.MemoryMappedFiles; #if NET using System.Runtime.Versioning; #endif using TinyIpc.Synchronization; namespace TinyIpc.IO; /// <summary> /// Wraps a MemoryMappedFile with inter process synchronization and signaling /// </summary> public class TinyMemoryMappedFile : IDisposable, ITinyMemoryMappedFile { private readonly Task fileWatcherTask; private readonly MemoryMappedFile memoryMappedFile; private readonly ITinyReadWriteLock readWriteLock; private readonly bool disposeLock; private readonly EventWaitHandle fileWaitHandle; private readonly EventWaitHandle disposeWaitHandle; private bool disposed; public event EventHandler? FileUpdated; public long MaxFileSize { get; } public const int DefaultMaxFileSize = 1024 * 1024; /// <summary> /// Initializes a new instance of the TinyMemoryMappedFile class. /// </summary> /// <param name="name">A system wide unique name, the name will have a prefix appended before use</param> #if NET [SupportedOSPlatform("windows")] #endif public TinyMemoryMappedFile(string name) : this(name, DefaultMaxFileSize) { } /// <summary> /// Initializes a new instance of the TinyMemoryMappedFile class. /// </summary> /// <param name="name">A system wide unique name, the name will have a prefix appended before use</param> /// <param name="maxFileSize">The maximum amount of data that can be written to the file memory mapped file</param> [SuppressMessage("Reliability", "CA2000:Dispose objects before losing scope", Justification = "Incorrect warning, lock is being disposed")] #if NET [SupportedOSPlatform("windows")] #endif public TinyMemoryMappedFile(string name, long maxFileSize) : this(name, maxFileSize, new TinyReadWriteLock(name), disposeLock: true) { } /// <summary> /// Initializes a new instance of the TinyMemoryMappedFile class. /// </summary> /// <param name="name">A system wide unique name, the name will have a prefix appended before use</param> /// <param name="maxFileSize">The maximum amount of data that can be written to the file memory mapped file</param> /// <param name="readWriteLock">A read/write lock that will be used to control access to the memory mapped file</param> /// <param name="disposeLock">Set to true if the read/write lock is to be disposed when this instance is disposed</param> #if NET [SupportedOSPlatform("windows")] #endif public TinyMemoryMappedFile(string name, long maxFileSize, ITinyReadWriteLock readWriteLock, bool disposeLock) : this(CreateOrOpenMemoryMappedFile(name, maxFileSize), CreateEventWaitHandle(name), maxFileSize, readWriteLock, disposeLock) { } /// <summary> /// Initializes a new instance of the TinyMemoryMappedFile class. /// </summary> /// <param name="memoryMappedFile">An instance of a memory mapped file</param> /// <param name="fileWaitHandle">A manual reset EventWaitHandle that is to be used to signal file changes</param> /// <param name="maxFileSize">The maximum amount of data that can be written to the file memory mapped file</param> /// <param name="readWriteLock">A read/write lock that will be used to control access to the memory mapped file</param> /// <param name="disposeLock">Set to true if the read/write lock is to be disposed when this instance is disposed</param> public TinyMemoryMappedFile(MemoryMappedFile memoryMappedFile, EventWaitHandle fileWaitHandle, long maxFileSize, ITinyReadWriteLock readWriteLock, bool disposeLock) { this.readWriteLock = readWriteLock ?? throw new ArgumentNullException(nameof(readWriteLock)); this.memoryMappedFile = memoryMappedFile ?? throw new ArgumentNullException(nameof(memoryMappedFile)); this.fileWaitHandle = fileWaitHandle ?? throw new ArgumentNullException(nameof(fileWaitHandle)); this.disposeLock = disposeLock; MaxFileSize = maxFileSize; disposeWaitHandle = new EventWaitHandle(false, EventResetMode.ManualReset); fileWatcherTask = Task.Run(() => FileWatcher()); } ~TinyMemoryMappedFile() { Dispose(false); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (disposed) return; // Always set the dispose wait handle even when dispised by the finalizer // otherwize the file watcher task will needleessly have to wait for its timeout. disposeWaitHandle?.Set(); fileWatcherTask?.Wait(TinyReadWriteLock.DefaultWaitTimeout); if (disposing) { memoryMappedFile.Dispose(); if (disposeLock && readWriteLock is IDisposable disposableLock) { disposableLock.Dispose(); } fileWaitHandle.Dispose(); disposeWaitHandle?.Dispose(); } disposed = true; } /// <summary> /// Gets the file size /// </summary> /// <returns>File size</returns> public int GetFileSize() { readWriteLock.AcquireReadLock(); try { using var accessor = memoryMappedFile.CreateViewAccessor(); return accessor.ReadInt32(0); } finally { readWriteLock.ReleaseReadLock(); } } /// <summary> /// Reads the content of the memory mapped file with a read lock in place. /// </summary> /// <returns>File content</returns> public byte[] Read() { readWriteLock.AcquireReadLock(); try { return InternalRead(); } finally { readWriteLock.ReleaseReadLock(); } } /// <summary> /// Replaces the content of the memory mapped file with a write lock in place. /// </summary> public void Write(byte[] data) { if (data is null) throw new ArgumentNullException(nameof(data)); if (data.Length > MaxFileSize) throw new ArgumentOutOfRangeException(nameof(data), "Length greater than max file size"); readWriteLock.AcquireWriteLock(); try { InternalWrite(data); } finally { readWriteLock.ReleaseWriteLock(); fileWaitHandle.Set(); fileWaitHandle.Reset(); } } /// <summary> /// Reads and then replaces the content of the memory mapped file with a write lock in place. /// </summary> public void ReadWrite(Func<byte[], byte[]> updateFunc) { if (updateFunc is null) throw new ArgumentNullException(nameof(updateFunc)); readWriteLock.AcquireWriteLock(); try { InternalWrite(updateFunc(InternalRead())); } finally { readWriteLock.ReleaseWriteLock(); fileWaitHandle.Set(); fileWaitHandle.Reset(); } } private void FileWatcher() { var waitHandles = new[] { disposeWaitHandle, fileWaitHandle }; while (!disposed) { var result = WaitHandle.WaitAny(waitHandles, TinyReadWriteLock.DefaultWaitTimeout); // Triggers when disposed if (result == 0 || disposed) return; // Triggers when the file is changed if (result == 1) FileUpdated?.Invoke(this, EventArgs.Empty); } } private byte[] InternalRead() { using var accessor = memoryMappedFile.CreateViewAccessor(); var length = accessor.ReadInt32(0); var data = new byte[length]; accessor.ReadArray(sizeof(int), data, 0, length); return data; } private void InternalWrite(byte[] data) { if (data.Length > MaxFileSize) throw new ArgumentOutOfRangeException(nameof(data), "Length greater than max file size"); using var accessor = memoryMappedFile.CreateViewAccessor(); accessor.Write(0, data.Length); accessor.WriteArray(sizeof(int), data, 0, data.Length); } /// <summary> /// Create or open a MemoryMappedFile that can be used to construct a TinyMemoryMappedFile /// </summary> /// <param name="name">A system wide unique name, the name will have a prefix appended</param> /// <param name="maxFileSize">The maximum amount of data that can be written to the file memory mapped file</param> /// <returns>A system wide MemoryMappedFile</returns> #if NET [SupportedOSPlatform("windows")] #endif public static MemoryMappedFile CreateOrOpenMemoryMappedFile(string name, long maxFileSize) { if (string.IsNullOrWhiteSpace(name)) throw new ArgumentException("File must be named", nameof(name)); if (maxFileSize <= 0) throw new ArgumentException("Max file size can not be less than 1 byte", nameof(maxFileSize)); return MemoryMappedFile.CreateOrOpen("TinyMemoryMappedFile_MemoryMappedFile_" + name, maxFileSize + sizeof(int)); } /// <summary> /// Create or open an EventWaitHandle that can be used to construct a TinyMemoryMappedFile /// </summary> /// <param name="name">A system wide unique name, the name will have a prefix appended</param> /// <returns>A system wide EventWaitHandle</returns> public static EventWaitHandle CreateEventWaitHandle(string name) { if (string.IsNullOrWhiteSpace(name)) throw new ArgumentException("EventWaitHandle must be named", nameof(name)); return new EventWaitHandle(false, EventResetMode.ManualReset, "TinyMemoryMappedFile_WaitHandle_" + name); } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.SignalR.Infrastructure; using Microsoft.AspNetCore.SignalR.Json; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Newtonsoft.Json; namespace Microsoft.AspNetCore.SignalR.Hubs { /// <summary> /// Handles all communication over the hubs persistent connection. /// </summary> [SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling", Justification = "This dispatcher makes use of many interfaces.")] public class HubDispatcher : PersistentConnection { private const string HubsSuffix = "/hubs"; private const string JsSuffix = "/js"; private readonly List<HubDescriptor> _hubs = new List<HubDescriptor>(); private readonly bool _enableJavaScriptProxies; private readonly bool _enableDetailedErrors; private IJavaScriptProxyGenerator _proxyGenerator; private IHubManager _manager; private IHubRequestParser _requestParser; private JsonSerializer _serializer; private IParameterResolver _binder; private IHubPipelineInvoker _pipelineInvoker; private IPerformanceCounterManager _counters; private bool _isDebuggingEnabled = false; private static readonly MethodInfo _continueWithMethod = typeof(HubDispatcher).GetMethod("ContinueWith", BindingFlags.NonPublic | BindingFlags.Static); /// <summary> /// Initializes an instance of the <see cref="HubDispatcher"/> class. /// </summary> /// <param name="options">Configuration settings determining whether to enable JS proxies and provide clients with detailed hub errors.</param> public HubDispatcher(IOptions<SignalROptions> optionsAccessor) { if (optionsAccessor == null) { throw new ArgumentNullException("optionsAccessor"); } var options = optionsAccessor.Value; _enableJavaScriptProxies = options.Hubs.EnableJavaScriptProxies; _enableDetailedErrors = options.Hubs.EnableDetailedErrors; } protected override ILogger Logger { get { return LoggerFactory.CreateLogger<HubDispatcher>(); } } internal override string GroupPrefix { get { return PrefixHelper.HubGroupPrefix; } } public override void Initialize(IServiceProvider serviceProvider) { if (serviceProvider == null) { throw new ArgumentNullException(nameof(serviceProvider)); } _proxyGenerator = _enableJavaScriptProxies ? serviceProvider.GetRequiredService<IJavaScriptProxyGenerator>() : new EmptyJavaScriptProxyGenerator(); _manager = serviceProvider.GetRequiredService<IHubManager>(); _binder = serviceProvider.GetRequiredService<IParameterResolver>(); _requestParser = serviceProvider.GetRequiredService<IHubRequestParser>(); _serializer = serviceProvider.GetRequiredService<JsonSerializer>(); _pipelineInvoker = serviceProvider.GetRequiredService<IHubPipelineInvoker>(); _counters = serviceProvider.GetRequiredService<IPerformanceCounterManager>(); base.Initialize(serviceProvider); } protected override bool AuthorizeRequest(HttpRequest request) { if (request == null) { throw new ArgumentNullException("request"); } // Populate _hubs string data = request.Query["connectionData"]; if (!String.IsNullOrEmpty(data)) { var clientHubInfo = JsonSerializer.Parse<IEnumerable<ClientHubInfo>>(data); // If there's any hubs then perform the auth check if (clientHubInfo != null && clientHubInfo.Any()) { var hubCache = new Dictionary<string, HubDescriptor>(StringComparer.OrdinalIgnoreCase); foreach (var hubInfo in clientHubInfo) { if (hubCache.ContainsKey(hubInfo.Name)) { throw new InvalidOperationException(Resources.Error_DuplicateHubNamesInConnectionData); } // Try to find the associated hub type HubDescriptor hubDescriptor = _manager.EnsureHub(hubInfo.Name, _counters.ErrorsHubResolutionTotal, _counters.ErrorsHubResolutionPerSec, _counters.ErrorsAllTotal, _counters.ErrorsAllPerSec); if (_pipelineInvoker.AuthorizeConnect(hubDescriptor, request)) { // Add this to the list of hub descriptors this connection is interested in hubCache.Add(hubDescriptor.Name, hubDescriptor); } } _hubs.AddRange(hubCache.Values); // If we have any hubs in the list then we're authorized return _hubs.Count > 0; } } return base.AuthorizeRequest(request); } /// <summary> /// Processes the hub's incoming method calls. /// </summary> protected override Task OnReceived(HttpRequest request, string connectionId, string data) { HubRequest hubRequest = _requestParser.Parse(data, _serializer); // Create the hub HubDescriptor descriptor = _manager.EnsureHub(hubRequest.Hub, _counters.ErrorsHubInvocationTotal, _counters.ErrorsHubInvocationPerSec, _counters.ErrorsAllTotal, _counters.ErrorsAllPerSec); IJsonValue[] parameterValues = hubRequest.ParameterValues; // Resolve the method MethodDescriptor methodDescriptor = _manager.GetHubMethod(descriptor.Name, hubRequest.Method, parameterValues); if (methodDescriptor == null) { // Empty (noop) method descriptor // Use: Forces the hub pipeline module to throw an error. This error is encapsulated in the HubDispatcher. // Encapsulating it in the HubDispatcher prevents the error from bubbling up to the transport level. // Specifically this allows us to return a faulted task (call .fail on client) and to not cause the // transport to unintentionally fail. IEnumerable<MethodDescriptor> availableMethods = _manager.GetHubMethods(descriptor.Name, m => m.Name == hubRequest.Method); methodDescriptor = new NullMethodDescriptor(descriptor, hubRequest.Method, availableMethods); } // Resolving the actual state object var tracker = new StateChangeTracker(hubRequest.State); var hub = CreateHub(request, descriptor, connectionId, tracker, throwIfFailedToCreate: true); return InvokeHubPipeline(hub, parameterValues, methodDescriptor, hubRequest, tracker) .ContinueWithPreservedCulture(task => hub.Dispose(), TaskContinuationOptions.ExecuteSynchronously); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Exceptions are flown to the caller.")] private Task InvokeHubPipeline(IHub hub, IJsonValue[] parameterValues, MethodDescriptor methodDescriptor, HubRequest hubRequest, StateChangeTracker tracker) { // TODO: Make adding parameters here pluggable? IValueProvider? ;) HubInvocationProgress progress = GetProgressInstance(methodDescriptor, value => SendProgressUpdate(hub.Context.ConnectionId, tracker, value, hubRequest), Logger); Task<object> piplineInvocation; try { var args = _binder.ResolveMethodParameters(methodDescriptor, parameterValues); // We need to add the IProgress<T> instance after resolving the method as the resolution // itself looks for overload matches based on the incoming arg values if (progress != null) { args = args.Concat(new[] { progress }).ToList(); } var context = new HubInvokerContext(hub, tracker, methodDescriptor, args); // Invoke the pipeline and save the task piplineInvocation = _pipelineInvoker.Invoke(context); } catch (Exception ex) { piplineInvocation = TaskAsyncHelper.FromError<object>(ex); } // Determine if we have a faulted task or not and handle it appropriately. return piplineInvocation.ContinueWithPreservedCulture(task => { if (progress != null) { // Stop ability to send any more progress updates progress.SetComplete(); } if (task.IsFaulted) { return ProcessResponse(tracker, result: null, request: hubRequest, error: task.Exception); } else if (task.IsCanceled) { return ProcessResponse(tracker, result: null, request: hubRequest, error: new OperationCanceledException()); } else { return ProcessResponse(tracker, task.Result, hubRequest, error: null); } }) .FastUnwrap(); } private static HubInvocationProgress GetProgressInstance(MethodDescriptor methodDescriptor, Func<object, Task> sendProgressFunc, ILogger logger) { HubInvocationProgress progress = null; if (methodDescriptor.ProgressReportingType != null) { progress = HubInvocationProgress.Create(methodDescriptor.ProgressReportingType, sendProgressFunc, logger); } return progress; } public override Task ProcessRequestCore(HttpContext context) { if (context == null) { throw new ArgumentNullException("context"); } // Trim any trailing slashes string normalized = context.Request.LocalPath().TrimEnd('/'); int suffixLength = -1; if (normalized.EndsWith(HubsSuffix, StringComparison.OrdinalIgnoreCase)) { suffixLength = HubsSuffix.Length; } else if (normalized.EndsWith(JsSuffix, StringComparison.OrdinalIgnoreCase)) { suffixLength = JsSuffix.Length; } if (suffixLength != -1) { // Generate the proper JS proxy url string hubUrl = normalized.Substring(0, normalized.Length - suffixLength); // Generate the proxy context.Response.ContentType = JsonUtility.JavaScriptMimeType; return context.Response.End(_proxyGenerator.GenerateProxy(hubUrl)); } // TODO: Is debugging enabled // _isDebuggingEnabled = context.Environment.IsDebugEnabled(); return base.ProcessRequestCore(context); } internal static Task Connect(IHub hub) { return hub.OnConnected(); } internal static Task Reconnect(IHub hub) { return hub.OnReconnected(); } internal static Task Disconnect(IHub hub, bool stopCalled) { return hub.OnDisconnected(stopCalled); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "A faulted task is returned.")] internal static Task<object> Incoming(IHubIncomingInvokerContext context) { var tcs = new TaskCompletionSource<object>(); try { object result = context.MethodDescriptor.Invoker(context.Hub, context.Args.ToArray()); Type returnType = context.MethodDescriptor.ReturnType; if (typeof(Task).IsAssignableFrom(returnType)) { var task = (Task)result; if (!returnType.GetTypeInfo().IsGenericType) { task.ContinueWith(tcs); } else { // Get the <T> in Task<T> Type resultType = returnType.GetGenericArguments().Single(); Type genericTaskType = typeof(Task<>).MakeGenericType(resultType); // Get the correct ContinueWith overload var parameter = Expression.Parameter(typeof(object)); // TODO: Cache this whole thing // Action<object> callback = result => ContinueWith((Task<T>)result, tcs); MethodInfo continueWithMethod = _continueWithMethod.MakeGenericMethod(resultType); Expression body = Expression.Call(continueWithMethod, Expression.Convert(parameter, genericTaskType), Expression.Constant(tcs)); var continueWithInvoker = Expression.Lambda<Action<object>>(body, parameter).Compile(); continueWithInvoker.Invoke(result); } } else { tcs.TrySetResult(result); } } catch (Exception ex) { tcs.TrySetUnwrappedException(ex); } return tcs.Task; } internal static Task Outgoing(IHubOutgoingInvokerContext context) { ConnectionMessage message = context.GetConnectionMessage(); return context.Connection.Send(message); } protected override Task OnConnected(HttpRequest request, string connectionId) { return ExecuteHubEvent(request, connectionId, hub => _pipelineInvoker.Connect(hub)); } protected override Task OnReconnected(HttpRequest request, string connectionId) { return ExecuteHubEvent(request, connectionId, hub => _pipelineInvoker.Reconnect(hub)); } protected override IList<string> OnRejoiningGroups(HttpRequest request, IList<string> groups, string connectionId) { return _hubs.Select(hubDescriptor => { string groupPrefix = hubDescriptor.Name + "."; var hubGroups = groups.Where(g => g.StartsWith(groupPrefix, StringComparison.OrdinalIgnoreCase)) .Select(g => g.Substring(groupPrefix.Length)) .ToList(); return _pipelineInvoker.RejoiningGroups(hubDescriptor, request, hubGroups) .Select(g => groupPrefix + g); }).SelectMany(groupsToRejoin => groupsToRejoin).ToList(); } protected override Task OnDisconnected(HttpRequest request, string connectionId, bool stopCalled) { return ExecuteHubEvent(request, connectionId, hub => _pipelineInvoker.Disconnect(hub, stopCalled)); } protected override IList<string> GetSignals(string userId, string connectionId) { var signals = _hubs.SelectMany(info => { var items = new List<string> { PrefixHelper.GetHubName(info.Name), PrefixHelper.GetHubConnectionId(info.CreateQualifiedName(connectionId)), }; if (!String.IsNullOrEmpty(userId)) { items.Add(PrefixHelper.GetHubUserId(info.CreateQualifiedName(userId))); } return items; }) .Concat(new[] { PrefixHelper.GetConnectionId(connectionId) }); return signals.ToList(); } private Task ExecuteHubEvent(HttpRequest request, string connectionId, Func<IHub, Task> action) { var hubs = GetHubs(request, connectionId).ToList(); var operations = hubs.Select(instance => action(instance).OrEmpty().Catch(Logger)).ToArray(); if (operations.Length == 0) { DisposeHubs(hubs); return TaskAsyncHelper.Empty; } var tcs = new TaskCompletionSource<object>(); Task.Factory.ContinueWhenAll(operations, tasks => { DisposeHubs(hubs); var faulted = tasks.FirstOrDefault(t => t.IsFaulted); if (faulted != null) { tcs.SetUnwrappedException(faulted.Exception); } else if (tasks.Any(t => t.IsCanceled)) { tcs.SetCanceled(); } else { tcs.SetResult(null); } }); return tcs.Task; } private IHub CreateHub(HttpRequest request, HubDescriptor descriptor, string connectionId, StateChangeTracker tracker = null, bool throwIfFailedToCreate = false) { try { var hub = _manager.ResolveHub(descriptor.Name); if (hub != null) { tracker = tracker ?? new StateChangeTracker(); hub.Context = new HubCallerContext(request, connectionId); hub.Clients = new HubConnectionContext(_pipelineInvoker, Connection, descriptor.Name, connectionId, tracker); hub.Groups = new GroupManager(Connection, PrefixHelper.GetHubGroupName(descriptor.Name)); } return hub; } catch (Exception ex) { Logger.LogInformation(String.Format("Error creating Hub {0}. {1}", descriptor.Name, ex.Message)); if (throwIfFailedToCreate) { throw; } return null; } } private IEnumerable<IHub> GetHubs(HttpRequest request, string connectionId) { return from descriptor in _hubs select CreateHub(request, descriptor, connectionId) into hub where hub != null select hub; } private static void DisposeHubs(IEnumerable<IHub> hubs) { foreach (var hub in hubs) { hub.Dispose(); } } private Task SendProgressUpdate(string connectionId, StateChangeTracker tracker, object value, HubRequest request) { var hubResult = new HubResponse { State = tracker.GetChanges(), Progress = new { I = request.Id, D = value }, // We prefix the ID here to ensure old clients treat this as a hub response // but fail to lookup a corresponding callback and thus no-op Id = "P|" + request.Id, }; return Connection.Send(connectionId, hubResult); } private Task ProcessResponse(StateChangeTracker tracker, object result, HubRequest request, Exception error) { var hubResult = new HubResponse { State = tracker.GetChanges(), Result = result, Id = request.Id, }; if (error != null) { _counters.ErrorsHubInvocationTotal.Increment(); _counters.ErrorsHubInvocationPerSec.Increment(); _counters.ErrorsAllTotal.Increment(); _counters.ErrorsAllPerSec.Increment(); var hubError = error.InnerException as HubException; if (_enableDetailedErrors || hubError != null) { var exception = error.InnerException ?? error; hubResult.StackTrace = _isDebuggingEnabled ? exception.StackTrace : null; hubResult.Error = exception.Message; if (hubError != null) { hubResult.IsHubException = true; hubResult.ErrorData = hubError.ErrorData; } } else { hubResult.Error = String.Format(CultureInfo.CurrentCulture, Resources.Error_HubInvocationFailed, request.Hub, request.Method); } } return Transport.Send(hubResult); } private static void ContinueWith<T>(Task<T> task, TaskCompletionSource<object> tcs) { if (task.IsCompleted) { // Fast path for tasks that completed synchronously ContinueSync<T>(task, tcs); } else { ContinueAsync<T>(task, tcs); } } private static void ContinueSync<T>(Task<T> task, TaskCompletionSource<object> tcs) { if (task.IsFaulted) { tcs.TrySetUnwrappedException(task.Exception); } else if (task.IsCanceled) { tcs.TrySetCanceled(); } else { tcs.TrySetResult(task.Result); } } private static void ContinueAsync<T>(Task<T> task, TaskCompletionSource<object> tcs) { task.ContinueWithPreservedCulture(t => { if (t.IsFaulted) { tcs.TrySetUnwrappedException(t.Exception); } else if (t.IsCanceled) { tcs.TrySetCanceled(); } else { tcs.TrySetResult(t.Result); } }); } [SuppressMessage("Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses", Justification = "It is instantiated through JSON deserialization.")] private class ClientHubInfo { public string Name { get; set; } } } }
using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading.Tasks; using Abp.Configuration; using Abp.Dependency; using Abp.Domain.Repositories; using Abp.Domain.Uow; using Abp.Events.Bus.Entities; using Abp.Events.Bus.Handlers; using Abp.Runtime.Caching; using System.Globalization; namespace Abp.Localization { /// <summary> /// Manages host and tenant languages. /// </summary> public class ApplicationLanguageManager : IApplicationLanguageManager, IEventHandler<EntityChangedEventData<ApplicationLanguage>>, ISingletonDependency { /// <summary> /// Cache name for languages. /// </summary> public const string CacheName = "AbpZeroLanguages"; private ITypedCache<int, Dictionary<string, ApplicationLanguage>> LanguageListCache => _cacheManager.GetCache<int, Dictionary<string, ApplicationLanguage>>(CacheName); private readonly IRepository<ApplicationLanguage> _languageRepository; private readonly ICacheManager _cacheManager; private readonly IUnitOfWorkManager _unitOfWorkManager; private readonly ISettingManager _settingManager; /// <summary> /// Initializes a new instance of the <see cref="ApplicationLanguageManager"/> class. /// </summary> public ApplicationLanguageManager( IRepository<ApplicationLanguage> languageRepository, ICacheManager cacheManager, IUnitOfWorkManager unitOfWorkManager, ISettingManager settingManager) { _languageRepository = languageRepository; _cacheManager = cacheManager; _unitOfWorkManager = unitOfWorkManager; _settingManager = settingManager; } /// <summary> /// Gets list of all languages available to given tenant (or null for host) /// </summary> /// <param name="tenantId">TenantId or null for host</param> public virtual async Task<IReadOnlyList<ApplicationLanguage>> GetLanguagesAsync(int? tenantId) { return (await GetLanguageDictionaryAsync(tenantId)).Values.ToImmutableList(); } public virtual async Task<IReadOnlyList<ApplicationLanguage>> GetActiveLanguagesAsync(int? tenantId) { return (await GetLanguagesAsync(tenantId)).Where(l => !l.IsDisabled).ToImmutableList(); } /// <summary> /// Gets list of all languages available to given tenant (or null for host) /// </summary> /// <param name="tenantId">TenantId or null for host</param> public virtual IReadOnlyList<ApplicationLanguage> GetLanguages(int? tenantId) { return (GetLanguageDictionary(tenantId)).Values.ToImmutableList(); } public virtual IReadOnlyList<ApplicationLanguage> GetActiveLanguages(int? tenantId) { return GetLanguages(tenantId).Where(l => !l.IsDisabled).ToImmutableList(); } /// <summary> /// Adds a new language. /// </summary> /// <param name="language">The language.</param> public virtual async Task AddAsync(ApplicationLanguage language) { await _unitOfWorkManager.WithUnitOfWorkAsync(async () => { if ((await GetLanguagesAsync(language.TenantId)).Any(l => l.Name == language.Name)) { throw new AbpException("There is already a language with name = " + language.Name); } using (_unitOfWorkManager.Current.SetTenantId(language.TenantId)) { await _languageRepository.InsertAsync(language); await _unitOfWorkManager.Current.SaveChangesAsync(); } }); } /// <summary> /// Adds a new language. /// </summary> /// <param name="language">The language.</param> public virtual void Add(ApplicationLanguage language) { _unitOfWorkManager.WithUnitOfWork(() => { if ((GetLanguages(language.TenantId)).Any(l => l.Name == language.Name)) { throw new AbpException("There is already a language with name = " + language.Name); } using (_unitOfWorkManager.Current.SetTenantId(language.TenantId)) { _languageRepository.Insert(language); _unitOfWorkManager.Current.SaveChanges(); } }); } /// <summary> /// Deletes a language. /// </summary> /// <param name="tenantId">Tenant Id or null for host.</param> /// <param name="languageName">Name of the language.</param> public virtual async Task RemoveAsync(int? tenantId, string languageName) { await _unitOfWorkManager.WithUnitOfWorkAsync(async () => { var currentLanguage = (await GetLanguagesAsync(tenantId)).FirstOrDefault(l => l.Name == languageName); if (currentLanguage == null) { return; } if (currentLanguage.TenantId == null && tenantId != null) { throw new AbpException("Can not delete a host language from tenant!"); } using (_unitOfWorkManager.Current.SetTenantId(currentLanguage.TenantId)) { await _languageRepository.DeleteAsync(currentLanguage.Id); await _unitOfWorkManager.Current.SaveChangesAsync(); } }); } /// <summary> /// Deletes a language. /// </summary> /// <param name="tenantId">Tenant Id or null for host.</param> /// <param name="languageName">Name of the language.</param> public virtual void Remove(int? tenantId, string languageName) { _unitOfWorkManager.WithUnitOfWork(() => { var currentLanguage = (GetLanguages(tenantId)).FirstOrDefault(l => l.Name == languageName); if (currentLanguage == null) { return; } if (currentLanguage.TenantId == null && tenantId != null) { throw new AbpException("Can not delete a host language from tenant!"); } using (_unitOfWorkManager.Current.SetTenantId(currentLanguage.TenantId)) { _languageRepository.Delete(currentLanguage.Id); _unitOfWorkManager.Current.SaveChanges(); } }); } /// <summary> /// Updates a language. /// </summary> public virtual async Task UpdateAsync(int? tenantId, ApplicationLanguage language) { await _unitOfWorkManager.WithUnitOfWorkAsync(async () => { var existingLanguageWithSameName = (await GetLanguagesAsync(language.TenantId)).FirstOrDefault(l => l.Name == language.Name); if (existingLanguageWithSameName != null) { if (existingLanguageWithSameName.Id != language.Id) { throw new AbpException("There is already a language with name = " + language.Name); } } if (language.TenantId == null && tenantId != null) { throw new AbpException("Can not update a host language from tenant"); } using (_unitOfWorkManager.Current.SetTenantId(language.TenantId)) { await _languageRepository.UpdateAsync(language); await _unitOfWorkManager.Current.SaveChangesAsync(); } }); } /// <summary> /// Updates a language. /// </summary> public virtual void Update(int? tenantId, ApplicationLanguage language) { _unitOfWorkManager.WithUnitOfWork(() => { var existingLanguageWithSameName = (GetLanguages(language.TenantId)).FirstOrDefault(l => l.Name == language.Name); if (existingLanguageWithSameName != null) { if (existingLanguageWithSameName.Id != language.Id) { throw new AbpException("There is already a language with name = " + language.Name); } } if (language.TenantId == null && tenantId != null) { throw new AbpException("Can not update a host language from tenant"); } using (_unitOfWorkManager.Current.SetTenantId(language.TenantId)) { _languageRepository.Update(language); _unitOfWorkManager.Current.SaveChanges(); } }); } /// <summary> /// Gets the default language or null for a tenant or the host. /// </summary> /// <param name="tenantId">Tenant Id of null for host</param> public virtual async Task<ApplicationLanguage> GetDefaultLanguageOrNullAsync(int? tenantId) { var defaultLanguageName = tenantId.HasValue ? await _settingManager.GetSettingValueForTenantAsync(LocalizationSettingNames.DefaultLanguage, tenantId.Value) : await _settingManager.GetSettingValueForApplicationAsync(LocalizationSettingNames.DefaultLanguage); return (await GetLanguagesAsync(tenantId)).FirstOrDefault(l => l.Name == defaultLanguageName); } /// <summary> /// Gets the default language or null for a tenant or the host. /// </summary> /// <param name="tenantId">Tenant Id of null for host</param> public virtual ApplicationLanguage GetDefaultLanguageOrNull(int? tenantId) { var defaultLanguageName = tenantId.HasValue ? _settingManager.GetSettingValueForTenant(LocalizationSettingNames.DefaultLanguage, tenantId.Value) : _settingManager.GetSettingValueForApplication(LocalizationSettingNames.DefaultLanguage); return (GetLanguages(tenantId)).FirstOrDefault(l => l.Name == defaultLanguageName); } /// <summary> /// Sets the default language for a tenant or the host. /// </summary> /// <param name="tenantId">Tenant Id of null for host</param> /// <param name="languageName">Name of the language.</param> public virtual async Task SetDefaultLanguageAsync(int? tenantId, string languageName) { var cultureInfo = CultureInfo.GetCultureInfo(languageName); if (tenantId.HasValue) { await _settingManager.ChangeSettingForTenantAsync(tenantId.Value, LocalizationSettingNames.DefaultLanguage, cultureInfo.Name); } else { await _settingManager.ChangeSettingForApplicationAsync(LocalizationSettingNames.DefaultLanguage, cultureInfo.Name); } } /// <summary> /// Sets the default language for a tenant or the host. /// </summary> /// <param name="tenantId">Tenant Id of null for host</param> /// <param name="languageName">Name of the language.</param> public virtual void SetDefaultLanguage(int? tenantId, string languageName) { var cultureInfo = CultureInfo.GetCultureInfo(languageName); if (tenantId.HasValue) { _settingManager.ChangeSettingForTenant(tenantId.Value, LocalizationSettingNames.DefaultLanguage, cultureInfo.Name); } else { _settingManager.ChangeSettingForApplication(LocalizationSettingNames.DefaultLanguage, cultureInfo.Name); } } public void HandleEvent(EntityChangedEventData<ApplicationLanguage> eventData) { LanguageListCache.Remove(eventData.Entity.TenantId ?? 0); //Also invalidate the language script cache _cacheManager.GetCache("AbpLocalizationScripts").Clear(); } protected virtual async Task<Dictionary<string, ApplicationLanguage>> GetLanguageDictionaryAsync(int? tenantId) { //Creates a copy of the cached dictionary (to not modify it) var languageDictionary = new Dictionary<string, ApplicationLanguage>(await GetLanguageDictionaryFromCacheAsync(null)); if (tenantId == null) { return languageDictionary; } //Override tenant languages foreach (var tenantLanguage in await GetLanguageDictionaryFromCacheAsync(tenantId.Value)) { languageDictionary[tenantLanguage.Key] = tenantLanguage.Value; } return languageDictionary; } protected virtual Dictionary<string, ApplicationLanguage> GetLanguageDictionary(int? tenantId) { //Creates a copy of the cached dictionary (to not modify it) var languageDictionary = new Dictionary<string, ApplicationLanguage>(GetLanguageDictionaryFromCache(null)); if (tenantId == null) { return languageDictionary; } //Override tenant languages foreach (var tenantLanguage in GetLanguageDictionaryFromCache(tenantId.Value)) { languageDictionary[tenantLanguage.Key] = tenantLanguage.Value; } return languageDictionary; } private Task<Dictionary<string, ApplicationLanguage>> GetLanguageDictionaryFromCacheAsync(int? tenantId) { return LanguageListCache.GetAsync(tenantId ?? 0, () => GetLanguagesFromDatabaseAsync(tenantId)); } private Dictionary<string, ApplicationLanguage> GetLanguageDictionaryFromCache(int? tenantId) { return LanguageListCache.Get(tenantId ?? 0, () => GetLanguagesFromDatabase(tenantId)); } protected virtual async Task<Dictionary<string, ApplicationLanguage>> GetLanguagesFromDatabaseAsync( int? tenantId) { return await _unitOfWorkManager.WithUnitOfWorkAsync(async () => { using (_unitOfWorkManager.Current.SetTenantId(tenantId)) { return (await _languageRepository.GetAllListAsync()).ToDictionary(l => l.Name); } }); } protected virtual Dictionary<string, ApplicationLanguage> GetLanguagesFromDatabase(int? tenantId) { return _unitOfWorkManager.WithUnitOfWork(() => { using (_unitOfWorkManager.Current.SetTenantId(tenantId)) { return (_languageRepository.GetAllList()).ToDictionary(l => l.Name); } }); } } }
using System; using UnityEngine; using UnityEngine.Experimental.Rendering.HDPipeline; using UnityEngine.Rendering; namespace UnityEditor.Experimental.Rendering.HDPipeline { public enum MaterialId { LitSSS = 0, LitStandard = 1, LitAniso = 2, LitIridescence = 3, LitSpecular = 4, LitTranslucent = 5 }; // A Material can be authored from the shader graph or by hand. When written by hand we need to provide an inspector. // Such a Material will share some properties between it various variant (shader graph variant or hand authored variant). // This is the purpose of BaseLitGUI. It contain all properties that are common to all Material based on Lit template. // For the default hand written Lit material see LitUI.cs that contain specific properties for our default implementation. abstract class BaseLitGUI : BaseUnlitGUI { protected static class StylesBaseLit { public static GUIContent doubleSidedNormalModeText = new GUIContent("Normal Mode", "Specifies the method HDRP uses to modify the normal base.\nMirror: Mirrors the normals with the vertex normal plane.\nFlip: Flips the normal."); public static GUIContent depthOffsetEnableText = new GUIContent("Depth Offset", "When enabled, HDRP uses the Height Map to calculate the depth offset for this Material."); // Displacement mapping (POM, tessellation, per vertex) //public static GUIContent enablePerPixelDisplacementText = new GUIContent("Per Pixel Displacement", ""); public static GUIContent displacementModeText = new GUIContent("Displacement Mode", "Specifies the method HDRP uses to apply height map displacement to the selected element: Vertex, pixel, or tessellated vertex.\n You must use flat surfaces for Pixel displacement."); public static GUIContent lockWithObjectScaleText = new GUIContent("Lock With Object Scale", "When enabled, displacement mapping takes the absolute value of the scale of the object into account."); public static GUIContent lockWithTilingRateText = new GUIContent("Lock With Height Map Tiling Rate", "When enabled, displacement mapping takes the absolute value of the tiling rate of the height map into account."); // Material ID public static GUIContent materialIDText = new GUIContent("Material Type", "Specifies additional feature for this Material. Customize you Material with different settings depending on which Material Type you select."); public static GUIContent transmissionEnableText = new GUIContent("Transmission", "When enabled HDRP processes the transmission effect for subsurface scattering. Simulates the translucency of the object."); // Per pixel displacement public static GUIContent ppdMinSamplesText = new GUIContent("Minimum Steps", "Controls the minimum number of steps HDRP uses for per pixel displacement mapping."); public static GUIContent ppdMaxSamplesText = new GUIContent("Maximum Steps", "Controls the maximum number of steps HDRP uses for per pixel displacement mapping."); public static GUIContent ppdLodThresholdText = new GUIContent("Fading Mip Level Start", "Controls the Height Map mip level where the parallax occlusion mapping effect begins to disappear."); public static GUIContent ppdPrimitiveLength = new GUIContent("Primitive Length", "Sets the length of the primitive (with the scale of 1) to which HDRP applies per-pixel displacement mapping. For example, the standard quad is 1 x 1 meter, while the standard plane is 10 x 10 meters."); public static GUIContent ppdPrimitiveWidth = new GUIContent("Primitive Width", "Sets the width of the primitive (with the scale of 1) to which HDRP applies per-pixel displacement mapping. For example, the standard quad is 1 x 1 meter, while the standard plane is 10 x 10 meters."); // Tessellation public static string tessellationModeStr = "Tessellation Mode"; public static readonly string[] tessellationModeNames = Enum.GetNames(typeof(TessellationMode)); public static GUIContent tessellationText = new GUIContent("Tessellation Options", "Tessellation options"); public static GUIContent tessellationFactorText = new GUIContent("Tessellation Factor", "Controls the strength of the tessellation effect. Higher values result in more tessellation. Maximum tessellation factor is 15 on the Xbox One and PS4"); public static GUIContent tessellationFactorMinDistanceText = new GUIContent("Start Fade Distance", "Sets the distance (in meters) at which tessellation begins to fade out."); public static GUIContent tessellationFactorMaxDistanceText = new GUIContent("End Fade Distance", "Sets the maximum distance (in meters) to the Camera where HDRP tessellates triangle."); public static GUIContent tessellationFactorTriangleSizeText = new GUIContent("Triangle Size", "Sets the desired screen space size of triangles (in pixels). Smaller values result in smaller triangle."); public static GUIContent tessellationShapeFactorText = new GUIContent("Shape Factor", "Controls the strength of Phong tessellation shape (lerp factor)."); public static GUIContent tessellationBackFaceCullEpsilonText = new GUIContent("Triangle Culling Epsilon", "Controls triangle culling. A value of -1.0 disables back face culling for tessellation, higher values produce more aggressive culling and better performance."); // Vertex animation public static string vertexAnimation = "Vertex Animation"; // Wind public static GUIContent windText = new GUIContent("Wind"); public static GUIContent windInitialBendText = new GUIContent("Initial Bend"); public static GUIContent windStiffnessText = new GUIContent("Stiffness"); public static GUIContent windDragText = new GUIContent("Drag"); public static GUIContent windShiverDragText = new GUIContent("Shiver Drag"); public static GUIContent windShiverDirectionalityText = new GUIContent("Shiver Directionality"); public static GUIContent supportDecalsText = new GUIContent("Receive Decals", "Enable to allow Materials to receive decals."); public static GUIContent enableGeometricSpecularAAText = new GUIContent("Geometric Specular AA", "When enabled, HDRP reduces specular aliasing on high density meshes (particularly useful when the not using a normal map)."); public static GUIContent specularAAScreenSpaceVarianceText = new GUIContent("Screen space variance", "Controls the strength of the Specular AA reduction. Higher values give a more blurry result and less aliasing."); public static GUIContent specularAAThresholdText = new GUIContent("Threshold", "Controls the effect of Specular AA reduction. A values of 0 does not apply reduction, higher values allow higher reduction."); // SSR public static GUIContent receivesSSRText = new GUIContent("Receive SSR", "When enabled, this Material can receive screen space reflections."); } public enum DoubleSidedNormalMode { Flip, Mirror, None } public enum TessellationMode { None, Phong } public enum DisplacementMode { None, Vertex, Pixel, Tessellation } public enum HeightmapParametrization { MinMax = 0, Amplitude = 1 } protected MaterialProperty doubleSidedNormalMode = null; protected const string kDoubleSidedNormalMode = "_DoubleSidedNormalMode"; protected MaterialProperty depthOffsetEnable = null; protected const string kDepthOffsetEnable = "_DepthOffsetEnable"; // Properties // Material ID protected MaterialProperty materialID = null; protected const string kMaterialID = "_MaterialID"; protected MaterialProperty transmissionEnable = null; protected const string kTransmissionEnable = "_TransmissionEnable"; protected const string kStencilRef = "_StencilRef"; protected const string kStencilWriteMask = "_StencilWriteMask"; protected const string kStencilRefDepth = "_StencilRefDepth"; protected const string kStencilWriteMaskDepth = "_StencilWriteMaskDepth"; protected const string kStencilRefGBuffer = "_StencilRefGBuffer"; protected const string kStencilWriteMaskGBuffer = "_StencilWriteMaskGBuffer"; protected const string kStencilRefMV = "_StencilRefMV"; protected const string kStencilWriteMaskMV = "_StencilWriteMaskMV"; protected const string kStencilRefDistortionVec = "_StencilRefDistortionVec"; protected const string kStencilWriteMaskDistortionVec = "_StencilWriteMaskDistortionVec"; protected MaterialProperty displacementMode = null; protected const string kDisplacementMode = "_DisplacementMode"; protected MaterialProperty displacementLockObjectScale = null; protected const string kDisplacementLockObjectScale = "_DisplacementLockObjectScale"; protected MaterialProperty displacementLockTilingScale = null; protected const string kDisplacementLockTilingScale = "_DisplacementLockTilingScale"; // Per pixel displacement params protected MaterialProperty ppdMinSamples = null; protected const string kPpdMinSamples = "_PPDMinSamples"; protected MaterialProperty ppdMaxSamples = null; protected const string kPpdMaxSamples = "_PPDMaxSamples"; protected MaterialProperty ppdLodThreshold = null; protected const string kPpdLodThreshold = "_PPDLodThreshold"; protected MaterialProperty ppdPrimitiveLength = null; protected const string kPpdPrimitiveLength = "_PPDPrimitiveLength"; protected MaterialProperty ppdPrimitiveWidth = null; protected const string kPpdPrimitiveWidth = "_PPDPrimitiveWidth"; protected MaterialProperty invPrimScale = null; protected const string kInvPrimScale = "_InvPrimScale"; // Wind protected MaterialProperty windEnable = null; protected const string kWindEnabled = "_EnableWind"; protected MaterialProperty windInitialBend = null; protected const string kWindInitialBend = "_InitialBend"; protected MaterialProperty windStiffness = null; protected const string kWindStiffness = "_Stiffness"; protected MaterialProperty windDrag = null; protected const string kWindDrag = "_Drag"; protected MaterialProperty windShiverDrag = null; protected const string kWindShiverDrag = "_ShiverDrag"; protected MaterialProperty windShiverDirectionality = null; protected const string kWindShiverDirectionality = "_ShiverDirectionality"; // tessellation params protected MaterialProperty tessellationMode = null; protected const string kTessellationMode = "_TessellationMode"; protected MaterialProperty tessellationFactor = null; protected const string kTessellationFactor = "_TessellationFactor"; protected MaterialProperty tessellationFactorMinDistance = null; protected const string kTessellationFactorMinDistance = "_TessellationFactorMinDistance"; protected MaterialProperty tessellationFactorMaxDistance = null; protected const string kTessellationFactorMaxDistance = "_TessellationFactorMaxDistance"; protected MaterialProperty tessellationFactorTriangleSize = null; protected const string kTessellationFactorTriangleSize = "_TessellationFactorTriangleSize"; protected MaterialProperty tessellationShapeFactor = null; protected const string kTessellationShapeFactor = "_TessellationShapeFactor"; protected MaterialProperty tessellationBackFaceCullEpsilon = null; protected const string kTessellationBackFaceCullEpsilon = "_TessellationBackFaceCullEpsilon"; // Decal protected MaterialProperty supportDecals = null; protected const string kSupportDecals = "_SupportDecals"; protected MaterialProperty enableGeometricSpecularAA = null; protected const string kEnableGeometricSpecularAA = "_EnableGeometricSpecularAA"; protected MaterialProperty specularAAScreenSpaceVariance = null; protected const string kSpecularAAScreenSpaceVariance = "_SpecularAAScreenSpaceVariance"; protected MaterialProperty specularAAThreshold = null; protected const string kSpecularAAThreshold = "_SpecularAAThreshold"; // SSR protected MaterialProperty receivesSSR = null; protected const string kReceivesSSR = "_ReceivesSSR"; protected override void FindBaseMaterialProperties(MaterialProperty[] props) { base.FindBaseMaterialProperties(props); doubleSidedNormalMode = FindProperty(kDoubleSidedNormalMode, props, false); depthOffsetEnable = FindProperty(kDepthOffsetEnable, props, false); // MaterialID materialID = FindProperty(kMaterialID, props, false); transmissionEnable = FindProperty(kTransmissionEnable, props, false); displacementMode = FindProperty(kDisplacementMode, props, false); displacementLockObjectScale = FindProperty(kDisplacementLockObjectScale, props, false); displacementLockTilingScale = FindProperty(kDisplacementLockTilingScale, props, false); // Per pixel displacement ppdMinSamples = FindProperty(kPpdMinSamples, props, false); ppdMaxSamples = FindProperty(kPpdMaxSamples, props, false); ppdLodThreshold = FindProperty(kPpdLodThreshold, props, false); ppdPrimitiveLength = FindProperty(kPpdPrimitiveLength, props, false); ppdPrimitiveWidth = FindProperty(kPpdPrimitiveWidth, props, false); invPrimScale = FindProperty(kInvPrimScale, props, false); // tessellation specific, silent if not found tessellationMode = FindProperty(kTessellationMode, props, false); tessellationFactor = FindProperty(kTessellationFactor, props, false); tessellationFactorMinDistance = FindProperty(kTessellationFactorMinDistance, props, false); tessellationFactorMaxDistance = FindProperty(kTessellationFactorMaxDistance, props, false); tessellationFactorTriangleSize = FindProperty(kTessellationFactorTriangleSize, props, false); tessellationShapeFactor = FindProperty(kTessellationShapeFactor, props, false); tessellationBackFaceCullEpsilon = FindProperty(kTessellationBackFaceCullEpsilon, props, false); // Wind windEnable = FindProperty(kWindEnabled, props, false); windInitialBend = FindProperty(kWindInitialBend, props, false); windStiffness = FindProperty(kWindStiffness, props, false); windDrag = FindProperty(kWindDrag, props, false); windShiverDrag = FindProperty(kWindShiverDrag, props, false); windShiverDirectionality = FindProperty(kWindShiverDirectionality, props, false); // Decal supportDecals = FindProperty(kSupportDecals, props, false); // specular AA enableGeometricSpecularAA = FindProperty(kEnableGeometricSpecularAA, props, false); specularAAScreenSpaceVariance = FindProperty(kSpecularAAScreenSpaceVariance, props, false); specularAAThreshold = FindProperty(kSpecularAAThreshold, props, false); // SSR receivesSSR = FindProperty(kReceivesSSR, props, false); } void TessellationModePopup() { EditorGUI.showMixedValue = tessellationMode.hasMixedValue; var mode = (TessellationMode)tessellationMode.floatValue; EditorGUI.BeginChangeCheck(); mode = (TessellationMode)EditorGUILayout.Popup(StylesBaseLit.tessellationModeStr, (int)mode, StylesBaseLit.tessellationModeNames); if (EditorGUI.EndChangeCheck()) { m_MaterialEditor.RegisterPropertyChangeUndo("Tessellation Mode"); tessellationMode.floatValue = (float)mode; } EditorGUI.showMixedValue = false; } protected virtual void UpdateDisplacement() {} protected override void BaseMaterialPropertiesGUI() { base.BaseMaterialPropertiesGUI(); // This follow double sided option if (doubleSidedEnable != null && doubleSidedEnable.floatValue > 0.0f) { EditorGUI.indentLevel++; m_MaterialEditor.ShaderProperty(doubleSidedNormalMode, StylesBaseLit.doubleSidedNormalModeText); EditorGUI.indentLevel--; } if (materialID != null) { m_MaterialEditor.ShaderProperty(materialID, StylesBaseLit.materialIDText); if ((int)materialID.floatValue == (int)MaterialId.LitSSS) { EditorGUI.indentLevel++; m_MaterialEditor.ShaderProperty(transmissionEnable, StylesBaseLit.transmissionEnableText); EditorGUI.indentLevel--; } } if (supportDecals != null) { m_MaterialEditor.ShaderProperty(supportDecals, StylesBaseLit.supportDecalsText); } if (receivesSSR != null) { m_MaterialEditor.ShaderProperty(receivesSSR, StylesBaseLit.receivesSSRText); } if (enableGeometricSpecularAA != null) { m_MaterialEditor.ShaderProperty(enableGeometricSpecularAA, StylesBaseLit.enableGeometricSpecularAAText); if (enableGeometricSpecularAA.floatValue > 0.0) { EditorGUI.indentLevel++; m_MaterialEditor.ShaderProperty(specularAAScreenSpaceVariance, StylesBaseLit.specularAAScreenSpaceVarianceText); m_MaterialEditor.ShaderProperty(specularAAThreshold, StylesBaseLit.specularAAThresholdText); EditorGUI.indentLevel--; } } if (displacementMode != null) { EditorGUI.BeginChangeCheck(); FilterDisplacementMode(); m_MaterialEditor.ShaderProperty(displacementMode, StylesBaseLit.displacementModeText); if (EditorGUI.EndChangeCheck()) { UpdateDisplacement(); } if ((DisplacementMode)displacementMode.floatValue != DisplacementMode.None) { EditorGUI.indentLevel++; m_MaterialEditor.ShaderProperty(displacementLockObjectScale, StylesBaseLit.lockWithObjectScaleText); m_MaterialEditor.ShaderProperty(displacementLockTilingScale, StylesBaseLit.lockWithTilingRateText); EditorGUI.indentLevel--; } if ((DisplacementMode)displacementMode.floatValue == DisplacementMode.Pixel) { EditorGUILayout.Space(); EditorGUI.indentLevel++; m_MaterialEditor.ShaderProperty(ppdMinSamples, StylesBaseLit.ppdMinSamplesText); m_MaterialEditor.ShaderProperty(ppdMaxSamples, StylesBaseLit.ppdMaxSamplesText); ppdMinSamples.floatValue = Mathf.Min(ppdMinSamples.floatValue, ppdMaxSamples.floatValue); m_MaterialEditor.ShaderProperty(ppdLodThreshold, StylesBaseLit.ppdLodThresholdText); m_MaterialEditor.ShaderProperty(ppdPrimitiveLength, StylesBaseLit.ppdPrimitiveLength); ppdPrimitiveLength.floatValue = Mathf.Max(0.01f, ppdPrimitiveLength.floatValue); m_MaterialEditor.ShaderProperty(ppdPrimitiveWidth, StylesBaseLit.ppdPrimitiveWidth); ppdPrimitiveWidth.floatValue = Mathf.Max(0.01f, ppdPrimitiveWidth.floatValue); invPrimScale.vectorValue = new Vector4(1.0f / ppdPrimitiveLength.floatValue, 1.0f / ppdPrimitiveWidth.floatValue); // Precompute m_MaterialEditor.ShaderProperty(depthOffsetEnable, StylesBaseLit.depthOffsetEnableText); EditorGUI.indentLevel--; } } } protected void FilterDisplacementMode() { if(tessellationMode == null) { if ((DisplacementMode)displacementMode.floatValue == DisplacementMode.Tessellation) displacementMode.floatValue = (float)DisplacementMode.None; } else { if ((DisplacementMode)displacementMode.floatValue == DisplacementMode.Pixel || (DisplacementMode)displacementMode.floatValue == DisplacementMode.Vertex) displacementMode.floatValue = (float)DisplacementMode.None; } } private void DrawDelayedFloatProperty(MaterialProperty prop, GUIContent content) { Rect position = EditorGUILayout.GetControlRect(); EditorGUI.BeginChangeCheck(); EditorGUI.showMixedValue = prop.hasMixedValue; float newValue = EditorGUI.DelayedFloatField(position, content, prop.floatValue); EditorGUI.showMixedValue = false; if (EditorGUI.EndChangeCheck()) prop.floatValue = newValue; } protected virtual void MaterialTesselationPropertiesGUI() { // Display tessellation option if it exist if (tessellationMode != null) { using (var header = new HeaderScope(StylesBaseLit.tessellationText.text, (uint)Expandable.Tesselation, this)) { if (header.expanded) { TessellationModePopup(); m_MaterialEditor.ShaderProperty(tessellationFactor, StylesBaseLit.tessellationFactorText); DrawDelayedFloatProperty(tessellationFactorMinDistance, StylesBaseLit.tessellationFactorMinDistanceText); DrawDelayedFloatProperty(tessellationFactorMaxDistance, StylesBaseLit.tessellationFactorMaxDistanceText); // clamp min distance to be below max distance tessellationFactorMinDistance.floatValue = Math.Min(tessellationFactorMaxDistance.floatValue, tessellationFactorMinDistance.floatValue); m_MaterialEditor.ShaderProperty(tessellationFactorTriangleSize, StylesBaseLit.tessellationFactorTriangleSizeText); if ((TessellationMode)tessellationMode.floatValue == TessellationMode.Phong) { m_MaterialEditor.ShaderProperty(tessellationShapeFactor, StylesBaseLit.tessellationShapeFactorText); } if (doubleSidedEnable.floatValue == 0.0) { m_MaterialEditor.ShaderProperty(tessellationBackFaceCullEpsilon, StylesBaseLit.tessellationBackFaceCullEpsilonText); } } } } } //override for adding Tesselation public override void ShaderPropertiesGUI(Material material) { // Use default labelWidth EditorGUIUtility.labelWidth = 0f; // Detect any changes to the material EditorGUI.BeginChangeCheck(); { using (var header = new HeaderScope(StylesBaseUnlit.optionText, (uint)Expandable.Base, this)) { if (header.expanded) BaseMaterialPropertiesGUI(); } MaterialTesselationPropertiesGUI(); VertexAnimationPropertiesGUI(); MaterialPropertiesGUI(material); using (var header = new HeaderScope(StylesBaseUnlit.advancedText, (uint)Expandable.Advance, this)) { if (header.expanded) { m_MaterialEditor.EnableInstancingField(); MaterialPropertiesAdvanceGUI(material); } } } if (EditorGUI.EndChangeCheck()) { foreach (var obj in m_MaterialEditor.targets) SetupMaterialKeywordsAndPassInternal((Material)obj); } } protected override void VertexAnimationPropertiesGUI() { if (windEnable == null && enableMotionVectorForVertexAnimation == null) return; using (var header = new HeaderScope(StylesBaseLit.vertexAnimation, (uint)Expandable.VertexAnimation, this)) { if (header.expanded) { if (windEnable != null) { // Hide wind option. Wind is deprecated and will be remove in the future. Use shader graph instead /* m_MaterialEditor.ShaderProperty(windEnable, StylesBaseLit.windText); if (!windEnable.hasMixedValue && windEnable.floatValue > 0.0f) { EditorGUI.indentLevel++; m_MaterialEditor.ShaderProperty(windInitialBend, StylesBaseLit.windInitialBendText); m_MaterialEditor.ShaderProperty(windStiffness, StylesBaseLit.windStiffnessText); m_MaterialEditor.ShaderProperty(windDrag, StylesBaseLit.windDragText); m_MaterialEditor.ShaderProperty(windShiverDrag, StylesBaseLit.windShiverDragText); m_MaterialEditor.ShaderProperty(windShiverDirectionality, StylesBaseLit.windShiverDirectionalityText); EditorGUI.indentLevel--; } */ } if (enableMotionVectorForVertexAnimation != null) m_MaterialEditor.ShaderProperty(enableMotionVectorForVertexAnimation, StylesBaseUnlit.enableMotionVectorForVertexAnimationText); } } } // All Setup Keyword functions must be static. It allow to create script to automatically update the shaders with a script if code change static public void SetupBaseLitKeywords(Material material) { SetupBaseUnlitKeywords(material); bool doubleSidedEnable = material.HasProperty(kDoubleSidedEnable) ? material.GetFloat(kDoubleSidedEnable) > 0.0f : false; if (doubleSidedEnable) { DoubleSidedNormalMode doubleSidedNormalMode = (DoubleSidedNormalMode)material.GetFloat(kDoubleSidedNormalMode); switch (doubleSidedNormalMode) { case DoubleSidedNormalMode.Mirror: // Mirror mode (in tangent space) material.SetVector("_DoubleSidedConstants", new Vector4(1.0f, 1.0f, -1.0f, 0.0f)); break; case DoubleSidedNormalMode.Flip: // Flip mode (in tangent space) material.SetVector("_DoubleSidedConstants", new Vector4(-1.0f, -1.0f, -1.0f, 0.0f)); break; case DoubleSidedNormalMode.None: // None mode (in tangent space) material.SetVector("_DoubleSidedConstants", new Vector4(1.0f, 1.0f, 1.0f, 0.0f)); break; } } // Stencil usage rules: // DoesntReceiveSSR and DecalsForwardOutputNormalBuffer need to be tagged during depth prepass // LightingMask need to be tagged during either GBuffer or Forward pass // ObjectMotionVectors need to be tagged in velocity pass. // As motion vectors pass can be use as a replacement of depth prepass it also need to have DoesntReceiveSSR and DecalsForwardOutputNormalBuffer // As GBuffer pass can have no depth prepass, it also need to have DoesntReceiveSSR and DecalsForwardOutputNormalBuffer // Object motion vectors is always render after a full depth buffer (if there is no depth prepass for GBuffer all object motion vectors are render after GBuffer) // so we have a guarantee than when we write object motion vectors no other object will be draw on top (and so would have require to overwrite motion vectors). // Final combination is: // Prepass: DoesntReceiveSSR, DecalsForwardOutputNormalBuffer // Motion vectors: DoesntReceiveSSR, DecalsForwardOutputNormalBuffer, ObjectVelocity // GBuffer: LightingMask, DecalsForwardOutputNormalBuffer, ObjectVelocity // Forward: LightingMask int stencilRef = (int)StencilLightingUsage.RegularLighting; // Forward case int stencilWriteMask = (int)HDRenderPipeline.StencilBitMask.LightingMask; int stencilRefDepth = 0; int stencilWriteMaskDepth = 0; int stencilRefGBuffer = (int)StencilLightingUsage.RegularLighting; int stencilWriteMaskGBuffer = (int)HDRenderPipeline.StencilBitMask.LightingMask; int stencilRefMV = (int)HDRenderPipeline.StencilBitMask.ObjectMotionVectors; int stencilWriteMaskMV = (int)HDRenderPipeline.StencilBitMask.ObjectMotionVectors; if (material.HasProperty(kMaterialID) && (int)material.GetFloat(kMaterialID) == (int)MaterialId.LitSSS) { stencilRefGBuffer = stencilRef = (int)StencilLightingUsage.SplitLighting; } if (material.HasProperty(kReceivesSSR) && material.GetInt(kReceivesSSR) == 0) { stencilRefDepth |= (int)HDRenderPipeline.StencilBitMask.DoesntReceiveSSR; stencilRefGBuffer |= (int)HDRenderPipeline.StencilBitMask.DoesntReceiveSSR; stencilRefMV |= (int)HDRenderPipeline.StencilBitMask.DoesntReceiveSSR; } stencilWriteMaskDepth |= (int)HDRenderPipeline.StencilBitMask.DoesntReceiveSSR | (int)HDRenderPipeline.StencilBitMask.DecalsForwardOutputNormalBuffer; stencilWriteMaskGBuffer |= (int)HDRenderPipeline.StencilBitMask.DoesntReceiveSSR | (int)HDRenderPipeline.StencilBitMask.DecalsForwardOutputNormalBuffer; stencilWriteMaskMV |= (int)HDRenderPipeline.StencilBitMask.DoesntReceiveSSR | (int)HDRenderPipeline.StencilBitMask.DecalsForwardOutputNormalBuffer; // As we tag both during motion vector pass and Gbuffer pass we need a separate state and we need to use the write mask material.SetInt(kStencilRef, stencilRef); material.SetInt(kStencilWriteMask, stencilWriteMask); material.SetInt(kStencilRefDepth, stencilRefDepth); material.SetInt(kStencilWriteMaskDepth, stencilWriteMaskDepth); material.SetInt(kStencilRefGBuffer, stencilRefGBuffer); material.SetInt(kStencilWriteMaskGBuffer, stencilWriteMaskGBuffer); material.SetInt(kStencilRefMV, stencilRefMV); material.SetInt(kStencilWriteMaskMV, stencilWriteMaskMV); material.SetInt(kStencilRefDistortionVec, (int)HDRenderPipeline.StencilBitMask.DistortionVectors); material.SetInt(kStencilWriteMaskDistortionVec, (int)HDRenderPipeline.StencilBitMask.DistortionVectors); if (material.HasProperty(kDisplacementMode)) { bool enableDisplacement = (DisplacementMode)material.GetFloat(kDisplacementMode) != DisplacementMode.None; bool enableVertexDisplacement = (DisplacementMode)material.GetFloat(kDisplacementMode) == DisplacementMode.Vertex; bool enablePixelDisplacement = (DisplacementMode)material.GetFloat(kDisplacementMode) == DisplacementMode.Pixel; bool enableTessellationDisplacement = ((DisplacementMode)material.GetFloat(kDisplacementMode) == DisplacementMode.Tessellation) && material.HasProperty(kTessellationMode); CoreUtils.SetKeyword(material, "_VERTEX_DISPLACEMENT", enableVertexDisplacement); CoreUtils.SetKeyword(material, "_PIXEL_DISPLACEMENT", enablePixelDisplacement); // Only set if tessellation exist CoreUtils.SetKeyword(material, "_TESSELLATION_DISPLACEMENT", enableTessellationDisplacement); bool displacementLockObjectScale = material.GetFloat(kDisplacementLockObjectScale) > 0.0; bool displacementLockTilingScale = material.GetFloat(kDisplacementLockTilingScale) > 0.0; // Tessellation reuse vertex flag. CoreUtils.SetKeyword(material, "_VERTEX_DISPLACEMENT_LOCK_OBJECT_SCALE", displacementLockObjectScale && (enableVertexDisplacement || enableTessellationDisplacement)); CoreUtils.SetKeyword(material, "_PIXEL_DISPLACEMENT_LOCK_OBJECT_SCALE", displacementLockObjectScale && enablePixelDisplacement); CoreUtils.SetKeyword(material, "_DISPLACEMENT_LOCK_TILING_SCALE", displacementLockTilingScale && enableDisplacement); // Depth offset is only enabled if per pixel displacement is bool depthOffsetEnable = (material.GetFloat(kDepthOffsetEnable) > 0.0f) && enablePixelDisplacement; CoreUtils.SetKeyword(material, "_DEPTHOFFSET_ON", depthOffsetEnable); } bool windEnabled = material.HasProperty(kWindEnabled) && material.GetFloat(kWindEnabled) > 0.0f; CoreUtils.SetKeyword(material, "_VERTEX_WIND", windEnabled); if (material.HasProperty(kTessellationMode)) { TessellationMode tessMode = (TessellationMode)material.GetFloat(kTessellationMode); CoreUtils.SetKeyword(material, "_TESSELLATION_PHONG", tessMode == TessellationMode.Phong); } SetupMainTexForAlphaTestGI("_BaseColorMap", "_BaseColor", material); // Use negation so we don't create keyword by default CoreUtils.SetKeyword(material, "_DISABLE_DECALS", material.HasProperty(kSupportDecals) && material.GetFloat(kSupportDecals) == 0.0); CoreUtils.SetKeyword(material, "_DISABLE_SSR", material.HasProperty(kReceivesSSR) && material.GetFloat(kReceivesSSR) == 0.0); CoreUtils.SetKeyword(material, "_ENABLE_GEOMETRIC_SPECULAR_AA", material.HasProperty(kEnableGeometricSpecularAA) && material.GetFloat(kEnableGeometricSpecularAA) == 1.0); } static public void SetupBaseLitMaterialPass(Material material) { SetupBaseUnlitMaterialPass(material); } } } // namespace UnityEditor
#region License /* * Copyright 2002-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #endregion #region Imports using System; using System.Collections; using System.Collections.Specialized; using System.ComponentModel; using System.Globalization; using System.Reflection; using System.Resources; using System.Web; #if NET_2_0 using System.Web.Compilation; #endif using System.Web.UI; using Spring.Collections; using Spring.Context; using Spring.Context.Support; using Spring.Core; using Spring.DataBinding; using Spring.Globalization; using Spring.Util; using Spring.Validation; using Spring.Web.Support; using IValidator = Spring.Validation.IValidator; #endregion namespace Spring.Web.UI { /// <summary> /// Extends standard .Net user control by adding data binding and localization functionality. /// </summary> /// <author>Aleksandar Seovic</author> public class UserControl : System.Web.UI.UserControl, IApplicationContextAware, IWebDataBound, ISupportsWebDependencyInjection, IPostBackDataHandler, IValidationContainer, IWebNavigable { #region Static fields private static readonly object EventPreLoadViewState = new object(); private static readonly object EventDataBindingsInitialized = new object(); private static readonly object EventDataBound = new object(); private static readonly object EventDataUnbound = new object(); #endregion #region Instance Fields private object controller; private ILocalizer localizer; private IMessageSource messageSource; private IDictionary sharedState; private IBindingContainer bindingManager; private IValidationErrors validationErrors = new ValidationErrors(); private IWebNavigator webNavigator; private IDictionary args; private IApplicationContext applicationContext; private IApplicationContext defaultApplicationContext; private bool needsUnbind = false; #endregion #region Control lifecycle methods /// <summary> /// Initialize a new UserControl instance. /// </summary> public UserControl() { InitializeNavigationSupport(); } #if !NET_2_0 /// <summary> /// Gets a value indicating whether this instance is in design mode. /// </summary> /// <value> /// <c>true</c> if this instance is in design mode; otherwise, <c>false</c>. /// </value> protected bool DesignMode { get { return this.Context == null; } } /// <summary> /// Gets a value indicating whether view state is enabled for this page. /// </summary> protected internal bool IsViewStateEnabled { get { for (Control parent = this; parent != null; parent = parent.Parent) { if (!parent.EnableViewState) { return false; } } return true; } } #endif /// <summary> /// Initializes user control. /// </summary> protected override void OnInit( EventArgs e ) { InitializeMessageSource(); InitializeBindingManager(); if (!IsPostBack) { InitializeModel(); } else { LoadModel( LoadModelFromPersistenceMedium() ); } base.OnInit( e ); OnInitializeControls( EventArgs.Empty ); } /// <summary> /// Raises the <see cref="PreLoadViewState"/> event after page initialization. /// </summary> protected internal virtual void OnPreLoadViewState( EventArgs e ) { EventHandler handler = (EventHandler)base.Events[EventPreLoadViewState]; if (handler != null) { handler( this, e ); } } /// <summary> /// PreLoadViewState event. /// </summary> /// <remarks> /// <para> /// This event is raised if <see cref="System.Web.UI.Page.IsPostBack"/> is true /// immediately before state is restored from ViewState. /// </para> /// <para> /// NOTE: Different from <see cref="System.Web.UI.Control.LoadViewState(object)"/>, this event will always be raised! /// </para> /// </remarks> public event EventHandler PreLoadViewState { add { base.Events.AddHandler( EventPreLoadViewState, value ); } remove { base.Events.RemoveHandler( EventPreLoadViewState, value ); } } /// <summary> /// This method is called during a postback if this control has been visible when being rendered to the client. /// </summary> /// <remarks> /// If the controls has been visible when being rendering to the client, <see cref="System.Web.UI.Page.RegisterRequiresPostBack"/> /// has been called during <see cref="OnPreRender"/> /// </remarks> /// <returns>true if the server control's state changes as a result of the post back; otherwise false.</returns> bool IPostBackDataHandler.LoadPostData( string postDataKey, NameValueCollection postCollection ) { return LoadPostData( postDataKey, postCollection ); } /// <summary> /// This method is called during a postback if this control has been visible when being rendered to the client. /// </summary> /// <returns>true if the server control's state changes as a result of the post back; otherwise false.</returns> protected virtual bool LoadPostData( string postDataKey, NameValueCollection postCollection ) { // mark this control for unbinding form data during OnLoad() this.needsUnbind = true; return false; } /// <summary> /// When implemented by a class, signals the server control object to notify the /// ASP.NET application that the state of the control has changed. /// </summary> void IPostBackDataHandler.RaisePostDataChangedEvent() { RaisePostDataChangedEvent(); } /// <summary> /// When implemented by a class, signals the server control object to notify the /// ASP.NET application that the state of the control has changed. /// </summary> protected virtual void RaisePostDataChangedEvent() { return; } /// <summary> /// First unbinds data from the controls into a data model and /// then raises Load event in order to execute all associated handlers. /// </summary> /// <param name="e">Event arguments.</param> protected override void OnLoad( EventArgs e ) { if (IsPostBack && needsUnbind) { // unbind form data UnbindFormData(); } base.OnLoad( e ); } /// <summary> /// Binds data from the data model into controls and raises /// PreRender event afterwards. /// </summary> /// <param name="e">Event arguments.</param> protected override void OnPreRender( EventArgs e ) { if (Visible) { // causes IPostBackDataHandler.LoadPostData() to be called on next postback. // this is used for indicating a required call to UnbindFormData() Page.RegisterRequiresPostBack( this ); BindFormData(); if (localizer != null) { localizer.ApplyResources( this, messageSource, UserCulture ); } else if (Page.Localizer != null) { Page.Localizer.ApplyResources( this, messageSource, UserCulture ); } } base.OnPreRender( e ); object modelToSave = SaveModel(); if (modelToSave != null) { SaveModelToPersistenceMedium( modelToSave ); } } /// <summary> /// This event is raised before Load event and should be used to initialize /// controls as necessary. /// </summary> public event EventHandler InitializeControls; /// <summary> /// Raises InitializeControls event. /// </summary> /// <param name="e">Event arguments.</param> protected virtual void OnInitializeControls( EventArgs e ) { if (InitializeControls != null) { InitializeControls( this, e ); } } /// <summary> /// Obtains a <see cref="T:System.Web.UI.UserControl"/> object from a user control file /// and injects dependencies according to Spring config file. /// </summary> /// <param name="virtualPath">The virtual path to a user control file.</param> /// <returns> /// Returns the specified <see langword="UserControl"/> object, with dependencies injected. /// </returns> protected virtual new Control LoadControl( string virtualPath ) { Control control = base.LoadControl( virtualPath ); control = WebDependencyInjectionUtils.InjectDependenciesRecursive( defaultApplicationContext, control ); return control; } #if NET_2_0 /// <summary> /// Obtains a <see cref="T:System.Web.UI.UserControl"/> object by type /// and injects dependencies according to Spring config file. /// </summary> /// <param name="t">The type of a user control.</param> /// <param name="parameters">parameters to pass to the control</param> /// <returns> /// Returns the specified <see langword="UserControl"/> object, with dependencies injected. /// </returns> protected virtual new Control LoadControl( Type t, params object[] parameters ) { Control control = base.LoadControl( t, parameters ); control = WebDependencyInjectionUtils.InjectDependenciesRecursive( defaultApplicationContext, control ); return control; } #endif #endregion #region Model Management Support private IModelPersistenceMedium modelPersistenceMedium = new SessionModelPersistenceMedium(); /// <summary> /// Set the <see cref="IModelPersistenceMedium"/> strategy for storing model /// instances between requests. /// </summary> /// <remarks> /// By default the <see cref="SessionModelPersistenceMedium"/> strategy is used. /// </remarks> public IModelPersistenceMedium ModelPersistenceMedium { set { AssertUtils.ArgumentNotNull(value, "ModelPersistenceMedium"); modelPersistenceMedium = value; } } /// <summary> /// Retrieves data model from a persistence store. /// </summary> /// <remarks> /// The default implementation uses <see cref="System.Web.UI.Page.Session"/> to store and retrieve /// the model for the current <see cref="System.Web.HttpRequest.CurrentExecutionFilePath" /> /// </remarks> protected virtual object LoadModelFromPersistenceMedium() { //return Session[Request.CurrentExecutionFilePath + this.UniqueID + ".Model"]; return modelPersistenceMedium.LoadFromMedium(this); } /// <summary> /// Saves data model to a persistence store. /// </summary> /// <remarks> /// The default implementation uses <see cref="System.Web.UI.Page.Session"/> to store and retrieve /// the model for the current <see cref="System.Web.HttpRequest.CurrentExecutionFilePath" /> /// </remarks> protected virtual void SaveModelToPersistenceMedium( object modelToSave ) { //Session[Request.CurrentExecutionFilePath + this.UniqueID + ".Model"] = modelToSave; modelPersistenceMedium.SaveToMedium(this, modelToSave); } /// <summary> /// Initializes data model when the page is first loaded. /// </summary> /// <remarks> /// This method should be overriden by the developer /// in order to initialize data model for the page. /// </remarks> protected virtual void InitializeModel() { } /// <summary> /// Loads the saved data model on postback. /// </summary> /// <remarks> /// This method should be overriden by the developer /// in order to load data model for the page. /// </remarks> protected virtual void LoadModel( object savedModel ) { } /// <summary> /// Returns a model object that should be saved. /// </summary> /// <remarks> /// This method should be overriden by the developer /// in order to save data model for the page. /// </remarks> /// <returns> /// A model object that should be saved. /// </returns> protected virtual object SaveModel() { return null; } #endregion< #region Controller Support /// <summary> /// Gets or sets controller for the control. /// </summary> /// <remarks> /// <para> /// Internally calls are delegated to <see cref="GetController"/> and <see cref="SetController"/>. /// </para> /// </remarks> /// <value>Controller for the control.</value> public object Controller { get { return GetController(); } set { SetController( value ); } } /// <summary> /// <para>Stores the controller to be returned by <see cref="Controller"/> property.</para> /// </summary> /// <remarks> /// The default implementation uses a field to store the reference. Derived classes may override this behaviour /// but must ensure to also change the behaviour of <see cref="GetController"/> accordingly. /// </remarks> /// <param name="controller">Controller for the control.</param> protected virtual void SetController( object controller ) { this.controller = controller; } /// <summary> /// <para>Returns the controller stored by <see cref="SetController"/>.</para> /// </summary> /// <remarks> /// <para> /// The default implementation uses a field to retrieve the reference. /// </para> /// <para> /// If external controller is not specified, control will serve as its own controller, /// which will allow data binding to work properly. /// </para> /// <para> /// You may override this method e.g. to return <see cref="Spring.Web.UI.Page.Controller"/> in order to /// have your control bind to the same controller as your page. When overriding this behaviour, derived classes /// must ensure to also change the behaviour of <see cref="SetController"/> accordingly. /// </para> /// </remarks> /// <returns> /// <para>The controller for this control.</para> /// <para>If no controller is set, a reference to the control itself is returned.</para> /// </returns> protected virtual object GetController() { if (controller == null) { return this; } return controller; } #endregion Controller Support #region Shared State support /// <summary> /// Returns a thread-safe dictionary that contains state that is shared by /// all instances of this control. /// </summary> [Browsable( false )] [DesignerSerializationVisibility( DesignerSerializationVisibility.Hidden )] protected IDictionary SharedState { get { if (sharedState == null) { string thisTypeKey = this.GetType().FullName + this.GetType().GetHashCode() + ".SharedState"; sharedState = Application[thisTypeKey] as IDictionary; if (sharedState == null) { Application.Lock(); try { sharedState = Application[thisTypeKey] as IDictionary; if (sharedState == null) { sharedState = new SynchronizedHashtable(); Application.Add( thisTypeKey, sharedState ); } } finally { Application.UnLock(); } } } return sharedState; } } #endregion Shared State support #region Result support /// <summary> /// Ensure, that <see cref="WebNavigator"/> is set to a valid instance. /// </summary> /// <remarks> /// If <see cref="WebNavigator"/> is not already set, creates and sets a new <see cref="WebFormsResultWebNavigator"/> instance.<br/> /// Override this method if you don't want to inject a navigator, but need a different default. /// </remarks> protected virtual void InitializeNavigationSupport() { webNavigator = new WebFormsResultWebNavigator(this, null, null, true); } /// <summary> /// Gets/Sets the navigator to be used for handling <see cref="SetResult(string, object)"/> calls. /// </summary> public IWebNavigator WebNavigator { get { return webNavigator; } set { webNavigator = value; } } /// <summary> /// Gets or sets map of result names to target URLs /// </summary> /// <remarks> /// Using <see cref="Results"/> requires <see cref="WebNavigator"/> to implement <see cref="IResultWebNavigator"/>. /// </remarks> [Browsable( false )] [DesignerSerializationVisibility( DesignerSerializationVisibility.Hidden )] public virtual IDictionary Results { get { if (WebNavigator is IResultWebNavigator) { return ((IResultWebNavigator)WebNavigator).Results; } return null; } set { if (WebNavigator is IResultWebNavigator) { ((IResultWebNavigator)WebNavigator).Results = value; return; } throw new NotSupportedException("WebNavigator must be of type IResultWebNavigator to support Results"); } } /// <summary> /// A convenience, case-insensitive table that may be used to e.g. pass data into SpEL expressions"/>. /// </summary> /// <remarks> /// By default, e.g. <see cref="SetResult(string)"/> passes the control instance into an expression. Using /// <see cref="Args"/> is an easy way to pass additional parameters into the expression /// <example> /// // config: /// /// &lt;property Name=&quot;Results&quot;&gt; /// &lt;dictionary&gt; /// &lt;entry key=&quot;ok_clicked&quot; value=&quot;redirect:~/ShowResult.aspx?result=%{Args['result']}&quot; /&gt; /// &lt;/dictionary&gt; /// &lt;/property&gt; /// /// // code: /// /// void OnOkClicked(object sender, EventArgs e) /// { /// Args[&quot;result&quot;] = txtUserInput.Text; /// SetResult(&quot;ok_clicked&quot;); /// } /// </example> /// </remarks> public IDictionary Args { get { if (args == null) { args = new CaseInsensitiveHashtable(); } return args; } } /// <summary> /// Redirects user to a URL mapped to specified result name. /// </summary> /// <param name="resultName">Result name.</param> protected void SetResult( string resultName ) { WebNavigator.NavigateTo( resultName, this, null ); } /// <summary> /// Redirects user to a URL mapped to specified result name. /// </summary> /// <param name="resultName">Name of the result.</param> /// <param name="context">The context to use for evaluating the SpEL expression in the Result.</param> protected void SetResult( string resultName, object context ) { WebNavigator.NavigateTo( resultName, this, context ); } /// <summary> /// Returns a redirect url string that points to the /// <see cref="Spring.Web.Support.Result.TargetPage"/> defined by this /// result evaluated using this Page for expression /// </summary> /// <param name="resultName">Name of the result.</param> /// <returns>A redirect url string.</returns> protected string GetResultUrl( string resultName ) { return ResolveUrl( WebNavigator.GetResultUri( resultName, this, null ) ); } /// <summary> /// Returns a redirect url string that points to the /// <see cref="Spring.Web.Support.Result.TargetPage"/> defined by this /// result evaluated using this Page for expression /// </summary> /// <param name="resultName">Name of the result.</param> /// <param name="context">The context to use for evaluating the SpEL expression in the Result</param> /// <returns>A redirect url string.</returns> protected string GetResultUrl( string resultName, object context ) { return ResolveUrl( WebNavigator.GetResultUri( resultName, this, context ) ); } #endregion #region Validation support /// <summary> /// Evaluates specified validators and returns <c>True</c> if all of them are valid. /// </summary> /// <remarks> /// <p> /// Each validator can itself represent a collection of other validators if it is /// an instance of <see cref="ValidatorGroup"/> or one of its derived types. /// </p> /// <p> /// Please see the Validation Framework section in the documentation for more info. /// </p> /// </remarks> /// <param name="validationContext">Object to validate.</param> /// <param name="validators">Validators to evaluate.</param> /// <returns> /// <c>True</c> if all of the specified validators are valid, <c>False</c> otherwise. /// </returns> public bool Validate( object validationContext, params IValidator[] validators ) { IDictionary contextParams = CreateValidatorParameters(); bool result = true; foreach (IValidator validator in validators) { if (validator == null) { throw new ArgumentException( "Validator is not defined." ); } result = validator.Validate( validationContext, contextParams, this.ValidationErrors ) && result; } return result; } /// <summary> /// Gets or sets the validation errors container. /// </summary> /// <value>The validation errors container.</value> public virtual IValidationErrors ValidationErrors { get { return validationErrors; } set { AssertUtils.ArgumentNotNull(value, "ValidationErrors"); validationErrors = value; } } /// <summary> /// Creates the validator parameters. /// </summary> /// <remarks> /// <para> /// This method can be overriden if you want to pass additional parameters /// to the validation framework, but you should make sure that you call /// this base implementation in order to add page, session, application, /// request, response and context to the variables collection. /// </para> /// </remarks> /// <returns> /// Dictionary containing parameters that should be passed to /// the data validation framework. /// </returns> protected virtual IDictionary CreateValidatorParameters() { IDictionary parameters = new ListDictionary(); parameters["page"] = this.Page; parameters["usercontrol"] = this; parameters["session"] = this.Session; parameters["application"] = this.Application; parameters["request"] = this.Request; parameters["response"] = this.Response; parameters["context"] = this.Context; return parameters; } #endregion #region Data binding support /// <summary> /// Initializes the data bindings. /// </summary> protected virtual void InitializeDataBindings() { } /// <summary> /// Returns the key to be used for looking up a cached /// BindingManager instance in <see cref="SharedState"/>. /// </summary> /// <returns>a unique key identifying the <see cref="IBindingContainer"/> instance in the <see cref="SharedState"/> dictionary.</returns> protected virtual string GetBindingManagerKey() { return "DataBindingManager"; } /// <summary> /// Creates a new <see cref="IBindingContainer"/> instance. /// </summary> /// <remarks> /// This factory method is called if no <see cref="IBindingContainer"/> could be found in <see cref="SharedState"/> /// using the key returned by <see cref="GetBindingManagerKey"/>.<br/> /// <br/> /// /// </remarks> /// <returns>a <see cref="IBindingContainer"/> instance to be used for DataBinding</returns> protected virtual IBindingContainer CreateBindingManager() { return new BaseBindingManager(); } /// <summary> /// Gets the binding manager for this control. /// </summary> /// <value>The binding manager.</value> public IBindingContainer BindingManager { get { return this.bindingManager; } } /// <summary> /// Initializes binding manager and data bindings if necessary. /// </summary> private void InitializeBindingManager() { IDictionary sharedState = this.SharedState; string key = GetBindingManagerKey(); this.bindingManager = sharedState[key] as BaseBindingManager; if (this.bindingManager == null) { lock (sharedState.SyncRoot) { this.bindingManager = sharedState[key] as BaseBindingManager; if (this.bindingManager == null) { try { this.bindingManager = CreateBindingManager(); if (bindingManager == null) { throw new ArgumentNullException( "bindingManager", "CreateBindingManager() must not return null" ); } InitializeDataBindings(); } catch { this.bindingManager = null; throw; } sharedState[key] = this.bindingManager; this.OnDataBindingsInitialized( EventArgs.Empty ); } } } } /// <summary> /// Raises the <see cref="DataBindingsInitialized"/> event. /// </summary> protected virtual void OnDataBindingsInitialized( EventArgs e ) { EventHandler handler = (EventHandler)base.Events[EventDataBindingsInitialized]; if (handler != null) { handler( this, e ); } } /// <summary> /// This event is raised after <see cref="BindingManager"/> as been initialized. /// </summary> public event EventHandler DataBindingsInitialized { add { base.Events.AddHandler( EventDataBindingsInitialized, value ); } remove { base.Events.RemoveHandler( EventDataBindingsInitialized, value ); } } /// <summary> /// Bind data from model to form. /// </summary> protected internal virtual void BindFormData() { if (BindingManager.HasBindings) { BindingManager.BindTargetToSource( this, Controller, this.ValidationErrors ); } OnDataBound( EventArgs.Empty ); } /// <summary> /// Unbind data from form to model. /// </summary> protected internal virtual void UnbindFormData() { if (BindingManager.HasBindings) { BindingManager.BindSourceToTarget( this, Controller, this.ValidationErrors ); } OnDataUnbound( EventArgs.Empty ); } /// <summary> /// This event is raised after all controls have been populated with values /// from the data model. /// </summary> public event EventHandler DataBound { add { base.Events.AddHandler( EventDataBound, value ); } remove { base.Events.RemoveHandler( EventDataBound, value ); } } /// <summary> /// Raises DataBound event. /// </summary> /// <param name="e">Event arguments.</param> protected virtual void OnDataBound( EventArgs e ) { EventHandler handler = (EventHandler)base.Events[EventDataBound]; if (handler != null) { handler( this, e ); } } /// <summary> /// This event is raised after data model has been populated with values from /// web controls. /// </summary> public event EventHandler DataUnbound { add { base.Events.AddHandler( EventDataUnbound, value ); } remove { base.Events.RemoveHandler( EventDataUnbound, value ); } } /// <summary> /// Raises DataBound event. /// </summary> /// <param name="e">Event arguments.</param> protected virtual void OnDataUnbound( EventArgs e ) { EventHandler handler = (EventHandler)base.Events[EventDataUnbound]; if (handler != null) { handler( this, e ); } } #endregion #region Application context support /// <summary> /// Gets or sets the <see cref="Spring.Context.IApplicationContext"/> that this /// object runs in. /// </summary> /// <value></value> /// <remarks> /// <p> /// Normally this call will be used to initialize the object. /// </p> /// <p> /// Invoked after population of normal object properties but before an /// init callback such as /// <see cref="Spring.Objects.Factory.IInitializingObject"/>'s /// <see cref="Spring.Objects.Factory.IInitializingObject.AfterPropertiesSet"/> /// or a custom init-method. Invoked after the setting of any /// <see cref="Spring.Context.IResourceLoaderAware"/>'s /// <see cref="Spring.Context.IResourceLoaderAware.ResourceLoader"/> /// property. /// </p> /// </remarks> /// <exception cref="Spring.Context.ApplicationContextException"> /// In the case of application context initialization errors. /// </exception> /// <exception cref="Spring.Objects.ObjectsException"> /// If thrown by any application context methods. /// </exception> /// <exception cref="Spring.Objects.Factory.ObjectInitializationException"/> [Browsable( false )] [DesignerSerializationVisibility( DesignerSerializationVisibility.Hidden )] public virtual IApplicationContext ApplicationContext { get { return applicationContext; } set { applicationContext = value; } } #endregion #region Message source and localization support /// <summary> /// Gets or sets the localizer. /// </summary> /// <value>The localizer.</value> [Browsable( false )] [DesignerSerializationVisibility( DesignerSerializationVisibility.Hidden )] public ILocalizer Localizer { get { return localizer; } set { localizer = value; if (localizer.ResourceCache is NullResourceCache) { localizer.ResourceCache = new AspNetResourceCache(); } } } /// <summary> /// Gets or sets the local message source. /// </summary> /// <value>The local message source.</value> [Browsable( false )] [DesignerSerializationVisibility( DesignerSerializationVisibility.Hidden )] public IMessageSource MessageSource { get { return messageSource; } set { messageSource = value; if (messageSource != null && messageSource is AbstractMessageSource) { ((AbstractMessageSource)messageSource).ParentMessageSource = applicationContext; } } } /// <summary> /// Initializes local message source /// </summary> protected void InitializeMessageSource() { if (this.MessageSource == null) { string key = CreateSharedStateKey( "MessageSource" ); IDictionary sharedState = this.SharedState; IMessageSource messageSource = sharedState[key] as IMessageSource; if (messageSource == null) { lock (sharedState.SyncRoot) { messageSource = sharedState[key] as IMessageSource; if (messageSource == null) { ResourceSetMessageSource defaultMessageSource = new ResourceSetMessageSource(); defaultMessageSource.UseCodeAsDefaultMessage = true; ResourceManager rm = GetLocalResourceManager(); if (rm != null) { defaultMessageSource.ResourceManagers.Add( rm ); } sharedState[key] = defaultMessageSource; messageSource = defaultMessageSource; } } } this.MessageSource = messageSource; } } /// <summary> /// Creates and returns local ResourceManager for this page. /// </summary> /// <remarks> /// <para> /// In ASP.NET 1.1, this method loads local resources from the web application assembly. /// </para> /// <para> /// However, in ASP.NET 2.0, local resources are compiled into the dynamic assembly, /// so we need to find that assembly instead and load the resources from it. /// </para> /// </remarks> /// <returns>Local ResourceManager instance.</returns> private ResourceManager GetLocalResourceManager() { #if !NET_2_0 return new ResourceManager(GetType().BaseType); #else return LocalResourceManager.GetLocalResourceManager(this); #endif } /// <summary> /// Returns message for the specified resource name. /// </summary> /// <param name="name">Resource name.</param> /// <returns>Message text.</returns> public string GetMessage( string name ) { return messageSource.GetMessage( name, UserCulture ); } /// <summary> /// Returns message for the specified resource name. /// </summary> /// <param name="name">Resource name.</param> /// <param name="args">Message arguments that will be used to format return value.</param> /// <returns>Formatted message text.</returns> public string GetMessage( string name, params object[] args ) { return messageSource.GetMessage( name, UserCulture, args ); } /// <summary> /// Returns resource object for the specified resource name. /// </summary> /// <param name="name">Resource name.</param> /// <returns>Resource object.</returns> public object GetResourceObject( string name ) { return messageSource.GetResourceObject( name, UserCulture ); } /// <summary> /// Gets or sets user's culture /// </summary> [Browsable( false )] [DesignerSerializationVisibility( DesignerSerializationVisibility.Hidden )] public virtual CultureInfo UserCulture { get { return Page.UserCulture; } set { Page.UserCulture = value; } } #endregion #region Spring Page support /// <summary> /// Overrides Page property to return <see cref="Spring.Web.UI.Page"/> /// instead of <see cref="System.Web.UI.Page"/>. /// </summary> [Browsable( false )] [DesignerSerializationVisibility( DesignerSerializationVisibility.Hidden )] public new Page Page { get { return (Page)base.Page; } } ///<summary> /// Publish <see cref="HttpContext"/> associated with this page for convenient usage in Binding Expressions ///</summary> [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public new virtual HttpContext Context { get { return base.Context; } } #endregion #region Helper Methods /// <summary> /// Creates a key for shared state, taking into account whether /// this page belongs to a process or not. /// </summary> /// <param name="key">Key suffix</param> /// <returns>Generated unique shared state key.</returns> protected string CreateSharedStateKey( string key ) { return key; } #endregion #region Dependency Injection Support /// <summary> /// Holds the default ApplicationContext to be used during DI. /// </summary> IApplicationContext ISupportsWebDependencyInjection.DefaultApplicationContext { get { return defaultApplicationContext; } set { defaultApplicationContext = value; } } /// <summary> /// Injects dependencies into control before adding it. /// </summary> protected override void AddedControl( Control control, int index ) { WebDependencyInjectionUtils.InjectDependenciesRecursive( defaultApplicationContext, control ); base.AddedControl( control, index ); } #endregion Dependency Injection Support } }
using Microsoft.CSharp; using System; using System.CodeDom.Compiler; using System.Collections; using System.ComponentModel; using System.Globalization; using System.Management; using System.Reflection; using System.Threading; namespace System.Management.Instrumentation { internal class InstrumentedAssembly { private SchemaNaming naming; public EventSource source; public Hashtable mapTypeToConverter; public static ReaderWriterLock readerWriterLock; public static Hashtable mapIDToPublishedObject; private static Hashtable mapPublishedObjectToID; private static int upcountId; private Hashtable mapTypeToTypeInfo; private InstrumentedAssembly.TypeInfo lastTypeInfo; private Type lastType; static InstrumentedAssembly() { InstrumentedAssembly.readerWriterLock = new ReaderWriterLock(); InstrumentedAssembly.mapIDToPublishedObject = new Hashtable(); InstrumentedAssembly.mapPublishedObjectToID = new Hashtable(); InstrumentedAssembly.upcountId = 0xeff; } public InstrumentedAssembly(Assembly assembly, SchemaNaming naming) { this.mapTypeToTypeInfo = new Hashtable(); SecurityHelper.UnmanagedCode.Demand(); this.naming = naming; Assembly precompiledAssembly = naming.PrecompiledAssembly; if (null == precompiledAssembly) { CSharpCodeProvider cSharpCodeProvider = new CSharpCodeProvider(); CompilerParameters compilerParameter = new CompilerParameters(); compilerParameter.GenerateInMemory = true; compilerParameter.ReferencedAssemblies.Add(assembly.Location); compilerParameter.ReferencedAssemblies.Add(typeof(BaseEvent).Assembly.Location); compilerParameter.ReferencedAssemblies.Add(typeof(Component).Assembly.Location); Type[] types = assembly.GetTypes(); for (int i = 0; i < (int)types.Length; i++) { Type type = types[i]; if (this.IsInstrumentedType(type)) { this.FindReferences(type, compilerParameter); } } string[] code = new string[1]; code[0] = naming.Code; CompilerResults compilerResult = cSharpCodeProvider.CompileAssemblyFromSource(compilerParameter, code); foreach (CompilerError error in compilerResult.Errors) { Console.WriteLine(error.ToString()); } if (!compilerResult.Errors.HasErrors) { precompiledAssembly = compilerResult.CompiledAssembly; } else { throw new Exception(RC.GetString("FAILED_TO_BUILD_GENERATED_ASSEMBLY")); } } Type type1 = precompiledAssembly.GetType("WMINET_Converter"); this.mapTypeToConverter = (Hashtable)type1.GetField("mapTypeToConverter").GetValue(null); if (MTAHelper.IsNoContextMTA()) { this.InitEventSource(this); return; } else { ThreadDispatch threadDispatch = new ThreadDispatch(new ThreadDispatch.ThreadWorkerMethodWithParam(this.InitEventSource)); threadDispatch.Parameter = this; threadDispatch.Start(); return; } } public void FindReferences(Type type, CompilerParameters parameters) { if (!parameters.ReferencedAssemblies.Contains(type.Assembly.Location)) { parameters.ReferencedAssemblies.Add(type.Assembly.Location); } if (type.BaseType != null) { this.FindReferences(type.BaseType, parameters); } Type[] interfaces = type.GetInterfaces(); for (int i = 0; i < (int)interfaces.Length; i++) { Type type1 = interfaces[i]; if (type1.Assembly != type.Assembly) { this.FindReferences(type1, parameters); } } } public void Fire(object o) { SecurityHelper.UnmanagedCode.Demand(); this.Fire(o.GetType(), o); } public void Fire(Type t, object o) { InstrumentedAssembly.TypeInfo typeInfo = this.GetTypeInfo(t); typeInfo.Fire(o); } private InstrumentedAssembly.TypeInfo GetTypeInfo(Type t) { InstrumentedAssembly.TypeInfo typeInfo; lock (this.mapTypeToTypeInfo) { if (this.lastType != t) { this.lastType = t; InstrumentedAssembly.TypeInfo item = (InstrumentedAssembly.TypeInfo)this.mapTypeToTypeInfo[t]; if (item == null) { item = new InstrumentedAssembly.TypeInfo(this.source, this.naming, (Type)this.mapTypeToConverter[t]); this.mapTypeToTypeInfo.Add(t, item); } this.lastTypeInfo = item; typeInfo = item; } else { typeInfo = this.lastTypeInfo; } } return typeInfo; } private void InitEventSource(object param) { InstrumentedAssembly eventSource = (InstrumentedAssembly)param; eventSource.source = new EventSource(eventSource.naming.NamespaceName, eventSource.naming.DecoupledProviderInstanceName, this); } public bool IsInstrumentedType(Type type) { if (null != type.GetInterface("System.Management.Instrumentation.IEvent", false) || null != type.GetInterface("System.Management.Instrumentation.IInstance", false)) { return true; } else { object[] customAttributes = type.GetCustomAttributes(typeof(InstrumentationClassAttribute), true); if (customAttributes == null || (int)customAttributes.Length == 0) { return false; } else { return true; } } } public void Publish(object o) { SecurityHelper.UnmanagedCode.Demand(); try { InstrumentedAssembly.readerWriterLock.AcquireWriterLock(-1); if (!InstrumentedAssembly.mapPublishedObjectToID.ContainsKey(o)) { InstrumentedAssembly.mapIDToPublishedObject.Add(InstrumentedAssembly.upcountId.ToString((IFormatProvider)CultureInfo.InvariantCulture.GetFormat(typeof(int))), o); InstrumentedAssembly.mapPublishedObjectToID.Add(o, InstrumentedAssembly.upcountId); InstrumentedAssembly.upcountId = InstrumentedAssembly.upcountId + 1; } } finally { InstrumentedAssembly.readerWriterLock.ReleaseWriterLock(); } } public void Revoke(object o) { SecurityHelper.UnmanagedCode.Demand(); try { InstrumentedAssembly.readerWriterLock.AcquireWriterLock(-1); object item = InstrumentedAssembly.mapPublishedObjectToID[o]; if (item != null) { int num = (int)item; InstrumentedAssembly.mapPublishedObjectToID.Remove(o); InstrumentedAssembly.mapIDToPublishedObject.Remove(num.ToString((IFormatProvider)CultureInfo.InvariantCulture.GetFormat(typeof(int)))); } } finally { InstrumentedAssembly.readerWriterLock.ReleaseWriterLock(); } } public void SetBatchSize(Type t, int batchSize) { this.GetTypeInfo(t).SetBatchSize(batchSize); } private class TypeInfo { private FieldInfo fieldInfo; private int batchSize; private bool batchEvents; private ConvertToWMI[] convertFunctionsBatch; private ConvertToWMI convertFunctionNoBatch; private IntPtr[] wbemObjects; private Type converterType; private int currentIndex; public EventSource source; public int lastFire; public Thread cleanupThread; public TypeInfo(EventSource source, SchemaNaming naming, Type converterType) { this.batchSize = 64; this.batchEvents = true; this.converterType = converterType; this.source = source; object obj = Activator.CreateInstance(converterType); this.convertFunctionNoBatch = (ConvertToWMI)Delegate.CreateDelegate(typeof(ConvertToWMI), obj, "ToWMI"); this.SetBatchSize(this.batchSize); } public void Cleanup() { int num = 0; while (num < 20) { Thread.Sleep(100); if (this.currentIndex != 0) { num = 0; if (Environment.TickCount - this.lastFire < 100) { continue; } lock (this) { if (this.currentIndex > 0) { this.source.IndicateEvents(this.currentIndex, this.wbemObjects); this.currentIndex = 0; this.lastFire = Environment.TickCount; } } } else { num++; } } this.cleanupThread = null; } public IntPtr ExtractIntPtr(object o) { return (IntPtr)o.GetType().GetField("instWbemObjectAccessIP").GetValue(o); } public void Fire(object o) { if (!this.source.Any()) { if (this.batchEvents) { lock (this) { InstrumentedAssembly.TypeInfo typeInfo = this; int num = typeInfo.currentIndex; int num1 = num; typeInfo.currentIndex = num + 1; this.convertFunctionsBatch[num1](o); this.wbemObjects[this.currentIndex - 1] = (IntPtr)this.fieldInfo.GetValue(this.convertFunctionsBatch[this.currentIndex - 1].Target); if (this.cleanupThread != null) { if (this.currentIndex == this.batchSize) { this.source.IndicateEvents(this.currentIndex, this.wbemObjects); this.currentIndex = 0; this.lastFire = Environment.TickCount; } } else { int tickCount = Environment.TickCount; if (tickCount - this.lastFire >= 0x3e8) { this.source.IndicateEvents(this.currentIndex, this.wbemObjects); this.currentIndex = 0; this.lastFire = tickCount; } else { this.lastFire = Environment.TickCount; this.cleanupThread = new Thread(new ThreadStart(this.Cleanup)); this.cleanupThread.SetApartmentState(ApartmentState.MTA); this.cleanupThread.Start(); } } } } else { lock (this) { this.convertFunctionNoBatch(o); this.wbemObjects[0] = (IntPtr)this.fieldInfo.GetValue(this.convertFunctionNoBatch.Target); this.source.IndicateEvents(1, this.wbemObjects); } } return; } else { return; } } public void SetBatchSize(int batchSize) { if (batchSize > 0) { if (!WMICapabilities.MultiIndicateSupported) { batchSize = 1; } lock (this) { if (this.currentIndex > 0) { this.source.IndicateEvents(this.currentIndex, this.wbemObjects); this.currentIndex = 0; this.lastFire = Environment.TickCount; } this.wbemObjects = new IntPtr[batchSize]; if (batchSize <= 1) { this.fieldInfo = this.convertFunctionNoBatch.Target.GetType().GetField("instWbemObjectAccessIP"); this.wbemObjects[0] = this.ExtractIntPtr(this.convertFunctionNoBatch.Target); this.batchEvents = false; } else { this.batchEvents = true; this.batchSize = batchSize; this.convertFunctionsBatch = new ConvertToWMI[batchSize]; for (int i = 0; i < batchSize; i++) { object obj = Activator.CreateInstance(this.converterType); this.convertFunctionsBatch[i] = (ConvertToWMI)Delegate.CreateDelegate(typeof(ConvertToWMI), obj, "ToWMI"); this.wbemObjects[i] = this.ExtractIntPtr(obj); } this.fieldInfo = this.convertFunctionsBatch[0].Target.GetType().GetField("instWbemObjectAccessIP"); } } return; } else { throw new ArgumentOutOfRangeException("batchSize"); } } } } }
// 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.Concurrent; using System.Collections.Generic; using Xunit; namespace System.Linq.Parallel.Tests { public class SelectSelectManyTests { [Theory] [MemberData(nameof(UnorderedSources.Ranges), new[] { 0, 1, 2, 16 }, MemberType = typeof(UnorderedSources))] public static void Select_Unordered(Labeled<ParallelQuery<int>> labeled, int count) { ParallelQuery<int> query = labeled.Item; IntegerRangeSet seen = new IntegerRangeSet(0, count); foreach (var p in query.Select(x => KeyValuePair.Create(x, x * x))) { seen.Add(p.Key); Assert.Equal(p.Key * p.Key, p.Value); } seen.AssertComplete(); } [Theory] [OuterLoop] [MemberData(nameof(UnorderedSources.Ranges), new[] { 1024, 1024 * 4 }, MemberType = typeof(UnorderedSources))] public static void Select_Unordered_Longrunning(Labeled<ParallelQuery<int>> labeled, int count) { Select_Unordered(labeled, count); } [Theory] [MemberData(nameof(Sources.Ranges), new[] { 0, 1, 2, 16 }, MemberType = typeof(Sources))] public static void Select(Labeled<ParallelQuery<int>> labeled, int count) { ParallelQuery<int> query = labeled.Item; int seen = 0; foreach (var p in query.Select(x => KeyValuePair.Create(x, x * x))) { Assert.Equal(seen++, p.Key); Assert.Equal(p.Key * p.Key, p.Value); } Assert.Equal(count, seen); } [Theory] [OuterLoop] [MemberData(nameof(Sources.Ranges), new[] { 1024, 1024 * 4 }, MemberType = typeof(Sources))] public static void Select_Longrunning(Labeled<ParallelQuery<int>> labeled, int count) { Select(labeled, count); } [Theory] [MemberData(nameof(UnorderedSources.Ranges), new[] { 0, 1, 2, 16 }, MemberType = typeof(UnorderedSources))] public static void Select_Unordered_NotPipelined(Labeled<ParallelQuery<int>> labeled, int count) { ParallelQuery<int> query = labeled.Item; IntegerRangeSet seen = new IntegerRangeSet(0, count); Assert.All(query.Select(x => KeyValuePair.Create(x, x * x)).ToList(), p => { seen.Add(p.Key); Assert.Equal(p.Key * p.Key, p.Value); }); seen.AssertComplete(); } [Theory] [OuterLoop] [MemberData(nameof(UnorderedSources.Ranges), new[] { 1024, 1024 * 4 }, MemberType = typeof(UnorderedSources))] public static void Select_Unordered_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> labeled, int count) { Select_Unordered_NotPipelined(labeled, count); } [Theory] [MemberData(nameof(Sources.Ranges), new[] { 0, 1, 2, 16 }, MemberType = typeof(Sources))] public static void Select_NotPipelined(Labeled<ParallelQuery<int>> labeled, int count) { ParallelQuery<int> query = labeled.Item; int seen = 0; Assert.All(query.Select(x => KeyValuePair.Create(x, x * x)).ToList(), p => { Assert.Equal(seen++, p.Key); Assert.Equal(p.Key * p.Key, p.Value); }); Assert.Equal(count, seen); } [Theory] [OuterLoop] [MemberData(nameof(Sources.Ranges), new[] { 1024, 1024 * 4 }, MemberType = typeof(Sources))] public static void Select_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> labeled, int count) { Select_NotPipelined(labeled, count); } // Uses an element's index to calculate an output value. If order preservation isn't // working, this would PROBABLY fail. Unfortunately, this isn't deterministic. But choosing // larger input sizes increases the probability that it will. [Theory] [MemberData(nameof(UnorderedSources.Ranges), new[] { 0, 1, 2, 16 }, MemberType = typeof(UnorderedSources))] public static void Select_Indexed_Unordered(Labeled<ParallelQuery<int>> labeled, int count) { // For unordered collections, which element is at which index isn't actually guaranteed, but an effect of the implementation. // If this test starts failing it should be updated, and possibly mentioned in release notes. ParallelQuery<int> query = labeled.Item; IntegerRangeSet seen = new IntegerRangeSet(0, count); foreach (var p in query.Select((x, index) => KeyValuePair.Create(x, index))) { seen.Add(p.Key); Assert.Equal(p.Key, p.Value); } seen.AssertComplete(); } [Theory] [OuterLoop] [MemberData(nameof(UnorderedSources.Ranges), new[] { 1024, 1024 * 4 }, MemberType = typeof(UnorderedSources))] public static void Select_Indexed_Unordered_Longrunning(Labeled<ParallelQuery<int>> labeled, int count) { Select_Indexed_Unordered(labeled, count); } [Theory] [MemberData(nameof(Sources.Ranges), new[] { 0, 1, 2, 16 }, MemberType = typeof(Sources))] public static void Select_Indexed(Labeled<ParallelQuery<int>> labeled, int count) { ParallelQuery<int> query = labeled.Item; int seen = 0; foreach (var p in query.Select((x, index) => KeyValuePair.Create(x, index))) { Assert.Equal(seen++, p.Key); Assert.Equal(p.Key, p.Value); } Assert.Equal(count, seen); } [Theory] [OuterLoop] [MemberData(nameof(Sources.Ranges), new[] { 1024, 1024 * 4 }, MemberType = typeof(Sources))] public static void Select_Indexed_Longrunning(Labeled<ParallelQuery<int>> labeled, int count) { Select_Unordered(labeled, count); } [Theory] [MemberData(nameof(UnorderedSources.Ranges), new[] { 0, 1, 2, 16 }, MemberType = typeof(UnorderedSources))] public static void Select_Indexed_Unordered_NotPipelined(Labeled<ParallelQuery<int>> labeled, int count) { // For unordered collections, which element is at which index isn't actually guaranteed, but an effect of the implementation. // If this test starts failing it should be updated, and possibly mentioned in release notes. ParallelQuery<int> query = labeled.Item; IntegerRangeSet seen = new IntegerRangeSet(0, count); Assert.All(query.Select((x, index) => KeyValuePair.Create(x, index)).ToList(), p => { seen.Add(p.Key); Assert.Equal(p.Key, p.Value); }); seen.AssertComplete(); } [Theory] [OuterLoop] [MemberData(nameof(UnorderedSources.Ranges), new[] { 1024, 1024 * 4 }, MemberType = typeof(UnorderedSources))] public static void Select_Indexed_Unordered_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> labeled, int count) { Select_Indexed_Unordered_NotPipelined(labeled, count); } [Theory] [MemberData(nameof(Sources.Ranges), new[] { 0, 1, 2, 16 }, MemberType = typeof(Sources))] public static void Select_Indexed_NotPipelined(Labeled<ParallelQuery<int>> labeled, int count) { ParallelQuery<int> query = labeled.Item; int seen = 0; Assert.All(query.Select((x, index) => KeyValuePair.Create(x, index)).ToList(), p => { Assert.Equal(seen++, p.Key); Assert.Equal(p.Key, p.Value); }); Assert.Equal(count, seen); } [Theory] [OuterLoop] [MemberData(nameof(Sources.Ranges), new[] { 1024, 1024 * 4 }, MemberType = typeof(Sources))] public static void Select_Indexed_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> labeled, int count) { Select_Indexed_NotPipelined(labeled, count); } [Fact] public static void Select_ArgumentNullException() { Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<bool>)null).Select(x => x)); Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<bool>)null).Select((x, index) => x)); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Empty<bool>().Select((Func<bool, bool>)null)); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Empty<bool>().Select((Func<bool, int, bool>)null)); } [Theory] [InlineData(true, true)] [InlineData(true, false)] [InlineData(false, true)] [InlineData(false, false)] public static void Select_OrderablePartitionerWithOutOfOrderInputs_AsOrdered_CorrectOrder(bool keysOrderedInEachPartition, bool keysNormalized) { var range = new RangeOrderablePartitioner(0, 1024, keysOrderedInEachPartition, keysNormalized); int next = 0; foreach (int i in range.AsParallel().AsOrdered().Select(i => i)) { Assert.Equal(next++, i); } } // // SelectMany // // [Regression Test] // An issue occurred because the QuerySettings structure was not being deep-cloned during // query-opening. As a result, the concurrent inner-enumerators (for the RHS operators) // that occur in SelectMany were sharing CancellationState that they should not have. // The result was that enumerators could falsely believe they had been canceled when // another inner-enumerator was disposed. // // Note: the failure was intermittent. this test would fail about 1 in 2 times on mikelid1 (4-core). public static IEnumerable<object[]> SelectManyUnorderedData(int[] counts) { foreach (object[] results in UnorderedSources.Ranges(counts.Cast<int>())) { foreach (Labeled<Func<int, int, IEnumerable<int>>> expander in Expanders()) { foreach (int count in new[] { 0, 1, 2, 8 }) { yield return new object[] { results[0], results[1], expander, count }; } } } } public static IEnumerable<object[]> SelectManyData(int[] counts) { foreach (object[] results in Sources.Ranges(counts.Cast<int>())) { foreach (Labeled<Func<int, int, IEnumerable<int>>> expander in Expanders()) { foreach (int count in new[] { 0, 1, 2, 8 }) { yield return new object[] { results[0], results[1], expander, count }; } } } } private static IEnumerable<Labeled<Func<int, int, IEnumerable<int>>>> Expanders() { yield return Labeled.Label("Array", (Func<int, int, IEnumerable<int>>)((start, count) => Enumerable.Range(start * count, count).ToArray())); yield return Labeled.Label("Enumerable.Range", (Func<int, int, IEnumerable<int>>)((start, count) => Enumerable.Range(start * count, count))); yield return Labeled.Label("ParallelEnumerable.Range", (Func<int, int, IEnumerable<int>>)((start, count) => ParallelEnumerable.Range(start * count, count).AsOrdered().Select(x => x))); } [Theory] [MemberData(nameof(SelectManyUnorderedData), new[] { 0, 1, 2, 16 })] public static void SelectMany_Unordered(Labeled<ParallelQuery<int>> labeled, int count, Labeled<Func<int, int, IEnumerable<int>>> expander, int expansion) { ParallelQuery<int> query = labeled.Item; Func<int, int, IEnumerable<int>> expand = expander.Item; IntegerRangeSet seen = new IntegerRangeSet(0, count * expansion); foreach (int i in query.SelectMany(x => expand(x, expansion))) { seen.Add(i); } seen.AssertComplete(); } [Theory] [OuterLoop] [MemberData(nameof(SelectManyUnorderedData), new[] { 1024, 1024 * 4 })] public static void SelectMany_Unordered_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, Labeled<Func<int, int, IEnumerable<int>>> expander, int expansion) { SelectMany_Unordered(labeled, count, expander, expansion); } [Theory] [MemberData(nameof(SelectManyData), new[] { 0, 1, 2, 16 })] public static void SelectMany(Labeled<ParallelQuery<int>> labeled, int count, Labeled<Func<int, int, IEnumerable<int>>> expander, int expansion) { ParallelQuery<int> query = labeled.Item; Func<int, int, IEnumerable<int>> expand = expander.Item; int seen = 0; foreach (int i in query.SelectMany(x => expand(x, expansion))) { Assert.Equal(seen++, i); } Assert.Equal(count * expansion, seen); } [Theory] [OuterLoop] [MemberData(nameof(SelectManyData), new[] { 1024, 1024 * 4 })] public static void SelectMany_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, Labeled<Func<int, int, IEnumerable<int>>> expander, int expansion) { SelectMany(labeled, count, expander, expansion); } [Theory] [MemberData(nameof(SelectManyUnorderedData), new[] { 0, 1, 2, 16 })] public static void SelectMany_Unordered_NotPipelined(Labeled<ParallelQuery<int>> labeled, int count, Labeled<Func<int, int, IEnumerable<int>>> expander, int expansion) { ParallelQuery<int> query = labeled.Item; Func<int, int, IEnumerable<int>> expand = expander.Item; IntegerRangeSet seen = new IntegerRangeSet(0, count * expansion); Assert.All(query.SelectMany(x => expand(x, expansion)).ToList(), x => seen.Add(x)); seen.AssertComplete(); } [Theory] [OuterLoop] [MemberData(nameof(SelectManyUnorderedData), new[] { 1024, 1024 * 4 })] public static void SelectMany_Unordered_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, Labeled<Func<int, int, IEnumerable<int>>> expander, int expansion) { SelectMany_Unordered_NotPipelined(labeled, count, expander, expansion); } [Theory] [MemberData(nameof(SelectManyData), new[] { 0, 1, 2, 16 })] public static void SelectMany_NotPipelined(Labeled<ParallelQuery<int>> labeled, int count, Labeled<Func<int, int, IEnumerable<int>>> expander, int expansion) { ParallelQuery<int> query = labeled.Item; Func<int, int, IEnumerable<int>> expand = expander.Item; int seen = 0; Assert.All(query.SelectMany(x => expand(x, expansion)).ToList(), x => Assert.Equal(seen++, x)); Assert.Equal(count * expansion, seen); } [Theory] [OuterLoop] [MemberData(nameof(SelectManyData), new[] { 1024, 1024 * 4 })] public static void SelectMany_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, Labeled<Func<int, int, IEnumerable<int>>> expander, int expansion) { SelectMany_NotPipelined(labeled, count, expander, expansion); } [Theory] [MemberData(nameof(SelectManyUnorderedData), new[] { 0, 1, 2, 16 })] public static void SelectMany_Unordered_ResultSelector(Labeled<ParallelQuery<int>> labeled, int count, Labeled<Func<int, int, IEnumerable<int>>> expander, int expansion) { ParallelQuery<int> query = labeled.Item; Func<int, int, IEnumerable<int>> expand = expander.Item; IntegerRangeSet seen = new IntegerRangeSet(0, count * expansion); foreach (var p in query.SelectMany(x => expand(x, expansion), (original, expanded) => KeyValuePair.Create(original, expanded))) { seen.Add(p.Value); Assert.Equal(p.Key, p.Value / expansion); } seen.AssertComplete(); } [Theory] [OuterLoop] [MemberData(nameof(SelectManyUnorderedData), new[] { 1024, 1024 * 4 })] public static void SelectMany_Unordered_ResultSelector_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, Labeled<Func<int, int, IEnumerable<int>>> expander, int expansion) { SelectMany_Unordered_ResultSelector(labeled, count, expander, expansion); } [Theory] [MemberData(nameof(SelectManyUnorderedData), new[] { 0, 1, 2, 16 })] public static void SelectMany_Unordered_ResultSelector_NotPipelined(Labeled<ParallelQuery<int>> labeled, int count, Labeled<Func<int, int, IEnumerable<int>>> expander, int expansion) { ParallelQuery<int> query = labeled.Item; Func<int, int, IEnumerable<int>> expand = expander.Item; IntegerRangeSet seen = new IntegerRangeSet(0, count * expansion); Assert.All(query.SelectMany(x => expand(x, expansion), (original, expanded) => KeyValuePair.Create(original, expanded)).ToList(), p => { seen.Add(p.Value); Assert.Equal(p.Key, p.Value / expansion); }); seen.AssertComplete(); } [Theory] [OuterLoop] [MemberData(nameof(SelectManyUnorderedData), new[] { 1024, 1024 * 4 })] public static void SelectMany_Unordered_ResultSelector_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, Labeled<Func<int, int, IEnumerable<int>>> expander, int expansion) { SelectMany_Unordered_ResultSelector_NotPipelined(labeled, count, expander, expansion); } [Theory] [MemberData(nameof(SelectManyData), new[] { 0, 1, 2, 16 })] public static void SelectMany_ResultSelector(Labeled<ParallelQuery<int>> labeled, int count, Labeled<Func<int, int, IEnumerable<int>>> expander, int expansion) { ParallelQuery<int> query = labeled.Item; Func<int, int, IEnumerable<int>> expand = expander.Item; int seen = 0; foreach (var p in query.SelectMany(x => expand(x, expansion), (original, expanded) => KeyValuePair.Create(original, expanded))) { Assert.Equal(seen++, p.Value); Assert.Equal(p.Key, p.Value / expansion); } Assert.Equal(count * expansion, seen); } [Theory] [OuterLoop] [MemberData(nameof(SelectManyData), new[] { 1024, 1024 * 4 })] public static void SelectMany_ResultSelector_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, Labeled<Func<int, int, IEnumerable<int>>> expander, int expansion) { SelectMany_ResultSelector(labeled, count, expander, expansion); } [Theory] [MemberData(nameof(SelectManyData), new[] { 0, 1, 2, 16 })] public static void SelectMany_ResultSelector_NotPipelined(Labeled<ParallelQuery<int>> labeled, int count, Labeled<Func<int, int, IEnumerable<int>>> expander, int expansion) { ParallelQuery<int> query = labeled.Item; Func<int, int, IEnumerable<int>> expand = expander.Item; int seen = 0; Assert.All(query.SelectMany(x => expand(x, expansion), (original, expanded) => KeyValuePair.Create(original, expanded)).ToList(), p => { Assert.Equal(seen++, p.Value); Assert.Equal(p.Key, p.Value / expansion); }); Assert.Equal(count * expansion, seen); } [Theory] [OuterLoop] [MemberData(nameof(SelectManyData), new[] { 1024, 1024 * 4 })] public static void SelectMany_ResultSelector_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, Labeled<Func<int, int, IEnumerable<int>>> expander, int expansion) { SelectMany_ResultSelector_NotPipelined(labeled, count, expander, expansion); } [Theory] [MemberData(nameof(SelectManyUnorderedData), new[] { 0, 1, 2, 16 })] public static void SelectMany_Indexed_Unordered(Labeled<ParallelQuery<int>> labeled, int count, Labeled<Func<int, int, IEnumerable<int>>> expander, int expansion) { // For unordered collections, which element is at which index isn't actually guaranteed, but an effect of the implementation. // If this test starts failing it should be updated, and possibly mentioned in release notes. ParallelQuery<int> query = labeled.Item; Func<int, int, IEnumerable<int>> expand = expander.Item; IntegerRangeSet seen = new IntegerRangeSet(0, count * expansion); foreach (var pIndex in query.SelectMany((x, index) => expand(x, expansion).Select(y => KeyValuePair.Create(index, y)))) { seen.Add(pIndex.Value); Assert.Equal(pIndex.Key, pIndex.Value / expansion); } seen.AssertComplete(); } [Theory] [OuterLoop] [MemberData(nameof(SelectManyUnorderedData), new[] { 1024, 1024 * 4 })] public static void SelectMany_Indexed_Unordered_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, Labeled<Func<int, int, IEnumerable<int>>> expander, int expansion) { SelectMany_Indexed_Unordered(labeled, count, expander, expansion); } [Theory] [MemberData(nameof(SelectManyUnorderedData), new[] { 0, 1, 2, 16 })] public static void SelectMany_Indexed_Unordered_NotPipelined(Labeled<ParallelQuery<int>> labeled, int count, Labeled<Func<int, int, IEnumerable<int>>> expander, int expansion) { // For unordered collections, which element is at which index isn't actually guaranteed, but an effect of the implementation. // If this test starts failing it should be updated, and possibly mentioned in release notes. ParallelQuery<int> query = labeled.Item; Func<int, int, IEnumerable<int>> expand = expander.Item; IntegerRangeSet seen = new IntegerRangeSet(0, count * expansion); Assert.All(query.SelectMany((x, index) => expand(x, expansion).Select(y => KeyValuePair.Create(index, y))).ToList(), pIndex => { seen.Add(pIndex.Value); Assert.Equal(pIndex.Key, pIndex.Value / expansion); }); seen.AssertComplete(); } [Theory] [OuterLoop] [MemberData(nameof(SelectManyUnorderedData), new[] { 1024, 1024 * 4 })] public static void SelectMany_Indexed_Unordered_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, Labeled<Func<int, int, IEnumerable<int>>> expander, int expansion) { SelectMany_Indexed_Unordered_NotPipelined(labeled, count, expander, expansion); } [Theory] [MemberData(nameof(SelectManyData), new[] { 0, 1, 2, 16 })] public static void SelectMany_Indexed(Labeled<ParallelQuery<int>> labeled, int count, Labeled<Func<int, int, IEnumerable<int>>> expander, int expansion) { ParallelQuery<int> query = labeled.Item; Func<int, int, IEnumerable<int>> expand = expander.Item; int seen = 0; foreach (var pIndex in query.SelectMany((x, index) => expand(x, expansion).Select(y => KeyValuePair.Create(index, y)))) { Assert.Equal(seen++, pIndex.Value); Assert.Equal(pIndex.Key, pIndex.Value / expansion); } Assert.Equal(count * expansion, seen); } [Theory] [OuterLoop] [MemberData(nameof(SelectManyData), new[] { 1024, 1024 * 4 })] public static void SelectMany_Indexed_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, Labeled<Func<int, int, IEnumerable<int>>> expander, int expansion) { SelectMany_Indexed(labeled, count, expander, expansion); } [Theory] [MemberData(nameof(SelectManyData), new[] { 0, 1, 2, 16 })] public static void SelectMany_Indexed_NotPipelined(Labeled<ParallelQuery<int>> labeled, int count, Labeled<Func<int, int, IEnumerable<int>>> expander, int expansion) { ParallelQuery<int> query = labeled.Item; Func<int, int, IEnumerable<int>> expand = expander.Item; int seen = 0; Assert.All(query.SelectMany((x, index) => expand(x, expansion).Select(y => KeyValuePair.Create(index, y))).ToList(), pIndex => { Assert.Equal(seen++, pIndex.Value); Assert.Equal(pIndex.Key, pIndex.Value / expansion); }); Assert.Equal(count * expansion, seen); } [Theory] [OuterLoop] [MemberData(nameof(SelectManyData), new[] { 1024, 1024 * 4 })] public static void SelectMany_Indexed_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, Labeled<Func<int, int, IEnumerable<int>>> expander, int expansion) { SelectMany_Indexed_NotPipelined(labeled, count, expander, expansion); } [Theory] [MemberData(nameof(SelectManyUnorderedData), new[] { 0, 1, 2, 16 })] public static void SelectMany_Indexed_Unordered_ResultSelector(Labeled<ParallelQuery<int>> labeled, int count, Labeled<Func<int, int, IEnumerable<int>>> expander, int expansion) { // For unordered collections, which element is at which index isn't actually guaranteed, but an effect of the implementation. // If this test starts failing it should be updated, and possibly mentioned in release notes. ParallelQuery<int> query = labeled.Item; Func<int, int, IEnumerable<int>> expand = expander.Item; IntegerRangeSet seen = new IntegerRangeSet(0, count * expansion); foreach (var pOuter in query.SelectMany((x, index) => expand(x, expansion).Select(y => KeyValuePair.Create(index, y)), (original, expanded) => KeyValuePair.Create(original, expanded))) { var pInner = pOuter.Value; Assert.Equal(pOuter.Key, pInner.Key); seen.Add(pInner.Value); Assert.Equal(pOuter.Key, pInner.Value / expansion); } seen.AssertComplete(); } [Theory] [OuterLoop] [MemberData(nameof(SelectManyUnorderedData), new[] { 1024, 1024 * 4 })] public static void SelectMany_Indexed_Unordered_ResultSelector_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, Labeled<Func<int, int, IEnumerable<int>>> expander, int expansion) { SelectMany_Indexed_Unordered_ResultSelector(labeled, count, expander, expansion); } [Theory] [MemberData(nameof(SelectManyUnorderedData), new[] { 0, 1, 2, 16 })] public static void SelectMany_Indexed_Unordered_ResultSelector_NotPipelined(Labeled<ParallelQuery<int>> labeled, int count, Labeled<Func<int, int, IEnumerable<int>>> expander, int expansion) { // For unordered collections, which element is at which index isn't actually guaranteed, but an effect of the implementation. // If this test starts failing it should be updated, and possibly mentioned in release notes. ParallelQuery<int> query = labeled.Item; Func<int, int, IEnumerable<int>> expand = expander.Item; IntegerRangeSet seen = new IntegerRangeSet(0, count * expansion); Assert.All(query.SelectMany((x, index) => expand(x, expansion).Select(y => KeyValuePair.Create(index, y)), (original, expanded) => KeyValuePair.Create(original, expanded)).ToList(), pOuter => { var pInner = pOuter.Value; Assert.Equal(pOuter.Key, pInner.Key); seen.Add(pInner.Value); Assert.Equal(pOuter.Key, pInner.Value / expansion); }); seen.AssertComplete(); } [Theory] [OuterLoop] [MemberData(nameof(SelectManyUnorderedData), new[] { 1024, 1024 * 4 })] public static void SelectMany_Indexed_Unordered_ResultSelector_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, Labeled<Func<int, int, IEnumerable<int>>> expander, int expansion) { SelectMany_Indexed_Unordered_ResultSelector_NotPipelined(labeled, count, expander, expansion); } [Theory] [MemberData(nameof(SelectManyData), new[] { 0, 1, 2, 16 })] public static void SelectMany_Indexed_ResultSelector(Labeled<ParallelQuery<int>> labeled, int count, Labeled<Func<int, int, IEnumerable<int>>> expander, int expansion) { ParallelQuery<int> query = labeled.Item; Func<int, int, IEnumerable<int>> expand = expander.Item; int seen = 0; foreach (var pOuter in query.SelectMany((x, index) => expand(x, expansion).Select(y => KeyValuePair.Create(index, y)), (original, expanded) => KeyValuePair.Create(original, expanded))) { var pInner = pOuter.Value; Assert.Equal(pOuter.Key, pInner.Key); Assert.Equal(seen++, pInner.Value); Assert.Equal(pOuter.Key, pInner.Value / expansion); } Assert.Equal(count * expansion, seen); } [Theory] [OuterLoop] [MemberData(nameof(SelectManyData), new[] { 1024, 1024 * 4 })] public static void SelectMany_Indexed_ResultSelector_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, Labeled<Func<int, int, IEnumerable<int>>> expander, int expansion) { SelectMany_Indexed_ResultSelector(labeled, count, expander, expansion); } [Theory] [MemberData(nameof(SelectManyData), new[] { 0, 1, 2, 16 })] public static void SelectMany_Indexed_ResultSelector_NotPipelined(Labeled<ParallelQuery<int>> labeled, int count, Labeled<Func<int, int, IEnumerable<int>>> expander, int expansion) { ParallelQuery<int> query = labeled.Item; Func<int, int, IEnumerable<int>> expand = expander.Item; int seen = 0; Assert.All(query.SelectMany((x, index) => expand(x, expansion).Select(y => KeyValuePair.Create(index, y)), (original, expanded) => KeyValuePair.Create(original, expanded)).ToList(), pOuter => { var pInner = pOuter.Value; Assert.Equal(pOuter.Key, pInner.Key); Assert.Equal(seen++, pInner.Value); Assert.Equal(pOuter.Key, pInner.Value / expansion); }); Assert.Equal(count * expansion, seen); } [Theory] [OuterLoop] [MemberData(nameof(SelectManyData), new[] { 1024, 1024 * 4 })] public static void SelectMany_Indexed_ResultSelector_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, Labeled<Func<int, int, IEnumerable<int>>> expander, int expansion) { SelectMany_Indexed_ResultSelector_NotPipelined(labeled, count, expander, expansion); } [Fact] public static void SelectMany_ArgumentNullException() { Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<bool>)null).SelectMany(x => new[] { x })); Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<bool>)null).SelectMany((x, index) => new[] { x })); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Empty<bool>().SelectMany((Func<bool, IEnumerable<bool>>)null)); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Empty<bool>().SelectMany((Func<bool, int, IEnumerable<bool>>)null)); Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<bool>)null).SelectMany(x => new[] { x }, (x, y) => x)); Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<bool>)null).SelectMany((x, index) => new[] { x }, (x, y) => x)); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Empty<bool>().SelectMany((Func<bool, IEnumerable<bool>>)null, (x, y) => x)); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Empty<bool>().SelectMany((Func<bool, int, IEnumerable<bool>>)null, (x, y) => x)); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Empty<bool>().SelectMany(x => new[] { x }, (Func<bool, bool, bool>)null)); Assert.Throws<ArgumentNullException>(() => ParallelEnumerable.Empty<bool>().SelectMany((x, index) => new[] { x }, (Func<bool, bool, bool>)null)); } } }
/* Copyright 2006 - 2010 Intel Corporation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Collections; using OpenSource.UPnP; using OpenSource.UPnP.AV; using OpenSource.Utilities; using OpenSource.UPnP.AV.CdsMetadata; namespace OpenSource.UPnP.AV.RENDERER.CP { /// <summary> /// This is the main abstraction object that a developer will be interacting /// with, when controlling a rendering device. /// <para> /// This object abstracts all the functionality that a renderer exposes to control points, such as volume, position, /// etc. This object is pretty primitive in how it is used, as it is basically a portal into the renderer session. Most of the grunt work of a control point will /// rest in obtaining these AVConnection objects. Yet, one will never need to directly instantiate one of these objects, as they will be created for you, by the <see cref="OpenSource.UPnP.AVRENDERERSTACK.AVRenderer"/> /// object. /// </para> /// </summary> public class AVConnection { public class MimeTypeMismatchException : Exception { public MimeTypeMismatchException(String msg):base(msg) { } } internal string ProtocolInfoString = null; private int StateCounter = 0; private object Tag = null; public delegate void OnReadyHandler(AVConnection sender, object Tag); public event OnReadyHandler OnReady; public delegate void OnReuseConnectionHandler(AVConnection sender, object Tag); public event OnReuseConnectionHandler OnReuseConnection; public event OnReuseConnectionHandler OnReuseConnectionFailed; private Hashtable PlayListTable = new Hashtable(); public void CreateConnection(IMediaContainer Container) { CreateConnection(Container,null); } public void CreateConnection(IMediaContainer Container, object Tag) { ArrayList RList = new ArrayList(); foreach(IMediaItem item in Container.Items) { foreach(IMediaResource r in item.MergedResources) { if(Parent.SupportsProtocolInfo(r.ProtocolInfo)) { RList.Add(r); break; } } } if(RList.Count==0) { //ToDo: Throw Exception here return; } CreateConnection((IMediaResource[])RList.ToArray(typeof(IMediaResource)),Tag); } public void CreateConnection(IMediaItem item) { CreateConnection(item,null); } public void CreateConnection(IMediaItem item, object Tag) { CreateConnection(new IMediaItem[1]{item},Tag); } public void CreateConnection(IMediaItem[] items) { CreateConnection(items,null); } public void CreateConnection(IMediaItem[] items, object Tag) { ArrayList RList = new ArrayList(); foreach(IMediaItem item in items) { foreach(IMediaResource resource in item.MergedResources) { if(Parent.SupportsProtocolInfo(resource.ProtocolInfo)) { // Use this resource RList.Add(resource); break; } } } if(RList.Count==0) { //ToDo: Throw Exception Here return; } CreateConnection((IMediaResource[])RList.ToArray(typeof(IMediaResource)),Tag); } public void CreateConnection(IMediaResource media) { CreateConnection(media,null); } public void CreateConnection(IMediaResource media, object Tag) { CreateConnection(new IMediaResource[1]{media}, Tag); } public void CreateConnection(IMediaResource[] resources) { CreateConnection(resources,null); } public void CreateConnection(IMediaResource[] resources, object Tag) { if(resources.Length>1) { if(!(new ProtocolInfoString(this.ProtocolInfoString)).Matches(new ProtocolInfoString("http-get:*:audio/mpegurl:*"))) { throw(new MimeTypeMismatchException("Cannot call SetAVTransportURI with a different MimeType")); } } else { if (this.Parent.HasConnectionHandling) { if(!(new ProtocolInfoString(this.ProtocolInfoString).Matches(resources[0].ProtocolInfo))) { throw(new MimeTypeMismatchException("Cannot call SetAVTransportURI with a different MimeType")); } } else { if(!this.Parent.SupportsProtocolInfo(resources[0].ProtocolInfo)) { throw(new MimeTypeMismatchException("Cannot call SetAVTransportURI with a different MimeType")); } } } AVPlayList pl = new AVPlayList(this,resources,new AVPlayList.ReadyHandler(PlayListSink), new AVPlayList.FailedHandler(PlayListFailedSink),Tag); PlayListTable[pl.GetHashCode()] = pl; } private void PlayListSink(AVPlayList sender, AVConnection c, object Tag) { PlayListTable.Remove(sender.GetHashCode()); if(OnReuseConnection!=null) OnReuseConnection(this,Tag); } private void PlayListFailedSink(AVPlayList sender, AVRenderer.CreateFailedReason reason) { PlayListTable.Remove(sender.GetHashCode()); if(OnReuseConnectionFailed!=null) OnReuseConnectionFailed(this,Tag); } public void Dispose() { AVTransport.Dispose(); RenderingControl.Dispose(); ConnectionManager.Dispose(); this.AV_LastChange.Dispose(); this.AV_LastChange = null; this.RC_LastChange.Dispose(); this.RC_LastChange = null; if(CurrentPlayList!=null) CurrentPlayList.Dispose(); this.CurrentPlayList = null; this.OnCurrentMetaDataChanged = null; this.OnMediaResourceChanged = null; this.OnMute = null; this.OnNumberOfTracksChanged = null; this.OnPositionChanged = null; this.OnReady = null; this.OnRemoved = null; this.OnTrackChanged = null; this.OnTrackURIChanged = null; this.OnVolume = null; if(OnRemoved!=null) OnRemoved(this); } /// <summary> /// Enumerations representing the possible PlayStates /// </summary> public enum PlayState { PLAYING, RECORDING, SEEKING, STOPPED, PAUSED, TRANSITIONING, } public enum PlayMode { NORMAL, INTRO, DIRECT_1, SHUFFLE, RANDOM, REPEAT_ONE, REPEAT_ALL, } // This event handles the Current Track URI public delegate void TrackURIChangedHandler(AVConnection sender); public event TrackURIChangedHandler OnTrackURIChanged; // This event handles the CurrentPlayMode public delegate void CurrentPlayModeChangedHandler(AVConnection sender, PlayMode NewMode); public event CurrentPlayModeChangedHandler OnCurrentPlayModeChanged; // This event handles the Current Meta Data public delegate void CurrentMetaDataChangedHandler(AVConnection sender); public event CurrentMetaDataChangedHandler OnCurrentMetaDataChanged; // This internal event handles the current AVTransportURI internal delegate void CurrentURIChangedHandler(AVConnection sender); private WeakEvent OnCurrentURIChangedEvent = new WeakEvent(); internal event CurrentURIChangedHandler OnCurrentURIChanged { add { OnCurrentURIChangedEvent.Register(value); } remove { OnCurrentURIChangedEvent.UnRegister(value); } } public delegate void MediaResourceChangedHandler(AVConnection sender, IMediaResource NewResource); /// <summary> /// Fired when the Current Media Resource changed /// </summary> public event MediaResourceChangedHandler OnMediaResourceChanged; public delegate void RendererHandler(AVConnection sender); /// <summary> /// Fired when this connection was closed /// </summary> public event RendererHandler OnRemoved; public delegate void CurrentTrackChangedHandler(AVConnection sender, UInt32 NewTrackNumber); /// <summary> /// Fired when the current track changed /// </summary> public event CurrentTrackChangedHandler OnTrackChanged; public delegate void NumberOfTracksChangedHandler(AVConnection sender, UInt32 NewNumberOfTracks); /// <summary> /// Fired when the number of tracks changed /// </summary> public event NumberOfTracksChangedHandler OnNumberOfTracksChanged; public delegate void TransportStatusChangedHandler(AVConnection sender, string NewTransportStatus); private WeakEvent OnTransportStatusChangedEvent = new WeakEvent(); public event TransportStatusChangedHandler OnTransportStatusChanged { add { OnTransportStatusChangedEvent.Register(value); } remove { OnTransportStatusChangedEvent.UnRegister(value); } } public delegate void PlayStateChangedHandler(AVConnection sender, PlayState NewState); private WeakEvent OnPlayStateChangedEvent = new WeakEvent(); /// <summary> /// Fired when the current play state changed /// </summary> public event PlayStateChangedHandler OnPlayStateChanged { add { OnPlayStateChangedEvent.Register(value); } remove { OnPlayStateChangedEvent.UnRegister(value); } } public delegate void MuteStateChangedHandler(AVConnection sender, bool NewMuteStatus); /// <summary> /// Fired when the mute state changed /// </summary> public event MuteStateChangedHandler OnMute; public delegate void VolumeChangedHandler(AVConnection sender, UInt16 Volume); /// <summary> /// Fired when the volume changed /// </summary> public event VolumeChangedHandler OnVolume; public delegate void PositionChangedHandler(AVConnection sender, TimeSpan Position); /// <summary> /// Fired when the current position changed /// </summary> public event PositionChangedHandler OnPositionChanged; // This internal event is triggered when SetAVTransportURI completes public delegate void AVTransportSetHandler(AVConnection sender, object Tag); private WeakEvent OnSetAVTransportURIEvent = new WeakEvent(); internal event AVTransportSetHandler OnSetAVTransportURI { add { OnSetAVTransportURIEvent.Register(value); } remove { OnSetAVTransportURIEvent.UnRegister(value); } } protected CpAVTransport AVTransport; protected CpRenderingControl RenderingControl; protected CpConnectionManager ConnectionManager; protected RenderingControlLastChange RC_LastChange; protected AVTransportLastChange AV_LastChange; /// <summary> /// Connection Manager ID /// </summary> protected Int32 CMid; /// <summary> /// AVTransport ID and Rendering Control ID /// </summary> protected int AVTid,RCid; /// <summary> /// The UPnP Friendly name for the RendererDevice /// </summary> public string FriendlyName; /// <summary> /// A Unique identifier for this AVConnection /// </summary> public string Identifier; private IMediaContainer _Container = null; private IMediaItem _CurrentItem = null; public IMediaContainer Container { get { return(_Container); } } /// <summary> /// The Current Item that is playing /// </summary> public IMediaItem CurrentItem { get { return(_CurrentItem); } } protected UInt16 MaxVolume = 0; protected UInt16 MinVolume = 0; protected IMediaResource _resource = null; internal AVRenderer _Parent = null; /// <summary> /// Upon successful connection, this is the sole reference to the AVPlaylist that /// is streaming the playlist /// </summary> internal AVPlayList CurrentPlayList = null; public string GetFileNameForLocallyServedMedia(Uri MediaUri) { if(this.CurrentPlayList!=null) { return(this.CurrentPlayList.GetFilenameFromURI(MediaUri)); } else { return(null); } } /// <summary> /// The UPnP A/V Connection ID /// </summary> public Int32 ConnectionID { get { return(this.CMid); } } /// <summary> /// The AVRenderer that owns this AVConnection /// </summary> public AVRenderer Parent { get { return(_Parent); } } /// <summary> /// bool indicating if this renderer implements ConnectionComplete /// </summary> public bool IsCloseSupported { get { return(ConnectionManager.HasAction_ConnectionComplete); } } /// <summary> /// Closes the connection, if supported /// </summary> public void Close() { if(IsCloseSupported) { ConnectionManager.ConnectionComplete(ConnectionID); } } ~AVConnection() { OpenSource.Utilities.InstanceTracker.Remove(this); } /// <summary> /// This construct is only called by the AVRenderer object. /// </summary> /// <param name="device"></param> /// <param name="AVTransportID"></param> /// <param name="RenderingControlID"></param> /// <param name="ConnectionID"></param> /// <param name="ReadyCallback"></param> /// <param name="StateObject"></param> internal AVConnection(UPnPDevice device, int AVTransportID, int RenderingControlID, Int32 ConnectionID, AVConnection.OnReadyHandler ReadyCallback, object StateObject) { OpenSource.Utilities.InstanceTracker.Add(this); this.Tag = StateObject; this.OnReady += ReadyCallback; FriendlyName = device.FriendlyName; Identifier = device.UniqueDeviceName + ":" + ConnectionID.ToString(); AVTid = AVTransportID; RCid = RenderingControlID; CMid = ConnectionID; AVTransport = new CpAVTransport(device.GetServices(CpAVTransport.SERVICE_NAME)[0]); RenderingControl = new CpRenderingControl(device.GetServices(CpRenderingControl.SERVICE_NAME)[0]); ConnectionManager = new CpConnectionManager(device.GetServices(CpConnectionManager.SERVICE_NAME)[0]); if(RenderingControl.HasStateVariable_Volume) { // If the renderer has defined ranges, use those if(RenderingControl.HasMaximum_Volume) { MaxVolume = (UInt16)RenderingControl.Maximum_Volume; } else { MaxVolume = UInt16.MaxValue; } if(RenderingControl.HasMinimum_Volume) { MinVolume = (UInt16)RenderingControl.Minimum_Volume; } else { MinVolume = UInt16.MinValue; } } lock(this) { if(AVTransport.HasStateVariable_LastChange) { // Hook up to the LastChange event of AVTransport ++this.StateCounter; AV_LastChange = new AVTransportLastChange(AVTransport,device.UniqueDeviceName, AVTid, new AVTransportLastChange.ReadyHandler(AVTLC)); AV_LastChange.OnCurrentPositionChanged += new AVTransportLastChange.VariableChangeHandler(PositionSink); AV_LastChange.OnPlayStateChanged += new AVTransportLastChange.VariableChangeHandler(PlayStateSink); AV_LastChange.OnAVTransportURIChanged += new AVTransportLastChange.VariableChangeHandler(AVTransportURISink); AV_LastChange.OnCurrentTrackChanged += new AVTransportLastChange.VariableChangeHandler(TrackChangedSink); AV_LastChange.OnNumberOfTracksChanged += new AVTransportLastChange.VariableChangeHandler(NumberOfTracksChangedSink); AV_LastChange.OnTrackURIChanged += new AVTransportLastChange.VariableChangeHandler(TrackURIChangedSink); AV_LastChange.OnCurrentURIMetaDataChanged += new AVTransportLastChange.VariableChangeHandler(URIMetaDataChangedSink); AV_LastChange.OnCurrentPlayModeChanged += new AVTransportLastChange.VariableChangeHandler(CurrentPlayModeChangedSink); AV_LastChange.OnTransportStatusChanged += new AVTransportLastChange.VariableChangeHandler(TransportStatusChangedSink); } if(RenderingControl.HasStateVariable_LastChange) { // Hook up to the LastChange event of RenderingControl ++this.StateCounter; RC_LastChange = new RenderingControlLastChange(RenderingControl,device.UniqueDeviceName, RCid, new RenderingControlLastChange.OnReadyHandler(RCLC)); RC_LastChange.OnMuteChanged += new RenderingControlLastChange.VariableChangeHandler(MuteSink); RC_LastChange.OnVolumeChanged += new RenderingControlLastChange.VariableChangeHandler(VolumeSink); } /* Get ProtocolInfo Value of current connection */ ++this.StateCounter; ConnectionManager.GetCurrentConnectionInfo(ConnectionID,this.GetHashCode(),new CpConnectionManager.Delegate_OnResult_GetCurrentConnectionInfo(InitialState_GetCurrentConnectionInfoSink)); } RenderingControl._subscribe(500); AVTransport._subscribe(500); } public PlayMode[] GetSupportedPlayModes() { // Returns all the PlayModes that the device is advertising it supports string[] RawModes = AVTransport.Values_CurrentPlayMode; ArrayList t = new ArrayList(); foreach(string s in RawModes) { t.Add(StringToPlayMode(s)); } return((PlayMode[])t.ToArray(typeof(PlayMode))); } /// <summary> /// This method converts a string value of a play mode /// into an enum type /// </summary> /// <param name="v"></param> /// <returns></returns> private PlayMode StringToPlayMode(string v) { PlayMode RetVal = PlayMode.NORMAL; switch(v) { case "DIRECT_1": RetVal = PlayMode.DIRECT_1; break; case "INTRO": RetVal = PlayMode.INTRO; break; case "NORMAL": RetVal = PlayMode.NORMAL; break; case "RANDOM": RetVal = PlayMode.RANDOM; break; case "REPEAT_ALL": RetVal = PlayMode.REPEAT_ALL; break; case "REPEAT_ONE": RetVal = PlayMode.REPEAT_ONE; break; case "SHUFFLE": RetVal = PlayMode.SHUFFLE; break; } return(RetVal); } /// <summary> /// This is called when AVTransportLastChange has acquired state /// </summary> /// <param name="sender"></param> private void AVTLC(AVTransportLastChange sender) { bool OK = false; lock(this) { --StateCounter; if(StateCounter==0) { this.UpdateCurrentItem(); OK = true; } } if(OK) if(OnReady!=null) OnReady(this, Tag); } /// <summary> /// This is called when RenderingControlLastChange has acquired state /// </summary> /// <param name="sender"></param> private void RCLC(RenderingControlLastChange sender) { bool OK = false; lock(this) { --StateCounter; if(StateCounter==0) { this.UpdateCurrentItem(); OK = true; } } if(OK) if(OnReady!=null) OnReady(this, Tag); } private void CurrentPlayModeChangedSink(AVTransportLastChange sender) { if(this.OnCurrentPlayModeChanged!=null) { OnCurrentPlayModeChanged(this,CurrentPlayMode); } } protected void URIMetaDataChangedSink(AVTransportLastChange sender) { if(sender.CurrentURIMetaData!="" && sender.CurrentURIMetaData!="NOT_IMPLEMENTED") { ArrayList a = MediaBuilder.BuildMediaBranches(sender.CurrentURIMetaData); if(a.Count>0) { // Since new metadata was evented, we need to update the container, and then // update the current item _Container = (IMediaContainer)a[0]; UpdateCurrentItem(); } } } protected void TrackChangedSink(AVTransportLastChange sender) { if(this.OnTrackChanged!=null) OnTrackChanged(this,sender.CurrentTrack); } protected void NumberOfTracksChangedSink(AVTransportLastChange sender) { if(this.OnNumberOfTracksChanged!=null) OnNumberOfTracksChanged(this,sender.NumberOfTracks); } /// <summary> /// Based on the MetaData that was evented, and the current track uri, this method /// will determine what is currently playing, and reflect it in the CurrentItem property /// </summary> /// <returns></returns> protected bool UpdateCurrentItem() { bool RetVal = false; this._CurrentItem = null; if(this.Container!=null) { foreach(IMediaItem Item in this.Container.Items) { foreach(IMediaResource R in Item.MergedResources) { if(R.ContentUri==this.TrackURI) { _CurrentItem = (IMediaItem)R.Owner; RetVal = true; break; } } } } if(RetVal) { if(this.OnCurrentMetaDataChanged!=null) OnCurrentMetaDataChanged(this); } return(RetVal); } protected void TrackURIChangedSink(AVTransportLastChange sender) { UpdateCurrentItem(); if(this.OnTrackURIChanged!=null) OnTrackURIChanged(this); } public string TrackURI { get { return(AV_LastChange.TrackURI); } } /// <summary> /// bool indicating if the renderer implements seek /// </summary> public bool SupportsSeek { get { return(AVTransport.HasAction_Seek); } } /// <summary> /// bool indicating if the renderer implements pause /// </summary> public bool SupportsPause { get { return(AVTransport.HasAction_Pause); } } /// <summary> /// bool indicating if the renderer implements record /// </summary> public bool SupportsRecord { get { return(AVTransport.HasAction_Record); } } /// <summary> /// bool indicating if the renderer implements current position /// </summary> public bool SupportsCurrentPosition { get { return(AVTransport.HasStateVariable_RelativeTimePosition); } } /// <summary> /// The current track /// </summary> public UInt32 CurrentTrack { get { if(AV_LastChange==null) return(0); return(AV_LastChange.CurrentTrack); } } /// <summary> /// The total number of tracks /// </summary> public UInt32 NumberOfTracks { get { if(AV_LastChange==null) return(0); return(AV_LastChange.NumberOfTracks); } } /// <summary> /// The duration of the current track /// </summary> public TimeSpan Duration { get { if(AV_LastChange==null) return(TimeSpan.FromTicks(0)); return(AV_LastChange.CurrentDuration); } } /// <summary> /// The current relative time position /// </summary> public TimeSpan CurrentPosition { get { if(AV_LastChange==null) return(TimeSpan.FromTicks(0)); return(AV_LastChange.CurrentPosition); } } /// <summary> /// The current IMediaResource /// </summary> public IMediaResource MediaResource { get { return(_resource); } set { _resource = value; //this.SetAVTransportURI(_resource.ContentUri); } } protected void TransportStatusChangedSink(AVTransportLastChange sender) { this.OnTransportStatusChangedEvent.Fire(this,TransportStatus); } /// <summary> /// This is called when AVTransportLastChange receives an event that this has changed /// </summary> /// <param name="sender"></param> protected void AVTransportURISink(AVTransportLastChange sender) { this.MediaResource = ResourceBuilder.CreateResource(sender.AVTransportURI,""); OnCurrentURIChangedEvent.Fire(this); ConnectionManager.GetCurrentConnectionInfo(this.ConnectionID,null,new CpConnectionManager.Delegate_OnResult_GetCurrentConnectionInfo(ConnectionInfoSink)); } /// <summary> /// This is called when GetCurrentConnectionInfo completes. /// </summary> /// <param name="sender"></param> /// <param name="ConnectionID"></param> /// <param name="RcsID"></param> /// <param name="AVTransportID"></param> /// <param name="ProtocolInfo"></param> /// <param name="PeerConnectionManager"></param> /// <param name="PeerConnectionID"></param> /// <param name="Direction"></param> /// <param name="Status"></param> /// <param name="e"></param> /// <param name="Tag"></param> protected void ConnectionInfoSink(CpConnectionManager sender, System.Int32 ConnectionID, System.Int32 RcsID, System.Int32 AVTransportID, System.String ProtocolInfo, System.String PeerConnectionManager, System.Int32 PeerConnectionID, CpConnectionManager.Enum_A_ARG_TYPE_Direction Direction, CpConnectionManager.Enum_A_ARG_TYPE_ConnectionStatus Status, UPnPInvokeException e, object Tag) { if(e!=null) return; MediaResource = ResourceBuilder.CreateResource(MediaResource.ContentUri,ProtocolInfo); if(OnMediaResourceChanged!=null) OnMediaResourceChanged(this,MediaResource); } protected void InitialState_GetCurrentConnectionInfoSink(CpConnectionManager sender, System.Int32 ConnectionID, System.Int32 RcsID, System.Int32 AVTransportID, System.String ProtocolInfo, System.String PeerConnectionManager, System.Int32 PeerConnectionID, CpConnectionManager.Enum_A_ARG_TYPE_Direction Direction, CpConnectionManager.Enum_A_ARG_TYPE_ConnectionStatus Status, UPnPInvokeException e, object __tag) { this.ProtocolInfoString = ProtocolInfo; bool OK = false; lock(this) { --StateCounter; if(StateCounter==0) { this.UpdateCurrentItem(); OK = true; } } if(OK) if(OnReady!=null) OnReady(this, Tag); } protected void PositionSink(AVTransportLastChange sender) { if(OnPositionChanged!=null) OnPositionChanged(this,sender.CurrentPosition); } protected void VolumeSink(RenderingControlLastChange sender) { double VolP = ((double)sender.GetVolume("Master")-(double)MinVolume)/(double)(MaxVolume-MinVolume); UInt16 NewVolume = (UInt16)(VolP*(double)100); if(OnVolume!=null) OnVolume(this,NewVolume); } protected void MuteSink(RenderingControlLastChange sender) { if(OnMute!=null) OnMute(this, sender.Mute); } protected void PlayStateSink(AVTransportLastChange sender) { PlayState state = PlayState.STOPPED; switch(sender.PlayState) { case CpAVTransport.Enum_TransportState.PLAYING: state = AVConnection.PlayState.PLAYING; break; case CpAVTransport.Enum_TransportState.PAUSED_PLAYBACK: state = AVConnection.PlayState.PAUSED; break; case CpAVTransport.Enum_TransportState.PAUSED_RECORDING: state = AVConnection.PlayState.PAUSED; break; case CpAVTransport.Enum_TransportState.STOPPED: state = AVConnection.PlayState.STOPPED; break; case CpAVTransport.Enum_TransportState.TRANSITIONING: state = AVConnection.PlayState.TRANSITIONING; break; case CpAVTransport.Enum_TransportState.RECORDING: state = AVConnection.PlayState.RECORDING; break; } OnPlayStateChangedEvent.Fire(this, state); } /// <summary> /// Play the current resource /// </summary> public void Play() { AVTransport.Play((UInt32)AVTid,CpAVTransport.Enum_TransportPlaySpeed._1); } /// <summary> /// Record the current resource /// </summary> public void Record() { AVTransport.Record((UInt32)AVTid); } /// <summary> /// Seek to the given relative time position /// </summary> /// <param name="TrackPosition">Time Position to seek to</param> public void SeekPosition(TimeSpan TrackPosition) { if(AVTransport.HasAction_Seek) { if(TrackPosition.TotalSeconds <0) TrackPosition = new TimeSpan(0,0,0,0); string Target = string.Format("{0:00}",TrackPosition.Hours) + ":" + string.Format("{0:00}",TrackPosition.Minutes) + ":" + string.Format("{0:00}",TrackPosition.Seconds); AVTransport.Seek((UInt32)AVTid,CpAVTransport.Enum_A_ARG_TYPE_SeekMode.REL_TIME,Target); } } /// <summary> /// Seek to the given track number /// </summary> /// <param name="TrackNumber">The track number to seek to</param> public void SeekTrack(int TrackNumber) { if(AVTransport.HasAction_Seek) { AVTransport.Seek((UInt32)AVTid,CpAVTransport.Enum_A_ARG_TYPE_SeekMode.TRACK_NR,TrackNumber.ToString()); } } /// <summary> /// stop the current resource /// </summary> public void Stop() { AVTransport.Stop((UInt32)AVTid); } /// <summary> /// paues the current resource /// </summary> public void Pause() { if(AVTransport.HasAction_Pause) { AVTransport.Pause((UInt32)AVTid); } } /// <summary> /// Toggle the current mute state /// </summary> public void ToggleMute() { RenderingControl.SetMute((UInt32)RCid,CpRenderingControl.Enum_A_ARG_TYPE_Channel.MASTER,!RC_LastChange.Mute); } /// <summary> /// Set the mute state, to the given state /// </summary> /// <param name="MuteState">Desired Mute state</param> public void Mute(bool MuteState) { RenderingControl.SetMute((UInt32)RCid,CpRenderingControl.Enum_A_ARG_TYPE_Channel.MASTER,MuteState); } public void Mute(bool MuteState, string channel) { RenderingControl.SetUnspecifiedValue("Enum_A_ARG_TYPE_Channel",channel); RenderingControl.SetMute((UInt32)RCid,CpRenderingControl.Enum_A_ARG_TYPE_Channel._UNSPECIFIED_,MuteState); } public bool GetMute(string channel) { return(RC_LastChange.GetMute(channel)); } /// <summary> /// An array of strings representing the implemented channels /// </summary> public string[] SupportedChannels { get { return(RenderingControl.Values_A_ARG_TYPE_Channel); } } /// <summary> /// Get the current volume for the specified channel /// <para> /// The volume level is abstracted to an integer representing the volume as a percentage from 0 to 100 /// </para> /// </summary> /// <param name="channel">Select Channel</param> /// <returns>Current Volume</returns> public UInt16 GetVolume(string channel) { UInt16 _Vol = RC_LastChange.GetVolume(channel); double VolP = ((double)_Vol-(double)MinVolume)/(double)(MaxVolume-MinVolume); UInt16 NewVolume = (UInt16)(VolP*(double)100); return(NewVolume); } /// <summary> /// Set the volume for the specified channel /// <para> /// The volume level is abstracted to an integer from 0 to 100 representing the percentage of maximum volume. /// </para> /// </summary> /// <param name="channel">DesiredChannel</param> /// <param name="DesiredVolume">Volume Level</param> public void SetVolume(string channel, UInt16 DesiredVolume) { double p = ((double)DesiredVolume)/((double)100); UInt16 R = (UInt16)(((double)(MaxVolume-MinVolume))*p); UInt16 NewVolume = (UInt16)((int)R + (int)MinVolume); RenderingControl.SetUnspecifiedValue("Enum_A_ARG_TYPE_Channel",channel); RenderingControl.SetVolume((UInt32)RCid,CpRenderingControl.Enum_A_ARG_TYPE_Channel._UNSPECIFIED_,NewVolume); } /// <summary> /// Change the PlayMode on the device /// </summary> /// <param name="NewMode">Desired Mode</param> public void SetPlayMode(PlayMode NewMode) { CpAVTransport.Enum_CurrentPlayMode RetVal = CpAVTransport.Enum_CurrentPlayMode._UNSPECIFIED_; AVTransport.SetUnspecifiedValue("Enum_CurrentPlayMode",NewMode.ToString()); AVTransport.SetPlayMode((UInt32)this.AVTid,RetVal); } /// <summary> /// Get/Set the MasterVolume level /// <para> /// The volume level is abstracted to an integer from 0 to 100 /// </para> /// </summary> public UInt16 MasterVolume { get { UInt16 _Vol = RC_LastChange.GetVolume("Master"); double VolP = ((double)_Vol - (double)MinVolume)/(double)(MaxVolume-MinVolume); UInt16 NewVolume = (UInt16)(VolP*(double)100); return(NewVolume); } set { double p = ((double)value)/((double)100); UInt16 R = (UInt16)(((double)(MaxVolume-MinVolume))*p); UInt16 NewVolume = (UInt16)((int)R + (int)MinVolume); RenderingControl.SetVolume((UInt32)RCid,CpRenderingControl.Enum_A_ARG_TYPE_Channel.MASTER,NewVolume); } } /// <summary> /// Skip to the next track /// </summary> public void NextTrack() { AVTransport.Next((UInt32)AVTid); } /// <summary> /// Skip to the previous track /// </summary> public void PreviousTrack() { AVTransport.Previous((UInt32)AVTid); } internal void SetAVTransportURI(string NewUri, string MetaData) { SetAVTransportURI(NewUri,MetaData, null, null); } internal void SetAVTransportURI(string NewUri, string MetaData, object Tag, CpAVTransport.Delegate_OnResult_SetAVTransportURI Callback) { AVTransport.SetAVTransportURI((UInt32)AVTid,NewUri,MetaData,Tag, Callback); //AVTransport.Sync_SetAVTransportURI((UInt32)AVTid, NewUri); } protected void SetAVTransportURISink(CpAVTransport sender, System.UInt32 InstanceID, System.String CurrentURI, System.String CurrentURIMetaData, UPnPInvokeException e, object Tag) { if(e!=null) return; OnSetAVTransportURIEvent.Fire(this,Tag); } /// <summary> /// bool indicating the current mute state /// </summary> public bool IsMute { get { return(RC_LastChange.Mute); } } public string TransportStatus { get { return(AV_LastChange.TransportStatus); } } /// <summary> /// Property returns the currnet playmode on the device /// </summary> public AVConnection.PlayMode CurrentPlayMode { get { PlayMode RetVal = PlayMode.NORMAL; if(AV_LastChange==null) return(RetVal); switch(AV_LastChange.CurrentPlayMode) { case CpAVTransport.Enum_CurrentPlayMode.DIRECT_1: RetVal = PlayMode.DIRECT_1; break; case CpAVTransport.Enum_CurrentPlayMode.INTRO: RetVal = PlayMode.INTRO; break; case CpAVTransport.Enum_CurrentPlayMode.NORMAL: RetVal = PlayMode.NORMAL; break; case CpAVTransport.Enum_CurrentPlayMode.RANDOM: RetVal = PlayMode.RANDOM; break; case CpAVTransport.Enum_CurrentPlayMode.REPEAT_ALL: RetVal = PlayMode.REPEAT_ALL; break; case CpAVTransport.Enum_CurrentPlayMode.REPEAT_ONE: RetVal = PlayMode.REPEAT_ONE; break; case CpAVTransport.Enum_CurrentPlayMode.SHUFFLE: RetVal = PlayMode.SHUFFLE; break; } return(RetVal); } } /// <summary> /// This method is called by the AVRenderer object, from a single thread, that is /// used to poll AVTransport for position information. /// </summary> internal void _Poll() { this.AV_LastChange._Poll(); } /// <summary> /// The current PlayState /// </summary> public AVConnection.PlayState CurrentState { get { PlayState RetVal = 0; if(AV_LastChange==null) return(PlayState.STOPPED); switch(AV_LastChange.PlayState) { case CpAVTransport.Enum_TransportState.STOPPED: RetVal = PlayState.STOPPED; break; case CpAVTransport.Enum_TransportState.PLAYING: RetVal = PlayState.PLAYING; break; case CpAVTransport.Enum_TransportState.PAUSED_PLAYBACK: RetVal = PlayState.PAUSED; break; case CpAVTransport.Enum_TransportState.PAUSED_RECORDING: RetVal = PlayState.PAUSED; break; case CpAVTransport.Enum_TransportState.RECORDING: RetVal = PlayState.RECORDING; break; case CpAVTransport.Enum_TransportState.TRANSITIONING: RetVal = PlayState.TRANSITIONING; break; } return(RetVal); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using Xunit; namespace System.Linq.Tests { public class FirstTests : EnumerableTests { [Fact] public void SameResultsRepeatCallsIntQuery() { var q = from x in new[] { 9999, 0, 888, -1, 66, -777, 1, 2, -12345 } where x > int.MinValue select x; Assert.Equal(q.First(), q.First()); } [Fact] public void SameResultsRepeatCallsStringQuery() { var q = from x in new[] { "!@#$%^", "C", "AAA", "", "Calling Twice", "SoS", string.Empty } where !string.IsNullOrEmpty(x) select x; Assert.Equal(q.First(), q.First()); } public void TestEmptyIList<T>() { T[] source = { }; Assert.NotNull(source as IList<T>); Assert.Throws<InvalidOperationException>(() => source.RunOnce().First()); } [Fact] public void EmptyIListT() { TestEmptyIList<int>(); TestEmptyIList<string>(); TestEmptyIList<DateTime>(); TestEmptyIList<FirstTests>(); } [Fact] public void IListTOneElement() { int[] source = { 5 }; int expected = 5; Assert.NotNull(source as IList<int>); Assert.Equal(expected, source.First()); } [Fact] public void IListTManyElementsFirstIsDefault() { int?[] source = { null, -10, 2, 4, 3, 0, 2 }; int? expected = null; Assert.IsAssignableFrom<IList<int?>>(source); Assert.Equal(expected, source.First()); } [Fact] public void IListTManyElementsFirstIsNotDefault() { int?[] source = { 19, null, -10, 2, 4, 3, 0, 2 }; int? expected = 19; Assert.IsAssignableFrom<IList<int?>>(source); Assert.Equal(expected, source.First()); } private static IEnumerable<T> EmptySource<T>() { yield break; } private static void TestEmptyNotIList<T>() { var source = EmptySource<T>(); Assert.Null(source as IList<T>); Assert.Throws<InvalidOperationException>(() => source.RunOnce().First()); } [Fact] public void EmptyNotIListT() { TestEmptyNotIList<int>(); TestEmptyNotIList<string>(); TestEmptyNotIList<DateTime>(); TestEmptyNotIList<FirstTests>(); } [Fact] public void OneElementNotIListT() { IEnumerable<int> source = NumberRangeGuaranteedNotCollectionType(-5, 1); int expected = -5; Assert.Null(source as IList<int>); Assert.Equal(expected, source.First()); } [Fact] public void ManyElementsNotIListT() { IEnumerable<int> source = NumberRangeGuaranteedNotCollectionType(3, 10); int expected = 3; Assert.Null(source as IList<int>); Assert.Equal(expected, source.First()); } [Fact] public void EmptySource() { int[] source = { }; Assert.Throws<InvalidOperationException>(() => source.First(x => true)); Assert.Throws<InvalidOperationException>(() => source.First(x => false)); } [Fact] public void OneElementTruePredicate() { int[] source = { 4 }; Func<int, bool> predicate = IsEven; int expected = 4; Assert.Equal(expected, source.First(predicate)); } [Fact] public void ManyElementsPredicateFalseForAll() { int[] source = { 9, 5, 1, 3, 17, 21 }; Func<int, bool> predicate = IsEven; Assert.Throws<InvalidOperationException>(() => source.First(predicate)); } [Fact] public void PredicateTrueOnlyForLast() { int[] source = { 9, 5, 1, 3, 17, 21, 50 }; Func<int, bool> predicate = IsEven; int expected = 50; Assert.Equal(expected, source.First(predicate)); } [Fact] public void PredicateTrueForSome() { int[] source = { 3, 7, 10, 7, 9, 2, 11, 17, 13, 8 }; Func<int, bool> predicate = IsEven; int expected = 10; Assert.Equal(expected, source.First(predicate)); } [Fact] public void PredicateTrueForSomeRunOnce() { int[] source = { 3, 7, 10, 7, 9, 2, 11, 17, 13, 8 }; Func<int, bool> predicate = IsEven; int expected = 10; Assert.Equal(expected, source.RunOnce().First(predicate)); } [Fact] public void NullSource() { AssertExtensions.Throws<ArgumentNullException>("source", () => ((IEnumerable<int>)null).First()); } [Fact] public void NullSourcePredicateUsed() { AssertExtensions.Throws<ArgumentNullException>("source", () => ((IEnumerable<int>)null).First(i => i != 2)); } [Fact] public void NullPredicate() { Func<int, bool> predicate = null; AssertExtensions.Throws<ArgumentNullException>("predicate", () => Enumerable.Range(0, 3).First(predicate)); } } }
using Aspose.Email.Live.Demos.UI.FileProcessing; using Aspose.Email.Live.Demos.UI.LibraryHelpers; using Aspose.Email.Live.Demos.UI.Models; using Aspose.Email; using Aspose.Email.Mapi; using System; using System.IO; using System.Linq; using System.Threading.Tasks; using System.Web.Http; using File = System.IO.File; namespace Aspose.Email.Live.Demos.UI.Controllers { ///<Summary> /// AsposeEmailSignatureController class to sign email file ///</Summary> public class AsposeEmailSignatureController : EmailBase { private const int ImageHeight = 100; ///<Summary> /// initialize AsposeEmailSignatureController class ///</Summary> public AsposeEmailSignatureController() { Aspose.Email.Live.Demos.UI.Models.License.SetAsposeEmailLicense(); } ///<Summary> /// Sign documents ///</Summary> [MimeMultipart] [HttpPost] [AcceptVerbs("GET", "POST")] public async Task<Response> Sign(string outputType, string signatureType) { (string folder, string[] files) = (null, null); try { (folder, files) = await UploadFiles(); var image = ReadAndRemoveAsText(ref files, folder, "image"); var text = ReadAndRemoveAsText(ref files, folder, "text"); var textColor = ReadAndRemoveAsText(ref files, folder, "textColor"); if (image == null && text == null) image = Convert.ToBase64String(ReadAndRemoveAsBytes(ref files, folder, files.Last())); var processor = new CustomSingleOrZipFileProcessor() { CustomFilesProcessMethod = (string[] inputFilePaths, string outputFolderPath) => { for (int i = 0; i < inputFilePaths.Length; i++) { var inputFilePath = inputFilePaths[i]; var mail = MapiHelper.GetMapiMessageFromFile(inputFilePath); if (mail == null) throw new Exception("Invalid file format"); switch (signatureType) { case "image": case "drawing": mail = AddDrawing(mail, image); break; case "text": mail = AddText(mail, text, textColor); break; default: throw new Exception("Unknown signature type."); } if (outputType.Equals("MSG", StringComparison.OrdinalIgnoreCase)) mail.Save(Path.Combine(outputFolderPath, Path.GetFileNameWithoutExtension(inputFilePath) + " Signed.msg")); else mail.Save(Path.Combine(outputFolderPath, Path.GetFileNameWithoutExtension(inputFilePath) + " Signed.eml"), new EmlSaveOptions(MailMessageSaveType.EmlFormat)); } } }; return processor.Process(folder, files); } catch (Exception ex) { Console.WriteLine(ex.Message); return new Response() { Status = "200", Text = "Error on processing file" }; } } ///<Summary> /// Sign method to sign email file ///</Summary> public Task<Response> Sign(string inputFileName, string inputFolderName, string outputType, string signatureType, dynamic signatureObject) { var processor = new CustomSingleOrZipFileProcessor() { CustomFileProcessMethod= (string inputFilePath, string outputFolderPath) => { var mail = MapiHelper.GetMapiMessageFromFile(inputFilePath); if (mail == null) throw new Exception("Invalid file format"); switch (signatureType) { case "drawing": mail = AddDrawing(mail, (string)signatureObject["DrawingImage"]); break; case "text": mail = AddText(mail, (string)signatureObject["Text"], (string)signatureObject["TextColor"]); break; case "image": mail = AddImage(mail, (string)signatureObject["ImageFolder"], (string)signatureObject["ImageFile"]); break; default: throw new Exception("Unknown signature type."); } if (outputType.Equals("MSG", StringComparison.OrdinalIgnoreCase)) mail.Save(Path.Combine(outputFolderPath, Path.GetFileNameWithoutExtension(inputFilePath) + " Signed.msg")); else mail.Save(Path.Combine(outputFolderPath, Path.GetFileNameWithoutExtension(inputFilePath) + " Signed.eml"), new EmlSaveOptions(MailMessageSaveType.EmlFormat)); } }; return Task.FromResult(processor.Process(inputFolderName, inputFileName)); } private MapiMessage AddDrawing(MapiMessage mail, string imageBase64) { var htmlDocument = new Aspose.Html.HTMLDocument(mail.BodyHtml, ""); var element = htmlDocument.CreateElement("Signature"); element.InnerHTML = "<img Src=\"data: image / png; base64, " + imageBase64 + "\" />"; htmlDocument.Body.AppendChild(element); var folderPath = Path.Combine(Config.Configuration.OutputDirectory, Guid.NewGuid().ToString()); var filePath = Path.Combine(folderPath, "Merged.html"); htmlDocument.Save(filePath); var content = System.IO.File.ReadAllText(filePath); System.IO.File.Delete(filePath); Directory.Delete(folderPath); mail.SetBodyContent(content, BodyContentType.Html); return mail; } private MapiMessage AddText(MapiMessage mail, string text, string textColor) { var htmlDocument = new Aspose.Html.HTMLDocument(mail.BodyHtml, ""); var element = htmlDocument.CreateElement("Signature"); element.InnerHTML = "<p style = \"color:"+ textColor + "\";>" + text + "</p>"; htmlDocument.Body.AppendChild(element); var folderPath = Path.Combine(Config.Configuration.OutputDirectory, Guid.NewGuid().ToString()); var filePath = Path.Combine(folderPath, "Merged.html"); htmlDocument.Save(filePath); var content = System.IO.File.ReadAllText(filePath); System.IO.File.Delete(filePath); Directory.Delete(folderPath); mail.SetBodyContent(content, BodyContentType.Html); return mail; } private MapiMessage AddImage(MapiMessage mail, string imageFoler, string imageFile) { var imageBase64 = Convert.ToBase64String(System.IO.File.ReadAllBytes(Path.Combine(Config.Configuration.WorkingDirectory, imageFoler, imageFile))); var htmlDocument = new Aspose.Html.HTMLDocument(mail.BodyHtml, ""); var element = htmlDocument.CreateElement("Signature"); element.InnerHTML = "<img Src=\"data: image / png; base64, " + imageBase64 + "\" />"; htmlDocument.Body.AppendChild(element); var folderPath = Path.Combine(Config.Configuration.OutputDirectory, Guid.NewGuid().ToString()); var filePath = Path.Combine(folderPath, "Merged.html"); htmlDocument.Save(filePath); var content = System.IO.File.ReadAllText(filePath); System.IO.File.Delete(filePath); Directory.Delete(folderPath); mail.SetBodyContent(content, BodyContentType.Html); return mail; } } }
// **************************************************************** // This is free software licensed under the NUnit license. You // may obtain a copy of the license as well as information regarding // copyright ownership at http://nunit.org. // **************************************************************** using System; using NUnit.Framework; using NUnit.Framework.Internal; namespace NUnit.Tests { namespace Assemblies { /// <summary> /// Constant definitions for the mock-assembly dll. /// </summary> public class MockAssembly { public static int Classes = 9; public static int NamespaceSuites = 6; // assembly, NUnit, Tests, Assemblies, Singletons, TestAssembly public static int Tests = MockTestFixture.Tests + Singletons.OneTestCase.Tests + TestAssembly.MockTestFixture.Tests + IgnoredFixture.Tests + ExplicitFixture.Tests + BadFixture.Tests + FixtureWithTestCases.Tests + ParameterizedFixture.Tests + GenericFixtureConstants.Tests; public static int Suites = MockTestFixture.Suites + Singletons.OneTestCase.Suites + TestAssembly.MockTestFixture.Suites + IgnoredFixture.Suites + ExplicitFixture.Suites + BadFixture.Suites + FixtureWithTestCases.Suites + ParameterizedFixture.Suites + GenericFixtureConstants.Suites + NamespaceSuites; public static readonly int Nodes = Tests + Suites; public static int ExplicitFixtures = 1; public static int SuitesRun = Suites - ExplicitFixtures; public static int Ignored = MockTestFixture.Ignored + IgnoredFixture.Tests; public static int Explicit = MockTestFixture.Explicit + ExplicitFixture.Tests; public static int NotRunnable = MockTestFixture.NotRunnable + BadFixture.Tests; public static int NotRun = Ignored + Explicit + NotRunnable; public static int TestsRun = Tests - NotRun; public static int ResultCount = Tests - Explicit; public static int Errors = MockTestFixture.Errors; public static int Failures = MockTestFixture.Failures; public static int ErrorsAndFailures = Errors + Failures; public static int Categories = MockTestFixture.Categories; #if !NETCF public static string AssemblyPath = AssemblyHelper.GetAssemblyPath(typeof(MockAssembly).Assembly); #endif } //public class MockSuite //{ // [Suite] // public static TestSuite Suite // { // get // { // return new TestSuite( "MockSuite" ); // } // } //} [TestFixture(Description="Fake Test Fixture")] [Category("FixtureCategory")] public class MockTestFixture { public const int Tests = 11; public const int Suites = 1; public const int Ignored = 1; public const int Explicit = 1; public const int NotRunnable = 2; public const int NotRun = Ignored + Explicit + NotRunnable; public const int TestsRun = Tests - NotRun; public const int ResultCount = Tests - Explicit; public const int Failures = 1; public const int Errors = 1; public const int ErrorsAndFailures = Errors + Failures; public const int Inconclusive = 1; public const int Categories = 5; public const int MockCategoryTests = 2; [Test(Description="Mock Test #1")] public void MockTest1() {} [Test] [Category("MockCategory")] [Property("Severity","Critical")] [Description("This is a really, really, really, really, really, really, really, really, really, really, really, really, really, really, really, really, really, really, really, really, really, really, really, really, really long description")] public void MockTest2() {} [Test] [Category("MockCategory")] [Category("AnotherCategory")] public void MockTest3() { Assert.Pass("Succeeded!"); } [Test] protected static void MockTest5() {} [Test] public void FailingTest() { Assert.Fail("Intentional failure"); } [Test, Property("TargetMethod", "SomeClassName"), Property("Size", 5), /*Property("TargetType", typeof( System.Threading.Thread ))*/] public void TestWithManyProperties() {} [Test] [Ignore("ignoring this test method for now")] [Category("Foo")] public void MockTest4() {} [Test, Explicit] [Category( "Special" )] public void ExplicitlyRunTest() {} [Test] public void NotRunnableTest( int a, int b) { } [Test] public void InconclusiveTest() { Assert.Inconclusive("No valid data"); } [Test] public void TestWithException() { MethodThrowsException(); } private void MethodThrowsException() { throw new Exception("Intentional Exception"); } } } namespace Singletons { [TestFixture] public class OneTestCase { public static readonly int Tests = 1; public static readonly int Suites = 1; [Test] public virtual void TestCase() {} } } namespace TestAssembly { [TestFixture] public class MockTestFixture { public static readonly int Tests = 1; public static readonly int Suites = 1; [Test] public void MyTest() { } } } [TestFixture, Ignore] public class IgnoredFixture { public static readonly int Tests = 3; public static readonly int Suites = 1; [Test] public void Test1() { } [Test] public void Test2() { } [Test] public void Test3() { } } [TestFixture,Explicit] public class ExplicitFixture { public static readonly int Tests = 2; public static readonly int Suites = 1; public static readonly int Nodes = Tests + Suites; [Test] public void Test1() { } [Test] public void Test2() { } } [TestFixture] public class BadFixture { public static readonly int Tests = 1; public static readonly int Suites = 1; public BadFixture(int val) { } [Test] public void SomeTest() { } } [TestFixture] public class FixtureWithTestCases { public static readonly int Tests = 4; public static readonly int Suites = 3; [TestCase(2, 2, ExpectedResult=4)] [TestCase(9, 11, ExpectedResult=20)] public int MethodWithParameters(int x, int y) { return x+y; } #if CLR_2_0 || CLR_4_0 [TestCase(2, 4)] [TestCase(9.2, 11.7)] public void GenericMethod<T>(T x, T y) { } #endif } [TestFixture(5)] [TestFixture(42)] public class ParameterizedFixture { public static readonly int Tests = 4; public static readonly int Suites = 3; public ParameterizedFixture(int num) { } [Test] public void Test1() { } [Test] public void Test2() { } } public class GenericFixtureConstants { #if CLR_2_0 || CLR_4_0 public static readonly int Tests = 4; public static readonly int Suites = 3; #else public static readonly int Tests = 0; public static readonly int Suites = 0; #endif } #if CLR_2_0 || CLR_4_0 [TestFixture(5)] [TestFixture(11.5)] public class GenericFixture<T> { public GenericFixture(T num){ } [Test] public void Test1() { } [Test] public void Test2() { } } #endif }
// <copyright file="Ilutp.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-2010 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.Collections.Generic; using MathNet.Numerics.LinearAlgebra.Solvers; using MathNet.Numerics.Properties; namespace MathNet.Numerics.LinearAlgebra.Complex.Solvers { #if NOSYSNUMERICS using Complex = Numerics.Complex; #else using Complex = System.Numerics.Complex; #endif /// <summary> /// This class performs an Incomplete LU factorization with drop tolerance /// and partial pivoting. The drop tolerance indicates which additional entries /// will be dropped from the factorized LU matrices. /// </summary> /// <remarks> /// The ILUTP-Mem algorithm was taken from: <br/> /// ILUTP_Mem: a Space-Efficient Incomplete LU Preconditioner /// <br/> /// Tzu-Yi Chen, Department of Mathematics and Computer Science, <br/> /// Pomona College, Claremont CA 91711, USA <br/> /// Published in: <br/> /// Lecture Notes in Computer Science <br/> /// Volume 3046 / 2004 <br/> /// pp. 20 - 28 <br/> /// Algorithm is described in Section 2, page 22 /// </remarks> public sealed class ILUTPPreconditioner : IPreconditioner<Complex> { /// <summary> /// The default fill level. /// </summary> public const double DefaultFillLevel = 200.0; /// <summary> /// The default drop tolerance. /// </summary> public const double DefaultDropTolerance = 0.0001; /// <summary> /// The decomposed upper triangular matrix. /// </summary> SparseMatrix _upper; /// <summary> /// The decomposed lower triangular matrix. /// </summary> SparseMatrix _lower; /// <summary> /// The array containing the pivot values. /// </summary> int[] _pivots; /// <summary> /// The fill level. /// </summary> double _fillLevel = DefaultFillLevel; /// <summary> /// The drop tolerance. /// </summary> double _dropTolerance = DefaultDropTolerance; /// <summary> /// The pivot tolerance. /// </summary> double _pivotTolerance; /// <summary> /// Initializes a new instance of the <see cref="ILUTPPreconditioner"/> class with the default settings. /// </summary> public ILUTPPreconditioner() { } /// <summary> /// Initializes a new instance of the <see cref="ILUTPPreconditioner"/> class with the specified settings. /// </summary> /// <param name="fillLevel"> /// The amount of fill that is allowed in the matrix. The value is a fraction of /// the number of non-zero entries in the original matrix. Values should be positive. /// </param> /// <param name="dropTolerance"> /// The absolute drop tolerance which indicates below what absolute value an entry /// will be dropped from the matrix. A drop tolerance of 0.0 means that no values /// will be dropped. Values should always be positive. /// </param> /// <param name="pivotTolerance"> /// The pivot tolerance which indicates at what level pivoting will take place. A /// value of 0.0 means that no pivoting will take place. /// </param> public ILUTPPreconditioner(double fillLevel, double dropTolerance, double pivotTolerance) { if (fillLevel < 0) { throw new ArgumentOutOfRangeException("fillLevel"); } if (dropTolerance < 0) { throw new ArgumentOutOfRangeException("dropTolerance"); } if (pivotTolerance < 0) { throw new ArgumentOutOfRangeException("pivotTolerance"); } _fillLevel = fillLevel; _dropTolerance = dropTolerance; _pivotTolerance = pivotTolerance; } /// <summary> /// Gets or sets the amount of fill that is allowed in the matrix. The /// value is a fraction of the number of non-zero entries in the original /// matrix. The standard value is 200. /// </summary> /// <remarks> /// <para> /// Values should always be positive and can be higher than 1.0. A value lower /// than 1.0 means that the eventual preconditioner matrix will have fewer /// non-zero entries as the original matrix. A value higher than 1.0 means that /// the eventual preconditioner can have more non-zero values than the original /// matrix. /// </para> /// <para> /// Note that any changes to the <b>FillLevel</b> after creating the preconditioner /// will invalidate the created preconditioner and will require a re-initialization of /// the preconditioner. /// </para> /// </remarks> /// <exception cref="ArgumentOutOfRangeException">Thrown if a negative value is provided.</exception> public double FillLevel { get { return _fillLevel; } set { if (value < 0) { throw new ArgumentOutOfRangeException("value"); } _fillLevel = value; } } /// <summary> /// Gets or sets the absolute drop tolerance which indicates below what absolute value /// an entry will be dropped from the matrix. The standard value is 0.0001. /// </summary> /// <remarks> /// <para> /// The values should always be positive and can be larger than 1.0. A low value will /// keep more small numbers in the preconditioner matrix. A high value will remove /// more small numbers from the preconditioner matrix. /// </para> /// <para> /// Note that any changes to the <b>DropTolerance</b> after creating the preconditioner /// will invalidate the created preconditioner and will require a re-initialization of /// the preconditioner. /// </para> /// </remarks> /// <exception cref="ArgumentOutOfRangeException">Thrown if a negative value is provided.</exception> public double DropTolerance { get { return _dropTolerance; } set { if (value < 0) { throw new ArgumentOutOfRangeException("value"); } _dropTolerance = value; } } /// <summary> /// Gets or sets the pivot tolerance which indicates at what level pivoting will /// take place. The standard value is 0.0 which means pivoting will never take place. /// </summary> /// <remarks> /// <para> /// The pivot tolerance is used to calculate if pivoting is necessary. Pivoting /// will take place if any of the values in a row is bigger than the /// diagonal value of that row divided by the pivot tolerance, i.e. pivoting /// will take place if <b>row(i,j) > row(i,i) / PivotTolerance</b> for /// any <b>j</b> that is not equal to <b>i</b>. /// </para> /// <para> /// Note that any changes to the <b>PivotTolerance</b> after creating the preconditioner /// will invalidate the created preconditioner and will require a re-initialization of /// the preconditioner. /// </para> /// </remarks> /// <exception cref="ArgumentOutOfRangeException">Thrown if a negative value is provided.</exception> public double PivotTolerance { get { return _pivotTolerance; } set { if (value < 0) { throw new ArgumentOutOfRangeException("value"); } _pivotTolerance = value; } } /// <summary> /// Returns the upper triagonal matrix that was created during the LU decomposition. /// </summary> /// <remarks> /// This method is used for debugging purposes only and should normally not be used. /// </remarks> /// <returns>A new matrix containing the upper triagonal elements.</returns> internal Matrix<Complex> UpperTriangle() { return _upper.Clone(); } /// <summary> /// Returns the lower triagonal matrix that was created during the LU decomposition. /// </summary> /// <remarks> /// This method is used for debugging purposes only and should normally not be used. /// </remarks> /// <returns>A new matrix containing the lower triagonal elements.</returns> internal Matrix<Complex> LowerTriangle() { return _lower.Clone(); } /// <summary> /// Returns the pivot array. This array is not needed for normal use because /// the preconditioner will return the solution vector values in the proper order. /// </summary> /// <remarks> /// This method is used for debugging purposes only and should normally not be used. /// </remarks> /// <returns>The pivot array.</returns> internal int[] Pivots() { var result = new int[_pivots.Length]; for (var i = 0; i < _pivots.Length; i++) { result[i] = _pivots[i]; } return result; } /// <summary> /// Initializes the preconditioner and loads the internal data structures. /// </summary> /// <param name="matrix"> /// The <see cref="Matrix"/> upon which this preconditioner is based. Note that the /// method takes a general matrix type. However internally the data is stored /// as a sparse matrix. Therefore it is not recommended to pass a dense matrix. /// </param> /// <exception cref="ArgumentNullException"> If <paramref name="matrix"/> is <see langword="null" />.</exception> /// <exception cref="ArgumentException">If <paramref name="matrix"/> is not a square matrix.</exception> public void Initialize(Matrix<Complex> matrix) { if (matrix == null) { throw new ArgumentNullException("matrix"); } if (matrix.RowCount != matrix.ColumnCount) { throw new ArgumentException(Resources.ArgumentMatrixSquare, "matrix"); } var sparseMatrix = matrix as SparseMatrix ?? SparseMatrix.OfMatrix(matrix); // The creation of the preconditioner follows the following algorithm. // spaceLeft = lfilNnz * nnz(A) // for i = 1, .. , n // { // w = a(i,*) // for j = 1, .. , i - 1 // { // if (w(j) != 0) // { // w(j) = w(j) / a(j,j) // if (w(j) < dropTol) // { // w(j) = 0; // } // if (w(j) != 0) // { // w = w - w(j) * U(j,*) // } // } // } // // for j = i, .. ,n // { // if w(j) <= dropTol * ||A(i,*)|| // { // w(j) = 0 // } // } // // spaceRow = spaceLeft / (n - i + 1) // Determine the space for this row // lfil = spaceRow / 2 // space for this row of L // l(i,j) = w(j) for j = 1, .. , i -1 // only the largest lfil elements // // lfil = spaceRow - nnz(L(i,:)) // space for this row of U // u(i,j) = w(j) for j = i, .. , n // only the largest lfil - 1 elements // w = 0 // // if max(U(i,i + 1: n)) > U(i,i) / pivTol then // pivot if necessary // { // pivot by swapping the max and the diagonal entries // Update L, U // Update P // } // spaceLeft = spaceLeft - nnz(L(i,:)) - nnz(U(i,:)) // } // Create the lower triangular matrix _lower = new SparseMatrix(sparseMatrix.RowCount); // Create the upper triangular matrix and copy the values _upper = new SparseMatrix(sparseMatrix.RowCount); // Create the pivot array _pivots = new int[sparseMatrix.RowCount]; for (var i = 0; i < _pivots.Length; i++) { _pivots[i] = i; } var workVector = new DenseVector(sparseMatrix.RowCount); var rowVector = new DenseVector(sparseMatrix.ColumnCount); var indexSorting = new int[sparseMatrix.RowCount]; // spaceLeft = lfilNnz * nnz(A) var spaceLeft = (int) _fillLevel*sparseMatrix.NonZerosCount; // for i = 1, .. , n for (var i = 0; i < sparseMatrix.RowCount; i++) { // w = a(i,*) sparseMatrix.Row(i, workVector); // pivot the row PivotRow(workVector); var vectorNorm = workVector.InfinityNorm(); // for j = 1, .. , i - 1) for (var j = 0; j < i; j++) { // if (w(j) != 0) // { // w(j) = w(j) / a(j,j) // if (w(j) < dropTol) // { // w(j) = 0; // } // if (w(j) != 0) // { // w = w - w(j) * U(j,*) // } if (workVector[j] != 0.0) { // Calculate the multiplication factors that go into the L matrix workVector[j] = workVector[j]/_upper[j, j]; if (workVector[j].Magnitude < _dropTolerance) { workVector[j] = 0.0; } // Calculate the addition factor if (workVector[j] != 0.0) { // vector update all in one go _upper.Row(j, rowVector); // zero out columnVector[k] because we don't need that // one anymore for k = 0 to k = j for (var k = 0; k <= j; k++) { rowVector[k] = 0.0; } rowVector.Multiply(workVector[j], rowVector); workVector.Subtract(rowVector, workVector); } } } // for j = i, .. ,n for (var j = i; j < sparseMatrix.RowCount; j++) { // if w(j) <= dropTol * ||A(i,*)|| // { // w(j) = 0 // } if (workVector[j].Magnitude <= _dropTolerance*vectorNorm) { workVector[j] = 0.0; } } // spaceRow = spaceLeft / (n - i + 1) // Determine the space for this row var spaceRow = spaceLeft/(sparseMatrix.RowCount - i + 1); // lfil = spaceRow / 2 // space for this row of L var fillLevel = spaceRow/2; FindLargestItems(0, i - 1, indexSorting, workVector); // l(i,j) = w(j) for j = 1, .. , i -1 // only the largest lfil elements var lowerNonZeroCount = 0; var count = 0; for (var j = 0; j < i; j++) { if ((count > fillLevel) || (indexSorting[j] == -1)) { break; } _lower[i, indexSorting[j]] = workVector[indexSorting[j]]; count += 1; lowerNonZeroCount += 1; } FindLargestItems(i + 1, sparseMatrix.RowCount - 1, indexSorting, workVector); // lfil = spaceRow - nnz(L(i,:)) // space for this row of U fillLevel = spaceRow - lowerNonZeroCount; // u(i,j) = w(j) for j = i + 1, .. , n // only the largest lfil - 1 elements var upperNonZeroCount = 0; count = 0; for (var j = 0; j < sparseMatrix.RowCount - i; j++) { if ((count > fillLevel - 1) || (indexSorting[j] == -1)) { break; } _upper[i, indexSorting[j]] = workVector[indexSorting[j]]; count += 1; upperNonZeroCount += 1; } // Simply copy the diagonal element. Next step is to see if we pivot _upper[i, i] = workVector[i]; // if max(U(i,i + 1: n)) > U(i,i) / pivTol then // pivot if necessary // { // pivot by swapping the max and the diagonal entries // Update L, U // Update P // } // Check if we really need to pivot. If (i+1) >=(mCoefficientMatrix.Rows -1) then // we are working on the last row. That means that there is only one number // And pivoting is useless. Also the indexSorting array will only contain // -1 values. if ((i + 1) < (sparseMatrix.RowCount - 1)) { if (workVector[i].Magnitude < _pivotTolerance*workVector[indexSorting[0]].Magnitude) { // swap columns of u (which holds the values of A in the // sections that haven't been partitioned yet. SwapColumns(_upper, i, indexSorting[0]); // Update P var temp = _pivots[i]; _pivots[i] = _pivots[indexSorting[0]]; _pivots[indexSorting[0]] = temp; } } // spaceLeft = spaceLeft - nnz(L(i,:)) - nnz(U(i,:)) spaceLeft -= lowerNonZeroCount + upperNonZeroCount; } for (var i = 0; i < _lower.RowCount; i++) { _lower[i, i] = 1.0; } } /// <summary> /// Pivot elements in the <paramref name="row"/> according to internal pivot array /// </summary> /// <param name="row">Row <see cref="Vector"/> to pivot in</param> void PivotRow(Vector<Complex> row) { var knownPivots = new Dictionary<int, int>(); // pivot the row for (var i = 0; i < row.Count; i++) { if ((_pivots[i] != i) && (!PivotMapFound(knownPivots, i))) { // store the pivots in the hashtable knownPivots.Add(_pivots[i], i); var t = row[i]; row[i] = row[_pivots[i]]; row[_pivots[i]] = t; } } } /// <summary> /// Was pivoting already performed /// </summary> /// <param name="knownPivots">Pivots already done</param> /// <param name="currentItem">Current item to pivot</param> /// <returns><c>true</c> if performed, otherwise <c>false</c></returns> bool PivotMapFound(Dictionary<int, int> knownPivots, int currentItem) { if (knownPivots.ContainsKey(_pivots[currentItem])) { if (knownPivots[_pivots[currentItem]].Equals(currentItem)) { return true; } } if (knownPivots.ContainsKey(currentItem)) { if (knownPivots[currentItem].Equals(_pivots[currentItem])) { return true; } } return false; } /// <summary> /// Swap columns in the <see cref="Matrix"/> /// </summary> /// <param name="matrix">Source <see cref="Matrix"/>.</param> /// <param name="firstColumn">First column index to swap</param> /// <param name="secondColumn">Second column index to swap</param> static void SwapColumns(Matrix<Complex> matrix, int firstColumn, int secondColumn) { for (var i = 0; i < matrix.RowCount; i++) { var temp = matrix[i, firstColumn]; matrix[i, firstColumn] = matrix[i, secondColumn]; matrix[i, secondColumn] = temp; } } /// <summary> /// Sort vector descending, not changing vector but placing sorted indicies to <paramref name="sortedIndices"/> /// </summary> /// <param name="lowerBound">Start sort form</param> /// <param name="upperBound">Sort till upper bound</param> /// <param name="sortedIndices">Array with sorted vector indicies</param> /// <param name="values">Source <see cref="Vector"/></param> static void FindLargestItems(int lowerBound, int upperBound, int[] sortedIndices, Vector<Complex> values) { // Copy the indices for the values into the array for (var i = 0; i < upperBound + 1 - lowerBound; i++) { sortedIndices[i] = lowerBound + i; } for (var i = upperBound + 1 - lowerBound; i < sortedIndices.Length; i++) { sortedIndices[i] = -1; } // Sort the first set of items. // Sorting starts at index 0 because the index array // starts at zero // and ends at index upperBound - lowerBound ILUTPElementSorter.SortDoubleIndicesDecreasing(0, upperBound - lowerBound, sortedIndices, values); } /// <summary> /// Approximates the solution to the matrix equation <b>Ax = b</b>. /// </summary> /// <param name="rhs">The right hand side vector.</param> /// <param name="lhs">The left hand side vector. Also known as the result vector.</param> public void Approximate(Vector<Complex> rhs, Vector<Complex> lhs) { if (_upper == null) { throw new ArgumentException(Resources.ArgumentMatrixDoesNotExist); } if ((lhs.Count != rhs.Count) || (lhs.Count != _upper.RowCount)) { throw new ArgumentException(Resources.ArgumentVectorsSameLength, "rhs"); } // Solve equation here // Pivot(vector, result); // Solve L*Y = B(piv,:) var rowValues = new DenseVector(_lower.RowCount); for (var i = 0; i < _lower.RowCount; i++) { _lower.Row(i, rowValues); var sum = Complex.Zero; for (var j = 0; j < i; j++) { sum += rowValues[j]*lhs[j]; } lhs[i] = rhs[i] - sum; } // Solve U*X = Y; for (var i = _upper.RowCount - 1; i > -1; i--) { _upper.Row(i, rowValues); var sum = Complex.Zero; for (var j = _upper.RowCount - 1; j > i; j--) { sum += rowValues[j]*lhs[j]; } lhs[i] = 1/rowValues[i]*(lhs[i] - sum); } // We have a column pivot so we only need to pivot the // end result not the incoming right hand side vector var temp = lhs.Clone(); Pivot(temp, lhs); } /// <summary> /// Pivot elements in <see cref="Vector"/> according to internal pivot array /// </summary> /// <param name="vector">Source <see cref="Vector"/>.</param> /// <param name="result">Result <see cref="Vector"/> after pivoting.</param> void Pivot(Vector<Complex> vector, Vector<Complex> result) { for (var i = 0; i < _pivots.Length; i++) { result[i] = vector[_pivots[i]]; } } } /// <summary> /// An element sort algorithm for the <see cref="ILUTPPreconditioner"/> class. /// </summary> /// <remarks> /// This sort algorithm is used to sort the columns in a sparse matrix based on /// the value of the element on the diagonal of the matrix. /// </remarks> internal static class ILUTPElementSorter { /// <summary> /// Sorts the elements of the <paramref name="values"/> vector in decreasing /// fashion. The vector itself is not affected. /// </summary> /// <param name="lowerBound">The starting index.</param> /// <param name="upperBound">The stopping index.</param> /// <param name="sortedIndices">An array that will contain the sorted indices once the algorithm finishes.</param> /// <param name="values">The <see cref="Vector{T}"/> that contains the values that need to be sorted.</param> public static void SortDoubleIndicesDecreasing(int lowerBound, int upperBound, int[] sortedIndices, Vector<Complex> values) { // Move all the indices that we're interested in to the beginning of the // array. Ignore the rest of the indices. if (lowerBound > 0) { for (var i = 0; i < (upperBound - lowerBound + 1); i++) { Exchange(sortedIndices, i, i + lowerBound); } upperBound -= lowerBound; lowerBound = 0; } HeapSortDoublesIndices(lowerBound, upperBound, sortedIndices, values); } /// <summary> /// Sorts the elements of the <paramref name="values"/> vector in decreasing /// fashion using heap sort algorithm. The vector itself is not affected. /// </summary> /// <param name="lowerBound">The starting index.</param> /// <param name="upperBound">The stopping index.</param> /// <param name="sortedIndices">An array that will contain the sorted indices once the algorithm finishes.</param> /// <param name="values">The <see cref="Vector{T}"/> that contains the values that need to be sorted.</param> private static void HeapSortDoublesIndices(int lowerBound, int upperBound, int[] sortedIndices, Vector<Complex> values) { var start = ((upperBound - lowerBound + 1) / 2) - 1 + lowerBound; var end = (upperBound - lowerBound + 1) - 1 + lowerBound; BuildDoubleIndexHeap(start, upperBound - lowerBound + 1, sortedIndices, values); while (end >= lowerBound) { Exchange(sortedIndices, end, lowerBound); SiftDoubleIndices(sortedIndices, values, lowerBound, end); end -= 1; } } /// <summary> /// Build heap for double indicies /// </summary> /// <param name="start">Root position</param> /// <param name="count">Length of <paramref name="values"/></param> /// <param name="sortedIndices">Indicies of <paramref name="values"/></param> /// <param name="values">Target <see cref="Vector{T}"/></param> private static void BuildDoubleIndexHeap(int start, int count, int[] sortedIndices, Vector<Complex> values) { while (start >= 0) { SiftDoubleIndices(sortedIndices, values, start, count); start -= 1; } } /// <summary> /// Sift double indicies /// </summary> /// <param name="sortedIndices">Indicies of <paramref name="values"/></param> /// <param name="values">Target <see cref="Vector{T}"/></param> /// <param name="begin">Root position</param> /// <param name="count">Length of <paramref name="values"/></param> private static void SiftDoubleIndices(int[] sortedIndices, Vector<Complex> values, int begin, int count) { var root = begin; while (root * 2 < count) { var child = root * 2; if ((child < count - 1) && (values[sortedIndices[child]].Magnitude > values[sortedIndices[child + 1]].Magnitude)) { child += 1; } if (values[sortedIndices[root]].Magnitude <= values[sortedIndices[child]].Magnitude) { return; } Exchange(sortedIndices, root, child); root = child; } } /// <summary> /// Sorts the given integers in a decreasing fashion. /// </summary> /// <param name="values">The values.</param> public static void SortIntegersDecreasing(int[] values) { HeapSortIntegers(values, values.Length); } /// <summary> /// Sort the given integers in a decreasing fashion using heapsort algorithm /// </summary> /// <param name="values">Array of values to sort</param> /// <param name="count">Length of <paramref name="values"/></param> private static void HeapSortIntegers(int[] values, int count) { var start = (count / 2) - 1; var end = count - 1; BuildHeap(values, start, count); while (end >= 0) { Exchange(values, end, 0); Sift(values, 0, end); end -= 1; } } /// <summary> /// Build heap /// </summary> /// <param name="values">Target values array</param> /// <param name="start">Root position</param> /// <param name="count">Length of <paramref name="values"/></param> private static void BuildHeap(int[] values, int start, int count) { while (start >= 0) { Sift(values, start, count); start -= 1; } } /// <summary> /// Sift values /// </summary> /// <param name="values">Target value array</param> /// <param name="start">Root position</param> /// <param name="count">Length of <paramref name="values"/></param> private static void Sift(int[] values, int start, int count) { var root = start; while (root * 2 < count) { var child = root * 2; if ((child < count - 1) && (values[child] > values[child + 1])) { child += 1; } if (values[root] > values[child]) { Exchange(values, root, child); root = child; } else { return; } } } /// <summary> /// Exchange values in array /// </summary> /// <param name="values">Target values array</param> /// <param name="first">First value to exchange</param> /// <param name="second">Second value to exchange</param> private static void Exchange(int[] values, int first, int second) { var t = values[first]; values[first] = values[second]; values[second] = t; } } }
namespace Mages.Plugins.LinearAlgebra.Decompositions { using System; /// <summary> /// LU Decomposition. /// For an m-by-n matrix A with m &gt;= n, the LU decomposition is an m-by-n /// unit lower triangular matrix L, an n-by-n upper triangular matrix U, /// and a permutation vector piv of length m so that A(piv,:) = L*U. /// <code> /// If m is smaller than n, then L is m-by-m and U is m-by-n. /// </code> /// The LU decompostion with pivoting always exists, even if the matrix is /// singular, so the constructor will never fail. The primary use of the /// LU decomposition is in the solution of square systems of simultaneous /// linear equations. This will fail if IsNonSingular() returns false. /// </summary> public class LUDecomposition : IDirectSolver { #region Fields private readonly Double[,] _LU; private readonly Int32 _rows; private readonly Int32 _columns; private readonly Int32 _pivsign; private readonly Int32[] _piv; #endregion #region ctor /// <summary> /// LU Decomposition /// </summary> /// <param name="matrix">Rectangular matrix</param> /// <returns>Structure to access L, U and piv.</returns> public LUDecomposition(Double[,] matrix) { // Use a "left-looking", dot-product, Crout / Doolittle algorithm. _LU = (Double[,])matrix.Clone(); _rows = matrix.GetLength(0); _columns = matrix.GetLength(1); _piv = new Int32[_rows]; for (var i = 1; i < _rows; i++) { _piv[i] = i; } _pivsign = 1; var LUcolj = new Double[_rows]; // Outer loop. for (var j = 0; j < _columns; j++) { // Make a copy of the j-th column to localize references. for (var i = 0; i < _rows; i++) { LUcolj[i] = _LU[i, j]; } // Apply previous transformations. for (var i = 0; i < _rows; i++) { var LUrowi = new Double[_columns]; for (var k = 0; k < _columns; k++) { LUrowi[k] = _LU[i, k]; } // Most of the time is spent in the following dot product. var kmax = Math.Min(i, j); var s = 0.0; for (var k = 0; k < kmax; k++) { s += LUrowi[k] * LUcolj[k]; } LUrowi[j] = LUcolj[i] -= s; } // Find pivot and exchange if necessary. var p = j; for (var i = j + 1; i < _rows; i++) { if (Math.Abs(LUcolj[i]) > Math.Abs(LUcolj[p])) { p = i; } } if (p != j) { for (var k = 0; k < _columns; k++) { var t = _LU[p, k]; _LU[p, k] = _LU[j, k]; _LU[j, k] = t; } var k2 = _piv[p]; _piv[p] = _piv[j]; _piv[j] = k2; _pivsign = -_pivsign; } // Compute multipliers. if (j < _rows & _LU[j, j] != 0.0) { for (var i = j + 1; i < _rows; i++) { _LU[i, j] = _LU[i, j] / _LU[j, j]; } } } } #endregion #region Properties /// <summary> /// Gets if the matrix nonsingular. /// </summary> public Boolean IsNonSingular { get { for (var j = 0; j < _columns; j++) { if (_LU[j, j] == 0.0) { return false; } } return true; } } /// <summary> /// Gets the lower triangular factor. /// </summary> public Double[,] L { get { var X = new Double[_rows, _columns]; for (var i = 0; i < _rows; i++) { for (var j = 0; j < _columns; j++) { if (i > j) { X[i, j] = _LU[i, j]; } else if (i == j) { X[i, j] = 1.0; } } } return X; } } /// <summary> /// Gets the upper triangular factor. /// </summary> public Double[,] U { get { var X = new Double[_columns, _columns]; for (var i = 0; i < _columns; i++) { for (var j = 0; j < _columns; j++) { if (i <= j) { X[i, j] = _LU[i, j]; } } } return X; } } /// <summary> /// Gets the pivot permutation vector. /// </summary> public Double[,] Pivot { get { var P = new Double[_rows, _rows]; for (var i = 0; i < _rows; i++) { P[i, _piv[i]] = 1.0; } return P; } } #endregion #region Methods /// <summary> /// Computes the determinant of the given matrix. /// </summary> public static Double Determinant(Double[,] matrix) { var lu = new LUDecomposition(matrix); if (lu._rows == lu._columns) { var d = (Double)lu._pivsign; for (var j = 0; j < lu._columns; j++) { d = d * lu._LU[j, j]; } return d; } return 0.0; } /// <summary> /// Solve A*X = B /// </summary> /// <param name="matrix">A Matrix with as many rows as A and any number of columns.</param> /// <returns>X so that L*U*X = B(piv,:)</returns> public Double[,] Solve(Double[,] matrix) { if (matrix.GetLength(0) != _rows) throw new InvalidOperationException(ErrorMessages.RowMismatch); if (!IsNonSingular) throw new InvalidOperationException(ErrorMessages.SingularSource); // Copy right hand side with pivoting var nx = matrix.GetLength(1); var X = Helpers.SubMatrix(matrix, _piv, 0, nx); // Solve L*Y = B(piv,:) for (var k = 0; k < _columns; k++) { for (var i = k + 1; i < _columns; i++) { for (var j = 0; j < nx; j++) { X[i, j] -= X[k, j] * _LU[i, k]; } } } // Solve U*X = Y; for (var k = _columns - 1; k >= 0; k--) { for (var j = 0; j < nx; j++) { X[k, j] = X[k, j] / _LU[k, k]; } for (var i = 0; i < k; i++) { for (var j = 0; j < nx; j++) { X[i, j] -= X[k, j] * _LU[i, k]; } } } return X; } #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.Xml.Schema; using System.Collections; using System.Diagnostics; namespace System.Xml { internal partial class XmlWrappingWriter : XmlWriter { // // Fields // protected XmlWriter writer; // // Constructor // internal XmlWrappingWriter(XmlWriter baseWriter) { Debug.Assert(baseWriter != null); this.writer = baseWriter; } // // XmlWriter implementation // public override XmlWriterSettings Settings { get { return writer.Settings; } } public override WriteState WriteState { get { return writer.WriteState; } } public override XmlSpace XmlSpace { get { return writer.XmlSpace; } } public override string XmlLang { get { return writer.XmlLang; } } public override void WriteStartDocument() { writer.WriteStartDocument(); } public override void WriteStartDocument(bool standalone) { writer.WriteStartDocument(standalone); } public override void WriteEndDocument() { writer.WriteEndDocument(); } public override void WriteDocType(string name, string pubid, string sysid, string subset) { writer.WriteDocType(name, pubid, sysid, subset); } public override void WriteStartElement(string prefix, string localName, string ns) { writer.WriteStartElement(prefix, localName, ns); } public override void WriteEndElement() { writer.WriteEndElement(); } public override void WriteFullEndElement() { writer.WriteFullEndElement(); } public override void WriteStartAttribute(string prefix, string localName, string ns) { writer.WriteStartAttribute(prefix, localName, ns); } public override void WriteEndAttribute() { writer.WriteEndAttribute(); } public override void WriteCData(string text) { writer.WriteCData(text); } public override void WriteComment(string text) { writer.WriteComment(text); } public override void WriteProcessingInstruction(string name, string text) { writer.WriteProcessingInstruction(name, text); } public override void WriteEntityRef(string name) { writer.WriteEntityRef(name); } public override void WriteCharEntity(char ch) { writer.WriteCharEntity(ch); } public override void WriteWhitespace(string ws) { writer.WriteWhitespace(ws); } public override void WriteString(string text) { writer.WriteString(text); } public override void WriteSurrogateCharEntity(char lowChar, char highChar) { writer.WriteSurrogateCharEntity(lowChar, highChar); } public override void WriteChars(char[] buffer, int index, int count) { writer.WriteChars(buffer, index, count); } public override void WriteRaw(char[] buffer, int index, int count) { writer.WriteRaw(buffer, index, count); } public override void WriteRaw(string data) { writer.WriteRaw(data); } public override void WriteBase64(byte[] buffer, int index, int count) { writer.WriteBase64(buffer, index, count); } public override void Flush() { writer.Flush(); } public override string LookupPrefix(string ns) { return writer.LookupPrefix(ns); } public override void WriteValue(object value) { writer.WriteValue(value); } public override void WriteValue(string value) { writer.WriteValue(value); } public override void WriteValue(bool value) { writer.WriteValue(value); } public override void WriteValue(DateTimeOffset value) { writer.WriteValue(value); } public override void WriteValue(double value) { writer.WriteValue(value); } public override void WriteValue(float value) { writer.WriteValue(value); } public override void WriteValue(decimal value) { writer.WriteValue(value); } public override void WriteValue(int value) { writer.WriteValue(value); } public override void WriteValue(long value) { writer.WriteValue(value); } protected override void Dispose(bool disposing) { if (disposing) { writer.Dispose(); } } } }
// 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 AndInt16() { var test = new SimpleBinaryOpTest__AndInt16(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); if (Avx.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (Avx.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (Avx.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (Avx.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (Avx.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__AndInt16 { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(Int16[] inArray1, Int16[] inArray2, Int16[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int16>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int16>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int16>(); if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Int16, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int16, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector256<Int16> _fld1; public Vector256<Int16> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref testStruct._fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref testStruct._fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__AndInt16 testClass) { var result = Avx2.And(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__AndInt16 testClass) { fixed (Vector256<Int16>* pFld1 = &_fld1) fixed (Vector256<Int16>* pFld2 = &_fld2) { var result = Avx2.And( Avx.LoadVector256((Int16*)(pFld1)), Avx.LoadVector256((Int16*)(pFld2)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 32; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Int16>>() / sizeof(Int16); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<Int16>>() / sizeof(Int16); private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Int16>>() / sizeof(Int16); private static Int16[] _data1 = new Int16[Op1ElementCount]; private static Int16[] _data2 = new Int16[Op2ElementCount]; private static Vector256<Int16> _clsVar1; private static Vector256<Int16> _clsVar2; private Vector256<Int16> _fld1; private Vector256<Int16> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__AndInt16() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _clsVar1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _clsVar2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>()); } public SimpleBinaryOpTest__AndInt16() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int16>, byte>(ref _fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<Int16>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } _dataTable = new DataTable(_data1, _data2, new Int16[RetElementCount], LargestVectorSize); } public bool IsSupported => Avx2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Avx2.And( Unsafe.Read<Vector256<Int16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Int16>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Avx2.And( Avx.LoadVector256((Int16*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Int16*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Avx2.And( Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Avx2).GetMethod(nameof(Avx2.And), new Type[] { typeof(Vector256<Int16>), typeof(Vector256<Int16>) }) .Invoke(null, new object[] { Unsafe.Read<Vector256<Int16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Int16>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Avx2).GetMethod(nameof(Avx2.And), new Type[] { typeof(Vector256<Int16>), typeof(Vector256<Int16>) }) .Invoke(null, new object[] { Avx.LoadVector256((Int16*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Int16*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Avx2).GetMethod(nameof(Avx2.And), new Type[] { typeof(Vector256<Int16>), typeof(Vector256<Int16>) }) .Invoke(null, new object[] { Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Avx2.And( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector256<Int16>* pClsVar1 = &_clsVar1) fixed (Vector256<Int16>* pClsVar2 = &_clsVar2) { var result = Avx2.And( Avx.LoadVector256((Int16*)(pClsVar1)), Avx.LoadVector256((Int16*)(pClsVar2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector256<Int16>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector256<Int16>>(_dataTable.inArray2Ptr); var result = Avx2.And(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = Avx.LoadVector256((Int16*)(_dataTable.inArray1Ptr)); var op2 = Avx.LoadVector256((Int16*)(_dataTable.inArray2Ptr)); var result = Avx2.And(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var op1 = Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray1Ptr)); var op2 = Avx.LoadAlignedVector256((Int16*)(_dataTable.inArray2Ptr)); var result = Avx2.And(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__AndInt16(); var result = Avx2.And(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleBinaryOpTest__AndInt16(); fixed (Vector256<Int16>* pFld1 = &test._fld1) fixed (Vector256<Int16>* pFld2 = &test._fld2) { var result = Avx2.And( Avx.LoadVector256((Int16*)(pFld1)), Avx.LoadVector256((Int16*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Avx2.And(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector256<Int16>* pFld1 = &_fld1) fixed (Vector256<Int16>* pFld2 = &_fld2) { var result = Avx2.And( Avx.LoadVector256((Int16*)(pFld1)), Avx.LoadVector256((Int16*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Avx2.And(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = Avx2.And( Avx.LoadVector256((Int16*)(&test._fld1)), Avx.LoadVector256((Int16*)(&test._fld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector256<Int16> op1, Vector256<Int16> op2, void* result, [CallerMemberName] string method = "") { Int16[] inArray1 = new Int16[Op1ElementCount]; Int16[] inArray2 = new Int16[Op2ElementCount]; Int16[] outArray = new Int16[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int16>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { Int16[] inArray1 = new Int16[Op1ElementCount]; Int16[] inArray2 = new Int16[Op2ElementCount]; Int16[] outArray = new Int16[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<Int16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector256<Int16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int16>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Int16[] left, Int16[] right, Int16[] result, [CallerMemberName] string method = "") { bool succeeded = true; if ((short)(left[0] & right[0]) != result[0]) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if ((short)(left[i] & right[i]) != result[i]) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Avx2)}.{nameof(Avx2.And)}<Int16>(Vector256<Int16>, Vector256<Int16>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
/* * Copyright (c) 2006-2016, openmetaverse.co * 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.co nor the names * of its contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.IO; using System.Xml; using System.Xml.Schema; using System.Text; namespace OpenMetaverse.StructuredData { /// <summary> /// /// </summary> public static partial class OSDParser { private static XmlSchema XmlSchema; private static XmlTextReader XmlTextReader; private static string LastXmlErrors = String.Empty; private static object XmlValidationLock = new object(); /// <summary> /// /// </summary> /// <param name="xmlData"></param> /// <returns></returns> public static OSD DeserializeLLSDXml(byte[] xmlData) { return DeserializeLLSDXml(new XmlTextReader(new MemoryStream(xmlData, false))); } public static OSD DeserializeLLSDXml(Stream xmlStream) { return DeserializeLLSDXml(new XmlTextReader(xmlStream)); } /// <summary> /// /// </summary> /// <param name="xmlData"></param> /// <returns></returns> public static OSD DeserializeLLSDXml(string xmlData) { byte[] bytes = Utils.StringToBytes(xmlData); return DeserializeLLSDXml(new XmlTextReader(new MemoryStream(bytes, false))); } /// <summary> /// /// </summary> /// <param name="xmlData"></param> /// <returns></returns> public static OSD DeserializeLLSDXml(XmlTextReader xmlData) { try { xmlData.Read(); SkipWhitespace(xmlData); xmlData.Read(); OSD ret = ParseLLSDXmlElement(xmlData); return ret; } catch { return new OSD(); } } /// <summary> /// /// </summary> /// <param name="data"></param> /// <returns></returns> public static byte[] SerializeLLSDXmlBytes(OSD data) { return Encoding.UTF8.GetBytes(SerializeLLSDXmlString(data)); } /// <summary> /// /// </summary> /// <param name="data"></param> /// <returns></returns> public static string SerializeLLSDXmlString(OSD data) { StringWriter sw = new StringWriter(); XmlTextWriter writer = new XmlTextWriter(sw); writer.Formatting = Formatting.None; writer.WriteStartElement(String.Empty, "llsd", String.Empty); SerializeLLSDXmlElement(writer, data); writer.WriteEndElement(); writer.Close(); return sw.ToString(); } /// <summary> /// /// </summary> /// <param name="writer"></param> /// <param name="data"></param> public static void SerializeLLSDXmlElement(XmlTextWriter writer, OSD data) { switch (data.Type) { case OSDType.Unknown: writer.WriteStartElement(String.Empty, "undef", String.Empty); writer.WriteEndElement(); break; case OSDType.Boolean: writer.WriteStartElement(String.Empty, "boolean", String.Empty); writer.WriteString(data.AsString()); writer.WriteEndElement(); break; case OSDType.Integer: writer.WriteStartElement(String.Empty, "integer", String.Empty); writer.WriteString(data.AsString()); writer.WriteEndElement(); break; case OSDType.Real: writer.WriteStartElement(String.Empty, "real", String.Empty); writer.WriteString(data.AsString()); writer.WriteEndElement(); break; case OSDType.String: writer.WriteStartElement(String.Empty, "string", String.Empty); writer.WriteString(data.AsString()); writer.WriteEndElement(); break; case OSDType.UUID: writer.WriteStartElement(String.Empty, "uuid", String.Empty); writer.WriteString(data.AsString()); writer.WriteEndElement(); break; case OSDType.Date: writer.WriteStartElement(String.Empty, "date", String.Empty); writer.WriteString(data.AsString()); writer.WriteEndElement(); break; case OSDType.URI: writer.WriteStartElement(String.Empty, "uri", String.Empty); writer.WriteString(data.AsString()); writer.WriteEndElement(); break; case OSDType.Binary: writer.WriteStartElement(String.Empty, "binary", String.Empty); writer.WriteStartAttribute(String.Empty, "encoding", String.Empty); writer.WriteString("base64"); writer.WriteEndAttribute(); writer.WriteString(data.AsString()); writer.WriteEndElement(); break; case OSDType.Map: OSDMap map = (OSDMap)data; writer.WriteStartElement(String.Empty, "map", String.Empty); foreach (KeyValuePair<string, OSD> kvp in map) { writer.WriteStartElement(String.Empty, "key", String.Empty); writer.WriteString(kvp.Key); writer.WriteEndElement(); SerializeLLSDXmlElement(writer, kvp.Value); } writer.WriteEndElement(); break; case OSDType.Array: OSDArray array = (OSDArray)data; writer.WriteStartElement(String.Empty, "array", String.Empty); for (int i = 0; i < array.Count; i++) { SerializeLLSDXmlElement(writer, array[i]); } writer.WriteEndElement(); break; } } /// <summary> /// /// </summary> /// <param name="xmlData"></param> /// <param name="error"></param> /// <returns></returns> public static bool TryValidateLLSDXml(XmlTextReader xmlData, out string error) { lock (XmlValidationLock) { LastXmlErrors = String.Empty; XmlTextReader = xmlData; CreateLLSDXmlSchema(); XmlReaderSettings readerSettings = new XmlReaderSettings(); readerSettings.ValidationType = ValidationType.Schema; readerSettings.Schemas.Add(XmlSchema); readerSettings.ValidationEventHandler += new ValidationEventHandler(LLSDXmlSchemaValidationHandler); XmlReader reader = XmlReader.Create(xmlData, readerSettings); try { while (reader.Read()) { } } catch (XmlException) { error = LastXmlErrors; return false; } if (LastXmlErrors == String.Empty) { error = null; return true; } else { error = LastXmlErrors; return false; } } } /// <summary> /// /// </summary> /// <param name="reader"></param> /// <returns></returns> private static OSD ParseLLSDXmlElement(XmlTextReader reader) { SkipWhitespace(reader); if (reader.NodeType != XmlNodeType.Element) throw new OSDException("Expected an element"); string type = reader.LocalName; OSD ret; switch (type) { case "undef": if (reader.IsEmptyElement) { reader.Read(); return new OSD(); } reader.Read(); SkipWhitespace(reader); ret = new OSD(); break; case "boolean": if (reader.IsEmptyElement) { reader.Read(); return OSD.FromBoolean(false); } if (reader.Read()) { string s = reader.ReadString().Trim(); if (!String.IsNullOrEmpty(s) && (s == "true" || s == "1")) { ret = OSD.FromBoolean(true); break; } } ret = OSD.FromBoolean(false); break; case "integer": if (reader.IsEmptyElement) { reader.Read(); return OSD.FromInteger(0); } if (reader.Read()) { int value = 0; Int32.TryParse(reader.ReadString().Trim(), out value); ret = OSD.FromInteger(value); break; } ret = OSD.FromInteger(0); break; case "real": if (reader.IsEmptyElement) { reader.Read(); return OSD.FromReal(0d); } if (reader.Read()) { double value = 0d; string str = reader.ReadString().Trim().ToLower(); if (str == "nan") value = Double.NaN; else Utils.TryParseDouble(str, out value); ret = OSD.FromReal(value); break; } ret = OSD.FromReal(0d); break; case "uuid": if (reader.IsEmptyElement) { reader.Read(); return OSD.FromUUID(UUID.Zero); } if (reader.Read()) { UUID value = UUID.Zero; UUID.TryParse(reader.ReadString().Trim(), out value); ret = OSD.FromUUID(value); break; } ret = OSD.FromUUID(UUID.Zero); break; case "date": if (reader.IsEmptyElement) { reader.Read(); return OSD.FromDate(Utils.Epoch); } if (reader.Read()) { DateTime value = Utils.Epoch; DateTime.TryParse(reader.ReadString().Trim(), out value); ret = OSD.FromDate(value); break; } ret = OSD.FromDate(Utils.Epoch); break; case "string": if (reader.IsEmptyElement) { reader.Read(); return OSD.FromString(String.Empty); } if (reader.Read()) { ret = OSD.FromString(reader.ReadString()); break; } ret = OSD.FromString(String.Empty); break; case "binary": if (reader.IsEmptyElement) { reader.Read(); return OSD.FromBinary(Utils.EmptyBytes); } if (reader.GetAttribute("encoding") != null && reader.GetAttribute("encoding") != "base64") throw new OSDException("Unsupported binary encoding: " + reader.GetAttribute("encoding")); if (reader.Read()) { try { ret = OSD.FromBinary(Convert.FromBase64String(reader.ReadString().Trim())); break; } catch (FormatException ex) { throw new OSDException("Binary decoding exception: " + ex.Message); } } ret = OSD.FromBinary(Utils.EmptyBytes); break; case "uri": if (reader.IsEmptyElement) { reader.Read(); return OSD.FromUri(new Uri(String.Empty, UriKind.RelativeOrAbsolute)); } if (reader.Read()) { ret = OSD.FromUri(new Uri(reader.ReadString(), UriKind.RelativeOrAbsolute)); break; } ret = OSD.FromUri(new Uri(String.Empty, UriKind.RelativeOrAbsolute)); break; case "map": return ParseLLSDXmlMap(reader); case "array": return ParseLLSDXmlArray(reader); default: reader.Read(); ret = null; break; } if (reader.NodeType != XmlNodeType.EndElement || reader.LocalName != type) { throw new OSDException("Expected </" + type + ">"); } else { reader.Read(); return ret; } } private static OSDMap ParseLLSDXmlMap(XmlTextReader reader) { if (reader.NodeType != XmlNodeType.Element || reader.LocalName != "map") throw new NotImplementedException("Expected <map>"); OSDMap map = new OSDMap(); if (reader.IsEmptyElement) { reader.Read(); return map; } if (reader.Read()) { while (true) { SkipWhitespace(reader); if (reader.NodeType == XmlNodeType.EndElement && reader.LocalName == "map") { reader.Read(); break; } if (reader.NodeType != XmlNodeType.Element || reader.LocalName != "key") throw new OSDException("Expected <key>"); string key = reader.ReadString(); if (reader.NodeType != XmlNodeType.EndElement || reader.LocalName != "key") throw new OSDException("Expected </key>"); if (reader.Read()) map[key] = ParseLLSDXmlElement(reader); else throw new OSDException("Failed to parse a value for key " + key); } } return map; } private static OSDArray ParseLLSDXmlArray(XmlTextReader reader) { if (reader.NodeType != XmlNodeType.Element || reader.LocalName != "array") throw new OSDException("Expected <array>"); OSDArray array = new OSDArray(); if (reader.IsEmptyElement) { reader.Read(); return array; } if (reader.Read()) { while (true) { SkipWhitespace(reader); if (reader.NodeType == XmlNodeType.EndElement && reader.LocalName == "array") { reader.Read(); break; } array.Add(ParseLLSDXmlElement(reader)); } } return array; } private static void SkipWhitespace(XmlTextReader reader) { while ( reader.NodeType == XmlNodeType.Comment || reader.NodeType == XmlNodeType.Whitespace || reader.NodeType == XmlNodeType.SignificantWhitespace || reader.NodeType == XmlNodeType.XmlDeclaration) { reader.Read(); } } private static void CreateLLSDXmlSchema() { if (XmlSchema == null) { #region XSD string schemaText = @" <?xml version=""1.0"" encoding=""utf-8""?> <xs:schema elementFormDefault=""qualified"" xmlns:xs=""http://www.w3.org/2001/XMLSchema""> <xs:import schemaLocation=""xml.xsd"" namespace=""http://www.w3.org/XML/1998/namespace"" /> <xs:element name=""uri"" type=""xs:string"" /> <xs:element name=""uuid"" type=""xs:string"" /> <xs:element name=""KEYDATA""> <xs:complexType> <xs:sequence> <xs:element ref=""key"" /> <xs:element ref=""DATA"" /> </xs:sequence> </xs:complexType> </xs:element> <xs:element name=""date"" type=""xs:string"" /> <xs:element name=""key"" type=""xs:string"" /> <xs:element name=""boolean"" type=""xs:string"" /> <xs:element name=""undef""> <xs:complexType> <xs:sequence> <xs:element ref=""EMPTY"" /> </xs:sequence> </xs:complexType> </xs:element> <xs:element name=""map""> <xs:complexType> <xs:sequence> <xs:element minOccurs=""0"" maxOccurs=""unbounded"" ref=""KEYDATA"" /> </xs:sequence> </xs:complexType> </xs:element> <xs:element name=""real"" type=""xs:string"" /> <xs:element name=""ATOMIC""> <xs:complexType> <xs:choice> <xs:element ref=""undef"" /> <xs:element ref=""boolean"" /> <xs:element ref=""integer"" /> <xs:element ref=""real"" /> <xs:element ref=""uuid"" /> <xs:element ref=""string"" /> <xs:element ref=""date"" /> <xs:element ref=""uri"" /> <xs:element ref=""binary"" /> </xs:choice> </xs:complexType> </xs:element> <xs:element name=""DATA""> <xs:complexType> <xs:choice> <xs:element ref=""ATOMIC"" /> <xs:element ref=""map"" /> <xs:element ref=""array"" /> </xs:choice> </xs:complexType> </xs:element> <xs:element name=""llsd""> <xs:complexType> <xs:sequence> <xs:element ref=""DATA"" /> </xs:sequence> </xs:complexType> </xs:element> <xs:element name=""binary""> <xs:complexType> <xs:simpleContent> <xs:extension base=""xs:string""> <xs:attribute default=""base64"" name=""encoding"" type=""xs:string"" /> </xs:extension> </xs:simpleContent> </xs:complexType> </xs:element> <xs:element name=""array""> <xs:complexType> <xs:sequence> <xs:element minOccurs=""0"" maxOccurs=""unbounded"" ref=""DATA"" /> </xs:sequence> </xs:complexType> </xs:element> <xs:element name=""integer"" type=""xs:string"" /> <xs:element name=""string""> <xs:complexType> <xs:simpleContent> <xs:extension base=""xs:string""> <xs:attribute ref=""xml:space"" /> </xs:extension> </xs:simpleContent> </xs:complexType> </xs:element> </xs:schema> "; #endregion XSD MemoryStream stream = new MemoryStream(Encoding.ASCII.GetBytes(schemaText)); XmlSchema = new XmlSchema(); XmlSchema = XmlSchema.Read(stream, new ValidationEventHandler(LLSDXmlSchemaValidationHandler)); } } private static void LLSDXmlSchemaValidationHandler(object sender, ValidationEventArgs args) { string error = String.Format("Line: {0} - Position: {1} - {2}", XmlTextReader.LineNumber, XmlTextReader.LinePosition, args.Message); if (LastXmlErrors == String.Empty) LastXmlErrors = error; else LastXmlErrors += Environment.NewLine + error; } } }
using System; using System.Text; using PalmeralGenNHibernate.CEN.Default_; using NHibernate; using NHibernate.Cfg; using NHibernate.Criterion; using NHibernate.Exceptions; using PalmeralGenNHibernate.EN.Default_; using PalmeralGenNHibernate.Exceptions; namespace PalmeralGenNHibernate.CAD.Default_ { public partial class InstalacionCAD : BasicCAD, IInstalacionCAD { public InstalacionCAD() : base () { } public InstalacionCAD(ISession sessionAux) : base (sessionAux) { } public InstalacionEN ReadOIDDefault (string id) { InstalacionEN instalacionEN = null; try { SessionInitializeTransaction (); instalacionEN = (InstalacionEN)session.Get (typeof(InstalacionEN), id); SessionCommit (); } catch (Exception ex) { SessionRollBack (); if (ex is PalmeralGenNHibernate.Exceptions.ModelException) throw ex; throw new PalmeralGenNHibernate.Exceptions.DataLayerException ("Error in InstalacionCAD.", ex); } finally { SessionClose (); } return instalacionEN; } public string Crear (InstalacionEN instalacion) { try { SessionInitializeTransaction (); if (instalacion.Cliente != null) { instalacion.Cliente = (PalmeralGenNHibernate.EN.Default_.ClienteEN)session.Load (typeof(PalmeralGenNHibernate.EN.Default_.ClienteEN), instalacion.Cliente.Nif); instalacion.Cliente.Instalaciones.Add (instalacion); } session.Save (instalacion); SessionCommit (); } catch (Exception ex) { SessionRollBack (); if (ex is PalmeralGenNHibernate.Exceptions.ModelException) throw ex; throw new PalmeralGenNHibernate.Exceptions.DataLayerException ("Error in InstalacionCAD.", ex); } finally { SessionClose (); } return instalacion.Id; } public void Editar (InstalacionEN instalacion) { try { SessionInitializeTransaction (); InstalacionEN instalacionEN = (InstalacionEN)session.Load (typeof(InstalacionEN), instalacion.Id); instalacionEN.Nombre = instalacion.Nombre; instalacionEN.Descripcion = instalacion.Descripcion; instalacionEN.Localidad = instalacion.Localidad; instalacionEN.Provincia = instalacion.Provincia; instalacionEN.Pais = instalacion.Pais; instalacionEN.Direccion = instalacion.Direccion; instalacionEN.CodigoPostal = instalacion.CodigoPostal; instalacionEN.Telefono = instalacion.Telefono; instalacionEN.MetrosCuadrados = instalacion.MetrosCuadrados; session.Update (instalacionEN); SessionCommit (); } catch (Exception ex) { SessionRollBack (); if (ex is PalmeralGenNHibernate.Exceptions.ModelException) throw ex; throw new PalmeralGenNHibernate.Exceptions.DataLayerException ("Error in InstalacionCAD.", ex); } finally { SessionClose (); } } public void Eliminar (string id) { try { SessionInitializeTransaction (); InstalacionEN instalacionEN = (InstalacionEN)session.Load (typeof(InstalacionEN), id); session.Delete (instalacionEN); SessionCommit (); } catch (Exception ex) { SessionRollBack (); if (ex is PalmeralGenNHibernate.Exceptions.ModelException) throw ex; throw new PalmeralGenNHibernate.Exceptions.DataLayerException ("Error in InstalacionCAD.", ex); } finally { SessionClose (); } } public System.Collections.Generic.IList<PalmeralGenNHibernate.EN.Default_.InstalacionEN> BuscarInstalacionesCliente (string p_cliente) { System.Collections.Generic.IList<PalmeralGenNHibernate.EN.Default_.InstalacionEN> result; try { SessionInitializeTransaction (); //String sql = @"FROM InstalacionEN self where FROM InstalacionEN AS ins WHERE ins.Cliente LIKE CONCAT('%', :p_cliente , '%')"; //IQuery query = session.CreateQuery(sql); IQuery query = (IQuery)session.GetNamedQuery ("InstalacionENbuscarInstalacionesClienteHQL"); query.SetParameter ("p_cliente", p_cliente); result = query.List<PalmeralGenNHibernate.EN.Default_.InstalacionEN>(); SessionCommit (); } catch (Exception ex) { SessionRollBack (); if (ex is PalmeralGenNHibernate.Exceptions.ModelException) throw ex; throw new PalmeralGenNHibernate.Exceptions.DataLayerException ("Error in InstalacionCAD.", ex); } finally { SessionClose (); } return result; } public InstalacionEN ObtenerInstalacion (string id) { InstalacionEN instalacionEN = null; try { SessionInitializeTransaction (); instalacionEN = (InstalacionEN)session.Get (typeof(InstalacionEN), id); SessionCommit (); } catch (Exception ex) { SessionRollBack (); if (ex is PalmeralGenNHibernate.Exceptions.ModelException) throw ex; throw new PalmeralGenNHibernate.Exceptions.DataLayerException ("Error in InstalacionCAD.", ex); } finally { SessionClose (); } return instalacionEN; } public System.Collections.Generic.IList<InstalacionEN> ObtenerTodas (int first, int size) { System.Collections.Generic.IList<InstalacionEN> result = null; try { SessionInitializeTransaction (); if (size > 0) result = session.CreateCriteria (typeof(InstalacionEN)). SetFirstResult (first).SetMaxResults (size).List<InstalacionEN>(); else result = session.CreateCriteria (typeof(InstalacionEN)).List<InstalacionEN>(); SessionCommit (); } catch (Exception ex) { SessionRollBack (); if (ex is PalmeralGenNHibernate.Exceptions.ModelException) throw ex; throw new PalmeralGenNHibernate.Exceptions.DataLayerException ("Error in InstalacionCAD.", ex); } finally { SessionClose (); } return result; } public void Relationer_cliente (string p_instalacion, string p_cliente) { PalmeralGenNHibernate.EN.Default_.InstalacionEN instalacionEN = null; try { SessionInitializeTransaction (); instalacionEN = (InstalacionEN)session.Load (typeof(InstalacionEN), p_instalacion); instalacionEN.Cliente = (PalmeralGenNHibernate.EN.Default_.ClienteEN)session.Load (typeof(PalmeralGenNHibernate.EN.Default_.ClienteEN), p_cliente); instalacionEN.Cliente.Instalaciones.Add (instalacionEN); session.Update (instalacionEN); SessionCommit (); } catch (Exception ex) { SessionRollBack (); if (ex is PalmeralGenNHibernate.Exceptions.ModelException) throw ex; throw new PalmeralGenNHibernate.Exceptions.DataLayerException ("Error in InstalacionCAD.", ex); } finally { SessionClose (); } } public void Relationer_facturas (string p_instalacion, System.Collections.Generic.IList<string> p_factura) { PalmeralGenNHibernate.EN.Default_.InstalacionEN instalacionEN = null; try { SessionInitializeTransaction (); instalacionEN = (InstalacionEN)session.Load (typeof(InstalacionEN), p_instalacion); PalmeralGenNHibernate.EN.Default_.FacturaEN facturasENAux = null; if (instalacionEN.Facturas == null) { instalacionEN.Facturas = new System.Collections.Generic.List<PalmeralGenNHibernate.EN.Default_.FacturaEN>(); } foreach (string item in p_factura) { facturasENAux = new PalmeralGenNHibernate.EN.Default_.FacturaEN (); facturasENAux = (PalmeralGenNHibernate.EN.Default_.FacturaEN)session.Load (typeof(PalmeralGenNHibernate.EN.Default_.FacturaEN), item); facturasENAux.Instalacion = instalacionEN; instalacionEN.Facturas.Add (facturasENAux); } session.Update (instalacionEN); SessionCommit (); } catch (Exception ex) { SessionRollBack (); if (ex is PalmeralGenNHibernate.Exceptions.ModelException) throw ex; throw new PalmeralGenNHibernate.Exceptions.DataLayerException ("Error in InstalacionCAD.", ex); } finally { SessionClose (); } } public void Relationer_jornadas (string p_instalacion, System.Collections.Generic.IList<int> p_jornadafecha) { PalmeralGenNHibernate.EN.Default_.InstalacionEN instalacionEN = null; try { SessionInitializeTransaction (); instalacionEN = (InstalacionEN)session.Load (typeof(InstalacionEN), p_instalacion); PalmeralGenNHibernate.EN.Default_.JornadaFechaEN jornadasENAux = null; if (instalacionEN.Jornadas == null) { instalacionEN.Jornadas = new System.Collections.Generic.List<PalmeralGenNHibernate.EN.Default_.JornadaFechaEN>(); } foreach (int item in p_jornadafecha) { jornadasENAux = new PalmeralGenNHibernate.EN.Default_.JornadaFechaEN (); jornadasENAux = (PalmeralGenNHibernate.EN.Default_.JornadaFechaEN)session.Load (typeof(PalmeralGenNHibernate.EN.Default_.JornadaFechaEN), item); jornadasENAux.Instalacion = instalacionEN; instalacionEN.Jornadas.Add (jornadasENAux); } session.Update (instalacionEN); SessionCommit (); } catch (Exception ex) { SessionRollBack (); if (ex is PalmeralGenNHibernate.Exceptions.ModelException) throw ex; throw new PalmeralGenNHibernate.Exceptions.DataLayerException ("Error in InstalacionCAD.", ex); } finally { SessionClose (); } } public void Unrelationer_cliente (string p_instalacion, string p_cliente) { try { SessionInitializeTransaction (); PalmeralGenNHibernate.EN.Default_.InstalacionEN instalacionEN = null; instalacionEN = (InstalacionEN)session.Load (typeof(InstalacionEN), p_instalacion); if (instalacionEN.Cliente.Nif == p_cliente) { instalacionEN.Cliente = null; } else throw new ModelException ("The identifier " + p_cliente + " in p_cliente you are trying to unrelationer, doesn't exist in InstalacionEN"); session.Update (instalacionEN); SessionCommit (); } catch (Exception ex) { SessionRollBack (); if (ex is PalmeralGenNHibernate.Exceptions.ModelException) throw ex; throw new PalmeralGenNHibernate.Exceptions.DataLayerException ("Error in InstalacionCAD.", ex); } finally { SessionClose (); } } public void Unrelationer_facturas (string p_instalacion, System.Collections.Generic.IList<string> p_factura) { try { SessionInitializeTransaction (); PalmeralGenNHibernate.EN.Default_.InstalacionEN instalacionEN = null; instalacionEN = (InstalacionEN)session.Load (typeof(InstalacionEN), p_instalacion); PalmeralGenNHibernate.EN.Default_.FacturaEN facturasENAux = null; if (instalacionEN.Facturas != null) { foreach (string item in p_factura) { facturasENAux = (PalmeralGenNHibernate.EN.Default_.FacturaEN)session.Load (typeof(PalmeralGenNHibernate.EN.Default_.FacturaEN), item); if (instalacionEN.Facturas.Contains (facturasENAux) == true) { instalacionEN.Facturas.Remove (facturasENAux); facturasENAux.Instalacion = null; } else throw new ModelException ("The identifier " + item + " in p_factura you are trying to unrelationer, doesn't exist in InstalacionEN"); } } session.Update (instalacionEN); SessionCommit (); } catch (Exception ex) { SessionRollBack (); if (ex is PalmeralGenNHibernate.Exceptions.ModelException) throw ex; throw new PalmeralGenNHibernate.Exceptions.DataLayerException ("Error in InstalacionCAD.", ex); } finally { SessionClose (); } } public void Unrelationer_jornadas (string p_instalacion, System.Collections.Generic.IList<int> p_jornadafecha) { try { SessionInitializeTransaction (); PalmeralGenNHibernate.EN.Default_.InstalacionEN instalacionEN = null; instalacionEN = (InstalacionEN)session.Load (typeof(InstalacionEN), p_instalacion); PalmeralGenNHibernate.EN.Default_.JornadaFechaEN jornadasENAux = null; if (instalacionEN.Jornadas != null) { foreach (int item in p_jornadafecha) { jornadasENAux = (PalmeralGenNHibernate.EN.Default_.JornadaFechaEN)session.Load (typeof(PalmeralGenNHibernate.EN.Default_.JornadaFechaEN), item); if (instalacionEN.Jornadas.Contains (jornadasENAux) == true) { instalacionEN.Jornadas.Remove (jornadasENAux); jornadasENAux.Instalacion = null; } else throw new ModelException ("The identifier " + item + " in p_jornadafecha you are trying to unrelationer, doesn't exist in InstalacionEN"); } } session.Update (instalacionEN); SessionCommit (); } catch (Exception ex) { SessionRollBack (); if (ex is PalmeralGenNHibernate.Exceptions.ModelException) throw ex; throw new PalmeralGenNHibernate.Exceptions.DataLayerException ("Error in InstalacionCAD.", ex); } finally { SessionClose (); } } } }
using UnityEngine; using System; using System.IO; using System.Collections; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Linq; /// <para> /// MATBinding wraps Android, iOS, and Windows Phone 8 MobileAppTracking SDK /// functions to be used within Unity. The functions can be called within any /// C# script by typing MATBinding.*. /// </para> namespace MATSDK { public class MATBinding : MonoBehaviour { /// <para> /// Initializes relevant information about the advertiser and /// conversion key on startup of Unity game. /// </para> /// <param name="advertiserId">the MAT advertiser ID for the app</param> /// <param name="conversionKey">the MAT advertiser key for the app</param> public static void Init(string advertiserId, string conversionKey) { if(!Application.isEditor) { #if UNITY_ANDROID MATAndroid.Instance.Init(advertiserId, conversionKey); #endif #if UNITY_IPHONE MATExterns.MATInit(advertiserId, conversionKey); #if UNITY_5_0 MATExterns.MATSetAppleAdvertisingIdentifier(UnityEngine.iOS.Device.advertisingIdentifier, UnityEngine.iOS.Device.advertisingTrackingEnabled); #else MATExterns.MATSetAppleAdvertisingIdentifier(UnityEngine.iOS.Device.advertisingIdentifier, UnityEngine.iOS.Device.advertisingTrackingEnabled); #endif #endif #if UNITY_WP8 MATWP8.MobileAppTracker.Instance.InitializeValues(advertiserId, conversionKey); #endif #if UNITY_METRO MATWinStore.MobileAppTracker.Instance.InitializeValues(advertiserId, conversionKey); #endif } } /// <para> /// Check if a deferred deep-link is available. /// </para> /// <param name="timeoutMillis">timeout duration in milliseconds</param> public static void CheckForDeferredDeeplinkWithTimeout(double timeoutMillis) { if(!Application.isEditor) { #if UNITY_ANDROID MATAndroid.Instance.SetDeferredDeeplink(true, (int)timeoutMillis); #endif #if UNITY_IPHONE MATExterns.MATCheckForDeferredDeeplinkWithTimeout(timeoutMillis); #endif #if UNITY_WP8 //MATWP8.MobileAppTracker.Instance.CheckForDeferredDeeplinkWithTimeout(timeoutMillis); #endif #if UNITY_METRO //MATWinStore.MobileAppTracker.Instance.CheckForDeferredDeeplinkWithTimeout(timeoutMillis); #endif } } /// <para> /// Enable auto-measurement of successful in-app-purchase (IAP) transactions as "purhcase" events in iOS. /// </para> /// <param name="automate">should auto-measure IAP transactions</param> public static void AutomateIapEventMeasurement(bool automate) { if(!Application.isEditor) { #if UNITY_IPHONE MATExterns.MATAutomateIapEventMeasurement(automate); #endif } } /// <para> /// Event measurement function, by event name. /// </para> /// <param name="eventName">event name in MAT system</param> public static void MeasureEvent(string eventName) { if(!Application.isEditor) { #if UNITY_ANDROID MATAndroid.Instance.MeasureEvent(eventName); #endif #if UNITY_IPHONE MATExterns.MATMeasureEventName(eventName); #endif #if UNITY_WP8 MATWP8.MobileAppTracker.Instance.MeasureAction(eventName); #endif #if UNITY_METRO MATWinStore.MobileAppTracker.Instance.MeasureAction(eventName); #endif } } /// <para> /// Measures the event with MATEvent. /// </para> /// <param name="matEvent">MATEvent object of event values to measure</param> public static void MeasureEvent(MATEvent matEvent) { if(!Application.isEditor) { int itemCount = null == matEvent.eventItems ? 0 : matEvent.eventItems.Length; #if UNITY_ANDROID MATAndroid.Instance.MeasureEvent(matEvent); #endif #if (UNITY_WP8 || UNITY_METRO) // Set event characteristic values separately SetEventContentType(matEvent.contentType); SetEventContentId(matEvent.contentId); if (matEvent.level != null) { SetEventLevel((int)matEvent.level); } if (matEvent.quantity != null) { SetEventQuantity((int)matEvent.quantity); } SetEventSearchString(matEvent.searchString); if (matEvent.rating != null) { SetEventRating((float)matEvent.rating); } if (matEvent.date1 != null) { SetEventDate1((DateTime)matEvent.date1); } if (matEvent.date2 != null) { SetEventDate2((DateTime)matEvent.date2); } SetEventAttribute1(matEvent.attribute1); SetEventAttribute2(matEvent.attribute2); SetEventAttribute3(matEvent.attribute3); SetEventAttribute4(matEvent.attribute4); SetEventAttribute5(matEvent.attribute5); #endif #if UNITY_IPHONE MATEventIos eventIos = new MATEventIos(matEvent); byte[] receiptBytes = null == matEvent.receipt ? null : System.Convert.FromBase64String(matEvent.receipt); int receiptByteCount = null == receiptBytes ? 0 : receiptBytes.Length; // Convert MATItem to C-marshallable struct MATItemIos MATItemIos[] items = new MATItemIos[itemCount]; for (int i = 0; i < itemCount; i++) { items[i] = new MATItemIos(matEvent.eventItems[i]); } MATExterns.MATMeasureEvent(eventIos, items, itemCount, receiptBytes, receiptByteCount); #endif #if UNITY_WP8 //Convert MATItem[] to MATEventItem[]. These are the same things, but must be converted for recognition of //MobileAppTracker.cs. MATWP8.MATEventItem[] newarr = new MATWP8.MATEventItem[itemCount]; //Conversion is necessary to prevent the need of referencing a separate class. for(int i = 0; i < itemCount; i++) { MATItem item = matEvent.eventItems[i]; newarr[i] = new MATWP8.MATEventItem(item.name, item.quantity == null? 0 : (int)item.quantity, item.unitPrice == null? 0 : (double)item.unitPrice, item.revenue == null? 0 : (double)item.revenue, item.attribute1, item.attribute2, item.attribute3, item.attribute4, item.attribute5); } List<MATWP8.MATEventItem> list = newarr.ToList(); MATWP8.MobileAppTracker.Instance.MeasureAction(matEvent.name, matEvent.revenue == null? 0 : (double)matEvent.revenue, matEvent.currencyCode, matEvent.advertiserRefId, list); #endif #if UNITY_METRO MATWinStore.MATEventItem[] newarr = new MATWinStore.MATEventItem[itemCount]; for(int i = 0; i < itemCount; i++) { MATItem item = matEvent.eventItems[i]; newarr[i] = new MATWinStore.MATEventItem(item.name, item.quantity == null? 0 : (int)item.quantity, item.unitPrice == null? 0 : (double)item.unitPrice, item.revenue == null? 0 : (double)item.revenue, item.attribute1, item.attribute2, item.attribute3, item.attribute4, item.attribute5); } List<MATWinStore.MATEventItem> list = newarr.ToList(); MATWinStore.MobileAppTracker.Instance.MeasureAction(matEvent.name, matEvent.revenue == null? 0 : (double)matEvent.revenue, matEvent.currencyCode, matEvent.advertiserRefId, list); #endif } } /// <para> /// Main session measurement function; this function should be called at every app open. /// </para> public static void MeasureSession() { if(!Application.isEditor) { #if UNITY_ANDROID MATAndroid.Instance.MeasureSession(); #endif #if UNITY_IPHONE MATExterns.MATMeasureSession(); #endif #if UNITY_WP8 MATWP8.MobileAppTracker.Instance.MeasureSession(); #endif #if UNITY_METRO MATWinStore.MobileAppTracker.Instance.MeasureSession(); #endif } } ///////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////// /*----------------------------------Setters--------------------------------*/ ///////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////// /// <para> /// Sets the user's age. /// </para> /// <param name="age">User age to track in MAT</param> public static void SetAge(int age) { if(!Application.isEditor) { #if UNITY_ANDROID MATAndroid.Instance.SetAge(age); #endif #if UNITY_IPHONE MATExterns.MATSetAge(age); #endif #if UNITY_WP8 MATWP8.MobileAppTracker.Instance.SetAge(age); #endif #if UNITY_METRO MATWinStore.MobileAppTracker.Instance.SetAge(age); #endif } } /// <para> /// Enables acceptance of duplicate installs from this device. /// </para> /// <param name="allow">whether to allow duplicate installs from device</param> public static void SetAllowDuplicates(bool allow) { if(!Application.isEditor) { #if UNITY_ANDROID MATAndroid.Instance.SetAllowDuplicates(allow); #endif #if UNITY_IPHONE MATExterns.MATSetAllowDuplicates(allow); #endif #if UNITY_WP8 MATWP8.MobileAppTracker.Instance.SetAllowDuplicates(allow); #endif #if UNITY_METRO MATWinStore.MobileAppTracker.Instance.SetAllowDuplicates(allow); #endif } } ///<para>Sets whether app-level ad tracking is enabled.</para> ///<param name="adTrackingEnabled">true if user has opted out of ad tracking at the app-level, false if not</param> public static void SetAppAdTracking(bool adTrackingEnabled) { if(!Application.isEditor) { #if UNITY_ANDROID MATAndroid.Instance.SetAppAdTracking(adTrackingEnabled); #endif #if UNITY_IPHONE MATExterns.MATSetAppAdTracking(adTrackingEnabled); #endif #if UNITY_WP8 MATWP8.MobileAppTracker.Instance.SetAppAdTracking(adTrackingEnabled); #endif #if UNITY_METRO MATWinStore.MobileAppTracker.Instance.SetAppAdTracking(adTrackingEnabled); #endif } } /// <para> /// Turns debug mode on or off, under tag "MobileAppTracker". /// </para> /// <param name="debug">whether to enable debug output</param> public static void SetDebugMode(bool debug) { if(!Application.isEditor) { #if UNITY_ANDROID MATAndroid.Instance.SetDebugMode(debug); #endif #if UNITY_IPHONE MATExterns.MATSetDebugMode(debug); #endif #if UNITY_WP8 MATWP8.MobileAppTracker.Instance.SetDebugMode(debug); #endif #if UNITY_METRO MATWinStore.MobileAppTracker.Instance.SetDebugMode(debug); #endif } } /// <para> /// Sets the first attribute associated with an app event. /// </para> /// <param name="eventAttribute">the attribute</param> private static void SetEventAttribute1(string eventAttribute) { if(!Application.isEditor) { #if UNITY_WP8 MATWP8.MobileAppTracker.Instance.SetEventAttribute1(eventAttribute); #endif #if UNITY_METRO MATWinStore.MobileAppTracker.Instance.SetEventAttribute1(eventAttribute); #endif } } /// <para> /// Sets the second attribute associated with an app event. /// </para> /// <param name="eventAttribute">the attribute</param> private static void SetEventAttribute2(string eventAttribute) { if(!Application.isEditor) { #if UNITY_WP8 MATWP8.MobileAppTracker.Instance.SetEventAttribute2(eventAttribute); #endif #if UNITY_METRO MATWinStore.MobileAppTracker.Instance.SetEventAttribute2(eventAttribute); #endif } } /// <para> /// Sets the third attribute associated with an app event. /// </para> /// <param name="eventAttribute">the attribute</param> private static void SetEventAttribute3(string eventAttribute) { if(!Application.isEditor) { #if UNITY_WP8 MATWP8.MobileAppTracker.Instance.SetEventAttribute3(eventAttribute); #endif #if UNITY_METRO MATWinStore.MobileAppTracker.Instance.SetEventAttribute3(eventAttribute); #endif } } /// <para> /// Sets the fourth attribute associated with an app event. /// </para> /// <param name="eventAttribute">the attribute</param> private static void SetEventAttribute4(string eventAttribute) { if(!Application.isEditor) { #if UNITY_WP8 MATWP8.MobileAppTracker.Instance.SetEventAttribute4(eventAttribute); #endif #if UNITY_METRO MATWinStore.MobileAppTracker.Instance.SetEventAttribute4(eventAttribute); #endif } } /// <para> /// Sets the fifth attribute associated with an app event. /// </para> /// <param name="eventAttribute">the attribute</param> private static void SetEventAttribute5(string eventAttribute) { if(!Application.isEditor) { #if UNITY_WP8 MATWP8.MobileAppTracker.Instance.SetEventAttribute5(eventAttribute); #endif #if UNITY_METRO MATWinStore.MobileAppTracker.Instance.SetEventAttribute5(eventAttribute); #endif } } /// <para> /// Sets the content ID associated with an app event. /// </para> /// <param name="eventContentId">the content ID</param> private static void SetEventContentId(string eventContentId) { if(!Application.isEditor) { #if UNITY_WP8 MATWP8.MobileAppTracker.Instance.SetEventContentId(eventContentId); #endif #if UNITY_METRO MATWinStore.MobileAppTracker.Instance.SetEventContentId(eventContentId); #endif } } /// <para> /// Sets the content type associated with an app event. /// </para> /// <param name="eventContentType">the content type</param> private static void SetEventContentType(string eventContentType) { if(!Application.isEditor) { #if UNITY_WP8 MATWP8.MobileAppTracker.Instance.SetEventContentType(eventContentType); #endif #if UNITY_METRO MATWinStore.MobileAppTracker.Instance.SetEventContentType(eventContentType); #endif } } /// <para> /// Sets the first date associated with an app event. /// Should be 1/1/1970 and after. /// </para> /// <param name="eventDate">the date</param> private static void SetEventDate1(DateTime eventDate) { if(!Application.isEditor) { #if (UNITY_WP8 || UNITY_METRO) double milliseconds = new TimeSpan(eventDate.Ticks).TotalMilliseconds; //datetime starts in 1970 DateTime datetime = new DateTime(1970, 1, 1); double millisecondsFrom1970 = milliseconds - (new TimeSpan(datetime.Ticks)).TotalMilliseconds; TimeSpan timeFrom1970 = TimeSpan.FromMilliseconds(millisecondsFrom1970); //Update to current time for c# datetime = datetime.Add(timeFrom1970); #if UNITY_WP8 MATWP8.MobileAppTracker.Instance.SetEventDate1(datetime); #endif #if UNITY_METRO MATWinStore.MobileAppTracker.Instance.SetEventDate1(datetime); #endif #endif } } /// <para> /// Sets the second date associated with an app event. /// </para> /// <param name="eventDate">the date.</param> private static void SetEventDate2(DateTime eventDate) { if(!Application.isEditor) { #if (UNITY_WP8 || UNITY_METRO) double milliseconds = new TimeSpan(eventDate.Ticks).TotalMilliseconds; //datetime starts in 1970 DateTime datetime = new DateTime(1970, 1, 1); double millisecondsFrom1970 = milliseconds - (new TimeSpan(datetime.Ticks)).TotalMilliseconds; TimeSpan timeFrom1970 = TimeSpan.FromMilliseconds(millisecondsFrom1970); //Update to current time for c# datetime = datetime.Add(timeFrom1970); #if UNITY_WP8 MATWP8.MobileAppTracker.Instance.SetEventDate2(datetime); #endif #if UNITY_METRO MATWinStore.MobileAppTracker.Instance.SetEventDate2(datetime); #endif #endif } } /// <para> /// Sets the level associated with an app event. /// </para> /// <param name="eventLevel">the level</param> private static void SetEventLevel(int eventLevel) { if(!Application.isEditor) { #if UNITY_WP8 MATWP8.MobileAppTracker.Instance.SetEventLevel(eventLevel); #endif #if UNITY_METRO MATWinStore.MobileAppTracker.Instance.SetEventLevel(eventLevel); #endif } } /// <para> /// Sets the quantity associated with an app event. /// </para> /// <param name="eventQuantity">the quantity</param> private static void SetEventQuantity(int eventQuantity) { if(!Application.isEditor) { #if UNITY_WP8 MATWP8.MobileAppTracker.Instance.SetEventQuantity(eventQuantity); #endif #if UNITY_METRO MATWinStore.MobileAppTracker.Instance.SetEventQuantity(eventQuantity); #endif } } /// <para> /// Sets the rating associated with an app event. /// </para> /// <param name="eventRating">the rating</param> private static void SetEventRating(float eventRating) { if(!Application.isEditor) { #if UNITY_WP8 MATWP8.MobileAppTracker.Instance.SetEventRating(eventRating); #endif #if UNITY_METRO MATWinStore.MobileAppTracker.Instance.SetEventRating(eventRating); #endif } } /// <para> /// Sets the search string associated with an app event. /// </para> /// <param name="eventSearchString">the search string</param> private static void SetEventSearchString(string eventSearchString) { if(!Application.isEditor) { #if UNITY_WP8 MATWP8.MobileAppTracker.Instance.SetEventSearchString(eventSearchString); #endif #if UNITY_METRO MATWinStore.MobileAppTracker.Instance.SetEventSearchString(eventSearchString); #endif } } /// <para> /// Sets whether app was previously installed prior to version with MAT SDK. /// </para> /// <param name="isExistingUser"> /// existing true if this user already had the app installed prior to updating to MAT version /// </param> public static void SetExistingUser(bool isExistingUser) { if(!Application.isEditor) { #if UNITY_IPHONE MATExterns.MATSetExistingUser(isExistingUser); #endif #if UNITY_WP8 MATWP8.MobileAppTracker.Instance.SetExistingUser(isExistingUser); #endif #if UNITY_METRO MATWinStore.MobileAppTracker.Instance.SetExistingUser(isExistingUser); #endif } } /// <para> /// Set whether the MAT events should also be logged to the Facebook SDK. This flag is ignored if the Facebook SDK is not present. /// </para> /// <param name="enable">Whether to send MAT events to FB as well</param> /// <param name="limitEventAndDataUsabe">Whether data such as that generated through FBAppEvents and sent to Facebook should be restricted from being used for other than analytics and conversions. Defaults to NO. This value is stored on the device and persists across app launches.</param> public static void SetFacebookEventLogging(bool enable, bool limit) { if(!Application.isEditor) { #if UNITY_ANDROID MATAndroid.Instance.SetFacebookEventLogging(enable, limit); #endif #if UNITY_IPHONE MATExterns.MATSetFacebookEventLogging(enable, limit); #endif #if UNITY_WP8 //MATWP8.MobileAppTracker.Instance.SetFacebookEventLogging(enable, limit); #endif #if UNITY_METRO //MATWinStore.MobileAppTracker.Instance.SetFacebookEventLogging(enable, limit); #endif } } /// <para> /// Sets the user ID to associate with Facebook. /// </para> /// <param name="fbUserId">Facebook User ID</param> public static void SetFacebookUserId(string fbUserId) { if(!Application.isEditor) { #if UNITY_ANDROID MATAndroid.Instance.SetFacebookUserId(fbUserId); #endif #if UNITY_IPHONE MATExterns.MATSetFacebookUserId(fbUserId); #endif #if UNITY_WP8 MATWP8.MobileAppTracker.Instance.SetFacebookUserId(fbUserId); #endif #if UNITY_METRO MATWinStore.MobileAppTracker.Instance.SetFacebookUserId(fbUserId); #endif } } /// <para> /// Sets the user gender. /// </para> /// <param name="gender">use MobileAppTracker.GENDER_MALE, MobileAppTracker.GENDER_FEMALE</param> public static void SetGender(int gender) { if(!Application.isEditor) { #if UNITY_ANDROID MATAndroid.Instance.SetGender(gender); #endif #if UNITY_IPHONE MATExterns.MATSetGender(gender); #endif #if UNITY_WP8 MATWP8.MATGender gender_temp; if(gender == 0) gender_temp = MATWP8.MATGender.MALE; else if (gender == 1) gender_temp = MATWP8.MATGender.FEMALE; else gender_temp = MATWP8.MATGender.NONE; MATWP8.MobileAppTracker.Instance.SetGender(gender_temp); #endif #if UNITY_METRO MATWinStore.MATGender gender_temp; if(gender == 0) gender_temp = MATWinStore.MATGender.MALE; else if (gender == 1) gender_temp = MATWinStore.MATGender.FEMALE; else gender_temp = MATWinStore.MATGender.NONE; MATWinStore.MobileAppTracker.Instance.SetGender(gender_temp); #endif } } /// <para> /// Sets the user ID to associate with Google. /// </para> /// <param name="googleUserId">Google user ID.</param> public static void SetGoogleUserId(string googleUserId) { if(!Application.isEditor) { #if UNITY_ANDROID MATAndroid.Instance.SetGoogleUserId(googleUserId); #endif #if UNITY_IPHONE MATExterns.MATSetGoogleUserId(googleUserId); #endif #if UNITY_WP8 MATWP8.MobileAppTracker.Instance.SetGoogleUserId(googleUserId); #endif #if UNITY_METRO MATWinStore.MobileAppTracker.Instance.SetGoogleUserId(googleUserId); #endif } } /// <para> /// Sets the user's latitude, longitude, and altitude. /// </para> /// <param name="latitude">user's latitude</param> /// <param name="longitude">user's longitude</param> /// <param name="altitude">user's altitude</param> public static void SetLocation(double latitude, double longitude, double altitude) { if(!Application.isEditor) { #if UNITY_ANDROID MATAndroid.Instance.SetLocation(latitude, longitude, altitude); #endif #if UNITY_IPHONE MATExterns.MATSetLocation(latitude, longitude, altitude); #endif #if UNITY_WP8 MATWP8.MobileAppTracker.Instance.SetLatitude(latitude); MATWP8.MobileAppTracker.Instance.SetLongitude(longitude); MATWP8.MobileAppTracker.Instance.SetAltitude(altitude); #endif #if UNITY_METRO MATWinStore.MobileAppTracker.Instance.SetLatitude(latitude); MATWinStore.MobileAppTracker.Instance.SetLongitude(longitude); MATWinStore.MobileAppTracker.Instance.SetAltitude(altitude); #endif } } /// <para> /// Sets the name of the package. /// </para> /// <param name="packageName">Package name</param> public static void SetPackageName(string packageName) { if(!Application.isEditor) { #if UNITY_ANDROID MATAndroid.Instance.SetPackageName(packageName); #endif #if UNITY_IPHONE MATExterns.MATSetPackageName(packageName); #endif #if UNITY_WP8 MATWP8.MobileAppTracker.Instance.SetPackageName(packageName); #endif #if UNITY_METRO MATWinStore.MobileAppTracker.Instance.SetPackageName(packageName); #endif } } /// <para> /// Set whether the user is generating revenue for the app or not. /// If measureAction is called with a non-zero revenue, this is automatically set to true. /// </para> /// <param name="isPayingUser">true if the user is revenue-generating, false if not</param> public static void SetPayingUser(bool isPayingUser) { if(!Application.isEditor) { #if UNITY_ANDROID MATAndroid.Instance.SetPayingUser(isPayingUser); #endif #if UNITY_IPHONE MATExterns.MATSetPayingUser(isPayingUser); #endif #if UNITY_WP8 MATWP8.MobileAppTracker.Instance.SetIsPayingUser(isPayingUser); #endif #if UNITY_METRO MATWinStore.MobileAppTracker.Instance.SetIsPayingUser(isPayingUser); #endif } } ///<para> ///Sets the custom user phone number. ///</para> ///<param name="phoneNumber">User's phone number</param> public static void SetPhoneNumber(string phoneNumber) { if(!Application.isEditor) { #if UNITY_ANDROID MATAndroid.Instance.SetPhoneNumber(phoneNumber); #endif #if UNITY_IPHONE MATExterns.MATSetPhoneNumber(phoneNumber); #endif // #if UNITY_WP8 // MATWP8.MobileAppTracker.Instance.SetPhoneNumber(phoneNumber); // #endif // #if UNITY_METRO // MATWinStore.MobileAppTracker.Instance.SetPhoneNumber(phoneNumber); // #endif } } ///<para> ///Sets the user ID to associate with Twitter. ///</para> ///<param name="twitterUserId">Twitter user ID</param> public static void SetTwitterUserId(string twitterUserId) { if(!Application.isEditor) { #if UNITY_ANDROID MATAndroid.Instance.SetTwitterUserId(twitterUserId); #endif #if UNITY_IPHONE MATExterns.MATSetTwitterUserId(twitterUserId); #endif #if UNITY_WP8 MATWP8.MobileAppTracker.Instance.SetTwitterUserId(twitterUserId); #endif #if UNITY_METRO MATWinStore.MobileAppTracker.Instance.SetTwitterUserId(twitterUserId); #endif } } ///<para> ///Sets the custom user email. ///</para> ///<param name="userEmail">User's email address</param> public static void SetUserEmail(string userEmail) { if(!Application.isEditor) { #if UNITY_ANDROID MATAndroid.Instance.SetUserEmail(userEmail); #endif #if UNITY_IPHONE MATExterns.MATSetUserEmail(userEmail); #endif #if UNITY_WP8 MATWP8.MobileAppTracker.Instance.SetUserEmail(userEmail); #endif #if UNITY_METRO MATWinStore.MobileAppTracker.Instance.SetUserEmail(userEmail); #endif } } /// <para> /// Sets the custom user ID. /// </para> /// <param name="userId">the new user ID</param> public static void SetUserId(string userId) { if(!Application.isEditor) { #if UNITY_ANDROID MATAndroid.Instance.SetUserId(userId); #endif #if UNITY_IPHONE MATExterns.MATSetUserId(userId); #endif #if UNITY_WP8 MATWP8.MobileAppTracker.Instance.SetUserId(userId); #endif #if UNITY_METRO MATWinStore.MobileAppTracker.Instance.SetUserId(userId); #endif } } ///<para> ///Sets the custom user name. ///</para> ///<param name="userName">User name</param> public static void SetUserName(string userName) { if(!Application.isEditor) { #if UNITY_ANDROID MATAndroid.Instance.SetUserName(userName); #endif #if UNITY_IPHONE MATExterns.MATSetUserName(userName); #endif #if UNITY_WP8 MATWP8.MobileAppTracker.Instance.SetUserName(userName); #endif #if UNITY_METRO MATWinStore.MobileAppTracker.Instance.SetUserName(userName); #endif } } ///////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////// /*--------------------------------Getters----------------------------------*/ ///////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////// /// <para> /// Gets whether the user is revenue-generating or not. /// </para> /// <returns>true if the user has produced revenue, false if not</returns> public static bool GetIsPayingUser() { if(!Application.isEditor) { #if UNITY_ANDROID return MATAndroid.Instance.GetIsPayingUser(); #endif #if UNITY_IPHONE return MATExterns.MATGetIsPayingUser(); #endif #if UNITY_WP8 return MATWP8.MobileAppTracker.Instance.GetIsPayingUser(); #endif #if UNITY_METRO return MATWinStore.MobileAppTracker.Instance.GetIsPayingUser(); #endif } return true; } /// <para> /// Gets the MAT ID generated on install. /// </para> /// <returns>MAT ID</returns> public static string GetMATId() { if(!Application.isEditor) { #if UNITY_ANDROID return MATAndroid.Instance.GetMatId(); #endif #if UNITY_IPHONE return MATExterns.MATGetMatId(); #endif #if UNITY_WP8 return MATWP8.MobileAppTracker.Instance.GetMatId(); #endif #if UNITY_METRO return MATWinStore.MobileAppTracker.Instance.GetMatId(); #endif } return string.Empty; } /// <para> /// Gets the first MAT open log ID. /// </para> /// <returns>first MAT open log ID</returns> public static string GetOpenLogId() { if(!Application.isEditor) { #if UNITY_ANDROID return MATAndroid.Instance.GetOpenLogId(); #endif #if UNITY_IPHONE return MATExterns.MATGetOpenLogId(); #endif #if UNITY_WP8 return MATWP8.MobileAppTracker.Instance.GetOpenLogId(); #endif #if UNITY_METRO return MATWinStore.MobileAppTracker.Instance.GetOpenLogId(); #endif } return string.Empty; } ///////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////// /*--------------------------iOS Specific Features--------------------------*/ ///////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////// /// <para> /// Sets the Apple Identifier For Advertising -- IDFA. /// Does nothing if not an iOS device. /// </para> /// <param name="advertiserIdentifier">Apple Identifier For Advertising -- IDFA</param> /// <param name="trackingEnabled"> /// A Boolean value that indicates whether the user has limited ad tracking /// </param> public static void SetAppleAdvertisingIdentifier(string advertiserIdentifier, bool trackingEnabled) { if(!Application.isEditor) { #if UNITY_IPHONE MATExterns.MATSetAppleAdvertisingIdentifier(advertiserIdentifier, trackingEnabled); #endif } } /// <para> /// Set the Apple Vendor Identifier available in iOS 6. /// Does nothing if not an iOS device. /// </para> /// <param name="vendorIdentifier">Apple Vendor Identifier</param> public static void SetAppleVendorIdentifier(string vendorIdentifier) { if(!Application.isEditor) { #if UNITY_IPHONE MATExterns.MATSetAppleVendorIdentifier(vendorIdentifier); #endif } } /// <para> /// Sets the jailbroken device flag. /// Does nothing if not an iOS device. /// </para> /// <param name="isJailbroken">The jailbroken device flag</param> public static void SetJailbroken(bool isJailbroken) { if(!Application.isEditor) { #if UNITY_IPHONE MATExterns.MATSetJailbroken(isJailbroken); #endif } } /// <para> /// Specifies if the sdk should auto detect if the iOS device is jailbroken. /// Does nothing if not an iOS device. /// </para> /// <param name="isAutoDetectJailbroken"> /// Will detect if the device is jailbroken if set to true. Defaults to true. /// </param> public static void SetShouldAutoDetectJailbroken(bool isAutoDetectJailbroken) { if(!Application.isEditor) { #if UNITY_IPHONE MATExterns.MATSetShouldAutoDetectJailbroken(isAutoDetectJailbroken); #endif } } /// <para> /// Specifies if the sdk should pull the Apple Vendor Identifier from the device. /// Does nothing if not iOS device. /// </para> /// <param name="shouldAutoGenerate">True if yes, false if no.</param> public static void SetShouldAutoGenerateVendorIdentifier(bool shouldAutoGenerate) { if(!Application.isEditor) { #if UNITY_IPHONE MATExterns.MATSetShouldAutoGenerateAppleVendorIdentifier(shouldAutoGenerate); #endif } } /// <para> /// Sets the use cookie tracking. Not used by default. /// Does nothing if not an iOS device. /// </para> /// <param name="useCookieTracking">True if yes, false if no.</param> public static void SetUseCookieTracking(bool useCookieTracking) { if(!Application.isEditor) { #if UNITY_IPHONE MATExterns.MATSetUseCookieTracking(useCookieTracking); #endif } } ///////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////// /*-----------------------Android Specific Features-------------------------*/ ///////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////// /// <para> /// Sets the ANDROID_ID. /// Does nothing if not an Android device. /// </para> /// <param name="androidId">Device ANDROID_ID</param> public static void SetAndroidId(string androidId) { if(!Application.isEditor) { #if UNITY_ANDROID MATAndroid.Instance.SetAndroidId(androidId); #endif } } /// <para> /// Sets the ANDROID_ID MD5 hash. /// Does nothing if not an Android device. /// </para> /// <param name="androidIdMd5">Device ANDROID_ID MD5 hash</param> public static void SetAndroidIdMd5(string androidIdMd5) { if(!Application.isEditor) { #if UNITY_ANDROID MATAndroid.Instance.SetAndroidIdMd5(androidIdMd5); #endif } } /// <para> /// Sets the ANDROID_ID SHA-1 hash. /// Does nothing if not an Android device. /// </para> /// <param name="androidIdSha1">Device ANDROID_ID SHA-1 hash</param> public static void SetAndroidIdSha1(string androidIdSha1) { if(!Application.isEditor) { #if UNITY_ANDROID MATAndroid.Instance.SetAndroidIdSha1(androidIdSha1); #endif } } /// <para> /// Sets the ANDROID_ID SHA-256 hash. /// Does nothing if not an Android device. /// </para> /// <param name="androidIdSha256">Device ANDROID_ID SHA-256 hash</param> public static void SetAndroidIdSha256(string androidIdSha256) { if(!Application.isEditor) { #if UNITY_ANDROID MATAndroid.Instance.SetAndroidIdSha256(androidIdSha256); #endif } } /// <para> /// Sets the device IMEI/MEID. /// Does nothing if not an Android device. /// </para> /// <param name="deviceId">Device IMEI/MEID</param> public static void SetDeviceId(string deviceId) { if(!Application.isEditor) { #if UNITY_ANDROID MATAndroid.Instance.SetDeviceId(deviceId); #endif } } /// <para> /// Enables or disables primary Gmail address collection. /// Requires GET_ACCOUNTS permission. /// Does nothing if not an Android device. /// </para> /// <param name="collectEmail">Whether to collect device email address</param> public static void SetEmailCollection(bool collectEmail) { if(!Application.isEditor) { #if UNITY_ANDROID MATAndroid.Instance.SetEmailCollection(collectEmail); #endif } } /// <para> /// Sets the device MAC address. /// Does nothing if not an Android device. /// </para> /// <param name="macAddress">Device MAC address</param> public static void SetMacAddress(string macAddress) { if(!Application.isEditor) { #if UNITY_ANDROID MATAndroid.Instance.SetMacAddress(macAddress); #endif } } /// <para> /// Sets the Google Play Services Advertising ID. /// Does nothing if not an Android device. /// </para> /// <param name="adId">Google Play advertising ID</param> /// <param name="isLATEnabled"> /// whether user has requested to limit use of the Google ad ID /// </param> public static void SetGoogleAdvertisingId(string adId, bool isLATEnabled) { if(!Application.isEditor) { #if UNITY_ANDROID MATAndroid.Instance.SetGoogleAdvertisingId(adId, isLATEnabled); #endif } } /// <para> /// Sets the preloaded app attribution values (publisher information). /// Does nothing if not an Android or iOS device. /// </para> /// <param name="preloadData">Preloaded app attribution values (publisher information)</param> public static void SetPreloadedApp(MATPreloadData preloadData) { if(!Application.isEditor) { #if UNITY_ANDROID MATAndroid.Instance.SetPreloadedApp(preloadData); #endif #if UNITY_IPHONE MATExterns.MATSetPreloadData(preloadData); #endif } } ///////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////// /*---------------------Windows Phone 8 Specific Features-------------------*/ ///////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////// /// <para> /// Sets the name of the app. /// Does nothing if not a Windows Phone 8 device. /// </para> /// <param name="appName">App name</param> public static void SetAppName(string appName) { if(!Application.isEditor) { #if UNITY_WP8 MATWP8.MobileAppTracker.Instance.SetAppName(appName); #endif } } /// <para> /// Sets the app version. /// Does nothing if not a Windows Phone 8 device. /// </para> /// <param name="appVersion">App version</param> public static void SetAppVersion(string appVersion) { if(!Application.isEditor) { #if UNITY_WP8 MATWP8.MobileAppTracker.Instance.SetAppVersion(appVersion); #endif } } /// <para> /// Sets the last open log ID. /// Does nothing if not a Windows Phone 8 device. /// </para> /// <param name="lastOpenLogId">Last open log ID</param> public static void SetLastOpenLogId(string lastOpenLogId) { if(!Application.isEditor) { #if UNITY_WP8 MATWP8.MobileAppTracker.Instance.SetLastOpenLogId(lastOpenLogId); #endif } } /// <para> /// Sets the MAT response. /// Does nothing if not a Windows Phone 8 device. /// </para> /// <param name="matResponse">MAT response</param> public static void SetMATResponse(MATWP8.MATResponse matResponse) { if(!Application.isEditor) { #if UNITY_WP8 MATWP8.MobileAppTracker.Instance.SetMATResponse (matResponse); #endif } } /// <para> /// Sets the MAT response. /// Does nothing if not a Windows Store device. /// </para> /// <param name="matResponse">MAT response</param> public static void SetMATResponse(MATWinStore.MATResponse matResponse) { if(!Application.isEditor) { #if UNITY_METRO MATWinStore.MobileAppTracker.Instance.SetMATResponse(matResponse); #endif } } /// <para> /// Sets the OS version. /// Does nothing if not a Windows Phone 8 device. /// </para> /// <param name="osVersion">OS version</param> public static void SetOSVersion(string osVersion) { if(!Application.isEditor) { #if UNITY_WP8 MATWP8.MobileAppTracker.Instance.SetOSVersion(osVersion); #endif } } ///////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////// /*----------------Android and iOS Platform-specific Features---------------*/ ///////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////// /// <para> /// Sets the ISO 4217 currency code. /// Does nothing if not Android or iOS. /// </para> /// <param name="currencyCode">the currency code</param> public static void SetCurrencyCode(string currencyCode) { if(!Application.isEditor) { #if UNITY_ANDROID MATAndroid.Instance.SetCurrencyCode(currencyCode); #endif #if UNITY_IPHONE MATExterns.MATSetCurrencyCode(currencyCode); #endif } } /// <para> /// Sets delegate used by MobileAppTracker to post success and failure callbacks from the MAT SDK. /// Does nothing if not an Android or iOS device. /// </para> /// <param name="enable">If set to true enable delegate.</param> public static void SetDelegate(bool enable) { if(!Application.isEditor) { #if UNITY_ANDROID MATAndroid.Instance.SetDelegate(enable); #endif #if (UNITY_IPHONE) MATExterns.MATSetDelegate(enable); #endif } } /// <para> /// Sets the MAT site ID to specify which app to attribute to. /// Does nothing if not Android or iOS device. /// </para> /// <param name="siteId"> MAT site ID to attribute to</param> public static void SetSiteId(string siteId) { if(!Application.isEditor) { #if UNITY_ANDROID MATAndroid.Instance.SetSiteId(siteId); #endif #if UNITY_IPHONE MATExterns.MATSetSiteId(siteId); #endif } } /// <para> /// Sets the TRUSTe ID, should generate via their SDK. /// Does nothing if not Android or iOS device. /// </para> /// <param name="tpid">TRUSTe ID</param> public static void SetTRUSTeId(string tpid) { if(!Application.isEditor) { #if UNITY_ANDROID MATAndroid.Instance.SetTRUSTeId(tpid); #endif #if UNITY_IPHONE MATExterns.MATSetTRUSTeId(tpid); #endif } } ///////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////// /*---------------------End of Platform-specific Features-------------------*/ ///////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////// } }
using System; using System.Collections.Generic; using UnityEngine.Rendering; namespace UnityEngine.PostProcessing { using DebugMode = BuiltinDebugViewsModel.Mode; #if UNITY_5_4_OR_NEWER [ImageEffectAllowedInSceneView] #endif [RequireComponent(typeof(Camera)), DisallowMultipleComponent, ExecuteInEditMode] [AddComponentMenu("Effects/Post-Processing Behaviour", -1)] public class PostProcessingBehaviour : MonoBehaviour { // Inspector fields public PostProcessingProfile profile; public Func<Vector2, Matrix4x4> jitteredMatrixFunc; // Internal helpers Dictionary<Type, KeyValuePair<CameraEvent, CommandBuffer>> m_CommandBuffers; List<PostProcessingComponentBase> m_Components; Dictionary<PostProcessingComponentBase, bool> m_ComponentStates; MaterialFactory m_MaterialFactory; RenderTextureFactory m_RenderTextureFactory; PostProcessingContext m_Context; Camera m_Camera; PostProcessingProfile m_PreviousProfile; bool m_RenderingInSceneView = false; // Effect components BuiltinDebugViewsComponent m_DebugViews; AmbientOcclusionComponent m_AmbientOcclusion; ScreenSpaceReflectionComponent m_ScreenSpaceReflection; FogComponent m_FogComponent; MotionBlurComponent m_MotionBlur; TaaComponent m_Taa; EyeAdaptationComponent m_EyeAdaptation; DepthOfFieldComponent m_DepthOfField; BloomComponent m_Bloom; ChromaticAberrationComponent m_ChromaticAberration; ColorGradingComponent m_ColorGrading; UserLutComponent m_UserLut; GrainComponent m_Grain; VignetteComponent m_Vignette; DitheringComponent m_Dithering; FxaaComponent m_Fxaa; void OnEnable() { m_CommandBuffers = new Dictionary<Type, KeyValuePair<CameraEvent, CommandBuffer>>(); m_MaterialFactory = new MaterialFactory(); m_RenderTextureFactory = new RenderTextureFactory(); m_Context = new PostProcessingContext(); // Keep a list of all post-fx for automation purposes m_Components = new List<PostProcessingComponentBase>(); // Component list m_DebugViews = AddComponent(new BuiltinDebugViewsComponent()); m_AmbientOcclusion = AddComponent(new AmbientOcclusionComponent()); m_ScreenSpaceReflection = AddComponent(new ScreenSpaceReflectionComponent()); m_FogComponent = AddComponent(new FogComponent()); m_MotionBlur = AddComponent(new MotionBlurComponent()); m_Taa = AddComponent(new TaaComponent()); m_EyeAdaptation = AddComponent(new EyeAdaptationComponent()); m_DepthOfField = AddComponent(new DepthOfFieldComponent()); m_Bloom = AddComponent(new BloomComponent()); m_ChromaticAberration = AddComponent(new ChromaticAberrationComponent()); m_ColorGrading = AddComponent(new ColorGradingComponent()); m_UserLut = AddComponent(new UserLutComponent()); m_Grain = AddComponent(new GrainComponent()); m_Vignette = AddComponent(new VignetteComponent()); m_Dithering = AddComponent(new DitheringComponent()); m_Fxaa = AddComponent(new FxaaComponent()); // Prepare state observers m_ComponentStates = new Dictionary<PostProcessingComponentBase, bool>(); foreach (var component in m_Components) m_ComponentStates.Add(component, false); useGUILayout = false; } void OnPreCull() { // All the per-frame initialization logic has to be done in OnPreCull instead of Update // because [ImageEffectAllowedInSceneView] doesn't trigger Update events... m_Camera = GetComponent<Camera>(); if (profile == null || m_Camera == null) return; #if UNITY_EDITOR // Track the scene view camera to disable some effects we don't want to see in the // scene view // Currently disabled effects : // - Temporal Antialiasing // - Depth of Field // - Motion blur m_RenderingInSceneView = UnityEditor.SceneView.currentDrawingSceneView != null && UnityEditor.SceneView.currentDrawingSceneView.camera == m_Camera; #endif // Prepare context var context = m_Context.Reset(); context.profile = profile; context.renderTextureFactory = m_RenderTextureFactory; context.materialFactory = m_MaterialFactory; context.camera = m_Camera; // Prepare components m_DebugViews.Init(context, profile.debugViews); m_AmbientOcclusion.Init(context, profile.ambientOcclusion); m_ScreenSpaceReflection.Init(context, profile.screenSpaceReflection); m_FogComponent.Init(context, profile.fog); m_MotionBlur.Init(context, profile.motionBlur); m_Taa.Init(context, profile.antialiasing); m_EyeAdaptation.Init(context, profile.eyeAdaptation); m_DepthOfField.Init(context, profile.depthOfField); m_Bloom.Init(context, profile.bloom); m_ChromaticAberration.Init(context, profile.chromaticAberration); m_ColorGrading.Init(context, profile.colorGrading); m_UserLut.Init(context, profile.userLut); m_Grain.Init(context, profile.grain); m_Vignette.Init(context, profile.vignette); m_Dithering.Init(context, profile.dithering); m_Fxaa.Init(context, profile.antialiasing); // Handles profile change and 'enable' state observers if (m_PreviousProfile != profile) { DisableComponents(); m_PreviousProfile = profile; } CheckObservers(); // Find out which camera flags are needed before rendering begins // Note that motion vectors will only be available one frame after being enabled var flags = context.camera.depthTextureMode; foreach (var component in m_Components) { if (component.active) flags |= component.GetCameraFlags(); } context.camera.depthTextureMode = flags; // Temporal antialiasing jittering, needs to happen before culling if (!m_RenderingInSceneView && m_Taa.active && !profile.debugViews.willInterrupt) m_Taa.SetProjectionMatrix(jitteredMatrixFunc); } void OnPreRender() { if (profile == null) return; // Command buffer-based effects should be set-up here TryExecuteCommandBuffer(m_DebugViews); TryExecuteCommandBuffer(m_AmbientOcclusion); TryExecuteCommandBuffer(m_ScreenSpaceReflection); TryExecuteCommandBuffer(m_FogComponent); if (!m_RenderingInSceneView) TryExecuteCommandBuffer(m_MotionBlur); } void OnPostRender() { if (profile == null || m_Camera == null) return; if (!m_RenderingInSceneView && m_Taa.active && !profile.debugViews.willInterrupt) m_Context.camera.ResetProjectionMatrix(); } // Classic render target pipeline for RT-based effects // Note that any effect that happens after this stack will work in LDR [ImageEffectTransformsToLDR] void OnRenderImage(RenderTexture source, RenderTexture destination) { if (profile == null || m_Camera == null) { Graphics.Blit(source, destination); return; } // Uber shader setup bool uberActive = false; bool fxaaActive = m_Fxaa.active; bool taaActive = m_Taa.active && !m_RenderingInSceneView; bool dofActive = m_DepthOfField.active && !m_RenderingInSceneView; var uberMaterial = m_MaterialFactory.Get("Hidden/Post FX/Uber Shader"); uberMaterial.shaderKeywords = null; var src = source; var dst = destination; if (taaActive) { var tempRT = m_RenderTextureFactory.Get(src); m_Taa.Render(src, tempRT); src = tempRT; } #if UNITY_EDITOR // Render to a dedicated target when monitors are enabled so they can show information // about the final render. // At runtime the output will always be the backbuffer or whatever render target is // currently set on the camera. if (profile.monitors.onFrameEndEditorOnly != null) dst = m_RenderTextureFactory.Get(src); #endif Texture autoExposure = GraphicsUtils.whiteTexture; if (m_EyeAdaptation.active) { uberActive = true; autoExposure = m_EyeAdaptation.Prepare(src, uberMaterial); } uberMaterial.SetTexture("_AutoExposure", autoExposure); if (dofActive) { uberActive = true; m_DepthOfField.Prepare(src, uberMaterial, taaActive, m_Taa.jitterVector, m_Taa.model.settings.taaSettings.motionBlending); } if (m_Bloom.active) { uberActive = true; m_Bloom.Prepare(src, uberMaterial, autoExposure); } uberActive |= TryPrepareUberImageEffect(m_ChromaticAberration, uberMaterial); uberActive |= TryPrepareUberImageEffect(m_ColorGrading, uberMaterial); uberActive |= TryPrepareUberImageEffect(m_Vignette, uberMaterial); uberActive |= TryPrepareUberImageEffect(m_UserLut, uberMaterial); var fxaaMaterial = fxaaActive ? m_MaterialFactory.Get("Hidden/Post FX/FXAA") : null; if (fxaaActive) { fxaaMaterial.shaderKeywords = null; TryPrepareUberImageEffect(m_Grain, fxaaMaterial); TryPrepareUberImageEffect(m_Dithering, fxaaMaterial); if (uberActive) { var output = m_RenderTextureFactory.Get(src); Graphics.Blit(src, output, uberMaterial, 0); src = output; } m_Fxaa.Render(src, dst); } else { uberActive |= TryPrepareUberImageEffect(m_Grain, uberMaterial); uberActive |= TryPrepareUberImageEffect(m_Dithering, uberMaterial); if (uberActive) { if (!GraphicsUtils.isLinearColorSpace) uberMaterial.EnableKeyword("UNITY_COLORSPACE_GAMMA"); Graphics.Blit(src, dst, uberMaterial, 0); } } if (!uberActive && !fxaaActive) Graphics.Blit(src, dst); #if UNITY_EDITOR if (profile.monitors.onFrameEndEditorOnly != null) { Graphics.Blit(dst, destination); var oldRt = RenderTexture.active; profile.monitors.onFrameEndEditorOnly(dst); RenderTexture.active = oldRt; } #endif m_RenderTextureFactory.ReleaseAll(); } void OnGUI() { if (Event.current.type != EventType.Repaint) return; if (profile == null || m_Camera == null) return; if (m_EyeAdaptation.active && profile.debugViews.IsModeActive(DebugMode.EyeAdaptation)) m_EyeAdaptation.OnGUI(); else if (m_ColorGrading.active && profile.debugViews.IsModeActive(DebugMode.LogLut)) m_ColorGrading.OnGUI(); else if (m_UserLut.active && profile.debugViews.IsModeActive(DebugMode.UserLut)) m_UserLut.OnGUI(); } void OnDisable() { // Clear command buffers foreach (var cb in m_CommandBuffers.Values) { m_Camera.RemoveCommandBuffer(cb.Key, cb.Value); cb.Value.Dispose(); } m_CommandBuffers.Clear(); // Clear components if (profile != null) DisableComponents(); m_Components.Clear(); // Factories m_MaterialFactory.Dispose(); m_RenderTextureFactory.Dispose(); GraphicsUtils.Dispose(); } public void ResetTemporalEffects() { m_Taa.ResetHistory(); m_MotionBlur.ResetHistory(); m_EyeAdaptation.ResetHistory(); } #region State management List<PostProcessingComponentBase> m_ComponentsToEnable = new List<PostProcessingComponentBase>(); List<PostProcessingComponentBase> m_ComponentsToDisable = new List<PostProcessingComponentBase>(); void CheckObservers() { foreach (var cs in m_ComponentStates) { var component = cs.Key; var state = component.GetModel().enabled; if (state != cs.Value) { if (state) m_ComponentsToEnable.Add(component); else m_ComponentsToDisable.Add(component); } } for (int i = 0; i < m_ComponentsToDisable.Count; i++) { var c = m_ComponentsToDisable[i]; m_ComponentStates[c] = false; c.OnDisable(); } for (int i = 0; i < m_ComponentsToEnable.Count; i++) { var c = m_ComponentsToEnable[i]; m_ComponentStates[c] = true; c.OnEnable(); } m_ComponentsToDisable.Clear(); m_ComponentsToEnable.Clear(); } void DisableComponents() { foreach (var component in m_Components) { var model = component.GetModel(); if (model != null && model.enabled) component.OnDisable(); } } #endregion #region Command buffer handling & rendering helpers // Placeholders before the upcoming Scriptable Render Loop as command buffers will be // executed on the go so we won't need of all that stuff CommandBuffer AddCommandBuffer<T>(CameraEvent evt, string name) where T : PostProcessingModel { var cb = new CommandBuffer { name = name }; var kvp = new KeyValuePair<CameraEvent, CommandBuffer>(evt, cb); m_CommandBuffers.Add(typeof(T), kvp); m_Camera.AddCommandBuffer(evt, kvp.Value); return kvp.Value; } void RemoveCommandBuffer<T>() where T : PostProcessingModel { KeyValuePair<CameraEvent, CommandBuffer> kvp; var type = typeof(T); if (!m_CommandBuffers.TryGetValue(type, out kvp)) return; m_Camera.RemoveCommandBuffer(kvp.Key, kvp.Value); m_CommandBuffers.Remove(type); kvp.Value.Dispose(); } CommandBuffer GetCommandBuffer<T>(CameraEvent evt, string name) where T : PostProcessingModel { CommandBuffer cb; KeyValuePair<CameraEvent, CommandBuffer> kvp; if (!m_CommandBuffers.TryGetValue(typeof(T), out kvp)) { cb = AddCommandBuffer<T>(evt, name); } else if (kvp.Key != evt) { RemoveCommandBuffer<T>(); cb = AddCommandBuffer<T>(evt, name); } else cb = kvp.Value; return cb; } void TryExecuteCommandBuffer<T>(PostProcessingComponentCommandBuffer<T> component) where T : PostProcessingModel { if (component.active) { var cb = GetCommandBuffer<T>(component.GetCameraEvent(), component.GetName()); cb.Clear(); component.PopulateCommandBuffer(cb); } else RemoveCommandBuffer<T>(); } bool TryPrepareUberImageEffect<T>(PostProcessingComponentRenderTexture<T> component, Material material) where T : PostProcessingModel { if (!component.active) return false; component.Prepare(material); return true; } T AddComponent<T>(T component) where T : PostProcessingComponentBase { m_Components.Add(component); return component; } #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. // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // TargetCore.cs // // // The core implementation of a standard ITargetBlock<TInput>. // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; using System.Linq; namespace System.Threading.Tasks.Dataflow.Internal { // LOCK-LEVELING SCHEME // -------------------- // TargetCore employs a single lock: IncomingLock. This lock must not be used when calling out to any targets, // which TargetCore should not have, anyway. It also must not be held when calling back to any sources, except // during calls to OfferMessage from that same source. /// <summary>Options used to configure a target core.</summary> [Flags] internal enum TargetCoreOptions : byte { /// <summary>Synchronous completion, both a target and a source, etc.</summary> None = 0x0, /// <summary>Whether the block relies on the delegate to signal when an async operation has completed.</summary> UsesAsyncCompletion = 0x1, /// <summary> /// Whether the block containing this target core is just a target or also has a source side. /// If it's just a target, then this target core's completion represents the entire block's completion. /// </summary> RepresentsBlockCompletion = 0x2 } /// <summary> /// Provides a core implementation of <see cref="ITargetBlock{TInput}"/>.</summary> /// <typeparam name="TInput">Specifies the type of data accepted by the <see cref="TargetCore{TInput}"/>.</typeparam> [SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable")] [DebuggerDisplay("{DebuggerDisplayContent,nq}")] internal sealed class TargetCore<TInput> { // *** These fields are readonly and are initialized at AppDomain startup. /// <summary>Caching the keep alive predicate.</summary> private static readonly Common.KeepAlivePredicate<TargetCore<TInput>, KeyValuePair<TInput, long>> _keepAlivePredicate = (TargetCore<TInput> thisTargetCore, out KeyValuePair<TInput, long> messageWithId) => thisTargetCore.TryGetNextAvailableOrPostponedMessage(out messageWithId); // *** These fields are readonly and are initialized to new instances at construction. /// <summary>A task representing the completion of the block.</summary> private readonly TaskCompletionSource<VoidResult> _completionSource = new TaskCompletionSource<VoidResult>(); // *** These fields are readonly and are initialized by arguments to the constructor. /// <summary>The target block using this helper.</summary> private readonly ITargetBlock<TInput> _owningTarget; /// <summary>The messages in this target.</summary> /// <remarks>This field doubles as the IncomingLock.</remarks> private readonly IProducerConsumerQueue<KeyValuePair<TInput, long>> _messages; /// <summary>The options associated with this block.</summary> private readonly ExecutionDataflowBlockOptions _dataflowBlockOptions; /// <summary>An action to invoke for every accepted message.</summary> private readonly Action<KeyValuePair<TInput, long>> _callAction; /// <summary>Whether the block relies on the delegate to signal when an async operation has completed.</summary> private readonly TargetCoreOptions _targetCoreOptions; /// <summary>Bounding state for when the block is executing in bounded mode.</summary> private readonly BoundingStateWithPostponed<TInput> _boundingState; /// <summary>The reordering buffer used by the owner. May be null.</summary> private readonly IReorderingBuffer _reorderingBuffer; /// <summary>Gets the object used as the incoming lock.</summary> private object IncomingLock { get { return _messages; } } // *** These fields are mutated during execution. /// <summary>Exceptions that may have occurred and gone unhandled during processing.</summary> private List<Exception> _exceptions; /// <summary>Whether to stop accepting new messages.</summary> private bool _decliningPermanently; /// <summary>The number of operations (including service tasks) currently running asynchronously.</summary> /// <remarks>Must always be accessed from inside a lock.</remarks> private int _numberOfOutstandingOperations; /// <summary>The number of service tasks in async mode currently running.</summary> /// <remarks>Must always be accessed from inside a lock.</remarks> private int _numberOfOutstandingServiceTasks; /// <summary>The next available ID we can assign to a message about to be processed.</summary> private PaddedInt64 _nextAvailableInputMessageId; // initialized to 0... very important for a reordering buffer /// <summary>A task has reserved the right to run the completion routine.</summary> private bool _completionReserved; /// <summary>This counter is set by the processing loop to prevent itself from trying to keep alive.</summary> private int _keepAliveBanCounter; /// <summary>Initializes the target core.</summary> /// <param name="owningTarget">The target using this helper.</param> /// <param name="callAction">An action to invoke for all accepted items.</param> /// <param name="reorderingBuffer">The reordering buffer used by the owner; may be null.</param> /// <param name="dataflowBlockOptions">The options to use to configure this block. The target core assumes these options are immutable.</param> /// <param name="targetCoreOptions">Options for how the target core should behave.</param> internal TargetCore( ITargetBlock<TInput> owningTarget, Action<KeyValuePair<TInput, long>> callAction, IReorderingBuffer reorderingBuffer, ExecutionDataflowBlockOptions dataflowBlockOptions, TargetCoreOptions targetCoreOptions) { // Validate internal arguments Debug.Assert(owningTarget != null, "Core must be associated with a target block."); Debug.Assert(dataflowBlockOptions != null, "Options must be provided to configure the core."); Debug.Assert(callAction != null, "Action to invoke for each item is required."); // Store arguments and do additional initialization _owningTarget = owningTarget; _callAction = callAction; _reorderingBuffer = reorderingBuffer; _dataflowBlockOptions = dataflowBlockOptions; _targetCoreOptions = targetCoreOptions; _messages = (dataflowBlockOptions.MaxDegreeOfParallelism == 1) ? (IProducerConsumerQueue<KeyValuePair<TInput, long>>)new SingleProducerSingleConsumerQueue<KeyValuePair<TInput, long>>() : (IProducerConsumerQueue<KeyValuePair<TInput, long>>)new MultiProducerMultiConsumerQueue<KeyValuePair<TInput, long>>(); if (_dataflowBlockOptions.BoundedCapacity != System.Threading.Tasks.Dataflow.DataflowBlockOptions.Unbounded) { Debug.Assert(_dataflowBlockOptions.BoundedCapacity > 0, "Positive bounding count expected; should have been verified by options ctor"); _boundingState = new BoundingStateWithPostponed<TInput>(_dataflowBlockOptions.BoundedCapacity); } } /// <summary>Internal Complete entry point with extra parameters for different contexts.</summary> /// <param name="exception">If not null, the block will be faulted.</param> /// <param name="dropPendingMessages">If true, any unprocessed input messages will be dropped.</param> /// <param name="storeExceptionEvenIfAlreadyCompleting">If true, an exception will be stored after _decliningPermanently has been set to true.</param> /// <param name="unwrapInnerExceptions">If true, exception will be treated as an AggregateException.</param> /// <param name="revertProcessingState">Indicates whether the processing state is dirty and has to be reverted.</param> internal void Complete(Exception exception, bool dropPendingMessages, bool storeExceptionEvenIfAlreadyCompleting = false, bool unwrapInnerExceptions = false, bool revertProcessingState = false) { Debug.Assert(storeExceptionEvenIfAlreadyCompleting || !revertProcessingState, "Indicating dirty processing state may only come with storeExceptionEvenIfAlreadyCompleting==true."); Contract.EndContractBlock(); // Ensure that no new messages may be added lock (IncomingLock) { // Faulting from outside is allowed until we start declining permanently. // Faulting from inside is allowed at any time. if (exception != null && (!_decliningPermanently || storeExceptionEvenIfAlreadyCompleting)) { Debug.Assert(_numberOfOutstandingOperations > 0 || !storeExceptionEvenIfAlreadyCompleting, "Calls with storeExceptionEvenIfAlreadyCompleting==true may only be coming from processing task."); #pragma warning disable 0420 Common.AddException(ref _exceptions, exception, unwrapInnerExceptions); } // Clear the messages queue if requested if (dropPendingMessages) { KeyValuePair<TInput, long> dummy; while (_messages.TryDequeue(out dummy)) ; } // Revert the dirty processing state if requested if (revertProcessingState) { Debug.Assert(_numberOfOutstandingOperations > 0 && (!UsesAsyncCompletion || _numberOfOutstandingServiceTasks > 0), "The processing state must be dirty when revertProcessingState==true."); _numberOfOutstandingOperations--; if (UsesAsyncCompletion) _numberOfOutstandingServiceTasks--; } // Trigger completion _decliningPermanently = true; CompleteBlockIfPossible(); } } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Targets/Member[@name="OfferMessage"]/*' /> internal DataflowMessageStatus OfferMessage(DataflowMessageHeader messageHeader, TInput messageValue, ISourceBlock<TInput> source, Boolean consumeToAccept) { // Validate arguments if (!messageHeader.IsValid) throw new ArgumentException(SR.Argument_InvalidMessageHeader, nameof(messageHeader)); if (source == null && consumeToAccept) throw new ArgumentException(SR.Argument_CantConsumeFromANullSource, nameof(consumeToAccept)); Contract.EndContractBlock(); lock (IncomingLock) { // If we shouldn't be accepting more messages, don't. if (_decliningPermanently) { CompleteBlockIfPossible(); return DataflowMessageStatus.DecliningPermanently; } // We can directly accept the message if: // 1) we are not bounding, OR // 2) we are bounding AND there is room available AND there are no postponed messages AND no messages are currently being transfered to the input queue. // (If there were any postponed messages, we would need to postpone so that ordering would be maintained.) // (Unlike all other blocks, TargetCore can accept messages while processing, because // input message IDs are properly assigned and the correct order is preserved.) if (_boundingState == null || (_boundingState.OutstandingTransfers == 0 && _boundingState.CountIsLessThanBound && _boundingState.PostponedMessages.Count == 0)) { // Consume the message from the source if necessary if (consumeToAccept) { Debug.Assert(source != null, "We must have thrown if source == null && consumeToAccept == true."); bool consumed; messageValue = source.ConsumeMessage(messageHeader, _owningTarget, out consumed); if (!consumed) return DataflowMessageStatus.NotAvailable; } // Assign a message ID - strictly sequential, no gaps. // Once consumed, enqueue the message with its ID and kick off asynchronous processing. long messageId = _nextAvailableInputMessageId.Value++; Debug.Assert(messageId != Common.INVALID_REORDERING_ID, "The assigned message ID is invalid."); if (_boundingState != null) _boundingState.CurrentCount += 1; // track this new item against our bound _messages.Enqueue(new KeyValuePair<TInput, long>(messageValue, messageId)); ProcessAsyncIfNecessary(); return DataflowMessageStatus.Accepted; } // Otherwise, we try to postpone if a source was provided else if (source != null) { Debug.Assert(_boundingState != null && _boundingState.PostponedMessages != null, "PostponedMessages must have been initialized during construction in non-greedy mode."); // Store the message's info and kick off asynchronous processing _boundingState.PostponedMessages.Push(source, messageHeader); ProcessAsyncIfNecessary(); return DataflowMessageStatus.Postponed; } // We can't do anything else about this message return DataflowMessageStatus.Declined; } } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Blocks/Member[@name="Completion"]/*' /> internal Task Completion { get { return _completionSource.Task; } } /// <summary>Gets the number of items waiting to be processed by this target.</summary> internal int InputCount { get { return _messages.GetCountSafe(IncomingLock); } } /// <summary>Signals to the target core that a previously launched asynchronous operation has now completed.</summary> internal void SignalOneAsyncMessageCompleted() { SignalOneAsyncMessageCompleted(boundingCountChange: 0); } /// <summary>Signals to the target core that a previously launched asynchronous operation has now completed.</summary> /// <param name="boundingCountChange">The number of elements by which to change the bounding count, if bounding is occurring.</param> internal void SignalOneAsyncMessageCompleted(int boundingCountChange) { lock (IncomingLock) { // We're no longer processing, so decrement the DOP counter Debug.Assert(_numberOfOutstandingOperations > 0, "Operations may only be completed if any are outstanding."); if (_numberOfOutstandingOperations > 0) _numberOfOutstandingOperations--; // Fix up the bounding count if necessary if (_boundingState != null && boundingCountChange != 0) { Debug.Assert(boundingCountChange <= 0 && _boundingState.CurrentCount + boundingCountChange >= 0, "Expected a negative bounding change and not to drop below zero."); _boundingState.CurrentCount += boundingCountChange; } // However, we may have given up early because we hit our own configured // processing limits rather than because we ran out of work to do. If that's // the case, make sure we spin up another task to keep going. ProcessAsyncIfNecessary(repeat: true); // If, however, we stopped because we ran out of work to do and we // know we'll never get more, then complete. CompleteBlockIfPossible(); } } /// <summary>Gets whether this instance has been constructed for async processing.</summary> private bool UsesAsyncCompletion { get { return (_targetCoreOptions & TargetCoreOptions.UsesAsyncCompletion) != 0; } } /// <summary>Gets whether there's room to launch more processing operations.</summary> private bool HasRoomForMoreOperations { get { Debug.Assert(_numberOfOutstandingOperations >= 0, "Number of outstanding operations should never be negative."); Debug.Assert(_numberOfOutstandingServiceTasks >= 0, "Number of outstanding service tasks should never be negative."); Debug.Assert(_numberOfOutstandingOperations >= _numberOfOutstandingServiceTasks, "Number of outstanding service tasks should never exceed the number of outstanding operations."); Common.ContractAssertMonitorStatus(IncomingLock, held: true); // In async mode, we increment _numberOfOutstandingOperations before we start // our own processing loop which should not count towards the MaxDOP. return (_numberOfOutstandingOperations - _numberOfOutstandingServiceTasks) < _dataflowBlockOptions.ActualMaxDegreeOfParallelism; } } /// <summary>Gets whether there's room to launch more service tasks for doing/launching processing operations.</summary> private bool HasRoomForMoreServiceTasks { get { Debug.Assert(_numberOfOutstandingOperations >= 0, "Number of outstanding operations should never be negative."); Debug.Assert(_numberOfOutstandingServiceTasks >= 0, "Number of outstanding service tasks should never be negative."); Debug.Assert(_numberOfOutstandingOperations >= _numberOfOutstandingServiceTasks, "Number of outstanding service tasks should never exceed the number of outstanding operations."); Common.ContractAssertMonitorStatus(IncomingLock, held: true); if (!UsesAsyncCompletion) { // Sync mode: // We don't count service tasks, because our tasks are counted as operations. // Therefore, return HasRoomForMoreOperations. return HasRoomForMoreOperations; } else { // Async mode: // We allow up to MaxDOP true service tasks. // Checking whether there is room for more processing operations is not necessary, // but doing so will help us avoid spinning up a task that will go away without // launching any processing operation. return HasRoomForMoreOperations && _numberOfOutstandingServiceTasks < _dataflowBlockOptions.ActualMaxDegreeOfParallelism; } } } /// <summary>Called when new messages are available to be processed.</summary> /// <param name="repeat">Whether this call is the continuation of a previous message loop.</param> private void ProcessAsyncIfNecessary(bool repeat = false) { Common.ContractAssertMonitorStatus(IncomingLock, held: true); if (HasRoomForMoreServiceTasks) { ProcessAsyncIfNecessary_Slow(repeat); } } /// <summary> /// Slow path for ProcessAsyncIfNecessary. /// Separating out the slow path into its own method makes it more likely that the fast path method will get inlined. /// </summary> [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")] private void ProcessAsyncIfNecessary_Slow(bool repeat) { Debug.Assert(HasRoomForMoreServiceTasks, "There must be room to process asynchronously."); Common.ContractAssertMonitorStatus(IncomingLock, held: true); // Determine preconditions to launching a processing task bool messagesAvailableOrPostponed = !_messages.IsEmpty || (!_decliningPermanently && _boundingState != null && _boundingState.CountIsLessThanBound && _boundingState.PostponedMessages.Count > 0); // If all conditions are met, launch away if (messagesAvailableOrPostponed && !CanceledOrFaulted) { // Any book keeping related to the processing task like incrementing the // DOP counter or eventually recording the tasks reference must be done // before the task starts. That is because the task itself will do the // reverse operation upon its completion. _numberOfOutstandingOperations++; if (UsesAsyncCompletion) _numberOfOutstandingServiceTasks++; var taskForInputProcessing = new Task(thisTargetCore => ((TargetCore<TInput>)thisTargetCore).ProcessMessagesLoopCore(), this, Common.GetCreationOptionsForTask(repeat)); #if FEATURE_TRACING DataflowEtwProvider etwLog = DataflowEtwProvider.Log; if (etwLog.IsEnabled()) { etwLog.TaskLaunchedForMessageHandling( _owningTarget, taskForInputProcessing, DataflowEtwProvider.TaskLaunchedReason.ProcessingInputMessages, _messages.Count + (_boundingState != null ? _boundingState.PostponedMessages.Count : 0)); } #endif // Start the task handling scheduling exceptions Exception exception = Common.StartTaskSafe(taskForInputProcessing, _dataflowBlockOptions.TaskScheduler); if (exception != null) { // Get out from under currently held locks. Complete re-acquires the locks it needs. Task.Factory.StartNew(exc => Complete(exception: (Exception)exc, dropPendingMessages: true, storeExceptionEvenIfAlreadyCompleting: true, unwrapInnerExceptions: false, revertProcessingState: true), exception, CancellationToken.None, Common.GetCreationOptionsForTask(), TaskScheduler.Default); } } } /// <summary>Task body used to process messages.</summary> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] private void ProcessMessagesLoopCore() { Common.ContractAssertMonitorStatus(IncomingLock, held: false); KeyValuePair<TInput, long> messageWithId = default(KeyValuePair<TInput, long>); try { bool useAsyncCompletion = UsesAsyncCompletion; bool shouldAttemptPostponedTransfer = _boundingState != null && _boundingState.BoundedCapacity > 1; int numberOfMessagesProcessedByThisTask = 0; int numberOfMessagesProcessedSinceTheLastKeepAlive = 0; int maxMessagesPerTask = _dataflowBlockOptions.ActualMaxMessagesPerTask; while (numberOfMessagesProcessedByThisTask < maxMessagesPerTask && !CanceledOrFaulted) { // If we're bounding, try to transfer a message from the postponed queue // to the input queue. This enables us to more quickly unblock sources // sending data to the block (otherwise, no postponed messages will be consumed // until the input queue is entirely empty). If the bounded size is 1, // there's no need to transfer, as attempting to get the next message will // just go and consume the postponed message anyway, and we'll save // the extra trip through the _messages queue. KeyValuePair<TInput, long> transferMessageWithId; if (shouldAttemptPostponedTransfer && TryConsumePostponedMessage(forPostponementTransfer: true, result: out transferMessageWithId)) { lock (IncomingLock) { Debug.Assert( _boundingState.OutstandingTransfers > 0 && _boundingState.OutstandingTransfers <= _dataflowBlockOptions.ActualMaxDegreeOfParallelism, "Expected TryConsumePostponedMessage to have incremented the count and for the count to not exceed the DOP."); _boundingState.OutstandingTransfers--; // was incremented in TryConsumePostponedMessage _messages.Enqueue(transferMessageWithId); ProcessAsyncIfNecessary(); } } if (useAsyncCompletion) { // Get the next message if DOP is available. // If we can't get a message or DOP is not available, bail out. if (!TryGetNextMessageForNewAsyncOperation(out messageWithId)) break; } else { // Try to get a message for sequential execution, i.e. without checking DOP availability if (!TryGetNextAvailableOrPostponedMessage(out messageWithId)) { // Try to keep the task alive only if MaxDOP=1 if (_dataflowBlockOptions.MaxDegreeOfParallelism != 1) break; // If this task has processed enough messages without being kept alive, // it has served its purpose. Don't keep it alive. if (numberOfMessagesProcessedSinceTheLastKeepAlive > Common.KEEP_ALIVE_NUMBER_OF_MESSAGES_THRESHOLD) break; // If keep alive is banned, don't attempt it if (_keepAliveBanCounter > 0) { _keepAliveBanCounter--; break; } // Reset the keep alive counter. (Keep this line together with TryKeepAliveUntil.) numberOfMessagesProcessedSinceTheLastKeepAlive = 0; // Try to keep the task alive briefly until a new message arrives if (!Common.TryKeepAliveUntil(_keepAlivePredicate, this, out messageWithId)) { // Keep alive was unsuccessful. // Therefore ban further attempts temporarily. _keepAliveBanCounter = Common.KEEP_ALIVE_BAN_COUNT; break; } } } // We have popped a message from the queue. // So increment the counter of processed messages. numberOfMessagesProcessedByThisTask++; numberOfMessagesProcessedSinceTheLastKeepAlive++; // Invoke the user action _callAction(messageWithId); } } catch (Exception exc) { Common.StoreDataflowMessageValueIntoExceptionData(exc, messageWithId.Key); Complete(exc, dropPendingMessages: true, storeExceptionEvenIfAlreadyCompleting: true, unwrapInnerExceptions: false); } finally { lock (IncomingLock) { // We incremented _numberOfOutstandingOperations before we launched this task. // So we must decremented it before exiting. // Note that each async task additionally incremented it before starting and // is responsible for decrementing it prior to exiting. Debug.Assert(_numberOfOutstandingOperations > 0, "Expected a positive number of outstanding operations, since we're completing one here."); _numberOfOutstandingOperations--; // If we are in async mode, we've also incremented _numberOfOutstandingServiceTasks. // Now it's time to decrement it. if (UsesAsyncCompletion) { Debug.Assert(_numberOfOutstandingServiceTasks > 0, "Expected a positive number of outstanding service tasks, since we're completing one here."); _numberOfOutstandingServiceTasks--; } // However, we may have given up early because we hit our own configured // processing limits rather than because we ran out of work to do. If that's // the case, make sure we spin up another task to keep going. ProcessAsyncIfNecessary(repeat: true); // If, however, we stopped because we ran out of work to do and we // know we'll never get more, then complete. CompleteBlockIfPossible(); } } } /// <summary>Retrieves the next message from the input queue for the useAsyncCompletion mode.</summary> /// <param name="messageWithId">The next message retrieved.</param> /// <returns>true if a message was found and removed; otherwise, false.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] private bool TryGetNextMessageForNewAsyncOperation(out KeyValuePair<TInput, long> messageWithId) { Debug.Assert(UsesAsyncCompletion, "Only valid to use when in async mode."); Common.ContractAssertMonitorStatus(IncomingLock, held: false); bool parallelismAvailable; lock (IncomingLock) { // If we have room for another asynchronous operation, reserve it. // If later it turns out that we had no work to fill the slot, we'll undo the addition. parallelismAvailable = HasRoomForMoreOperations; if (parallelismAvailable) ++_numberOfOutstandingOperations; } messageWithId = default(KeyValuePair<TInput, long>); if (parallelismAvailable) { // If a parallelism slot was available, try to get an item. // Be careful, because an exception may be thrown from ConsumeMessage // and we have already incremented _numberOfOutstandingOperations. bool gotMessage = false; try { gotMessage = TryGetNextAvailableOrPostponedMessage(out messageWithId); } catch { // We have incremented the counter, but we didn't get a message. // So we must undo the increment and eventually complete the block. SignalOneAsyncMessageCompleted(); // Re-throw the exception. The processing loop will catch it. throw; } // There may not be an error, but may have still failed to get a message. // So we must undo the increment and eventually complete the block. if (!gotMessage) SignalOneAsyncMessageCompleted(); return gotMessage; } // If there was no parallelism available, we didn't increment _numberOfOutstandingOperations. // So there is nothing to do except to return false. return false; } /// <summary> /// Either takes the next available message from the input queue or retrieves a postponed /// message from a source, based on whether we're in greedy or non-greedy mode. /// </summary> /// <param name="messageWithId">The retrieved item with its Id.</param> /// <returns>true if a message could be removed and returned; otherwise, false.</returns> private bool TryGetNextAvailableOrPostponedMessage(out KeyValuePair<TInput, long> messageWithId) { Common.ContractAssertMonitorStatus(IncomingLock, held: false); // First try to get a message from our input buffer. if (_messages.TryDequeue(out messageWithId)) { return true; } // If we can't, but if we have any postponed messages due to bounding, then // try to consume one of these postponed messages. // Since we are not currently holding the lock, it is possible that new messages get queued up // by the time we take the lock to manipulate _boundingState. So we have to double-check the // input queue once we take the lock before we consider postponed messages. else if (_boundingState != null && TryConsumePostponedMessage(forPostponementTransfer: false, result: out messageWithId)) { return true; } // Otherwise, there's no message available. else { messageWithId = default(KeyValuePair<TInput, long>); return false; } } /// <summary>Consumes a single postponed message.</summary> /// <param name="forPostponementTransfer"> /// true if the method is being called to consume a message that'll then be stored into the input queue; /// false if the method is being called to consume a message that'll be processed immediately. /// If true, the bounding state's ForcePostponement will be updated. /// If false, the method will first try (while holding the lock) to consume from the input queue before /// consuming a postponed message. /// </param> /// <param name="result">The consumed message.</param> /// <returns>true if a message was consumed; otherwise, false.</returns> private bool TryConsumePostponedMessage( bool forPostponementTransfer, out KeyValuePair<TInput, long> result) { Debug.Assert( _dataflowBlockOptions.BoundedCapacity != System.Threading.Tasks.Dataflow.DataflowBlockOptions.Unbounded, "Only valid to use when in bounded mode."); Common.ContractAssertMonitorStatus(IncomingLock, held: false); // Iterate until we either consume a message successfully or there are no more postponed messages. bool countIncrementedExpectingToGetItem = false; long messageId = Common.INVALID_REORDERING_ID; while (true) { KeyValuePair<ISourceBlock<TInput>, DataflowMessageHeader> element; lock (IncomingLock) { // If we are declining permanently, don't consume postponed messages. if (_decliningPermanently) break; // New messages may have been queued up while we weren't holding the lock. // In particular, the input queue may have been filled up and messages may have // gotten postponed. If we process such a postponed message, we would mess up the // order. Therefore, we have to double-check the input queue first. if (!forPostponementTransfer && _messages.TryDequeue(out result)) return true; // We can consume a message to process if there's one to process and also if // if we have logical room within our bound for the message. if (!_boundingState.CountIsLessThanBound || !_boundingState.PostponedMessages.TryPop(out element)) { if (countIncrementedExpectingToGetItem) { countIncrementedExpectingToGetItem = false; _boundingState.CurrentCount -= 1; } break; } if (!countIncrementedExpectingToGetItem) { countIncrementedExpectingToGetItem = true; messageId = _nextAvailableInputMessageId.Value++; // optimistically assign an ID Debug.Assert(messageId != Common.INVALID_REORDERING_ID, "The assigned message ID is invalid."); _boundingState.CurrentCount += 1; // optimistically take bounding space if (forPostponementTransfer) { Debug.Assert(_boundingState.OutstandingTransfers >= 0, "Expected TryConsumePostponedMessage to not be negative."); _boundingState.OutstandingTransfers++; // temporarily force postponement until we've successfully consumed the element } } } // Must not call to source while holding lock bool consumed; TInput consumedValue = element.Key.ConsumeMessage(element.Value, _owningTarget, out consumed); if (consumed) { result = new KeyValuePair<TInput, long>(consumedValue, messageId); return true; } else { if (forPostponementTransfer) { // We didn't consume message so we need to decrement because we haven't consumed the element. _boundingState.OutstandingTransfers--; } } } // We optimistically acquired a message ID for a message that, in the end, we never got. // So, we need to let the reordering buffer (if one exists) know that it should not // expect an item with this ID. Otherwise, it would stall forever. if (_reorderingBuffer != null && messageId != Common.INVALID_REORDERING_ID) _reorderingBuffer.IgnoreItem(messageId); // Similarly, we optimistically increased the bounding count, expecting to get another message in. // Since we didn't, we need to fix the bounding count back to what it should have been. if (countIncrementedExpectingToGetItem) ChangeBoundingCount(-1); // Inform the caller that no message could be consumed. result = default(KeyValuePair<TInput, long>); return false; } /// <summary>Gets whether the target has had cancellation requested or an exception has occurred.</summary> private bool CanceledOrFaulted { get { return _dataflowBlockOptions.CancellationToken.IsCancellationRequested || Volatile.Read(ref _exceptions) != null; } } /// <summary>Completes the block once all completion conditions are met.</summary> private void CompleteBlockIfPossible() { Common.ContractAssertMonitorStatus(IncomingLock, held: true); bool noMoreMessages = _decliningPermanently && _messages.IsEmpty; if (noMoreMessages || CanceledOrFaulted) { CompleteBlockIfPossible_Slow(); } } /// <summary> /// Slow path for CompleteBlockIfPossible. /// Separating out the slow path into its own method makes it more likely that the fast path method will get inlined. /// </summary> private void CompleteBlockIfPossible_Slow() { Debug.Assert((_decliningPermanently && _messages.IsEmpty) || CanceledOrFaulted, "There must be no more messages."); Common.ContractAssertMonitorStatus(IncomingLock, held: true); bool notCurrentlyProcessing = _numberOfOutstandingOperations == 0; if (notCurrentlyProcessing && !_completionReserved) { // Make sure no one else tries to call CompleteBlockOncePossible _completionReserved = true; // Make sure the target is declining _decliningPermanently = true; // Get out from under currently held locks. This is to avoid // invoking synchronous continuations off of _completionSource.Task // while holding a lock. Task.Factory.StartNew(state => ((TargetCore<TInput>)state).CompleteBlockOncePossible(), this, CancellationToken.None, Common.GetCreationOptionsForTask(), TaskScheduler.Default); } } /// <summary> /// Completes the block. This must only be called once, and only once all of the completion conditions are met. /// As such, it must only be called from CompleteBlockIfPossible. /// </summary> private void CompleteBlockOncePossible() { // Since the lock is needed only for the Assert, we do this only in DEBUG mode #if DEBUG lock (IncomingLock) Debug.Assert(_numberOfOutstandingOperations == 0, "Everything must be done by now."); #endif // Release any postponed messages if (_boundingState != null) { // Note: No locks should be held at this point. Common.ReleaseAllPostponedMessages(_owningTarget, _boundingState.PostponedMessages, ref _exceptions); } // For good measure and help in preventing leaks, clear out the incoming message queue, // which may still contain orphaned data if we were canceled or faulted. However, // we don't reset the bounding count here, as the block as a whole may still be active. KeyValuePair<TInput, long> ignored; IProducerConsumerQueue<KeyValuePair<TInput, long>> messages = _messages; while (messages.TryDequeue(out ignored)) ; // If we completed with any unhandled exception, finish in an error state if (Volatile.Read(ref _exceptions) != null) { // It's ok to read _exceptions' content here, because // at this point no more exceptions can be generated and thus no one will // be writing to it. _completionSource.TrySetException(Volatile.Read(ref _exceptions)); } // If we completed with cancellation, finish in a canceled state else if (_dataflowBlockOptions.CancellationToken.IsCancellationRequested) { _completionSource.TrySetCanceled(); } // Otherwise, finish in a successful state. else { _completionSource.TrySetResult(default(VoidResult)); } #if FEATURE_TRACING // We only want to do tracing for block completion if this target core represents the whole block. // If it only represents a part of the block (i.e. there's a source associated with it as well), // then we shouldn't log just for the first half of the block; the source half will handle logging. DataflowEtwProvider etwLog; if ((_targetCoreOptions & TargetCoreOptions.RepresentsBlockCompletion) != 0 && (etwLog = DataflowEtwProvider.Log).IsEnabled()) { etwLog.DataflowBlockCompleted(_owningTarget); } #endif } /// <summary>Gets whether the target core is operating in a bounded mode.</summary> internal bool IsBounded { get { return _boundingState != null; } } /// <summary>Increases or decreases the bounding count.</summary> /// <param name="count">The incremental addition (positive to increase, negative to decrease).</param> internal void ChangeBoundingCount(int count) { Debug.Assert(count != 0, "Should only be called when the count is actually changing."); Common.ContractAssertMonitorStatus(IncomingLock, held: false); if (_boundingState != null) { lock (IncomingLock) { Debug.Assert(count > 0 || (count < 0 && _boundingState.CurrentCount + count >= 0), "If count is negative, it must not take the total count negative."); _boundingState.CurrentCount += count; ProcessAsyncIfNecessary(); CompleteBlockIfPossible(); } } } /// <summary>Gets the object to display in the debugger display attribute.</summary> [SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider")] private object DebuggerDisplayContent { get { var displayTarget = _owningTarget as IDebuggerDisplay; return string.Format("Block=\"{0}\"", displayTarget != null ? displayTarget.Content : _owningTarget); } } /// <summary>Gets the DataflowBlockOptions used to configure this block.</summary> internal ExecutionDataflowBlockOptions DataflowBlockOptions { get { return _dataflowBlockOptions; } } /// <summary>Gets information about this helper to be used for display in a debugger.</summary> /// <returns>Debugging information about this target.</returns> internal DebuggingInformation GetDebuggingInformation() { return new DebuggingInformation(this); } /// <summary>Provides a wrapper for commonly needed debugging information.</summary> internal sealed class DebuggingInformation { /// <summary>The target being viewed.</summary> private readonly TargetCore<TInput> _target; /// <summary>Initializes the debugging helper.</summary> /// <param name="target">The target being viewed.</param> internal DebuggingInformation(TargetCore<TInput> target) { _target = target; } /// <summary>Gets the number of messages waiting to be processed.</summary> internal int InputCount { get { return _target._messages.Count; } } /// <summary>Gets the messages waiting to be processed.</summary> internal IEnumerable<TInput> InputQueue { get { return _target._messages.Select(kvp => kvp.Key).ToList(); } } /// <summary>Gets any postponed messages.</summary> internal QueuedMap<ISourceBlock<TInput>, DataflowMessageHeader> PostponedMessages { get { return _target._boundingState != null ? _target._boundingState.PostponedMessages : null; } } /// <summary>Gets the current number of outstanding input processing operations.</summary> internal Int32 CurrentDegreeOfParallelism { get { return _target._numberOfOutstandingOperations - _target._numberOfOutstandingServiceTasks; } } /// <summary>Gets the DataflowBlockOptions used to configure this block.</summary> internal ExecutionDataflowBlockOptions DataflowBlockOptions { get { return _target._dataflowBlockOptions; } } /// <summary>Gets whether the block is declining further messages.</summary> internal bool IsDecliningPermanently { get { return _target._decliningPermanently; } } /// <summary>Gets whether the block is completed.</summary> internal bool IsCompleted { get { return _target.Completion.IsCompleted; } } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // The implementation of the intervals using System; using System.Diagnostics; using Microsoft.Research.AbstractDomains; using System.Diagnostics.Contracts; namespace Microsoft.Research.AbstractDomains.Numerical { [ContractVerification(true)] [ContractClass(typeof(IntervalBaseTypeContracts<,>))] abstract public class IntervalBase<IType, NType> : IAbstractDomain where IType : IntervalBase<IType, NType> { [ContractInvariantMethod] private void ObjectInvariant() { Contract.Invariant(!object.Equals(this.lowerBound, null)); Contract.Invariant(!object.Equals(this.upperBound, null)); } protected /*readonly*/ NType lowerBound; protected /*readonly*/ NType upperBound; protected IntervalBase(NType lower, NType upper) { Contract.Requires(!object.Equals(lower, null)); Contract.Requires(!object.Equals(upper, null)); this.lowerBound = lower; this.upperBound = upper; } #region Common Interval helper methods public NType UpperBound { get { Contract.Ensures(!object.Equals(Contract.Result<NType>(), null)); return this.upperBound; } } public NType LowerBound { get { Contract.Ensures(!object.Equals(Contract.Result<NType>(), null)); return this.lowerBound; } } public bool IsSingleton { get { return this.IsNormal() && lowerBound.Equals(upperBound); } } /// <summary> /// Is this a singleton? If it is, then its value is v /// </summary> /// <param name="v"></param> /// <returns></returns> public bool TryGetSingletonValue(out NType v) { Contract.Ensures(!Contract.Result<bool>() || !(object.Equals(Contract.ValueAtReturn(out v), null))); if (this.IsNormal && this.IsSingleton) { v = this.LowerBound; return true; } else { v = default(NType); return false; } } #endregion #region Type information abstract public bool IsInt32 { get; } abstract public bool IsInt64 { get; } #endregion #region Unknown intervals, etc. public bool IsFinite { get { return this.IsNormal && !this.IsLowerBoundMinusInfinity && !this.IsUpperBoundPlusInfinity; } } #endregion #region To be overridden abstract public bool IsLowerBoundMinusInfinity { get; } abstract public bool IsUpperBoundPlusInfinity { get; } abstract public bool IsNormal { get; } [Pure] abstract public IType ToUnsigned(); [Pure] abstract public bool LessEqual(IType a); abstract public bool IsBottom { get; } abstract public bool IsTop { get; } abstract public IType Bottom { get; } abstract public IType Top { get; } [Pure] abstract public IType Join(IType a); [Pure] abstract public IType Meet(IType a); [Pure] abstract public IType Widening(IType a); [Pure] abstract public IType DuplicateMe(); #endregion #region Code to factor out the interface calls IAbstractDomain IAbstractDomain.Bottom { get { return this.Bottom; } } IAbstractDomain IAbstractDomain.Top { get { return this.Top; } } bool IAbstractDomain.LessEqual(IAbstractDomain a) { return this.LessEqual((IType)a); } IAbstractDomain IAbstractDomain.Join(IAbstractDomain a) { return this.Join((IType)a); } IAbstractDomain IAbstractDomain.Meet(IAbstractDomain a) { return this.Meet((IType)a); } IAbstractDomain IAbstractDomain.Widening(IAbstractDomain/*!*/ prev) { return this.Widening((IType)prev); } #endregion #region To<> public virtual T To<T>(IFactory<T> factory) { T varName; if (this.IsBottom) { return factory.Constant(false); } else if (this.IsTop) { return factory.Constant(true); } else if (factory.TryGetName(out varName)) { } return factory.Constant(true); } public override string ToString() { return "[" + this.LowerBound + ", " + this.upperBound + "]" + (this.IsBottom ? "_|_" : ""); } public object Clone() { return this.DuplicateMe(); } #endregion } [ContractClassFor(typeof(IntervalBase<,>))] internal abstract class IntervalBaseTypeContracts<IType, NType> : IntervalBase<IType, NType> where IType : IntervalBase<IType, NType> { public IntervalBaseTypeContracts(NType lower, NType upper) : base(lower, upper) { } abstract public override bool IsInt32 { get; } abstract public override bool IsInt64 { get; } abstract public override bool IsLowerBoundMinusInfinity { get; } abstract public override bool IsUpperBoundPlusInfinity { get; } abstract public override bool IsNormal { get; } public override bool LessEqual(IType a) { Contract.Requires(a != null); return default(bool); } abstract public override bool IsBottom { get; } abstract public override bool IsTop { get; } public override IType Bottom { get { Contract.Ensures(Contract.Result<IType>() != null); return default(IType); } } public override IType Top { get { Contract.Ensures(Contract.Result<IType>() != null); return default(IType); } } public override IType Join(IType a) { Contract.Requires(a != null); Contract.Ensures(Contract.Result<IType>() != null); return default(IType); } public override IType Meet(IType a) { Contract.Requires(a != null); Contract.Ensures(Contract.Result<IType>() != null); return default(IType); } public override IType Widening(IType a) { Contract.Requires(a != null); Contract.Ensures(Contract.Result<IType>() != null); return default(IType); } public override IType DuplicateMe() { Contract.Ensures(Contract.Result<IType>() != null); return default(IType); } } }
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for Additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ namespace TestCases.XWPF.UserModel { using NPOI.OpenXmlFormats.Wordprocessing; using NPOI.Util; using NPOI.XWPF.UserModel; using NUnit.Framework; using System; using System.Collections.Generic; using System.Text; /** * Tests for XWPF Paragraphs */ [TestFixture] public class TestXWPFParagraph { /** * Check that we Get the right paragraph from the header * @throws IOException */ [Test] public void TestHeaderParagraph() { XWPFDocument xml = XWPFTestDataSamples.OpenSampleDocument("ThreeColHead.docx"); XWPFHeader hdr = xml.GetHeaderFooterPolicy().GetDefaultHeader(); Assert.IsNotNull(hdr); IList<XWPFParagraph> ps = hdr.Paragraphs; Assert.AreEqual(1, ps.Count); XWPFParagraph p = ps[(0)]; Assert.AreEqual(5, p.GetCTP().GetRList().Count); Assert.AreEqual("First header column!\tMid header\tRight header!", p.Text); } /** * Check that we Get the right paragraphs from the document * @throws IOException */ [Test] public void TestDocumentParagraph() { XWPFDocument xml = XWPFTestDataSamples.OpenSampleDocument("ThreeColHead.docx"); IList<XWPFParagraph> ps = xml.Paragraphs; Assert.AreEqual(10, ps.Count); Assert.IsFalse(ps[(0)].IsEmpty); Assert.AreEqual( "This is a sample word document. It has two pages. It has a three column heading, but no footer.", ps[(0)].Text); Assert.IsTrue(ps[1].IsEmpty); Assert.AreEqual("", ps[1].Text); Assert.IsFalse(ps[2].IsEmpty); Assert.AreEqual("HEADING TEXT", ps[2].Text); Assert.IsTrue(ps[3].IsEmpty); Assert.AreEqual("", ps[3].Text); Assert.IsFalse(ps[4].IsEmpty); Assert.AreEqual("More on page one", ps[4].Text); } [Test] public void TestSetBorderTop() { //new clean instance of paragraph XWPFDocument doc = new XWPFDocument(); XWPFParagraph p = doc.CreateParagraph(); Assert.AreEqual(ST_Border.none, EnumConverter.ValueOf<ST_Border, Borders>(p.BorderTop)); CT_P ctp = p.GetCTP(); CT_PPr ppr = ctp.pPr == null ? ctp.AddNewPPr() : ctp.pPr; //bordi CT_PBdr bdr = ppr.AddNewPBdr(); CT_Border borderTop = bdr.AddNewTop(); borderTop.val = (ST_Border.@double); bdr.top = (borderTop); Assert.AreEqual(Borders.Double, p.BorderTop); p.BorderTop = (Borders.Single); Assert.AreEqual(ST_Border.single, borderTop.val); } [Test] public void TestSetAlignment() { //new clean instance of paragraph XWPFDocument doc = new XWPFDocument(); XWPFParagraph p = doc.CreateParagraph(); Assert.AreEqual(ParagraphAlignment.LEFT, p.Alignment); CT_P ctp = p.GetCTP(); CT_PPr ppr = ctp.pPr == null ? ctp.AddNewPPr() : ctp.pPr; CT_Jc align = ppr.AddNewJc(); align.val = (ST_Jc.center); Assert.AreEqual(ParagraphAlignment.CENTER, p.Alignment); p.Alignment = (ParagraphAlignment.BOTH); Assert.AreEqual((int)ST_Jc.both, (int)ppr.jc.val); } [Test] public void TestSetGetSpacing() { XWPFDocument doc = new XWPFDocument(); XWPFParagraph p = doc.CreateParagraph(); CT_P ctp = p.GetCTP(); CT_PPr ppr = ctp.pPr == null ? ctp.AddNewPPr() : ctp.pPr; Assert.AreEqual(-1, p.SpacingAfter); CT_Spacing spacing = ppr.AddNewSpacing(); spacing.after = 10; Assert.AreEqual(10, p.SpacingAfter); p.SpacingAfter = 100; Assert.AreEqual(100, (int)spacing.after); } [Test] public void TestSetGetSpacingLineRule() { XWPFDocument doc = new XWPFDocument(); XWPFParagraph p = doc.CreateParagraph(); CT_P ctp = p.GetCTP(); CT_PPr ppr = ctp.pPr == null ? ctp.AddNewPPr() : ctp.pPr; Assert.AreEqual(LineSpacingRule.AUTO, p.SpacingLineRule); CT_Spacing spacing = ppr.AddNewSpacing(); spacing.lineRule = (ST_LineSpacingRule.atLeast); Assert.AreEqual(LineSpacingRule.ATLEAST, p.SpacingLineRule); p.SpacingAfter = 100; Assert.AreEqual(100, (int)spacing.after); } [Test] public void TestSetGetIndentation() { XWPFDocument doc = new XWPFDocument(); XWPFParagraph p = doc.CreateParagraph(); Assert.AreEqual(-1, p.IndentationLeft); CT_P ctp = p.GetCTP(); CT_PPr ppr = ctp.pPr == null ? ctp.AddNewPPr() : ctp.pPr; Assert.AreEqual(-1, p.IndentationLeft); CT_Ind ind = ppr.AddNewInd(); ind.left = "10"; Assert.AreEqual(10, p.IndentationLeft); p.IndentationLeft = 100; Assert.AreEqual(100, int.Parse(ind.left)); } [Test] public void TestSetGetVerticalAlignment() { //new clean instance of paragraph XWPFDocument doc = new XWPFDocument(); XWPFParagraph p = doc.CreateParagraph(); CT_P ctp = p.GetCTP(); CT_PPr ppr = ctp.pPr == null ? ctp.AddNewPPr() : ctp.pPr; CT_TextAlignment txtAlign = ppr.AddNewTextAlignment(); txtAlign.val = (ST_TextAlignment.center); Assert.AreEqual(TextAlignment.CENTER, p.VerticalAlignment); p.VerticalAlignment = (TextAlignment.BOTTOM); Assert.AreEqual(ST_TextAlignment.bottom, ppr.textAlignment.val); } [Test] public void TestSetGetWordWrap() { XWPFDocument doc = new XWPFDocument(); XWPFParagraph p = doc.CreateParagraph(); CT_P ctp = p.GetCTP(); CT_PPr ppr = ctp.pPr == null ? ctp.AddNewPPr() : ctp.pPr; CT_OnOff wordWrap = ppr.AddNewWordWrap(); wordWrap.val = false; Assert.AreEqual(false, p.IsWordWrap); p.IsWordWrap = true; Assert.AreEqual(true, ppr.wordWrap.val); } [Test] public void TestSetGetPageBreak() { XWPFDocument doc = new XWPFDocument(); XWPFParagraph p = doc.CreateParagraph(); CT_P ctp = p.GetCTP(); CT_PPr ppr = ctp.pPr == null ? ctp.AddNewPPr() : ctp.pPr; CT_OnOff pageBreak = ppr.AddNewPageBreakBefore(); pageBreak.val = false; Assert.AreEqual(false, p.IsPageBreak); p.IsPageBreak = (true); Assert.AreEqual(true, ppr.pageBreakBefore.val); } [Test] public void TestBookmarks() { XWPFDocument doc = XWPFTestDataSamples.OpenSampleDocument("bookmarks.docx"); XWPFParagraph paragraph = doc.Paragraphs[0]; Assert.AreEqual("Sample Word Document", paragraph.Text); Assert.AreEqual(1, paragraph.GetCTP().SizeOfBookmarkStartArray()); Assert.AreEqual(0, paragraph.GetCTP().SizeOfBookmarkEndArray()); CT_Bookmark ctBookmark = paragraph.GetCTP().GetBookmarkStartArray(0); Assert.AreEqual("poi", ctBookmark.name); foreach (CT_Bookmark bookmark in paragraph.GetCTP().GetBookmarkStartList()) { Assert.AreEqual("poi", bookmark.name); } } [Test] public void TestGetSetNumID() { XWPFDocument doc = new XWPFDocument(); XWPFParagraph p = doc.CreateParagraph(); p.SetNumID("10"); Assert.AreEqual("10", p.GetNumID()); } [Test] public void TestGetSetILvl() { XWPFDocument doc = new XWPFDocument(); XWPFParagraph p = doc.CreateParagraph(); p.SetNumILvl("1"); Assert.AreEqual("1", p.GetNumIlvl()); } [Test] public void TestAddingRuns() { XWPFDocument doc = XWPFTestDataSamples.OpenSampleDocument("sample.docx"); XWPFParagraph p = doc.Paragraphs[0]; Assert.AreEqual(2, p.Runs.Count); XWPFRun r = p.CreateRun(); Assert.AreEqual(3, p.Runs.Count); Assert.AreEqual(2, p.Runs.IndexOf(r)); XWPFRun r2 = p.InsertNewRun(1); Assert.AreEqual(4, p.Runs.Count); Assert.AreEqual(1, p.Runs.IndexOf(r2)); Assert.AreEqual(3, p.Runs.IndexOf(r)); } [Test] public void TestPictures() { XWPFDocument doc = XWPFTestDataSamples.OpenSampleDocument("VariousPictures.docx"); Assert.AreEqual(7, doc.Paragraphs.Count); XWPFParagraph p; XWPFRun r; // Text paragraphs Assert.AreEqual("Sheet with various pictures", doc.Paragraphs[0].Text); Assert.AreEqual("(jpeg, png, wmf, emf and pict) ", doc.Paragraphs[1].Text); // Spacer ones Assert.AreEqual("", doc.Paragraphs[2].Text); Assert.AreEqual("", doc.Paragraphs[3].Text); Assert.AreEqual("", doc.Paragraphs[4].Text); // Image one p = doc.Paragraphs[5]; Assert.AreEqual(6, p.Runs.Count); r = p.Runs[0]; Assert.AreEqual("", r.ToString()); Assert.AreEqual(1, r.GetEmbeddedPictures().Count); Assert.IsNotNull(r.GetEmbeddedPictures()[0].GetPictureData()); Assert.AreEqual("image1.wmf", r.GetEmbeddedPictures()[0].GetPictureData().FileName); r = p.Runs[1]; Assert.AreEqual("", r.ToString()); Assert.AreEqual(1, r.GetEmbeddedPictures().Count); Assert.IsNotNull(r.GetEmbeddedPictures()[0].GetPictureData()); Assert.AreEqual("image2.png", r.GetEmbeddedPictures()[0].GetPictureData().FileName); r = p.Runs[2]; Assert.AreEqual("", r.ToString()); Assert.AreEqual(1, r.GetEmbeddedPictures().Count); Assert.IsNotNull(r.GetEmbeddedPictures()[0].GetPictureData()); Assert.AreEqual("image3.emf", r.GetEmbeddedPictures()[0].GetPictureData().FileName); r = p.Runs[3]; Assert.AreEqual("", r.ToString()); Assert.AreEqual(1, r.GetEmbeddedPictures().Count); Assert.IsNotNull(r.GetEmbeddedPictures()[0].GetPictureData()); Assert.AreEqual("image4.emf", r.GetEmbeddedPictures()[0].GetPictureData().FileName); r = p.Runs[4]; Assert.AreEqual("", r.ToString()); Assert.AreEqual(1, r.GetEmbeddedPictures().Count); Assert.IsNotNull(r.GetEmbeddedPictures()[0].GetPictureData()); Assert.AreEqual("image5.jpeg", r.GetEmbeddedPictures()[0].GetPictureData().FileName); r = p.Runs[5]; //Is there a bug about XmlSerializer? it can not Deserialize the tag which inner text is only one whitespace //e.g. <w:t> </w:t> to CT_Text; //TODO Assert.AreEqual(" ", r.ToString()); Assert.AreEqual(0, r.GetEmbeddedPictures().Count); // Final spacer Assert.AreEqual("", doc.Paragraphs[(6)].Text); // Look in detail at one r = p.Runs[4]; XWPFPicture pict = r.GetEmbeddedPictures()[0]; //CT_Picture picture = pict.GetCTPicture(); NPOI.OpenXmlFormats.Dml.Picture.CT_Picture picture = pict.GetCTPicture(); //Assert.Fail("picture.blipFill.blip.embed is missing from wordprocessing CT_Picture."); Assert.AreEqual("rId8", picture.blipFill.blip.embed); // Ensure that the ooxml compiler Finds everything we need r.GetCTR().GetDrawingArray(0); r.GetCTR().GetDrawingArray(0).GetInlineArray(0); NPOI.OpenXmlFormats.Dml.CT_GraphicalObject go = r.GetCTR().GetDrawingArray(0).GetInlineArray(0).graphic; NPOI.OpenXmlFormats.Dml.CT_GraphicalObjectData god = r.GetCTR().GetDrawingArray(0).GetInlineArray(0).graphic.graphicData; //PicDocument pd = new PicDocumentImpl(null); //assertTrue(pd.isNil()); } [Test] public void TestTika792() { //This test forces the loading of CTMoveBookmark and //CTMoveBookmarkImpl into ooxml-lite. XWPFDocument doc = XWPFTestDataSamples.OpenSampleDocument("Tika-792.docx"); XWPFParagraph paragraph = doc.Paragraphs[(0)]; Assert.AreEqual("s", paragraph.Text); } [Test] public void TestSettersGetters() { XWPFDocument doc = new XWPFDocument(); XWPFParagraph p = doc.CreateParagraph(); //Assert.IsTrue(p.IsEmpty); Assert.IsFalse(p.RemoveRun(0)); p.BorderTop = (/*setter*/Borders.BabyPacifier); p.BorderBetween = (/*setter*/Borders.BabyPacifier); p.BorderBottom = (/*setter*/Borders.BabyPacifier); Assert.IsNotNull(p.IRuns); Assert.AreEqual(0, p.IRuns.Count); Assert.IsFalse(p.IsEmpty); Assert.IsNull(p.StyleID); Assert.IsNull(p.Style); Assert.IsNull(p.GetNumID()); p.SetNumID("12"); Assert.AreEqual("12", p.GetNumID()); p.SetNumID("13"); Assert.AreEqual("13", p.GetNumID()); Assert.IsNull(p.GetNumFmt()); //Assert.IsNull(p.GetNumIlvl()); Assert.AreEqual("", p.ParagraphText); Assert.AreEqual("", p.PictureText); Assert.AreEqual("", p.FootnoteText); p.BorderBetween = (/*setter*/Borders.None); Assert.AreEqual(Borders.None, p.BorderBetween); p.BorderBetween = (/*setter*/Borders.BasicBlackDashes); Assert.AreEqual(Borders.BasicBlackDashes, p.BorderBetween); p.BorderBottom = (/*setter*/Borders.None); Assert.AreEqual(Borders.None, p.BorderBottom); p.BorderBottom = (/*setter*/Borders.BabyPacifier); Assert.AreEqual(Borders.BabyPacifier, p.BorderBottom); p.BorderLeft = (/*setter*/Borders.None); Assert.AreEqual(Borders.None, p.BorderLeft); p.BorderLeft = (/*setter*/Borders.BasicWhiteSquares); Assert.AreEqual(Borders.BasicWhiteSquares, p.BorderLeft); p.BorderRight = (/*setter*/Borders.None); Assert.AreEqual(Borders.None, p.BorderRight); p.BorderRight = (/*setter*/Borders.BasicWhiteDashes); Assert.AreEqual(Borders.BasicWhiteDashes, p.BorderRight); p.BorderBottom = (/*setter*/Borders.None); Assert.AreEqual(Borders.None, p.BorderBottom); p.BorderBottom = (/*setter*/Borders.BasicWhiteDots); Assert.AreEqual(Borders.BasicWhiteDots, p.BorderBottom); Assert.IsFalse(p.IsPageBreak); p.IsPageBreak = (/*setter*/true); Assert.IsTrue(p.IsPageBreak); p.IsPageBreak = (/*setter*/false); Assert.IsFalse(p.IsPageBreak); Assert.AreEqual(-1, p.SpacingAfter); p.SpacingAfter = (/*setter*/12); Assert.AreEqual(12, p.SpacingAfter); Assert.AreEqual(-1, p.SpacingAfterLines); p.SpacingAfterLines = (/*setter*/14); Assert.AreEqual(14, p.SpacingAfterLines); Assert.AreEqual(-1, p.SpacingBefore); p.SpacingBefore = (/*setter*/16); Assert.AreEqual(16, p.SpacingBefore); Assert.AreEqual(-1, p.SpacingBeforeLines); p.SpacingBeforeLines = (/*setter*/18); Assert.AreEqual(18, p.SpacingBeforeLines); Assert.AreEqual(LineSpacingRule.AUTO, p.SpacingLineRule); p.SpacingLineRule = (/*setter*/LineSpacingRule.EXACT); Assert.AreEqual(LineSpacingRule.EXACT, p.SpacingLineRule); Assert.AreEqual(-1, p.IndentationLeft); p.IndentationLeft = (/*setter*/21); Assert.AreEqual(21, p.IndentationLeft); Assert.AreEqual(-1, p.IndentationRight); p.IndentationRight = (/*setter*/25); Assert.AreEqual(25, p.IndentationRight); Assert.AreEqual(-1, p.IndentationHanging); p.IndentationHanging = (/*setter*/25); Assert.AreEqual(25, p.IndentationHanging); Assert.AreEqual(-1, p.IndentationFirstLine); p.IndentationFirstLine = (/*setter*/25); Assert.AreEqual(25, p.IndentationFirstLine); Assert.IsFalse(p.IsWordWrap); p.IsWordWrap = (/*setter*/true); Assert.IsTrue(p.IsWordWrap); p.IsWordWrap = (/*setter*/false); Assert.IsFalse(p.IsWordWrap); Assert.IsNull(p.Style); p.Style = (/*setter*/"teststyle"); Assert.AreEqual("teststyle", p.Style); p.AddRun(new CT_R()); //Assert.IsTrue(p.RemoveRun(0)); Assert.IsNotNull(p.Body); Assert.AreEqual(BodyElementType.PARAGRAPH, p.ElementType); Assert.AreEqual(BodyType.DOCUMENT, p.PartType); } [Test] public void TestSearchTextNotFound() { XWPFDocument doc = new XWPFDocument(); XWPFParagraph p = doc.CreateParagraph(); Assert.IsNull(p.SearchText("test", new PositionInParagraph())); Assert.AreEqual("", p.Text); } [Test] public void TestSearchTextFound() { XWPFDocument xml = XWPFTestDataSamples.OpenSampleDocument("ThreeColHead.docx"); IList<XWPFParagraph> ps = xml.Paragraphs; Assert.AreEqual(10, ps.Count); XWPFParagraph p = ps[(0)]; TextSegment segment = p.SearchText("sample word document", new PositionInParagraph()); Assert.IsNotNull(segment); Assert.AreEqual("sample word document", p.GetText(segment)); Assert.IsTrue(p.RemoveRun(0)); } [Test] public void TestFieldRuns() { XWPFDocument doc = XWPFTestDataSamples.OpenSampleDocument("FldSimple.docx"); IList<XWPFParagraph> ps = doc.Paragraphs; Assert.AreEqual(1, ps.Count); XWPFParagraph p = ps[0]; Assert.AreEqual(1, p.Runs.Count); Assert.AreEqual(1, p.IRuns.Count); XWPFRun r = p.Runs[0]; Assert.AreEqual(typeof(XWPFFieldRun), r.GetType()); XWPFFieldRun fr = (XWPFFieldRun)r; Assert.AreEqual(" FILENAME \\* MERGEFORMAT ", fr.FieldInstruction); Assert.AreEqual("FldSimple.docx", fr.Text); Assert.AreEqual("FldSimple.docx", p.Text); } [Test] public void TestRuns() { XWPFDocument doc = new XWPFDocument(); XWPFParagraph p = doc.CreateParagraph(); CT_R run = new CT_R(); XWPFRun r = new XWPFRun(run, doc.CreateParagraph()); p.AddRun(r); p.AddRun(r); Assert.IsNotNull(p.GetRun(run)); Assert.IsNull(p.GetRun(null)); } [Test] public void Test58067() { XWPFDocument doc = XWPFTestDataSamples.OpenSampleDocument("58067.docx"); StringBuilder str = new StringBuilder(); foreach (XWPFParagraph par in doc.Paragraphs) { str.Append(par.Text).Append("\n"); } Assert.AreEqual("This is a test.\n\n\n\n3\n4\n5\n\n\n\nThis is a whole paragraph where one word is deleted.\n", str.ToString()); } [Test] public void Test61787() { XWPFDocument doc = XWPFTestDataSamples.OpenSampleDocument("61787.docx"); StringBuilder str = new StringBuilder(); foreach (XWPFParagraph par in doc.Paragraphs) { str.Append(par.Text).Append("\n"); } String s = str.ToString(); Assert.IsTrue(s.Trim().Length > 0, "Having text: \n" + s + "\nTrimmed lenght: " + s.Trim().Length); } [Test] public void Test61787_1() { XWPFDocument doc = XWPFTestDataSamples.OpenSampleDocument("61787-1.docx"); StringBuilder str = new StringBuilder(); foreach (XWPFParagraph par in doc.Paragraphs) { str.Append(par.Text).Append("\n"); } String s = str.ToString(); Assert.IsFalse(s.Contains("This is another Test")); } [Test] public void Testpullrequest404() { XWPFDocument doc = new XWPFDocument(); var paragraph = doc.CreateParagraph(); paragraph.CreateRun().AppendText("abc"); paragraph.CreateRun().AppendText("de"); paragraph.CreateRun().AppendText("f"); paragraph.CreateRun().AppendText("g"); var result = paragraph.SearchText("cdefg",new PositionInParagraph()); Assert.AreEqual(result.BeginRun, 0); Assert.AreEqual(result.EndRun, 3); Assert.AreEqual(result.BeginText, 0); Assert.AreEqual(result.EndText, 0); Assert.AreEqual(result.BeginChar, 2); Assert.AreEqual(result.EndChar, 0); } [Test] public void Testpullrequest404_1() { XWPFDocument doc = new XWPFDocument(); var paragraph = doc.CreateParagraph(); paragraph.CreateRun().AppendText("abc"); paragraph.CreateRun().AppendText("de"); paragraph.CreateRun().AppendText("fg"); paragraph.CreateRun().AppendText("hi"); var result = paragraph.SearchText("cdefg",new PositionInParagraph()); Assert.AreEqual(result.BeginRun, 0); Assert.AreEqual(result.EndRun, 2); Assert.AreEqual(result.BeginText, 0); Assert.AreEqual(result.EndText, 0); Assert.AreEqual(result.BeginChar, 2); Assert.AreEqual(result.EndChar, 1); } } }
// 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.AcceptanceTestsModelFlattening { 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 Models; /// <summary> /// Resource Flattening for AutoRest /// </summary> public partial class AutoRestResourceFlatteningTestService : ServiceClient<AutoRestResourceFlatteningTestService>, IAutoRestResourceFlatteningTestService { /// <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> /// Initializes a new instance of the AutoRestResourceFlatteningTestService class. /// </summary> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> public AutoRestResourceFlatteningTestService(params DelegatingHandler[] handlers) : base(handlers) { this.Initialize(); } /// <summary> /// Initializes a new instance of the AutoRestResourceFlatteningTestService 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> public AutoRestResourceFlatteningTestService(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers) { this.Initialize(); } /// <summary> /// Initializes a new instance of the AutoRestResourceFlatteningTestService 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> public AutoRestResourceFlatteningTestService(Uri baseUri, params DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new ArgumentNullException("baseUri"); } this.BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the AutoRestResourceFlatteningTestService 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> public AutoRestResourceFlatteningTestService(Uri baseUri, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new ArgumentNullException("baseUri"); } this.BaseUri = baseUri; } /// <summary> /// An optional partial-method to perform custom initialization. ///</summary> partial void CustomInitialize(); /// <summary> /// Initializes client properties. /// </summary> private void Initialize() { this.BaseUri = new Uri("http://localhost"); 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() } }; SerializationSettings.Converters.Add(new TransformationJsonConverter()); DeserializationSettings = new JsonSerializerSettings { DateFormatHandling = DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = DateTimeZoneHandling.Utc, NullValueHandling = NullValueHandling.Ignore, ReferenceLoopHandling = ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new List<JsonConverter> { new Iso8601TimeSpanConverter() } }; CustomInitialize(); DeserializationSettings.Converters.Add(new TransformationJsonConverter()); } /// <summary> /// Put External Resource as an Array /// </summary> /// <param name='resourceArray'> /// External Resource as an Array to put /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse> PutArrayWithHttpMessagesAsync(IList<Resource> resourceArray = default(IList<Resource>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceArray", resourceArray); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "PutArray", tracingParameters); } // Construct URL var _baseUrl = this.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "model-flatten/array").ToString(); // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new Uri(_url); // Set Headers 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(resourceArray != null) { _requestContent = SafeJsonConvert.SerializeObject(resourceArray, this.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.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 ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get External Resource as an Array /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse<IList<FlattenedProduct>>> GetArrayWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetArray", tracingParameters); } // Construct URL var _baseUrl = this.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "model-flatten/array").ToString(); // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers 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; // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.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 ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse<IList<FlattenedProduct>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<IList<FlattenedProduct>>(_responseContent, this.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> /// Put External Resource as a Dictionary /// </summary> /// <param name='resourceDictionary'> /// External Resource as a Dictionary to put /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse> PutDictionaryWithHttpMessagesAsync(IDictionary<string, FlattenedProduct> resourceDictionary = default(IDictionary<string, FlattenedProduct>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceDictionary", resourceDictionary); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "PutDictionary", tracingParameters); } // Construct URL var _baseUrl = this.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "model-flatten/dictionary").ToString(); // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new Uri(_url); // Set Headers 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(resourceDictionary != null) { _requestContent = SafeJsonConvert.SerializeObject(resourceDictionary, this.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.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 ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get External Resource as a Dictionary /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse<IDictionary<string, FlattenedProduct>>> GetDictionaryWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetDictionary", tracingParameters); } // Construct URL var _baseUrl = this.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "model-flatten/dictionary").ToString(); // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers 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; // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.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 ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse<IDictionary<string, FlattenedProduct>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<IDictionary<string, FlattenedProduct>>(_responseContent, this.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> /// Put External Resource as a ResourceCollection /// </summary> /// <param name='resourceComplexObject'> /// External Resource as a ResourceCollection to put /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse> PutResourceCollectionWithHttpMessagesAsync(ResourceCollection resourceComplexObject = default(ResourceCollection), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceComplexObject", resourceComplexObject); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "PutResourceCollection", tracingParameters); } // Construct URL var _baseUrl = this.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "model-flatten/resourcecollection").ToString(); // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new Uri(_url); // Set Headers 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(resourceComplexObject != null) { _requestContent = SafeJsonConvert.SerializeObject(resourceComplexObject, this.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.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 ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get External Resource as a ResourceCollection /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse<ResourceCollection>> GetResourceCollectionWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetResourceCollection", tracingParameters); } // Construct URL var _baseUrl = this.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "model-flatten/resourcecollection").ToString(); // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers 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; // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.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 ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse<ResourceCollection>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<ResourceCollection>(_responseContent, this.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> /// Put Simple Product with client flattening true on the model /// </summary> /// <param name='simpleBodyProduct'> /// Simple body product to put /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse<SimpleProduct>> PutSimpleProductWithHttpMessagesAsync(SimpleProduct simpleBodyProduct = default(SimpleProduct), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (simpleBodyProduct != null) { simpleBodyProduct.Validate(); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("simpleBodyProduct", simpleBodyProduct); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "PutSimpleProduct", tracingParameters); } // Construct URL var _baseUrl = this.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "model-flatten/customFlattening").ToString(); // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new Uri(_url); // Set Headers 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(simpleBodyProduct != null) { _requestContent = SafeJsonConvert.SerializeObject(simpleBodyProduct, this.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.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 ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse<SimpleProduct>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<SimpleProduct>(_responseContent, this.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> /// Put Flattened Simple Product with client flattening true on the parameter /// </summary> /// <param name='productId'> /// Unique identifier representing a specific product for a given latitude /// &amp; longitude. For example, uberX in San Francisco will have a /// different product_id than uberX in Los Angeles. /// </param> /// <param name='maxProductDisplayName'> /// Display name of product. /// </param> /// <param name='description'> /// Description of product. /// </param> /// <param name='genericValue'> /// Generic URL value. /// </param> /// <param name='odatavalue'> /// URL value. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// 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> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse<SimpleProduct>> PostFlattenedSimpleProductWithHttpMessagesAsync(string productId, string maxProductDisplayName, string description = default(string), string genericValue = default(string), string odatavalue = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (productId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "productId"); } if (maxProductDisplayName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "maxProductDisplayName"); } SimpleProduct simpleBodyProduct = default(SimpleProduct); if (productId != null || description != null || maxProductDisplayName != null || genericValue != null || odatavalue != null) { simpleBodyProduct = new SimpleProduct(); simpleBodyProduct.ProductId = productId; simpleBodyProduct.Description = description; simpleBodyProduct.MaxProductDisplayName = maxProductDisplayName; simpleBodyProduct.GenericValue = genericValue; simpleBodyProduct.Odatavalue = odatavalue; } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("simpleBodyProduct", simpleBodyProduct); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "PostFlattenedSimpleProduct", tracingParameters); } // Construct URL var _baseUrl = this.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "model-flatten/customFlattening").ToString(); // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("POST"); _httpRequest.RequestUri = new Uri(_url); // Set Headers 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(simpleBodyProduct != null) { _requestContent = SafeJsonConvert.SerializeObject(simpleBodyProduct, this.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.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 ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse<SimpleProduct>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<SimpleProduct>(_responseContent, this.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> /// Put Simple Product with client flattening true on the model /// </summary> /// <param name='flattenParameterGroup'> /// Additional parameters for the operation /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// 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> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse<SimpleProduct>> PutSimpleProductWithGroupingWithHttpMessagesAsync(FlattenParameterGroup flattenParameterGroup, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (flattenParameterGroup == null) { throw new ValidationException(ValidationRules.CannotBeNull, "flattenParameterGroup"); } if (flattenParameterGroup != null) { flattenParameterGroup.Validate(); } string name = default(string); if (flattenParameterGroup != null) { name = flattenParameterGroup.Name; } string productId = default(string); if (flattenParameterGroup != null) { productId = flattenParameterGroup.ProductId; } string description = default(string); if (flattenParameterGroup != null) { description = flattenParameterGroup.Description; } string maxProductDisplayName = default(string); if (flattenParameterGroup != null) { maxProductDisplayName = flattenParameterGroup.MaxProductDisplayName; } string genericValue = default(string); if (flattenParameterGroup != null) { genericValue = flattenParameterGroup.GenericValue; } string odatavalue = default(string); if (flattenParameterGroup != null) { odatavalue = flattenParameterGroup.Odatavalue; } SimpleProduct simpleBodyProduct = default(SimpleProduct); if (productId != null || description != null || maxProductDisplayName != null || genericValue != null || odatavalue != null) { simpleBodyProduct = new SimpleProduct(); simpleBodyProduct.ProductId = productId; simpleBodyProduct.Description = description; simpleBodyProduct.MaxProductDisplayName = maxProductDisplayName; simpleBodyProduct.GenericValue = genericValue; simpleBodyProduct.Odatavalue = odatavalue; } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("name", name); tracingParameters.Add("productId", productId); tracingParameters.Add("description", description); tracingParameters.Add("maxProductDisplayName", maxProductDisplayName); tracingParameters.Add("genericValue", genericValue); tracingParameters.Add("odatavalue", odatavalue); tracingParameters.Add("simpleBodyProduct", simpleBodyProduct); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "PutSimpleProductWithGrouping", tracingParameters); } // Construct URL var _baseUrl = this.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "model-flatten/customFlattening/parametergrouping/{name}/").ToString(); _url = _url.Replace("{name}", Uri.EscapeDataString(name)); // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new Uri(_url); // Set Headers 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(simpleBodyProduct != null) { _requestContent = SafeJsonConvert.SerializeObject(simpleBodyProduct, this.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.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 ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse<SimpleProduct>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<SimpleProduct>(_responseContent, this.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; } } }
// 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. // ------------------------------------------------------------------------------ // Changes to this file must follow the http://aka.ms/api-review process. // ------------------------------------------------------------------------------ namespace System.ComponentModel { [System.AttributeUsageAttribute(System.AttributeTargets.All)] public sealed partial class BrowsableAttribute : System.Attribute { public static readonly System.ComponentModel.BrowsableAttribute Default; public static readonly System.ComponentModel.BrowsableAttribute No; public static readonly System.ComponentModel.BrowsableAttribute Yes; public BrowsableAttribute(bool browsable) { } public bool Browsable { get { throw null; } } public override bool Equals(object obj) { throw null; } public override int GetHashCode() { throw null; } public override bool IsDefaultAttribute() { throw null; } } [System.AttributeUsageAttribute(System.AttributeTargets.All)] public partial class CategoryAttribute : System.Attribute { public CategoryAttribute() { } public CategoryAttribute(string category) { } public static System.ComponentModel.CategoryAttribute Action { get { throw null; } } public static System.ComponentModel.CategoryAttribute Appearance { get { throw null; } } public static System.ComponentModel.CategoryAttribute Asynchronous { get { throw null; } } public static System.ComponentModel.CategoryAttribute Behavior { get { throw null; } } public string Category { get { throw null; } } public static System.ComponentModel.CategoryAttribute Data { get { throw null; } } public static System.ComponentModel.CategoryAttribute Default { get { throw null; } } public static System.ComponentModel.CategoryAttribute Design { get { throw null; } } public static System.ComponentModel.CategoryAttribute DragDrop { get { throw null; } } public static System.ComponentModel.CategoryAttribute Focus { get { throw null; } } public static System.ComponentModel.CategoryAttribute Format { get { throw null; } } public static System.ComponentModel.CategoryAttribute Key { get { throw null; } } public static System.ComponentModel.CategoryAttribute Layout { get { throw null; } } public static System.ComponentModel.CategoryAttribute Mouse { get { throw null; } } public static System.ComponentModel.CategoryAttribute WindowStyle { get { throw null; } } public override bool Equals(object obj) { throw null; } public override int GetHashCode() { throw null; } protected virtual string GetLocalizedString(string value) { throw null; } public override bool IsDefaultAttribute() { throw null; } } [System.ComponentModel.DesignerCategoryAttribute("Component")] public partial class Component : System.MarshalByRefObject, System.ComponentModel.IComponent, System.IDisposable { public Component() { } protected virtual bool CanRaiseEvents { get { throw null; } } [System.ComponentModel.BrowsableAttribute(false)] [System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] public System.ComponentModel.IContainer Container { get { throw null; } } [System.ComponentModel.BrowsableAttribute(false)] [System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] protected bool DesignMode { get { throw null; } } protected System.ComponentModel.EventHandlerList Events { get { throw null; } } [System.ComponentModel.BrowsableAttribute(false)] [System.ComponentModel.DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] public virtual System.ComponentModel.ISite Site { get { throw null; } set { } } [System.ComponentModel.BrowsableAttribute(false)] [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)] public event System.EventHandler Disposed { add { } remove { } } public void Dispose() { } protected virtual void Dispose(bool disposing) { } ~Component() { } protected virtual object GetService(System.Type service) { throw null; } public override string ToString() { throw null; } } public partial class ComponentCollection : System.Collections.ReadOnlyCollectionBase { public ComponentCollection(System.ComponentModel.IComponent[] components) { } public virtual System.ComponentModel.IComponent this[int index] { get { throw null; } } public virtual System.ComponentModel.IComponent this[string name] { get { throw null; } } public void CopyTo(System.ComponentModel.IComponent[] array, int index) { } } [System.AttributeUsageAttribute(System.AttributeTargets.All)] public partial class DescriptionAttribute : System.Attribute { public static readonly System.ComponentModel.DescriptionAttribute Default; public DescriptionAttribute() { } public DescriptionAttribute(string description) { } public virtual string Description { get { throw null; } } protected string DescriptionValue { get { throw null; } set { } } public override bool Equals(object obj) { throw null; } public override int GetHashCode() { throw null; } public override bool IsDefaultAttribute() { throw null; } } [System.AttributeUsageAttribute(System.AttributeTargets.Class, AllowMultiple=false, Inherited=true)] public sealed partial class DesignerCategoryAttribute : System.Attribute { public static readonly System.ComponentModel.DesignerCategoryAttribute Component; public static readonly System.ComponentModel.DesignerCategoryAttribute Default; public static readonly System.ComponentModel.DesignerCategoryAttribute Form; public static readonly System.ComponentModel.DesignerCategoryAttribute Generic; public DesignerCategoryAttribute() { } public DesignerCategoryAttribute(string category) { } public string Category { get { throw null; } } public override object TypeId { get { throw null; } } public override bool Equals(object obj) { throw null; } public override int GetHashCode() { throw null; } public override bool IsDefaultAttribute() { throw null; } } public enum DesignerSerializationVisibility { Hidden = 0, Visible = 1, Content = 2, } [System.AttributeUsageAttribute(System.AttributeTargets.Event | System.AttributeTargets.Field | System.AttributeTargets.Method | System.AttributeTargets.Property)] public sealed partial class DesignerSerializationVisibilityAttribute : System.Attribute { public static readonly System.ComponentModel.DesignerSerializationVisibilityAttribute Content; public static readonly System.ComponentModel.DesignerSerializationVisibilityAttribute Default; public static readonly System.ComponentModel.DesignerSerializationVisibilityAttribute Hidden; public static readonly System.ComponentModel.DesignerSerializationVisibilityAttribute Visible; public DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility visibility) { } public System.ComponentModel.DesignerSerializationVisibility Visibility { get { throw null; } } public override bool Equals(object obj) { throw null; } public override int GetHashCode() { throw null; } public override bool IsDefaultAttribute() { throw null; } } [System.AttributeUsageAttribute(System.AttributeTargets.All)] public sealed partial class DesignOnlyAttribute : System.Attribute { public static readonly System.ComponentModel.DesignOnlyAttribute Default; public static readonly System.ComponentModel.DesignOnlyAttribute No; public static readonly System.ComponentModel.DesignOnlyAttribute Yes; public DesignOnlyAttribute(bool isDesignOnly) { } public bool IsDesignOnly { get { throw null; } } public override bool Equals(object obj) { throw null; } public override int GetHashCode() { throw null; } public override bool IsDefaultAttribute() { throw null; } } [System.AttributeUsageAttribute(System.AttributeTargets.Class | System.AttributeTargets.Event | System.AttributeTargets.Method | System.AttributeTargets.Property)] public partial class DisplayNameAttribute : System.Attribute { public static readonly System.ComponentModel.DisplayNameAttribute Default; public DisplayNameAttribute() { } public DisplayNameAttribute(string displayName) { } public virtual string DisplayName { get { throw null; } } protected string DisplayNameValue { get { throw null; } set { } } public override bool Equals(object obj) { throw null; } public override int GetHashCode() { throw null; } public override bool IsDefaultAttribute() { throw null; } } public sealed partial class EventHandlerList : System.IDisposable { public EventHandlerList() { } public System.Delegate this[object key] { get { throw null; } set { } } public void AddHandler(object key, System.Delegate value) { } public void AddHandlers(System.ComponentModel.EventHandlerList listToAddFrom) { } public void Dispose() { } public void RemoveHandler(object key, System.Delegate value) { } } public partial interface IComponent : System.IDisposable { System.ComponentModel.ISite Site { get; set; } event System.EventHandler Disposed; } public partial interface IContainer : System.IDisposable { System.ComponentModel.ComponentCollection Components { get; } void Add(System.ComponentModel.IComponent component); void Add(System.ComponentModel.IComponent component, string name); void Remove(System.ComponentModel.IComponent component); } [System.AttributeUsageAttribute(System.AttributeTargets.All)] public sealed partial class ImmutableObjectAttribute : System.Attribute { public static readonly System.ComponentModel.ImmutableObjectAttribute Default; public static readonly System.ComponentModel.ImmutableObjectAttribute No; public static readonly System.ComponentModel.ImmutableObjectAttribute Yes; public ImmutableObjectAttribute(bool immutable) { } public bool Immutable { get { throw null; } } public override bool Equals(object obj) { throw null; } public override int GetHashCode() { throw null; } public override bool IsDefaultAttribute() { throw null; } } [System.AttributeUsageAttribute(System.AttributeTargets.Class)] public sealed partial class InitializationEventAttribute : System.Attribute { public InitializationEventAttribute(string eventName) { } public string EventName { get { throw null; } } } public partial class InvalidAsynchronousStateException : System.ArgumentException { public InvalidAsynchronousStateException() { } protected InvalidAsynchronousStateException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public InvalidAsynchronousStateException(string message) { } public InvalidAsynchronousStateException(string message, System.Exception innerException) { } } public partial class InvalidEnumArgumentException : System.ArgumentException { public InvalidEnumArgumentException() { } protected InvalidEnumArgumentException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } public InvalidEnumArgumentException(string message) { } public InvalidEnumArgumentException(string message, System.Exception innerException) { } public InvalidEnumArgumentException(string argumentName, int invalidValue, System.Type enumClass) { } } public partial interface ISite : System.IServiceProvider { System.ComponentModel.IComponent Component { get; } System.ComponentModel.IContainer Container { get; } bool DesignMode { get; } string Name { get; set; } } public partial interface ISupportInitialize { void BeginInit(); void EndInit(); } public partial interface ISynchronizeInvoke { bool InvokeRequired { get; } System.IAsyncResult BeginInvoke(System.Delegate method, object[] args); object EndInvoke(System.IAsyncResult result); object Invoke(System.Delegate method, object[] args); } [System.AttributeUsageAttribute(System.AttributeTargets.All)] public sealed partial class LocalizableAttribute : System.Attribute { public static readonly System.ComponentModel.LocalizableAttribute Default; public static readonly System.ComponentModel.LocalizableAttribute No; public static readonly System.ComponentModel.LocalizableAttribute Yes; public LocalizableAttribute(bool isLocalizable) { } public bool IsLocalizable { get { throw null; } } public override bool Equals(object obj) { throw null; } public override int GetHashCode() { throw null; } public override bool IsDefaultAttribute() { throw null; } } [System.AttributeUsageAttribute(System.AttributeTargets.All)] public sealed partial class MergablePropertyAttribute : System.Attribute { public static readonly System.ComponentModel.MergablePropertyAttribute Default; public static readonly System.ComponentModel.MergablePropertyAttribute No; public static readonly System.ComponentModel.MergablePropertyAttribute Yes; public MergablePropertyAttribute(bool allowMerge) { } public bool AllowMerge { get { throw null; } } public override bool Equals(object obj) { throw null; } public override int GetHashCode() { throw null; } public override bool IsDefaultAttribute() { throw null; } } [System.AttributeUsageAttribute(System.AttributeTargets.Property)] public sealed partial class NotifyParentPropertyAttribute : System.Attribute { public static readonly System.ComponentModel.NotifyParentPropertyAttribute Default; public static readonly System.ComponentModel.NotifyParentPropertyAttribute No; public static readonly System.ComponentModel.NotifyParentPropertyAttribute Yes; public NotifyParentPropertyAttribute(bool notifyParent) { } public bool NotifyParent { get { throw null; } } public override bool Equals(object obj) { throw null; } public override int GetHashCode() { throw null; } public override bool IsDefaultAttribute() { throw null; } } [System.AttributeUsageAttribute(System.AttributeTargets.All)] public sealed partial class ParenthesizePropertyNameAttribute : System.Attribute { public static readonly System.ComponentModel.ParenthesizePropertyNameAttribute Default; public ParenthesizePropertyNameAttribute() { } public ParenthesizePropertyNameAttribute(bool needParenthesis) { } public bool NeedParenthesis { get { throw null; } } public override bool Equals(object o) { throw null; } public override int GetHashCode() { throw null; } public override bool IsDefaultAttribute() { throw null; } } [System.AttributeUsageAttribute(System.AttributeTargets.All)] public sealed partial class ReadOnlyAttribute : System.Attribute { public static readonly System.ComponentModel.ReadOnlyAttribute Default; public static readonly System.ComponentModel.ReadOnlyAttribute No; public static readonly System.ComponentModel.ReadOnlyAttribute Yes; public ReadOnlyAttribute(bool isReadOnly) { } public bool IsReadOnly { get { throw null; } } public override bool Equals(object value) { throw null; } public override int GetHashCode() { throw null; } public override bool IsDefaultAttribute() { throw null; } } public enum RefreshProperties { None = 0, All = 1, Repaint = 2, } [System.AttributeUsageAttribute(System.AttributeTargets.All)] public sealed partial class RefreshPropertiesAttribute : System.Attribute { public static readonly System.ComponentModel.RefreshPropertiesAttribute All; public static readonly System.ComponentModel.RefreshPropertiesAttribute Default; public static readonly System.ComponentModel.RefreshPropertiesAttribute Repaint; public RefreshPropertiesAttribute(System.ComponentModel.RefreshProperties refresh) { } public System.ComponentModel.RefreshProperties RefreshProperties { get { throw null; } } public override bool Equals(object value) { throw null; } public override int GetHashCode() { throw null; } public override bool IsDefaultAttribute() { throw null; } } }
/* * 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 NVelocity.Runtime.Log { using System; using Exception; using System.Collections.Generic; /// <summary> <p> /// This class is responsible for instantiating the correct ILogChute /// </p> /// /// <p> /// The approach is : /// </p> /// <ul> /// <li> /// First try to see if the user is passing in a living object /// that is a ILogChute, allowing the app to give its living /// custom loggers. /// </li> /// <li> /// Next, run through the (possible) list of classes specified /// specified as loggers, taking the first one that appears to /// work. This is how we support finding logkit, log4j or /// jdk logging, whichever is in the classpath and found first, /// as all three are listed as defaults. /// </li> /// <li> /// Finally, we turn to the System.err stream and print Log messages /// to it if nothing else works. /// </li> /// /// </summary> /// <author> <a href="mailto:jvanzyl@apache.org">Jason van Zyl</a> /// </author> /// <author> <a href="mailto:jon@latchkey.com">Jon S. Stevens</a> /// </author> /// <author> <a href="mailto:geirm@optonline.net">Geir Magnusson Jr.</a> /// </author> /// <author> <a href="mailto:nbubna@apache.org">Nathan Bubna</a> /// </author> /// <version> $Id: LogManager.java 699307 2008-09-26 13:16:05Z cbrisson $ /// </version> public class LogManager { // Creates a new logging system or returns an existing one // specified by the application. private static ILogChute CreateLogChute(IRuntimeServices rsvc) { Log log = rsvc.Log; /* If a ILogChute or LogSystem instance was set as a configuration * value, use that. This is any class the user specifies. */ System.Object o = rsvc.GetProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM); if (o != null) { // first check for a ILogChute if (o is ILogChute) { try { ((ILogChute)o).Init(rsvc); return (ILogChute)o; } catch (System.Exception e) { System.String msg = "Could not init runtime.log.logsystem " + o; log.Error(msg, e); throw new VelocityException(msg, e); } } else { System.String msg = o.GetType().FullName + " object set as runtime.log.logsystem is not a valid log implementation."; log.Error(msg); throw new VelocityException(msg); } } /* otherwise, see if a class was specified. You can Put multiple * classes, and we use the first one we find. * * Note that the default value of this property contains the * AvalonLogChute, the Log4JLogChute, CommonsLogLogChute, * ServletLogChute, and the JdkLogChute for * convenience - so we use whichever we works first. */ System.Collections.IList classes = new List<object>(); System.Object obj = rsvc.GetProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM_CLASS); /* * we might have a list, or not - so check */ if (obj is System.Collections.IList) { classes = (System.Collections.IList)obj; } else if (obj is System.String) { classes.Add(obj); } /* * now run through the list, trying each. It's ok to * fail with a class not found, as we do this to also * search out a default simple file logger */ for (System.Collections.IEnumerator ii = classes.GetEnumerator(); ii.MoveNext(); ) { System.String claz = (System.String)ii.Current; if (claz != null && claz.Length > 0) { log.Debug("Trying to use logger class " + claz); try { o = Activator.CreateInstance(Type.GetType(claz.Replace(';', ','))); if (o is ILogChute) { ((ILogChute)o).Init(rsvc); log.Debug("Using logger class " + claz); return (ILogChute)o; } else { System.String msg = "The specified logger class " + claz + " does not implement the " + typeof(ILogChute).FullName + " interface."; log.Error(msg); // be extra informative if it appears to be a classloader issue // this should match all our provided LogChutes if (IsProbablyProvidedLogChute(claz)) { // if it's likely to be ours, tip them off about classloader stuff log.Error("This appears to be a ClassLoader issue. Check for multiple Velocity jars in your classpath."); } throw new VelocityException(msg); } } /* catch (System.Exception ncdfe) { // note these errors for anyone debugging the app if (IsProbablyProvidedLogChute(claz)) { log.Debug("Target log system for " + claz + " is not available (" + ncdfe.ToString() + "). Falling back to next log system..."); } else { log.Debug("Couldn't find class " + claz + " or necessary supporting classes in classpath.", ncdfe); } } */ catch (System.Exception e) { System.String msg = "Failed to initialize an instance of " + claz + " with the current runtime configuration."; // Log unexpected Init exception at higher priority log.Error(msg, e); throw new VelocityException(msg, e); } } } /* If the above failed, that means either the user specified a * logging class that we can't find, there weren't the necessary * dependencies in the classpath for it, or there were the same * problems for the default loggers, log4j and Java1.4+. * Since we really don't know and we want to be sure the user knows * that something went wrong with the logging, let's fall back to the * surefire SystemLogChute. No panicking or failing to Log!! */ ILogChute slc = new NullLogChute(); slc.Init(rsvc); log.Debug("Using SystemLogChute."); return slc; } /// <summary> Simply tells whether the specified classname probably is provided /// by Velocity or is implemented by someone else. Not surefire, but /// it'll probably always be right. In any case, this method shouldn't /// be relied upon for anything important. /// </summary> private static bool IsProbablyProvidedLogChute(System.String claz) { if (claz == null) { return false; } else { return (claz.StartsWith("org.apache.velocity.runtime.log") && claz.EndsWith("ILogChute")); } } /// <summary> Update the Log instance with the appropriate ILogChute and other /// settings determined by the RuntimeServices. /// </summary> /// <param name="Log"> /// </param> /// <param name="rsvc"> /// </param> /// <throws> Exception </throws> /// <since> 1.5 /// </since> public static void UpdateLog(Log log, IRuntimeServices rsvc) { // create a new ILogChute using the RuntimeServices ILogChute newLogChute = CreateLogChute(rsvc); ILogChute oldLogChute = log.GetLogChute(); // pass the new ILogChute to the Log first, // (if the old was a HoldingLogChute, we don't want it // to accrue new messages during the transfer below) log.SetLogChute(newLogChute); // If the old ILogChute was the pre-Init logger, // dump its messages into the new system. if (oldLogChute is HoldingLogChute) { HoldingLogChute hlc = (HoldingLogChute)oldLogChute; hlc.TransferTo(newLogChute); } } } }
using Orleans.Serialization.Activators; using Orleans.Serialization.Buffers; using Orleans.Serialization.Cloning; using Orleans.Serialization.Codecs; using Orleans.Serialization.Configuration; using Orleans.Serialization.Serializers; using Orleans.Serialization.Session; using Orleans.Serialization.TypeSystem; using Orleans.Serialization.WireProtocol; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using System; using System.Buffers; using System.Collections.Generic; using Microsoft.Extensions.Options; using System.Security.Cryptography.X509Certificates; using System.Reflection; using System.Threading.Tasks; namespace Orleans.Serialization { /// <summary> /// Extensions for <see cref="IServiceCollection"/>. /// </summary> public static class ServiceCollectionExtensions { /// <summary> /// Adds serializer support. /// </summary> /// <param name="services">The service collection.</param> /// <param name="configure">The configuration delegate.</param> /// <returns>The service collection.</returns> public static IServiceCollection AddSerializer(this IServiceCollection services, Action<ISerializerBuilder> configure = null) { // Only add the services once. var context = GetFromServices<ConfigurationContext>(services); if (context is null) { context = new ConfigurationContext(services); foreach (var asm in ReferencedAssemblyHelper.GetRelevantAssemblies(services)) { context.Builder.AddAssembly(asm); } services.Add(context.CreateServiceDescriptor()); services.AddOptions(); services.AddSingleton<IConfigureOptions<TypeManifestOptions>, DefaultTypeManifestProvider>(); services.AddSingleton<TypeResolver, CachedTypeResolver>(); services.AddSingleton<TypeConverter>(); services.TryAddSingleton(typeof(ListActivator<>)); services.TryAddSingleton(typeof(DictionaryActivator<,>)); services.TryAddSingleton<CodecProvider>(); services.TryAddSingleton<ICodecProvider>(sp => sp.GetRequiredService<CodecProvider>()); services.TryAddSingleton<IDeepCopierProvider>(sp => sp.GetRequiredService<CodecProvider>()); services.TryAddSingleton<IFieldCodecProvider>(sp => sp.GetRequiredService<CodecProvider>()); services.TryAddSingleton<IBaseCodecProvider>(sp => sp.GetRequiredService<CodecProvider>()); services.TryAddSingleton<IValueSerializerProvider>(sp => sp.GetRequiredService<CodecProvider>()); services.TryAddSingleton<IActivatorProvider>(sp => sp.GetRequiredService<CodecProvider>()); services.TryAddSingleton(typeof(IFieldCodec<>), typeof(FieldCodecHolder<>)); services.TryAddSingleton(typeof(IBaseCodec<>), typeof(BaseCodecHolder<>)); services.TryAddSingleton(typeof(IValueSerializer<>), typeof(ValueSerializerHolder<>)); services.TryAddSingleton(typeof(DefaultActivator<>)); services.TryAddSingleton(typeof(IActivator<>), typeof(ActivatorHolder<>)); services.TryAddSingleton<WellKnownTypeCollection>(); services.TryAddSingleton<TypeCodec>(); services.TryAddSingleton(typeof(IDeepCopier<>), typeof(CopierHolder<>)); services.TryAddSingleton(typeof(IBaseCopier<>), typeof(BaseCopierHolder<>)); // Type filtering services.AddSingleton<ITypeFilter, DefaultTypeFilter>(); // Session services.TryAddSingleton<SerializerSessionPool>(); services.TryAddSingleton<CopyContextPool>(); services.AddSingleton<IGeneralizedCodec, CompareInfoCodec>(); services.AddSingleton<IGeneralizedCopier, CompareInfoCopier>(); services.AddSingleton<IGeneralizedCodec, WellKnownStringComparerCodec>(); services.AddSingleton<ExceptionCodec>(); services.AddSingleton<IGeneralizedCodec>(sp => sp.GetRequiredService<ExceptionCodec>()); services.AddSingleton<IGeneralizedBaseCodec>(sp => sp.GetRequiredService<ExceptionCodec>()); // Serializer services.TryAddSingleton<ObjectSerializer>(); services.TryAddSingleton<Serializer>(); services.TryAddSingleton(typeof(Serializer<>)); services.TryAddSingleton(typeof(ValueSerializer<>)); services.TryAddSingleton<DeepCopier>(); services.TryAddSingleton(typeof(DeepCopier<>)); } configure?.Invoke(context.Builder); return services; } private static T GetFromServices<T>(IServiceCollection services) { foreach (var service in services) { if (service.ServiceType == typeof(T)) { return (T)service.ImplementationInstance; } } return default; } private sealed class ConfigurationContext { public ConfigurationContext(IServiceCollection services) => Builder = new SerializerBuilder(services); public ServiceDescriptor CreateServiceDescriptor() => new ServiceDescriptor(typeof(ConfigurationContext), this); public ISerializerBuilder Builder { get; } } private class SerializerBuilder : ISerializerBuilderImplementation { private readonly IServiceCollection _services; public SerializerBuilder(IServiceCollection services) => _services = services; public Dictionary<object, object> Properties { get; } = new(); public ISerializerBuilderImplementation ConfigureServices(Action<IServiceCollection> configureDelegate) { configureDelegate(_services); return this; } } private sealed class ActivatorHolder<T> : IActivator<T>, IServiceHolder<IActivator<T>> { private readonly IActivatorProvider _activatorProvider; private IActivator<T> _activator; public ActivatorHolder(IActivatorProvider codecProvider) { _activatorProvider = codecProvider; } public IActivator<T> Value => _activator ??= _activatorProvider.GetActivator<T>(); public T Create() => Value.Create(); } private sealed class FieldCodecHolder<TField> : IFieldCodec<TField>, IServiceHolder<IFieldCodec<TField>> { private readonly IFieldCodecProvider _codecProvider; private IFieldCodec<TField> _codec; public FieldCodecHolder(IFieldCodecProvider codecProvider) { _codecProvider = codecProvider; } public void WriteField<TBufferWriter>(ref Writer<TBufferWriter> writer, uint fieldIdDelta, Type expectedType, TField value) where TBufferWriter : IBufferWriter<byte> => Value.WriteField(ref writer, fieldIdDelta, expectedType, value); public TField ReadValue<TInput>(ref Reader<TInput> reader, Field field) => Value.ReadValue(ref reader, field); public IFieldCodec<TField> Value => _codec ??= _codecProvider.GetCodec<TField>(); } private sealed class BaseCodecHolder<TField> : IBaseCodec<TField>, IServiceHolder<IBaseCodec<TField>> where TField : class { private readonly IBaseCodecProvider _provider; private IBaseCodec<TField> _baseCodec; public BaseCodecHolder(IBaseCodecProvider provider) { _provider = provider; } public void Serialize<TBufferWriter>(ref Writer<TBufferWriter> writer, TField value) where TBufferWriter : IBufferWriter<byte> => Value.Serialize(ref writer, value); public void Deserialize<TInput>(ref Reader<TInput> reader, TField value) => Value.Deserialize(ref reader, value); public IBaseCodec<TField> Value => _baseCodec ??= _provider.GetBaseCodec<TField>(); } private sealed class ValueSerializerHolder<TField> : IValueSerializer<TField>, IServiceHolder<IValueSerializer<TField>> where TField : struct { private readonly IValueSerializerProvider _provider; private IValueSerializer<TField> _serializer; public ValueSerializerHolder(IValueSerializerProvider provider) { _provider = provider; } public void Serialize<TBufferWriter>(ref Writer<TBufferWriter> writer, ref TField value) where TBufferWriter : IBufferWriter<byte> => Value.Serialize(ref writer, ref value); public void Deserialize<TInput>(ref Reader<TInput> reader, ref TField value) => Value.Deserialize(ref reader, ref value); public IValueSerializer<TField> Value => _serializer ??= _provider.GetValueSerializer<TField>(); } private sealed class CopierHolder<T> : IDeepCopier<T>, IServiceHolder<IDeepCopier<T>> { private readonly IDeepCopierProvider _codecProvider; private IDeepCopier<T> _copier; public CopierHolder(IDeepCopierProvider codecProvider) { _codecProvider = codecProvider; } public T DeepCopy(T original, CopyContext context) => Value.DeepCopy(original, context); public IDeepCopier<T> Value => _copier ??= _codecProvider.GetDeepCopier<T>(); } private sealed class BaseCopierHolder<T> : IBaseCopier<T>, IServiceHolder<IBaseCopier<T>> where T : class { private readonly IDeepCopierProvider _codecProvider; private IBaseCopier<T> _copier; public BaseCopierHolder(IDeepCopierProvider codecProvider) { _codecProvider = codecProvider; } public void DeepCopy(T original, T copy, CopyContext context) => Value.DeepCopy(original, copy, context); public IBaseCopier<T> Value => _copier ??= _codecProvider.GetBaseCopier<T>(); } } }
// // MonoSymbolFile.cs // // Authors: // Martin Baulig (martin@ximian.com) // Marek Safar (marek.safar@gmail.com) // // (C) 2003 Ximian, Inc. http://www.ximian.com // Copyright (C) 2012 Xamarin Inc (http://www.xamarin.com) // // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Reflection; using System.Collections.Generic; using System.IO; namespace Mono.CompilerServices.SymbolWriter { public class MonoSymbolFileException : Exception { public MonoSymbolFileException () : base () { } public MonoSymbolFileException (string message, params object[] args) : base (String.Format (message, args)) { } public MonoSymbolFileException (string message, Exception innerException) : base (message, innerException) { } } sealed class MyBinaryWriter : BinaryWriter { public MyBinaryWriter (Stream stream) : base (stream) { } public void WriteLeb128 (int value) { base.Write7BitEncodedInt (value); } } internal class MyBinaryReader : BinaryReader { public MyBinaryReader (Stream stream) : base (stream) { } public int ReadLeb128 () { return base.Read7BitEncodedInt (); } public string ReadString (int offset) { long old_pos = BaseStream.Position; BaseStream.Position = offset; string text = ReadString (); BaseStream.Position = old_pos; return text; } } public interface ISourceFile { SourceFileEntry Entry { get; } } public interface ICompileUnit { CompileUnitEntry Entry { get; } } public interface IMethodDef { string Name { get; } int Token { get; } } public class MonoSymbolFile : IDisposable { List<MethodEntry> methods = new List<MethodEntry> (); List<SourceFileEntry> sources = new List<SourceFileEntry> (); List<CompileUnitEntry> comp_units = new List<CompileUnitEntry> (); Dictionary<int, AnonymousScopeEntry> anonymous_scopes; OffsetTable ot; int last_type_index; int last_method_index; int last_namespace_index; public readonly int MajorVersion = OffsetTable.MajorVersion; public readonly int MinorVersion = OffsetTable.MinorVersion; public int NumLineNumbers; public MonoSymbolFile () { ot = new OffsetTable (); } public int AddSource (SourceFileEntry source) { sources.Add (source); return sources.Count; } public int AddCompileUnit (CompileUnitEntry entry) { comp_units.Add (entry); return comp_units.Count; } public void AddMethod (MethodEntry entry) { methods.Add (entry); } public MethodEntry DefineMethod (CompileUnitEntry comp_unit, int token, ScopeVariable[] scope_vars, LocalVariableEntry[] locals, LineNumberEntry[] lines, CodeBlockEntry[] code_blocks, string real_name, MethodEntry.Flags flags, int namespace_id) { if (reader != null) throw new InvalidOperationException (); MethodEntry method = new MethodEntry ( this, comp_unit, token, scope_vars, locals, lines, code_blocks, real_name, flags, namespace_id); AddMethod (method); return method; } internal void DefineAnonymousScope (int id) { if (reader != null) throw new InvalidOperationException (); if (anonymous_scopes == null) anonymous_scopes = new Dictionary<int, AnonymousScopeEntry> (); anonymous_scopes.Add (id, new AnonymousScopeEntry (id)); } internal void DefineCapturedVariable (int scope_id, string name, string captured_name, CapturedVariable.CapturedKind kind) { if (reader != null) throw new InvalidOperationException (); AnonymousScopeEntry scope = anonymous_scopes [scope_id]; scope.AddCapturedVariable (name, captured_name, kind); } internal void DefineCapturedScope (int scope_id, int id, string captured_name) { if (reader != null) throw new InvalidOperationException (); AnonymousScopeEntry scope = anonymous_scopes [scope_id]; scope.AddCapturedScope (id, captured_name); } internal int GetNextTypeIndex () { return ++last_type_index; } internal int GetNextMethodIndex () { return ++last_method_index; } internal int GetNextNamespaceIndex () { return ++last_namespace_index; } void Write (MyBinaryWriter bw, Guid guid) { // Magic number and file version. bw.Write (OffsetTable.Magic); bw.Write (MajorVersion); bw.Write (MinorVersion); bw.Write (guid.ToByteArray ()); // // Offsets of file sections; we must write this after we're done // writing the whole file, so we just reserve the space for it here. // long offset_table_offset = bw.BaseStream.Position; ot.Write (bw, MajorVersion, MinorVersion); // // Sort the methods according to their tokens and update their index. // methods.Sort (); for (int i = 0; i < methods.Count; i++) methods [i].Index = i + 1; // // Write data sections. // ot.DataSectionOffset = (int) bw.BaseStream.Position; foreach (SourceFileEntry source in sources) source.WriteData (bw); foreach (CompileUnitEntry comp_unit in comp_units) comp_unit.WriteData (bw); foreach (MethodEntry method in methods) method.WriteData (this, bw); ot.DataSectionSize = (int) bw.BaseStream.Position - ot.DataSectionOffset; // // Write the method index table. // ot.MethodTableOffset = (int) bw.BaseStream.Position; for (int i = 0; i < methods.Count; i++) { MethodEntry entry = methods [i]; entry.Write (bw); } ot.MethodTableSize = (int) bw.BaseStream.Position - ot.MethodTableOffset; // // Write source table. // ot.SourceTableOffset = (int) bw.BaseStream.Position; for (int i = 0; i < sources.Count; i++) { SourceFileEntry source = sources [i]; source.Write (bw); } ot.SourceTableSize = (int) bw.BaseStream.Position - ot.SourceTableOffset; // // Write compilation unit table. // ot.CompileUnitTableOffset = (int) bw.BaseStream.Position; for (int i = 0; i < comp_units.Count; i++) { CompileUnitEntry unit = comp_units [i]; unit.Write (bw); } ot.CompileUnitTableSize = (int) bw.BaseStream.Position - ot.CompileUnitTableOffset; // // Write anonymous scope table. // ot.AnonymousScopeCount = anonymous_scopes != null ? anonymous_scopes.Count : 0; ot.AnonymousScopeTableOffset = (int) bw.BaseStream.Position; if (anonymous_scopes != null) { foreach (AnonymousScopeEntry scope in anonymous_scopes.Values) scope.Write (bw); } ot.AnonymousScopeTableSize = (int) bw.BaseStream.Position - ot.AnonymousScopeTableOffset; // // Fixup offset table. // ot.TypeCount = last_type_index; ot.MethodCount = methods.Count; ot.SourceCount = sources.Count; ot.CompileUnitCount = comp_units.Count; // // Write offset table. // ot.TotalFileSize = (int) bw.BaseStream.Position; bw.Seek ((int) offset_table_offset, SeekOrigin.Begin); ot.Write (bw, MajorVersion, MinorVersion); bw.Seek (0, SeekOrigin.End); #if false Console.WriteLine ("TOTAL: {0} line numbes, {1} bytes, extended {2} bytes, " + "{3} methods.", NumLineNumbers, LineNumberSize, ExtendedLineNumberSize, methods.Count); #endif } public void CreateSymbolFile (Guid guid, FileStream fs) { if (reader != null) throw new InvalidOperationException (); Write (new MyBinaryWriter (fs), guid); } MyBinaryReader reader; Dictionary<int, SourceFileEntry> source_file_hash; Dictionary<int, CompileUnitEntry> compile_unit_hash; List<MethodEntry> method_list; Dictionary<int, MethodEntry> method_token_hash; Dictionary<string, int> source_name_hash; Guid guid; MonoSymbolFile (Stream stream) { reader = new MyBinaryReader (stream); try { long magic = reader.ReadInt64 (); int major_version = reader.ReadInt32 (); int minor_version = reader.ReadInt32 (); if (magic != OffsetTable.Magic) throw new MonoSymbolFileException ("Symbol file is not a valid"); if (major_version != OffsetTable.MajorVersion) throw new MonoSymbolFileException ( "Symbol file has version {0} but expected {1}", major_version, OffsetTable.MajorVersion); if (minor_version != OffsetTable.MinorVersion) throw new MonoSymbolFileException ("Symbol file has version {0}.{1} but expected {2}.{3}", major_version, minor_version, OffsetTable.MajorVersion, OffsetTable.MinorVersion); MajorVersion = major_version; MinorVersion = minor_version; guid = new Guid (reader.ReadBytes (16)); ot = new OffsetTable (reader, major_version, minor_version); } catch (Exception e) { throw new MonoSymbolFileException ("Cannot read symbol file", e); } source_file_hash = new Dictionary<int, SourceFileEntry> (); compile_unit_hash = new Dictionary<int, CompileUnitEntry> (); } #if !NET_CORE public static MonoSymbolFile ReadSymbolFile (Assembly assembly) { string filename = assembly.Location; string name = filename + ".mdb"; Module[] modules = assembly.GetModules (); Guid assembly_guid = modules[0].ModuleVersionId; return ReadSymbolFile (name, assembly_guid); } #endif public static MonoSymbolFile ReadSymbolFile (string mdbFilename) { return ReadSymbolFile (new FileStream (mdbFilename, FileMode.Open, FileAccess.Read)); } public static MonoSymbolFile ReadSymbolFile (string mdbFilename, Guid assemblyGuid) { var sf = ReadSymbolFile (mdbFilename); if (assemblyGuid != sf.guid) throw new MonoSymbolFileException ("Symbol file `{0}' does not match assembly", mdbFilename); return sf; } public static MonoSymbolFile ReadSymbolFile (Stream stream) { return new MonoSymbolFile (stream); } public int CompileUnitCount { get { return ot.CompileUnitCount; } } public int SourceCount { get { return ot.SourceCount; } } public int MethodCount { get { return ot.MethodCount; } } public int TypeCount { get { return ot.TypeCount; } } public int AnonymousScopeCount { get { return ot.AnonymousScopeCount; } } public int NamespaceCount { get { return last_namespace_index; } } public Guid Guid { get { return guid; } } public OffsetTable OffsetTable { get { return ot; } } internal int LineNumberCount = 0; internal int LocalCount = 0; internal int StringSize = 0; internal int LineNumberSize = 0; internal int ExtendedLineNumberSize = 0; public SourceFileEntry GetSourceFile (int index) { if ((index < 1) || (index > ot.SourceCount)) throw new ArgumentException (); if (reader == null) throw new InvalidOperationException (); lock (this) { SourceFileEntry source; if (source_file_hash.TryGetValue (index, out source)) return source; long old_pos = reader.BaseStream.Position; reader.BaseStream.Position = ot.SourceTableOffset + SourceFileEntry.Size * (index - 1); source = new SourceFileEntry (this, reader); source_file_hash.Add (index, source); reader.BaseStream.Position = old_pos; return source; } } public SourceFileEntry[] Sources { get { if (reader == null) throw new InvalidOperationException (); SourceFileEntry[] retval = new SourceFileEntry [SourceCount]; for (int i = 0; i < SourceCount; i++) retval [i] = GetSourceFile (i + 1); return retval; } } public CompileUnitEntry GetCompileUnit (int index) { if ((index < 1) || (index > ot.CompileUnitCount)) throw new ArgumentException (); if (reader == null) throw new InvalidOperationException (); lock (this) { CompileUnitEntry unit; if (compile_unit_hash.TryGetValue (index, out unit)) return unit; long old_pos = reader.BaseStream.Position; reader.BaseStream.Position = ot.CompileUnitTableOffset + CompileUnitEntry.Size * (index - 1); unit = new CompileUnitEntry (this, reader); compile_unit_hash.Add (index, unit); reader.BaseStream.Position = old_pos; return unit; } } public CompileUnitEntry[] CompileUnits { get { if (reader == null) throw new InvalidOperationException (); CompileUnitEntry[] retval = new CompileUnitEntry [CompileUnitCount]; for (int i = 0; i < CompileUnitCount; i++) retval [i] = GetCompileUnit (i + 1); return retval; } } void read_methods () { lock (this) { if (method_token_hash != null) return; method_token_hash = new Dictionary<int, MethodEntry> (); method_list = new List<MethodEntry> (); long old_pos = reader.BaseStream.Position; reader.BaseStream.Position = ot.MethodTableOffset; for (int i = 0; i < MethodCount; i++) { MethodEntry entry = new MethodEntry (this, reader, i + 1); method_token_hash.Add (entry.Token, entry); method_list.Add (entry); } reader.BaseStream.Position = old_pos; } } public MethodEntry GetMethodByToken (int token) { if (reader == null) throw new InvalidOperationException (); lock (this) { read_methods (); MethodEntry me; method_token_hash.TryGetValue (token, out me); return me; } } public MethodEntry GetMethod (int index) { if ((index < 1) || (index > ot.MethodCount)) throw new ArgumentException (); if (reader == null) throw new InvalidOperationException (); lock (this) { read_methods (); return method_list [index - 1]; } } public MethodEntry[] Methods { get { if (reader == null) throw new InvalidOperationException (); lock (this) { read_methods (); MethodEntry[] retval = new MethodEntry [MethodCount]; method_list.CopyTo (retval, 0); return retval; } } } public int FindSource (string file_name) { if (reader == null) throw new InvalidOperationException (); lock (this) { if (source_name_hash == null) { source_name_hash = new Dictionary<string, int> (); for (int i = 0; i < ot.SourceCount; i++) { SourceFileEntry source = GetSourceFile (i + 1); source_name_hash.Add (source.FileName, i); } } int value; if (!source_name_hash.TryGetValue (file_name, out value)) return -1; return value; } } public AnonymousScopeEntry GetAnonymousScope (int id) { if (reader == null) throw new InvalidOperationException (); AnonymousScopeEntry scope; lock (this) { if (anonymous_scopes != null) { anonymous_scopes.TryGetValue (id, out scope); return scope; } anonymous_scopes = new Dictionary<int, AnonymousScopeEntry> (); reader.BaseStream.Position = ot.AnonymousScopeTableOffset; for (int i = 0; i < ot.AnonymousScopeCount; i++) { scope = new AnonymousScopeEntry (reader); anonymous_scopes.Add (scope.ID, scope); } return anonymous_scopes [id]; } } internal MyBinaryReader BinaryReader { get { if (reader == null) throw new InvalidOperationException (); return reader; } } public void Dispose () { Dispose (true); } protected virtual void Dispose (bool disposing) { if (disposing) { if (reader != null) { #if NET_CORE reader.Dispose (); #else reader.Close (); #endif reader = null; } } } } }
using System; using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Orleans.CodeGenerator.Analyzers; using Orleans.CodeGenerator.Compatibility; using Orleans.CodeGenerator.Utilities; namespace Orleans.CodeGenerator.Analysis { internal class CompilationAnalyzer { private readonly IGeneratorExecutionContext context; private readonly WellKnownTypes wellKnownTypes; private readonly INamedTypeSymbol serializableAttribute; private readonly INamedTypeSymbol knownBaseTypeAttribute; private readonly INamedTypeSymbol knownAssemblyAttribute; private readonly INamedTypeSymbol considerForCodeGenerationAttribute; private readonly Compilation compilation; /// <summary> /// Assemblies whose declared types are all considered serializable. /// </summary> private readonly HashSet<IAssemblySymbol> assembliesWithForcedSerializability = new HashSet<IAssemblySymbol>(SymbolEqualityComparer.Default); /// <summary> /// Types whose sub-types are all considered serializable. /// </summary> private readonly HashSet<INamedTypeSymbol> knownBaseTypes = new HashSet<INamedTypeSymbol>(SymbolEqualityComparer.Default); /// <summary> /// Types which were observed in a grain interface. /// </summary> private readonly HashSet<ITypeSymbol> dependencyTypes = new HashSet<ITypeSymbol>(SymbolEqualityComparer.Default); private readonly HashSet<INamedTypeSymbol> grainInterfacesToProcess = new HashSet<INamedTypeSymbol>(SymbolEqualityComparer.Default); private readonly HashSet<INamedTypeSymbol> grainClassesToProcess = new HashSet<INamedTypeSymbol>(SymbolEqualityComparer.Default); private readonly HashSet<INamedTypeSymbol> serializationTypesToProcess = new HashSet<INamedTypeSymbol>(SymbolEqualityComparer.Default); private readonly HashSet<INamedTypeSymbol> fieldOfSerializableType = new HashSet<INamedTypeSymbol>(SymbolEqualityComparer.Default); public CompilationAnalyzer(IGeneratorExecutionContext context, WellKnownTypes wellKnownTypes, Compilation compilation) { this.context = context; this.wellKnownTypes = wellKnownTypes; this.serializableAttribute = wellKnownTypes.SerializableAttribute; this.knownBaseTypeAttribute = wellKnownTypes.KnownBaseTypeAttribute; this.knownAssemblyAttribute = wellKnownTypes.KnownAssemblyAttribute; this.considerForCodeGenerationAttribute = wellKnownTypes.ConsiderForCodeGenerationAttribute; this.compilation = compilation; } public HashSet<INamedTypeSymbol> CodeGenerationRequiredTypes { get; } = new HashSet<INamedTypeSymbol>(SymbolEqualityComparer.Default); /// <summary> /// All assemblies referenced by this compilation. /// </summary> public HashSet<IAssemblySymbol> ReferencedAssemblies = new HashSet<IAssemblySymbol>(SymbolEqualityComparer.Default); /// <summary> /// Assemblies which should be excluded from code generation (eg, because they already contain generated code). /// </summary> public HashSet<IAssemblySymbol> AssembliesExcludedFromCodeGeneration = new HashSet<IAssemblySymbol>(SymbolEqualityComparer.Default); /// <summary> /// Assemblies which should be excluded from metadata generation. /// </summary> public HashSet<IAssemblySymbol> AssembliesExcludedFromMetadataGeneration = new HashSet<IAssemblySymbol>(SymbolEqualityComparer.Default); public HashSet<IAssemblySymbol> KnownAssemblies { get; } = new HashSet<IAssemblySymbol>(SymbolEqualityComparer.Default); public HashSet<string> ApplicationParts { get; } = new HashSet<string>(StringComparer.Ordinal); public HashSet<INamedTypeSymbol> KnownTypes { get; } = new HashSet<INamedTypeSymbol>(SymbolEqualityComparer.Default); public (IEnumerable<INamedTypeSymbol> grainClasses, IEnumerable<INamedTypeSymbol> grainInterfaces, IEnumerable<INamedTypeSymbol> types) GetTypesToProcess() => (this.grainClassesToProcess, this.grainInterfacesToProcess, this.GetSerializationTypesToProcess()); private IEnumerable<INamedTypeSymbol> GetSerializationTypesToProcess() { var done = new HashSet<INamedTypeSymbol>(SymbolEqualityComparer.Default); var remaining = new HashSet<INamedTypeSymbol>(SymbolEqualityComparer.Default); while (done.Count != this.serializationTypesToProcess.Count) { remaining.Clear(); foreach (var type in this.serializationTypesToProcess) { if (done.Add(type)) remaining.Add(type); } foreach (var type in remaining) { yield return type; } } } public bool IsSerializable(INamedTypeSymbol type) { var result = false; if (type.IsSerializable || type.HasAttribute(this.serializableAttribute)) { result = true; } if (!result && this.assembliesWithForcedSerializability.Contains(type.ContainingAssembly)) { result = true; } if (!result && this.KnownTypes.Contains(type)) { result = true; } if (!result && this.dependencyTypes.Contains(type)) { result = true; } if (!result) { for (var current = type; current != null; current = current.BaseType) { if (!knownBaseTypes.Contains(current)) continue; result = true; } } if (!result) { foreach (var iface in type.AllInterfaces) { if (!knownBaseTypes.Contains(iface)) continue; result = true; } } if (!result && this.fieldOfSerializableType.Contains(type)) { result = true; } if (result) { foreach (var field in type.GetInstanceMembers<IFieldSymbol>()) { ExpandGenericArguments(field.Type); } void ExpandGenericArguments(ITypeSymbol typeSymbol) { if (typeSymbol is INamedTypeSymbol named && this.fieldOfSerializableType.Add(named)) { InspectType(named); foreach (var param in named.GetHierarchyTypeArguments()) { ExpandGenericArguments(param); } } } } return result; } public bool IsFromKnownAssembly(ITypeSymbol type) => this.KnownAssemblies.Contains(type.OriginalDefinition.ContainingAssembly); private void InspectGrainInterface(INamedTypeSymbol type) { this.serializationTypesToProcess.Add(type); this.grainInterfacesToProcess.Add(type); foreach (var method in type.GetInstanceMembers<IMethodSymbol>()) { var awaitable = IsAwaitable(method); if (!awaitable && !method.ReturnsVoid) { var declaration = method.DeclaringSyntaxReferences.FirstOrDefault()?.GetSyntax() as MethodDeclarationSyntax; this.context.ReportDiagnostic(UnawaitableGrainMethodReturnTypeDiagostic.CreateDiagnostic(declaration)); continue; } if (method.ReturnType is INamedTypeSymbol returnType) { foreach (var named in ExpandType(returnType).OfType<INamedTypeSymbol>()) { this.AddDependencyType(named); this.serializationTypesToProcess.Add(named); } } foreach (var param in method.Parameters) { if (param.Type is INamedTypeSymbol parameterType) { foreach (var named in ExpandType(parameterType).OfType<INamedTypeSymbol>()) { this.AddDependencyType(named); this.serializationTypesToProcess.Add(named); } } } } bool IsAwaitable(IMethodSymbol method) { foreach (var member in method.ReturnType.GetMembers("GetAwaiter")) { if (member.IsStatic) continue; if (member is IMethodSymbol m && HasZeroParameters(m)) { return true; } } return false; bool HasZeroParameters(IMethodSymbol m) => m.Parameters.Length == 0 && m.TypeParameters.Length == 0; } } private static IEnumerable<ITypeSymbol> ExpandType(ITypeSymbol symbol) { return ExpandTypeInternal(symbol, new HashSet<ITypeSymbol>(SymbolEqualityComparer.Default)); IEnumerable<ITypeSymbol> ExpandTypeInternal(ITypeSymbol s, HashSet<ITypeSymbol> emitted) { if (!emitted.Add(s)) yield break; yield return s; switch (s) { case IArrayTypeSymbol array: foreach (var t in ExpandTypeInternal(array.ElementType, emitted)) yield return t; break; case INamedTypeSymbol named: foreach (var p in named.TypeArguments) foreach (var t in ExpandTypeInternal(p, emitted)) yield return t; break; } if (s.BaseType != null) { foreach (var t in ExpandTypeInternal(s.BaseType, emitted)) yield return t; } } } public void InspectType(INamedTypeSymbol type) { if (type.HasAttribute(knownBaseTypeAttribute)) this.AddKnownBaseType(type); if (this.wellKnownTypes.IsGrainInterface(type)) this.InspectGrainInterface(type); if (this.wellKnownTypes.IsGrainClass(type)) this.grainClassesToProcess.Add(type); this.serializationTypesToProcess.Add(type); } public void Analyze(System.Threading.CancellationToken cancellationToken) { ApplicationParts.Add(this.compilation.Assembly.MetadataName); foreach (var reference in this.compilation.References) { if (this.compilation.GetAssemblyOrModuleSymbol(reference) is not IAssemblySymbol asm) continue; this.ReferencedAssemblies.Add(asm); AddApplicationParts(asm); } // Recursively all assemblies considered known from the inspected assembly. ExpandKnownAssemblies(compilation.Assembly); // Add all types considered known from each known assembly. ExpandKnownTypes(this.KnownAssemblies); foreach (var asm in this.KnownAssemblies) { AddApplicationParts(asm); } this.ExpandAssembliesWithGeneratedCode(); void ExpandKnownAssemblies(IAssemblySymbol asm) { if (!this.KnownAssemblies.Add(asm)) { return; } if (!asm.GetAttributes(this.knownAssemblyAttribute, out var attrs)) return; foreach (var attr in attrs) { var param = attr.ConstructorArguments.First(); if (param.Kind != TypedConstantKind.Type) { throw new ArgumentException($"Unrecognized argument type in attribute [{attr.AttributeClass.Name}({param.ToCSharpString()})]"); } var type = (ITypeSymbol)param.Value; // Check if the attribute has the TreatTypesAsSerializable property set. var prop = attr.NamedArguments.FirstOrDefault(a => a.Key.Equals("TreatTypesAsSerializable")).Value; if (prop.Type != null) { var treatAsSerializable = (bool)prop.Value; if (treatAsSerializable) { // When checking if a type in this assembly is serializable, always respond that it is. this.AddAssemblyWithForcedSerializability(asm); } } // Recurse on the assemblies which the type was declared in. ExpandKnownAssemblies(type.OriginalDefinition.ContainingAssembly); } } void ExpandKnownTypes(IEnumerable<IAssemblySymbol> asm) { foreach (var a in asm) { if (!a.GetAttributes(this.considerForCodeGenerationAttribute, out var attrs)) continue; foreach (var attr in attrs) { var typeParam = attr.ConstructorArguments.First(); if (typeParam.Kind != TypedConstantKind.Type) { throw new ArgumentException($"Unrecognized argument type in attribute [{attr.AttributeClass.Name}({typeParam.ToCSharpString()})]"); } var type = (INamedTypeSymbol)typeParam.Value; this.KnownTypes.Add(type); var throwOnFailure = false; var throwOnFailureParam = attr.ConstructorArguments.ElementAtOrDefault(2); if (throwOnFailureParam.Type != null) { throwOnFailure = (bool)throwOnFailureParam.Value; if (throwOnFailure) this.CodeGenerationRequiredTypes.Add(type); } } } } void AddApplicationParts(IAssemblySymbol asm) { if (asm.GetAttributes(this.wellKnownTypes.ApplicationPartAttribute, out var attrs)) { ApplicationParts.Add(asm.MetadataName); foreach (var attr in attrs) { ApplicationParts.Add((string)attr.ConstructorArguments.First().Value); } } } } private void ExpandAssembliesWithGeneratedCode() { foreach (var asm in this.ReferencedAssemblies) { if (!asm.GetAttributes(this.wellKnownTypes.OrleansCodeGenerationTargetAttribute, out var attrs)) continue; this.AssembliesExcludedFromMetadataGeneration.Add(asm); this.AssembliesExcludedFromCodeGeneration.Add(asm); foreach (var attr in attrs) { var assemblyName = attr.ConstructorArguments[0].Value as string; bool metadataOnly; if (attr.ConstructorArguments.Length >= 2 && attr.ConstructorArguments[1].Value is bool val) { metadataOnly = val; } else { metadataOnly = false; } if (string.IsNullOrWhiteSpace(assemblyName)) continue; foreach (var candidate in this.ReferencedAssemblies) { bool hasGeneratedCode; if (string.Equals(assemblyName, candidate.Identity.Name, StringComparison.OrdinalIgnoreCase)) { hasGeneratedCode = true; } else if (string.Equals(assemblyName, candidate.Identity.GetDisplayName())) { hasGeneratedCode = true; } else if (string.Equals(assemblyName, candidate.Identity.GetDisplayName(fullKey: true))) { hasGeneratedCode = true; } else { hasGeneratedCode = false; } if (hasGeneratedCode) { this.AssembliesExcludedFromMetadataGeneration.Add(candidate); if (!metadataOnly) { this.AssembliesExcludedFromCodeGeneration.Add(candidate); } break; } } } } } public void AddAssemblyWithForcedSerializability(IAssemblySymbol asm) => this.assembliesWithForcedSerializability.Add(asm); public void AddKnownBaseType(INamedTypeSymbol type) { this.knownBaseTypes.Add(type); } public void AddDependencyType(ITypeSymbol type) { if (!(type is INamedTypeSymbol named)) return; if (named.IsGenericType && !named.IsUnboundGenericType) { var unbound = named.ConstructUnboundGenericType(); if (SymbolEqualityComparer.Default.Equals(unbound, this.wellKnownTypes.Task_1)) { return; } } this.dependencyTypes.Add(type); } } }
// Copyright (c) Microsoft Open Technologies, Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { [CompilerTrait(CompilerFeature.RefLocalsReturns)] public class RefLocalTests : CompilingTestBase { [Fact] public void RefAssignArrayAccess() { var text = @" class Program { static void M() { ref int rl = ref (new int[1])[0]; } } "; CompileAndVerify(text, options: TestOptions.DebugDll).VerifyIL("Program.M()", @" { // Code size 15 (0xf) .maxstack 2 .locals init (int& V_0) //rl IL_0000: nop IL_0001: ldc.i4.1 IL_0002: newarr ""int"" IL_0007: ldc.i4.0 IL_0008: ldelema ""int"" IL_000d: stloc.0 IL_000e: ret }"); } [Fact] public void RefAssignRefParameter() { var text = @" class Program { static void M(ref int i) { ref int rl = ref i; } } "; CompileAndVerify(text, options: TestOptions.DebugDll).VerifyIL("Program.M(ref int)", @" { // Code size 4 (0x4) .maxstack 1 .locals init (int& V_0) //rl IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.0 IL_0003: ret }"); } [Fact] public void RefAssignOutParameter() { var text = @" class Program { static void M(out int i) { i = 0; ref int rl = ref i; } } "; CompileAndVerify(text, options: TestOptions.DebugDll).VerifyIL("Program.M(out int)", @" { // Code size 7 (0x7) .maxstack 2 .locals init (int& V_0) //rl IL_0000: nop IL_0001: ldarg.0 IL_0002: ldc.i4.0 IL_0003: stind.i4 IL_0004: ldarg.0 IL_0005: stloc.0 IL_0006: ret }"); } [Fact] public void RefAssignRefLocal() { var text = @" class Program { static void M(ref int i) { ref int local = ref i; ref int rl = ref local; } } "; CompileAndVerify(text, options: TestOptions.DebugDll).VerifyIL("Program.M(ref int)", @" { // Code size 6 (0x6) .maxstack 1 .locals init (int& V_0, //local int& V_1) //rl IL_0000: nop IL_0001: ldarg.0 IL_0002: stloc.0 IL_0003: ldloc.0 IL_0004: stloc.1 IL_0005: ret }"); } [Fact] public void RefAssignStaticProperty() { var text = @" class Program { static int field = 0; static ref int P { get { return ref field; } } static void M() { ref int rl = ref P; } } "; CompileAndVerify(text, options: TestOptions.DebugDll, verify: false).VerifyIL("Program.M()", @" { // Code size 8 (0x8) .maxstack 1 .locals init (int& V_0) //rl IL_0000: nop IL_0001: call ""ref int Program.P.get"" IL_0006: stloc.0 IL_0007: ret }"); } [Fact] public void RefAssignClassInstanceProperty() { var text = @" class Program { int field = 0; ref int P { get { return ref field; } } void M() { ref int rl = ref P; } void M1() { ref int rl = ref new Program().P; } } "; var comp = CompileAndVerify(text, options: TestOptions.DebugDll, verify: false); comp.VerifyIL("Program.M()", @" { // Code size 9 (0x9) .maxstack 1 .locals init (int& V_0) //rl IL_0000: nop IL_0001: ldarg.0 IL_0002: call ""ref int Program.P.get"" IL_0007: stloc.0 IL_0008: ret }"); comp.VerifyIL("Program.M1()", @" { // Code size 13 (0xd) .maxstack 1 .locals init (int& V_0) //rl IL_0000: nop IL_0001: newobj ""Program..ctor()"" IL_0006: call ""ref int Program.P.get"" IL_000b: stloc.0 IL_000c: ret }"); } [Fact] public void RefAssignStructInstanceProperty() { var text = @" struct Program { public ref int P { get { return ref (new int[1])[0]; } } void M() { ref int rl = ref P; } void M1(ref Program program) { ref int rl = ref program.P; } } struct Program2 { Program program; Program2(Program program) { this.program = program; } void M() { ref int rl = ref program.P; } } class Program3 { Program program = default(Program); void M() { ref int rl = ref program.P; } } "; var comp = CompileAndVerify(text, options: TestOptions.DebugDll, verify: false); comp.VerifyIL("Program.M()", @" { // Code size 9 (0x9) .maxstack 1 .locals init (int& V_0) //rl IL_0000: nop IL_0001: ldarg.0 IL_0002: call ""ref int Program.P.get"" IL_0007: stloc.0 IL_0008: ret }"); comp.VerifyIL("Program.M1(ref Program)", @" { // Code size 9 (0x9) .maxstack 1 .locals init (int& V_0) //rl IL_0000: nop IL_0001: ldarg.1 IL_0002: call ""ref int Program.P.get"" IL_0007: stloc.0 IL_0008: ret }"); comp.VerifyIL("Program2.M()", @" { // Code size 14 (0xe) .maxstack 1 .locals init (int& V_0) //rl IL_0000: nop IL_0001: ldarg.0 IL_0002: ldflda ""Program Program2.program"" IL_0007: call ""ref int Program.P.get"" IL_000c: stloc.0 IL_000d: ret }"); comp.VerifyIL("Program3.M()", @" { // Code size 14 (0xe) .maxstack 1 .locals init (int& V_0) //rl IL_0000: nop IL_0001: ldarg.0 IL_0002: ldflda ""Program Program3.program"" IL_0007: call ""ref int Program.P.get"" IL_000c: stloc.0 IL_000d: ret }"); } [Fact] public void RefAssignConstrainedInstanceProperty() { var text = @" interface I { ref int P { get; } } class Program<T> where T : I { T t = default(T); void M() { ref int rl = ref t.P; } } class Program2<T> where T : class, I { void M(T t) { ref int rl = ref t.P; } } class Program3<T> where T : struct, I { T t = default(T); void M() { ref int rl = ref t.P; } } "; var comp = CompileAndVerify(text, options: TestOptions.DebugDll); comp.VerifyIL("Program<T>.M()", @" { // Code size 20 (0x14) .maxstack 1 .locals init (int& V_0) //rl IL_0000: nop IL_0001: ldarg.0 IL_0002: ldflda ""T Program<T>.t"" IL_0007: constrained. ""T"" IL_000d: callvirt ""ref int I.P.get"" IL_0012: stloc.0 IL_0013: ret }"); comp.VerifyIL("Program2<T>.M(T)", @" { // Code size 14 (0xe) .maxstack 1 .locals init (int& V_0) //rl IL_0000: nop IL_0001: ldarg.1 IL_0002: box ""T"" IL_0007: callvirt ""ref int I.P.get"" IL_000c: stloc.0 IL_000d: ret }"); comp.VerifyIL("Program3<T>.M()", @" { // Code size 20 (0x14) .maxstack 1 .locals init (int& V_0) //rl IL_0000: nop IL_0001: ldarg.0 IL_0002: ldflda ""T Program3<T>.t"" IL_0007: constrained. ""T"" IL_000d: callvirt ""ref int I.P.get"" IL_0012: stloc.0 IL_0013: ret }"); } [Fact] public void RefAssignClassInstanceIndexer() { var text = @" class Program { int field = 0; ref int this[int i] { get { return ref field; } } void M() { ref int rl = ref this[0]; } void M1() { ref int rl = ref new Program()[0]; } } "; var comp = CompileAndVerify(text, options: TestOptions.DebugDll, verify: false); comp.VerifyIL("Program.M()", @" { // Code size 10 (0xa) .maxstack 2 .locals init (int& V_0) //rl IL_0000: nop IL_0001: ldarg.0 IL_0002: ldc.i4.0 IL_0003: call ""ref int Program.this[int].get"" IL_0008: stloc.0 IL_0009: ret }"); comp.VerifyIL("Program.M1()", @" { // Code size 14 (0xe) .maxstack 2 .locals init (int& V_0) //rl IL_0000: nop IL_0001: newobj ""Program..ctor()"" IL_0006: ldc.i4.0 IL_0007: call ""ref int Program.this[int].get"" IL_000c: stloc.0 IL_000d: ret }"); } [Fact] public void RefAssignStructInstanceIndexer() { var text = @" struct Program { public ref int this[int i] { get { return ref (new int[1])[0]; } } void M() { ref int rl = ref this[0]; } } struct Program2 { Program program; Program2(Program program) { this.program = program; } void M() { ref int rl = ref program[0]; } } class Program3 { Program program = default(Program); void M() { ref int rl = ref program[0]; } } "; var comp = CompileAndVerify(text, options: TestOptions.DebugDll, verify: false); comp.VerifyIL("Program.M()", @" { // Code size 10 (0xa) .maxstack 2 .locals init (int& V_0) //rl IL_0000: nop IL_0001: ldarg.0 IL_0002: ldc.i4.0 IL_0003: call ""ref int Program.this[int].get"" IL_0008: stloc.0 IL_0009: ret }"); comp.VerifyIL("Program2.M()", @" { // Code size 15 (0xf) .maxstack 2 .locals init (int& V_0) //rl IL_0000: nop IL_0001: ldarg.0 IL_0002: ldflda ""Program Program2.program"" IL_0007: ldc.i4.0 IL_0008: call ""ref int Program.this[int].get"" IL_000d: stloc.0 IL_000e: ret }"); comp.VerifyIL("Program3.M()", @" { // Code size 15 (0xf) .maxstack 2 .locals init (int& V_0) //rl IL_0000: nop IL_0001: ldarg.0 IL_0002: ldflda ""Program Program3.program"" IL_0007: ldc.i4.0 IL_0008: call ""ref int Program.this[int].get"" IL_000d: stloc.0 IL_000e: ret }"); } [Fact] public void RefAssignConstrainedInstanceIndexer() { var text = @" interface I { ref int this[int i] { get; } } class Program<T> where T : I { T t = default(T); void M() { ref int rl = ref t[0]; } } class Program2<T> where T : class, I { void M(T t) { ref int rl = ref t[0]; } } class Program3<T> where T : struct, I { T t = default(T); void M() { ref int rl = ref t[0]; } } "; var comp = CompileAndVerify(text, options: TestOptions.DebugDll); comp.VerifyIL("Program<T>.M()", @" { // Code size 21 (0x15) .maxstack 2 .locals init (int& V_0) //rl IL_0000: nop IL_0001: ldarg.0 IL_0002: ldflda ""T Program<T>.t"" IL_0007: ldc.i4.0 IL_0008: constrained. ""T"" IL_000e: callvirt ""ref int I.this[int].get"" IL_0013: stloc.0 IL_0014: ret }"); comp.VerifyIL("Program2<T>.M(T)", @" { // Code size 15 (0xf) .maxstack 2 .locals init (int& V_0) //rl IL_0000: nop IL_0001: ldarg.1 IL_0002: box ""T"" IL_0007: ldc.i4.0 IL_0008: callvirt ""ref int I.this[int].get"" IL_000d: stloc.0 IL_000e: ret }"); comp.VerifyIL("Program3<T>.M()", @" { // Code size 21 (0x15) .maxstack 2 .locals init (int& V_0) //rl IL_0000: nop IL_0001: ldarg.0 IL_0002: ldflda ""T Program3<T>.t"" IL_0007: ldc.i4.0 IL_0008: constrained. ""T"" IL_000e: callvirt ""ref int I.this[int].get"" IL_0013: stloc.0 IL_0014: ret }"); } [Fact] public void RefAssignStaticFieldLikeEvent() { var text = @" delegate void D(); class Program { static event D d; static void M() { ref D rl = ref d; } } "; CompileAndVerify(text, options: TestOptions.DebugDll).VerifyIL("Program.M()", @" { // Code size 8 (0x8) .maxstack 1 .locals init (D& V_0) //rl IL_0000: nop IL_0001: ldsflda ""D Program.d"" IL_0006: stloc.0 IL_0007: ret }"); } [Fact] public void RefAssignClassInstanceFieldLikeEvent() { var text = @" delegate void D(); class Program { event D d; void M() { ref D rl = ref d; } void M1() { ref D rl = ref new Program().d; } } "; var comp = CompileAndVerify(text, options: TestOptions.DebugDll); comp.VerifyIL("Program.M()", @" { // Code size 9 (0x9) .maxstack 1 .locals init (D& V_0) //rl IL_0000: nop IL_0001: ldarg.0 IL_0002: ldflda ""D Program.d"" IL_0007: stloc.0 IL_0008: ret }"); comp.VerifyIL("Program.M1()", @" { // Code size 13 (0xd) .maxstack 1 .locals init (D& V_0) //rl IL_0000: nop IL_0001: newobj ""Program..ctor()"" IL_0006: ldflda ""D Program.d"" IL_000b: stloc.0 IL_000c: ret }"); } [Fact] public void RefAssignStaticField() { var text = @" class Program { static int i = 0; static void M() { ref int rl = ref i; rl = i; } } "; CompileAndVerify(text, options: TestOptions.DebugDll).VerifyIL("Program.M()", @" { // Code size 15 (0xf) .maxstack 2 .locals init (int& V_0) //rl IL_0000: nop IL_0001: ldsflda ""int Program.i"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: ldsfld ""int Program.i"" IL_000d: stind.i4 IL_000e: ret }"); } [Fact] public void RefAssignClassInstanceField() { var text = @" class Program { int i = 0; void M() { ref int rl = ref i; } void M1() { ref int rl = ref new Program().i; } } "; var comp = CompileAndVerify(text, options: TestOptions.DebugDll); comp.VerifyIL("Program.M()", @" { // Code size 9 (0x9) .maxstack 1 .locals init (int& V_0) //rl IL_0000: nop IL_0001: ldarg.0 IL_0002: ldflda ""int Program.i"" IL_0007: stloc.0 IL_0008: ret }"); comp.VerifyIL("Program.M1()", @" { // Code size 13 (0xd) .maxstack 1 .locals init (int& V_0) //rl IL_0000: nop IL_0001: newobj ""Program..ctor()"" IL_0006: ldflda ""int Program.i"" IL_000b: stloc.0 IL_000c: ret }"); } [Fact] public void RefAssignStructInstanceField() { var text = @" struct Program { public int i; } class Program2 { Program program = default(Program); void M(ref Program program) { ref int rl = ref program.i; rl = program.i; } void M() { ref int rl = ref program.i; } } "; var comp = CompileAndVerify(text, options: TestOptions.DebugDll); comp.VerifyIL("Program2.M(ref Program)", @" { // Code size 17 (0x11) .maxstack 2 .locals init (int& V_0) //rl IL_0000: nop IL_0001: ldarg.1 IL_0002: ldflda ""int Program.i"" IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: ldarg.1 IL_000a: ldfld ""int Program.i"" IL_000f: stind.i4 IL_0010: ret }"); comp.VerifyIL("Program2.M()", @" { // Code size 14 (0xe) .maxstack 1 .locals init (int& V_0) //rl IL_0000: nop IL_0001: ldarg.0 IL_0002: ldflda ""Program Program2.program"" IL_0007: ldflda ""int Program.i"" IL_000c: stloc.0 IL_000d: ret }"); } [Fact] public void RefAssignStaticCallWithoutArguments() { var text = @" class Program { static ref int M() { ref int rl = ref M(); return ref rl; } } "; CompileAndVerify(text, options: TestOptions.DebugDll, verify: false).VerifyIL("Program.M()", @" { // Code size 13 (0xd) .maxstack 1 .locals init (int& V_0, //rl int& V_1) IL_0000: nop IL_0001: call ""ref int Program.M()"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: stloc.1 IL_0009: br.s IL_000b IL_000b: ldloc.1 IL_000c: ret }"); } [Fact] public void RefAssignClassInstanceCallWithoutArguments() { var text = @" class Program { ref int M() { ref int rl = ref M(); return ref rl; } ref int M1() { ref int rl = ref new Program().M(); return ref rl; } } "; var comp = CompileAndVerify(text, options: TestOptions.DebugDll, verify: false); comp.VerifyIL("Program.M()", @" { // Code size 14 (0xe) .maxstack 1 .locals init (int& V_0, //rl int& V_1) IL_0000: nop IL_0001: ldarg.0 IL_0002: call ""ref int Program.M()"" IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: stloc.1 IL_000a: br.s IL_000c IL_000c: ldloc.1 IL_000d: ret }"); comp.VerifyIL("Program.M1()", @" { // Code size 18 (0x12) .maxstack 1 .locals init (int& V_0, //rl int& V_1) IL_0000: nop IL_0001: newobj ""Program..ctor()"" IL_0006: call ""ref int Program.M()"" IL_000b: stloc.0 IL_000c: ldloc.0 IL_000d: stloc.1 IL_000e: br.s IL_0010 IL_0010: ldloc.1 IL_0011: ret }"); } [Fact] public void RefAssignStructInstanceCallWithoutArguments() { var text = @" struct Program { public ref int M() { ref int rl = ref M(); return ref rl; } } struct Program2 { Program program; ref int M() { ref int rl = ref program.M(); return ref rl; } } class Program3 { Program program; ref int M() { ref int rl = ref program.M(); return ref rl; } } "; var comp = CompileAndVerify(text, options: TestOptions.DebugDll, verify: false); comp.VerifyIL("Program.M()", @" { // Code size 14 (0xe) .maxstack 1 .locals init (int& V_0, //rl int& V_1) IL_0000: nop IL_0001: ldarg.0 IL_0002: call ""ref int Program.M()"" IL_0007: stloc.0 IL_0008: ldloc.0 IL_0009: stloc.1 IL_000a: br.s IL_000c IL_000c: ldloc.1 IL_000d: ret }"); comp.VerifyIL("Program2.M()", @" { // Code size 19 (0x13) .maxstack 1 .locals init (int& V_0, //rl int& V_1) IL_0000: nop IL_0001: ldarg.0 IL_0002: ldflda ""Program Program2.program"" IL_0007: call ""ref int Program.M()"" IL_000c: stloc.0 IL_000d: ldloc.0 IL_000e: stloc.1 IL_000f: br.s IL_0011 IL_0011: ldloc.1 IL_0012: ret }"); comp.VerifyIL("Program3.M()", @" { // Code size 19 (0x13) .maxstack 1 .locals init (int& V_0, //rl int& V_1) IL_0000: nop IL_0001: ldarg.0 IL_0002: ldflda ""Program Program3.program"" IL_0007: call ""ref int Program.M()"" IL_000c: stloc.0 IL_000d: ldloc.0 IL_000e: stloc.1 IL_000f: br.s IL_0011 IL_0011: ldloc.1 IL_0012: ret }"); } [Fact] public void RefAssignConstrainedInstanceCallWithoutArguments() { var text = @" interface I { ref int M(); } class Program<T> where T : I { T t = default(T); ref int M() { ref int rl = ref t.M(); return ref rl; } } class Program2<T> where T : class, I { ref int M(T t) { ref int rl = ref t.M(); return ref rl; } } class Program3<T> where T : struct, I { T t = default(T); ref int M() { ref int rl = ref t.M(); return ref rl; } } "; var comp = CompileAndVerify(text, options: TestOptions.DebugDll, verify: false); comp.VerifyIL("Program<T>.M()", @" { // Code size 25 (0x19) .maxstack 1 .locals init (int& V_0, //rl int& V_1) IL_0000: nop IL_0001: ldarg.0 IL_0002: ldflda ""T Program<T>.t"" IL_0007: constrained. ""T"" IL_000d: callvirt ""ref int I.M()"" IL_0012: stloc.0 IL_0013: ldloc.0 IL_0014: stloc.1 IL_0015: br.s IL_0017 IL_0017: ldloc.1 IL_0018: ret }"); comp.VerifyIL("Program2<T>.M(T)", @" { // Code size 19 (0x13) .maxstack 1 .locals init (int& V_0, //rl int& V_1) IL_0000: nop IL_0001: ldarg.1 IL_0002: box ""T"" IL_0007: callvirt ""ref int I.M()"" IL_000c: stloc.0 IL_000d: ldloc.0 IL_000e: stloc.1 IL_000f: br.s IL_0011 IL_0011: ldloc.1 IL_0012: ret }"); comp.VerifyIL("Program3<T>.M()", @" { // Code size 25 (0x19) .maxstack 1 .locals init (int& V_0, //rl int& V_1) IL_0000: nop IL_0001: ldarg.0 IL_0002: ldflda ""T Program3<T>.t"" IL_0007: constrained. ""T"" IL_000d: callvirt ""ref int I.M()"" IL_0012: stloc.0 IL_0013: ldloc.0 IL_0014: stloc.1 IL_0015: br.s IL_0017 IL_0017: ldloc.1 IL_0018: ret }"); } [Fact] public void RefAssignStaticCallWithArguments() { var text = @" class Program { static ref int M(ref int i, ref int j, object o) { ref int rl = ref M(ref i, ref j, o); return ref rl; } } "; CompileAndVerify(text, options: TestOptions.DebugDll, verify: false).VerifyIL("Program.M(ref int, ref int, object)", @" { // Code size 16 (0x10) .maxstack 3 .locals init (int& V_0, //rl int& V_1) IL_0000: nop IL_0001: ldarg.0 IL_0002: ldarg.1 IL_0003: ldarg.2 IL_0004: call ""ref int Program.M(ref int, ref int, object)"" IL_0009: stloc.0 IL_000a: ldloc.0 IL_000b: stloc.1 IL_000c: br.s IL_000e IL_000e: ldloc.1 IL_000f: ret }"); } [Fact] public void RefAssignClassInstanceCallWithArguments() { var text = @" class Program { ref int M(ref int i, ref int j, object o) { ref int rl = ref M(ref i, ref j, o); return ref rl; } ref int M1(ref int i, ref int j, object o) { ref int rl = ref new Program().M(ref i, ref j, o); return ref rl; } } "; var comp = CompileAndVerify(text, options: TestOptions.DebugDll, verify: false); comp.VerifyIL("Program.M(ref int, ref int, object)", @" { // Code size 17 (0x11) .maxstack 4 .locals init (int& V_0, //rl int& V_1) IL_0000: nop IL_0001: ldarg.0 IL_0002: ldarg.1 IL_0003: ldarg.2 IL_0004: ldarg.3 IL_0005: call ""ref int Program.M(ref int, ref int, object)"" IL_000a: stloc.0 IL_000b: ldloc.0 IL_000c: stloc.1 IL_000d: br.s IL_000f IL_000f: ldloc.1 IL_0010: ret }"); comp.VerifyIL("Program.M1(ref int, ref int, object)", @" { // Code size 21 (0x15) .maxstack 4 .locals init (int& V_0, //rl int& V_1) IL_0000: nop IL_0001: newobj ""Program..ctor()"" IL_0006: ldarg.1 IL_0007: ldarg.2 IL_0008: ldarg.3 IL_0009: call ""ref int Program.M(ref int, ref int, object)"" IL_000e: stloc.0 IL_000f: ldloc.0 IL_0010: stloc.1 IL_0011: br.s IL_0013 IL_0013: ldloc.1 IL_0014: ret }"); } [Fact] public void RefAssignStructInstanceCallWithArguments() { var text = @" struct Program { public ref int M(ref int i, ref int j, object o) { ref int rl = ref M(ref i, ref j, o); return ref rl; } } struct Program2 { Program program; ref int M(ref int i, ref int j, object o) { ref int rl = ref program.M(ref i, ref j, o); return ref rl; } } class Program3 { Program program; ref int M(ref int i, ref int j, object o) { ref int rl = ref program.M(ref i, ref j, o); return ref rl; } } "; var comp = CompileAndVerify(text, options: TestOptions.DebugDll, verify: false); comp.VerifyIL("Program.M(ref int, ref int, object)", @" { // Code size 17 (0x11) .maxstack 4 .locals init (int& V_0, //rl int& V_1) IL_0000: nop IL_0001: ldarg.0 IL_0002: ldarg.1 IL_0003: ldarg.2 IL_0004: ldarg.3 IL_0005: call ""ref int Program.M(ref int, ref int, object)"" IL_000a: stloc.0 IL_000b: ldloc.0 IL_000c: stloc.1 IL_000d: br.s IL_000f IL_000f: ldloc.1 IL_0010: ret }"); comp.VerifyIL("Program2.M(ref int, ref int, object)", @" { // Code size 22 (0x16) .maxstack 4 .locals init (int& V_0, //rl int& V_1) IL_0000: nop IL_0001: ldarg.0 IL_0002: ldflda ""Program Program2.program"" IL_0007: ldarg.1 IL_0008: ldarg.2 IL_0009: ldarg.3 IL_000a: call ""ref int Program.M(ref int, ref int, object)"" IL_000f: stloc.0 IL_0010: ldloc.0 IL_0011: stloc.1 IL_0012: br.s IL_0014 IL_0014: ldloc.1 IL_0015: ret }"); comp.VerifyIL("Program3.M(ref int, ref int, object)", @" { // Code size 22 (0x16) .maxstack 4 .locals init (int& V_0, //rl int& V_1) IL_0000: nop IL_0001: ldarg.0 IL_0002: ldflda ""Program Program3.program"" IL_0007: ldarg.1 IL_0008: ldarg.2 IL_0009: ldarg.3 IL_000a: call ""ref int Program.M(ref int, ref int, object)"" IL_000f: stloc.0 IL_0010: ldloc.0 IL_0011: stloc.1 IL_0012: br.s IL_0014 IL_0014: ldloc.1 IL_0015: ret }"); } [Fact] public void RefAssignConstrainedInstanceCallWithArguments() { var text = @" interface I { ref int M(ref int i, ref int j, object o); } class Program<T> where T : I { T t = default(T); ref int M(ref int i, ref int j, object o) { ref int rl = ref t.M(ref i, ref j, o); return ref rl; } } class Program2<T> where T : class, I { ref int M(T t, ref int i, ref int j, object o) { ref int rl = ref t.M(ref i, ref j, o); return ref rl; } } class Program3<T> where T : struct, I { T t = default(T); ref int M(ref int i, ref int j, object o) { ref int rl = ref t.M(ref i, ref j, o); return ref rl; } } "; var comp = CompileAndVerify(text, options: TestOptions.DebugDll, verify: false); comp.VerifyIL("Program<T>.M(ref int, ref int, object)", @" { // Code size 28 (0x1c) .maxstack 4 .locals init (int& V_0, //rl int& V_1) IL_0000: nop IL_0001: ldarg.0 IL_0002: ldflda ""T Program<T>.t"" IL_0007: ldarg.1 IL_0008: ldarg.2 IL_0009: ldarg.3 IL_000a: constrained. ""T"" IL_0010: callvirt ""ref int I.M(ref int, ref int, object)"" IL_0015: stloc.0 IL_0016: ldloc.0 IL_0017: stloc.1 IL_0018: br.s IL_001a IL_001a: ldloc.1 IL_001b: ret }"); comp.VerifyIL("Program2<T>.M(T, ref int, ref int, object)", @" { // Code size 23 (0x17) .maxstack 4 .locals init (int& V_0, //rl int& V_1) IL_0000: nop IL_0001: ldarg.1 IL_0002: box ""T"" IL_0007: ldarg.2 IL_0008: ldarg.3 IL_0009: ldarg.s V_4 IL_000b: callvirt ""ref int I.M(ref int, ref int, object)"" IL_0010: stloc.0 IL_0011: ldloc.0 IL_0012: stloc.1 IL_0013: br.s IL_0015 IL_0015: ldloc.1 IL_0016: ret }"); comp.VerifyIL("Program3<T>.M(ref int, ref int, object)", @" { // Code size 28 (0x1c) .maxstack 4 .locals init (int& V_0, //rl int& V_1) IL_0000: nop IL_0001: ldarg.0 IL_0002: ldflda ""T Program3<T>.t"" IL_0007: ldarg.1 IL_0008: ldarg.2 IL_0009: ldarg.3 IL_000a: constrained. ""T"" IL_0010: callvirt ""ref int I.M(ref int, ref int, object)"" IL_0015: stloc.0 IL_0016: ldloc.0 IL_0017: stloc.1 IL_0018: br.s IL_001a IL_001a: ldloc.1 IL_001b: ret }"); } [Fact] public void RefAssignDelegateInvocationWithNoArguments() { var text = @" delegate ref int D(); class Program { static void M(D d) { ref int rl = ref d(); } } "; CompileAndVerify(text, options: TestOptions.DebugDll).VerifyIL("Program.M(D)", @" { // Code size 9 (0x9) .maxstack 1 .locals init (int& V_0) //rl IL_0000: nop IL_0001: ldarg.0 IL_0002: callvirt ""ref int D.Invoke()"" IL_0007: stloc.0 IL_0008: ret }"); } [Fact] public void RefAssignDelegateInvocationWithArguments() { var text = @" delegate ref int D(ref int i, ref int j, object o); class Program { static ref int M(D d, ref int i, ref int j, object o) { ref int rl = ref d(ref i, ref j, o); return ref rl; } } "; CompileAndVerify(text, options: TestOptions.DebugDll, verify: false).VerifyIL("Program.M(D, ref int, ref int, object)", @" { // Code size 17 (0x11) .maxstack 4 .locals init (int& V_0, //rl int& V_1) IL_0000: nop IL_0001: ldarg.0 IL_0002: ldarg.1 IL_0003: ldarg.2 IL_0004: ldarg.3 IL_0005: callvirt ""ref int D.Invoke(ref int, ref int, object)"" IL_000a: stloc.0 IL_000b: ldloc.0 IL_000c: stloc.1 IL_000d: br.s IL_000f IL_000f: ldloc.1 IL_0010: ret }"); } [Fact] public void RefLocalsAreVariables() { var text = @" class Program { static int field = 0; static void M(ref int i) { } static void N(out int i) { i = 0; } static unsafe void Main() { ref int rl = ref field; rl = 0; rl += 1; rl++; M(ref rl); N(out rl); fixed (int* i = &rl) { } var tr = __makeref(rl); } } "; CompileAndVerify(text, options: TestOptions.UnsafeDebugDll).VerifyIL("Program.Main()", @" { // Code size 51 (0x33) .maxstack 3 .locals init (int& V_0, //rl System.TypedReference V_1, //tr pinned int& V_2) //i IL_0000: nop IL_0001: ldsflda ""int Program.field"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: ldc.i4.0 IL_0009: stind.i4 IL_000a: ldloc.0 IL_000b: ldloc.0 IL_000c: ldind.i4 IL_000d: ldc.i4.1 IL_000e: add IL_000f: stind.i4 IL_0010: ldloc.0 IL_0011: ldloc.0 IL_0012: ldind.i4 IL_0013: ldc.i4.1 IL_0014: add IL_0015: stind.i4 IL_0016: ldloc.0 IL_0017: call ""void Program.M(ref int)"" IL_001c: nop IL_001d: ldloc.0 IL_001e: call ""void Program.N(out int)"" IL_0023: nop IL_0024: ldloc.0 IL_0025: stloc.2 IL_0026: nop IL_0027: nop IL_0028: ldc.i4.0 IL_0029: conv.u IL_002a: stloc.2 IL_002b: ldloc.0 IL_002c: mkrefany ""int"" IL_0031: stloc.1 IL_0032: ret }"); } [Fact] private void RefLocalsAreValues() { var text = @" class Program { static int field = 0; static void N(int i) { } static unsafe int Main() { ref int rl = ref field; var @int = rl + 0; var @string = rl.ToString(); var @long = (long)rl; N(rl); return unchecked((int)((long)@int + @long)); } } "; CompileAndVerify(text, options: TestOptions.UnsafeDebugDll).VerifyIL("Program.Main()", @" { // Code size 41 (0x29) .maxstack 2 .locals init (int& V_0, //rl int V_1, //int string V_2, //string long V_3, //long int V_4) IL_0000: nop IL_0001: ldsflda ""int Program.field"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: ldind.i4 IL_0009: stloc.1 IL_000a: ldloc.0 IL_000b: call ""string int.ToString()"" IL_0010: stloc.2 IL_0011: ldloc.0 IL_0012: ldind.i4 IL_0013: conv.i8 IL_0014: stloc.3 IL_0015: ldloc.0 IL_0016: ldind.i4 IL_0017: call ""void Program.N(int)"" IL_001c: nop IL_001d: ldloc.1 IL_001e: conv.i8 IL_001f: ldloc.3 IL_0020: add IL_0021: conv.i4 IL_0022: stloc.s V_4 IL_0024: br.s IL_0026 IL_0026: ldloc.s V_4 IL_0028: ret } "); } [Fact] public void RefLocal_CSharp6() { var text = @" class Program { static void M() { ref int rl = ref (new int[1])[0]; } } "; var comp = CreateCompilationWithMscorlib(text, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp6)); comp.VerifyDiagnostics( // (6,9): error CS8059: Feature 'byref locals and returns' is not available in C# 6. Please use language version 7 or greater. // ref int rl = ref (new int[1])[0]; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "ref int").WithArguments("byref locals and returns", "7").WithLocation(6, 9), // (6,22): error CS8059: Feature 'byref locals and returns' is not available in C# 6. Please use language version 7 or greater. // ref int rl = ref (new int[1])[0]; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "ref").WithArguments("byref locals and returns", "7").WithLocation(6, 22) ); } } }
// Copyright (c) The Avalonia Project. All rights reserved. // Licensed under the MIT license. See licence.md file in the project root for full license information. using System; using System.Reactive.Linq; using System.Threading.Tasks; using Avalonia.Controls.Platform; using Avalonia.Input; using Avalonia.Layout; using Avalonia.Media; using Avalonia.Platform; using Avalonia.Styling; using System.Collections.Generic; using System.Linq; using JetBrains.Annotations; using System.ComponentModel; namespace Avalonia.Controls { /// <summary> /// Determines how a <see cref="Window"/> will size itself to fit its content. /// </summary> [Flags] public enum SizeToContent { /// <summary> /// The window will not automatically size itself to fit its content. /// </summary> Manual = 0, /// <summary> /// The window will size itself horizontally to fit its content. /// </summary> Width = 1, /// <summary> /// The window will size itself vertically to fit its content. /// </summary> Height = 2, /// <summary> /// The window will size itself horizontally and vertically to fit its content. /// </summary> WidthAndHeight = 3, } /// <summary> /// A top-level window. /// </summary> public class Window : WindowBase, IStyleable, IFocusScope, ILayoutRoot, INameScope { private static List<Window> s_windows = new List<Window>(); /// <summary> /// Retrieves an enumeration of all Windows in the currently running application. /// </summary> public static IReadOnlyList<Window> OpenWindows => s_windows; /// <summary> /// Defines the <see cref="SizeToContent"/> property. /// </summary> public static readonly StyledProperty<SizeToContent> SizeToContentProperty = AvaloniaProperty.Register<Window, SizeToContent>(nameof(SizeToContent)); /// <summary> /// Enables or disables system window decorations (title bar, buttons, etc) /// </summary> public static readonly StyledProperty<bool> HasSystemDecorationsProperty = AvaloniaProperty.Register<Window, bool>(nameof(HasSystemDecorations), true); /// <summary> /// Enables or disables the taskbar icon /// </summary> public static readonly StyledProperty<bool> ShowInTaskbarProperty = AvaloniaProperty.Register<Window, bool>(nameof(ShowInTaskbar), true); /// <summary> /// Defines the <see cref="Title"/> property. /// </summary> public static readonly StyledProperty<string> TitleProperty = AvaloniaProperty.Register<Window, string>(nameof(Title), "Window"); /// <summary> /// Defines the <see cref="Icon"/> property. /// </summary> public static readonly StyledProperty<WindowIcon> IconProperty = AvaloniaProperty.Register<Window, WindowIcon>(nameof(Icon)); /// <summary> /// Defines the <see cref="WindowStartupLocation"/> proeprty. /// </summary> public static readonly DirectProperty<Window, WindowStartupLocation> WindowStartupLocationProperty = AvaloniaProperty.RegisterDirect<Window, WindowStartupLocation>( nameof(WindowStartupLocation), o => o.WindowStartupLocation, (o, v) => o.WindowStartupLocation = v); public static readonly StyledProperty<bool> CanResizeProperty = AvaloniaProperty.Register<Window, bool>(nameof(CanResize), true); private readonly NameScope _nameScope = new NameScope(); private object _dialogResult; private readonly Size _maxPlatformClientSize; private WindowStartupLocation _windowStartupLoction; /// <summary> /// Initializes static members of the <see cref="Window"/> class. /// </summary> static Window() { BackgroundProperty.OverrideDefaultValue(typeof(Window), Brushes.White); TitleProperty.Changed.AddClassHandler<Window>((s, e) => s.PlatformImpl?.SetTitle((string)e.NewValue)); HasSystemDecorationsProperty.Changed.AddClassHandler<Window>( (s, e) => s.PlatformImpl?.SetSystemDecorations((bool) e.NewValue)); ShowInTaskbarProperty.Changed.AddClassHandler<Window>((w, e) => w.PlatformImpl?.ShowTaskbarIcon((bool)e.NewValue)); IconProperty.Changed.AddClassHandler<Window>((s, e) => s.PlatformImpl?.SetIcon(((WindowIcon)e.NewValue).PlatformImpl)); CanResizeProperty.Changed.AddClassHandler<Window>((w, e) => w.PlatformImpl?.CanResize((bool)e.NewValue)); } /// <summary> /// Initializes a new instance of the <see cref="Window"/> class. /// </summary> public Window() : this(PlatformManager.CreateWindow()) { } /// <summary> /// Initializes a new instance of the <see cref="Window"/> class. /// </summary> /// <param name="impl">The window implementation.</param> public Window(IWindowImpl impl) : base(impl) { impl.Closing = HandleClosing; _maxPlatformClientSize = PlatformImpl?.MaxClientSize ?? default(Size); Screens = new Screens(PlatformImpl?.Screen); } /// <inheritdoc/> event EventHandler<NameScopeEventArgs> INameScope.Registered { add { _nameScope.Registered += value; } remove { _nameScope.Registered -= value; } } /// <inheritdoc/> event EventHandler<NameScopeEventArgs> INameScope.Unregistered { add { _nameScope.Unregistered += value; } remove { _nameScope.Unregistered -= value; } } public Screens Screens { get; private set; } /// <summary> /// Gets the platform-specific window implementation. /// </summary> [CanBeNull] public new IWindowImpl PlatformImpl => (IWindowImpl)base.PlatformImpl; /// <summary> /// Gets or sets a value indicating how the window will size itself to fit its content. /// </summary> public SizeToContent SizeToContent { get { return GetValue(SizeToContentProperty); } set { SetValue(SizeToContentProperty, value); } } /// <summary> /// Gets or sets the title of the window. /// </summary> public string Title { get { return GetValue(TitleProperty); } set { SetValue(TitleProperty, value); } } /// <summary> /// Enables or disables system window decorations (title bar, buttons, etc) /// </summary> /// public bool HasSystemDecorations { get { return GetValue(HasSystemDecorationsProperty); } set { SetValue(HasSystemDecorationsProperty, value); } } /// <summary> /// Enables or disables the taskbar icon /// </summary> /// public bool ShowInTaskbar { get { return GetValue(ShowInTaskbarProperty); } set { SetValue(ShowInTaskbarProperty, value); } } /// <summary> /// Gets or sets the minimized/maximized state of the window. /// </summary> public WindowState WindowState { get { return PlatformImpl?.WindowState ?? WindowState.Normal; } set { if (PlatformImpl != null) PlatformImpl.WindowState = value; } } /// <summary> /// Enables or disables resizing of the window /// </summary> public bool CanResize { get { return GetValue(CanResizeProperty); } set { SetValue(CanResizeProperty, value); } } /// <summary> /// Gets or sets the icon of the window. /// </summary> public WindowIcon Icon { get { return GetValue(IconProperty); } set { SetValue(IconProperty, value); } } /// <summary> /// Gets or sets the startup location of the window. /// </summary> public WindowStartupLocation WindowStartupLocation { get { return _windowStartupLoction; } set { SetAndRaise(WindowStartupLocationProperty, ref _windowStartupLoction, value); } } /// <inheritdoc/> Size ILayoutRoot.MaxClientSize => _maxPlatformClientSize; /// <inheritdoc/> Type IStyleable.StyleKey => typeof(Window); /// <summary> /// Fired before a window is closed. /// </summary> public event EventHandler<CancelEventArgs> Closing; /// <summary> /// Closes the window. /// </summary> public void Close() { Close(false); } protected override void HandleApplicationExiting() { base.HandleApplicationExiting(); Close(true); } /// <summary> /// Closes a dialog window with the specified result. /// </summary> /// <param name="dialogResult">The dialog result.</param> /// <remarks> /// When the window is shown with the <see cref="ShowDialog{TResult}"/> method, the /// resulting task will produce the <see cref="_dialogResult"/> value when the window /// is closed. /// </remarks> public void Close(object dialogResult) { _dialogResult = dialogResult; Close(false); } internal void Close(bool ignoreCancel) { var cancelClosing = false; try { cancelClosing = HandleClosing(); } finally { if (ignoreCancel || !cancelClosing) { s_windows.Remove(this); PlatformImpl?.Dispose(); IsVisible = false; } } } /// <summary> /// Handles a closing notification from <see cref="IWindowImpl.Closing"/>. /// </summary> protected virtual bool HandleClosing() { var args = new CancelEventArgs(); Closing?.Invoke(this, args); return args.Cancel; } /// <summary> /// Hides the window but does not close it. /// </summary> public override void Hide() { if (!IsVisible) { return; } using (BeginAutoSizing()) { Renderer?.Stop(); PlatformImpl?.Hide(); } IsVisible = false; } /// <summary> /// Shows the window. /// </summary> public override void Show() { if (IsVisible) { return; } s_windows.Add(this); EnsureInitialized(); SetWindowStartupLocation(); IsVisible = true; LayoutManager.Instance.ExecuteInitialLayoutPass(this); using (BeginAutoSizing()) { PlatformImpl?.Show(); Renderer?.Start(); } } /// <summary> /// Shows the window as a dialog. /// </summary> /// <returns> /// A task that can be used to track the lifetime of the dialog. /// </returns> public Task ShowDialog() { return ShowDialog<object>(); } /// <summary> /// Shows the window as a dialog. /// </summary> /// <typeparam name="TResult"> /// The type of the result produced by the dialog. /// </typeparam> /// <returns>. /// A task that can be used to retrive the result of the dialog when it closes. /// </returns> public Task<TResult> ShowDialog<TResult>() { if (IsVisible) { throw new InvalidOperationException("The window is already being shown."); } s_windows.Add(this); EnsureInitialized(); SetWindowStartupLocation(); IsVisible = true; LayoutManager.Instance.ExecuteInitialLayoutPass(this); using (BeginAutoSizing()) { var affectedWindows = s_windows.Where(w => w.IsEnabled && w != this).ToList(); var activated = affectedWindows.Where(w => w.IsActive).FirstOrDefault(); SetIsEnabled(affectedWindows, false); var modal = PlatformImpl?.ShowDialog(); var result = new TaskCompletionSource<TResult>(); Renderer?.Start(); Observable.FromEventPattern<EventHandler, EventArgs>( x => this.Closed += x, x => this.Closed -= x) .Take(1) .Subscribe(_ => { modal?.Dispose(); SetIsEnabled(affectedWindows, true); activated?.Activate(); result.SetResult((TResult)(_dialogResult ?? default(TResult))); }); return result.Task; } } void SetIsEnabled(IEnumerable<Window> windows, bool isEnabled) { foreach (var window in windows) { window.IsEnabled = isEnabled; } } void SetWindowStartupLocation() { if (WindowStartupLocation == WindowStartupLocation.CenterScreen) { var screen = Screens.ScreenFromPoint(Bounds.Position); if (screen != null) Position = screen.WorkingArea.CenterRect(new Rect(ClientSize)).Position; } else if (WindowStartupLocation == WindowStartupLocation.CenterOwner) { if (Owner != null) { var positionAsSize = Owner.ClientSize / 2 - ClientSize / 2; Position = Owner.Position + new Point(positionAsSize.Width, positionAsSize.Height); } } } /// <inheritdoc/> void INameScope.Register(string name, object element) { _nameScope.Register(name, element); } /// <inheritdoc/> object INameScope.Find(string name) { return _nameScope.Find(name); } /// <inheritdoc/> void INameScope.Unregister(string name) { _nameScope.Unregister(name); } /// <inheritdoc/> protected override Size MeasureOverride(Size availableSize) { var sizeToContent = SizeToContent; var clientSize = ClientSize; Size constraint = clientSize; if ((sizeToContent & SizeToContent.Width) != 0) { constraint = constraint.WithWidth(double.PositiveInfinity); } if ((sizeToContent & SizeToContent.Height) != 0) { constraint = constraint.WithHeight(double.PositiveInfinity); } var result = base.MeasureOverride(constraint); if ((sizeToContent & SizeToContent.Width) == 0) { result = result.WithWidth(clientSize.Width); } if ((sizeToContent & SizeToContent.Height) == 0) { result = result.WithHeight(clientSize.Height); } return result; } protected override void HandleClosed() { IsVisible = false; s_windows.Remove(this); base.HandleClosed(); } /// <inheritdoc/> protected override void HandleResized(Size clientSize) { if (!AutoSizing) { SizeToContent = SizeToContent.Manual; } base.HandleResized(clientSize); } } } namespace Avalonia { public static class WindowApplicationExtensions { public static void RunWithMainWindow<TWindow>(this Application app) where TWindow : Avalonia.Controls.Window, new() { var window = new TWindow(); window.Show(); app.Run(window); } } }
// "Therefore those skilled at the unorthodox // are infinite as heaven and earth, // inexhaustible as the great rivers. // When they come to an end, // they begin again, // like the days and months; // they die and are reborn, // like the four seasons." // // - Sun Tsu, // "The Art of War" using System; using System.Collections.Generic; using Scientia.HtmlRenderer.Adapters; using Scientia.HtmlRenderer.Adapters.Entities; using Scientia.HtmlRenderer.Core.Utils; namespace Scientia.HtmlRenderer.Core.Dom { /// <summary> /// Helps on CSS Layout. /// </summary> internal static class CssLayoutEngine { /// <summary> /// Measure image box size by the width\height set on the box and the actual rendered image size.<br/> /// If no image exists for the box error icon will be set. /// </summary> /// <param name="imageWord">the image word to measure</param> public static void MeasureImageSize(CssRectImage imageWord) { ArgChecker.AssertArgNotNull(imageWord, "imageWord"); ArgChecker.AssertArgNotNull(imageWord.OwnerBox, "imageWord.OwnerBox"); var width = new CssLength(imageWord.OwnerBox.Width); var height = new CssLength(imageWord.OwnerBox.Height); bool hasImageTagWidth = width.Number > 0 && width.Unit == CssUnit.Pixels; bool hasImageTagHeight = height.Number > 0 && height.Unit == CssUnit.Pixels; bool scaleImageHeight = false; if (hasImageTagWidth) { imageWord.Width = width.Number; } else if (width.Number > 0 && width.IsPercentage) { imageWord.Width = width.Number * imageWord.OwnerBox.ContainingBlock.Size.Width; scaleImageHeight = true; } else if (imageWord.Image != null) { imageWord.Width = imageWord.ImageRectangle == RRect.Empty ? imageWord.Image.Width : imageWord.ImageRectangle.Width; } else { imageWord.Width = hasImageTagHeight ? height.Number / 1.14f : 20; } var maxWidth = new CssLength(imageWord.OwnerBox.MaxWidth); if (maxWidth.Number > 0) { double maxWidthVal = -1; if (maxWidth.Unit == CssUnit.Pixels) { maxWidthVal = maxWidth.Number; } else if (maxWidth.IsPercentage) { maxWidthVal = maxWidth.Number * imageWord.OwnerBox.ContainingBlock.Size.Width; } if (maxWidthVal > -1 && imageWord.Width > maxWidthVal) { imageWord.Width = maxWidthVal; scaleImageHeight = !hasImageTagHeight; } } if (hasImageTagHeight) { imageWord.Height = height.Number; } else if (imageWord.Image != null) { imageWord.Height = imageWord.ImageRectangle == RRect.Empty ? imageWord.Image.Height : imageWord.ImageRectangle.Height; } else { imageWord.Height = imageWord.Width > 0 ? imageWord.Width * 1.14f : 22.8f; } if (imageWord.Image != null) { // If only the width was set in the html tag, ratio the height. if ((hasImageTagWidth && !hasImageTagHeight) || scaleImageHeight) { // Divide the given tag width with the actual image width, to get the ratio. double ratio = imageWord.Width / imageWord.Image.Width; imageWord.Height = imageWord.Image.Height * ratio; } // If only the height was set in the html tag, ratio the width. else if (hasImageTagHeight && !hasImageTagWidth) { // Divide the given tag height with the actual image height, to get the ratio. double ratio = imageWord.Height / imageWord.Image.Height; imageWord.Width = imageWord.Image.Width * ratio; } } imageWord.Height += imageWord.OwnerBox.ActualBorderBottomWidth + imageWord.OwnerBox.ActualBorderTopWidth + imageWord.OwnerBox.ActualPaddingTop + imageWord.OwnerBox.ActualPaddingBottom; } /// <summary> /// Creates line boxes for the specified blockbox /// </summary> /// <param name="g"></param> /// <param name="blockBox"></param> public static void CreateLineBoxes(RGraphics g, CssBox blockBox) { ArgChecker.AssertArgNotNull(g, "g"); ArgChecker.AssertArgNotNull(blockBox, "blockBox"); blockBox.LineBoxes.Clear(); double limitRight = blockBox.ActualRight - blockBox.ActualPaddingRight - blockBox.ActualBorderRightWidth; // Get the start x and y of the blockBox double startx = blockBox.Location.X + blockBox.ActualPaddingLeft - 0 + blockBox.ActualBorderLeftWidth; double starty = blockBox.Location.Y + blockBox.ActualPaddingTop - 0 + blockBox.ActualBorderTopWidth; double curx = startx + blockBox.ActualTextIndent; double cury = starty; // Reminds the maximum bottom reached double maxRight = startx; double maxBottom = starty; // First line box CssLineBox line = new CssLineBox(blockBox); // Flow words and boxes FlowBox(g, blockBox, blockBox, limitRight, 0, startx, ref line, ref curx, ref cury, ref maxRight, ref maxBottom); // if width is not restricted we need to lower it to the actual width if (blockBox.ActualRight >= 90999) { blockBox.ActualRight = maxRight + blockBox.ActualPaddingRight + blockBox.ActualBorderRightWidth; } // Gets the rectangles for each line-box foreach (var linebox in blockBox.LineBoxes) { ApplyHorizontalAlignment(g, linebox); ApplyRightToLeft(blockBox, linebox); BubbleRectangles(blockBox, linebox); ApplyVerticalAlignment(g, linebox); linebox.AssignRectanglesToBoxes(); } blockBox.ActualBottom = maxBottom + blockBox.ActualPaddingBottom + blockBox.ActualBorderBottomWidth; // handle limiting block height when overflow is hidden if (blockBox.Height != null && blockBox.Height != CssConstants.Auto && blockBox.Overflow == CssConstants.Hidden && blockBox.ActualBottom - blockBox.Location.Y > blockBox.ActualHeight) { blockBox.ActualBottom = blockBox.Location.Y + blockBox.ActualHeight; } } /// <summary> /// Applies special vertical alignment for table-cells /// </summary> /// <param name="g"></param> /// <param name="cell"></param> public static void ApplyCellVerticalAlignment(RGraphics g, CssBox cell) { ArgChecker.AssertArgNotNull(g, "g"); ArgChecker.AssertArgNotNull(cell, "cell"); if (cell.VerticalAlign == CssConstants.Top || cell.VerticalAlign == CssConstants.Baseline) return; double cellbot = cell.ClientBottom; double bottom = cell.GetMaximumBottom(cell, 0f); double dist = 0f; if (cell.VerticalAlign == CssConstants.Bottom) { dist = cellbot - bottom; } else if (cell.VerticalAlign == CssConstants.Middle) { dist = (cellbot - bottom) / 2; } foreach (CssBox b in cell.Boxes) { b.OffsetTop(dist); } // float top = cell.ClientTop; // float bottom = cell.ClientBottom; // bool middle = cell.VerticalAlign == CssConstants.Middle; // foreach (LineBox line in cell.LineBoxes) // { // for (int i = 0; i < line.RelatedBoxes.Count; i++) // { // double diff = bottom - line.RelatedBoxes[i].Rectangles[line].Bottom; // if (middle) diff /= 2f; // RectangleF r = line.RelatedBoxes[i].Rectangles[line]; // line.RelatedBoxes[i].Rectangles[line] = new RectangleF(r.X, r.Y + diff, r.Width, r.Height); // } // foreach (BoxWord word in line.Words) // { // double gap = word.Top - top; // word.Top = bottom - gap - word.Height; // } // } } #region Private methods /// <summary> /// Recursively flows the content of the box using the inline model /// </summary> /// <param name="g">Device Info</param> /// <param name="blockbox">Blockbox that contains the text flow</param> /// <param name="box">Current box to flow its content</param> /// <param name="limitRight">Maximum reached right</param> /// <param name="linespacing">Space to use between rows of text</param> /// <param name="startx">x starting coordinate for when breaking lines of text</param> /// <param name="line">Current linebox being used</param> /// <param name="curx">Current x coordinate that will be the left of the next word</param> /// <param name="cury">Current y coordinate that will be the top of the next word</param> /// <param name="maxRight">Maximum right reached so far</param> /// <param name="maxbottom">Maximum bottom reached so far</param> private static void FlowBox(RGraphics g, CssBox blockbox, CssBox box, double limitRight, double linespacing, double startx, ref CssLineBox line, ref double curx, ref double cury, ref double maxRight, ref double maxbottom) { var startX = curx; var startY = cury; box.FirstHostingLineBox = line; var localCurx = curx; var localMaxRight = maxRight; var localmaxbottom = maxbottom; foreach (CssBox b in box.Boxes) { double leftspacing = (b.Position != CssConstants.Absolute && b.Position != CssConstants.Fixed) ? b.ActualMarginLeft + b.ActualBorderLeftWidth + b.ActualPaddingLeft : 0; double rightspacing = (b.Position != CssConstants.Absolute && b.Position != CssConstants.Fixed) ? b.ActualMarginRight + b.ActualBorderRightWidth + b.ActualPaddingRight : 0; b.RectanglesReset(); b.MeasureWordsSize(g); curx += leftspacing; if (b.Words.Count > 0) { bool wrapNoWrapBox = false; if (b.WhiteSpace == CssConstants.NoWrap && curx > startx) { var boxRight = curx; foreach (var word in b.Words) boxRight += word.FullWidth; if (boxRight > limitRight) wrapNoWrapBox = true; } if (DomUtils.IsBoxHasWhitespace(b)) curx += box.ActualWordSpacing; foreach (var word in b.Words) { if (maxbottom - cury < box.ActualLineHeight) maxbottom += box.ActualLineHeight - (maxbottom - cury); if ((b.WhiteSpace != CssConstants.NoWrap && b.WhiteSpace != CssConstants.Pre && curx + word.Width + rightspacing > limitRight && (b.WhiteSpace != CssConstants.PreWrap || !word.IsSpaces)) || word.IsLineBreak || wrapNoWrapBox) { wrapNoWrapBox = false; curx = startx; // handle if line is wrapped for the first text element where parent has left margin\padding if (b == box.Boxes[0] && !word.IsLineBreak && (word == b.Words[0] || (box.ParentBox != null && box.ParentBox.IsBlock))) curx += box.ActualMarginLeft + box.ActualBorderLeftWidth + box.ActualPaddingLeft; cury = maxbottom + linespacing; line = new CssLineBox(blockbox); if (word.IsImage || word.Equals(b.FirstWord)) { curx += leftspacing; } } line.ReportExistanceOf(word); word.Left = curx; word.Top = cury; if (!box.IsFixed && box.PageBreakInside == CssConstants.Avoid) { word.BreakPage(); } curx = word.Left + word.FullWidth; maxRight = Math.Max(maxRight, word.Right); maxbottom = Math.Max(maxbottom, word.Bottom); if (b.Position == CssConstants.Absolute) { word.Left += box.ActualMarginLeft; word.Top += box.ActualMarginTop; } } } else { FlowBox(g, blockbox, b, limitRight, linespacing, startx, ref line, ref curx, ref cury, ref maxRight, ref maxbottom); } curx += rightspacing; } // handle height setting if (maxbottom - startY < box.ActualHeight) { maxbottom += box.ActualHeight - (maxbottom - startY); } // handle width setting if (box.IsInline && 0 <= curx - startX && curx - startX < box.ActualWidth) { // hack for actual width handling curx += box.ActualWidth - (curx - startX); line.Rectangles.Add(box, new RRect(startX, startY, box.ActualWidth, box.ActualHeight)); } // handle box that is only a whitespace if (box.Text != null && box.Text.IsWhitespace() && !box.IsImage && box.IsInline && box.Boxes.Count == 0 && box.Words.Count == 0) { curx += box.ActualWordSpacing; } // hack to support specific absolute position elements if (box.Position == CssConstants.Absolute) { curx = localCurx; maxRight = localMaxRight; maxbottom = localmaxbottom; AdjustAbsolutePosition(box, 0, 0); } box.LastHostingLineBox = line; } /// <summary> /// Adjust the position of absolute elements by letf and top margins. /// </summary> private static void AdjustAbsolutePosition(CssBox box, double left, double top) { left += box.ActualMarginLeft; top += box.ActualMarginTop; if (box.Words.Count > 0) { foreach (var word in box.Words) { word.Left += left; word.Top += top; } } else { foreach (var b in box.Boxes) AdjustAbsolutePosition(b, left, top); } } /// <summary> /// Recursively creates the rectangles of the blockBox, by bubbling from deep to outside of the boxes /// in the rectangle structure /// </summary> private static void BubbleRectangles(CssBox box, CssLineBox line) { if (box.Words.Count > 0) { double x = Single.MaxValue, y = Single.MaxValue, r = Single.MinValue, b = Single.MinValue; List<CssRect> words = line.WordsOf(box); if (words.Count > 0) { foreach (CssRect word in words) { // handle if line is wrapped for the first text element where parent has left margin\padding var left = word.Left; if (box == box.ParentBox.Boxes[0] && word == box.Words[0] && word == line.Words[0] && line != line.OwnerBox.LineBoxes[0] && !word.IsLineBreak) left -= box.ParentBox.ActualMarginLeft + box.ParentBox.ActualBorderLeftWidth + box.ParentBox.ActualPaddingLeft; x = Math.Min(x, left); r = Math.Max(r, word.Right); y = Math.Min(y, word.Top); b = Math.Max(b, word.Bottom); } line.UpdateRectangle(box, x, y, r, b); } } else { foreach (CssBox b in box.Boxes) { BubbleRectangles(b, line); } } } /// <summary> /// Applies vertical and horizontal alignment to words in lineboxes /// </summary> /// <param name="g"></param> /// <param name="lineBox"></param> private static void ApplyHorizontalAlignment(RGraphics g, CssLineBox lineBox) { switch (lineBox.OwnerBox.TextAlign) { case CssConstants.Right: ApplyRightAlignment(g, lineBox); break; case CssConstants.Center: ApplyCenterAlignment(g, lineBox); break; case CssConstants.Justify: ApplyJustifyAlignment(g, lineBox); break; default: ApplyLeftAlignment(g, lineBox); break; } } /// <summary> /// Applies right to left direction to words /// </summary> /// <param name="blockBox"></param> /// <param name="lineBox"></param> private static void ApplyRightToLeft(CssBox blockBox, CssLineBox lineBox) { if (blockBox.Direction == CssConstants.Rtl) { ApplyRightToLeftOnLine(lineBox); } else { foreach (var box in lineBox.RelatedBoxes) { if (box.Direction == CssConstants.Rtl) { ApplyRightToLeftOnSingleBox(lineBox, box); } } } } /// <summary> /// Applies RTL direction to all the words on the line. /// </summary> /// <param name="line">the line to apply RTL to</param> private static void ApplyRightToLeftOnLine(CssLineBox line) { if (line.Words.Count > 0) { double left = line.Words[0].Left; double right = line.Words[line.Words.Count - 1].Right; foreach (CssRect word in line.Words) { double diff = word.Left - left; double wright = right - diff; word.Left = wright - word.Width; } } } /// <summary> /// Applies RTL direction to specific box words on the line. /// </summary> /// <param name="lineBox"></param> /// <param name="box"></param> private static void ApplyRightToLeftOnSingleBox(CssLineBox lineBox, CssBox box) { int leftWordIdx = -1; int rightWordIdx = -1; for (int i = 0; i < lineBox.Words.Count; i++) { if (lineBox.Words[i].OwnerBox == box) { if (leftWordIdx < 0) leftWordIdx = i; rightWordIdx = i; } } if (leftWordIdx > -1 && rightWordIdx > leftWordIdx) { double left = lineBox.Words[leftWordIdx].Left; double right = lineBox.Words[rightWordIdx].Right; for (int i = leftWordIdx; i <= rightWordIdx; i++) { double diff = lineBox.Words[i].Left - left; double wright = right - diff; lineBox.Words[i].Left = wright - lineBox.Words[i].Width; } } } /// <summary> /// Applies vertical alignment to the linebox /// </summary> /// <param name="g"></param> /// <param name="lineBox"></param> private static void ApplyVerticalAlignment(RGraphics g, CssLineBox lineBox) { double baseline = Single.MinValue; foreach (var box in lineBox.Rectangles.Keys) { baseline = Math.Max(baseline, lineBox.Rectangles[box].Top); } var boxes = new List<CssBox>(lineBox.Rectangles.Keys); foreach (CssBox box in boxes) { // Important notes on http://www.w3.org/TR/CSS21/tables.html#height-layout switch (box.VerticalAlign) { case CssConstants.Sub: lineBox.SetBaseLine(g, box, baseline + (lineBox.Rectangles[box].Height * .5f)); break; case CssConstants.Super: lineBox.SetBaseLine(g, box, baseline - (lineBox.Rectangles[box].Height * .2f)); break; case CssConstants.TextTop: break; case CssConstants.TextBottom: break; case CssConstants.Top: break; case CssConstants.Bottom: break; case CssConstants.Middle: break; default: // case: baseline lineBox.SetBaseLine(g, box, baseline); break; } } } /// <summary> /// Applies centered alignment to the text on the linebox /// </summary> /// <param name="g"></param> /// <param name="lineBox"></param> private static void ApplyJustifyAlignment(RGraphics g, CssLineBox lineBox) { if (lineBox.Equals(lineBox.OwnerBox.LineBoxes[lineBox.OwnerBox.LineBoxes.Count - 1])) return; double indent = lineBox.Equals(lineBox.OwnerBox.LineBoxes[0]) ? lineBox.OwnerBox.ActualTextIndent : 0f; double textSum = 0f; double words = 0f; double availWidth = lineBox.OwnerBox.ClientRectangle.Width - indent; // Gather text sum foreach (CssRect w in lineBox.Words) { textSum += w.Width; words += 1f; } if (words <= 0f) return; // Avoid Zero division double spacing = (availWidth - textSum) / words; // Spacing that will be used double curx = lineBox.OwnerBox.ClientLeft + indent; foreach (CssRect word in lineBox.Words) { word.Left = curx; curx = word.Right + spacing; if (word == lineBox.Words[lineBox.Words.Count - 1]) { word.Left = lineBox.OwnerBox.ClientRight - word.Width; } } } /// <summary> /// Applies centered alignment to the text on the linebox /// </summary> /// <param name="g"></param> /// <param name="line"></param> private static void ApplyCenterAlignment(RGraphics g, CssLineBox line) { if (line.Words.Count == 0) return; CssRect lastWord = line.Words[line.Words.Count - 1]; double right = line.OwnerBox.ActualRight - line.OwnerBox.ActualPaddingRight - line.OwnerBox.ActualBorderRightWidth; double diff = right - lastWord.Right - lastWord.OwnerBox.ActualBorderRightWidth - lastWord.OwnerBox.ActualPaddingRight; diff /= 2; if (diff > 0) { foreach (CssRect word in line.Words) { word.Left += diff; } if (line.Rectangles.Count > 0) { foreach (CssBox b in ToList(line.Rectangles.Keys)) { RRect r = line.Rectangles[b]; line.Rectangles[b] = new RRect(r.X + diff, r.Y, r.Width, r.Height); } } } } /// <summary> /// Applies right alignment to the text on the linebox /// </summary> /// <param name="g"></param> /// <param name="line"></param> private static void ApplyRightAlignment(RGraphics g, CssLineBox line) { if (line.Words.Count == 0) return; CssRect lastWord = line.Words[line.Words.Count - 1]; double right = line.OwnerBox.ActualRight - line.OwnerBox.ActualPaddingRight - line.OwnerBox.ActualBorderRightWidth; double diff = right - lastWord.Right - lastWord.OwnerBox.ActualBorderRightWidth - lastWord.OwnerBox.ActualPaddingRight; if (diff > 0) { foreach (CssRect word in line.Words) { word.Left += diff; } if (line.Rectangles.Count > 0) { foreach (CssBox b in ToList(line.Rectangles.Keys)) { RRect r = line.Rectangles[b]; line.Rectangles[b] = new RRect(r.X + diff, r.Y, r.Width, r.Height); } } } } /// <summary> /// Simplest alignment, just arrange words. /// </summary> /// <param name="g"></param> /// <param name="line"></param> private static void ApplyLeftAlignment(RGraphics g, CssLineBox line) { // No alignment needed. // foreach (LineBoxRectangle r in line.Rectangles) // { // double curx = r.Left + (r.Index == 0 ? r.OwnerBox.ActualPaddingLeft + r.OwnerBox.ActualBorderLeftWidth / 2 : 0); // if (r.SpaceBefore) curx += r.OwnerBox.ActualWordSpacing; // foreach (BoxWord word in r.Words) // { // word.Left = curx; // word.Top = r.Top;// +r.OwnerBox.ActualPaddingTop + r.OwnerBox.ActualBorderTopWidth / 2; // curx = word.Right + r.OwnerBox.ActualWordSpacing; // } // } } /// <summary> /// todo: optimizate, not creating a list each time /// </summary> private static List<T> ToList<T>(IEnumerable<T> collection) { List<T> result = new List<T>(); foreach (T item in collection) { result.Add(item); } return result; } #endregion } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.ComponentModel; using System.Diagnostics; using System.Runtime; using System.ServiceModel.Channels; using System.ServiceModel.Description; using System.ServiceModel.Diagnostics; using System.Threading; using System.ServiceModel.Diagnostics.Application; using System.ServiceModel.Dispatcher; namespace System.ServiceModel { public abstract class ClientBase<TChannel> : ICommunicationObject, IDisposable where TChannel : class { private TChannel _channel; private ChannelFactoryRef<TChannel> _channelFactoryRef; private EndpointTrait<TChannel> _endpointTrait; // Determine whether the proxy can share factory with others. It is false only if the public getters // are invoked. private bool _canShareFactory = true; // Determine whether the proxy is currently holding a cached factory private bool _useCachedFactory; // Determine whether we have locked down sharing for this proxy. This is turned on only when the channel // is created. private bool _sharingFinalized; // Determine whether the ChannelFactoryRef has been released. We should release it only once per proxy private bool _channelFactoryRefReleased; // Determine whether we have released the last ref count of the ChannelFactory so that we could abort it when it was closing. private bool _releasedLastRef; private object _syncRoot = new object(); private object _finalizeLock = new object(); // Cache at most 32 ChannelFactories private const int maxNumChannelFactories = 32; private static ChannelFactoryRefCache<TChannel> s_factoryRefCache = new ChannelFactoryRefCache<TChannel>(maxNumChannelFactories); private static object s_staticLock = new object(); private static object s_cacheLock = new object(); private static CacheSetting s_cacheSetting = CacheSetting.Default; private static bool s_isCacheSettingReadOnly; private static AsyncCallback s_onAsyncCallCompleted = Fx.ThunkCallback(new AsyncCallback(OnAsyncCallCompleted)); // IMPORTANT: any changes to the set of protected .ctors of this class need to be reflected // in ServiceContractGenerator.cs as well. protected ClientBase() { MakeCacheSettingReadOnly(); if (s_cacheSetting == CacheSetting.AlwaysOff) { _channelFactoryRef = new ChannelFactoryRef<TChannel>(new ChannelFactory<TChannel>("*")); _channelFactoryRef.ChannelFactory.TraceOpenAndClose = false; TryDisableSharing(); } else { _endpointTrait = new ConfigurationEndpointTrait<TChannel>("*", null, null); InitializeChannelFactoryRef(); } } protected ClientBase(string endpointConfigurationName) { if (endpointConfigurationName == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("endpointConfigurationName"); MakeCacheSettingReadOnly(); if (s_cacheSetting == CacheSetting.AlwaysOff) { _channelFactoryRef = new ChannelFactoryRef<TChannel>(new ChannelFactory<TChannel>(endpointConfigurationName)); _channelFactoryRef.ChannelFactory.TraceOpenAndClose = false; TryDisableSharing(); } else { _endpointTrait = new ConfigurationEndpointTrait<TChannel>(endpointConfigurationName, null, null); InitializeChannelFactoryRef(); } } protected ClientBase(string endpointConfigurationName, string remoteAddress) { if (endpointConfigurationName == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("endpointConfigurationName"); if (remoteAddress == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("remoteAddress"); MakeCacheSettingReadOnly(); EndpointAddress endpointAddress = new EndpointAddress(remoteAddress); if (s_cacheSetting == CacheSetting.AlwaysOff) { _channelFactoryRef = new ChannelFactoryRef<TChannel>(new ChannelFactory<TChannel>(endpointConfigurationName, endpointAddress)); _channelFactoryRef.ChannelFactory.TraceOpenAndClose = false; TryDisableSharing(); } else { _endpointTrait = new ConfigurationEndpointTrait<TChannel>(endpointConfigurationName, endpointAddress, null); InitializeChannelFactoryRef(); } } protected ClientBase(string endpointConfigurationName, EndpointAddress remoteAddress) { if (endpointConfigurationName == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("endpointConfigurationName"); if (remoteAddress == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("remoteAddress"); MakeCacheSettingReadOnly(); if (s_cacheSetting == CacheSetting.AlwaysOff) { _channelFactoryRef = new ChannelFactoryRef<TChannel>(new ChannelFactory<TChannel>(endpointConfigurationName, remoteAddress)); _channelFactoryRef.ChannelFactory.TraceOpenAndClose = false; TryDisableSharing(); } else { _endpointTrait = new ConfigurationEndpointTrait<TChannel>(endpointConfigurationName, remoteAddress, null); InitializeChannelFactoryRef(); } } protected ClientBase(Binding binding, EndpointAddress remoteAddress) { if (binding == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("binding"); if (remoteAddress == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("remoteAddress"); MakeCacheSettingReadOnly(); { _channelFactoryRef = new ChannelFactoryRef<TChannel>(new ChannelFactory<TChannel>(binding, remoteAddress)); _channelFactoryRef.ChannelFactory.TraceOpenAndClose = false; TryDisableSharing(); } } protected ClientBase(ServiceEndpoint endpoint) { if (endpoint == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("endpoint"); MakeCacheSettingReadOnly(); { _channelFactoryRef = new ChannelFactoryRef<TChannel>(new ChannelFactory<TChannel>(endpoint)); _channelFactoryRef.ChannelFactory.TraceOpenAndClose = false; TryDisableSharing(); } } protected ClientBase(InstanceContext callbackInstance) { if (callbackInstance == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("callbackInstance"); MakeCacheSettingReadOnly(); if (s_cacheSetting == CacheSetting.AlwaysOff) { _channelFactoryRef = new ChannelFactoryRef<TChannel>( new DuplexChannelFactory<TChannel>(callbackInstance, "*")); _channelFactoryRef.ChannelFactory.TraceOpenAndClose = false; TryDisableSharing(); } else { _endpointTrait = new ConfigurationEndpointTrait<TChannel>("*", null, callbackInstance); InitializeChannelFactoryRef(); } } protected ClientBase(InstanceContext callbackInstance, string endpointConfigurationName) { if (callbackInstance == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("callbackInstance"); if (endpointConfigurationName == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("endpointConfigurationName"); MakeCacheSettingReadOnly(); if (s_cacheSetting == CacheSetting.AlwaysOff) { _channelFactoryRef = new ChannelFactoryRef<TChannel>( new DuplexChannelFactory<TChannel>(callbackInstance, endpointConfigurationName)); _channelFactoryRef.ChannelFactory.TraceOpenAndClose = false; TryDisableSharing(); } else { _endpointTrait = new ConfigurationEndpointTrait<TChannel>(endpointConfigurationName, null, callbackInstance); InitializeChannelFactoryRef(); } } protected ClientBase(InstanceContext callbackInstance, string endpointConfigurationName, string remoteAddress) { if (callbackInstance == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("callbackInstance"); if (endpointConfigurationName == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("endpointConfigurationName"); if (remoteAddress == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("remoteAddress"); MakeCacheSettingReadOnly(); EndpointAddress endpointAddress = new EndpointAddress(remoteAddress); if (s_cacheSetting == CacheSetting.AlwaysOff) { _channelFactoryRef = new ChannelFactoryRef<TChannel>( new DuplexChannelFactory<TChannel>(callbackInstance, endpointConfigurationName, endpointAddress)); _channelFactoryRef.ChannelFactory.TraceOpenAndClose = false; TryDisableSharing(); } else { _endpointTrait = new ConfigurationEndpointTrait<TChannel>(endpointConfigurationName, endpointAddress, callbackInstance); InitializeChannelFactoryRef(); } } protected ClientBase(InstanceContext callbackInstance, string endpointConfigurationName, EndpointAddress remoteAddress) { if (callbackInstance == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("callbackInstance"); if (endpointConfigurationName == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("endpointConfigurationName"); if (remoteAddress == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("remoteAddress"); MakeCacheSettingReadOnly(); if (s_cacheSetting == CacheSetting.AlwaysOff) { _channelFactoryRef = new ChannelFactoryRef<TChannel>( new DuplexChannelFactory<TChannel>(callbackInstance, endpointConfigurationName, remoteAddress)); _channelFactoryRef.ChannelFactory.TraceOpenAndClose = false; TryDisableSharing(); } else { _endpointTrait = new ConfigurationEndpointTrait<TChannel>(endpointConfigurationName, remoteAddress, callbackInstance); InitializeChannelFactoryRef(); } } protected ClientBase(InstanceContext callbackInstance, Binding binding, EndpointAddress remoteAddress) { if (callbackInstance == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("callbackInstance"); if (binding == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("binding"); if (remoteAddress == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("remoteAddress"); MakeCacheSettingReadOnly(); { _channelFactoryRef = new ChannelFactoryRef<TChannel>( new DuplexChannelFactory<TChannel>(callbackInstance, binding, remoteAddress)); _channelFactoryRef.ChannelFactory.TraceOpenAndClose = false; TryDisableSharing(); } } protected ClientBase(InstanceContext callbackInstance, ServiceEndpoint endpoint) { if (callbackInstance == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("callbackInstance"); if (endpoint == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("endpoint"); MakeCacheSettingReadOnly(); { _channelFactoryRef = new ChannelFactoryRef<TChannel>( new DuplexChannelFactory<TChannel>(callbackInstance, endpoint)); _channelFactoryRef.ChannelFactory.TraceOpenAndClose = false; TryDisableSharing(); } } protected T GetDefaultValueForInitialization<T>() { return default(T); } private object ThisLock { get { return _syncRoot; } } protected TChannel Channel { get { // created on demand, so that Mort can modify .Endpoint before calling methods on the client if (_channel == null) { lock (ThisLock) { if (_channel == null) { using (ServiceModelActivity activity = DiagnosticUtility.ShouldUseActivity ? ServiceModelActivity.CreateBoundedActivity() : null) { if (DiagnosticUtility.ShouldUseActivity) { ServiceModelActivity.Start(activity, SR.Format(SR.ActivityOpenClientBase, typeof(TChannel).FullName), ActivityType.OpenClient); } if (_useCachedFactory) { try { CreateChannelInternal(); } #pragma warning suppress 56500 // covered by FxCOP catch (Exception ex) { if (_useCachedFactory && (ex is CommunicationException || ex is ObjectDisposedException || ex is TimeoutException)) { InvalidateCacheAndCreateChannel(); } else { throw; } } } else { CreateChannelInternal(); } } } } } return _channel; } } public static CacheSetting CacheSetting { get { return s_cacheSetting; } set { lock (s_cacheLock) { if (s_isCacheSettingReadOnly && s_cacheSetting != value) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.SFxImmutableClientBaseCacheSetting, typeof(TChannel).ToString()))); } else { s_cacheSetting = value; } } } } public ChannelFactory<TChannel> ChannelFactory { get { if (s_cacheSetting == CacheSetting.Default) { TryDisableSharing(); } return GetChannelFactory(); } } public ClientCredentials ClientCredentials { get { if (s_cacheSetting == CacheSetting.Default) { TryDisableSharing(); } return this.ChannelFactory.Credentials; } } public CommunicationState State { get { IChannel channel = (IChannel)_channel; if (channel != null) { return channel.State; } else { // we may have failed to create the channel under open, in which case we our factory wouldn't be open if (!_useCachedFactory) { return GetChannelFactory().State; } else { return CommunicationState.Created; } } } } public IClientChannel InnerChannel { get { return (IClientChannel)Channel; } } public ServiceEndpoint Endpoint { get { if (s_cacheSetting == CacheSetting.Default) { TryDisableSharing(); } return GetChannelFactory().Endpoint; } } public void Open() { ((ICommunicationObject)this).Open(GetChannelFactory().InternalOpenTimeout); } public void Abort() { IChannel channel = (IChannel)_channel; if (channel != null) { channel.Abort(); } if (!_channelFactoryRefReleased) { lock (s_staticLock) { if (!_channelFactoryRefReleased) { if (_channelFactoryRef.Release()) { _releasedLastRef = true; } _channelFactoryRefReleased = true; } } } // Abort the ChannelFactory if we released the last one. We should be able to abort it when another thread is closing it. if (_releasedLastRef) { _channelFactoryRef.Abort(); } } public void Close() { ((ICommunicationObject)this).Close(GetChannelFactory().InternalCloseTimeout); } public void DisplayInitializationUI() { ((IClientChannel)this.InnerChannel).DisplayInitializationUI(); } // This ensures that the cachesetting (on, off or default) cannot be modified by // another ClientBase instance of matching TChannel after the first instance is created. private void MakeCacheSettingReadOnly() { if (s_isCacheSettingReadOnly) return; lock (s_cacheLock) { s_isCacheSettingReadOnly = true; } } private void CreateChannelInternal() { try { _channel = this.CreateChannel(); if (_sharingFinalized) { if (_canShareFactory && !_useCachedFactory) { // It is OK to add ChannelFactory to the cache now. TryAddChannelFactoryToCache(); } } } finally { if (!_sharingFinalized && s_cacheSetting == CacheSetting.Default) { // this.CreateChannel() is not called. For safety, we disable sharing. TryDisableSharing(); } } } protected virtual TChannel CreateChannel() { if (_sharingFinalized) return GetChannelFactory().CreateChannel(); lock (_finalizeLock) { _sharingFinalized = true; return GetChannelFactory().CreateChannel(); } } void IDisposable.Dispose() { this.Close(); } void ICommunicationObject.Open(TimeSpan timeout) { TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); if (!_useCachedFactory) { GetChannelFactory().Open(timeoutHelper.RemainingTime()); } this.InnerChannel.Open(timeoutHelper.RemainingTime()); } void ICommunicationObject.Close(TimeSpan timeout) { using (ServiceModelActivity activity = DiagnosticUtility.ShouldUseActivity ? ServiceModelActivity.CreateBoundedActivity() : null) { if (DiagnosticUtility.ShouldUseActivity) { ServiceModelActivity.Start(activity, SR.Format(SR.ActivityCloseClientBase, typeof(TChannel).FullName), ActivityType.Close); } TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); if (_channel != null) { InnerChannel.Close(timeoutHelper.RemainingTime()); } if (!_channelFactoryRefReleased) { lock (s_staticLock) { if (!_channelFactoryRefReleased) { if (_channelFactoryRef.Release()) { _releasedLastRef = true; } _channelFactoryRefReleased = true; } } // Close the factory outside of the lock so that we can abort from a different thread. if (_releasedLastRef) { if (_useCachedFactory) { _channelFactoryRef.Abort(); } else { _channelFactoryRef.Close(timeoutHelper.RemainingTime()); } } } } } event EventHandler ICommunicationObject.Closed { add { this.InnerChannel.Closed += value; } remove { this.InnerChannel.Closed -= value; } } event EventHandler ICommunicationObject.Closing { add { this.InnerChannel.Closing += value; } remove { this.InnerChannel.Closing -= value; } } event EventHandler ICommunicationObject.Faulted { add { this.InnerChannel.Faulted += value; } remove { this.InnerChannel.Faulted -= value; } } event EventHandler ICommunicationObject.Opened { add { this.InnerChannel.Opened += value; } remove { this.InnerChannel.Opened -= value; } } event EventHandler ICommunicationObject.Opening { add { this.InnerChannel.Opening += value; } remove { this.InnerChannel.Opening -= value; } } IAsyncResult ICommunicationObject.BeginClose(AsyncCallback callback, object state) { return ((ICommunicationObject)this).BeginClose(GetChannelFactory().InternalCloseTimeout, callback, state); } IAsyncResult ICommunicationObject.BeginClose(TimeSpan timeout, AsyncCallback callback, object state) { return new ChainedAsyncResult(timeout, callback, state, BeginChannelClose, EndChannelClose, BeginFactoryClose, EndFactoryClose); } void ICommunicationObject.EndClose(IAsyncResult result) { ChainedAsyncResult.End(result); } IAsyncResult ICommunicationObject.BeginOpen(AsyncCallback callback, object state) { return ((ICommunicationObject)this).BeginOpen(GetChannelFactory().InternalOpenTimeout, callback, state); } IAsyncResult ICommunicationObject.BeginOpen(TimeSpan timeout, AsyncCallback callback, object state) { return new ChainedAsyncResult(timeout, callback, state, BeginFactoryOpen, EndFactoryOpen, BeginChannelOpen, EndChannelOpen); } void ICommunicationObject.EndOpen(IAsyncResult result) { ChainedAsyncResult.End(result); } //ChainedAsyncResult methods for opening and closing ChannelFactory<T> internal IAsyncResult BeginFactoryOpen(TimeSpan timeout, AsyncCallback callback, object state) { if (_useCachedFactory) { return new CompletedAsyncResult(callback, state); } else { return GetChannelFactory().BeginOpen(timeout, callback, state); } } internal void EndFactoryOpen(IAsyncResult result) { if (_useCachedFactory) { CompletedAsyncResult.End(result); } else { GetChannelFactory().EndOpen(result); } } internal IAsyncResult BeginChannelOpen(TimeSpan timeout, AsyncCallback callback, object state) { return this.InnerChannel.BeginOpen(timeout, callback, state); } internal void EndChannelOpen(IAsyncResult result) { this.InnerChannel.EndOpen(result); } internal IAsyncResult BeginFactoryClose(TimeSpan timeout, AsyncCallback callback, object state) { if (_useCachedFactory) { return new CompletedAsyncResult(callback, state); } else { return GetChannelFactory().BeginClose(timeout, callback, state); } } internal void EndFactoryClose(IAsyncResult result) { if (typeof(CompletedAsyncResult).IsAssignableFrom(result.GetType())) { CompletedAsyncResult.End(result); } else { GetChannelFactory().EndClose(result); } } internal IAsyncResult BeginChannelClose(TimeSpan timeout, AsyncCallback callback, object state) { if (_channel != null) { return this.InnerChannel.BeginClose(timeout, callback, state); } else { return new CompletedAsyncResult(callback, state); } } internal void EndChannelClose(IAsyncResult result) { if (typeof(CompletedAsyncResult).IsAssignableFrom(result.GetType())) { CompletedAsyncResult.End(result); } else { this.InnerChannel.EndClose(result); } } private ChannelFactory<TChannel> GetChannelFactory() { return _channelFactoryRef.ChannelFactory; } private void InitializeChannelFactoryRef() { Fx.Assert(_channelFactoryRef == null, "The channelFactory should have never been assigned"); Fx.Assert(_canShareFactory, "GetChannelFactoryFromCache can be called only when canShareFactory is true"); lock (s_staticLock) { ChannelFactoryRef<TChannel> factoryRef; if (s_factoryRefCache.TryGetValue(_endpointTrait, out factoryRef)) { if (factoryRef.ChannelFactory.State != CommunicationState.Opened) { // Remove the bad ChannelFactory. s_factoryRefCache.Remove(_endpointTrait); } else { _channelFactoryRef = factoryRef; _channelFactoryRef.AddRef(); _useCachedFactory = true; if (TD.ClientBaseChannelFactoryCacheHitIsEnabled()) { TD.ClientBaseChannelFactoryCacheHit(this); } return; } } } if (_channelFactoryRef == null) { // Creating the ChannelFactory at initial time to catch configuration exception earlier. _channelFactoryRef = CreateChannelFactoryRef(_endpointTrait); } } private static ChannelFactoryRef<TChannel> CreateChannelFactoryRef(EndpointTrait<TChannel> endpointTrait) { Fx.Assert(endpointTrait != null, "The endpointTrait should not be null when the factory can be shared."); ChannelFactory<TChannel> channelFactory = endpointTrait.CreateChannelFactory(); channelFactory.TraceOpenAndClose = false; return new ChannelFactoryRef<TChannel>(channelFactory); } // Once the channel is created, we can't disable caching. // This method can be called safely multiple times. // this.sharingFinalized is set the first time the method is called. // Subsequent calls are essentially no-ops. private void TryDisableSharing() { if (_sharingFinalized) return; lock (_finalizeLock) { if (_sharingFinalized) return; _canShareFactory = false; _sharingFinalized = true; if (_useCachedFactory) { ChannelFactoryRef<TChannel> pendingFactoryRef = _channelFactoryRef; _channelFactoryRef = CreateChannelFactoryRef(_endpointTrait); _useCachedFactory = false; lock (s_staticLock) { if (!pendingFactoryRef.Release()) { pendingFactoryRef = null; } } if (pendingFactoryRef != null) pendingFactoryRef.Abort(); } } // can be done outside the lock since the lines below do not access shared data. // also the use of this.sharingFinalized in the lines above ensures that tracing // happens only once and only when needed. if (TD.ClientBaseUsingLocalChannelFactoryIsEnabled()) { TD.ClientBaseUsingLocalChannelFactory(this); } } private void TryAddChannelFactoryToCache() { Fx.Assert(_canShareFactory, "This should be called only when this proxy can share ChannelFactory."); Fx.Assert(_channelFactoryRef.ChannelFactory.State == CommunicationState.Opened, "The ChannelFactory must be in Opened state for caching."); // Lock the cache and add the item to synchronize with lookup. lock (s_staticLock) { ChannelFactoryRef<TChannel> cfRef; if (!s_factoryRefCache.TryGetValue(_endpointTrait, out cfRef)) { // Increment the ref count before adding to the cache. _channelFactoryRef.AddRef(); s_factoryRefCache.Add(_endpointTrait, _channelFactoryRef); _useCachedFactory = true; if (TD.ClientBaseCachedChannelFactoryCountIsEnabled()) { TD.ClientBaseCachedChannelFactoryCount(s_factoryRefCache.Count, maxNumChannelFactories, this); } } } } // NOTE: This should be called inside ThisLock private void InvalidateCacheAndCreateChannel() { RemoveFactoryFromCache(); TryDisableSharing(); CreateChannelInternal(); } private void RemoveFactoryFromCache() { lock (s_staticLock) { ChannelFactoryRef<TChannel> factoryRef; if (s_factoryRefCache.TryGetValue(_endpointTrait, out factoryRef)) { if (object.ReferenceEquals(_channelFactoryRef, factoryRef)) { s_factoryRefCache.Remove(_endpointTrait); } } } } // WARNING: changes in the signature/name of the following delegates must be applied to the // ClientClassGenerator.cs as well, otherwise the ClientClassGenerator would generate wrong code. protected delegate IAsyncResult BeginOperationDelegate(object[] inValues, AsyncCallback asyncCallback, object state); protected delegate object[] EndOperationDelegate(IAsyncResult result); // WARNING: Any changes in the signature/name of the following type and its ctor must be applied to the // ClientClassGenerator.cs as well, otherwise the ClientClassGenerator would generate wrong code. protected class InvokeAsyncCompletedEventArgs : AsyncCompletedEventArgs { private object[] _results; internal InvokeAsyncCompletedEventArgs(object[] results, Exception error, bool cancelled, object userState) : base(error, cancelled, userState) { _results = results; } public object[] Results { get { return _results; } } } // WARNING: Any changes in the signature/name of the following method ctor must be applied to the // ClientClassGenerator.cs as well, otherwise the ClientClassGenerator would generate wrong code. protected void InvokeAsync(BeginOperationDelegate beginOperationDelegate, object[] inValues, EndOperationDelegate endOperationDelegate, SendOrPostCallback operationCompletedCallback, object userState) { if (beginOperationDelegate == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("beginOperationDelegate"); } if (endOperationDelegate == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("endOperationDelegate"); } AsyncOperation asyncOperation = AsyncOperationManager.CreateOperation(userState); AsyncOperationContext context = new AsyncOperationContext(asyncOperation, endOperationDelegate, operationCompletedCallback); Exception error = null; object[] results = null; IAsyncResult result = null; try { result = beginOperationDelegate(inValues, s_onAsyncCallCompleted, context); if (result.CompletedSynchronously) { results = endOperationDelegate(result); } } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } error = e; } if (error != null || result.CompletedSynchronously) /* result cannot be null if error == null */ { CompleteAsyncCall(context, results, error); } } private static void OnAsyncCallCompleted(IAsyncResult result) { if (result.CompletedSynchronously) { return; } AsyncOperationContext context = (AsyncOperationContext)result.AsyncState; Exception error = null; object[] results = null; try { results = context.EndDelegate(result); } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } error = e; } CompleteAsyncCall(context, results, error); } private static void CompleteAsyncCall(AsyncOperationContext context, object[] results, Exception error) { if (context.CompletionCallback != null) { InvokeAsyncCompletedEventArgs e = new InvokeAsyncCompletedEventArgs(results, error, false, context.AsyncOperation.UserSuppliedState); context.AsyncOperation.PostOperationCompleted(context.CompletionCallback, e); } else { context.AsyncOperation.OperationCompleted(); } } protected class AsyncOperationContext { private AsyncOperation _asyncOperation; private EndOperationDelegate _endDelegate; private SendOrPostCallback _completionCallback; internal AsyncOperationContext(AsyncOperation asyncOperation, EndOperationDelegate endDelegate, SendOrPostCallback completionCallback) { _asyncOperation = asyncOperation; _endDelegate = endDelegate; _completionCallback = completionCallback; } internal AsyncOperation AsyncOperation { get { return _asyncOperation; } } internal EndOperationDelegate EndDelegate { get { return _endDelegate; } } internal SendOrPostCallback CompletionCallback { get { return _completionCallback; } } } protected class ChannelBase<T> : IClientChannel, IOutputChannel, IRequestChannel, IChannelBaseProxy where T : class { private ServiceChannel _channel; private System.ServiceModel.Dispatcher.ImmutableClientRuntime _runtime; protected ChannelBase(ClientBase<T> client) { if (client.Endpoint.Address == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.SFxChannelFactoryEndpointAddressUri)); } ChannelFactory<T> cf = client.ChannelFactory; cf.EnsureOpened(); // to prevent the NullReferenceException that is thrown if the ChannelFactory is not open when cf.ServiceChannelFactory is accessed. _channel = cf.ServiceChannelFactory.CreateServiceChannel(client.Endpoint.Address, client.Endpoint.Address.Uri); _channel.InstanceContext = cf.CallbackInstance; _runtime = _channel.ClientRuntime.GetRuntime(); } protected IAsyncResult BeginInvoke(string methodName, object[] args, AsyncCallback callback, object state) { object[] inArgs = new object[args.Length + 2]; Array.Copy(args, inArgs, args.Length); inArgs[inArgs.Length - 2] = callback; inArgs[inArgs.Length - 1] = state; MethodCall methodCall = new MethodCall(inArgs); ProxyOperationRuntime op = GetOperationByName(methodName); object[] ins = op.MapAsyncBeginInputs(methodCall, out callback, out state); return _channel.BeginCall(op.Action, op.IsOneWay, op, ins, callback, state); } protected object EndInvoke(string methodName, object[] args, IAsyncResult result) { object[] inArgs = new object[args.Length + 1]; Array.Copy(args, inArgs, args.Length); inArgs[inArgs.Length - 1] = result; MethodCall methodCall = new MethodCall(inArgs); ProxyOperationRuntime op = GetOperationByName(methodName); object[] outs; op.MapAsyncEndInputs(methodCall, out result, out outs); object ret = _channel.EndCall(op.Action, outs, result); object[] retArgs = op.MapAsyncOutputs(methodCall, outs, ref ret); if (retArgs != null) { Fx.Assert(retArgs.Length == inArgs.Length, "retArgs.Length should be equal to inArgs.Length"); Array.Copy(retArgs, args, args.Length); } return ret; } private System.ServiceModel.Dispatcher.ProxyOperationRuntime GetOperationByName(string methodName) { ProxyOperationRuntime op = _runtime.GetOperationByName(methodName); if (op == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.Format(SR.SFxMethodNotSupported1, methodName))); } return op; } bool IClientChannel.AllowInitializationUI { get { return ((IClientChannel)_channel).AllowInitializationUI; } set { ((IClientChannel)_channel).AllowInitializationUI = value; } } bool IClientChannel.DidInteractiveInitialization { get { return ((IClientChannel)_channel).DidInteractiveInitialization; } } Uri IClientChannel.Via { get { return ((IClientChannel)_channel).Via; } } event EventHandler<UnknownMessageReceivedEventArgs> IClientChannel.UnknownMessageReceived { add { ((IClientChannel)_channel).UnknownMessageReceived += value; } remove { ((IClientChannel)_channel).UnknownMessageReceived -= value; } } void IClientChannel.DisplayInitializationUI() { ((IClientChannel)_channel).DisplayInitializationUI(); } IAsyncResult IClientChannel.BeginDisplayInitializationUI(AsyncCallback callback, object state) { return ((IClientChannel)_channel).BeginDisplayInitializationUI(callback, state); } void IClientChannel.EndDisplayInitializationUI(IAsyncResult result) { ((IClientChannel)_channel).EndDisplayInitializationUI(result); } bool IContextChannel.AllowOutputBatching { get { return ((IContextChannel)_channel).AllowOutputBatching; } set { ((IContextChannel)_channel).AllowOutputBatching = value; } } IInputSession IContextChannel.InputSession { get { return ((IContextChannel)_channel).InputSession; } } EndpointAddress IContextChannel.LocalAddress { get { return ((IContextChannel)_channel).LocalAddress; } } TimeSpan IContextChannel.OperationTimeout { get { return ((IContextChannel)_channel).OperationTimeout; } set { ((IContextChannel)_channel).OperationTimeout = value; } } IOutputSession IContextChannel.OutputSession { get { return ((IContextChannel)_channel).OutputSession; } } EndpointAddress IContextChannel.RemoteAddress { get { return ((IContextChannel)_channel).RemoteAddress; } } string IContextChannel.SessionId { get { return ((IContextChannel)_channel).SessionId; } } TProperty IChannel.GetProperty<TProperty>() { return ((IChannel)_channel).GetProperty<TProperty>(); } CommunicationState ICommunicationObject.State { get { return ((ICommunicationObject)_channel).State; } } event EventHandler ICommunicationObject.Closed { add { ((ICommunicationObject)_channel).Closed += value; } remove { ((ICommunicationObject)_channel).Closed -= value; } } event EventHandler ICommunicationObject.Closing { add { ((ICommunicationObject)_channel).Closing += value; } remove { ((ICommunicationObject)_channel).Closing -= value; } } event EventHandler ICommunicationObject.Faulted { add { ((ICommunicationObject)_channel).Faulted += value; } remove { ((ICommunicationObject)_channel).Faulted -= value; } } event EventHandler ICommunicationObject.Opened { add { ((ICommunicationObject)_channel).Opened += value; } remove { ((ICommunicationObject)_channel).Opened -= value; } } event EventHandler ICommunicationObject.Opening { add { ((ICommunicationObject)_channel).Opening += value; } remove { ((ICommunicationObject)_channel).Opening -= value; } } void ICommunicationObject.Abort() { ((ICommunicationObject)_channel).Abort(); } void ICommunicationObject.Close() { ((ICommunicationObject)_channel).Close(); } void ICommunicationObject.Close(TimeSpan timeout) { ((ICommunicationObject)_channel).Close(timeout); } IAsyncResult ICommunicationObject.BeginClose(AsyncCallback callback, object state) { return ((ICommunicationObject)_channel).BeginClose(callback, state); } IAsyncResult ICommunicationObject.BeginClose(TimeSpan timeout, AsyncCallback callback, object state) { return ((ICommunicationObject)_channel).BeginClose(timeout, callback, state); } void ICommunicationObject.EndClose(IAsyncResult result) { ((ICommunicationObject)_channel).EndClose(result); } void ICommunicationObject.Open() { ((ICommunicationObject)_channel).Open(); } void ICommunicationObject.Open(TimeSpan timeout) { ((ICommunicationObject)_channel).Open(timeout); } IAsyncResult ICommunicationObject.BeginOpen(AsyncCallback callback, object state) { return ((ICommunicationObject)_channel).BeginOpen(callback, state); } IAsyncResult ICommunicationObject.BeginOpen(TimeSpan timeout, AsyncCallback callback, object state) { return ((ICommunicationObject)_channel).BeginOpen(timeout, callback, state); } void ICommunicationObject.EndOpen(IAsyncResult result) { ((ICommunicationObject)_channel).EndOpen(result); } IExtensionCollection<IContextChannel> IExtensibleObject<IContextChannel>.Extensions { get { return ((IExtensibleObject<IContextChannel>)_channel).Extensions; } } void IDisposable.Dispose() { ((IDisposable)_channel).Dispose(); } Uri IOutputChannel.Via { get { return ((IOutputChannel)_channel).Via; } } EndpointAddress IOutputChannel.RemoteAddress { get { return ((IOutputChannel)_channel).RemoteAddress; } } void IOutputChannel.Send(Message message) { ((IOutputChannel)_channel).Send(message); } void IOutputChannel.Send(Message message, TimeSpan timeout) { ((IOutputChannel)_channel).Send(message, timeout); } IAsyncResult IOutputChannel.BeginSend(Message message, AsyncCallback callback, object state) { return ((IOutputChannel)_channel).BeginSend(message, callback, state); } IAsyncResult IOutputChannel.BeginSend(Message message, TimeSpan timeout, AsyncCallback callback, object state) { return ((IOutputChannel)_channel).BeginSend(message, timeout, callback, state); } void IOutputChannel.EndSend(IAsyncResult result) { ((IOutputChannel)_channel).EndSend(result); } Uri IRequestChannel.Via { get { return ((IRequestChannel)_channel).Via; } } EndpointAddress IRequestChannel.RemoteAddress { get { return ((IRequestChannel)_channel).RemoteAddress; } } Message IRequestChannel.Request(Message message) { return ((IRequestChannel)_channel).Request(message); } Message IRequestChannel.Request(Message message, TimeSpan timeout) { return ((IRequestChannel)_channel).Request(message, timeout); } IAsyncResult IRequestChannel.BeginRequest(Message message, AsyncCallback callback, object state) { return ((IRequestChannel)_channel).BeginRequest(message, callback, state); } IAsyncResult IRequestChannel.BeginRequest(Message message, TimeSpan timeout, AsyncCallback callback, object state) { return ((IRequestChannel)_channel).BeginRequest(message, timeout, callback, state); } Message IRequestChannel.EndRequest(IAsyncResult result) { return ((IRequestChannel)_channel).EndRequest(result); } ServiceChannel IChannelBaseProxy.GetServiceChannel() { return _channel; } } } }
using System; using System.Drawing; using System.Drawing.Imaging; using System.Linq; using System.Windows.Forms; using AForge.Imaging; using Image = System.Drawing.Image; using System.Runtime.InteropServices; using System.Threading; using AForge.Imaging.Filters; using System.IO; namespace ImageBaseTest { public static class ImageTestUtil { #region Consts private const int MOUSEEVENTF_LEFTDOWN = 0x02; private const int MOUSEEVENTF_LEFTUP = 0x04; private const int MOUSEEVENTF_RIGHTDOWN = 0x08; private const int MOUSEEVENTF_RIGHTUP = 0x10; private const int MOUSEEVENTF_MOVE = 0x01; #endregion #region COM Methods [DllImport("user32.dll")] public static extern void mouse_event(int dwFlags, int dx, int dy, int cButtons, int dwExtraInfo); #endregion #region Members private static Size? _screenSearchSize; private static Point? _positionSearch; #endregion #region Properties public static string DebugFolderPath { get; set; } #endregion #region Public methods public static Point? GetImagePosition(string imagePath, int waitTimeoutInSeconds = 30, bool isCancelSearchOptimization = false, float similarityThreshold = 0.92f) { Size dummy; return GetImagePosition(out dummy, imagePath, waitTimeoutInSeconds, isCancelSearchOptimization, similarityThreshold); } public static void Click(string imagePath, bool isDoubleClick = false, Size? imageClickPointOffset = null, bool isRightClick = false, int waitTimeoutInSeconds = 60, bool isCancelSearchOptimization = true, Size? dragPosition = null, float similarityThreshold = 0.92f) { Size imageCenterPoint; var position = GetImagePosition(out imageCenterPoint, imagePath, waitTimeoutInSeconds, isCancelSearchOptimization, similarityThreshold); if (imageClickPointOffset.HasValue) imageCenterPoint = imageClickPointOffset.Value; if (position.HasValue) { Cursor.Position = Point.Add(position.Value, imageCenterPoint); mouse_event(isRightClick ? MOUSEEVENTF_RIGHTDOWN : MOUSEEVENTF_LEFTDOWN, position.Value.X, position.Value.Y, 0, 0); if (dragPosition.HasValue) MoveDragPosition(position.Value, dragPosition.Value); Thread.Sleep(10); mouse_event(isRightClick ? MOUSEEVENTF_RIGHTUP : MOUSEEVENTF_LEFTUP, position.Value.X, position.Value.Y, 0, 0); if (isDoubleClick) { mouse_event(MOUSEEVENTF_LEFTDOWN, position.Value.X, position.Value.Y, 0, 0); Thread.Sleep(10); mouse_event(MOUSEEVENTF_LEFTUP, position.Value.X, position.Value.Y, 0, 0); } } else throw new Exception(string.Format("Image was not found:{0}", imagePath)); } private static void MoveDragPosition(Point currentPosision, Size dragPositionOffset) { Cursor.Position = Point.Add(currentPosision, dragPositionOffset); } public static bool Exists(string imagePath, int waitTimeoutInSeconds = 30, bool isCancelSearchOptimization = false, float similarityThreshold = 0.92f) { return GetImagePosition(imagePath, waitTimeoutInSeconds, isCancelSearchOptimization, similarityThreshold ).HasValue; } public static void Type(string value) { SendKeys.SendWait(value); } public static void SetScreenSearchSize(Size? screenSize, Point? position) { _screenSearchSize = screenSize; _positionSearch = position; } public static Size GetScreenSize() { return Screen.PrimaryScreen.Bounds.Size; } #endregion #region Private Methods private static Point? GetImagePosition(out Size imageCenterPoint, string imagePath, int waitTimeoutInSeconds, bool isCancelSearchOptimization, float similarityThreshold) { var imageTofind = Image.FromFile(imagePath) as Bitmap; if (imageTofind == null) throw new BadImageFormatException("Image {0} cannot convert to Bitmap"); imageCenterPoint = new Size(imageTofind.Width / 2, imageTofind.Height / 2); var sourceImage = GetScreenImage(); return GetImagePosition(sourceImage, imageTofind, waitTimeoutInSeconds, isCancelSearchOptimization, similarityThreshold); } private static string HandleDebugMode(Bitmap imageTofind, Bitmap sourceImage, bool isResize = false, string debugFolder = null) { if (!string.IsNullOrWhiteSpace(DebugFolderPath)) { var folderName = DateTime.Now.ToString().Replace("/", "-").Replace(" ", string.Empty).Replace(":", "_"); string debugDir; if (string.IsNullOrWhiteSpace(debugFolder)) debugDir = Directory.CreateDirectory(Path.Combine(DebugFolderPath, folderName)).FullName; else debugDir = debugFolder; imageTofind.Save(Path.Combine(debugDir, isResize ? "resize_imageTofind.png" : "imageTofind.png")); sourceImage.Save(Path.Combine(debugDir, isResize ? "resize_sourceImage.png" : "sourceImage.png")); return debugDir; } return null; } private static void HandleDebugMode(string debugFolder, Rectangle rectangle, Bitmap sourceImage) { if (!string.IsNullOrWhiteSpace(DebugFolderPath)) { var data = sourceImage.LockBits( new Rectangle(0, 0, sourceImage.Width, sourceImage.Height), ImageLockMode.ReadWrite, sourceImage.PixelFormat); Drawing.Rectangle(data, rectangle, Color.Red); sourceImage.Save(Path.Combine(debugFolder, string.Format("clickImage_{0}x{1}.png", rectangle.Location.X, rectangle.Location.Y))); } } private static void HandleDebugMode(string debugFolder) { if (!string.IsNullOrWhiteSpace(DebugFolderPath)) { File.Create(Path.Combine(debugFolder, "ImageNotFound.txt")); } } private static Point? GetImagePosition(Bitmap sourceImage, Bitmap imageTofind, int waitTimeoutInSeconds, bool isCancelSearchOptimization, float similarityThreshold) { var tm = new ExhaustiveTemplateMatching(similarityThreshold); var timeoutDate = DateTime.Now.AddSeconds(waitTimeoutInSeconds); var result = GetImagePosition(sourceImage, imageTofind, tm, isCancelSearchOptimization); while (!result.HasValue && DateTime.Now < timeoutDate) { sourceImage = GetScreenImage(); result = GetImagePosition(sourceImage, imageTofind, tm, isCancelSearchOptimization); } return result; } private static Point? GetImagePosition(Bitmap sourceImage, Bitmap imageTofind, ExhaustiveTemplateMatching tm, bool isCancelSearchOptimization) { string debugFolder = null; Point? result; if (!isCancelSearchOptimization) { result = SearchOptimazeImage(out debugFolder, sourceImage, imageTofind, tm); if (result.HasValue) return result; } debugFolder = HandleDebugMode(imageTofind, sourceImage, debugFolder: debugFolder); var matchings = tm.ProcessImage( sourceImage, imageTofind); if (matchings.Any()) { var rectangle = matchings.First().Rectangle; result = rectangle.Location; if (_positionSearch.HasValue) { if (_positionSearch.Value.X > 0) result = new Point(result.Value.X + _positionSearch.Value.X, result.Value.Y); if (_positionSearch.Value.Y > 0) result = new Point(result.Value.X, result.Value.Y + _positionSearch.Value.Y); } HandleDebugMode(debugFolder, rectangle, sourceImage); } else { result = null; HandleDebugMode(debugFolder); } return result; } private static Point? SearchOptimazeImage(out string debugFolder, Bitmap sourceImage, Bitmap imageTofind, ExhaustiveTemplateMatching tm) { const int divisor = 2; var resizeSourceImage = new ResizeNearestNeighbor(sourceImage.Width / divisor, sourceImage.Height / divisor).Apply(sourceImage); var resizeImageTofind = new ResizeNearestNeighbor(imageTofind.Width / divisor, imageTofind.Height / divisor).Apply(imageTofind); var matchings = tm.ProcessImage(resizeSourceImage, resizeImageTofind); debugFolder = HandleDebugMode(resizeImageTofind, resizeSourceImage, true); if (matchings.Any()) { var rectangle = matchings.First().Rectangle; var result = new Point(rectangle.Location.X * divisor, rectangle.Location.Y * divisor); HandleDebugMode(debugFolder, rectangle, resizeSourceImage); return result; } return null; } private static Bitmap GetScreenImage() { var image = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height, PixelFormat.Format24bppRgb); var gfx = Graphics.FromImage(image); gfx.CopyFromScreen(0, 0 , Screen.PrimaryScreen.Bounds.X, Screen.PrimaryScreen.Bounds.Y, Screen.PrimaryScreen.Bounds.Size, CopyPixelOperation.SourceCopy); CropImage(ref image); return image; } private static void CropImage(ref Bitmap src) { if (_screenSearchSize.HasValue) { var screenWidth = Screen.PrimaryScreen.Bounds.Width; var screenHeight = Screen.PrimaryScreen.Bounds.Height; var screenX = 0; var screenY = 0; if (_screenSearchSize.Value.Width > 0) { screenWidth = _screenSearchSize.Value.Width; } if (_screenSearchSize.Value.Height > 0) { screenHeight = _screenSearchSize.Value.Height; } if (_positionSearch.HasValue && _positionSearch.Value.X > 0) { screenX = _positionSearch.Value.X; } if (_positionSearch.HasValue && _positionSearch.Value.Y > 0) { screenY = _positionSearch.Value.Y; } var cropRect = new Rectangle(screenX, screenY, Screen.PrimaryScreen.Bounds.Width - screenX, Screen.PrimaryScreen.Bounds.Height - screenY); var target = new Bitmap(cropRect.Width, cropRect.Height, PixelFormat.Format24bppRgb); using (Graphics g = Graphics.FromImage(target)) { g.DrawImage(src, new Rectangle(0, 0, target.Width, target.Height), cropRect, GraphicsUnit.Pixel); } src = target; } } #endregion } }
/* * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; namespace Amazon.OpsWorks.Model { /// <summary> /// <para>Describes a command.</para> /// </summary> public class Command { private string commandId; private string instanceId; private string deploymentId; private string createdAt; private string acknowledgedAt; private string completedAt; private string status; private int? exitCode; private string logUrl; private string type; /// <summary> /// The command ID. /// /// </summary> public string CommandId { get { return this.commandId; } set { this.commandId = value; } } /// <summary> /// Sets the CommandId property /// </summary> /// <param name="commandId">The value to set for the CommandId property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public Command WithCommandId(string commandId) { this.commandId = commandId; return this; } // Check to see if CommandId property is set internal bool IsSetCommandId() { return this.commandId != null; } /// <summary> /// The ID of the instance where the command was executed. /// /// </summary> public string InstanceId { get { return this.instanceId; } set { this.instanceId = value; } } /// <summary> /// Sets the InstanceId property /// </summary> /// <param name="instanceId">The value to set for the InstanceId property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public Command WithInstanceId(string instanceId) { this.instanceId = instanceId; return this; } // Check to see if InstanceId property is set internal bool IsSetInstanceId() { return this.instanceId != null; } /// <summary> /// The command deployment ID. /// /// </summary> public string DeploymentId { get { return this.deploymentId; } set { this.deploymentId = value; } } /// <summary> /// Sets the DeploymentId property /// </summary> /// <param name="deploymentId">The value to set for the DeploymentId property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public Command WithDeploymentId(string deploymentId) { this.deploymentId = deploymentId; return this; } // Check to see if DeploymentId property is set internal bool IsSetDeploymentId() { return this.deploymentId != null; } /// <summary> /// Date and time when the command was run. /// /// </summary> public string CreatedAt { get { return this.createdAt; } set { this.createdAt = value; } } /// <summary> /// Sets the CreatedAt property /// </summary> /// <param name="createdAt">The value to set for the CreatedAt property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public Command WithCreatedAt(string createdAt) { this.createdAt = createdAt; return this; } // Check to see if CreatedAt property is set internal bool IsSetCreatedAt() { return this.createdAt != null; } /// <summary> /// Date and time when the command was acknowledged. /// /// </summary> public string AcknowledgedAt { get { return this.acknowledgedAt; } set { this.acknowledgedAt = value; } } /// <summary> /// Sets the AcknowledgedAt property /// </summary> /// <param name="acknowledgedAt">The value to set for the AcknowledgedAt property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public Command WithAcknowledgedAt(string acknowledgedAt) { this.acknowledgedAt = acknowledgedAt; return this; } // Check to see if AcknowledgedAt property is set internal bool IsSetAcknowledgedAt() { return this.acknowledgedAt != null; } /// <summary> /// Date when the command completed. /// /// </summary> public string CompletedAt { get { return this.completedAt; } set { this.completedAt = value; } } /// <summary> /// Sets the CompletedAt property /// </summary> /// <param name="completedAt">The value to set for the CompletedAt property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public Command WithCompletedAt(string completedAt) { this.completedAt = completedAt; return this; } // Check to see if CompletedAt property is set internal bool IsSetCompletedAt() { return this.completedAt != null; } /// <summary> /// The command status: <ul> <li>failed</li> <li>successful</li> <li>skipped</li> <li>pending</li> </ul> /// /// </summary> public string Status { get { return this.status; } set { this.status = value; } } /// <summary> /// Sets the Status property /// </summary> /// <param name="status">The value to set for the Status property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public Command WithStatus(string status) { this.status = status; return this; } // Check to see if Status property is set internal bool IsSetStatus() { return this.status != null; } /// <summary> /// The command exit code. /// /// </summary> public int ExitCode { get { return this.exitCode ?? default(int); } set { this.exitCode = value; } } /// <summary> /// Sets the ExitCode property /// </summary> /// <param name="exitCode">The value to set for the ExitCode property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public Command WithExitCode(int exitCode) { this.exitCode = exitCode; return this; } // Check to see if ExitCode property is set internal bool IsSetExitCode() { return this.exitCode.HasValue; } /// <summary> /// The URL of the command log. /// /// </summary> public string LogUrl { get { return this.logUrl; } set { this.logUrl = value; } } /// <summary> /// Sets the LogUrl property /// </summary> /// <param name="logUrl">The value to set for the LogUrl property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public Command WithLogUrl(string logUrl) { this.logUrl = logUrl; return this; } // Check to see if LogUrl property is set internal bool IsSetLogUrl() { return this.logUrl != null; } /// <summary> /// The command type: <ul> <li>deploy</li> <li>rollback</li> <li>start</li> <li>stop</li> <li>restart</li> <li>undeploy</li> /// <li>update_dependencies</li> <li>install_dependencies</li> <li>update_custom_cookbooks</li> <li>execute_recipes</li> </ul> /// /// </summary> public string Type { get { return this.type; } set { this.type = value; } } /// <summary> /// Sets the Type property /// </summary> /// <param name="type">The value to set for the Type property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public Command WithType(string type) { this.type = type; return this; } // Check to see if Type property is set internal bool IsSetType() { return this.type != null; } } }
using System; using RestSharp; using System.Text; using System.Collections.Generic; using Gx.Conclusion; using Gx.Rs.Api.Util; using Gx.Links; using System.Net; using System.Linq; using Newtonsoft.Json; using Gx.Records; using Gx.Common; using Gedcomx.Model; using Gedcomx.Support; using System.Diagnostics; namespace Gx.Rs.Api { /// <summary> /// This is the base class for all state instances. /// </summary> public abstract class GedcomxApplicationState : HypermediaEnabledData { /// <summary> /// The factory responsible for creating new state instances from REST API response data. /// </summary> protected internal readonly StateFactory stateFactory; /// <summary> /// The default link loader for reading links from <see cref="Gx.Gedcomx"/> instances. Also see <seealso cref="Gx.Rs.Api.Util.EmbeddedLinkLoader.DEFAULT_EMBEDDED_LINK_RELS"/> for types of links that will be loaded. /// </summary> protected static readonly EmbeddedLinkLoader DEFAULT_EMBEDDED_LINK_LOADER = new EmbeddedLinkLoader(); private readonly String gzipSuffix = "-gzip"; /// <summary> /// Gets or sets the main REST API client to use with all API calls. /// </summary> /// <value> /// The REST API client to use with all API calls. /// </value> public IFilterableRestClient Client { get; protected set; } /// <summary> /// Gets or sets the current access token (the OAuth2 token), see https://familysearch.org/developers/docs/api/authentication/Access_Token_resource. /// </summary> /// <value> /// The current access token (the OAuth2 token), see https://familysearch.org/developers/docs/api/authentication/Access_Token_resource. /// </value> public String CurrentAccessToken { get; set; } /// <summary> /// The link factory for managing RFC 5988 compliant hypermedia links. /// </summary> protected Tavis.LinkFactory linkFactory; /// <summary> /// The parser for extracting RFC 5988 compliant hypermedia links from a web response header. /// </summary> protected Tavis.LinkHeaderParser linkHeaderParser; /// <summary> /// Gets a value indicating whether this instance is authenticated. /// </summary> /// <value> /// <c>true</c> if this instance is authenticated; otherwise, <c>false</c>. /// </value> public bool IsAuthenticated { get { return CurrentAccessToken != null; } } /// <summary> /// Gets or sets the REST API request. /// </summary> /// <value> /// The REST API request. /// </value> public IRestRequest Request { get; protected set; } /// <summary> /// Gets or sets the REST API response. /// </summary> /// <value> /// The REST API response. /// </value> public IRestResponse Response { get; protected set; } /// <summary> /// Gets or sets the last embedded request (from a previous call to GedcomxApplicationState{T}.Embed{T}()). /// </summary> /// <value> /// The last embedded request (from a previous call to GedcomxApplicationState{T}.Embed{T}()). /// </value> public IRestRequest LastEmbeddedRequest { get; set; } /// <summary> /// Gets or sets the last embedded response (from a previous call to GedcomxApplicationState{T}.Embed{T}()). /// </summary> /// <value> /// The last embedded response (from a previous call to GedcomxApplicationState{T}.Embed{T}()). /// </value> public IRestResponse LastEmbeddedResponse { get; set; } /// <summary> /// Gets the entity tag of the entity represented by this instance. /// </summary> /// <value> /// The entity tag of the entity represented by this instance. /// </value> public string ETag { get { var result = this.Response != null ? this.Response.Headers.Get("ETag").Select(x => x.Value.ToString()).FirstOrDefault() : null; if (result != null && result.IndexOf(gzipSuffix) != -1) { result = result.Replace(gzipSuffix, String.Empty); } return result; } } /// <summary> /// Gets the last modified date of the entity represented by this instance. /// </summary> /// <value> /// The last modified date of the entity represented by this instance. /// </value> public DateTime? LastModified { get { return this.Response != null ? this.Response.Headers.Get("Last-Modified").Select(x => (DateTime?)DateTime.Parse(x.Value.ToString())).FirstOrDefault() : null; } } /// <summary> /// Gets the link loader for reading links from <see cref="Gx.Gedcomx"/> instances. Also see <seealso cref="Gx.Rs.Api.Util.EmbeddedLinkLoader.DEFAULT_EMBEDDED_LINK_RELS"/> for types of links that will be loaded. /// </summary> /// <value> /// This always returns the default embedded link loader. /// </value> protected EmbeddedLinkLoader EmbeddedLinkLoader { get { return DEFAULT_EMBEDDED_LINK_LOADER; } } /// <summary> /// Gets the main data element represented by this state instance. /// </summary> /// <value> /// The main data element represented by this state instance. /// </value> protected abstract ISupportsLinks MainDataElement { get; } /// <summary> /// Initializes a new instance of the <see cref="GedcomxApplicationState{T}"/> class. /// </summary> protected GedcomxApplicationState(IRestRequest request, IRestResponse response, IFilterableRestClient client, String accessToken, StateFactory stateFactory) { linkFactory = new Tavis.LinkFactory(); linkHeaderParser = new Tavis.LinkHeaderParser(linkFactory); this.Request = request; this.Response = response; this.Client = client; this.CurrentAccessToken = accessToken; this.stateFactory = stateFactory; } /// <summary> /// Executes the specified link and embeds the response in the specified Gedcomx entity. /// </summary> /// <typeparam name="T">The type of the expected response. The raw response data will be parsed (from JSON or XML) and casted to this type.</typeparam> /// <param name="link">The link to execute.</param> /// <param name="entity">The entity which will embed the reponse data.</param> /// <param name="options">The options to apply before executing the REST API call.</param> /// <exception cref="GedcomxApplicationException">Thrown when the server responds with HTTP status code >= 500 and &lt; 600.</exception> protected void Embed<T>(Link link, Gedcomx entity, params IStateTransitionOption[] options) where T : Gedcomx { if (link.Href != null) { LastEmbeddedRequest = CreateRequestForEmbeddedResource(link.Rel).Build(link.Href, Method.GET); LastEmbeddedResponse = Invoke(LastEmbeddedRequest, options); if (LastEmbeddedResponse.StatusCode == HttpStatusCode.OK) { entity.Embed(LastEmbeddedResponse.ToIRestResponse<T>().Data); } else if (LastEmbeddedResponse.HasServerError()) { throw new GedcomxApplicationException(String.Format("Unable to load embedded resources: server says \"{0}\" at {1}.", LastEmbeddedResponse.StatusDescription, LastEmbeddedRequest.Resource), LastEmbeddedResponse); } else { //todo: log a warning? throw an error? } } } /// <summary> /// Creates a REST API request (with appropriate authentication headers). /// </summary> /// <param name="rel">This parameter is currently unused.</param> /// <returns>A REST API requeset (with appropriate authentication headers).</returns> protected virtual IRestRequest CreateRequestForEmbeddedResource(String rel) { return CreateAuthenticatedGedcomxRequest(); } /// <summary> /// Applies the specified options before calling IFilterableRestClient.Handle() which applies any filters before executing the request. /// </summary> /// <param name="request">The REST API request.</param> /// <param name="options">The options to applying before the request is handled.</param> /// <returns>The REST API response after being handled.</returns> protected internal IRestResponse Invoke(IRestRequest request, params IStateTransitionOption[] options) { IRestResponse result; foreach (IStateTransitionOption option in options) { option.Apply(request); } result = this.Client.Handle(request); Debug.WriteLine(string.Format("\nRequest: {0}", request.Resource)); foreach (var header in request.Parameters) { Debug.WriteLine(string.Format("{0} {1}", header.Name, header.Value)); } Debug.WriteLine(string.Format("\nResponse Status: {0} {1}", result.StatusCode, result.StatusDescription)); Debug.WriteLine(string.Format("\nResponse Content: {0}", result.Content)); return result; } /// <summary> /// Clones the current state instance. /// </summary> /// <param name="request">The REST API request used to create this state instance.</param> /// <param name="response">The REST API response used to create this state instance.</param> /// <param name="client">The REST API client used to create this state instance.</param> /// <returns>A cloned instance of the current state instance.</returns> protected abstract GedcomxApplicationState Clone(IRestRequest request, IRestResponse response, IFilterableRestClient client); /// <summary> /// Creates a REST API request with authentication. /// </summary> /// <returns>The REST API request with authentication.</returns> /// <remarks>This also sets the accept and content type headers.</remarks> protected internal IRestRequest CreateAuthenticatedGedcomxRequest() { return CreateAuthenticatedRequest().Accept(MediaTypes.GEDCOMX_JSON_MEDIA_TYPE).ContentType(MediaTypes.GEDCOMX_JSON_MEDIA_TYPE); } /// <summary> /// Creates a REST API request with authentication. /// </summary> /// <returns>The REST API request with authentication.</returns> protected IRestRequest CreateAuthenticatedRequest() { IRestRequest request = CreateRequest(); if (this.CurrentAccessToken != null) { request = request.AddHeader("Authorization", "Bearer " + this.CurrentAccessToken); } return request; } /// <summary> /// Creates a basic REST API request. /// </summary> /// <returns>A basic REST API request</returns> protected IRestRequest CreateRequest() { return new RedirectableRestRequest(); } /// <summary> /// Extracts embedded links from the specified entity, calls each one, and embeds the response into the specified entity. /// </summary> /// <typeparam name="T">The type of the expected response. The raw response data will be parsed (from JSON or XML) and casted to this type.</typeparam> /// <param name="entity">The entity with links and which shall have the data loaded into.</param> /// <param name="options">The options to apply before handling the REST API requests.</param> protected void IncludeEmbeddedResources<T>(Gedcomx entity, params IStateTransitionOption[] options) where T : Gedcomx { Embed<T>(EmbeddedLinkLoader.LoadEmbeddedLinks(entity), entity, options); } /// <summary> /// Executes the specified links and embeds the response into the specified entity. /// </summary> /// <typeparam name="T">The type of the expected response. The raw response data will be parsed (from JSON or XML) and casted to this type.</typeparam> /// <param name="links">The links to call.</param> /// <param name="entity">The entity which shall have the data loaded into.</param> /// <param name="options">The options to apply before handling the REST API requests.</param> protected void Embed<T>(IEnumerable<Link> links, Gedcomx entity, params IStateTransitionOption[] options) where T : Gedcomx { foreach (Link link in links) { Embed<T>(link, entity, options); } } /// <summary> /// Gets the URI of the REST API request associated to this state instance. /// </summary> /// <returns>The URI of the REST API request associated to this state instance.</returns> public string GetUri() { return this.Client.BaseUrl + this.Request.Resource; } /// <summary> /// Determines whether this instance has error (server [code >= 500 and &lt; 600] or client [code >= 400 and &lt; 500]). /// </summary> /// <returns>True if a server or client error exists; otherwise, false.</returns> public bool HasError() { return this.Response.HasClientError() || this.Response.HasServerError(); } /// <summary> /// Determines whether the current REST API response has the specified status. /// </summary> /// <param name="status">The status to evaluate.</param> /// <returns>True if the current REST API response has the specified status; otherwise, false.</returns> public bool HasStatus(HttpStatusCode status) { return this.Response.StatusCode == status; } /// <summary> /// Returns the current state instance if there are no errors in the current REST API response; otherwise, it throws an exception with the response details. /// </summary> /// <returns> /// A <see cref="GedcomxApplicationState{T}"/> instance containing the REST API response or throws an exception with the response details. /// </returns> /// <exception cref="GedcomxApplicationException">Thrown if <see cref="HasError()" /> returns true.</exception> public virtual GedcomxApplicationState IfSuccessful() { if (HasError()) { throw new GedcomxApplicationException(String.Format("Unsuccessful {0} to {1}", this.Request.Method, GetUri()), this.Response); } return this; } /// <summary> /// Executes a HEAD verb request against the current REST API request and returns a state instance with the response. /// </summary> /// <param name="options">The options to apply before executing the REST API call.</param> /// <returns>A <see cref="GedcomxApplicationState{T}"/> instance containing the REST API response.</returns> public virtual GedcomxApplicationState Head(params IStateTransitionOption[] options) { IRestRequest request = CreateAuthenticatedRequest(); Parameter accept = this.Request.GetHeaders().Get("Accept").FirstOrDefault(); if (accept != null) { request.Accept(accept.Value as string); } request.Build(GetSelfUri(), Method.HEAD); return Clone(request, Invoke(request, options), this.Client); } /// <summary> /// Executes an OPTIONS verb request against the current REST API request and returns a state instance with the response. /// </summary> /// <param name="options">The options to apply before executing the REST API call.</param> /// <returns>A <see cref="GedcomxApplicationState{T}"/> instance containing the REST API response.</returns> public virtual GedcomxApplicationState Options(params IStateTransitionOption[] options) { IRestRequest request = CreateAuthenticatedRequest(); Parameter accept = this.Request.GetHeaders().Get("Accept").FirstOrDefault(); if (accept != null) { request.Accept(accept.Value as string); } request.Build(GetSelfUri(), Method.OPTIONS); return Clone(request, Invoke(request, options), this.Client); } /// <summary> /// Executes a GET verb request against the current REST API request and returns a state instance with the response. /// </summary> /// <param name="options">The options to apply before executing the REST API call.</param> /// <returns>A <see cref="GedcomxApplicationState{T}"/> instance containing the REST API response.</returns> public virtual GedcomxApplicationState Get(params IStateTransitionOption[] options) { IRestRequest request = CreateAuthenticatedRequest(); Parameter accept = this.Request.GetHeaders().Get("Accept").FirstOrDefault(); if (accept != null) { request.Accept(accept.Value as string); } request.Build(GetSelfUri(), Method.GET); IRestResponse response = Invoke(request, options); return Clone(request, response, this.Client); } /// <summary> /// Executes an DELETE verb request against the current REST API request and returns a state instance with the response. /// </summary> /// <param name="options">The options to apply before executing the REST API call.</param> /// <returns>A <see cref="GedcomxApplicationState{T}"/> instance containing the REST API response.</returns> public virtual GedcomxApplicationState Delete(params IStateTransitionOption[] options) { IRestRequest request = CreateAuthenticatedRequest(); Parameter accept = this.Request.GetHeaders().Get("Accept").FirstOrDefault(); if (accept != null) { request.Accept(accept.Value as string); } request.Build(GetSelfUri(), Method.DELETE); return Clone(request, Invoke(request, options), this.Client); } /// <summary> /// Executes a PUT verb request against the current REST API request and returns a state instance with the response. /// </summary> /// <param name="entity">The entity to be used as the body of the REST API request. This is the entity to be PUT.</param> /// <param name="options">The options to apply before executing the REST API call.</param> /// <returns>A <see cref="GedcomxApplicationState{T}"/> instance containing the REST API response.</returns> public virtual GedcomxApplicationState Put(object entity, params IStateTransitionOption[] options) { IRestRequest request = CreateAuthenticatedRequest(); Parameter accept = this.Request.GetHeaders().Get("Accept").FirstOrDefault(); Parameter contentType = this.Request.GetHeaders().Get("Content-Type").FirstOrDefault(); if (accept != null) { request.Accept(accept.Value as string); } if (contentType != null) { request.ContentType(contentType.Value as string); } request.SetEntity(entity).Build(GetSelfUri(), Method.PUT); return Clone(request, Invoke(request, options), this.Client); } /// <summary> /// Executes a POST verb request against the current REST API request and returns a state instance with the response. /// </summary> /// <param name="entity">The entity to be used as the body of the REST API request. This is the entity to be POST.</param> /// <param name="options">The options to apply before executing the REST API call.</param> /// <returns>A <see cref="GedcomxApplicationState{T}"/> instance containing the REST API response.</returns> public virtual GedcomxApplicationState Post(object entity, params IStateTransitionOption[] options) { IRestRequest request = CreateAuthenticatedRequest(); Parameter accept = this.Request.GetHeaders().Get("Accept").FirstOrDefault(); Parameter contentType = this.Request.GetHeaders().Get("Content-Type").FirstOrDefault(); if (accept != null) { request.Accept(accept.Value as string); } if (contentType != null) { request.ContentType(contentType.Value as string); } request.SetEntity(entity).Build(GetSelfUri(), Method.POST); return Clone(request, Invoke(request, options), this.Client); } /// <summary> /// Gets the warning headers from the current REST API response. /// </summary> /// <value> /// The warning headers from the current REST API response. /// </value> public List<HttpWarning> Warnings { get { List<HttpWarning> warnings = new List<HttpWarning>(); IEnumerable<Parameter> warningValues = this.Response.Headers.Get("Warning"); if (warningValues != null) { foreach (Parameter warningValue in warningValues) { warnings.AddRange(HttpWarning.Parse(warningValue)); } } return warnings; } } /// <summary> /// Authenticates this session via OAuth2 password. /// </summary> /// <param name="username">The username.</param> /// <param name="password">The password.</param> /// <param name="clientId">The client identifier.</param> /// <returns>A <see cref="GedcomxApplicationState{T}"/> instance containing the REST API response.</returns> /// <remarks>See https://familysearch.org/developers/docs/guides/oauth2 for more information.</remarks> public virtual GedcomxApplicationState AuthenticateViaOAuth2Password(String username, String password, String clientId) { return AuthenticateViaOAuth2Password(username, password, clientId, null); } /// <summary> /// Authenticates this session via OAuth2 password. /// </summary> /// <param name="username">The username.</param> /// <param name="password">The password.</param> /// <param name="clientId">The client identifier.</param> /// <param name="clientSecret">The client secret.</param> /// <returns>A <see cref="GedcomxApplicationState{T}"/> instance containing the REST API response.</returns> /// <remarks>See https://familysearch.org/developers/docs/guides/oauth2 for more information.</remarks> public virtual GedcomxApplicationState AuthenticateViaOAuth2Password(String username, String password, String clientId, String clientSecret) { IDictionary<String, String> formData = new Dictionary<String, String>(); formData.Add("grant_type", "password"); formData.Add("username", username); formData.Add("password", password); formData.Add("client_id", clientId); if (clientSecret != null) { formData.Add("client_secret", clientSecret); } return AuthenticateViaOAuth2(formData); } /// <summary> /// Authenticates this session via OAuth2 authentication code. /// </summary> /// <param name="authCode">The authentication code.</param> /// <param name="redirect">The redirect.</param> /// <param name="clientId">The client identifier.</param> /// <returns>A <see cref="GedcomxApplicationState{T}"/> instance containing the REST API response.</returns> /// <remarks>See https://familysearch.org/developers/docs/guides/oauth2 for more information.</remarks> public GedcomxApplicationState AuthenticateViaOAuth2AuthCode(String authCode, String redirect, String clientId) { return AuthenticateViaOAuth2Password(authCode, authCode, clientId, null); } /// <summary> /// Authenticates this session via OAuth2 authentication code. /// </summary> /// <param name="authCode">The authentication code.</param> /// <param name="redirect">The redirect.</param> /// <param name="clientId">The client identifier.</param> /// <param name="clientSecret">The client secret.</param> /// <returns>A <see cref="GedcomxApplicationState{T}"/> instance containing the REST API response.</returns> /// <remarks>See https://familysearch.org/developers/docs/guides/oauth2 for more information.</remarks> public GedcomxApplicationState AuthenticateViaOAuth2AuthCode(String authCode, String redirect, String clientId, String clientSecret) { IDictionary<String, String> formData = new Dictionary<String, String>(); formData.Add("grant_type", "authorization_code"); formData.Add("code", authCode); formData.Add("redirect_uri", redirect); formData.Add("client_id", clientId); if (clientSecret != null) { formData.Add("client_secret", clientSecret); } return AuthenticateViaOAuth2(formData); } /// <summary> /// Authenticates this session via OAuth2 client credentials. /// </summary> /// <param name="clientId">The client identifier.</param> /// <param name="clientSecret">The client secret.</param> /// <returns>A <see cref="GedcomxApplicationState{T}"/> instance containing the REST API response.</returns> /// <remarks>See https://familysearch.org/developers/docs/guides/oauth2 for more information.</remarks> public GedcomxApplicationState AuthenticateViaOAuth2ClientCredentials(String clientId, String clientSecret) { IDictionary<String, String> formData = new Dictionary<String, String>(); formData.Add("grant_type", "client_credentials"); formData.Add("client_id", clientId); if (clientSecret != null) { formData.Add("client_secret", clientSecret); } return AuthenticateViaOAuth2(formData); } /// <summary> /// Creates a state instance without authentication. It will produce an access token, but only good for requests that do not need authentication. /// </summary> /// <param name="ipAddress">The ip address.</param> /// <param name="clientId">The client identifier.</param> /// <param name="clientSecret">The client secret.</param> /// <returns>A <see cref="GedcomxApplicationState{T}"/> instance containing the REST API response.</returns> /// <remarks>See https://familysearch.org/developers/docs/guides/oauth2 for more information.</remarks> public GedcomxApplicationState UnauthenticatedAccess(string ipAddress, string clientId, string clientSecret = null) { IDictionary<String, String> formData = new Dictionary<String, String>(); formData.Add("grant_type", "unauthenticated_session"); formData.Add("client_id", clientId); formData.Add("ip_address", ipAddress); if (clientSecret != null) { formData.Add("client_secret", clientSecret); } return AuthenticateViaOAuth2(formData); } /// <summary> /// Sets the current access token to the one specified. The server is not contacted during this operation. /// </summary> /// <param name="accessToken">The access token.</param> /// <returns>Returns this instance.</returns> public GedcomxApplicationState AuthenticateWithAccessToken(String accessToken) { this.CurrentAccessToken = accessToken; return this; } /// <summary> /// Authenticates this session via OAuth2. /// </summary> /// <param name="formData">The form data.</param> /// <param name="options">The options to apply before executing the REST API call.</param> /// <returns>A <see cref="GedcomxApplicationState{T}"/> instance containing the REST API response.</returns> /// <exception cref="GedcomxApplicationException"> /// Illegal access token response: no access_token provided. /// or /// Unable to obtain an access token. /// </exception> public GedcomxApplicationState AuthenticateViaOAuth2(IDictionary<String, String> formData, params IStateTransitionOption[] options) { Link tokenLink = this.GetLink(Rel.OAUTH2_TOKEN); if (tokenLink == null || tokenLink.Href == null) { throw new GedcomxApplicationException(String.Format("No OAuth2 token URI supplied for resource at {0}.", GetUri())); } IRestRequest request = CreateRequest() .Accept(MediaTypes.APPLICATION_JSON_TYPE) .ContentType(MediaTypes.APPLICATION_FORM_URLENCODED_TYPE) .SetEntity(formData) .Build(tokenLink.Href, Method.POST); IRestResponse response = Invoke(request, options); if ((int)response.StatusCode >= 200 && (int)response.StatusCode < 300) { var accessToken = JsonConvert.DeserializeObject<IDictionary<string, object>>(response.Content); String access_token = null; if (accessToken.ContainsKey("access_token")) { access_token = accessToken["access_token"] as string; } if (access_token == null && accessToken.ContainsKey("token")) { //workaround to accommodate providers that were built on an older version of the oauth2 specification. access_token = accessToken["token"] as string; } if (access_token == null) { throw new GedcomxApplicationException("Illegal access token response: no access_token provided.", response); } return AuthenticateWithAccessToken(access_token); } else { throw new GedcomxApplicationException("Unable to obtain an access token.", response); } } /// <summary> /// Reads a page of results (usually of type <see cref="Gx.Atom.Feed"/>). /// </summary> /// <param name="rel">The rel name to use when looking for the link.</param> /// <param name="options">The options to apply before executing the REST API call.</param> /// <returns>A <see cref="GedcomxApplicationState{T}"/> instance containing the REST API response.</returns> public GedcomxApplicationState ReadPage(String rel, params IStateTransitionOption[] options) { Link link = GetLink(rel); if (link == null || link.Href == null) { return null; } IRestRequest request = CreateAuthenticatedRequest(); Parameter accept = this.Request.GetHeaders().Get("Accept").FirstOrDefault(); Parameter contentType = this.Request.GetHeaders().Get("Content-Type").FirstOrDefault(); if (accept != null) { request.Accept(accept.Value as string); } if (contentType != null) { request.ContentType(contentType.Value as string); } request.Build(link.Href, Method.GET); return Clone(request, Invoke(request, options), this.Client); } /// <summary> /// Reads the next page of results (usually of type <see cref="Gx.Atom.Feed"/>). /// </summary> /// <param name="options">The options to apply before executing the REST API call.</param> /// <returns>A <see cref="GedcomxApplicationState{T}"/> instance containing the REST API response.</returns> /// <remarks>This is a shorthand method for calling <see cref="ReadPage"/> and specifying Rel.NEXT.</remarks> public GedcomxApplicationState ReadNextPage(params IStateTransitionOption[] options) { return ReadPage(Rel.NEXT, options); } /// <summary> /// Reads the previous page of results (usually of type <see cref="Gx.Atom.Feed"/>). /// </summary> /// <param name="options">The options to apply before executing the REST API call.</param> /// <returns>A <see cref="GedcomxApplicationState{T}"/> instance containing the REST API response.</returns> /// <remarks>This is a shorthand method for calling <see cref="ReadPage"/> and specifying Rel.PREVIOUS.</remarks> public GedcomxApplicationState ReadPreviousPage(params IStateTransitionOption[] options) { return ReadPage(Rel.PREVIOUS, options); } /// <summary> /// Reads the first page of results (usually of type <see cref="Gx.Atom.Feed"/>). /// </summary> /// <param name="options">The options to apply before executing the REST API call.</param> /// <returns>A <see cref="GedcomxApplicationState{T}"/> instance containing the REST API response.</returns> /// <remarks>This is a shorthand method for calling <see cref="ReadPage"/> and specifying Rel.FIRST.</remarks> public GedcomxApplicationState ReadFirstPage(params IStateTransitionOption[] options) { return ReadPage(Rel.FIRST, options); } /// <summary> /// Reads the last page of results (usually of type <see cref="Gx.Atom.Feed"/>). /// </summary> /// <param name="options">The options to apply before executing the REST API call.</param> /// <returns>A <see cref="GedcomxApplicationState{T}"/> instance containing the REST API response.</returns> /// <remarks>This is a shorthand method for calling <see cref="ReadPage"/> and specifying Rel.LAST.</remarks> public GedcomxApplicationState ReadLastPage(params IStateTransitionOption[] options) { return ReadPage(Rel.LAST, options); } /// <summary> /// Creates an authenticated feed request by attaching the authentication token and specifying the accept type. /// </summary> /// <returns>A REST API requeset (with appropriate authentication headers).</returns> protected IRestRequest CreateAuthenticatedFeedRequest() { return CreateAuthenticatedRequest().Accept(MediaTypes.ATOM_GEDCOMX_JSON_MEDIA_TYPE); } /// <summary> /// Reads the contributor for the current state instance. /// </summary> /// <param name="options">The options to apply before executing the REST API call.</param> /// <returns>An <see cref="AgentState"/> instance containing the REST API response.</returns> public AgentState ReadContributor(params IStateTransitionOption[] options) { var scope = MainDataElement; if (scope is IAttributable) { return ReadContributor((IAttributable)scope, options); } else { return null; } } /// <summary> /// Reads the contributor for the specified <see cref="IAttributable"/>. /// </summary> /// <param name="attributable">The attributable.</param> /// <param name="options">The options to apply before executing the REST API call.</param> /// <returns>An <see cref="AgentState"/> instance containing the REST API response.</returns> public AgentState ReadContributor(IAttributable attributable, params IStateTransitionOption[] options) { Attribution attribution = attributable.Attribution; if (attribution == null) { return null; } return ReadContributor(attribution.Contributor, options); } /// <summary> /// Reads the contributor for the specified <see cref="ResourceReference"/>. /// </summary> /// <param name="contributor">The contributor.</param> /// <param name="options">The options to apply before executing the REST API call.</param> /// <returns>An <see cref="AgentState"/> instance containing the REST API response.</returns> public AgentState ReadContributor(ResourceReference contributor, params IStateTransitionOption[] options) { if (contributor == null || contributor.Resource == null) { return null; } IRestRequest request = CreateAuthenticatedGedcomxRequest().Build(contributor.Resource, Method.GET); return this.stateFactory.NewAgentState(request, Invoke(request, options), this.Client, this.CurrentAccessToken); } /// <summary> /// Gets the headers of the current REST API response. /// </summary> /// <value> /// The headers of the current REST API response. /// </value> public IList<Parameter> Headers { get { return Response.Headers; } } /// <summary> /// Gets the URI representing this current state instance. /// </summary> /// <returns>The URI representing this current state instance</returns> public string GetSelfUri() { String selfRel = SelfRel; Link link = null; if (selfRel != null) { link = this.GetLink(selfRel); } link = link == null ? this.GetLink(Rel.SELF) : link; String self = link == null ? null : link.Href == null ? null : link.Href; return self == null ? GetUri() : self; } /// <summary> /// Gets the rel name for the current state instance. This is expected to be overridden. /// </summary> /// <value> /// The rel name for the current state instance /// </value> public virtual String SelfRel { get { return null; } } } /// <summary> /// This is the base class for all state instances with generic specific functionality. /// </summary> /// <typeparam name="T">The type of the expected response. The raw response data will be parsed (from JSON or XML) and casted to this type.</typeparam> public abstract class GedcomxApplicationState<T> : GedcomxApplicationState where T : class, new() { /// <summary> /// Gets the entity represented by this state (if applicable). Not all responses produce entities. /// </summary> /// <value> /// The entity represented by this state. /// </value> public T Entity { get; private set; } /// <summary> /// Returns the entity from the REST API response. /// </summary> /// <param name="response">The REST API response.</param> /// <returns>The entity from the REST API response.</returns> protected virtual T LoadEntity(IRestResponse response) { T result = null; if (response != null) { result = response.ToIRestResponse<T>().Data; } return result; } /// <summary> /// Gets the main data element represented by this state instance. /// </summary> /// <value> /// The main data element represented by this state instance. /// </value> protected override ISupportsLinks MainDataElement { get { return (ISupportsLinks)Entity; } } /// <summary> /// Initializes a new instance of the <see cref="GedcomxApplicationState{T}"/> class. /// </summary> /// <param name="request">The REST API request.</param> /// <param name="response">The REST API response.</param> /// <param name="client">The REST API client.</param> /// <param name="accessToken">The access token.</param> /// <param name="stateFactory">The state factory.</param> protected GedcomxApplicationState(IRestRequest request, IRestResponse response, IFilterableRestClient client, String accessToken, StateFactory stateFactory) : base(request, response, client, accessToken, stateFactory) { this.Entity = LoadEntityConditionally(this.Response); List<Link> links = LoadLinks(this.Response, this.Entity, this.Request.RequestFormat); this.Links = new List<Link>(); this.Links.AddRange(links); } /// <summary> /// Loads the entity from the REST API response if the response should have data. /// </summary> /// <param name="response">The REST API response.</param> /// <returns>Conditional returns the entity from the REST API response if the response should have data.</returns> /// <remarks>The REST API response should have data if the invoking request was not a HEAD or OPTIONS request and the response status is OK.</remarks> protected virtual T LoadEntityConditionally(IRestResponse response) { if (Request.Method != Method.HEAD && Request.Method != Method.OPTIONS && response.StatusCode == HttpStatusCode.OK) { return LoadEntity(response); } else { return null; } } /// <summary> /// Invokes the specified REST API request and returns a state instance of the REST API response. /// </summary> /// <param name="request">The REST API request to execute.</param> /// <returns>The state instance of the REST API response.</returns> public GedcomxApplicationState Inject(IRestRequest request) { return Clone(request, Invoke(request), this.Client); } /// <summary> /// Loads all links from a REST API response and entity object, whether from the header, response body, or any other properties available to extract useful links for this state instance. /// </summary> /// <param name="response">The REST API response.</param> /// <param name="entity">The entity to also consider for finding links.</param> /// <param name="contentFormat">The content format (JSON or XML) of the REST API response data.</param> /// <returns>A list of all links discovered from the REST API response and entity object.</returns> protected List<Link> LoadLinks(IRestResponse response, T entity, DataFormat contentFormat) { List<Link> links = new List<Link>(); var location = response.Headers.FirstOrDefault(x => x.Name == "Location"); //if there's a location, we'll consider it a "self" link. if (location != null && location.Value != null) { links.Add(new Link() { Rel = Rel.SELF, Href = location.Value.ToString() }); } //initialize links with link headers foreach (var header in response.Headers.Where(x => x.Name == "Link" && x.Value != null).SelectMany(x => linkHeaderParser.Parse(response.ResponseUri, x.Value.ToString()))) { Link link = new Link() { Rel = header.Relation, Href = header.Target.ToString() }; link.Template = header.LinkExtensions.Any(x => x.Key == "template") ? header.GetLinkExtension("template") : null; link.Title = header.Title; link.Accept = header.LinkExtensions.Any(x => x.Key == "accept") ? header.GetLinkExtension("accept") : null; link.Allow = header.LinkExtensions.Any(x => x.Key == "allow") ? header.GetLinkExtension("allow") : null; link.Hreflang = header.HrefLang.Select(x => x.Name).FirstOrDefault(); link.Type = header.LinkExtensions.Any(x => x.Key == "type") ? header.GetLinkExtension("type") : null; links.Add(link); } //load the links from the main data element ISupportsLinks mainElement = MainDataElement; if (mainElement != null && mainElement.Links != null) { links.AddRange(mainElement.Links); } //load links at the document level var collection = entity as ISupportsLinks; if (entity != mainElement && collection != null && collection.Links != null) { links.AddRange(collection.Links); } return links; } } }
#region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Reflection; using Newtonsoft.Json.Utilities; using System.Collections; #if NET20 using Newtonsoft.Json.Utilities.LinqBridge; #endif namespace Newtonsoft.Json.Serialization { /// <summary> /// Contract details for a <see cref="Type"/> used by the <see cref="JsonSerializer"/>. /// </summary> public class JsonDictionaryContract : JsonContainerContract { /// <summary> /// Gets or sets the property name resolver. /// </summary> /// <value>The property name resolver.</value> [Obsolete("PropertyNameResolver is obsolete. Use DictionaryKeyResolver instead.")] public Func<string, string> PropertyNameResolver { get { return DictionaryKeyResolver; } set { DictionaryKeyResolver = value; } } /// <summary> /// Gets or sets the dictionary key resolver. /// </summary> /// <value>The dictionary key resolver.</value> public Func<string, string> DictionaryKeyResolver { get; set; } /// <summary> /// Gets the <see cref="Type"/> of the dictionary keys. /// </summary> /// <value>The <see cref="Type"/> of the dictionary keys.</value> public Type DictionaryKeyType { get; private set; } /// <summary> /// Gets the <see cref="Type"/> of the dictionary values. /// </summary> /// <value>The <see cref="Type"/> of the dictionary values.</value> public Type DictionaryValueType { get; private set; } internal JsonContract KeyContract { get; set; } private readonly Type _genericCollectionDefinitionType; private Type _genericWrapperType; private ObjectConstructor<object> _genericWrapperCreator; private Func<object> _genericTemporaryDictionaryCreator; internal bool ShouldCreateWrapper { get; private set; } private readonly ConstructorInfo _parametrizedConstructor; private ObjectConstructor<object> _parametrizedCreator; internal ObjectConstructor<object> ParametrizedCreator { get { if (_parametrizedCreator == null) _parametrizedCreator = JsonTypeReflector.ReflectionDelegateFactory.CreateParametrizedConstructor(_parametrizedConstructor); return _parametrizedCreator; } } internal bool HasParametrizedCreator { get { return _parametrizedCreator != null || _parametrizedConstructor != null; } } /// <summary> /// Initializes a new instance of the <see cref="JsonDictionaryContract"/> class. /// </summary> /// <param name="underlyingType">The underlying type for the contract.</param> public JsonDictionaryContract(Type underlyingType) : base(underlyingType) { ContractType = JsonContractType.Dictionary; Type keyType; Type valueType; if (ReflectionUtils.ImplementsGenericDefinition(underlyingType, typeof(IDictionary<,>), out _genericCollectionDefinitionType)) { keyType = _genericCollectionDefinitionType.GetGenericArguments()[0]; valueType = _genericCollectionDefinitionType.GetGenericArguments()[1]; if (ReflectionUtils.IsGenericDefinition(UnderlyingType, typeof(IDictionary<,>))) CreatedType = typeof(Dictionary<,>).MakeGenericType(keyType, valueType); #if !(NET40 || NET35 || NET20 || PORTABLE40) IsReadOnlyOrFixedSize = ReflectionUtils.InheritsGenericDefinition(underlyingType, typeof(ReadOnlyDictionary<,>)); #endif } #if !(NET40 || NET35 || NET20 || PORTABLE40) else if (ReflectionUtils.ImplementsGenericDefinition(underlyingType, typeof(IReadOnlyDictionary<,>), out _genericCollectionDefinitionType)) { keyType = _genericCollectionDefinitionType.GetGenericArguments()[0]; valueType = _genericCollectionDefinitionType.GetGenericArguments()[1]; if (ReflectionUtils.IsGenericDefinition(UnderlyingType, typeof(IReadOnlyDictionary<,>))) CreatedType = typeof(ReadOnlyDictionary<,>).MakeGenericType(keyType, valueType); IsReadOnlyOrFixedSize = true; } #endif else { ReflectionUtils.GetDictionaryKeyValueTypes(UnderlyingType, out keyType, out valueType); if (UnderlyingType == typeof(IDictionary)) CreatedType = typeof(Dictionary<object, object>); } if (keyType != null && valueType != null) { _parametrizedConstructor = CollectionUtils.ResolveEnumerableCollectionConstructor(CreatedType, typeof(KeyValuePair<,>).MakeGenericType(keyType, valueType)); #if !(NET35 || NET20 || NETFX_CORE) if (!HasParametrizedCreator && underlyingType.Name == FSharpUtils.FSharpMapTypeName) { FSharpUtils.EnsureInitialized(underlyingType.Assembly()); _parametrizedCreator = FSharpUtils.CreateMap(keyType, valueType); } #endif } ShouldCreateWrapper = !typeof(IDictionary).IsAssignableFrom(CreatedType); DictionaryKeyType = keyType; DictionaryValueType = valueType; #if (NET20 || NET35) if (DictionaryValueType != null && ReflectionUtils.IsNullableType(DictionaryValueType)) { Type tempDictioanryType; // bug in .NET 2.0 & 3.5 that Dictionary<TKey, Nullable<TValue>> throws an error when adding null via IDictionary[key] = object // wrapper will handle calling Add(T) instead if (ReflectionUtils.InheritsGenericDefinition(CreatedType, typeof(Dictionary<,>), out tempDictioanryType)) { ShouldCreateWrapper = true; } } #endif #if !(NET20 || NET35 || NET40 || PORTABLE40) Type immutableCreatedType; ObjectConstructor<object> immutableParameterizedCreator; if (ImmutableCollectionsUtils.TryBuildImmutableForDictionaryContract(underlyingType, DictionaryKeyType, DictionaryValueType, out immutableCreatedType, out immutableParameterizedCreator)) { CreatedType = immutableCreatedType; _parametrizedCreator = immutableParameterizedCreator; IsReadOnlyOrFixedSize = true; } #endif } internal IWrappedDictionary CreateWrapper(object dictionary) { if (_genericWrapperCreator == null) { _genericWrapperType = typeof(DictionaryWrapper<,>).MakeGenericType(DictionaryKeyType, DictionaryValueType); ConstructorInfo genericWrapperConstructor = _genericWrapperType.GetConstructor(new[] { _genericCollectionDefinitionType }); _genericWrapperCreator = JsonTypeReflector.ReflectionDelegateFactory.CreateParametrizedConstructor(genericWrapperConstructor); } return (IWrappedDictionary)_genericWrapperCreator(dictionary); } internal IDictionary CreateTemporaryDictionary() { if (_genericTemporaryDictionaryCreator == null) { Type temporaryDictionaryType = typeof(Dictionary<,>).MakeGenericType(DictionaryKeyType, DictionaryValueType); _genericTemporaryDictionaryCreator = JsonTypeReflector.ReflectionDelegateFactory.CreateDefaultConstructor<object>(temporaryDictionaryType); } return (IDictionary)_genericTemporaryDictionaryCreator(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading; using System.Threading.Tasks; using Microsoft.Win32.SafeHandles; using System.Diagnostics; namespace System.IO { public partial class FileStream : Stream { private const FileShare DefaultShare = FileShare.Read; private const bool DefaultIsAsync = false; internal const int DefaultBufferSize = 4096; private byte[] _buffer; private int _bufferLength; private readonly SafeFileHandle _fileHandle; /// <summary>Whether the file is opened for reading, writing, or both.</summary> private readonly FileAccess _access; /// <summary>The path to the opened file.</summary> private readonly string _path; /// <summary>The next available byte to be read from the _buffer.</summary> private int _readPos; /// <summary>The number of valid bytes in _buffer.</summary> private int _readLength; /// <summary>The next location in which a write should occur to the buffer.</summary> private int _writePos; /// <summary> /// Whether asynchronous read/write/flush operations should be performed using async I/O. /// On Windows FileOptions.Asynchronous controls how the file handle is configured, /// and then as a result how operations are issued against that file handle. On Unix, /// there isn't any distinction around how file descriptors are created for async vs /// sync, but we still differentiate how the operations are issued in order to provide /// similar behavioral semantics and performance characteristics as on Windows. On /// Windows, if non-async, async read/write requests just delegate to the base stream, /// and no attempt is made to synchronize between sync and async operations on the stream; /// if async, then async read/write requests are implemented specially, and sync read/write /// requests are coordinated with async ones by implementing the sync ones over the async /// ones. On Unix, we do something similar. If non-async, async read/write requests just /// delegate to the base stream, and no attempt is made to synchronize. If async, we use /// a semaphore to coordinate both sync and async operations. /// </summary> private readonly bool _useAsyncIO; /// <summary>cached task for read ops that complete synchronously</summary> private Task<int> _lastSynchronouslyCompletedTask = null; /// <summary> /// Currently cached position in the stream. This should always mirror the underlying file's actual position, /// and should only ever be out of sync if another stream with access to this same file manipulates it, at which /// point we attempt to error out. /// </summary> private long _filePosition; /// <summary>Whether the file stream's handle has been exposed.</summary> private bool _exposedHandle; [Obsolete("This constructor has been deprecated. Please use new FileStream(SafeFileHandle handle, FileAccess access) instead. https://go.microsoft.com/fwlink/?linkid=14202")] public FileStream(IntPtr handle, FileAccess access) : this(handle, access, true, DefaultBufferSize, false) { } [Obsolete("This constructor has been deprecated. Please use new FileStream(SafeFileHandle handle, FileAccess access) instead, and optionally make a new SafeFileHandle with ownsHandle=false if needed. https://go.microsoft.com/fwlink/?linkid=14202")] public FileStream(IntPtr handle, FileAccess access, bool ownsHandle) : this(handle, access, ownsHandle, DefaultBufferSize, false) { } [Obsolete("This constructor has been deprecated. Please use new FileStream(SafeFileHandle handle, FileAccess access, int bufferSize) instead, and optionally make a new SafeFileHandle with ownsHandle=false if needed. https://go.microsoft.com/fwlink/?linkid=14202")] public FileStream(IntPtr handle, FileAccess access, bool ownsHandle, int bufferSize) : this(handle, access, ownsHandle, bufferSize, false) { } [Obsolete("This constructor has been deprecated. Please use new FileStream(SafeFileHandle handle, FileAccess access, int bufferSize, bool isAsync) instead, and optionally make a new SafeFileHandle with ownsHandle=false if needed. https://go.microsoft.com/fwlink/?linkid=14202")] public FileStream(IntPtr handle, FileAccess access, bool ownsHandle, int bufferSize, bool isAsync) { SafeFileHandle safeHandle = new SafeFileHandle(handle, ownsHandle: ownsHandle); try { ValidateAndInitFromHandle(safeHandle, access, bufferSize, isAsync); } catch { // We don't want to take ownership of closing passed in handles // *unless* the constructor completes successfully. GC.SuppressFinalize(safeHandle); // This would also prevent Close from being called, but is unnecessary // as we've removed the object from the finalizer queue. // // safeHandle.SetHandleAsInvalid(); throw; } // Note: Cleaner to set the following fields in ValidateAndInitFromHandle, // but we can't as they're readonly. _access = access; _useAsyncIO = isAsync; // As the handle was passed in, we must set the handle field at the very end to // avoid the finalizer closing the handle when we throw errors. _fileHandle = safeHandle; } public FileStream(SafeFileHandle handle, FileAccess access) : this(handle, access, DefaultBufferSize) { } public FileStream(SafeFileHandle handle, FileAccess access, int bufferSize) : this(handle, access, bufferSize, GetDefaultIsAsync(handle)) { } private void ValidateAndInitFromHandle(SafeFileHandle handle, FileAccess access, int bufferSize, bool isAsync) { if (handle.IsInvalid) throw new ArgumentException(SR.Arg_InvalidHandle, nameof(handle)); if (access < FileAccess.Read || access > FileAccess.ReadWrite) throw new ArgumentOutOfRangeException(nameof(access), SR.ArgumentOutOfRange_Enum); if (bufferSize <= 0) throw new ArgumentOutOfRangeException(nameof(bufferSize), SR.ArgumentOutOfRange_NeedPosNum); if (handle.IsClosed) throw new ObjectDisposedException(SR.ObjectDisposed_FileClosed); if (handle.IsAsync.HasValue && isAsync != handle.IsAsync.Value) throw new ArgumentException(SR.Arg_HandleNotAsync, nameof(handle)); _exposedHandle = true; _bufferLength = bufferSize; InitFromHandle(handle, access, isAsync); } public FileStream(SafeFileHandle handle, FileAccess access, int bufferSize, bool isAsync) { ValidateAndInitFromHandle(handle, access, bufferSize, isAsync); // Note: Cleaner to set the following fields in ValidateAndInitFromHandle, // but we can't as they're readonly. _access = access; _useAsyncIO = isAsync; // As the handle was passed in, we must set the handle field at the very end to // avoid the finalizer closing the handle when we throw errors. _fileHandle = handle; } public FileStream(string path, FileMode mode) : this(path, mode, (mode == FileMode.Append ? FileAccess.Write : FileAccess.ReadWrite), DefaultShare, DefaultBufferSize, DefaultIsAsync) { } public FileStream(string path, FileMode mode, FileAccess access) : this(path, mode, access, DefaultShare, DefaultBufferSize, DefaultIsAsync) { } public FileStream(string path, FileMode mode, FileAccess access, FileShare share) : this(path, mode, access, share, DefaultBufferSize, DefaultIsAsync) { } public FileStream(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize) : this(path, mode, access, share, bufferSize, DefaultIsAsync) { } public FileStream(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, bool useAsync) : this(path, mode, access, share, bufferSize, useAsync ? FileOptions.Asynchronous : FileOptions.None) { } public FileStream(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, FileOptions options) { if (path == null) throw new ArgumentNullException(nameof(path), SR.ArgumentNull_Path); if (path.Length == 0) throw new ArgumentException(SR.Argument_EmptyPath, nameof(path)); // don't include inheritable in our bounds check for share FileShare tempshare = share & ~FileShare.Inheritable; string badArg = null; if (mode < FileMode.CreateNew || mode > FileMode.Append) badArg = nameof(mode); else if (access < FileAccess.Read || access > FileAccess.ReadWrite) badArg = nameof(access); else if (tempshare < FileShare.None || tempshare > (FileShare.ReadWrite | FileShare.Delete)) badArg = nameof(share); if (badArg != null) throw new ArgumentOutOfRangeException(badArg, SR.ArgumentOutOfRange_Enum); // NOTE: any change to FileOptions enum needs to be matched here in the error validation if (options != FileOptions.None && (options & ~(FileOptions.WriteThrough | FileOptions.Asynchronous | FileOptions.RandomAccess | FileOptions.DeleteOnClose | FileOptions.SequentialScan | FileOptions.Encrypted | (FileOptions)0x20000000 /* NoBuffering */)) != 0) throw new ArgumentOutOfRangeException(nameof(options), SR.ArgumentOutOfRange_Enum); if (bufferSize <= 0) throw new ArgumentOutOfRangeException(nameof(bufferSize), SR.ArgumentOutOfRange_NeedPosNum); // Write access validation if ((access & FileAccess.Write) == 0) { if (mode == FileMode.Truncate || mode == FileMode.CreateNew || mode == FileMode.Create || mode == FileMode.Append) { // No write access, mode and access disagree but flag access since mode comes first throw new ArgumentException(SR.Format(SR.Argument_InvalidFileModeAndAccessCombo, mode, access), nameof(access)); } } if ((access & FileAccess.Read) != 0 && mode == FileMode.Append) throw new ArgumentException(SR.Argument_InvalidAppendMode, nameof(access)); string fullPath = Path.GetFullPath(path); _path = fullPath; _access = access; _bufferLength = bufferSize; if ((options & FileOptions.Asynchronous) != 0) _useAsyncIO = true; _fileHandle = OpenHandle(mode, share, options); try { Init(mode, share, path); } catch { // If anything goes wrong while setting up the stream, make sure we deterministically dispose // of the opened handle. _fileHandle.Dispose(); _fileHandle = null; throw; } } [Obsolete("This property has been deprecated. Please use FileStream's SafeFileHandle property instead. https://go.microsoft.com/fwlink/?linkid=14202")] public virtual IntPtr Handle { get { return SafeFileHandle.DangerousGetHandle(); } } public virtual void Lock(long position, long length) { if (position < 0 || length < 0) { throw new ArgumentOutOfRangeException(position < 0 ? nameof(position) : nameof(length), SR.ArgumentOutOfRange_NeedNonNegNum); } if (_fileHandle.IsClosed) { throw Error.GetFileNotOpen(); } LockInternal(position, length); } public virtual void Unlock(long position, long length) { if (position < 0 || length < 0) { throw new ArgumentOutOfRangeException(position < 0 ? nameof(position) : nameof(length), SR.ArgumentOutOfRange_NeedNonNegNum); } if (_fileHandle.IsClosed) { throw Error.GetFileNotOpen(); } UnlockInternal(position, length); } public override Task FlushAsync(CancellationToken cancellationToken) { // If we have been inherited into a subclass, the following implementation could be incorrect // since it does not call through to Flush() which a subclass might have overridden. To be safe // we will only use this implementation in cases where we know it is safe to do so, // and delegate to our base class (which will call into Flush) when we are not sure. if (GetType() != typeof(FileStream)) return base.FlushAsync(cancellationToken); return FlushAsyncInternal(cancellationToken); } public override int Read(byte[] array, int offset, int count) { ValidateReadWriteArgs(array, offset, count); return _useAsyncIO ? ReadAsyncTask(array, offset, count, CancellationToken.None).GetAwaiter().GetResult() : ReadSpan(new Span<byte>(array, offset, count)); } public override int Read(Span<byte> buffer) { if (GetType() == typeof(FileStream) && !_useAsyncIO) { if (_fileHandle.IsClosed) { throw Error.GetFileNotOpen(); } return ReadSpan(buffer); } else { // This type is derived from FileStream and/or the stream is in async mode. If this is a // derived type, it may have overridden Read(byte[], int, int) prior to this Read(Span<byte>) // overload being introduced. In that case, this Read(Span<byte>) overload should use the behavior // of Read(byte[],int,int) overload. Or if the stream is in async mode, we can't call the // synchronous ReadSpan, so we similarly call the base Read, which will turn delegate to // Read(byte[],int,int), which will do the right thing if we're in async mode. return base.Read(buffer); } } public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { if (buffer == null) throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer); if (offset < 0) throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum); if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); if (buffer.Length - offset < count) throw new ArgumentException(SR.Argument_InvalidOffLen /*, no good single parameter name to pass*/); // If we have been inherited into a subclass, the following implementation could be incorrect // since it does not call through to Read() which a subclass might have overridden. // To be safe we will only use this implementation in cases where we know it is safe to do so, // and delegate to our base class (which will call into Read/ReadAsync) when we are not sure. // Similarly, if we weren't opened for asynchronous I/O, call to the base implementation so that // Read is invoked asynchronously. if (GetType() != typeof(FileStream) || !_useAsyncIO) return base.ReadAsync(buffer, offset, count, cancellationToken); if (cancellationToken.IsCancellationRequested) return Task.FromCanceled<int>(cancellationToken); if (IsClosed) throw Error.GetFileNotOpen(); return ReadAsyncTask(buffer, offset, count, cancellationToken); } public override ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken = default) { if (!_useAsyncIO || GetType() != typeof(FileStream)) { // If we're not using async I/O, delegate to the base, which will queue a call to Read. // Or if this isn't a concrete FileStream, a derived type may have overridden ReadAsync(byte[],...), // which was introduced first, so delegate to the base which will delegate to that. return base.ReadAsync(buffer, cancellationToken); } if (cancellationToken.IsCancellationRequested) { return new ValueTask<int>(Task.FromCanceled<int>(cancellationToken)); } if (IsClosed) { throw Error.GetFileNotOpen(); } Task<int> t = ReadAsyncInternal(buffer, cancellationToken, out int synchronousResult); return t != null ? new ValueTask<int>(t) : new ValueTask<int>(synchronousResult); } private Task<int> ReadAsyncTask(byte[] array, int offset, int count, CancellationToken cancellationToken) { Task<int> t = ReadAsyncInternal(new Memory<byte>(array, offset, count), cancellationToken, out int synchronousResult); if (t == null) { t = _lastSynchronouslyCompletedTask; Debug.Assert(t == null || t.IsCompletedSuccessfully, "Cached task should have completed successfully"); if (t == null || t.Result != synchronousResult) { _lastSynchronouslyCompletedTask = t = Task.FromResult(synchronousResult); } } return t; } public override void Write(byte[] array, int offset, int count) { ValidateReadWriteArgs(array, offset, count); if (_useAsyncIO) { WriteAsyncInternal(new ReadOnlyMemory<byte>(array, offset, count), CancellationToken.None).GetAwaiter().GetResult(); } else { WriteSpan(new ReadOnlySpan<byte>(array, offset, count)); } } public override void Write(ReadOnlySpan<byte> buffer) { if (GetType() == typeof(FileStream) && !_useAsyncIO) { if (_fileHandle.IsClosed) { throw Error.GetFileNotOpen(); } WriteSpan(buffer); } else { // This type is derived from FileStream and/or the stream is in async mode. If this is a // derived type, it may have overridden Write(byte[], int, int) prior to this Write(ReadOnlySpan<byte>) // overload being introduced. In that case, this Write(ReadOnlySpan<byte>) overload should use the behavior // of Write(byte[],int,int) overload. Or if the stream is in async mode, we can't call the // synchronous WriteSpan, so we similarly call the base Write, which will turn delegate to // Write(byte[],int,int), which will do the right thing if we're in async mode. base.Write(buffer); } } public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { if (buffer == null) throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer); if (offset < 0) throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum); if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); if (buffer.Length - offset < count) throw new ArgumentException(SR.Argument_InvalidOffLen /*, no good single parameter name to pass*/); // If we have been inherited into a subclass, the following implementation could be incorrect // since it does not call through to Write() or WriteAsync() which a subclass might have overridden. // To be safe we will only use this implementation in cases where we know it is safe to do so, // and delegate to our base class (which will call into Write/WriteAsync) when we are not sure. if (!_useAsyncIO || GetType() != typeof(FileStream)) return base.WriteAsync(buffer, offset, count, cancellationToken); if (cancellationToken.IsCancellationRequested) return Task.FromCanceled(cancellationToken); if (IsClosed) throw Error.GetFileNotOpen(); return WriteAsyncInternal(new ReadOnlyMemory<byte>(buffer, offset, count), cancellationToken).AsTask(); } public override ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken = default) { if (!_useAsyncIO || GetType() != typeof(FileStream)) { // If we're not using async I/O, delegate to the base, which will queue a call to Write. // Or if this isn't a concrete FileStream, a derived type may have overridden WriteAsync(byte[],...), // which was introduced first, so delegate to the base which will delegate to that. return base.WriteAsync(buffer, cancellationToken); } if (cancellationToken.IsCancellationRequested) { return new ValueTask(Task.FromCanceled<int>(cancellationToken)); } if (IsClosed) { throw Error.GetFileNotOpen(); } return WriteAsyncInternal(buffer, cancellationToken); } /// <summary> /// Clears buffers for this stream and causes any buffered data to be written to the file. /// </summary> public override void Flush() { // Make sure that we call through the public virtual API Flush(flushToDisk: false); } /// <summary> /// Clears buffers for this stream, and if <param name="flushToDisk"/> is true, /// causes any buffered data to be written to the file. /// </summary> public virtual void Flush(bool flushToDisk) { if (IsClosed) throw Error.GetFileNotOpen(); FlushInternalBuffer(); if (flushToDisk && CanWrite) { FlushOSBuffer(); } } /// <summary>Gets a value indicating whether the current stream supports reading.</summary> public override bool CanRead { get { return !_fileHandle.IsClosed && (_access & FileAccess.Read) != 0; } } /// <summary>Gets a value indicating whether the current stream supports writing.</summary> public override bool CanWrite { get { return !_fileHandle.IsClosed && (_access & FileAccess.Write) != 0; } } /// <summary>Validates arguments to Read and Write and throws resulting exceptions.</summary> /// <param name="array">The buffer to read from or write to.</param> /// <param name="offset">The zero-based offset into the array.</param> /// <param name="count">The maximum number of bytes to read or write.</param> private void ValidateReadWriteArgs(byte[] array, int offset, int count) { if (array == null) throw new ArgumentNullException(nameof(array), SR.ArgumentNull_Buffer); if (offset < 0) throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum); if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); if (array.Length - offset < count) throw new ArgumentException(SR.Argument_InvalidOffLen /*, no good single parameter name to pass*/); if (_fileHandle.IsClosed) throw Error.GetFileNotOpen(); } /// <summary>Sets the length of this stream to the given value.</summary> /// <param name="value">The new length of the stream.</param> public override void SetLength(long value) { if (value < 0) throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_NeedNonNegNum); if (_fileHandle.IsClosed) throw Error.GetFileNotOpen(); if (!CanSeek) throw Error.GetSeekNotSupported(); if (!CanWrite) throw Error.GetWriteNotSupported(); SetLengthInternal(value); } public virtual SafeFileHandle SafeFileHandle { get { Flush(); _exposedHandle = true; return _fileHandle; } } /// <summary>Gets the path that was passed to the constructor.</summary> public virtual string Name { get { return _path ?? SR.IO_UnknownFileName; } } /// <summary>Gets a value indicating whether the stream was opened for I/O to be performed synchronously or asynchronously.</summary> public virtual bool IsAsync { get { return _useAsyncIO; } } /// <summary>Gets the length of the stream in bytes.</summary> public override long Length { get { if (_fileHandle.IsClosed) throw Error.GetFileNotOpen(); if (!CanSeek) throw Error.GetSeekNotSupported(); return GetLengthInternal(); } } /// <summary> /// Verify that the actual position of the OS's handle equals what we expect it to. /// This will fail if someone else moved the UnixFileStream's handle or if /// our position updating code is incorrect. /// </summary> private void VerifyOSHandlePosition() { bool verifyPosition = _exposedHandle; // in release, only verify if we've given out the handle such that someone else could be manipulating it #if DEBUG verifyPosition = true; // in debug, always make sure our position matches what the OS says it should be #endif if (verifyPosition && CanSeek) { long oldPos = _filePosition; // SeekCore will override the current _position, so save it now long curPos = SeekCore(_fileHandle, 0, SeekOrigin.Current); if (oldPos != curPos) { // For reads, this is non-fatal but we still could have returned corrupted // data in some cases, so discard the internal buffer. For writes, // this is a problem; discard the buffer and error out. _readPos = _readLength = 0; if (_writePos > 0) { _writePos = 0; throw new IOException(SR.IO_FileStreamHandlePosition); } } } } /// <summary>Verifies that state relating to the read/write buffer is consistent.</summary> [Conditional("DEBUG")] private void AssertBufferInvariants() { // Read buffer values must be in range: 0 <= _bufferReadPos <= _bufferReadLength <= _bufferLength Debug.Assert(0 <= _readPos && _readPos <= _readLength && _readLength <= _bufferLength); // Write buffer values must be in range: 0 <= _bufferWritePos <= _bufferLength Debug.Assert(0 <= _writePos && _writePos <= _bufferLength); // Read buffering and write buffering can't both be active Debug.Assert((_readPos == 0 && _readLength == 0) || _writePos == 0); } /// <summary>Validates that we're ready to read from the stream.</summary> private void PrepareForReading() { if (_fileHandle.IsClosed) throw Error.GetFileNotOpen(); if (_readLength == 0 && !CanRead) throw Error.GetReadNotSupported(); AssertBufferInvariants(); } /// <summary>Gets or sets the position within the current stream</summary> public override long Position { get { if (_fileHandle.IsClosed) throw Error.GetFileNotOpen(); if (!CanSeek) throw Error.GetSeekNotSupported(); AssertBufferInvariants(); VerifyOSHandlePosition(); // We may have read data into our buffer from the handle, such that the handle position // is artificially further along than the consumer's view of the stream's position. // Thus, when reading, our position is really starting from the handle position negatively // offset by the number of bytes in the buffer and positively offset by the number of // bytes into that buffer we've read. When writing, both the read length and position // must be zero, and our position is just the handle position offset positive by how many // bytes we've written into the buffer. return (_filePosition - _readLength) + _readPos + _writePos; } set { if (value < 0) throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_NeedNonNegNum); Seek(value, SeekOrigin.Begin); } } internal virtual bool IsClosed => _fileHandle.IsClosed; private static bool IsIoRelatedException(Exception e) => // These all derive from IOException // DirectoryNotFoundException // DriveNotFoundException // EndOfStreamException // FileLoadException // FileNotFoundException // PathTooLongException // PipeException e is IOException || // Note that SecurityException is only thrown on runtimes that support CAS // e is SecurityException || e is UnauthorizedAccessException || e is NotSupportedException || (e is ArgumentException && !(e is ArgumentNullException)); /// <summary> /// Gets the array used for buffering reading and writing. /// If the array hasn't been allocated, this will lazily allocate it. /// </summary> /// <returns>The buffer.</returns> private byte[] GetBuffer() { Debug.Assert(_buffer == null || _buffer.Length == _bufferLength); if (_buffer == null) { _buffer = new byte[_bufferLength]; OnBufferAllocated(); } return _buffer; } partial void OnBufferAllocated(); /// <summary> /// Flushes the internal read/write buffer for this stream. If write data has been buffered, /// that data is written out to the underlying file. Or if data has been buffered for /// reading from the stream, the data is dumped and our position in the underlying file /// is rewound as necessary. This does not flush the OS buffer. /// </summary> private void FlushInternalBuffer() { AssertBufferInvariants(); if (_writePos > 0) { FlushWriteBuffer(); } else if (_readPos < _readLength && CanSeek) { FlushReadBuffer(); } } /// <summary>Dumps any read data in the buffer and rewinds our position in the stream, accordingly, as necessary.</summary> private void FlushReadBuffer() { // Reading is done by blocks from the file, but someone could read // 1 byte from the buffer then write. At that point, the OS's file // pointer is out of sync with the stream's position. All write // functions should call this function to preserve the position in the file. AssertBufferInvariants(); Debug.Assert(_writePos == 0, "FileStream: Write buffer must be empty in FlushReadBuffer!"); int rewind = _readPos - _readLength; if (rewind != 0) { Debug.Assert(CanSeek, "FileStream will lose buffered read data now."); SeekCore(_fileHandle, rewind, SeekOrigin.Current); } _readPos = _readLength = 0; } /// <summary> /// Reads a byte from the file stream. Returns the byte cast to an int /// or -1 if reading from the end of the stream. /// </summary> public override int ReadByte() { PrepareForReading(); byte[] buffer = GetBuffer(); if (_readPos == _readLength) { FlushWriteBuffer(); _readLength = FillReadBufferForReadByte(); _readPos = 0; if (_readLength == 0) { return -1; } } return buffer[_readPos++]; } /// <summary> /// Writes a byte to the current position in the stream and advances the position /// within the stream by one byte. /// </summary> /// <param name="value">The byte to write to the stream.</param> public override void WriteByte(byte value) { PrepareForWriting(); // Flush the write buffer if it's full if (_writePos == _bufferLength) FlushWriteBufferForWriteByte(); // We now have space in the buffer. Store the byte. GetBuffer()[_writePos++] = value; } /// <summary> /// Validates that we're ready to write to the stream, /// including flushing a read buffer if necessary. /// </summary> private void PrepareForWriting() { if (_fileHandle.IsClosed) throw Error.GetFileNotOpen(); // Make sure we're good to write. We only need to do this if there's nothing already // in our write buffer, since if there is something in the buffer, we've already done // this checking and flushing. if (_writePos == 0) { if (!CanWrite) throw Error.GetWriteNotSupported(); FlushReadBuffer(); Debug.Assert(_bufferLength > 0, "_bufferSize > 0"); } } ~FileStream() { // Preserved for compatibility since FileStream has defined a // finalizer in past releases and derived classes may depend // on Dispose(false) call. Dispose(false); } public override IAsyncResult BeginRead(byte[] array, int offset, int numBytes, AsyncCallback callback, object state) { if (array == null) throw new ArgumentNullException(nameof(array)); if (offset < 0) throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum); if (numBytes < 0) throw new ArgumentOutOfRangeException(nameof(numBytes), SR.ArgumentOutOfRange_NeedNonNegNum); if (array.Length - offset < numBytes) throw new ArgumentException(SR.Argument_InvalidOffLen); if (IsClosed) throw new ObjectDisposedException(SR.ObjectDisposed_FileClosed); if (!CanRead) throw new NotSupportedException(SR.NotSupported_UnreadableStream); if (!IsAsync) return base.BeginRead(array, offset, numBytes, callback, state); else return TaskToApm.Begin(ReadAsyncTask(array, offset, numBytes, CancellationToken.None), callback, state); } public override IAsyncResult BeginWrite(byte[] array, int offset, int numBytes, AsyncCallback callback, object state) { if (array == null) throw new ArgumentNullException(nameof(array)); if (offset < 0) throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum); if (numBytes < 0) throw new ArgumentOutOfRangeException(nameof(numBytes), SR.ArgumentOutOfRange_NeedNonNegNum); if (array.Length - offset < numBytes) throw new ArgumentException(SR.Argument_InvalidOffLen); if (IsClosed) throw new ObjectDisposedException(SR.ObjectDisposed_FileClosed); if (!CanWrite) throw new NotSupportedException(SR.NotSupported_UnwritableStream); if (!IsAsync) return base.BeginWrite(array, offset, numBytes, callback, state); else return TaskToApm.Begin(WriteAsyncInternal(new ReadOnlyMemory<byte>(array, offset, numBytes), CancellationToken.None).AsTask(), callback, state); } public override int EndRead(IAsyncResult asyncResult) { if (asyncResult == null) throw new ArgumentNullException(nameof(asyncResult)); if (!IsAsync) return base.EndRead(asyncResult); else return TaskToApm.End<int>(asyncResult); } public override void EndWrite(IAsyncResult asyncResult) { if (asyncResult == null) throw new ArgumentNullException(nameof(asyncResult)); if (!IsAsync) base.EndWrite(asyncResult); else TaskToApm.End(asyncResult); } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Azure.Management.Resources; using Microsoft.Azure.Management.Resources.Models; namespace Microsoft.Azure.Management.Resources { public static partial class FeaturesExtensions { /// <summary> /// Get all features under the subscription. /// </summary> /// <param name='operations'> /// Reference to the Microsoft.Azure.Management.Resources.IFeatures. /// </param> /// <param name='resourceProviderNamespace'> /// Required. Namespace of the resource provider. /// </param> /// <param name='featureName'> /// Required. Previewed feature name in the resource provider. /// </param> /// <returns> /// Previewed feature information. /// </returns> public static FeatureResponse Get(this IFeatures operations, string resourceProviderNamespace, string featureName) { return Task.Factory.StartNew((object s) => { return ((IFeatures)s).GetAsync(resourceProviderNamespace, featureName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get all features under the subscription. /// </summary> /// <param name='operations'> /// Reference to the Microsoft.Azure.Management.Resources.IFeatures. /// </param> /// <param name='resourceProviderNamespace'> /// Required. Namespace of the resource provider. /// </param> /// <param name='featureName'> /// Required. Previewed feature name in the resource provider. /// </param> /// <returns> /// Previewed feature information. /// </returns> public static Task<FeatureResponse> GetAsync(this IFeatures operations, string resourceProviderNamespace, string featureName) { return operations.GetAsync(resourceProviderNamespace, featureName, CancellationToken.None); } /// <summary> /// Gets a list of previewed features of a resource provider. /// </summary> /// <param name='operations'> /// Reference to the Microsoft.Azure.Management.Resources.IFeatures. /// </param> /// <param name='resourceProviderNamespace'> /// Required. The namespace of the resource provider. /// </param> /// <returns> /// List of previewed features. /// </returns> public static FeatureOperationsListResult List(this IFeatures operations, string resourceProviderNamespace) { return Task.Factory.StartNew((object s) => { return ((IFeatures)s).ListAsync(resourceProviderNamespace); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets a list of previewed features of a resource provider. /// </summary> /// <param name='operations'> /// Reference to the Microsoft.Azure.Management.Resources.IFeatures. /// </param> /// <param name='resourceProviderNamespace'> /// Required. The namespace of the resource provider. /// </param> /// <returns> /// List of previewed features. /// </returns> public static Task<FeatureOperationsListResult> ListAsync(this IFeatures operations, string resourceProviderNamespace) { return operations.ListAsync(resourceProviderNamespace, CancellationToken.None); } /// <summary> /// Gets a list of previewed features for all the providers in the /// current subscription. /// </summary> /// <param name='operations'> /// Reference to the Microsoft.Azure.Management.Resources.IFeatures. /// </param> /// <returns> /// List of previewed features. /// </returns> public static FeatureOperationsListResult ListAll(this IFeatures operations) { return Task.Factory.StartNew((object s) => { return ((IFeatures)s).ListAllAsync(); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets a list of previewed features for all the providers in the /// current subscription. /// </summary> /// <param name='operations'> /// Reference to the Microsoft.Azure.Management.Resources.IFeatures. /// </param> /// <returns> /// List of previewed features. /// </returns> public static Task<FeatureOperationsListResult> ListAllAsync(this IFeatures operations) { return operations.ListAllAsync(CancellationToken.None); } /// <summary> /// Gets a list of previewed features of a subscription. /// </summary> /// <param name='operations'> /// Reference to the Microsoft.Azure.Management.Resources.IFeatures. /// </param> /// <param name='nextLink'> /// Required. NextLink from the previous successful call to List /// operation. /// </param> /// <returns> /// List of previewed features. /// </returns> public static FeatureOperationsListResult ListAllNext(this IFeatures operations, string nextLink) { return Task.Factory.StartNew((object s) => { return ((IFeatures)s).ListAllNextAsync(nextLink); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets a list of previewed features of a subscription. /// </summary> /// <param name='operations'> /// Reference to the Microsoft.Azure.Management.Resources.IFeatures. /// </param> /// <param name='nextLink'> /// Required. NextLink from the previous successful call to List /// operation. /// </param> /// <returns> /// List of previewed features. /// </returns> public static Task<FeatureOperationsListResult> ListAllNextAsync(this IFeatures operations, string nextLink) { return operations.ListAllNextAsync(nextLink, CancellationToken.None); } /// <summary> /// Gets a list of previewed features of a resource provider. /// </summary> /// <param name='operations'> /// Reference to the Microsoft.Azure.Management.Resources.IFeatures. /// </param> /// <param name='nextLink'> /// Required. NextLink from the previous successful call to List /// operation. /// </param> /// <returns> /// List of previewed features. /// </returns> public static FeatureOperationsListResult ListNext(this IFeatures operations, string nextLink) { return Task.Factory.StartNew((object s) => { return ((IFeatures)s).ListNextAsync(nextLink); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets a list of previewed features of a resource provider. /// </summary> /// <param name='operations'> /// Reference to the Microsoft.Azure.Management.Resources.IFeatures. /// </param> /// <param name='nextLink'> /// Required. NextLink from the previous successful call to List /// operation. /// </param> /// <returns> /// List of previewed features. /// </returns> public static Task<FeatureOperationsListResult> ListNextAsync(this IFeatures operations, string nextLink) { return operations.ListNextAsync(nextLink, CancellationToken.None); } /// <summary> /// Registers for a previewed feature of a resource provider. /// </summary> /// <param name='operations'> /// Reference to the Microsoft.Azure.Management.Resources.IFeatures. /// </param> /// <param name='resourceProviderNamespace'> /// Required. Namespace of the resource provider. /// </param> /// <param name='featureName'> /// Required. Previewed feature name in the resource provider. /// </param> /// <returns> /// Previewed feature information. /// </returns> public static FeatureResponse Register(this IFeatures operations, string resourceProviderNamespace, string featureName) { return Task.Factory.StartNew((object s) => { return ((IFeatures)s).RegisterAsync(resourceProviderNamespace, featureName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Registers for a previewed feature of a resource provider. /// </summary> /// <param name='operations'> /// Reference to the Microsoft.Azure.Management.Resources.IFeatures. /// </param> /// <param name='resourceProviderNamespace'> /// Required. Namespace of the resource provider. /// </param> /// <param name='featureName'> /// Required. Previewed feature name in the resource provider. /// </param> /// <returns> /// Previewed feature information. /// </returns> public static Task<FeatureResponse> RegisterAsync(this IFeatures operations, string resourceProviderNamespace, string featureName) { return operations.RegisterAsync(resourceProviderNamespace, featureName, CancellationToken.None); } } }
//------------------------------------------------------------------------------ // <copyright file="AsyncCopyController.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation // </copyright> //------------------------------------------------------------------------------ namespace Microsoft.WindowsAzure.Storage.DataMovement.TransferControllers { using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Net; using System.Threading; using System.Threading.Tasks; using Microsoft.WindowsAzure.Storage.Blob; using Microsoft.WindowsAzure.Storage.Blob.Protocol; using Microsoft.WindowsAzure.Storage.File; internal abstract class AsyncCopyController : TransferControllerBase { /// <summary> /// Timer to signal refresh status. /// </summary> private Timer statusRefreshTimer; /// <summary> /// Lock to protect statusRefreshTimer. /// </summary> private object statusRefreshTimerLock = new object(); /// <summary> /// Wait time between two status refresh requests. /// </summary> private long statusRefreshWaitTime = Constants.CopyStatusRefreshMinWaitTimeInMilliseconds; /// <summary> /// Indicates whether the copy job is apporaching finish. /// </summary> private bool approachingFinish = false; /// <summary> /// Request count sent with current statusRefreshWaitTime /// </summary> private long statusRefreshRequestCount = 0; /// <summary> /// Keeps track of the internal state-machine state. /// </summary> private volatile State state; /// <summary> /// Indicates whether the controller has work available /// or not for the calling code. /// </summary> private bool hasWork; /// <summary> /// Indicates the BytesCopied value of last CopyState /// </summary> private long lastBytesCopied; /// <summary> /// Initializes a new instance of the <see cref="AsyncCopyController"/> class. /// </summary> /// <param name="scheduler">Scheduler object which creates this object.</param> /// <param name="transferJob">Instance of job to start async copy.</param> /// <param name="userCancellationToken">Token user input to notify about cancellation.</param> internal AsyncCopyController( TransferScheduler scheduler, TransferJob transferJob, CancellationToken userCancellationToken) : base(scheduler, transferJob, userCancellationToken) { if (null == transferJob.Destination) { throw new ArgumentException( string.Format( CultureInfo.CurrentCulture, Resources.ParameterCannotBeNullException, "Dest"), "transferJob"); } switch(this.TransferJob.Source.Type) { case TransferLocationType.AzureBlob: this.SourceBlob = (this.TransferJob.Source as AzureBlobLocation).Blob; break; case TransferLocationType.AzureFile: this.SourceFile = (this.TransferJob.Source as AzureFileLocation).AzureFile; break; case TransferLocationType.SourceUri: this.SourceUri = (this.TransferJob.Source as UriLocation).Uri; break; default: throw new ArgumentException( string.Format( CultureInfo.CurrentCulture, Resources.ProvideExactlyOneOfThreeParameters, "Source.SourceUri", "Source.Blob", "Source.AzureFile"), "transferJob"); } // initialize the status refresh timer this.statusRefreshTimer = new Timer( new TimerCallback( delegate(object timerState) { this.hasWork = true; #if DOTNET5_4 }), null, -1, Timeout.Infinite); #else })); #endif this.SetInitialStatus(); } /// <summary> /// Internal state values. /// </summary> private enum State { FetchSourceAttributes, GetDestination, StartCopy, GetCopyState, Finished, Error, } public override bool HasWork { get { return this.hasWork; } } protected CloudBlob SourceBlob { get; private set; } protected CloudFile SourceFile { get; private set; } protected Uri SourceUri { get; private set; } protected abstract Uri DestUri { get; } public static AsyncCopyController CreateAsyncCopyController(TransferScheduler transferScheduler, TransferJob transferJob, CancellationToken cancellationToken) { if (transferJob.Destination.Type == TransferLocationType.AzureFile) { return new FileAsyncCopyController(transferScheduler, transferJob, cancellationToken); } if (transferJob.Destination.Type == TransferLocationType.AzureBlob) { return new BlobAsyncCopyController(transferScheduler, transferJob, cancellationToken); } throw new InvalidOperationException(Resources.CanOnlyCopyToFileOrBlobException); } /// <summary> /// Do work in the controller. /// A controller controls the whole transfer from source to destination, /// which could be split into several work items. This method is to let controller to do one of those work items. /// There could be several work items to do at the same time in the controller. /// </summary> /// <returns>Whether the controller has completed. This is to tell <c>TransferScheduler</c> /// whether the controller can be disposed.</returns> protected override async Task<bool> DoWorkInternalAsync() { switch (this.state) { case State.FetchSourceAttributes: await this.FetchSourceAttributesAsync(); break; case State.GetDestination: await this.GetDestinationAsync(); break; case State.StartCopy: await this.StartCopyAsync(); break; case State.GetCopyState: await this.GetCopyStateAsync(); break; case State.Finished: case State.Error: default: break; } return (State.Error == this.state || State.Finished == this.state); } /// <summary> /// Sets the state of the controller to Error, while recording /// the last occurred exception and setting the HasWork and /// IsFinished fields. /// </summary> /// <param name="ex">Exception to record.</param> protected override void SetErrorState(Exception ex) { Debug.Assert( this.state != State.Finished, "SetErrorState called, while controller already in Finished state"); this.state = State.Error; this.hasWork = false; } /// <summary> /// Taken from <c>Microsoft.WindowsAzure.Storage.Core.Util.HttpUtility</c>: Parse the http query string. /// </summary> /// <param name="query">Http query string.</param> /// <returns>A dictionary of query pairs.</returns> protected static Dictionary<string, string> ParseQueryString(string query) { Dictionary<string, string> retVal = new Dictionary<string, string>(); if (query == null || query.Length == 0) { return retVal; } // remove ? if present if (query.StartsWith("?", StringComparison.OrdinalIgnoreCase)) { query = query.Substring(1); } string[] valuePairs = query.Split(new string[] { "&" }, StringSplitOptions.RemoveEmptyEntries); foreach (string vp in valuePairs) { int equalDex = vp.IndexOf("=", StringComparison.OrdinalIgnoreCase); if (equalDex < 0) { retVal.Add(Uri.UnescapeDataString(vp), null); continue; } string key = vp.Substring(0, equalDex); string value = vp.Substring(equalDex + 1); retVal.Add(Uri.UnescapeDataString(key), Uri.UnescapeDataString(value)); } return retVal; } private void SetInitialStatus() { switch (this.TransferJob.Status) { case TransferJobStatus.NotStarted: this.TransferJob.Status = TransferJobStatus.Transfer; break; case TransferJobStatus.Transfer: break; case TransferJobStatus.Monitor: this.lastBytesCopied = this.TransferJob.Transfer.ProgressTracker.BytesTransferred; break; case TransferJobStatus.Finished: default: throw new ArgumentException(string.Format( CultureInfo.CurrentCulture, Resources.InvalidInitialEntryStatusForControllerException, this.TransferJob.Status, this.GetType().Name)); } this.SetHasWorkAfterStatusChanged(); } private void SetHasWorkAfterStatusChanged() { if (TransferJobStatus.Transfer == this.TransferJob.Status) { if (null != this.SourceUri) { this.state = State.GetDestination; } else { this.state = State.FetchSourceAttributes; } } else if(TransferJobStatus.Monitor == this.TransferJob.Status) { this.state = State.GetCopyState; } else { Debug.Fail("We should never be here"); } this.hasWork = true; } private async Task FetchSourceAttributesAsync() { Debug.Assert( this.state == State.FetchSourceAttributes, "FetchSourceAttributesAsync called, but state isn't FetchSourceAttributes"); this.hasWork = false; this.StartCallbackHandler(); try { await this.DoFetchSourceAttributesAsync(); } #if EXPECT_INTERNAL_WRAPPEDSTORAGEEXCEPTION catch (Exception ex) when (ex is StorageException || ex.InnerException is StorageException) { var e = ex as StorageException ?? ex.InnerException as StorageException; #else catch (StorageException e) { #endif HandleFetchSourceAttributesException(e); throw; } if (this.TransferJob.Source.Type == TransferLocationType.AzureBlob) { (this.TransferJob.Source as AzureBlobLocation).CheckedAccessCondition = true; } else { (this.TransferJob.Source as AzureFileLocation).CheckedAccessCondition = true; } this.state = State.GetDestination; this.hasWork = true; } private static void HandleFetchSourceAttributesException(StorageException e) { // Getting a storage exception is expected if the source doesn't // exist. For those cases that indicate the source doesn't exist // we will set a specific error state. if (e?.RequestInformation?.HttpStatusCode == (int)HttpStatusCode.NotFound) { throw new InvalidOperationException(Resources.SourceDoesNotExistException); } } private async Task GetDestinationAsync() { Debug.Assert( this.state == State.GetDestination, "GetDestinationAsync called, but state isn't GetDestination"); this.hasWork = false; this.StartCallbackHandler(); if (!this.IsForceOverwrite) { try { await this.DoFetchDestAttributesAsync(); } #if EXPECT_INTERNAL_WRAPPEDSTORAGEEXCEPTION catch (Exception e) when (e is StorageException || e.InnerException is StorageException) { var se = e as StorageException ?? e.InnerException as StorageException; #else catch (StorageException se) { #endif if (!this.HandleGetDestinationResult(se)) { throw se; } return; } } this.HandleGetDestinationResult(null); } private bool HandleGetDestinationResult(Exception e) { bool destExist = !this.IsForceOverwrite; if (null != e) { StorageException se = e as StorageException; // Getting a storage exception is expected if the destination doesn't // exist. In this case we won't error out, but set the // destExist flag to false to indicate we will copy to // a new blob/file instead of overwriting an existing one. if (null != se && null != se.RequestInformation && se.RequestInformation.HttpStatusCode == (int)HttpStatusCode.NotFound) { destExist = false; } else { this.DoHandleGetDestinationException(se); return false; } } if (this.TransferJob.Destination.Type == TransferLocationType.AzureBlob) { (this.TransferJob.Destination as AzureBlobLocation).CheckedAccessCondition = true; } else if(this.TransferJob.Destination.Type == TransferLocationType.AzureFile) { (this.TransferJob.Destination as AzureFileLocation).CheckedAccessCondition = true; } if ((TransferJobStatus.Monitor == this.TransferJob.Status) && string.IsNullOrEmpty(this.TransferJob.CopyId)) { throw new InvalidOperationException(Resources.RestartableInfoCorruptedException); } if (!this.IsForceOverwrite) { Uri sourceUri = this.GetSourceUri(); // If destination file exists, query user whether to overwrite it. this.CheckOverwrite( destExist, sourceUri.ToString(), this.DestUri.ToString()); } this.UpdateProgressAddBytesTransferred(0); this.state = State.StartCopy; this.hasWork = true; return true; } private async Task StartCopyAsync() { Debug.Assert( this.state == State.StartCopy, "StartCopyAsync called, but state isn't StartCopy"); this.hasWork = false; try { this.TransferJob.CopyId = await this.DoStartCopyAsync(); } #if EXPECT_INTERNAL_WRAPPEDSTORAGEEXCEPTION catch (Exception e) when (e is StorageException || e.InnerException is StorageException) { var se = e as StorageException ?? e.InnerException as StorageException; #else catch (StorageException se) { #endif if (!this.HandleStartCopyResult(se)) { throw; } return; } this.HandleStartCopyResult(null); } private bool HandleStartCopyResult(StorageException se) { if (null != se) { if (null != se.RequestInformation && null != se.RequestInformation.ExtendedErrorInformation && BlobErrorCodeStrings.PendingCopyOperation == se.RequestInformation.ExtendedErrorInformation.ErrorCode) { CopyState copyState = this.FetchCopyStateAsync().Result; if (null == copyState) { return false; } string baseUriString = copyState.Source.GetComponents( UriComponents.Host | UriComponents.Port | UriComponents.Path, UriFormat.UriEscaped); Uri sourceUri = this.GetSourceUri(); string ourBaseUriString = sourceUri.GetComponents(UriComponents.Host | UriComponents.Port | UriComponents.Path, UriFormat.UriEscaped); DateTimeOffset? baseSnapshot = null; DateTimeOffset? ourSnapshot = null == this.SourceBlob ? null : this.SourceBlob.SnapshotTime; string snapshotString; if (ParseQueryString(copyState.Source.Query).TryGetValue("snapshot", out snapshotString)) { if (!string.IsNullOrEmpty(snapshotString)) { DateTimeOffset snapshotTime; if (DateTimeOffset.TryParse( snapshotString, CultureInfo.CurrentCulture, DateTimeStyles.AdjustToUniversal, out snapshotTime)) { baseSnapshot = snapshotTime; } } } if (!baseUriString.Equals(ourBaseUriString) || !baseSnapshot.Equals(ourSnapshot)) { return false; } if (string.IsNullOrEmpty(this.TransferJob.CopyId)) { this.TransferJob.CopyId = copyState.CopyId; } } else { return false; } } this.TransferJob.Status = TransferJobStatus.Monitor; this.state = State.GetCopyState; this.TransferJob.Transfer.UpdateJournal(); this.hasWork = true; return true; } private async Task GetCopyStateAsync() { Debug.Assert( this.state == State.GetCopyState, "GetCopyStateAsync called, but state isn't GetCopyState"); this.hasWork = false; this.StartCallbackHandler(); CopyState copyState = null; try { copyState = await this.FetchCopyStateAsync(); } #if EXPECT_INTERNAL_WRAPPEDSTORAGEEXCEPTION catch (Exception e) when (e is StorageException || e.InnerException is StorageException) { var se = e as StorageException ?? e.InnerException as StorageException; #else catch (StorageException se) { #endif if (null != se.RequestInformation && se.RequestInformation.HttpStatusCode == (int)HttpStatusCode.NotFound) { // The reason of 404 (Not Found) may be that the destination blob has not been created yet. this.RestartTimer(); } else { throw; } } await this.HandleFetchCopyStateResultAsync(copyState); } private async Task HandleFetchCopyStateResultAsync(CopyState copyState) { if (null == copyState) { // Reach here, the destination should already exist. string exceptionMessage = string.Format( CultureInfo.CurrentCulture, Resources.FailedToRetrieveCopyStateForObjectException, this.DestUri.ToString()); throw new TransferException( TransferErrorCode.FailToRetrieveCopyStateForObject, exceptionMessage); } else { // Verify we are monitoring the right blob copying process. if (!this.TransferJob.CopyId.Equals(copyState.CopyId)) { throw new TransferException( TransferErrorCode.MismatchCopyId, Resources.MismatchFoundBetweenLocalAndServerCopyIdsException); } if (CopyStatus.Success == copyState.Status) { this.UpdateTransferProgress(copyState); this.DisposeStatusRefreshTimer(); if (null != this.TransferContext && null != this.TransferContext.SetAttributesCallback) { // If got here, we've done FetchAttributes on destination after copying completed on server, // no need to one more round of FetchAttributes anymore. await this.SetAttributesAsync(this.TransferContext.SetAttributesCallback); } this.SetFinished(); } else if (CopyStatus.Pending == copyState.Status) { this.UpdateTransferProgress(copyState); // Wait a period to restart refresh the status. this.RestartTimer(); } else { string exceptionMessage = string.Format( CultureInfo.CurrentCulture, Resources.FailedToAsyncCopyObjectException, this.GetSourceUri().ToString(), this.DestUri.ToString(), copyState.Status.ToString(), copyState.StatusDescription); // CopyStatus.Invalid | Failed | Aborted throw new TransferException( TransferErrorCode.AsyncCopyFailed, exceptionMessage); } } } private void UpdateTransferProgress(CopyState copyState) { if (null != copyState && copyState.TotalBytes.HasValue) { Debug.Assert( copyState.BytesCopied.HasValue, "BytesCopied cannot be null as TotalBytes is not null."); if (this.approachingFinish == false && copyState.TotalBytes - copyState.BytesCopied <= Constants.CopyApproachingFinishThresholdInBytes) { this.approachingFinish = true; } if (this.TransferContext != null) { long bytesTransferred = copyState.BytesCopied.Value; this.UpdateProgress(() => { this.UpdateProgressAddBytesTransferred(bytesTransferred - this.lastBytesCopied); }); this.lastBytesCopied = bytesTransferred; } } } private void SetFinished() { this.state = State.Finished; this.hasWork = false; this.FinishCallbackHandler(null); } private void RestartTimer() { if (this.approachingFinish) { this.statusRefreshWaitTime = Constants.CopyStatusRefreshMinWaitTimeInMilliseconds; } else if (this.statusRefreshRequestCount >= Constants.CopyStatusRefreshWaitTimeMaxRequestCount && this.statusRefreshWaitTime < Constants.CopyStatusRefreshMaxWaitTimeInMilliseconds) { this.statusRefreshRequestCount = 0; this.statusRefreshWaitTime *= 10; this.statusRefreshWaitTime = Math.Min(this.statusRefreshWaitTime, Constants.CopyStatusRefreshMaxWaitTimeInMilliseconds); } else if (this.statusRefreshWaitTime < Constants.CopyStatusRefreshMaxWaitTimeInMilliseconds) { this.statusRefreshRequestCount++; } // Wait a period to restart refresh the status. this.statusRefreshTimer.Change( TimeSpan.FromMilliseconds(this.statusRefreshWaitTime), new TimeSpan(-1)); } private void DisposeStatusRefreshTimer() { if (null != this.statusRefreshTimer) { lock (this.statusRefreshTimerLock) { if (null != this.statusRefreshTimer) { this.statusRefreshTimer.Dispose(); this.statusRefreshTimer = null; } } } } private Uri GetSourceUri() { if (null != this.SourceUri) { return this.SourceUri; } if (null != this.SourceBlob) { return this.SourceBlob.SnapshotQualifiedUri; } return this.SourceFile.Uri; } protected async Task DoFetchSourceAttributesAsync() { if (this.TransferJob.Source.Type == TransferLocationType.AzureBlob) { AzureBlobLocation sourceLocation = this.TransferJob.Source as AzureBlobLocation; AccessCondition accessCondition = Utils.GenerateConditionWithCustomerCondition( sourceLocation.AccessCondition, sourceLocation.CheckedAccessCondition); OperationContext operationContext = Utils.GenerateOperationContext(this.TransferContext); await sourceLocation.Blob.FetchAttributesAsync( accessCondition, Utils.GenerateBlobRequestOptions(sourceLocation.BlobRequestOptions), operationContext, this.CancellationToken); } else if(this.TransferJob.Source.Type == TransferLocationType.AzureFile) { AzureFileLocation sourceLocation = this.TransferJob.Source as AzureFileLocation; AccessCondition accessCondition = Utils.GenerateConditionWithCustomerCondition( sourceLocation.AccessCondition, sourceLocation.CheckedAccessCondition); OperationContext operationContext = Utils.GenerateOperationContext(this.TransferContext); await sourceLocation.AzureFile.FetchAttributesAsync( accessCondition, Utils.GenerateFileRequestOptions(sourceLocation.FileRequestOptions), operationContext, this.CancellationToken); } } protected abstract Task DoFetchDestAttributesAsync(); protected abstract Task<string> DoStartCopyAsync(); protected abstract void DoHandleGetDestinationException(StorageException se); protected abstract Task<CopyState> FetchCopyStateAsync(); protected abstract Task SetAttributesAsync(SetAttributesCallback setAttributes); } }
using Microsoft.TeamFoundation.DistributedTask.WebApi; using Microsoft.VisualStudio.Services.Agent.Listener; using Microsoft.VisualStudio.Services.Agent.Capabilities; using Microsoft.VisualStudio.Services.Agent.Listener.Configuration; using Moq; using System; using System.Runtime.CompilerServices; using System.Threading.Tasks; using Xunit; using System.Threading; using System.Reflection; using System.Collections.Generic; namespace Microsoft.VisualStudio.Services.Agent.Tests.Listener { public sealed class MessageListenerL0 { private AgentSettings _settings; private Mock<IConfigurationManager> _config; private Mock<IAgentServer> _agentServer; private Mock<ICredentialManager> _credMgr; private Mock<ICapabilitiesManager> _capabilitiesManager; public MessageListenerL0() { _settings = new AgentSettings { AgentId = 1, AgentName = "myagent", PoolId = 123, PoolName = "default", ServerUrl = "http://myserver", WorkFolder = "_work" }; _config = new Mock<IConfigurationManager>(); _config.Setup(x => x.LoadSettings()).Returns(_settings); _agentServer = new Mock<IAgentServer>(); _credMgr = new Mock<ICredentialManager>(); _capabilitiesManager = new Mock<ICapabilitiesManager>(); } private TestHostContext CreateTestContext([CallerMemberName] String testName = "") { TestHostContext tc = new TestHostContext(this, testName); tc.SetSingleton<IConfigurationManager>(_config.Object); tc.SetSingleton<IAgentServer>(_agentServer.Object); tc.SetSingleton<ICredentialManager>(_credMgr.Object); tc.SetSingleton<ICapabilitiesManager>(_capabilitiesManager.Object); return tc; } [Fact] [Trait("Level", "L0")] [Trait("Category", "Agent")] public async void CreatesSession() { using (TestHostContext tc = CreateTestContext()) using (var tokenSource = new CancellationTokenSource()) { Tracing trace = tc.GetTrace(); // Arrange. var expectedSession = new TaskAgentSession(); _agentServer .Setup(x => x.CreateAgentSessionAsync( _settings.PoolId, It.Is<TaskAgentSession>(y => y != null), tokenSource.Token)) .Returns(Task.FromResult(expectedSession)); _capabilitiesManager.Setup(x => x.GetCapabilitiesAsync(_settings, It.IsAny<CancellationToken>())).Returns(Task.FromResult(new Dictionary<string, string>())); _credMgr.Setup(x => x.LoadCredentials()).Returns(new Common.VssCredentials()); // Act. MessageListener listener = new MessageListener(); listener.Initialize(tc); bool result = await listener.CreateSessionAsync(tokenSource.Token); trace.Info("result: {0}", result); // Assert. Assert.True(result); _agentServer .Verify(x => x.CreateAgentSessionAsync( _settings.PoolId, It.Is<TaskAgentSession>(y => y != null), tokenSource.Token), Times.Once()); } } [Fact] [Trait("Level", "L0")] [Trait("Category", "Agent")] public async void DeleteSession() { using (TestHostContext tc = CreateTestContext()) using (var tokenSource = new CancellationTokenSource()) { Tracing trace = tc.GetTrace(); // Arrange. var expectedSession = new TaskAgentSession(); PropertyInfo sessionIdProperty = expectedSession.GetType().GetProperty("SessionId", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public); Assert.NotNull(sessionIdProperty); sessionIdProperty.SetValue(expectedSession, Guid.NewGuid()); _agentServer .Setup(x => x.CreateAgentSessionAsync( _settings.PoolId, It.Is<TaskAgentSession>(y => y != null), tokenSource.Token)) .Returns(Task.FromResult(expectedSession)); _capabilitiesManager.Setup(x => x.GetCapabilitiesAsync(_settings, It.IsAny<CancellationToken>())).Returns(Task.FromResult(new Dictionary<string, string>())); _credMgr.Setup(x => x.LoadCredentials()).Returns(new Common.VssCredentials()); // Act. MessageListener listener = new MessageListener(); listener.Initialize(tc); bool result = await listener.CreateSessionAsync(tokenSource.Token); Assert.True(result); _agentServer .Setup(x => x.DeleteAgentSessionAsync( _settings.PoolId, expectedSession.SessionId, It.IsAny<CancellationToken>())) .Returns(Task.CompletedTask); await listener.DeleteSessionAsync(); //Assert _agentServer .Verify(x => x.DeleteAgentSessionAsync( _settings.PoolId, expectedSession.SessionId, It.IsAny<CancellationToken>()), Times.Once()); } } [Fact] [Trait("Level", "L0")] [Trait("Category", "Agent")] public async void GetNextMessage() { using (TestHostContext tc = CreateTestContext()) using (var tokenSource = new CancellationTokenSource()) { Tracing trace = tc.GetTrace(); // Arrange. var expectedSession = new TaskAgentSession(); PropertyInfo sessionIdProperty = expectedSession.GetType().GetProperty("SessionId", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public); Assert.NotNull(sessionIdProperty); sessionIdProperty.SetValue(expectedSession, Guid.NewGuid()); _agentServer .Setup(x => x.CreateAgentSessionAsync( _settings.PoolId, It.Is<TaskAgentSession>(y => y != null), tokenSource.Token)) .Returns(Task.FromResult(expectedSession)); _capabilitiesManager.Setup(x => x.GetCapabilitiesAsync(_settings, It.IsAny<CancellationToken>())).Returns(Task.FromResult(new Dictionary<string, string>())); _credMgr.Setup(x => x.LoadCredentials()).Returns(new Common.VssCredentials()); // Act. MessageListener listener = new MessageListener(); listener.Initialize(tc); bool result = await listener.CreateSessionAsync(tokenSource.Token); Assert.True(result); var arMessages = new TaskAgentMessage[] { new TaskAgentMessage { Body = "somebody1", MessageId = 4234, MessageType = JobRequestMessageTypes.AgentJobRequest }, new TaskAgentMessage { Body = "somebody2", MessageId = 4235, MessageType = JobCancelMessage.MessageType }, null, //should be skipped by GetNextMessageAsync implementation null, new TaskAgentMessage { Body = "somebody3", MessageId = 4236, MessageType = JobRequestMessageTypes.AgentJobRequest } }; var messages = new Queue<TaskAgentMessage>(arMessages); _agentServer .Setup(x => x.GetAgentMessageAsync( _settings.PoolId, expectedSession.SessionId, It.IsAny<long?>(), tokenSource.Token)) .Returns(async (Int32 poolId, Guid sessionId, Int64? lastMessageId, CancellationToken cancellationToken) => { await Task.Yield(); return messages.Dequeue(); }); TaskAgentMessage message1 = await listener.GetNextMessageAsync(tokenSource.Token); TaskAgentMessage message2 = await listener.GetNextMessageAsync(tokenSource.Token); TaskAgentMessage message3 = await listener.GetNextMessageAsync(tokenSource.Token); Assert.Equal(arMessages[0], message1); Assert.Equal(arMessages[1], message2); Assert.Equal(arMessages[4], message3); //Assert _agentServer .Verify(x => x.GetAgentMessageAsync( _settings.PoolId, expectedSession.SessionId, It.IsAny<long?>(), tokenSource.Token), Times.Exactly(arMessages.Length)); } } } }
// // TableViewBackend.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 MonoMac.AppKit; using Xwt.Backends; using System.Collections.Generic; using MonoMac.Foundation; namespace Xwt.Mac { public abstract class TableViewBackend<T,S>: ViewBackend<NSScrollView,S>, ITableViewBackend, ICellSource where T:NSTableView where S:ITableViewEventSink { List<NSTableColumn> cols = new List<NSTableColumn> (); protected NSTableView Table; ScrollView scroll; NSObject selChangeObserver; NormalClipView clipView; public TableViewBackend () { } public override void Initialize () { Table = CreateView (); scroll = new ScrollView (); clipView = new NormalClipView (); clipView.Scrolled += OnScrolled; scroll.ContentView = clipView; scroll.DocumentView = Table; scroll.BorderType = NSBorderType.BezelBorder; ViewObject = scroll; Widget.AutoresizingMask = NSViewResizingMask.HeightSizable | NSViewResizingMask.WidthSizable; Widget.AutoresizesSubviews = true; } protected override void Dispose (bool disposing) { base.Dispose (disposing); Util.DrainObjectCopyPool (); } public ScrollPolicy VerticalScrollPolicy { get { if (scroll.AutohidesScrollers && scroll.HasVerticalScroller) return ScrollPolicy.Automatic; else if (scroll.HasVerticalScroller) return ScrollPolicy.Always; else return ScrollPolicy.Never; } set { switch (value) { case ScrollPolicy.Automatic: scroll.AutohidesScrollers = true; scroll.HasVerticalScroller = true; break; case ScrollPolicy.Always: scroll.AutohidesScrollers = false; scroll.HasVerticalScroller = true; break; case ScrollPolicy.Never: scroll.HasVerticalScroller = false; break; } } } public ScrollPolicy HorizontalScrollPolicy { get { if (scroll.AutohidesScrollers && scroll.HasHorizontalScroller) return ScrollPolicy.Automatic; else if (scroll.HasHorizontalScroller) return ScrollPolicy.Always; else return ScrollPolicy.Never; } set { switch (value) { case ScrollPolicy.Automatic: scroll.AutohidesScrollers = true; scroll.HasHorizontalScroller = true; break; case ScrollPolicy.Always: scroll.AutohidesScrollers = false; scroll.HasHorizontalScroller = true; break; case ScrollPolicy.Never: scroll.HasHorizontalScroller = false; break; } } } ScrollControlBackend vertScroll; public IScrollControlBackend CreateVerticalScrollControl () { if (vertScroll == null) vertScroll = new ScrollControlBackend (ApplicationContext, scroll, true); return vertScroll; } ScrollControlBackend horScroll; public IScrollControlBackend CreateHorizontalScrollControl () { if (horScroll == null) horScroll = new ScrollControlBackend (ApplicationContext, scroll, false); return horScroll; } void OnScrolled (object o, EventArgs e) { if (vertScroll != null) vertScroll.NotifyValueChanged (); if (horScroll != null) horScroll.NotifyValueChanged (); } protected override Size GetNaturalSize () { return EventSink.GetDefaultNaturalSize (); } protected abstract NSTableView CreateView (); protected abstract string SelectionChangeEventName { get; } public override void EnableEvent (object eventId) { base.EnableEvent (eventId); if (eventId is TableViewEvent) { switch ((TableViewEvent)eventId) { case TableViewEvent.SelectionChanged: selChangeObserver = NSNotificationCenter.DefaultCenter.AddObserver (new NSString (SelectionChangeEventName), HandleTreeSelectionDidChange, Table); break; } } } public override void DisableEvent (object eventId) { base.DisableEvent (eventId); if (eventId is TableViewEvent) { switch ((TableViewEvent)eventId) { case TableViewEvent.SelectionChanged: if (selChangeObserver != null) NSNotificationCenter.DefaultCenter.RemoveObserver (selChangeObserver); break; } } } void HandleTreeSelectionDidChange (NSNotification notif) { ApplicationContext.InvokeUserCode (delegate { EventSink.OnSelectionChanged (); }); } public void SetSelectionMode (SelectionMode mode) { Table.AllowsMultipleSelection = mode == SelectionMode.Multiple; } public virtual NSTableColumn AddColumn (ListViewColumn col) { var tcol = new NSTableColumn (); tcol.Editable = true; cols.Add (tcol); var c = CellUtil.CreateCell (ApplicationContext, Table, this, col.Views, cols.Count - 1); tcol.DataCell = c; Table.AddColumn (tcol); var hc = new NSTableHeaderCell (); hc.Title = col.Title ?? ""; tcol.HeaderCell = hc; Widget.InvalidateIntrinsicContentSize (); return tcol; } object IColumnContainerBackend.AddColumn (ListViewColumn col) { return AddColumn (col); } public void RemoveColumn (ListViewColumn col, object handle) { Table.RemoveColumn ((NSTableColumn)handle); } public void UpdateColumn (ListViewColumn col, object handle, ListViewColumnChange change) { NSTableColumn tcol = (NSTableColumn) handle; tcol.DataCell = CellUtil.CreateCell (ApplicationContext, Table, this, col.Views, cols.IndexOf (tcol)); } public void SelectAll () { Table.SelectAll (null); } public void UnselectAll () { Table.DeselectAll (null); } public void ScrollToRow (int row) { Table.ScrollRowToVisible (row); } public abstract object GetValue (object pos, int nField); public abstract void SetValue (object pos, int nField, object value); public abstract void SetCurrentEventRow (object pos); float ICellSource.RowHeight { get { return Table.RowHeight; } set { Table.RowHeight = value; } } public bool BorderVisible { get { return scroll.BorderType == NSBorderType.BezelBorder;} set { scroll.BorderType = value ? NSBorderType.BezelBorder : NSBorderType.NoBorder; } } public bool HeadersVisible { get { return Table.HeaderView != null; } set { if (value) { if (Table.HeaderView == null) Table.HeaderView = new NSTableHeaderView (); } else { Table.HeaderView = null; } } } public GridLines GridLinesVisible { get { return Table.GridStyleMask.ToXwtValue (); } set { Table.GridStyleMask = value.ToMacValue (); } } } class ScrollView: NSScrollView, IViewObject { public ViewBackend Backend { get; set; } public NSView View { get { return this; } } } }
/* Copyright 2006 - 2010 Intel Corporation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Net; using System.Threading; using System.Collections; using System.Runtime.Serialization; using OpenSource.UPnP; namespace UPnPValidator.BasicTests { /// <summary> /// Summary description for UPnPTestDiscovery. /// </summary> [Serializable()] public class UPnPTestDiscovery : BasicTestGroup { // Specific Test Variables UPnPTestStates NOTIFY = UPnPTestStates.Pass; UPnPTestStates DISCOVERY = UPnPTestStates.Pass; UPnPTestStates MX = UPnPTestStates.Pass; private Hashtable NotifyTable = new Hashtable(); private Hashtable MSEARCHTable = new Hashtable(); [NonSerialized()] private ManualResetEvent MRE; private AsyncSocket ASocket, ASocket2; private UPnPDevice TestDevice; private DataPointAnalyzer DPA = new DataPointAnalyzer(); private int Cache = -1; //private DateTime StartTime; //private int TimeLeft = 0; //private int TotalTime = 0; private string sample = ""; private string sample2 = ""; public UPnPTestDiscovery() { Category = "Discovery"; GroupName = "Discovery/Notification Test Suite"; Description = "Discovery Test Suite. Tests various aspects of UPnP device discovery, network searching, advertizing and check reply timing and correct formatting of received messages."; AddTest("MX Value", ""); AddTest("Notifications", ""); AddTest("Discovery", ""); Reset(); } public override void Reset() { base.Reset(); if (MRE == null) MRE = new ManualResetEvent(false); } public override void Start(UPnPDevice device) { UPnPDevice d = device; while (d.ParentDevice != null) { d = d.ParentDevice; } TestDevice = d; ASocket = new AsyncSocket(4096); ASocket.Attach(new IPEndPoint(TestDevice.InterfaceToHost, 0), System.Net.Sockets.ProtocolType.Udp); ASocket.SetTTL(4); ASocket.AddMembership((IPEndPoint)ASocket.LocalEndPoint, IPAddress.Parse("239.255.255.250")); ASocket.OnReceive += new AsyncSocket.OnReceiveHandler(ReceiveSink); ASocket.Begin(); ASocket2 = new AsyncSocket(4096); ASocket2.Attach(new IPEndPoint(TestDevice.InterfaceToHost, 1900), System.Net.Sockets.ProtocolType.Udp); ASocket2.SetTTL(2); ASocket2.AddMembership((IPEndPoint)ASocket.LocalEndPoint, IPAddress.Parse("239.255.255.250")); ASocket2.OnReceive += new AsyncSocket.OnReceiveHandler(ReceiveSink2); Validate_MSEARCH_RESPONSETIME(); Validate_NOTIFY(); Validate_DISCOVERY(); UPnPTestStates RetState = UPnPTestStates.Pass; if (NOTIFY == UPnPTestStates.Failed || DISCOVERY == UPnPTestStates.Failed) { RetState = UPnPTestStates.Failed; } else { if (NOTIFY == UPnPTestStates.Warn || DISCOVERY == UPnPTestStates.Warn || MX == UPnPTestStates.Warn) { RetState = UPnPTestStates.Warn; } } state = RetState; } private void Validate_MSEARCH_RESPONSETIME() { AddMessage(0, "Testing Notifications"); HTTPMessage r = new HTTPMessage(); r.Directive = "M-SEARCH"; r.DirectiveObj = "*"; r.AddTag("MX", "10"); r.AddTag("ST", "uuid:" + TestDevice.UniqueDeviceName); r.AddTag("Host", "239.255.255.250:1900"); r.AddTag("MAN", "\"ssdp:discover\""); byte[] buf = r.RawPacket; IPEndPoint dest = new IPEndPoint(IPAddress.Parse("239.255.255.250"), 1900); Cache = -1; MRE.Reset(); StartTime = DateTime.Now; ASocket.Send(buf, 0, buf.Length, dest); StartCountDown(0, 90); MRE.WaitOne(15000, false); AbortCountDown(); MRE.Reset(); StartTime = DateTime.Now; ASocket.Send(buf, 0, buf.Length, dest); StartCountDown(15, 90); MRE.WaitOne(15000, false); AbortCountDown(); MRE.Reset(); StartTime = DateTime.Now; ASocket.Send(buf, 0, buf.Length, dest); StartCountDown(30, 90); MRE.WaitOne(15000, false); AbortCountDown(); MRE.Reset(); StartTime = DateTime.Now; ASocket.Send(buf, 0, buf.Length, dest); StartCountDown(45, 90); MRE.WaitOne(15000, false); AbortCountDown(); MRE.Reset(); StartTime = DateTime.Now; ASocket.Send(buf, 0, buf.Length, dest); StartCountDown(60, 90); MRE.WaitOne(15000, false); AbortCountDown(); MRE.Reset(); StartTime = DateTime.Now; ASocket.Send(buf, 0, buf.Length, dest); StartCountDown(75, 90); MRE.WaitOne(15000, false); AbortCountDown(); double s = 0; try { s = DPA.StandardDeviation.TotalSeconds; } catch (DivideByZeroException) {} if (s < (double)1.50) { AddEvent(LogImportance.Medium, "M-SEARCH, MX Value", "WARNING: Device not choosing Random interval based on MX value <<Standard Deviation: " + s.ToString() + ">>"); Results.Add("M-SEARCH Response time not choosing Random interval based on MX value"); MX = UPnPTestStates.Warn; SetState("MX Value", UPnPTestStates.Warn); } else { MX = UPnPTestStates.Pass; AddEvent(LogImportance.Remark, "M-SEARCH, MX Value", "Random MX interval: <<Standard Deviation: " + s.ToString() + ">> OK"); Results.Add("M-SEARCH Response time OK"); SetState("MX Value", UPnPTestStates.Pass); } } private void ReceiveSink(AsyncSocket sender, Byte[] buffer, int HeadPointer, int BufferSize, int BytesRead, IPEndPoint source, IPEndPoint remote) { DateTime EndTime = DateTime.Now; DText P = new DText(); HTTPMessage msg = HTTPMessage.ParseByteArray(buffer, 0, BufferSize); string USN = msg.GetTag("USN"); string UDN = USN; if (USN.IndexOf("::") != -1) { UDN = USN.Substring(0, USN.IndexOf("::")); } UDN = UDN.Substring(5); sender.BufferBeginPointer = BufferSize; if (UDN != TestDevice.UniqueDeviceName) return; string cc = msg.GetTag("Cache-Control"); P.ATTRMARK = "="; P[0] = cc; cc = P[2].Trim(); this.Cache = int.Parse(cc); DPA.AddDataPoint(EndTime.Subtract(StartTime)); MRE.Set(); } private void ReceiveSink2(AsyncSocket sender, Byte[] buffer, int HeadPointer, int BufferSize, int BytesRead, IPEndPoint source, IPEndPoint remote) { HTTPMessage msg = HTTPMessage.ParseByteArray(buffer, 0, BufferSize); if (msg.Directive != "NOTIFY") { sender.BufferBeginPointer = BufferSize; return; } string USN = msg.GetTag("USN"); string UDN; if (USN.IndexOf("::") != -1) { UDN = USN.Substring(0, USN.IndexOf("::")); } else { UDN = USN; } UDN = UDN.Substring(5); if (msg.GetTag("NTS").Trim() == "ssdp:alive") { if (TestDevice.GetDevice(UDN) != null) { NotifyTable[msg.GetTag("NT")] = DateTime.Now; } } sender.BufferBeginPointer = BufferSize; } private void Validate_NOTIFY() { ManualResetEvent M = new ManualResetEvent(false); // Check to see if received all the NOTIFY packets NotifyTable.Clear(); ASocket2.Begin(); M.Reset(); StartCountDown(0, Cache); M.WaitOne(Cache * 1000, false); AbortCountDown(); ASocket2.OnReceive -= new AsyncSocket.OnReceiveHandler(ReceiveSink2); if (NotifyTable.ContainsKey("upnp:rootdevice")) { AddEvent(LogImportance.Remark, "Notifications", "NOTIFY <<upnp:rootdevice>> OK"); } else { NOTIFY = UPnPTestStates.Failed; AddEvent(LogImportance.Critical, "Notifications", "NOTIFY <<upnp:rootdevice>> MISSING/LATE"); } ValidateNotifyTable(TestDevice); if (NOTIFY == UPnPTestStates.Pass) { Results.Add("Notifications OK"); } else { Results.Add("One ore more NOTIFY packets were MISSING"); } SetState("Notifications", NOTIFY); } private HTTPMessage[] MSEARCH(UPnPDevice device) { ArrayList PacketList = new ArrayList(); foreach (UPnPDevice d in device.EmbeddedDevices) { foreach (HTTPMessage m in MSEARCH(d)) { PacketList.Add(m); } } HTTPMessage rq; rq = new HTTPMessage(); rq.Directive = "M-SEARCH"; rq.DirectiveObj = "*"; rq.AddTag("MX", "5"); rq.AddTag("ST", "uuid:" + device.UniqueDeviceName); rq.AddTag("Host", "239.255.255.250:1900"); rq.AddTag("MAN", "\"ssdp:discover\""); PacketList.Add(rq); rq = new HTTPMessage(); rq.Directive = "M-SEARCH"; rq.DirectiveObj = "*"; rq.AddTag("MX", "5"); rq.AddTag("ST", device.DeviceURN); rq.AddTag("Host", "239.255.255.250:1900"); rq.AddTag("MAN", "\"ssdp:discover\""); PacketList.Add(rq); foreach (UPnPService s in device.Services) { rq = new HTTPMessage(); rq.Directive = "M-SEARCH"; rq.DirectiveObj = "*"; rq.AddTag("MX", "5"); rq.AddTag("ST", s.ServiceURN); rq.AddTag("Host", "239.255.255.250:1900"); rq.AddTag("MAN", "\"ssdp:discover\""); PacketList.Add(rq); } return ((HTTPMessage[])PacketList.ToArray(typeof(HTTPMessage))); } private UPnPService FetchAService(UPnPDevice d) { UPnPService RetVal = null; if (d.Services.Length != 0) { return (d.Services[0]); } foreach (UPnPDevice ed in d.EmbeddedDevices) { RetVal = FetchAService(ed); if (RetVal != null) { return (RetVal); } } return (null); } private void Validate_DISCOVERY() { //Test all types of M-SEARCH, both valid and invalid MSEARCHTable.Clear(); ASocket.OnReceive -= new AsyncSocket.OnReceiveHandler(ReceiveSink); ASocket.OnReceive += new AsyncSocket.OnReceiveHandler(MSEARCHSink); HTTPMessage rq = new HTTPMessage(); byte[] rbuf; IPEndPoint d = new IPEndPoint(IPAddress.Parse("239.255.255.250"), 1900); rq.Directive = "M-SEARCH"; rq.DirectiveObj = "*"; rq.AddTag("MX", "5"); rq.AddTag("Host", "239.255.255.250:1900"); rq.AddTag("MAN", "\"ssdp:discover\""); rq.AddTag("ST", "ssdp:all"); rbuf = rq.RawPacket; ASocket.Send(rbuf, 0, rbuf.Length, d); MRE.Reset(); StartCountDown(0, 91); MRE.WaitOne(8000, false); AbortCountDown(); if (MSEARCHTable.ContainsKey("upnp:rootdevice")) { AddEvent(LogImportance.Remark, "Discovery", "MSEARCH <<ssdp:all / upnp:rootdevice>> OK"); } else { DISCOVERY = UPnPTestStates.Failed; AddEvent(LogImportance.Critical, "Discovery", "MSEARCH <<ssdp:all / upnp:rootdevice>> MISSING"); } foreach (HTTPMessage m in MSEARCH(TestDevice)) { if (MSEARCHTable.ContainsKey(m.GetTag("ST").Trim())) { AddEvent(LogImportance.Remark, "Discovery", "MSEARCH <<ssdp:all / " + m.GetTag("ST").Trim() + ">> OK"); } else { DISCOVERY = UPnPTestStates.Failed; AddEvent(LogImportance.Critical, "Discovery", "MSEARCH <<ssdp:all / " + m.GetTag("ST").Trim() + ">> MISSING"); } } // Test MSEARCH upnp:rootdevice, and others MSEARCHTable.Clear(); rq.AddTag("ST", "upnp:rootdevice"); rbuf = rq.RawPacket; ASocket.Send(rbuf, 0, rbuf.Length, d); foreach (HTTPMessage m in MSEARCH(TestDevice)) { this.sample2 += "\r\n\r\n" + m.StringPacket; ASocket.Send(m.RawPacket, 0, m.RawPacket.Length, d); } MRE.Reset(); StartCountDown(8, 91); MRE.WaitOne(8000, false); AbortCountDown(); ASocket.OnReceive -= new AsyncSocket.OnReceiveHandler(MSEARCHSink); if (MSEARCHTable.ContainsKey("upnp:rootdevice")) { AddEvent(LogImportance.Remark, "Discovery", "MSEARCH <<upnp:rootdevice>> OK"); } else { DISCOVERY = UPnPTestStates.Failed; AddEvent(LogImportance.Critical, "Discovery", "MSEARCH <<upnp:rootdevice>> MISSING"); } foreach (HTTPMessage m in MSEARCH(TestDevice)) { if (MSEARCHTable.ContainsKey(m.GetTag("ST").Trim())) { AddEvent(LogImportance.Remark, "Discovery", "MSEARCH <<" + m.GetTag("ST").Trim() + ">> OK"); } else { DISCOVERY = UPnPTestStates.Failed; AddEvent(LogImportance.Critical, "Discovery", "MSEARCH <<" + m.GetTag("ST").Trim() + ">> MISSING"); } } // Test Invalid MSEARCHes string ST = ""; MSEARCHTable.Clear(); ASocket.OnReceive += new AsyncSocket.OnReceiveHandler(BadMSEARCHSink); rq = new HTTPMessage(); rq.Directive = "M-SEARCH"; rq.DirectiveObj = "*"; rq.AddTag("MX", "2"); rq.AddTag("Host", "239.255.255.250:1900"); rq.AddTag("MAN", "\"ssdp:discover\""); rq.AddTag("ST", "uuid:___" + TestDevice.UniqueDeviceName + "___"); rbuf = rq.RawPacket; ASocket.Send(rbuf, 0, rbuf.Length, d); MRE.Reset(); StartCountDown(16, 91); MRE.WaitOne(5000, false); AbortCountDown(); if (MSEARCHTable.Count != 0) { DISCOVERY = UPnPTestStates.Failed; AddEvent(LogImportance.High, "Discovery", "MSEARCH <<NonExistent UDN>> Unexpected Response"); } else { AddEvent(LogImportance.Remark, "Discovery", "MSEARCH <<NonExistent UDN>> OK"); } MSEARCHTable.Clear(); ST = TestDevice.DeviceURN; int i = ST.LastIndexOf(":"); if (i == -1) { DISCOVERY = UPnPTestStates.Failed; AddEvent(LogImportance.High, "Discovery", "Can't parse DeviceURN"); return; } ST = ST.Substring(0, i); ST = ST + ":" + ((int)(int.Parse(TestDevice.Version) + 5)).ToString(); rq.AddTag("ST", ST); rbuf = rq.RawPacket; ASocket.Send(rbuf, 0, rbuf.Length, d); MRE.Reset(); StartCountDown(21, 91); MRE.WaitOne(5000, false); AbortCountDown(); if (MSEARCHTable.Count != 0) { DISCOVERY = UPnPTestStates.Failed; AddEvent(LogImportance.High, "Discovery", "MSEARCH <<Existing Device Type, Bad Version>> Unexpected Response"); } else { AddEvent(LogImportance.Remark, "Discovery", "MSEARCH <<Existing Device Type, Bad Version>> OK"); } MSEARCHTable.Clear(); UPnPService _S = FetchAService(TestDevice); ST = _S.ServiceURN; ST = ST.Substring(0, ST.LastIndexOf(":")); ST = ST + ":" + ((int)(int.Parse(_S.Version) + 5)).ToString(); rq.AddTag("ST", ST); rbuf = rq.RawPacket; ASocket.Send(rbuf, 0, rbuf.Length, d); MRE.Reset(); StartCountDown(26, 91); MRE.WaitOne(5000, false); AbortCountDown(); if (MSEARCHTable.Count != 0) { DISCOVERY = UPnPTestStates.Failed; AddEvent(LogImportance.High, "Discovery", "MSEARCH <<Existing Service Type, Bad Version>> Unexpected Response"); } else { AddEvent(LogImportance.Remark, "Discovery", "MSEARCH <<Existing Service Type, Bad Version>> OK"); } // Test MSEARCH No * MSEARCHTable.Clear(); rq = new HTTPMessage(); rq.Directive = "M-SEARCH"; rq.DirectiveObj = ""; rq.AddTag("MX", "2"); rq.AddTag("Host", "239.255.255.250:1900"); rq.AddTag("MAN", "\"ssdp:discover\""); rq.AddTag("ST", "upnp:rootdevice"); rbuf = rq.RawPacket; ASocket.Send(rbuf, 0, rbuf.Length, d); MRE.Reset(); StartCountDown(31, 91); MRE.WaitOne(5000, false); AbortCountDown(); if (MSEARCHTable.Count != 0) { DISCOVERY = UPnPTestStates.Failed; AddEvent(LogImportance.High, "Discovery", "MSEARCH <<No *>> Unexpected Response"); } else { AddEvent(LogImportance.Remark, "Discovery", "MSEARCH <<No *>> OK"); } MSEARCHTable.Clear(); rq.DirectiveObj = "/"; rbuf = rq.RawPacket; ASocket.Send(rbuf, 0, rbuf.Length, d); MRE.Reset(); StartCountDown(36, 91); MRE.WaitOne(5000, false); AbortCountDown(); if (MSEARCHTable.Count != 0) { DISCOVERY = UPnPTestStates.Failed; AddEvent(LogImportance.High, "Discovery", "MSEARCH <<Not *>> Unexpected Response"); } else { AddEvent(LogImportance.Remark, "Discovery", "MSEARCH <<Not *>> OK"); } MSEARCHTable.Clear(); rq = new HTTPMessage(); rq.Directive = "M-SEARCH"; rq.DirectiveObj = ""; rq.AddTag("MX", "2"); rq.AddTag("Host", "239.255.255.250:1900"); rq.AddTag("MAN", "\"ssdp:discover\""); rq.AddTag("ST", "upnp:rootdevice"); rq.Version = "1.0"; rbuf = rq.RawPacket; ASocket.Send(rbuf, 0, rbuf.Length, d); MRE.Reset(); StartCountDown(41, 91); MRE.WaitOne(5000, false); AbortCountDown(); if (MSEARCHTable.Count != 0) { DISCOVERY = UPnPTestStates.Failed; AddEvent(LogImportance.High, "Discovery", "MSEARCH <<Version = 1.0>> Unexpected Response"); } else { AddEvent(LogImportance.Remark, "Discovery", "MSEARCH <<Version = 1.0>> OK"); } MSEARCHTable.Clear(); rq.DirectiveObj = "*"; rq.Version = ""; rbuf = rq.RawPacket; ASocket.Send(rbuf, 0, rbuf.Length, d); MRE.Reset(); StartCountDown(46, 91); MRE.WaitOne(5000, false); AbortCountDown(); if (MSEARCHTable.Count != 0) { DISCOVERY = UPnPTestStates.Failed; AddEvent(LogImportance.High, "Discovery", "MSEARCH <<No Version>> Unexpected Response"); } else { AddEvent(LogImportance.Remark, "Discovery", "MSEARCH <<No Version>> OK"); } MSEARCHTable.Clear(); rq.Version = "1.1"; rq.RemoveTag("MAN"); rbuf = rq.RawPacket; ASocket.Send(rbuf, 0, rbuf.Length, d); MRE.Reset(); StartCountDown(51, 91); MRE.WaitOne(5000, false); AbortCountDown(); if (MSEARCHTable.Count != 0) { DISCOVERY = UPnPTestStates.Failed; AddEvent(LogImportance.High, "Discovery", "MSEARCH <<No MAN>> Unexpected Response"); } else { AddEvent(LogImportance.Remark, "Discovery", "MSEARCH <<No MAN>> OK"); } MSEARCHTable.Clear(); rq.AddTag("MAN", "\"ssdp:discover\""); rq.RemoveTag("MX"); rbuf = rq.RawPacket; ASocket.Send(rbuf, 0, rbuf.Length, d); MRE.Reset(); StartCountDown(56, 91); MRE.WaitOne(5000, false); AbortCountDown(); if (MSEARCHTable.Count != 0) { DISCOVERY = UPnPTestStates.Failed; AddEvent(LogImportance.High, "Discovery", "MSEARCH <<No MX>> Unexpected Response"); } else { AddEvent(LogImportance.Remark, "Discovery", "MSEARCH <<No MX>> OK"); } MSEARCHTable.Clear(); rq.AddTag("MX", ""); rbuf = rq.RawPacket; ASocket.Send(rbuf, 0, rbuf.Length, d); MRE.Reset(); StartCountDown(61, 91); MRE.WaitOne(5000, false); AbortCountDown(); if (MSEARCHTable.Count != 0) { DISCOVERY = UPnPTestStates.Failed; AddEvent(LogImportance.High, "Discovery", "MSEARCH <<MX Empty>> Unexpected Response"); } else { AddEvent(LogImportance.Remark, "Discovery", "MSEARCH <<MX Empty>> OK"); } MSEARCHTable.Clear(); rq.AddTag("MX", "Z"); rbuf = rq.RawPacket; ASocket.Send(rbuf, 0, rbuf.Length, d); MRE.Reset(); StartCountDown(66, 91); MRE.WaitOne(5000, false); AbortCountDown(); if (MSEARCHTable.Count != 0) { DISCOVERY = UPnPTestStates.Failed; AddEvent(LogImportance.High, "Discovery", "MSEARCH <<MX Not Integer>> Unexpected Response"); } else { AddEvent(LogImportance.Remark, "Discovery", "MSEARCH <<MX Not Integer>> OK"); } MSEARCHTable.Clear(); rq.AddTag("MX", "-1"); rbuf = rq.RawPacket; ASocket.Send(rbuf, 0, rbuf.Length, d); MRE.Reset(); StartCountDown(71, 91); MRE.WaitOne(5000, false); AbortCountDown(); if (MSEARCHTable.Count != 0) { DISCOVERY = UPnPTestStates.Failed; AddEvent(LogImportance.High, "Discovery", "MSEARCH <<MX Negative>> Unexpected Response"); } else { AddEvent(LogImportance.Remark, "Discovery", "MSEARCH <<MX Negative>> OK"); } MSEARCHTable.Clear(); rq.AddTag("MX", "2"); rq.RemoveTag("ST"); rbuf = rq.RawPacket; ASocket.Send(rbuf, 0, rbuf.Length, d); MRE.Reset(); StartCountDown(76, 91); MRE.WaitOne(5000, false); AbortCountDown(); if (MSEARCHTable.Count != 0) { DISCOVERY = UPnPTestStates.Failed; AddEvent(LogImportance.High, "Discovery", "MSEARCH <<No ST>> Unexpected Response"); } else { AddEvent(LogImportance.Remark, "Discovery", "MSEARCH <<No ST>> OK"); } MSEARCHTable.Clear(); rq.AddTag("ST", ""); rbuf = rq.RawPacket; ASocket.Send(rbuf, 0, rbuf.Length, d); MRE.Reset(); StartCountDown(81, 91); MRE.WaitOne(5000, false); AbortCountDown(); if (MSEARCHTable.Count != 0) { DISCOVERY = UPnPTestStates.Failed; AddEvent(LogImportance.High, "Discovery", "MSEARCH <<ST Empty>> Unexpected Response"); } else { AddEvent(LogImportance.Remark, "Discovery", "MSEARCH <<ST Empty>> OK"); } MSEARCHTable.Clear(); rq.AddTag("ST", "ABCDEFG"); rbuf = rq.RawPacket; ASocket.Send(rbuf, 0, rbuf.Length, d); MRE.Reset(); StartCountDown(86, 91); MRE.WaitOne(5000, false); AbortCountDown(); if (MSEARCHTable.Count != 0) { DISCOVERY = UPnPTestStates.Failed; AddEvent(LogImportance.High, "Discovery", "MSEARCH <<ST Invalid>> Unexpected Response"); } else { AddEvent(LogImportance.Remark, "Discovery", "MSEARCH <<ST Invalid>> OK"); } SetState("Discovery", DISCOVERY); if (DISCOVERY == UPnPTestStates.Pass) { Results.Add("Discovery mechanism OK"); } else { Results.Add("Discovery mechanism is not behaving correctly"); } } private void MSEARCHSink(AsyncSocket sender, Byte[] buffer, int HeadPointer, int BufferSize, int BytesRead, IPEndPoint source, IPEndPoint remote) { HTTPMessage msg = HTTPMessage.ParseByteArray(buffer, HeadPointer, BufferSize); DText P = new DText(); string USN = msg.GetTag("USN"); string UDN; if (USN.IndexOf("::") != -1) { UDN = USN.Substring(0, USN.IndexOf("::")); } else { UDN = USN; } UDN = UDN.Substring(5); sender.BufferBeginPointer = BufferSize; if (TestDevice.GetDevice(UDN) == null) { return; } lock (MSEARCHTable) { this.sample += "\r\n" + msg.GetTag("ST"); MSEARCHTable[msg.GetTag("ST").Trim()] = ""; } } private void BadMSEARCHSink(AsyncSocket sender, Byte[] buffer, int HeadPointer, int BufferSize, int BytesRead, IPEndPoint source, IPEndPoint remote) { HTTPMessage msg = HTTPMessage.ParseByteArray(buffer, HeadPointer, BufferSize); if (remote.Address.ToString() == TestDevice.RemoteEndPoint.Address.ToString()) { lock (MSEARCHTable) { MSEARCHTable[remote.Address.ToString()] = msg; } } } private void ValidateNotifyTable(UPnPDevice d) { foreach (UPnPDevice ed in d.EmbeddedDevices) { ValidateNotifyTable(ed); } if (NotifyTable.ContainsKey(d.DeviceURN)) { AddEvent(LogImportance.Remark, "Notifications", "NOTIFY <<" + d.DeviceURN + ">> OK"); } else { NOTIFY = UPnPTestStates.Failed; AddEvent(LogImportance.Critical, "Notifications", "NOTIFY <<" + d.DeviceURN + ">> MISSING/LATE"); } if (NotifyTable.ContainsKey("uuid:" + d.UniqueDeviceName)) { AddEvent(LogImportance.Remark, "Notifications", "NOTIFY <<uuid:" + d.UniqueDeviceName + ">> OK"); } else { NOTIFY = UPnPTestStates.Failed; AddEvent(LogImportance.Critical, "Notifications", "NOTIFY <<uuid:" + d.UniqueDeviceName + ">> MISSING/LATE"); } foreach (UPnPService s in d.Services) { if (NotifyTable.ContainsKey(s.ServiceURN)) { AddEvent(LogImportance.Remark, "Notifications", "NOTIFY <<" + s.ServiceURN + ">> OK"); } else { NOTIFY = UPnPTestStates.Failed; AddEvent(LogImportance.Critical, "Notifications", "NOTIFY <<" + s.ServiceURN + ">> MISSING/LATE"); } } } } }
using System; using System.Collections.Generic; using GuiLabs.Canvas.Events; using GuiLabs.Editor.UI; using GuiLabs.Utils.Delegates; using GuiLabs.Utils; namespace GuiLabs.Editor.Blocks { public class TextSelectionBlock : FocusableLabelBlock { #region ctors public TextSelectionBlock() : base() { Init(); } public TextSelectionBlock(string text) : base(text) { Init(); } public TextSelectionBlock(params string[] itemStrings) : this((IEnumerable<string>)itemStrings) { } public TextSelectionBlock(IEnumerable<string> itemStrings) : base() { ItemStrings = new List<string>(itemStrings); SetDefaultText(); Init(); } public TextSelectionBlock(Enum enumeration) : base(enumeration.ToString()) { this.ItemStrings = Enum.GetNames(enumeration.GetType()); Init(); } private void Init() { mCompletion = new CompletionFunctionality(); this.Completion.CustomItemsRequested += FillItems; } #endregion #region Text public override string Text { get { return base.Text; } set { string oldText = this.Text; if (oldText != value) { OnTextChanging(oldText, value); base.Text = value; OnTextChanged(oldText, value); RaiseTextChanged(oldText, value); } } } protected virtual void SetDefaultText() { string firstItem = Common.Head(ItemStrings); if (!string.IsNullOrEmpty(firstItem)) { this.Text = firstItem; } } protected virtual void OnTextChanging(string oldText, string newText) { } protected virtual void OnTextChanged(string oldText, string newText) { } #endregion #region Completion private CompletionFunctionality mCompletion; public CompletionFunctionality Completion { get { return mCompletion; } } private IEnumerable<string> mItemStrings = new List<string>(); public IEnumerable<string> ItemStrings { get { return mItemStrings; } set { mItemStrings = value; } } #region Add items public virtual void FillItems(CustomItemsRequestEventArgs e) { AddItems(e.Items, ItemStrings); } protected void AddItems(ICompletionListBuilder items, IEnumerable<string> itemsToAdd) { foreach (string s in itemsToAdd) { CompletionListItem item = CreateItem(s); if (item.ShouldShow(this.Completion)) { items.Add(item); } } } public void AddTextItem(string text) { Completion.AddItem(CreateItem(text)); } protected virtual CompletionListItem CreateItem(string text) { TextSelectItem item = new TextSelectItem(text); return item; } #endregion #endregion #region OnEvents protected override void OnDoubleClick(MouseWithKeysEventArgs MouseInfo) { ShouldShowCompletion(); } protected override void OnMouseDown(MouseWithKeysEventArgs e) { if (e.IsRightButtonPressed) { ShouldShowCompletion(); SetFocus(); e.Handled = true; } } protected override void OnKeyDown(object sender, System.Windows.Forms.KeyEventArgs e) { if (e.KeyCode == System.Windows.Forms.Keys.Return || e.KeyCode == System.Windows.Forms.Keys.Space) { ShouldShowCompletion(); e.Handled = true; } if (!e.Handled) { base.OnKeyDown(sender, e); } } protected override void OnKeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e) { foreach (CompletionListItem item in this.Completion.Items) { if (item.Text.ToLower().StartsWith(e.KeyChar.ToString().ToLower())) { Completion.ShowCompletionList(this, e.KeyChar.ToString()); return; } } } public void ShouldShowCompletion() { Completion.ShowCompletionList(this, Text); } #endregion #region Style protected override string StyleName() { return "TextSelectionBlock"; } #endregion } }
/// This code was generated by /// \ / _ _ _| _ _ /// | (_)\/(_)(_|\/| |(/_ v1.0.0 /// / / /// <summary> /// ConfigurationResource /// </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.Conversations.V1.Service { public class ConfigurationResource : Resource { private static Request BuildFetchRequest(FetchConfigurationOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Get, Rest.Domain.Conversations, "/v1/Services/" + options.PathChatServiceSid + "/Configuration", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// Fetch the configuration of a conversation service /// </summary> /// <param name="options"> Fetch Configuration parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Configuration </returns> public static ConfigurationResource Fetch(FetchConfigurationOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildFetchRequest(options, client)); return FromJson(response.Content); } #if !NET35 /// <summary> /// Fetch the configuration of a conversation service /// </summary> /// <param name="options"> Fetch Configuration parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Configuration </returns> public static async System.Threading.Tasks.Task<ConfigurationResource> FetchAsync(FetchConfigurationOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildFetchRequest(options, client)); return FromJson(response.Content); } #endif /// <summary> /// Fetch the configuration of a conversation service /// </summary> /// <param name="pathChatServiceSid"> The SID of the Service configuration resource to fetch </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Configuration </returns> public static ConfigurationResource Fetch(string pathChatServiceSid, ITwilioRestClient client = null) { var options = new FetchConfigurationOptions(pathChatServiceSid); return Fetch(options, client); } #if !NET35 /// <summary> /// Fetch the configuration of a conversation service /// </summary> /// <param name="pathChatServiceSid"> The SID of the Service configuration resource to fetch </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Configuration </returns> public static async System.Threading.Tasks.Task<ConfigurationResource> FetchAsync(string pathChatServiceSid, ITwilioRestClient client = null) { var options = new FetchConfigurationOptions(pathChatServiceSid); return await FetchAsync(options, client); } #endif private static Request BuildUpdateRequest(UpdateConfigurationOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Post, Rest.Domain.Conversations, "/v1/Services/" + options.PathChatServiceSid + "/Configuration", postParams: options.GetParams(), headerParams: null ); } /// <summary> /// Update configuration settings of a conversation service /// </summary> /// <param name="options"> Update Configuration parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Configuration </returns> public static ConfigurationResource Update(UpdateConfigurationOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildUpdateRequest(options, client)); return FromJson(response.Content); } #if !NET35 /// <summary> /// Update configuration settings of a conversation service /// </summary> /// <param name="options"> Update Configuration parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Configuration </returns> public static async System.Threading.Tasks.Task<ConfigurationResource> UpdateAsync(UpdateConfigurationOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildUpdateRequest(options, client)); return FromJson(response.Content); } #endif /// <summary> /// Update configuration settings of a conversation service /// </summary> /// <param name="pathChatServiceSid"> The SID of the Service configuration resource to update </param> /// <param name="defaultConversationCreatorRoleSid"> The role assigned to a conversation creator when they join a new /// conversation </param> /// <param name="defaultConversationRoleSid"> The role assigned to users when they are added to a conversation </param> /// <param name="defaultChatServiceRoleSid"> The service role assigned to users when they are added to the service /// </param> /// <param name="reachabilityEnabled"> Whether the Reachability Indicator feature is enabled for this Conversations /// Service </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of Configuration </returns> public static ConfigurationResource Update(string pathChatServiceSid, string defaultConversationCreatorRoleSid = null, string defaultConversationRoleSid = null, string defaultChatServiceRoleSid = null, bool? reachabilityEnabled = null, ITwilioRestClient client = null) { var options = new UpdateConfigurationOptions(pathChatServiceSid){DefaultConversationCreatorRoleSid = defaultConversationCreatorRoleSid, DefaultConversationRoleSid = defaultConversationRoleSid, DefaultChatServiceRoleSid = defaultChatServiceRoleSid, ReachabilityEnabled = reachabilityEnabled}; return Update(options, client); } #if !NET35 /// <summary> /// Update configuration settings of a conversation service /// </summary> /// <param name="pathChatServiceSid"> The SID of the Service configuration resource to update </param> /// <param name="defaultConversationCreatorRoleSid"> The role assigned to a conversation creator when they join a new /// conversation </param> /// <param name="defaultConversationRoleSid"> The role assigned to users when they are added to a conversation </param> /// <param name="defaultChatServiceRoleSid"> The service role assigned to users when they are added to the service /// </param> /// <param name="reachabilityEnabled"> Whether the Reachability Indicator feature is enabled for this Conversations /// Service </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of Configuration </returns> public static async System.Threading.Tasks.Task<ConfigurationResource> UpdateAsync(string pathChatServiceSid, string defaultConversationCreatorRoleSid = null, string defaultConversationRoleSid = null, string defaultChatServiceRoleSid = null, bool? reachabilityEnabled = null, ITwilioRestClient client = null) { var options = new UpdateConfigurationOptions(pathChatServiceSid){DefaultConversationCreatorRoleSid = defaultConversationCreatorRoleSid, DefaultConversationRoleSid = defaultConversationRoleSid, DefaultChatServiceRoleSid = defaultChatServiceRoleSid, ReachabilityEnabled = reachabilityEnabled}; return await UpdateAsync(options, client); } #endif /// <summary> /// Converts a JSON string into a ConfigurationResource object /// </summary> /// <param name="json"> Raw JSON string </param> /// <returns> ConfigurationResource object represented by the provided JSON </returns> public static ConfigurationResource FromJson(string json) { // Convert all checked exceptions to Runtime try { return JsonConvert.DeserializeObject<ConfigurationResource>(json); } catch (JsonException e) { throw new ApiException(e.Message, e); } } /// <summary> /// The unique string that identifies the resource /// </summary> [JsonProperty("chat_service_sid")] public string ChatServiceSid { get; private set; } /// <summary> /// The role assigned to a conversation creator user when they join a new conversation /// </summary> [JsonProperty("default_conversation_creator_role_sid")] public string DefaultConversationCreatorRoleSid { get; private set; } /// <summary> /// The role assigned to users when they are added to a conversation /// </summary> [JsonProperty("default_conversation_role_sid")] public string DefaultConversationRoleSid { get; private set; } /// <summary> /// The service role assigned to users when they are added to the service /// </summary> [JsonProperty("default_chat_service_role_sid")] public string DefaultChatServiceRoleSid { get; private set; } /// <summary> /// An absolute URL for this service configuration. /// </summary> [JsonProperty("url")] public Uri Url { get; private set; } /// <summary> /// Absolute URL to access the push notifications configuration of this service. /// </summary> [JsonProperty("links")] public Dictionary<string, string> Links { get; private set; } /// <summary> /// Whether the Reachability Indicator feature is enabled for this Conversations Service /// </summary> [JsonProperty("reachability_enabled")] public bool? ReachabilityEnabled { get; private set; } private ConfigurationResource() { } } }
/********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ using System.Collections.Generic; using System.Globalization; using System.IO; using System.Management.Automation.Runspaces; using Dbg = System.Management.Automation.Diagnostics; namespace System.Management.Automation.Internal { internal static class ModuleUtils { internal static bool IsPossibleModuleDirectory(string dir) { // We shouldn't be searching in hidden directories. var attributes = File.GetAttributes(dir); if (0 != (attributes & FileAttributes.Hidden)) { return false; } // Assume locale directories do not contain modules. if (dir.EndsWith(@"\en", StringComparison.OrdinalIgnoreCase) || dir.EndsWith(@"\en-us", StringComparison.OrdinalIgnoreCase)) { return false; } #if !CORECLR dir = Path.GetFileName(dir); // Use some simple pattern matching to avoid the call into GetCultureInfo when we know it will fail (and throw). if ((dir.Length == 2 && char.IsLetter(dir[0]) && char.IsLetter(dir[1])) || (dir.Length == 5 && char.IsLetter(dir[0]) && char.IsLetter(dir[1]) && (dir[2] == '-') && char.IsLetter(dir[3]) && char.IsLetter(dir[4]))) { try { // This might not throw on invalid culture still // 4096 is considered the unknown locale - so assume that could be a module var cultureInfo = new CultureInfo(dir); return cultureInfo.LCID == 4096; } catch { } } #endif return true; } /// <summary> /// Get a list of all module files /// which can be imported just by specifying a non rooted file name of the module /// (Import-Module foo\bar.psm1; but not Import-Module .\foo\bar.psm1) /// </summary> /// <remarks>When obtaining all module files we return all possible /// combinations for a given file. For example, for foo we return both /// foo.psd1 and foo.psm1 if found. Get-Module will create the module /// info only for the first one</remarks> internal static IEnumerable<string> GetAllAvailableModuleFiles(string topDirectoryToCheck) { Queue<string> directoriesToCheck = new Queue<string>(); directoriesToCheck.Enqueue(topDirectoryToCheck); while (directoriesToCheck.Count > 0) { var directoryToCheck = directoriesToCheck.Dequeue(); try { var subDirectories = Directory.GetDirectories(directoryToCheck, "*", SearchOption.TopDirectoryOnly); foreach (var toAdd in subDirectories) { if (IsPossibleModuleDirectory(toAdd)) { directoriesToCheck.Enqueue(toAdd); } } } catch (IOException) { } catch (UnauthorizedAccessException) { } var files = Directory.GetFiles(directoryToCheck, "*", SearchOption.TopDirectoryOnly); foreach (string moduleFile in files) { foreach (string ext in ModuleIntrinsics.PSModuleExtensions) { if (moduleFile.EndsWith(ext, StringComparison.OrdinalIgnoreCase)) { yield return moduleFile; break; // one file can have only one extension } } } } } internal static IEnumerable<string> GetDefaultAvailableModuleFiles(bool force, bool isForAutoDiscovery, ExecutionContext context) { HashSet<string> uniqueModuleFiles = new HashSet<string>(StringComparer.OrdinalIgnoreCase); foreach (string directory in ModuleIntrinsics.GetModulePath(isForAutoDiscovery, context)) { var needWriteProgressCompleted = false; ProgressRecord analysisProgress = null; // Write a progress message for UNC paths, so that users know what is happening try { if ((context.CurrentCommandProcessor != null) && Utils.PathIsUnc(directory)) { analysisProgress = new ProgressRecord(0, Modules.DeterminingAvailableModules, String.Format(CultureInfo.InvariantCulture, Modules.SearchingUncShare, directory)) { RecordType = ProgressRecordType.Processing }; context.CurrentCommandProcessor.CommandRuntime.WriteProgress(analysisProgress); needWriteProgressCompleted = true; } } catch (InvalidOperationException) { // This may be called when we are not allowed to write progress, // So eat the invalid operation } try { foreach (string moduleFile in ModuleUtils.GetDefaultAvailableModuleFiles(directory)) { if (uniqueModuleFiles.Add(moduleFile)) { yield return moduleFile; } } } finally { if (needWriteProgressCompleted) { analysisProgress.RecordType = ProgressRecordType.Completed; context.CurrentCommandProcessor.CommandRuntime.WriteProgress(analysisProgress); } } } } internal static List<string> GetModuleVersionsFromAbsolutePath(string directory) { List<string> result = new List<string>(); string fileName = Path.GetFileName(directory); Version moduleVersion; // if the user give the module path including version, we should be able to find the module as well if (Version.TryParse(fileName, out moduleVersion) && Directory.Exists(Directory.GetParent(directory).ToString())) { fileName = Directory.GetParent(directory).Name; } foreach (var version in GetModuleVersionSubfolders(directory)) { var qualifiedPathWithVersion = Path.Combine(directory, Path.Combine(version.ToString(), fileName)); string manifestPath = qualifiedPathWithVersion + StringLiterals.PowerShellDataFileExtension; if (File.Exists(manifestPath)) { bool isValidModuleVersion = version.Equals(ModuleIntrinsics.GetManifestModuleVersion(manifestPath)); if (isValidModuleVersion) { result.Add(manifestPath); } } } foreach (string ext in ModuleIntrinsics.PSModuleExtensions) { string moduleFile = Path.Combine(directory, fileName) + ext; if (!Utils.NativeFileExists(moduleFile)) { continue; } result.Add(moduleFile); // when finding the default modules we stop when the first // match is hit - searching in order .psd1, .psm1, .dll // if a file is found but is not readable then it is an // error break; } return result; } /// <summary> /// Get a list of the available module files /// which can be imported just by specifying a non rooted directory name of the module /// (Import-Module foo\bar; but not Import-Module .\foo\bar or Import-Module .\foo\bar.psm1) /// </summary> internal static IEnumerable<string> GetDefaultAvailableModuleFiles(string topDirectoryToCheck) { List<Version> versionDirectories = new List<Version>(); LinkedList<string> directoriesToCheck = new LinkedList<string>(); directoriesToCheck.AddLast(topDirectoryToCheck); while (directoriesToCheck.Count > 0) { versionDirectories.Clear(); string[] subdirectories; var directoryToCheck = directoriesToCheck.First.Value; directoriesToCheck.RemoveFirst(); try { subdirectories = Directory.GetDirectories(directoryToCheck, "*", SearchOption.TopDirectoryOnly); ProcessPossibleVersionSubdirectories(subdirectories, versionDirectories); } catch (IOException) { subdirectories = Utils.EmptyArray<string>(); } catch (UnauthorizedAccessException) { subdirectories = Utils.EmptyArray<string>(); } bool isModuleDirectory = false; string proposedModuleName = Path.GetFileName(directoryToCheck); foreach (var version in versionDirectories) { var qualifiedPathWithVersion = Path.Combine(directoryToCheck, Path.Combine(version.ToString(), proposedModuleName)); string manifestPath = qualifiedPathWithVersion + StringLiterals.PowerShellDataFileExtension; if (File.Exists(manifestPath)) { isModuleDirectory = true; yield return manifestPath; } } foreach (string ext in ModuleIntrinsics.PSModuleExtensions) { string moduleFile = Path.Combine(directoryToCheck, proposedModuleName) + ext; if (!Utils.NativeFileExists(moduleFile)) { continue; } isModuleDirectory = true; yield return moduleFile; // when finding the default modules we stop when the first // match is hit - searching in order .psd1, .psm1, .dll // if a file is found but is not readable then it is an // error break; } if (!isModuleDirectory) { foreach (var subdirectory in subdirectories) { if (IsPossibleModuleDirectory(subdirectory)) { if (subdirectory.EndsWith("Microsoft.PowerShell.Management", StringComparison.OrdinalIgnoreCase) || subdirectory.EndsWith("Microsoft.PowerShell.Utility", StringComparison.OrdinalIgnoreCase)) { directoriesToCheck.AddFirst(subdirectory); } else { directoriesToCheck.AddLast(subdirectory); } } } } } } /// <summary> /// Gets the list of versions under the specified module base path in descending sorted order /// </summary> /// <param name="moduleBase">module base path</param> /// <returns>sorted list of versions</returns> internal static List<Version> GetModuleVersionSubfolders(string moduleBase) { var versionFolders = new List<Version>(); if (!string.IsNullOrWhiteSpace(moduleBase) && Directory.Exists(moduleBase)) { var subdirectories = Directory.GetDirectories(moduleBase); ProcessPossibleVersionSubdirectories(subdirectories, versionFolders); } return versionFolders; } private static void ProcessPossibleVersionSubdirectories(string[] subdirectories, List<Version> versionFolders) { foreach (var subdir in subdirectories) { var subdirName = Path.GetFileName(subdir); Version version; if (Version.TryParse(subdirName, out version)) { versionFolders.Add(version); } } if (versionFolders.Count > 1) { versionFolders.Sort((x, y) => y.CompareTo(x)); } } internal static bool IsModuleInVersionSubdirectory(string modulePath, out Version version) { version = null; var folderName = Path.GetDirectoryName(modulePath); if (folderName != null) { folderName = Path.GetFileName(folderName); return Version.TryParse(folderName, out version); } return false; } /// <summary> /// Gets a list of matching commands /// </summary> /// <param name="pattern">command pattern</param> /// <param name="commandOrigin"></param> /// <param name="context"></param> /// <param name="rediscoverImportedModules"></param> /// <param name="moduleVersionRequired"></param> /// <returns></returns> internal static IEnumerable<CommandInfo> GetMatchingCommands(string pattern, ExecutionContext context, CommandOrigin commandOrigin, bool rediscoverImportedModules = false, bool moduleVersionRequired = false) { // Otherwise, if it had wildcards, just return the "AvailableCommand" // type of command info. WildcardPattern commandPattern = WildcardPattern.Get(pattern, WildcardOptions.IgnoreCase); CmdletInfo cmdletInfo = context.SessionState.InvokeCommand.GetCmdlet("Microsoft.PowerShell.Core\\Get-Module"); PSModuleAutoLoadingPreference moduleAutoLoadingPreference = CommandDiscovery.GetCommandDiscoveryPreference(context, SpecialVariables.PSModuleAutoLoadingPreferenceVarPath, "PSModuleAutoLoadingPreference"); if ((moduleAutoLoadingPreference != PSModuleAutoLoadingPreference.None) && ((commandOrigin == CommandOrigin.Internal) || ((cmdletInfo != null) && (cmdletInfo.Visibility == SessionStateEntryVisibility.Public)) ) ) { foreach (string modulePath in GetDefaultAvailableModuleFiles(true, false, context)) { // Skip modules that have already been loaded so that we don't expose private commands. string moduleName = Path.GetFileNameWithoutExtension(modulePath); var modules = context.Modules.GetExactMatchModules(moduleName, all: false, exactMatch: true); PSModuleInfo tempModuleInfo = null; if (modules.Count != 0) { // 1. We continue to the next module path if we don't want to re-discover those imported modules // 2. If we want to re-discover the imported modules, but one or more commands from the module were made private, // then we don't do re-discovery if (!rediscoverImportedModules || modules.Exists(module => module.ModuleHasPrivateMembers)) { continue; } if (modules.Count == 1) { PSModuleInfo psModule = modules[0]; tempModuleInfo = new PSModuleInfo(psModule.Name, psModule.Path, null, null); tempModuleInfo.SetModuleBase(psModule.ModuleBase); foreach (var entry in psModule.ExportedCommands) { if (commandPattern.IsMatch(entry.Value.Name)) { CommandInfo current = null; switch (entry.Value.CommandType) { case CommandTypes.Alias: current = new AliasInfo(entry.Value.Name, null, context); break; case CommandTypes.Workflow: current = new WorkflowInfo(entry.Value.Name, ScriptBlock.EmptyScriptBlock, context); break; case CommandTypes.Function: current = new FunctionInfo(entry.Value.Name, ScriptBlock.EmptyScriptBlock, context); break; case CommandTypes.Filter: current = new FilterInfo(entry.Value.Name, ScriptBlock.EmptyScriptBlock, context); break; case CommandTypes.Configuration: current = new ConfigurationInfo(entry.Value.Name, ScriptBlock.EmptyScriptBlock, context); break; case CommandTypes.Cmdlet: current = new CmdletInfo(entry.Value.Name, null, null, null, context); break; default: Dbg.Assert(false, "cannot be hit"); break; } current.Module = tempModuleInfo; yield return current; } } continue; } } string moduleShortName = System.IO.Path.GetFileNameWithoutExtension(modulePath); var exportedCommands = AnalysisCache.GetExportedCommands(modulePath, false, context); if (exportedCommands == null) { continue; } tempModuleInfo = new PSModuleInfo(moduleShortName, modulePath, null, null); if (InitialSessionState.IsEngineModule(moduleShortName)) { tempModuleInfo.SetModuleBase(Utils.GetApplicationBase(Utils.DefaultPowerShellShellID)); } //moduleVersionRequired is bypassed by FullyQualifiedModule from calling method. This is the only place where guid will be involved. if (moduleVersionRequired && modulePath.EndsWith(StringLiterals.PowerShellDataFileExtension, StringComparison.OrdinalIgnoreCase)) { tempModuleInfo.SetVersion(ModuleIntrinsics.GetManifestModuleVersion(modulePath)); tempModuleInfo.SetGuid(ModuleIntrinsics.GetManifestGuid(modulePath)); } foreach (var pair in exportedCommands) { var commandName = pair.Key; var commandTypes = pair.Value; if (commandPattern.IsMatch(commandName)) { bool shouldExportCommand = true; // Verify that we don't already have it represented in the initial session state. if ((context.InitialSessionState != null) && (commandOrigin == CommandOrigin.Runspace)) { foreach (SessionStateCommandEntry commandEntry in context.InitialSessionState.Commands[commandName]) { string moduleCompareName = null; if (commandEntry.Module != null) { moduleCompareName = commandEntry.Module.Name; } else if (commandEntry.PSSnapIn != null) { moduleCompareName = commandEntry.PSSnapIn.Name; } if (String.Equals(moduleShortName, moduleCompareName, StringComparison.OrdinalIgnoreCase)) { if (commandEntry.Visibility == SessionStateEntryVisibility.Private) { shouldExportCommand = false; } } } } if (shouldExportCommand) { if ((commandTypes & CommandTypes.Alias) == CommandTypes.Alias) { yield return new AliasInfo(commandName, null, context) { Module = tempModuleInfo }; } if ((commandTypes & CommandTypes.Cmdlet) == CommandTypes.Cmdlet) { yield return new CmdletInfo(commandName, implementingType: null, helpFile: null, PSSnapin: null, context: context) { Module = tempModuleInfo }; } if ((commandTypes & CommandTypes.Function) == CommandTypes.Function) { yield return new FunctionInfo(commandName, ScriptBlock.EmptyScriptBlock, context) { Module = tempModuleInfo }; } if ((commandTypes & CommandTypes.Configuration) == CommandTypes.Configuration) { yield return new ConfigurationInfo(commandName, ScriptBlock.EmptyScriptBlock, context) { Module = tempModuleInfo }; } if ((commandTypes & CommandTypes.Workflow) == CommandTypes.Workflow) { yield return new WorkflowInfo(commandName, ScriptBlock.EmptyScriptBlock, context) { Module = tempModuleInfo }; } } } } } } } } }
// 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.AssuredWorkloads.V1; using sys = System; namespace Google.Cloud.AssuredWorkloads.V1 { /// <summary>Resource name for the <c>Workload</c> resource.</summary> public sealed partial class WorkloadName : gax::IResourceName, sys::IEquatable<WorkloadName> { /// <summary>The possible contents of <see cref="WorkloadName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern <c>organizations/{organization}/locations/{location}/workloads/{workload}</c> /// . /// </summary> OrganizationLocationWorkload = 1, } private static gax::PathTemplate s_organizationLocationWorkload = new gax::PathTemplate("organizations/{organization}/locations/{location}/workloads/{workload}"); /// <summary>Creates a <see cref="WorkloadName"/> 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="WorkloadName"/> containing the provided <paramref name="unparsedResourceName"/> /// . /// </returns> public static WorkloadName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new WorkloadName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="WorkloadName"/> with the pattern /// <c>organizations/{organization}/locations/{location}/workloads/{workload}</c>. /// </summary> /// <param name="organizationId">The <c>Organization</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="workloadId">The <c>Workload</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="WorkloadName"/> constructed from the provided ids.</returns> public static WorkloadName FromOrganizationLocationWorkload(string organizationId, string locationId, string workloadId) => new WorkloadName(ResourceNameType.OrganizationLocationWorkload, organizationId: gax::GaxPreconditions.CheckNotNullOrEmpty(organizationId, nameof(organizationId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), workloadId: gax::GaxPreconditions.CheckNotNullOrEmpty(workloadId, nameof(workloadId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="WorkloadName"/> with pattern /// <c>organizations/{organization}/locations/{location}/workloads/{workload}</c>. /// </summary> /// <param name="organizationId">The <c>Organization</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="workloadId">The <c>Workload</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="WorkloadName"/> with pattern /// <c>organizations/{organization}/locations/{location}/workloads/{workload}</c>. /// </returns> public static string Format(string organizationId, string locationId, string workloadId) => FormatOrganizationLocationWorkload(organizationId, locationId, workloadId); /// <summary> /// Formats the IDs into the string representation of this <see cref="WorkloadName"/> with pattern /// <c>organizations/{organization}/locations/{location}/workloads/{workload}</c>. /// </summary> /// <param name="organizationId">The <c>Organization</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="workloadId">The <c>Workload</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="WorkloadName"/> with pattern /// <c>organizations/{organization}/locations/{location}/workloads/{workload}</c>. /// </returns> public static string FormatOrganizationLocationWorkload(string organizationId, string locationId, string workloadId) => s_organizationLocationWorkload.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(organizationId, nameof(organizationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(workloadId, nameof(workloadId))); /// <summary>Parses the given resource name string into a new <see cref="WorkloadName"/> instance.</summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description><c>organizations/{organization}/locations/{location}/workloads/{workload}</c></description> /// </item> /// </list> /// </remarks> /// <param name="workloadName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="WorkloadName"/> if successful.</returns> public static WorkloadName Parse(string workloadName) => Parse(workloadName, false); /// <summary> /// Parses the given resource name string into a new <see cref="WorkloadName"/> instance; optionally allowing an /// unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description><c>organizations/{organization}/locations/{location}/workloads/{workload}</c></description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="workloadName">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="WorkloadName"/> if successful.</returns> public static WorkloadName Parse(string workloadName, bool allowUnparsed) => TryParse(workloadName, allowUnparsed, out WorkloadName 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="WorkloadName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description><c>organizations/{organization}/locations/{location}/workloads/{workload}</c></description> /// </item> /// </list> /// </remarks> /// <param name="workloadName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="WorkloadName"/>, 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 workloadName, out WorkloadName result) => TryParse(workloadName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="WorkloadName"/> instance; optionally /// allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description><c>organizations/{organization}/locations/{location}/workloads/{workload}</c></description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="workloadName">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="WorkloadName"/>, 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 workloadName, bool allowUnparsed, out WorkloadName result) { gax::GaxPreconditions.CheckNotNull(workloadName, nameof(workloadName)); gax::TemplatedResourceName resourceName; if (s_organizationLocationWorkload.TryParseName(workloadName, out resourceName)) { result = FromOrganizationLocationWorkload(resourceName[0], resourceName[1], resourceName[2]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(workloadName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private WorkloadName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string locationId = null, string organizationId = null, string workloadId = null) { Type = type; UnparsedResource = unparsedResourceName; LocationId = locationId; OrganizationId = organizationId; WorkloadId = workloadId; } /// <summary> /// Constructs a new instance of a <see cref="WorkloadName"/> class from the component parts of pattern /// <c>organizations/{organization}/locations/{location}/workloads/{workload}</c> /// </summary> /// <param name="organizationId">The <c>Organization</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="workloadId">The <c>Workload</c> ID. Must not be <c>null</c> or empty.</param> public WorkloadName(string organizationId, string locationId, string workloadId) : this(ResourceNameType.OrganizationLocationWorkload, organizationId: gax::GaxPreconditions.CheckNotNullOrEmpty(organizationId, nameof(organizationId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), workloadId: gax::GaxPreconditions.CheckNotNullOrEmpty(workloadId, nameof(workloadId))) { } /// <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>Organization</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource /// name. /// </summary> public string OrganizationId { get; } /// <summary> /// The <c>Workload</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string WorkloadId { 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.OrganizationLocationWorkload: return s_organizationLocationWorkload.Expand(OrganizationId, LocationId, WorkloadId); 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 WorkloadName); /// <inheritdoc/> public bool Equals(WorkloadName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(WorkloadName a, WorkloadName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(WorkloadName a, WorkloadName b) => !(a == b); } /// <summary>Resource name for the <c>Location</c> resource.</summary> public sealed partial class LocationName : gax::IResourceName, sys::IEquatable<LocationName> { /// <summary>The possible contents of <see cref="LocationName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern <c>organizations/{organization}/locations/{location}</c>. /// </summary> OrganizationLocation = 1, } private static gax::PathTemplate s_organizationLocation = new gax::PathTemplate("organizations/{organization}/locations/{location}"); /// <summary>Creates a <see cref="LocationName"/> 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="LocationName"/> containing the provided <paramref name="unparsedResourceName"/> /// . /// </returns> public static LocationName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new LocationName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="LocationName"/> with the pattern <c>organizations/{organization}/locations/{location}</c> /// . /// </summary> /// <param name="organizationId">The <c>Organization</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> /// <returns>A new instance of <see cref="LocationName"/> constructed from the provided ids.</returns> public static LocationName FromOrganizationLocation(string organizationId, string locationId) => new LocationName(ResourceNameType.OrganizationLocation, organizationId: gax::GaxPreconditions.CheckNotNullOrEmpty(organizationId, nameof(organizationId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="LocationName"/> with pattern /// <c>organizations/{organization}/locations/{location}</c>. /// </summary> /// <param name="organizationId">The <c>Organization</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> /// <returns> /// The string representation of this <see cref="LocationName"/> with pattern /// <c>organizations/{organization}/locations/{location}</c>. /// </returns> public static string Format(string organizationId, string locationId) => FormatOrganizationLocation(organizationId, locationId); /// <summary> /// Formats the IDs into the string representation of this <see cref="LocationName"/> with pattern /// <c>organizations/{organization}/locations/{location}</c>. /// </summary> /// <param name="organizationId">The <c>Organization</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> /// <returns> /// The string representation of this <see cref="LocationName"/> with pattern /// <c>organizations/{organization}/locations/{location}</c>. /// </returns> public static string FormatOrganizationLocation(string organizationId, string locationId) => s_organizationLocation.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(organizationId, nameof(organizationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId))); /// <summary>Parses the given resource name string into a new <see cref="LocationName"/> instance.</summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>organizations/{organization}/locations/{location}</c></description></item> /// </list> /// </remarks> /// <param name="locationName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="LocationName"/> if successful.</returns> public static LocationName Parse(string locationName) => Parse(locationName, false); /// <summary> /// Parses the given resource name string into a new <see cref="LocationName"/> instance; optionally allowing an /// unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>organizations/{organization}/locations/{location}</c></description></item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="locationName">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="LocationName"/> if successful.</returns> public static LocationName Parse(string locationName, bool allowUnparsed) => TryParse(locationName, allowUnparsed, out LocationName 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="LocationName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>organizations/{organization}/locations/{location}</c></description></item> /// </list> /// </remarks> /// <param name="locationName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="LocationName"/>, 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 locationName, out LocationName result) => TryParse(locationName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="LocationName"/> instance; optionally /// allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>organizations/{organization}/locations/{location}</c></description></item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="locationName">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="LocationName"/>, 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 locationName, bool allowUnparsed, out LocationName result) { gax::GaxPreconditions.CheckNotNull(locationName, nameof(locationName)); gax::TemplatedResourceName resourceName; if (s_organizationLocation.TryParseName(locationName, out resourceName)) { result = FromOrganizationLocation(resourceName[0], resourceName[1]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(locationName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private LocationName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string locationId = null, string organizationId = null) { Type = type; UnparsedResource = unparsedResourceName; LocationId = locationId; OrganizationId = organizationId; } /// <summary> /// Constructs a new instance of a <see cref="LocationName"/> class from the component parts of pattern /// <c>organizations/{organization}/locations/{location}</c> /// </summary> /// <param name="organizationId">The <c>Organization</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> public LocationName(string organizationId, string locationId) : this(ResourceNameType.OrganizationLocation, organizationId: gax::GaxPreconditions.CheckNotNullOrEmpty(organizationId, nameof(organizationId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId))) { } /// <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>Organization</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource /// name. /// </summary> public string OrganizationId { 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.OrganizationLocation: return s_organizationLocation.Expand(OrganizationId, LocationId); 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 LocationName); /// <inheritdoc/> public bool Equals(LocationName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(LocationName a, LocationName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(LocationName a, LocationName b) => !(a == b); } public partial class CreateWorkloadRequest { /// <summary> /// <see cref="LocationName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public LocationName ParentAsLocationName { get => string.IsNullOrEmpty(Parent) ? null : LocationName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } } public partial class DeleteWorkloadRequest { /// <summary> /// <see cref="gcav::WorkloadName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcav::WorkloadName WorkloadName { get => string.IsNullOrEmpty(Name) ? null : gcav::WorkloadName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class GetWorkloadRequest { /// <summary> /// <see cref="gcav::WorkloadName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcav::WorkloadName WorkloadName { get => string.IsNullOrEmpty(Name) ? null : gcav::WorkloadName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class ListWorkloadsRequest { /// <summary> /// <see cref="LocationName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public LocationName ParentAsLocationName { get => string.IsNullOrEmpty(Parent) ? null : LocationName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } } public partial class Workload { /// <summary> /// <see cref="gcav::WorkloadName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcav::WorkloadName WorkloadName { get => string.IsNullOrEmpty(Name) ? null : gcav::WorkloadName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } }
#region License, Terms and Author(s) // // ELMAH - Error Logging Modules and Handlers for ASP.NET // Copyright (c) 2004-9 Atif Aziz. All rights reserved. // // Author(s): // // Atif Aziz, http://www.raboof.com // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion [assembly: Elmah.Scc("$Id: ErrorLogPageFactory.cs 923 2011-12-23 22:02:10Z azizatif $")] namespace Elmah { #region Imports using System; using System.Linq; using System.Web; using System.Collections.Generic; using Encoding = System.Text.Encoding; #endregion /// <summary> /// HTTP handler factory that dispenses handlers for rendering views and /// resources needed to display the error log. /// </summary> public class ErrorLogPageFactory : IHttpHandlerFactory { private static readonly object _authorizationHandlersKey = new object(); IHttpHandler IHttpHandlerFactory.GetHandler(HttpContext context, string requestType, string url, string pathTranslated) { return GetHandler(new HttpContextWrapper(context), requestType, url, pathTranslated); } /// <summary> /// Returns an object that implements the <see cref="IHttpHandler"/> /// interface and which is responsible for serving the request. /// </summary> /// <returns> /// A new <see cref="IHttpHandler"/> object that processes the request. /// </returns> public virtual IHttpHandler GetHandler(HttpContextBase context, string requestType, string url, string pathTranslated) { // // The request resource is determined by the looking up the // value of the PATH_INFO server variable. // var request = context.Request; var resource = request.PathInfo.Length == 0 ? string.Empty : request.PathInfo.Substring(1).ToLowerInvariant(); var handler = FindHandler(resource); if (handler == null) throw new HttpException(404, "Resource not found."); // // Check if authorized then grant or deny request. // var authorized = IsAuthorized(context); if (authorized == false || (authorized == null // Compatibility case... && !request.IsLocal && !SecurityConfiguration.Default.AllowRemoteAccess)) { ManifestResourceHandler.Create("RemoteAccessError.htm", "text/html")(context); var response = context.Response; response.Status = "403 Forbidden"; response.End(); // // HttpResponse.End docs say that it throws // ThreadAbortException and so should never end up here but // that's not been the observation in the debugger. So as a // precautionary measure, bail out anyway. // return null; } return handler; } private static IHttpHandler FindHandler(string name) { Debug.Assert(name != null); switch (name) { case "detail": return CreateTemplateHandler<ErrorDetailPage>(); case "html": return new ErrorHtmlPage(); case "xml": return new DelegatingHttpHandler(ErrorXmlHandler.ProcessRequest); case "json": return new DelegatingHttpHandler(ErrorJsonHandler.ProcessRequest); case "rss": return new DelegatingHttpHandler(ErrorRssHandler.ProcessRequest); case "digestrss": return new DelegatingHttpHandler(ErrorDigestRssHandler.ProcessRequest); case "download": #if NET_3_5 || NET_4_0 return new HttpAsyncHandler((context, getAsyncCallback) => HttpTextAsyncHandler.Create(ErrorLogDownloadHandler.ProcessRequest)(context, getAsyncCallback)); #else return new DelegatingHttpTaskAsyncHandler(ErrorLogDownloadHandler.ProcessRequestAsync); #endif case "stylesheet": return new DelegatingHttpHandler(ManifestResourceHandler.Create(StyleSheetHelper.StyleSheetResourceNames, "text/css", Encoding.GetEncoding("Windows-1252"), true)); case "javascript": return new DelegatingHttpHandler(ManifestResourceHandler.Create(JavascriptHelper.JavascriptResourceNames, "text/javascript", Encoding.GetEncoding("Windows-1252"), true)); case "ajax": return new DelegatingHttpHandler(AjaxHandler.ProcessRequest); case "test": throw new TestException(); case "about": return CreateTemplateHandler<AboutPage>(); default: return name.Length == 0 ? CreateTemplateHandler<ErrorLogPage>() : null; } } static IHttpHandler CreateTemplateHandler<T>() where T : WebTemplateBase, new() { return new DelegatingHttpHandler(context => { var template = new T { Context = context }; context.Response.Write(template.TransformText()); }); } /// <summary> /// Enables the factory to reuse an existing handler instance. /// </summary> public virtual void ReleaseHandler(IHttpHandler handler) {} /// <summary> /// Determines if the request is authorized by objects implementing /// <see cref="IRequestAuthorizationHandler" />. /// </summary> /// <returns> /// Returns <c>false</c> if unauthorized, <c>true</c> if authorized /// otherwise <c>null</c> if no handlers were available to answer. /// </returns> private static bool? IsAuthorized(HttpContextBase context) { Debug.Assert(context != null); var handlers = GetAuthorizationHandlers(context).ToArray(); return handlers.Length != 0 ? handlers.All(h => h.Authorize(context)) : (bool?) null; } private static IEnumerable<IRequestAuthorizationHandler> GetAuthorizationHandlers(HttpContextBase context) { Debug.Assert(context != null); var key = _authorizationHandlersKey; var handlers = (IEnumerable<IRequestAuthorizationHandler>) context.Items[key]; if (handlers == null) { handlers = from app in new[] { context.ApplicationInstance } let mods = HttpModuleRegistry.GetModules(app) select new[] { app }.Concat(from object m in mods select m) into objs from obj in objs select obj as IRequestAuthorizationHandler into handler where handler != null select handler; context.Items[key] = handlers = Array.AsReadOnly(handlers.ToArray()); } return handlers; } internal static Uri GetRequestUrl(HttpContextBase context) { if (context == null) throw new ArgumentNullException("context"); var url = context.Items["ELMAH_REQUEST_URL"] as Uri; return url ?? context.Request.Url; } } public interface IRequestAuthorizationHandler { bool Authorize(HttpContextBase context); } }
// 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.Generic; using System.IO; using Microsoft.Protocols.TestTools.StackSdk; using Microsoft.Protocols.TestTools.StackSdk.Messages; namespace Microsoft.Protocols.TestTools.StackSdk.FileAccessService.Cifs { /// <summary> /// Packets for SmbTrans2FindFirst2 Request /// </summary> public class SmbTrans2FindFirst2RequestPacket : SmbTransaction2RequestPacket { #region Fields private TRANS2_FIND_FIRST2_Request_Trans2_Parameters trans2Parameters; private TRANS2_FIND_FIRST2_Request_Trans2_Data trans2Data; /// <summary> /// The size of SizeOfListInBytes field in trans2Data /// </summary> private const ushort sizeOfListInBytesLength = 4; /// <summary> /// This is a fixed length including length of SearchAttributes, SearchCount, Flags, InformationLevel, /// and SearchStorageType. /// </summary> private const ushort trans2ParametersLength = 12; #endregion #region Properties /// <summary> /// get or set the Trans2_Parameters:TRANS2_FIND_FIRST2_Request_Trans2_Parameters /// </summary> public TRANS2_FIND_FIRST2_Request_Trans2_Parameters Trans2Parameters { get { return this.trans2Parameters; } set { this.trans2Parameters = value; } } /// <summary> /// get or set the Trans2_Data:TRANS2_FIND_FIRST2_Request_Trans2_Data /// </summary> public TRANS2_FIND_FIRST2_Request_Trans2_Data Trans2Data { get { return this.trans2Data; } set { this.trans2Data = value; } } /// <summary> /// get the FID of Trans2_Parameters /// </summary> internal override ushort FID { get { return INVALID_FID; } } #endregion #region Constructor /// <summary> /// Constructor. /// </summary> public SmbTrans2FindFirst2RequestPacket() : base() { this.InitDefaultValue(); } /// <summary> /// Constructor: Create a request directly from a buffer. /// </summary> public SmbTrans2FindFirst2RequestPacket(byte[] data) : base(data) { } /// <summary> /// Deep copy constructor. /// </summary> public SmbTrans2FindFirst2RequestPacket(SmbTrans2FindFirst2RequestPacket packet) : base(packet) { this.InitDefaultValue(); this.trans2Parameters.SearchAttributes = packet.trans2Parameters.SearchAttributes; this.trans2Parameters.SearchCount = packet.trans2Parameters.SearchCount; this.trans2Parameters.Flags = packet.trans2Parameters.Flags; this.trans2Parameters.InformationLevel = packet.trans2Parameters.InformationLevel; this.trans2Parameters.SearchStorageType = packet.trans2Parameters.SearchStorageType; if (packet.trans2Parameters.FileName != null) { this.trans2Parameters.FileName = new byte[packet.trans2Parameters.FileName.Length]; Array.Copy(packet.trans2Parameters.FileName, this.trans2Parameters.FileName, packet.trans2Parameters.FileName.Length); } else { this.trans2Parameters.FileName = new byte[0]; } this.trans2Data.GetExtendedAttributeList.SizeOfListInBytes = packet.trans2Data.GetExtendedAttributeList.SizeOfListInBytes; if (packet.trans2Data.GetExtendedAttributeList.GEAList != null) { this.trans2Data.GetExtendedAttributeList.GEAList = new SMB_GEA[packet.trans2Data.GetExtendedAttributeList.GEAList.Length]; Array.Copy(packet.trans2Data.GetExtendedAttributeList.GEAList, this.trans2Data.GetExtendedAttributeList.GEAList, packet.trans2Data.GetExtendedAttributeList.GEAList.Length); } else { this.trans2Data.GetExtendedAttributeList.GEAList = new SMB_GEA[0]; } } #endregion #region override methods /// <summary> /// to create an instance of the StackPacket class that is identical to the current StackPacket. /// </summary> /// <returns>a new Packet cloned from this.</returns> public override StackPacket Clone() { return new SmbTrans2FindFirst2RequestPacket(this); } /// <summary> /// Encode the struct of Trans2Parameters into the byte array in SmbData.Trans2_Parameters /// </summary> protected override void EncodeTrans2Parameters() { int trans2ParametersCount = trans2ParametersLength; if (this.trans2Parameters.FileName != null) { trans2ParametersCount += this.trans2Parameters.FileName.Length; } this.smbData.Trans2_Parameters = new byte[trans2ParametersCount]; using (MemoryStream memoryStream = new MemoryStream(this.smbData.Trans2_Parameters)) { using (Channel channel = new Channel(null, memoryStream)) { channel.BeginWriteGroup(); channel.Write<SmbFileAttributes>(this.trans2Parameters.SearchAttributes); channel.Write<ushort>(this.trans2Parameters.SearchCount); channel.Write<Trans2FindFlags>(this.trans2Parameters.Flags); channel.Write<FindInformationLevel>(this.trans2Parameters.InformationLevel); channel.Write<Trans2FindFirst2SearchStorageType>(this.trans2Parameters.SearchStorageType); if (this.trans2Parameters.FileName != null) { channel.WriteBytes(this.trans2Parameters.FileName); } channel.EndWriteGroup(); } } } /// <summary> /// Encode the struct of Trans2Data into the byte array in SmbData.Trans2_Data /// </summary> protected override void EncodeTrans2Data() { if (this.trans2Parameters.InformationLevel == FindInformationLevel.SMB_INFO_QUERY_EAS_FROM_LIST) { this.smbData.Trans2_Data = new byte[sizeOfListInBytesLength + CifsMessageUtils.GetSmbQueryEAListSize( this.trans2Data.GetExtendedAttributeList.GEAList)]; using (MemoryStream memoryStream = new MemoryStream(this.smbData.Trans2_Data)) { using (Channel channel = new Channel(null, memoryStream)) { channel.BeginWriteGroup(); channel.Write<uint>(this.trans2Data.GetExtendedAttributeList.SizeOfListInBytes); if (this.trans2Data.GetExtendedAttributeList.GEAList != null) { foreach (SMB_GEA smbQueryEa in this.trans2Data.GetExtendedAttributeList.GEAList) { channel.Write<byte>(smbQueryEa.AttributeNameLengthInBytes); if (smbQueryEa.AttributeName != null) { channel.WriteBytes(smbQueryEa.AttributeName); } } } channel.EndWriteGroup(); } } } else { this.smbData.Trans2_Data = new byte[0]; } } /// <summary> /// to decode the Trans2 parameters: from the general Trans2Parameters to the concrete Trans2 Parameters. /// </summary> protected override void DecodeTrans2Parameters() { using (MemoryStream memoryStream = new MemoryStream(this.smbData.Trans2_Parameters)) { using (Channel channel = new Channel(null, memoryStream)) { this.trans2Parameters.SearchAttributes = channel.Read<SmbFileAttributes>(); this.trans2Parameters.SearchCount = channel.Read<ushort>(); this.trans2Parameters.Flags = channel.Read<Trans2FindFlags>(); this.trans2Parameters.InformationLevel = channel.Read<FindInformationLevel>(); this.trans2Parameters.SearchStorageType = channel.Read<Trans2FindFirst2SearchStorageType>(); this.trans2Parameters.FileName = channel.ReadBytes(this.SmbParameters.ParameterCount - trans2ParametersLength); } } } /// <summary> /// to decode the Trans2 data: from the general Trans2Dada to the concrete Trans2 Data. /// </summary> protected override void DecodeTrans2Data() { if (this.trans2Parameters.InformationLevel == FindInformationLevel.SMB_INFO_QUERY_EAS_FROM_LIST) { using (MemoryStream memoryStream = new MemoryStream(this.smbData.Trans2_Data)) { using (Channel channel = new Channel(null, memoryStream)) { this.trans2Data.GetExtendedAttributeList.SizeOfListInBytes = channel.Read<uint>(); uint sizeOfListInBytes = this.trans2Data.GetExtendedAttributeList.SizeOfListInBytes - sizeOfListInBytesLength; List<SMB_GEA> attributeList = new List<SMB_GEA>(); while (sizeOfListInBytes > 0) { SMB_GEA smbQueryEa = channel.Read<SMB_GEA>(); attributeList.Add(smbQueryEa); sizeOfListInBytes -= (uint)(EA.SMB_QUERY_EA_FIXED_SIZE + smbQueryEa.AttributeName.Length); } this.trans2Data.GetExtendedAttributeList.GEAList = attributeList.ToArray(); } } } else { this.trans2Data.GetExtendedAttributeList.GEAList = new SMB_GEA[0]; } } #endregion #region initialize fields with default value /// <summary> /// init packet, set default field data /// </summary> private void InitDefaultValue() { } #endregion } }
namespace GitVersion { using JetBrains.Annotations; using LibGit2Sharp; using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; public class BranchConfigurationCalculator { /// <summary> /// Gets the <see cref="BranchConfig"/> for the current commit. /// </summary> public static BranchConfig GetBranchConfiguration(GitVersionContext context, Branch targetBranch, IList<Branch> excludedInheritBranches = null) { var matchingBranches = LookupBranchConfiguration(context.FullConfiguration, targetBranch).ToArray(); BranchConfig branchConfiguration; if (matchingBranches.Length > 0) { branchConfiguration = matchingBranches[0]; if (matchingBranches.Length > 1) { Logger.WriteWarning(string.Format( "Multiple branch configurations match the current branch branchName of '{0}'. Using the first matching configuration, '{1}'. Matching configurations include: '{2}'", targetBranch.FriendlyName, branchConfiguration.Name, string.Join("', '", matchingBranches.Select(b => b.Name)))); } } else { Logger.WriteInfo(string.Format( "No branch configuration found for branch {0}, falling back to default configuration", targetBranch.FriendlyName)); branchConfiguration = new BranchConfig { Name = string.Empty }; ConfigurationProvider.ApplyBranchDefaults(context.FullConfiguration, branchConfiguration, ""); } return branchConfiguration.Increment == IncrementStrategy.Inherit ? InheritBranchConfiguration(context, targetBranch, branchConfiguration, excludedInheritBranches) : branchConfiguration; } static IEnumerable<BranchConfig> LookupBranchConfiguration([NotNull] Config config, [NotNull] Branch currentBranch) { if (config == null) { throw new ArgumentNullException("config"); } if (currentBranch == null) { throw new ArgumentNullException("currentBranch"); } return config.Branches.Where(b => Regex.IsMatch(currentBranch.FriendlyName, "^" + b.Value.Regex, RegexOptions.IgnoreCase)).Select(kvp => kvp.Value); } static BranchConfig InheritBranchConfiguration(GitVersionContext context, Branch targetBranch, BranchConfig branchConfiguration, IList<Branch> excludedInheritBranches) { var repository = context.Repository; var config = context.FullConfiguration; using (Logger.IndentLog("Attempting to inherit branch configuration from parent branch")) { var excludedBranches = new[] { targetBranch }; // Check if we are a merge commit. If so likely we are a pull request var parentCount = context.CurrentCommit.Parents.Count(); if (parentCount == 2) { excludedBranches = CalculateWhenMultipleParents(repository, context.CurrentCommit, ref targetBranch, excludedBranches); } if (excludedInheritBranches == null) { excludedInheritBranches = repository.Branches.Where(b => { var branchConfig = LookupBranchConfiguration(config, b).ToArray(); // NOTE: if length is 0 we couldn't find the configuration for the branch e.g. "origin/master" // NOTE: if the length is greater than 1 we cannot decide which merge strategy to pick return (branchConfig.Length != 1) || (branchConfig.Length == 1 && branchConfig[0].Increment == IncrementStrategy.Inherit); }).ToList(); } // Add new excluded branches. foreach (var excludedBranch in excludedBranches.ExcludingBranches(excludedInheritBranches)) { excludedInheritBranches.Add(excludedBranch); } var branchesToEvaluate = repository.Branches.Except(excludedInheritBranches).ToList(); var branchPoint = context.RepositoryMetadataProvider .FindCommitBranchWasBranchedFrom(targetBranch, excludedInheritBranches.ToArray()); List<Branch> possibleParents; if (branchPoint == BranchCommit.Empty) { possibleParents = context.RepositoryMetadataProvider.GetBranchesContainingCommit(context.CurrentCommit, branchesToEvaluate, true) // It fails to inherit Increment branch configuration if more than 1 parent; // therefore no point to get more than 2 parents .Take(2) .ToList(); } else { var branches = context.RepositoryMetadataProvider .GetBranchesContainingCommit(branchPoint.Commit, branchesToEvaluate, true).ToList(); if (branches.Count > 1) { var currentTipBranches = context.RepositoryMetadataProvider .GetBranchesContainingCommit(context.CurrentCommit, branchesToEvaluate, true).ToList(); possibleParents = branches.Except(currentTipBranches).ToList(); } else { possibleParents = branches; } } Logger.WriteInfo("Found possible parent branches: " + string.Join(", ", possibleParents.Select(p => p.FriendlyName))); if (possibleParents.Count == 1) { var branchConfig = GetBranchConfiguration(context, possibleParents[0], excludedInheritBranches); return new BranchConfig(branchConfiguration) { Increment = branchConfig.Increment, PreventIncrementOfMergedBranchVersion = branchConfig.PreventIncrementOfMergedBranchVersion, // If we are inheriting from develop then we should behave like develop TracksReleaseBranches = branchConfig.TracksReleaseBranches }; } // If we fail to inherit it is probably because the branch has been merged and we can't do much. So we will fall back to develop's config // if develop exists and master if not string errorMessage; if (possibleParents.Count == 0) errorMessage = "Failed to inherit Increment branch configuration, no branches found."; else errorMessage = "Failed to inherit Increment branch configuration, ended up with: " + string.Join(", ", possibleParents.Select(p => p.FriendlyName)); var chosenBranch = repository.Branches.FirstOrDefault(b => Regex.IsMatch(b.FriendlyName, "^develop", RegexOptions.IgnoreCase) || Regex.IsMatch(b.FriendlyName, "master$", RegexOptions.IgnoreCase)); if (chosenBranch == null) { // TODO We should call the build server to generate this exception, each build server works differently // for fetch issues and we could give better warnings. throw new InvalidOperationException("Could not find a 'develop' or 'master' branch, neither locally nor remotely."); } var branchName = chosenBranch.FriendlyName; Logger.WriteWarning(errorMessage + Environment.NewLine + Environment.NewLine + "Falling back to " + branchName + " branch config"); // To prevent infinite loops, make sure that a new branch was chosen. if (targetBranch.IsSameBranch(chosenBranch)) { Logger.WriteWarning("Fallback branch wants to inherit Increment branch configuration from itself. Using patch increment instead."); return new BranchConfig(branchConfiguration) { Increment = IncrementStrategy.Patch }; } var inheritingBranchConfig = GetBranchConfiguration(context, chosenBranch, excludedInheritBranches); return new BranchConfig(branchConfiguration) { Increment = inheritingBranchConfig.Increment, PreventIncrementOfMergedBranchVersion = inheritingBranchConfig.PreventIncrementOfMergedBranchVersion, // If we are inheriting from develop then we should behave like develop TracksReleaseBranches = inheritingBranchConfig.TracksReleaseBranches }; } } static Branch[] CalculateWhenMultipleParents(IRepository repository, Commit currentCommit, ref Branch currentBranch, Branch[] excludedBranches) { var parents = currentCommit.Parents.ToArray(); var branches = repository.Branches.Where(b => !b.IsRemote && b.Tip == parents[1]).ToList(); if (branches.Count == 1) { var branch = branches[0]; excludedBranches = new[] { currentBranch, branch }; currentBranch = branch; } else if (branches.Count > 1) { currentBranch = branches.FirstOrDefault(b => b.FriendlyName == "master") ?? branches.First(); } else { var possibleTargetBranches = repository.Branches.Where(b => !b.IsRemote && b.Tip == parents[0]).ToList(); if (possibleTargetBranches.Count > 1) { currentBranch = possibleTargetBranches.FirstOrDefault(b => b.FriendlyName == "master") ?? possibleTargetBranches.First(); } else { currentBranch = possibleTargetBranches.FirstOrDefault() ?? currentBranch; } } Logger.WriteInfo("HEAD is merge commit, this is likely a pull request using " + currentBranch.FriendlyName + " as base"); return excludedBranches; } } }
// 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; namespace Microsoft.CSharp.RuntimeBinder.Semantics { internal abstract class ExprVisitorBase { protected Expr Visit(Expr pExpr) => pExpr == null ? null : Dispatch(pExpr); protected virtual Expr Dispatch(Expr pExpr) => pExpr.Kind switch { ExpressionKind.BinaryOp => VisitBINOP(pExpr as ExprBinOp), ExpressionKind.UnaryOp => VisitUNARYOP(pExpr as ExprUnaryOp), ExpressionKind.Assignment => VisitASSIGNMENT(pExpr as ExprAssignment), ExpressionKind.List => VisitLIST(pExpr as ExprList), ExpressionKind.ArrayIndex => VisitARRAYINDEX(pExpr as ExprArrayIndex), ExpressionKind.Call => VisitCALL(pExpr as ExprCall), ExpressionKind.Field => VisitFIELD(pExpr as ExprField), ExpressionKind.Local => VisitLOCAL(pExpr as ExprLocal), ExpressionKind.Constant => VisitCONSTANT(pExpr as ExprConstant), ExpressionKind.Class => pExpr, ExpressionKind.Property => VisitPROP(pExpr as ExprProperty), ExpressionKind.Multi => VisitMULTI(pExpr as ExprMulti), ExpressionKind.MultiGet => VisitMULTIGET(pExpr as ExprMultiGet), ExpressionKind.Wrap => VisitWRAP(pExpr as ExprWrap), ExpressionKind.Concat => VisitCONCAT(pExpr as ExprConcat), ExpressionKind.ArrayInit => VisitARRINIT(pExpr as ExprArrayInit), ExpressionKind.Cast => VisitCAST(pExpr as ExprCast), ExpressionKind.UserDefinedConversion => VisitUSERDEFINEDCONVERSION(pExpr as ExprUserDefinedConversion), ExpressionKind.TypeOf => VisitTYPEOF(pExpr as ExprTypeOf), ExpressionKind.ZeroInit => VisitZEROINIT(pExpr as ExprZeroInit), ExpressionKind.UserLogicalOp => VisitUSERLOGOP(pExpr as ExprUserLogicalOp), ExpressionKind.MemberGroup => VisitMEMGRP(pExpr as ExprMemberGroup), ExpressionKind.FieldInfo => VisitFIELDINFO(pExpr as ExprFieldInfo), ExpressionKind.MethodInfo => VisitMETHODINFO(pExpr as ExprMethodInfo), // Binary operators ExpressionKind.EqualsParam => VisitEQUALS(pExpr as ExprBinOp), ExpressionKind.Compare => VisitCOMPARE(pExpr as ExprBinOp), ExpressionKind.NotEq => VisitNE(pExpr as ExprBinOp), ExpressionKind.LessThan => VisitLT(pExpr as ExprBinOp), ExpressionKind.LessThanOrEqual => VisitLE(pExpr as ExprBinOp), ExpressionKind.GreaterThan => VisitGT(pExpr as ExprBinOp), ExpressionKind.GreaterThanOrEqual => VisitGE(pExpr as ExprBinOp), ExpressionKind.Add => VisitADD(pExpr as ExprBinOp), ExpressionKind.Subtract => VisitSUB(pExpr as ExprBinOp), ExpressionKind.Multiply => VisitMUL(pExpr as ExprBinOp), ExpressionKind.Divide => VisitDIV(pExpr as ExprBinOp), ExpressionKind.Modulo => VisitMOD(pExpr as ExprBinOp), ExpressionKind.BitwiseAnd => VisitBITAND(pExpr as ExprBinOp), ExpressionKind.BitwiseOr => VisitBITOR(pExpr as ExprBinOp), ExpressionKind.BitwiseExclusiveOr => VisitBITXOR(pExpr as ExprBinOp), ExpressionKind.LeftShirt => VisitLSHIFT(pExpr as ExprBinOp), ExpressionKind.RightShift => VisitRSHIFT(pExpr as ExprBinOp), ExpressionKind.LogicalAnd => VisitLOGAND(pExpr as ExprBinOp), ExpressionKind.LogicalOr => VisitLOGOR(pExpr as ExprBinOp), ExpressionKind.Sequence => VisitSEQUENCE(pExpr as ExprBinOp), ExpressionKind.Save => VisitSAVE(pExpr as ExprBinOp), ExpressionKind.Swap => VisitSWAP(pExpr as ExprBinOp), ExpressionKind.Indir => VisitINDIR(pExpr as ExprBinOp), ExpressionKind.StringEq => VisitSTRINGEQ(pExpr as ExprBinOp), ExpressionKind.StringNotEq => VisitSTRINGNE(pExpr as ExprBinOp), ExpressionKind.DelegateEq => VisitDELEGATEEQ(pExpr as ExprBinOp), ExpressionKind.DelegateNotEq => VisitDELEGATENE(pExpr as ExprBinOp), ExpressionKind.DelegateAdd => VisitDELEGATEADD(pExpr as ExprBinOp), ExpressionKind.DelegateSubtract => VisitDELEGATESUB(pExpr as ExprBinOp), ExpressionKind.Eq => VisitEQ(pExpr as ExprBinOp), // Unary operators ExpressionKind.True => VisitTRUE(pExpr as ExprUnaryOp), ExpressionKind.False => VisitFALSE(pExpr as ExprUnaryOp), ExpressionKind.Inc => VisitINC(pExpr as ExprUnaryOp), ExpressionKind.Dec => VisitDEC(pExpr as ExprUnaryOp), ExpressionKind.LogicalNot => VisitLOGNOT(pExpr as ExprUnaryOp), ExpressionKind.Negate => VisitNEG(pExpr as ExprUnaryOp), ExpressionKind.UnaryPlus => VisitUPLUS(pExpr as ExprUnaryOp), ExpressionKind.BitwiseNot => VisitBITNOT(pExpr as ExprUnaryOp), ExpressionKind.Addr => VisitADDR(pExpr as ExprUnaryOp), ExpressionKind.DecimalNegate => VisitDECIMALNEG(pExpr as ExprUnaryOp), ExpressionKind.DecimalInc => VisitDECIMALINC(pExpr as ExprUnaryOp), ExpressionKind.DecimalDec => VisitDECIMALDEC(pExpr as ExprUnaryOp), _ => throw Error.InternalCompilerError(), }; private void VisitChildren(Expr pExpr) { Debug.Assert(pExpr != null); Expr exprRet; switch (pExpr.Kind) { case ExpressionKind.List: // Lists are a special case. We treat a list not as a // binary node but rather as a node with n children. ExprList list = (ExprList)pExpr; while (true) { list.OptionalElement = Visit(list.OptionalElement); Expr nextNode = list.OptionalNextListNode; if (nextNode == null) { return; } if (!(nextNode is ExprList next)) { list.OptionalNextListNode = Visit(nextNode); return; } list = next; } case ExpressionKind.Assignment: exprRet = Visit((pExpr as ExprAssignment).LHS); Debug.Assert(exprRet != null); (pExpr as ExprAssignment).LHS = exprRet; exprRet = Visit((pExpr as ExprAssignment).RHS); Debug.Assert(exprRet != null); (pExpr as ExprAssignment).RHS = exprRet; break; case ExpressionKind.ArrayIndex: exprRet = Visit((pExpr as ExprArrayIndex).Array); Debug.Assert(exprRet != null); (pExpr as ExprArrayIndex).Array = exprRet; exprRet = Visit((pExpr as ExprArrayIndex).Index); Debug.Assert(exprRet != null); (pExpr as ExprArrayIndex).Index = exprRet; break; case ExpressionKind.UnaryOp: case ExpressionKind.True: case ExpressionKind.False: case ExpressionKind.Inc: case ExpressionKind.Dec: case ExpressionKind.LogicalNot: case ExpressionKind.Negate: case ExpressionKind.UnaryPlus: case ExpressionKind.BitwiseNot: case ExpressionKind.Addr: case ExpressionKind.DecimalNegate: case ExpressionKind.DecimalInc: case ExpressionKind.DecimalDec: exprRet = Visit((pExpr as ExprUnaryOp).Child); Debug.Assert(exprRet != null); (pExpr as ExprUnaryOp).Child = exprRet; break; case ExpressionKind.UserLogicalOp: exprRet = Visit((pExpr as ExprUserLogicalOp).TrueFalseCall); Debug.Assert(exprRet != null); (pExpr as ExprUserLogicalOp).TrueFalseCall = exprRet; exprRet = Visit((pExpr as ExprUserLogicalOp).OperatorCall); Debug.Assert(exprRet != null); (pExpr as ExprUserLogicalOp).OperatorCall = exprRet as ExprCall; exprRet = Visit((pExpr as ExprUserLogicalOp).FirstOperandToExamine); Debug.Assert(exprRet != null); (pExpr as ExprUserLogicalOp).FirstOperandToExamine = exprRet; break; case ExpressionKind.TypeOf: break; case ExpressionKind.Cast: exprRet = Visit((pExpr as ExprCast).Argument); Debug.Assert(exprRet != null); (pExpr as ExprCast).Argument = exprRet; break; case ExpressionKind.UserDefinedConversion: exprRet = Visit((pExpr as ExprUserDefinedConversion).UserDefinedCall); Debug.Assert(exprRet != null); (pExpr as ExprUserDefinedConversion).UserDefinedCall = exprRet; break; case ExpressionKind.ZeroInit: break; case ExpressionKind.MemberGroup: // The object expression. NULL for a static invocation. exprRet = Visit((pExpr as ExprMemberGroup).OptionalObject); (pExpr as ExprMemberGroup).OptionalObject = exprRet; break; case ExpressionKind.Call: exprRet = Visit((pExpr as ExprCall).OptionalArguments); (pExpr as ExprCall).OptionalArguments = exprRet; exprRet = Visit((pExpr as ExprCall).MemberGroup); Debug.Assert(exprRet != null); (pExpr as ExprCall).MemberGroup = exprRet as ExprMemberGroup; break; case ExpressionKind.Property: exprRet = Visit((pExpr as ExprProperty).OptionalArguments); (pExpr as ExprProperty).OptionalArguments = exprRet; exprRet = Visit((pExpr as ExprProperty).MemberGroup); Debug.Assert(exprRet != null); (pExpr as ExprProperty).MemberGroup = exprRet as ExprMemberGroup; break; case ExpressionKind.Field: exprRet = Visit((pExpr as ExprField).OptionalObject); (pExpr as ExprField).OptionalObject = exprRet; break; case ExpressionKind.Constant: // Used for when we zeroinit 0 parameter constructors for structs/enums. exprRet = Visit((pExpr as ExprConstant).OptionalConstructorCall); (pExpr as ExprConstant).OptionalConstructorCall = exprRet; break; /************************************************************************************************* TYPEEXPRs defined: The following exprs are used to represent the results of type binding, and are defined as follows: TYPEARGUMENTS - This wraps the type arguments for a class. It contains the TypeArray* which is associated with the AggregateType for the instantiation of the class. TYPEORNAMESPACE - This is the base class for this set of Exprs. When binding a type, the result must be a type or a namespace. This Expr encapsulates that fact. The lhs member is the Expr tree that was bound to resolve the type or namespace. TYPEORNAMESPACEERROR - This is the error class for the type or namespace exprs when we don't know what to bind it to. The following two exprs all have a TYPEORNAMESPACE child, which is their fundamental type: POINTERTYPE - This wraps the sym for the pointer type. NULLABLETYPE - This wraps the sym for the nullable type. CLASS - This represents an instantiation of a class. NSPACE - This represents a namespace, which is the intermediate step when attempting to bind a qualified name. ALIAS - This represents an alias *************************************************************************************************/ case ExpressionKind.Multi: exprRet = Visit((pExpr as ExprMulti).Left); Debug.Assert(exprRet != null); (pExpr as ExprMulti).Left = exprRet; exprRet = Visit((pExpr as ExprMulti).Operator); Debug.Assert(exprRet != null); (pExpr as ExprMulti).Operator = exprRet; break; case ExpressionKind.Concat: exprRet = Visit((pExpr as ExprConcat).FirstArgument); Debug.Assert(exprRet != null); (pExpr as ExprConcat).FirstArgument = exprRet; exprRet = Visit((pExpr as ExprConcat).SecondArgument); Debug.Assert(exprRet != null); (pExpr as ExprConcat).SecondArgument = exprRet; break; case ExpressionKind.ArrayInit: exprRet = Visit((pExpr as ExprArrayInit).OptionalArguments); (pExpr as ExprArrayInit).OptionalArguments = exprRet; exprRet = Visit((pExpr as ExprArrayInit).OptionalArgumentDimensions); (pExpr as ExprArrayInit).OptionalArgumentDimensions = exprRet; break; case ExpressionKind.Local: case ExpressionKind.Class: case ExpressionKind.MultiGet: case ExpressionKind.Wrap: case ExpressionKind.NoOp: case ExpressionKind.FieldInfo: case ExpressionKind.MethodInfo: break; default: pExpr.AssertIsBin(); exprRet = Visit((pExpr as ExprBinOp).OptionalLeftChild); (pExpr as ExprBinOp).OptionalLeftChild = exprRet; exprRet = Visit((pExpr as ExprBinOp).OptionalRightChild); (pExpr as ExprBinOp).OptionalRightChild = exprRet; break; } } protected virtual Expr VisitEXPR(Expr pExpr) { VisitChildren(pExpr); return pExpr; } protected virtual Expr VisitBINOP(ExprBinOp pExpr) { return VisitEXPR(pExpr); } protected virtual Expr VisitLIST(ExprList pExpr) { return VisitEXPR(pExpr); } protected virtual Expr VisitASSIGNMENT(ExprAssignment pExpr) { return VisitEXPR(pExpr); } protected virtual Expr VisitARRAYINDEX(ExprArrayIndex pExpr) { return VisitEXPR(pExpr); } protected virtual Expr VisitUNARYOP(ExprUnaryOp pExpr) { return VisitEXPR(pExpr); } protected virtual Expr VisitUSERLOGOP(ExprUserLogicalOp pExpr) { return VisitEXPR(pExpr); } protected virtual Expr VisitTYPEOF(ExprTypeOf pExpr) { return VisitEXPR(pExpr); } protected virtual Expr VisitCAST(ExprCast pExpr) { return VisitEXPR(pExpr); } protected virtual Expr VisitUSERDEFINEDCONVERSION(ExprUserDefinedConversion pExpr) { return VisitEXPR(pExpr); } protected virtual Expr VisitZEROINIT(ExprZeroInit pExpr) { return VisitEXPR(pExpr); } protected virtual Expr VisitMEMGRP(ExprMemberGroup pExpr) { return VisitEXPR(pExpr); } protected virtual Expr VisitCALL(ExprCall pExpr) { return VisitEXPR(pExpr); } protected virtual Expr VisitPROP(ExprProperty pExpr) { return VisitEXPR(pExpr); } protected virtual Expr VisitFIELD(ExprField pExpr) { return VisitEXPR(pExpr); } protected virtual Expr VisitLOCAL(ExprLocal pExpr) { return VisitEXPR(pExpr); } protected virtual Expr VisitCONSTANT(ExprConstant pExpr) { return VisitEXPR(pExpr); } protected virtual Expr VisitMULTIGET(ExprMultiGet pExpr) { return VisitEXPR(pExpr); } protected virtual Expr VisitMULTI(ExprMulti pExpr) { return VisitEXPR(pExpr); } protected virtual Expr VisitWRAP(ExprWrap pExpr) { return VisitEXPR(pExpr); } protected virtual Expr VisitCONCAT(ExprConcat pExpr) { return VisitEXPR(pExpr); } protected virtual Expr VisitARRINIT(ExprArrayInit pExpr) { return VisitEXPR(pExpr); } protected virtual Expr VisitFIELDINFO(ExprFieldInfo pExpr) { return VisitEXPR(pExpr); } protected virtual Expr VisitMETHODINFO(ExprMethodInfo pExpr) { return VisitEXPR(pExpr); } protected virtual Expr VisitEQUALS(ExprBinOp pExpr) { return VisitBINOP(pExpr); } protected virtual Expr VisitCOMPARE(ExprBinOp pExpr) { return VisitBINOP(pExpr); } protected virtual Expr VisitEQ(ExprBinOp pExpr) { return VisitBINOP(pExpr); } protected virtual Expr VisitNE(ExprBinOp pExpr) { return VisitBINOP(pExpr); } protected virtual Expr VisitLE(ExprBinOp pExpr) { return VisitBINOP(pExpr); } protected virtual Expr VisitGE(ExprBinOp pExpr) { return VisitBINOP(pExpr); } protected virtual Expr VisitADD(ExprBinOp pExpr) { return VisitBINOP(pExpr); } protected virtual Expr VisitSUB(ExprBinOp pExpr) { return VisitBINOP(pExpr); } protected virtual Expr VisitDIV(ExprBinOp pExpr) { return VisitBINOP(pExpr); } protected virtual Expr VisitBITAND(ExprBinOp pExpr) { return VisitBINOP(pExpr); } protected virtual Expr VisitBITOR(ExprBinOp pExpr) { return VisitBINOP(pExpr); } protected virtual Expr VisitLSHIFT(ExprBinOp pExpr) { return VisitBINOP(pExpr); } protected virtual Expr VisitLOGAND(ExprBinOp pExpr) { return VisitBINOP(pExpr); } protected virtual Expr VisitSEQUENCE(ExprBinOp pExpr) { return VisitBINOP(pExpr); } protected virtual Expr VisitSAVE(ExprBinOp pExpr) { return VisitBINOP(pExpr); } protected virtual Expr VisitINDIR(ExprBinOp pExpr) { return VisitBINOP(pExpr); } protected virtual Expr VisitSTRINGEQ(ExprBinOp pExpr) { return VisitBINOP(pExpr); } protected virtual Expr VisitDELEGATEEQ(ExprBinOp pExpr) { return VisitBINOP(pExpr); } protected virtual Expr VisitDELEGATEADD(ExprBinOp pExpr) { return VisitBINOP(pExpr); } protected virtual Expr VisitLT(ExprBinOp pExpr) { return VisitBINOP(pExpr); } protected virtual Expr VisitMUL(ExprBinOp pExpr) { return VisitBINOP(pExpr); } protected virtual Expr VisitBITXOR(ExprBinOp pExpr) { return VisitBINOP(pExpr); } protected virtual Expr VisitRSHIFT(ExprBinOp pExpr) { return VisitBINOP(pExpr); } protected virtual Expr VisitLOGOR(ExprBinOp pExpr) { return VisitBINOP(pExpr); } protected virtual Expr VisitSTRINGNE(ExprBinOp pExpr) { return VisitBINOP(pExpr); } protected virtual Expr VisitDELEGATENE(ExprBinOp pExpr) { return VisitBINOP(pExpr); } protected virtual Expr VisitGT(ExprBinOp pExpr) { return VisitBINOP(pExpr); } protected virtual Expr VisitMOD(ExprBinOp pExpr) { return VisitBINOP(pExpr); } protected virtual Expr VisitSWAP(ExprBinOp pExpr) { return VisitBINOP(pExpr); } protected virtual Expr VisitDELEGATESUB(ExprBinOp pExpr) { return VisitBINOP(pExpr); } protected virtual Expr VisitTRUE(ExprUnaryOp pExpr) { return VisitUNARYOP(pExpr); } protected virtual Expr VisitINC(ExprUnaryOp pExpr) { return VisitUNARYOP(pExpr); } protected virtual Expr VisitLOGNOT(ExprUnaryOp pExpr) { return VisitUNARYOP(pExpr); } protected virtual Expr VisitNEG(ExprUnaryOp pExpr) { return VisitUNARYOP(pExpr); } protected virtual Expr VisitBITNOT(ExprUnaryOp pExpr) { return VisitUNARYOP(pExpr); } protected virtual Expr VisitADDR(ExprUnaryOp pExpr) { return VisitUNARYOP(pExpr); } protected virtual Expr VisitDECIMALNEG(ExprUnaryOp pExpr) { return VisitUNARYOP(pExpr); } protected virtual Expr VisitDECIMALDEC(ExprUnaryOp pExpr) { return VisitUNARYOP(pExpr); } protected virtual Expr VisitFALSE(ExprUnaryOp pExpr) { return VisitUNARYOP(pExpr); } protected virtual Expr VisitDEC(ExprUnaryOp pExpr) { return VisitUNARYOP(pExpr); } protected virtual Expr VisitUPLUS(ExprUnaryOp pExpr) { return VisitUNARYOP(pExpr); } protected virtual Expr VisitDECIMALINC(ExprUnaryOp pExpr) { return VisitUNARYOP(pExpr); } } }
// 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.Diagnostics.CodeAnalysis; namespace System.Net.Http.Headers { [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "This is not a collection")] public sealed class HttpRequestHeaders : HttpHeaders { private static readonly Dictionary<string, HttpHeaderParser> s_parserStore = CreateParserStore(); private static readonly HashSet<string> s_invalidHeaders = CreateInvalidHeaders(); private const int AcceptSlot = 0; private const int AcceptCharsetSlot = 1; private const int AcceptEncodingSlot = 2; private const int AcceptLanguageSlot = 3; private const int ExpectSlot = 4; private const int IfMatchSlot = 5; private const int IfNoneMatchSlot = 6; private const int TransferEncodingSlot = 7; private const int UserAgentSlot = 8; private const int NumCollectionsSlots = 9; private object[] _specialCollectionsSlots; private HttpGeneralHeaders _generalHeaders; private bool _expectContinueSet; #region Request Headers private T GetSpecializedCollection<T>(int slot, Func<HttpRequestHeaders, T> creationFunc) { // 9 properties each lazily allocate a collection to store the value(s) for that property. // Rather than having a field for each of these, store them untyped in an array that's lazily // allocated. Then we only pay for the 72 bytes for those fields when any is actually accessed. object[] collections = _specialCollectionsSlots ?? (_specialCollectionsSlots = new object[NumCollectionsSlots]); object result = collections[slot]; if (result == null) { collections[slot] = result = creationFunc(this); } return (T)result; } public HttpHeaderValueCollection<MediaTypeWithQualityHeaderValue> Accept => GetSpecializedCollection(AcceptSlot, thisRef => new HttpHeaderValueCollection<MediaTypeWithQualityHeaderValue>(HttpKnownHeaderNames.Accept, thisRef)); [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Charset", Justification = "The HTTP header name is 'Accept-Charset'.")] public HttpHeaderValueCollection<StringWithQualityHeaderValue> AcceptCharset => GetSpecializedCollection(AcceptCharsetSlot, thisRef => new HttpHeaderValueCollection<StringWithQualityHeaderValue>(HttpKnownHeaderNames.AcceptCharset, thisRef)); public HttpHeaderValueCollection<StringWithQualityHeaderValue> AcceptEncoding => GetSpecializedCollection(AcceptEncodingSlot, thisRef => new HttpHeaderValueCollection<StringWithQualityHeaderValue>(HttpKnownHeaderNames.AcceptEncoding, thisRef)); public HttpHeaderValueCollection<StringWithQualityHeaderValue> AcceptLanguage => GetSpecializedCollection(AcceptLanguageSlot, thisRef => new HttpHeaderValueCollection<StringWithQualityHeaderValue>(HttpKnownHeaderNames.AcceptLanguage, thisRef)); public AuthenticationHeaderValue Authorization { get { return (AuthenticationHeaderValue)GetParsedValues(HttpKnownHeaderNames.Authorization); } set { SetOrRemoveParsedValue(HttpKnownHeaderNames.Authorization, value); } } public HttpHeaderValueCollection<NameValueWithParametersHeaderValue> Expect { get { return ExpectCore; } } public bool? ExpectContinue { get { if (ExpectCore.IsSpecialValueSet) { return true; } if (_expectContinueSet) { return false; } return null; } set { if (value == true) { _expectContinueSet = true; ExpectCore.SetSpecialValue(); } else { _expectContinueSet = value != null; ExpectCore.RemoveSpecialValue(); } } } public string From { get { return (string)GetParsedValues(HttpKnownHeaderNames.From); } set { // Null and empty string are equivalent. In this case it means, remove the From header value (if any). if (value == string.Empty) { value = null; } if ((value != null) && !HeaderUtilities.IsValidEmailAddress(value)) { throw new FormatException(SR.net_http_headers_invalid_from_header); } SetOrRemoveParsedValue(HttpKnownHeaderNames.From, value); } } public string Host { get { return (string)GetParsedValues(HttpKnownHeaderNames.Host); } set { // Null and empty string are equivalent. In this case it means, remove the Host header value (if any). if (value == string.Empty) { value = null; } string host = null; if ((value != null) && (HttpRuleParser.GetHostLength(value, 0, false, out host) != value.Length)) { throw new FormatException(SR.net_http_headers_invalid_host_header); } SetOrRemoveParsedValue(HttpKnownHeaderNames.Host, value); } } public HttpHeaderValueCollection<EntityTagHeaderValue> IfMatch => GetSpecializedCollection(IfMatchSlot, thisRef => new HttpHeaderValueCollection<EntityTagHeaderValue>(HttpKnownHeaderNames.IfMatch, thisRef)); public DateTimeOffset? IfModifiedSince { get { return HeaderUtilities.GetDateTimeOffsetValue(HttpKnownHeaderNames.IfModifiedSince, this); } set { SetOrRemoveParsedValue(HttpKnownHeaderNames.IfModifiedSince, value); } } public HttpHeaderValueCollection<EntityTagHeaderValue> IfNoneMatch => GetSpecializedCollection(IfNoneMatchSlot, thisRef => new HttpHeaderValueCollection<EntityTagHeaderValue>(HttpKnownHeaderNames.IfNoneMatch, thisRef)); public RangeConditionHeaderValue IfRange { get { return (RangeConditionHeaderValue)GetParsedValues(HttpKnownHeaderNames.IfRange); } set { SetOrRemoveParsedValue(HttpKnownHeaderNames.IfRange, value); } } public DateTimeOffset? IfUnmodifiedSince { get { return HeaderUtilities.GetDateTimeOffsetValue(HttpKnownHeaderNames.IfUnmodifiedSince, this); } set { SetOrRemoveParsedValue(HttpKnownHeaderNames.IfUnmodifiedSince, value); } } public int? MaxForwards { get { object storedValue = GetParsedValues(HttpKnownHeaderNames.MaxForwards); if (storedValue != null) { return (int)storedValue; } return null; } set { SetOrRemoveParsedValue(HttpKnownHeaderNames.MaxForwards, value); } } public AuthenticationHeaderValue ProxyAuthorization { get { return (AuthenticationHeaderValue)GetParsedValues(HttpKnownHeaderNames.ProxyAuthorization); } set { SetOrRemoveParsedValue(HttpKnownHeaderNames.ProxyAuthorization, value); } } public RangeHeaderValue Range { get { return (RangeHeaderValue)GetParsedValues(HttpKnownHeaderNames.Range); } set { SetOrRemoveParsedValue(HttpKnownHeaderNames.Range, value); } } public Uri Referrer { get { return (Uri)GetParsedValues(HttpKnownHeaderNames.Referer); } set { SetOrRemoveParsedValue(HttpKnownHeaderNames.Referer, value); } } public HttpHeaderValueCollection<TransferCodingWithQualityHeaderValue> TE => GetSpecializedCollection(TransferEncodingSlot, thisRef => new HttpHeaderValueCollection<TransferCodingWithQualityHeaderValue>(HttpKnownHeaderNames.TE, thisRef)); public HttpHeaderValueCollection<ProductInfoHeaderValue> UserAgent => GetSpecializedCollection(UserAgentSlot, thisRef => new HttpHeaderValueCollection<ProductInfoHeaderValue>(HttpKnownHeaderNames.UserAgent, thisRef)); private HttpHeaderValueCollection<NameValueWithParametersHeaderValue> ExpectCore => GetSpecializedCollection(ExpectSlot, thisRef => new HttpHeaderValueCollection<NameValueWithParametersHeaderValue>(HttpKnownHeaderNames.Expect, thisRef, HeaderUtilities.ExpectContinue)); #endregion #region General Headers public CacheControlHeaderValue CacheControl { get { return GeneralHeaders.CacheControl; } set { GeneralHeaders.CacheControl = value; } } public HttpHeaderValueCollection<string> Connection { get { return GeneralHeaders.Connection; } } public bool? ConnectionClose { get { return HttpGeneralHeaders.GetConnectionClose(this, _generalHeaders); } // special-cased to avoid forcing _generalHeaders initialization set { GeneralHeaders.ConnectionClose = value; } } public DateTimeOffset? Date { get { return GeneralHeaders.Date; } set { GeneralHeaders.Date = value; } } public HttpHeaderValueCollection<NameValueHeaderValue> Pragma { get { return GeneralHeaders.Pragma; } } public HttpHeaderValueCollection<string> Trailer { get { return GeneralHeaders.Trailer; } } public HttpHeaderValueCollection<TransferCodingHeaderValue> TransferEncoding { get { return GeneralHeaders.TransferEncoding; } } public bool? TransferEncodingChunked { get { return HttpGeneralHeaders.GetTransferEncodingChunked(this, _generalHeaders); } // special-cased to avoid forcing _generalHeaders initialization set { GeneralHeaders.TransferEncodingChunked = value; } } public HttpHeaderValueCollection<ProductHeaderValue> Upgrade { get { return GeneralHeaders.Upgrade; } } public HttpHeaderValueCollection<ViaHeaderValue> Via { get { return GeneralHeaders.Via; } } public HttpHeaderValueCollection<WarningHeaderValue> Warning { get { return GeneralHeaders.Warning; } } #endregion internal HttpRequestHeaders() { base.SetConfiguration(s_parserStore, s_invalidHeaders); } private static Dictionary<string, HttpHeaderParser> CreateParserStore() { var parserStore = new Dictionary<string, HttpHeaderParser>(StringComparer.OrdinalIgnoreCase); parserStore.Add(HttpKnownHeaderNames.Accept, MediaTypeHeaderParser.MultipleValuesParser); parserStore.Add(HttpKnownHeaderNames.AcceptCharset, GenericHeaderParser.MultipleValueStringWithQualityParser); parserStore.Add(HttpKnownHeaderNames.AcceptEncoding, GenericHeaderParser.MultipleValueStringWithQualityParser); parserStore.Add(HttpKnownHeaderNames.AcceptLanguage, GenericHeaderParser.MultipleValueStringWithQualityParser); parserStore.Add(HttpKnownHeaderNames.Authorization, GenericHeaderParser.SingleValueAuthenticationParser); parserStore.Add(HttpKnownHeaderNames.Expect, GenericHeaderParser.MultipleValueNameValueWithParametersParser); parserStore.Add(HttpKnownHeaderNames.From, GenericHeaderParser.MailAddressParser); parserStore.Add(HttpKnownHeaderNames.Host, GenericHeaderParser.HostParser); parserStore.Add(HttpKnownHeaderNames.IfMatch, GenericHeaderParser.MultipleValueEntityTagParser); parserStore.Add(HttpKnownHeaderNames.IfModifiedSince, DateHeaderParser.Parser); parserStore.Add(HttpKnownHeaderNames.IfNoneMatch, GenericHeaderParser.MultipleValueEntityTagParser); parserStore.Add(HttpKnownHeaderNames.IfRange, GenericHeaderParser.RangeConditionParser); parserStore.Add(HttpKnownHeaderNames.IfUnmodifiedSince, DateHeaderParser.Parser); parserStore.Add(HttpKnownHeaderNames.MaxForwards, Int32NumberHeaderParser.Parser); parserStore.Add(HttpKnownHeaderNames.ProxyAuthorization, GenericHeaderParser.SingleValueAuthenticationParser); parserStore.Add(HttpKnownHeaderNames.Range, GenericHeaderParser.RangeParser); parserStore.Add(HttpKnownHeaderNames.Referer, UriHeaderParser.RelativeOrAbsoluteUriParser); parserStore.Add(HttpKnownHeaderNames.TE, TransferCodingHeaderParser.MultipleValueWithQualityParser); parserStore.Add(HttpKnownHeaderNames.UserAgent, ProductInfoHeaderParser.MultipleValueParser); HttpGeneralHeaders.AddParsers(parserStore); return parserStore; } private static HashSet<string> CreateInvalidHeaders() { var invalidHeaders = new HashSet<string>(StringComparer.OrdinalIgnoreCase); HttpContentHeaders.AddKnownHeaders(invalidHeaders); return invalidHeaders; // Note: Reserved response header names are allowed as custom request header names. Reserved response // headers have no defined meaning or format when used on a request. This enables a server to accept // any headers sent from the client as either content headers or request headers. } internal static void AddKnownHeaders(HashSet<string> headerSet) { Debug.Assert(headerSet != null); headerSet.Add(HttpKnownHeaderNames.Accept); headerSet.Add(HttpKnownHeaderNames.AcceptCharset); headerSet.Add(HttpKnownHeaderNames.AcceptEncoding); headerSet.Add(HttpKnownHeaderNames.AcceptLanguage); headerSet.Add(HttpKnownHeaderNames.Authorization); headerSet.Add(HttpKnownHeaderNames.Expect); headerSet.Add(HttpKnownHeaderNames.From); headerSet.Add(HttpKnownHeaderNames.Host); headerSet.Add(HttpKnownHeaderNames.IfMatch); headerSet.Add(HttpKnownHeaderNames.IfModifiedSince); headerSet.Add(HttpKnownHeaderNames.IfNoneMatch); headerSet.Add(HttpKnownHeaderNames.IfRange); headerSet.Add(HttpKnownHeaderNames.IfUnmodifiedSince); headerSet.Add(HttpKnownHeaderNames.MaxForwards); headerSet.Add(HttpKnownHeaderNames.ProxyAuthorization); headerSet.Add(HttpKnownHeaderNames.Range); headerSet.Add(HttpKnownHeaderNames.Referer); headerSet.Add(HttpKnownHeaderNames.TE); headerSet.Add(HttpKnownHeaderNames.UserAgent); } internal override void AddHeaders(HttpHeaders sourceHeaders) { base.AddHeaders(sourceHeaders); HttpRequestHeaders sourceRequestHeaders = sourceHeaders as HttpRequestHeaders; Debug.Assert(sourceRequestHeaders != null); // Copy special values but do not overwrite. if (sourceRequestHeaders._generalHeaders != null) { GeneralHeaders.AddSpecialsFrom(sourceRequestHeaders._generalHeaders); } bool? expectContinue = ExpectContinue; if (!expectContinue.HasValue) { ExpectContinue = sourceRequestHeaders.ExpectContinue; } } private HttpGeneralHeaders GeneralHeaders => _generalHeaders ?? (_generalHeaders = new HttpGeneralHeaders(this)); } }
// MIT License // // Copyright (c) 2009-2017 Luca Piccioni // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // // This file is automatically generated #pragma warning disable 649, 1572, 1573 // ReSharper disable RedundantUsingDirective using System; using System.Diagnostics; using System.Runtime.InteropServices; using System.Security; using System.Text; using Khronos; // ReSharper disable CheckNamespace // ReSharper disable InconsistentNaming // ReSharper disable JoinDeclarationAndInitializer namespace OpenGL { public partial class Wgl { /// <summary> /// [WGL] Value of WGL_UNIQUE_ID_NV symbol. /// </summary> [RequiredByFeature("WGL_NV_video_capture")] public const int UNIQUE_ID_NV = 0x20CE; /// <summary> /// [WGL] Value of WGL_NUM_VIDEO_CAPTURE_SLOTS_NV symbol. /// </summary> [RequiredByFeature("WGL_NV_video_capture")] public const int NUM_VIDEO_CAPTURE_SLOTS_NV = 0x20CF; /// <summary> /// [WGL] wglBindVideoCaptureDeviceNV: Binding for wglBindVideoCaptureDeviceNV. /// </summary> /// <param name="uVideoSlot"> /// A <see cref="T:uint"/>. /// </param> /// <param name="hDevice"> /// A <see cref="T:IntPtr"/>. /// </param> [RequiredByFeature("WGL_NV_video_capture")] public static bool BindVideoCaptureDeviceNV(uint uVideoSlot, IntPtr hDevice) { bool retValue; Debug.Assert(Delegates.pwglBindVideoCaptureDeviceNV != null, "pwglBindVideoCaptureDeviceNV not implemented"); retValue = Delegates.pwglBindVideoCaptureDeviceNV(uVideoSlot, hDevice); LogCommand("wglBindVideoCaptureDeviceNV", retValue, uVideoSlot, hDevice ); DebugCheckErrors(retValue); return (retValue); } /// <summary> /// [WGL] wglEnumerateVideoCaptureDevicesNV: Binding for wglEnumerateVideoCaptureDevicesNV. /// </summary> /// <param name="hDc"> /// A <see cref="T:IntPtr"/>. /// </param> /// <param name="phDeviceList"> /// A <see cref="T:IntPtr[]"/>. /// </param> [RequiredByFeature("WGL_NV_video_capture")] public static uint EnumerateVideoCaptureDevicesNV(IntPtr hDc, IntPtr[] phDeviceList) { uint retValue; unsafe { fixed (IntPtr* p_phDeviceList = phDeviceList) { Debug.Assert(Delegates.pwglEnumerateVideoCaptureDevicesNV != null, "pwglEnumerateVideoCaptureDevicesNV not implemented"); retValue = Delegates.pwglEnumerateVideoCaptureDevicesNV(hDc, p_phDeviceList); LogCommand("wglEnumerateVideoCaptureDevicesNV", retValue, hDc, phDeviceList ); } } DebugCheckErrors(retValue); return (retValue); } /// <summary> /// [WGL] wglLockVideoCaptureDeviceNV: Binding for wglLockVideoCaptureDeviceNV. /// </summary> /// <param name="hDc"> /// A <see cref="T:IntPtr"/>. /// </param> /// <param name="hDevice"> /// A <see cref="T:IntPtr"/>. /// </param> [RequiredByFeature("WGL_NV_video_capture")] public static bool LockVideoCaptureDeviceNV(IntPtr hDc, IntPtr hDevice) { bool retValue; Debug.Assert(Delegates.pwglLockVideoCaptureDeviceNV != null, "pwglLockVideoCaptureDeviceNV not implemented"); retValue = Delegates.pwglLockVideoCaptureDeviceNV(hDc, hDevice); LogCommand("wglLockVideoCaptureDeviceNV", retValue, hDc, hDevice ); DebugCheckErrors(retValue); return (retValue); } /// <summary> /// [WGL] wglQueryVideoCaptureDeviceNV: Binding for wglQueryVideoCaptureDeviceNV. /// </summary> /// <param name="hDc"> /// A <see cref="T:IntPtr"/>. /// </param> /// <param name="hDevice"> /// A <see cref="T:IntPtr"/>. /// </param> /// <param name="iAttribute"> /// A <see cref="T:int"/>. /// </param> /// <param name="piValue"> /// A <see cref="T:int[]"/>. /// </param> [RequiredByFeature("WGL_NV_video_capture")] public static bool QueryVideoCaptureDeviceNV(IntPtr hDc, IntPtr hDevice, int iAttribute, int[] piValue) { bool retValue; unsafe { fixed (int* p_piValue = piValue) { Debug.Assert(Delegates.pwglQueryVideoCaptureDeviceNV != null, "pwglQueryVideoCaptureDeviceNV not implemented"); retValue = Delegates.pwglQueryVideoCaptureDeviceNV(hDc, hDevice, iAttribute, p_piValue); LogCommand("wglQueryVideoCaptureDeviceNV", retValue, hDc, hDevice, iAttribute, piValue ); } } DebugCheckErrors(retValue); return (retValue); } /// <summary> /// [WGL] wglReleaseVideoCaptureDeviceNV: Binding for wglReleaseVideoCaptureDeviceNV. /// </summary> /// <param name="hDc"> /// A <see cref="T:IntPtr"/>. /// </param> /// <param name="hDevice"> /// A <see cref="T:IntPtr"/>. /// </param> [RequiredByFeature("WGL_NV_video_capture")] public static bool ReleaseVideoCaptureDeviceNV(IntPtr hDc, IntPtr hDevice) { bool retValue; Debug.Assert(Delegates.pwglReleaseVideoCaptureDeviceNV != null, "pwglReleaseVideoCaptureDeviceNV not implemented"); retValue = Delegates.pwglReleaseVideoCaptureDeviceNV(hDc, hDevice); LogCommand("wglReleaseVideoCaptureDeviceNV", retValue, hDc, hDevice ); DebugCheckErrors(retValue); return (retValue); } internal static unsafe partial class Delegates { [RequiredByFeature("WGL_NV_video_capture")] [SuppressUnmanagedCodeSecurity] internal delegate bool wglBindVideoCaptureDeviceNV(uint uVideoSlot, IntPtr hDevice); [RequiredByFeature("WGL_NV_video_capture")] internal static wglBindVideoCaptureDeviceNV pwglBindVideoCaptureDeviceNV; [RequiredByFeature("WGL_NV_video_capture")] [SuppressUnmanagedCodeSecurity] internal delegate uint wglEnumerateVideoCaptureDevicesNV(IntPtr hDc, IntPtr* phDeviceList); [RequiredByFeature("WGL_NV_video_capture")] internal static wglEnumerateVideoCaptureDevicesNV pwglEnumerateVideoCaptureDevicesNV; [RequiredByFeature("WGL_NV_video_capture")] [SuppressUnmanagedCodeSecurity] internal delegate bool wglLockVideoCaptureDeviceNV(IntPtr hDc, IntPtr hDevice); [RequiredByFeature("WGL_NV_video_capture")] internal static wglLockVideoCaptureDeviceNV pwglLockVideoCaptureDeviceNV; [RequiredByFeature("WGL_NV_video_capture")] [SuppressUnmanagedCodeSecurity] internal delegate bool wglQueryVideoCaptureDeviceNV(IntPtr hDc, IntPtr hDevice, int iAttribute, int* piValue); [RequiredByFeature("WGL_NV_video_capture")] internal static wglQueryVideoCaptureDeviceNV pwglQueryVideoCaptureDeviceNV; [RequiredByFeature("WGL_NV_video_capture")] [SuppressUnmanagedCodeSecurity] internal delegate bool wglReleaseVideoCaptureDeviceNV(IntPtr hDc, IntPtr hDevice); [RequiredByFeature("WGL_NV_video_capture")] internal static wglReleaseVideoCaptureDeviceNV pwglReleaseVideoCaptureDeviceNV; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.CognitiveServices.Vision.Face { using Microsoft.CognitiveServices; using Microsoft.CognitiveServices.Vision; using Models; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; /// <summary> /// Extension methods for Person. /// </summary> public static partial class PersonExtensions { /// <summary> /// Create a new person in a specified person group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='personGroupId'> /// Specifying the target person group to create the person. /// </param> /// <param name='name'> /// Display name of the target person. The maximum length is 128. /// </param> /// <param name='userData'> /// Optional fields for user-provided data attached to a person. Size limit is /// 16KB. /// </param> public static CreatePersonResult Create(this IPerson operations, string personGroupId, string name = default(string), string userData = default(string)) { return operations.CreateAsync(personGroupId, name, userData).GetAwaiter().GetResult(); } /// <summary> /// Create a new person in a specified person group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='personGroupId'> /// Specifying the target person group to create the person. /// </param> /// <param name='name'> /// Display name of the target person. The maximum length is 128. /// </param> /// <param name='userData'> /// Optional fields for user-provided data attached to a person. Size limit is /// 16KB. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<CreatePersonResult> CreateAsync(this IPerson operations, string personGroupId, string name = default(string), string userData = default(string), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CreateWithHttpMessagesAsync(personGroupId, name, userData, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// List all persons in a person group, and retrieve person information /// (including personId, name, userData and persistedFaceIds of registered /// faces of the person). /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='personGroupId'> /// personGroupId of the target person group. /// </param> public static IList<PersonResult> List(this IPerson operations, string personGroupId) { return operations.ListAsync(personGroupId).GetAwaiter().GetResult(); } /// <summary> /// List all persons in a person group, and retrieve person information /// (including personId, name, userData and persistedFaceIds of registered /// faces of the person). /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='personGroupId'> /// personGroupId of the target person group. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IList<PersonResult>> ListAsync(this IPerson operations, string personGroupId, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListWithHttpMessagesAsync(personGroupId, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Delete an existing person from a person group. Persisted face images of the /// person will also be deleted. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='personGroupId'> /// Specifying the person group containing the person. /// </param> /// <param name='personId'> /// The target personId to delete. /// </param> public static void Delete(this IPerson operations, string personGroupId, string personId) { operations.DeleteAsync(personGroupId, personId).GetAwaiter().GetResult(); } /// <summary> /// Delete an existing person from a person group. Persisted face images of the /// person will also be deleted. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='personGroupId'> /// Specifying the person group containing the person. /// </param> /// <param name='personId'> /// The target personId to delete. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task DeleteAsync(this IPerson operations, string personGroupId, string personId, CancellationToken cancellationToken = default(CancellationToken)) { (await operations.DeleteWithHttpMessagesAsync(personGroupId, personId, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Retrieve a person's information, including registered persisted faces, name /// and userData. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='personGroupId'> /// Specifying the person group containing the target person. /// </param> /// <param name='personId'> /// Specifying the target person. /// </param> public static PersonResult Get(this IPerson operations, string personGroupId, string personId) { return operations.GetAsync(personGroupId, personId).GetAwaiter().GetResult(); } /// <summary> /// Retrieve a person's information, including registered persisted faces, name /// and userData. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='personGroupId'> /// Specifying the person group containing the target person. /// </param> /// <param name='personId'> /// Specifying the target person. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<PersonResult> GetAsync(this IPerson operations, string personGroupId, string personId, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetWithHttpMessagesAsync(personGroupId, personId, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Update name or userData of a person. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='personGroupId'> /// Specifying the person group containing the target person. /// </param> /// <param name='personId'> /// personId of the target person. /// </param> /// <param name='name'> /// Display name of the target person. The maximum length is 128. /// </param> /// <param name='userData'> /// Optional fields for user-provided data attached to a person. Size limit is /// 16KB. /// </param> public static void Update(this IPerson operations, string personGroupId, string personId, string name = default(string), string userData = default(string)) { operations.UpdateAsync(personGroupId, personId, name, userData).GetAwaiter().GetResult(); } /// <summary> /// Update name or userData of a person. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='personGroupId'> /// Specifying the person group containing the target person. /// </param> /// <param name='personId'> /// personId of the target person. /// </param> /// <param name='name'> /// Display name of the target person. The maximum length is 128. /// </param> /// <param name='userData'> /// Optional fields for user-provided data attached to a person. Size limit is /// 16KB. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task UpdateAsync(this IPerson operations, string personGroupId, string personId, string name = default(string), string userData = default(string), CancellationToken cancellationToken = default(CancellationToken)) { (await operations.UpdateWithHttpMessagesAsync(personGroupId, personId, name, userData, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Delete a face from a person. Relative image for the persisted face will /// also be deleted. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='personGroupId'> /// Specifying the person group containing the target person. /// </param> /// <param name='personId'> /// Specifying the person that the target persisted face belong to. /// </param> /// <param name='persistedFaceId'> /// The persisted face to remove. /// </param> public static void DeleteFace(this IPerson operations, string personGroupId, string personId, string persistedFaceId) { operations.DeleteFaceAsync(personGroupId, personId, persistedFaceId).GetAwaiter().GetResult(); } /// <summary> /// Delete a face from a person. Relative image for the persisted face will /// also be deleted. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='personGroupId'> /// Specifying the person group containing the target person. /// </param> /// <param name='personId'> /// Specifying the person that the target persisted face belong to. /// </param> /// <param name='persistedFaceId'> /// The persisted face to remove. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task DeleteFaceAsync(this IPerson operations, string personGroupId, string personId, string persistedFaceId, CancellationToken cancellationToken = default(CancellationToken)) { (await operations.DeleteFaceWithHttpMessagesAsync(personGroupId, personId, persistedFaceId, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Retrieve information about a persisted face (specified by persistedFaceId, /// personId and its belonging personGroupId). /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='personGroupId'> /// Specifying the person group containing the target person. /// </param> /// <param name='personId'> /// Specifying the target person that the face belongs to. /// </param> /// <param name='persistedFaceId'> /// The persistedFaceId of the target persisted face of the person. /// </param> public static PersonFaceResult GetFace(this IPerson operations, string personGroupId, string personId, string persistedFaceId) { return operations.GetFaceAsync(personGroupId, personId, persistedFaceId).GetAwaiter().GetResult(); } /// <summary> /// Retrieve information about a persisted face (specified by persistedFaceId, /// personId and its belonging personGroupId). /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='personGroupId'> /// Specifying the person group containing the target person. /// </param> /// <param name='personId'> /// Specifying the target person that the face belongs to. /// </param> /// <param name='persistedFaceId'> /// The persistedFaceId of the target persisted face of the person. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<PersonFaceResult> GetFaceAsync(this IPerson operations, string personGroupId, string personId, string persistedFaceId, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetFaceWithHttpMessagesAsync(personGroupId, personId, persistedFaceId, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Update a person persisted face's userData field. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='personGroupId'> /// Specifying the person group containing the target person. /// </param> /// <param name='personId'> /// personId of the target person. /// </param> /// <param name='persistedFaceId'> /// persistedFaceId of target face, which is persisted and will not expire. /// </param> /// <param name='userData'> /// User-provided data attached to the face. The size limit is 1KB /// </param> public static void UpdateFace(this IPerson operations, string personGroupId, string personId, string persistedFaceId, string userData = default(string)) { operations.UpdateFaceAsync(personGroupId, personId, persistedFaceId, userData).GetAwaiter().GetResult(); } /// <summary> /// Update a person persisted face's userData field. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='personGroupId'> /// Specifying the person group containing the target person. /// </param> /// <param name='personId'> /// personId of the target person. /// </param> /// <param name='persistedFaceId'> /// persistedFaceId of target face, which is persisted and will not expire. /// </param> /// <param name='userData'> /// User-provided data attached to the face. The size limit is 1KB /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task UpdateFaceAsync(this IPerson operations, string personGroupId, string personId, string persistedFaceId, string userData = default(string), CancellationToken cancellationToken = default(CancellationToken)) { (await operations.UpdateFaceWithHttpMessagesAsync(personGroupId, personId, persistedFaceId, userData, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Add a representative face to a person for identification. The input face is /// specified as an image with a targetFace rectangle. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='personGroupId'> /// Specifying the person group containing the target person. /// </param> /// <param name='personId'> /// Target person that the face is added to. /// </param> /// <param name='userData'> /// User-specified data about the target face to add for any purpose. The /// maximum length is 1KB. /// </param> /// <param name='targetFace'> /// A face rectangle to specify the target face to be added to a person in the /// format of "targetFace=left,top,width,height". E.g. /// "targetFace=10,10,100,100". If there is more than one face in the image, /// targetFace is required to specify which face to add. No targetFace means /// there is only one face detected in the entire image. /// </param> public static void AddFace(this IPerson operations, string personGroupId, string personId, string userData = default(string), string targetFace = default(string)) { operations.AddFaceAsync(personGroupId, personId, userData, targetFace).GetAwaiter().GetResult(); } /// <summary> /// Add a representative face to a person for identification. The input face is /// specified as an image with a targetFace rectangle. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='personGroupId'> /// Specifying the person group containing the target person. /// </param> /// <param name='personId'> /// Target person that the face is added to. /// </param> /// <param name='userData'> /// User-specified data about the target face to add for any purpose. The /// maximum length is 1KB. /// </param> /// <param name='targetFace'> /// A face rectangle to specify the target face to be added to a person in the /// format of "targetFace=left,top,width,height". E.g. /// "targetFace=10,10,100,100". If there is more than one face in the image, /// targetFace is required to specify which face to add. No targetFace means /// there is only one face detected in the entire image. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task AddFaceAsync(this IPerson operations, string personGroupId, string personId, string userData = default(string), string targetFace = default(string), CancellationToken cancellationToken = default(CancellationToken)) { (await operations.AddFaceWithHttpMessagesAsync(personGroupId, personId, userData, targetFace, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Add a representative face to a person for identification. The input face is /// specified as an image with a targetFace rectangle. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='personGroupId'> /// Specifying the person group containing the target person. /// </param> /// <param name='personId'> /// Target person that the face is added to. /// </param> /// <param name='userData'> /// User-specified data about the target face to add for any purpose. The /// maximum length is 1KB. /// </param> /// <param name='targetFace'> /// A face rectangle to specify the target face to be added to a person, in the /// format of "targetFace=left,top,width,height". E.g. /// "targetFace=10,10,100,100". If there is more than one face in the image, /// targetFace is required to specify which face to add. No targetFace means /// there is only one face detected in the entire image. /// </param> public static void AddFaceFromStream(this IPerson operations, string personGroupId, string personId, string userData = default(string), string targetFace = default(string)) { operations.AddFaceFromStreamAsync(personGroupId, personId, userData, targetFace).GetAwaiter().GetResult(); } /// <summary> /// Add a representative face to a person for identification. The input face is /// specified as an image with a targetFace rectangle. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='personGroupId'> /// Specifying the person group containing the target person. /// </param> /// <param name='personId'> /// Target person that the face is added to. /// </param> /// <param name='userData'> /// User-specified data about the target face to add for any purpose. The /// maximum length is 1KB. /// </param> /// <param name='targetFace'> /// A face rectangle to specify the target face to be added to a person, in the /// format of "targetFace=left,top,width,height". E.g. /// "targetFace=10,10,100,100". If there is more than one face in the image, /// targetFace is required to specify which face to add. No targetFace means /// there is only one face detected in the entire image. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task AddFaceFromStreamAsync(this IPerson operations, string personGroupId, string personId, string userData = default(string), string targetFace = default(string), CancellationToken cancellationToken = default(CancellationToken)) { (await operations.AddFaceFromStreamWithHttpMessagesAsync(personGroupId, personId, userData, targetFace, null, cancellationToken).ConfigureAwait(false)).Dispose(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.IO; using System.Net.Test.Common; using System.Threading; using Xunit; using Xunit.Abstractions; namespace System.Net.Sockets.Tests { public class SendPacketsAsync { private readonly ITestOutputHelper _log; private IPAddress _serverAddress = IPAddress.IPv6Loopback; // Accessible directories for UWP app: // C:\Users\<UserName>\AppData\Local\Packages\<ApplicationPackageName>\ private string TestFileName = Environment.GetEnvironmentVariable("LocalAppData") + @"\NCLTest.Socket.SendPacketsAsync.testpayload"; private static int s_testFileSize = 1024; #region Additional test attributes public SendPacketsAsync(ITestOutputHelper output) { _log = TestLogging.GetInstance(); byte[] buffer = new byte[s_testFileSize]; for (int i = 0; i < s_testFileSize; i++) { buffer[i] = (byte)(i % 255); } try { _log.WriteLine("Creating file {0} with size: {1}", TestFileName, s_testFileSize); using (FileStream fs = new FileStream(TestFileName, FileMode.CreateNew)) { fs.Write(buffer, 0, buffer.Length); } } catch (IOException) { // Test payload file already exists. _log.WriteLine("Payload file exists: {0}", TestFileName); } } #endregion Additional test attributes #region Basic Arguments [OuterLoop] // TODO: Issue #11345 [Theory] [InlineData(SocketImplementationType.APM)] [InlineData(SocketImplementationType.Async)] public void Disposed_Throw(SocketImplementationType type) { int port; using (SocketTestServer.SocketTestServerFactory(type, _serverAddress, out port)) { using (Socket sock = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp)) { sock.Connect(new IPEndPoint(_serverAddress, port)); sock.Dispose(); Assert.Throws<ObjectDisposedException>(() => { sock.SendPacketsAsync(new SocketAsyncEventArgs()); }); } } } [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Bug in SendPacketsAsync that dereferences null SAEA argument")] [OuterLoop] // TODO: Issue #11345 [Theory] [InlineData(SocketImplementationType.APM)] [InlineData(SocketImplementationType.Async)] public void NullArgs_Throw(SocketImplementationType type) { int port; using (SocketTestServer.SocketTestServerFactory(type, _serverAddress, out port)) { using (Socket sock = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp)) { sock.Connect(new IPEndPoint(_serverAddress, port)); AssertExtensions.Throws<ArgumentNullException>("e", () => sock.SendPacketsAsync(null)); } } } [Fact] public void NotConnected_Throw() { Socket socket = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp); // Needs to be connected before send Assert.Throws<NotSupportedException>(() => { socket.SendPacketsAsync(new SocketAsyncEventArgs { SendPacketsElements = new SendPacketsElement[0] }); }); } [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Bug in SendPacketsAsync that dereferences null m_SendPacketsElementsInternal array")] [OuterLoop] // TODO: Issue #11345 [Theory] [InlineData(SocketImplementationType.APM)] [InlineData(SocketImplementationType.Async)] public void NullList_Throws(SocketImplementationType type) { AssertExtensions.Throws<ArgumentNullException>("e.SendPacketsElements", () => SendPackets(type, (SendPacketsElement[])null, SocketError.Success, 0)); } [OuterLoop] // TODO: Issue #11345 [Theory] [InlineData(SocketImplementationType.APM)] [InlineData(SocketImplementationType.Async)] [ActiveIssue(20135, TargetFrameworkMonikers.Uap)] public void NullElement_Ignored(SocketImplementationType type) { SendPackets(type, (SendPacketsElement)null, 0); } [OuterLoop] // TODO: Issue #11345 [Theory] [InlineData(SocketImplementationType.APM)] [InlineData(SocketImplementationType.Async)] [ActiveIssue(20135, TargetFrameworkMonikers.Uap)] public void EmptyList_Ignored(SocketImplementationType type) { SendPackets(type, new SendPacketsElement[0], SocketError.Success, 0); } [OuterLoop] // TODO: Issue #11345 [Fact] public void SocketAsyncEventArgs_DefaultSendSize_0() { SocketAsyncEventArgs args = new SocketAsyncEventArgs(); Assert.Equal(0, args.SendPacketsSendSize); } #endregion Basic Arguments #region Buffers [Theory] [InlineData(SocketImplementationType.APM)] [InlineData(SocketImplementationType.Async)] public void NormalBuffer_Success(SocketImplementationType type) { SendPackets(type, new SendPacketsElement(new byte[10]), 10); } [Theory] [InlineData(SocketImplementationType.APM)] [InlineData(SocketImplementationType.Async)] public void NormalBufferRange_Success(SocketImplementationType type) { SendPackets(type, new SendPacketsElement(new byte[10], 5, 5), 5); } [Theory] [InlineData(SocketImplementationType.APM)] [InlineData(SocketImplementationType.Async)] [ActiveIssue(20135, TargetFrameworkMonikers.Uap)] public void EmptyBuffer_Ignored(SocketImplementationType type) { SendPackets(type, new SendPacketsElement(new byte[0]), 0); } [Theory] [InlineData(SocketImplementationType.APM)] [InlineData(SocketImplementationType.Async)] [ActiveIssue(20135, TargetFrameworkMonikers.Uap)] public void BufferZeroCount_Ignored(SocketImplementationType type) { SendPackets(type, new SendPacketsElement(new byte[10], 4, 0), 0); } [Theory] [InlineData(SocketImplementationType.APM)] [InlineData(SocketImplementationType.Async)] public void BufferMixedBuffers_ZeroCountBufferIgnored(SocketImplementationType type) { SendPacketsElement[] elements = new SendPacketsElement[] { new SendPacketsElement(new byte[10], 4, 0), // Ignored new SendPacketsElement(new byte[10], 4, 4), new SendPacketsElement(new byte[10], 0, 4) }; SendPackets(type, elements, SocketError.Success, 8); } [Theory] [InlineData(SocketImplementationType.APM)] [InlineData(SocketImplementationType.Async)] [ActiveIssue(20135, TargetFrameworkMonikers.Uap)] public void BufferZeroCountThenNormal_ZeroCountIgnored(SocketImplementationType type) { Assert.True(Capability.IPv6Support()); EventWaitHandle completed = new ManualResetEvent(false); int port; using (SocketTestServer.SocketTestServerFactory(type, _serverAddress, out port)) { using (Socket sock = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp)) { sock.Connect(new IPEndPoint(_serverAddress, port)); using (SocketAsyncEventArgs args = new SocketAsyncEventArgs()) { args.Completed += OnCompleted; args.UserToken = completed; // First do an empty send, ignored args.SendPacketsElements = new SendPacketsElement[] { new SendPacketsElement(new byte[5], 3, 0) }; if (sock.SendPacketsAsync(args)) { Assert.True(completed.WaitOne(TestSettings.PassingTestTimeout), "Timed out"); } Assert.Equal(SocketError.Success, args.SocketError); Assert.Equal(0, args.BytesTransferred); completed.Reset(); // Now do a real send args.SendPacketsElements = new SendPacketsElement[] { new SendPacketsElement(new byte[5], 1, 4) }; if (sock.SendPacketsAsync(args)) { Assert.True(completed.WaitOne(TestSettings.PassingTestTimeout), "Timed out"); } Assert.Equal(SocketError.Success, args.SocketError); Assert.Equal(4, args.BytesTransferred); } } } } #endregion Buffers #region TransmitFileOptions [Theory] [InlineData(SocketImplementationType.APM)] [InlineData(SocketImplementationType.Async)] public void SocketDisconnected_TransmitFileOptionDisconnect(SocketImplementationType type) { SendPackets(type, new SendPacketsElement(new byte[10], 4, 4), TransmitFileOptions.Disconnect, 4); } [Theory] [InlineData(SocketImplementationType.APM)] [InlineData(SocketImplementationType.Async)] public void SocketDisconnectedAndReusable_TransmitFileOptionReuseSocket(SocketImplementationType type) { SendPackets(type, new SendPacketsElement(new byte[10], 4, 4), TransmitFileOptions.Disconnect | TransmitFileOptions.ReuseSocket, 4); } #endregion #region Files [Theory] [InlineData(SocketImplementationType.APM)] [InlineData(SocketImplementationType.Async)] public void SendPacketsElement_EmptyFileName_Throws(SocketImplementationType type) { Assert.Throws<ArgumentException>(() => { SendPackets(type, new SendPacketsElement(String.Empty), 0); }); } [Theory] [InlineData(SocketImplementationType.APM)] [InlineData(SocketImplementationType.Async)] [PlatformSpecific(TestPlatforms.Windows)] // whitespace-only is a valid name on Unix public void SendPacketsElement_BlankFileName_Throws(SocketImplementationType type) { Assert.Throws<ArgumentException>(() => { // Existence is validated on send SendPackets(type, new SendPacketsElement(" \t "), 0); }); } [Theory] [InlineData(SocketImplementationType.APM)] [InlineData(SocketImplementationType.Async)] [PlatformSpecific(TestPlatforms.Windows)] // valid filename chars on Unix public void SendPacketsElement_BadCharactersFileName_Throws(SocketImplementationType type) { Assert.Throws<ArgumentException>(() => { // Existence is validated on send SendPackets(type, new SendPacketsElement("blarkd@dfa?/sqersf"), 0); }); } [Theory] [InlineData(SocketImplementationType.APM)] [InlineData(SocketImplementationType.Async)] public void SendPacketsElement_MissingDirectoryName_Throws(SocketImplementationType type) { Assert.Throws<DirectoryNotFoundException>(() => { // Existence is validated on send SendPackets(type, new SendPacketsElement(Path.Combine("nodir", "nofile")), 0); }); } [Theory] [InlineData(SocketImplementationType.APM)] [InlineData(SocketImplementationType.Async)] public void SendPacketsElement_MissingFile_Throws(SocketImplementationType type) { Assert.Throws<FileNotFoundException>(() => { // Existence is validated on send SendPackets(type, new SendPacketsElement("DoesntExit"), 0); }); } [Theory] [InlineData(SocketImplementationType.APM)] [InlineData(SocketImplementationType.Async)] public void SendPacketsElement_File_Success(SocketImplementationType type) { SendPackets(type, new SendPacketsElement(TestFileName), s_testFileSize); // Whole File } [Theory] [InlineData(SocketImplementationType.APM)] [InlineData(SocketImplementationType.Async)] public void SendPacketsElement_FileZeroCount_Success(SocketImplementationType type) { SendPackets(type, new SendPacketsElement(TestFileName, 0, 0), s_testFileSize); // Whole File } [Theory] [InlineData(SocketImplementationType.APM)] [InlineData(SocketImplementationType.Async)] public void SendPacketsElement_FilePart_Success(SocketImplementationType type) { SendPackets(type, new SendPacketsElement(TestFileName, 10, 20), 20); } [Theory] [InlineData(SocketImplementationType.APM)] [InlineData(SocketImplementationType.Async)] public void SendPacketsElement_FileMultiPart_Success(SocketImplementationType type) { SendPacketsElement[] elements = new SendPacketsElement[] { new SendPacketsElement(TestFileName, 10, 20), new SendPacketsElement(TestFileName, 30, 10), new SendPacketsElement(TestFileName, 0, 10), }; SendPackets(type, elements, SocketError.Success, 40); } [Theory] [InlineData(SocketImplementationType.APM)] [InlineData(SocketImplementationType.Async)] public void SendPacketsElement_FileLargeOffset_Throws(SocketImplementationType type) { // Length is validated on Send SendPackets(type, new SendPacketsElement(TestFileName, 11000, 1), SocketError.InvalidArgument, 0); } [Theory] [InlineData(SocketImplementationType.APM)] [InlineData(SocketImplementationType.Async)] public void SendPacketsElement_FileLargeCount_Throws(SocketImplementationType type) { // Length is validated on Send SendPackets(type, new SendPacketsElement(TestFileName, 5, 10000), SocketError.InvalidArgument, 0); } #endregion Files #region Helpers private void SendPackets(SocketImplementationType type, SendPacketsElement element, TransmitFileOptions flags, int bytesExpected) { Assert.True(Capability.IPv6Support()); EventWaitHandle completed = new ManualResetEvent(false); int port; using (SocketTestServer.SocketTestServerFactory(type, _serverAddress, out port)) { using (Socket sock = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp)) { sock.Connect(new IPEndPoint(_serverAddress, port)); using (SocketAsyncEventArgs args = new SocketAsyncEventArgs()) { args.Completed += OnCompleted; args.UserToken = completed; args.SendPacketsElements = new[] { element }; args.SendPacketsFlags = flags; if (sock.SendPacketsAsync(args)) { Assert.True(completed.WaitOne(TestSettings.PassingTestTimeout), "Timed out"); } Assert.Equal(SocketError.Success, args.SocketError); Assert.Equal(bytesExpected, args.BytesTransferred); } switch (flags) { case TransmitFileOptions.Disconnect: // Sending data again throws with socket shut down error. Assert.Throws<SocketException>(() => { sock.Send(new byte[1] { 01 }); }); break; case TransmitFileOptions.ReuseSocket & TransmitFileOptions.Disconnect: // Able to send data again with reuse socket flag set. Assert.Equal(1, sock.Send(new byte[1] { 01 })); break; } } } } private void SendPackets(SocketImplementationType type, SendPacketsElement element, int bytesExpected) { SendPackets(type, new SendPacketsElement[] { element }, SocketError.Success, bytesExpected); } private void SendPackets(SocketImplementationType type, SendPacketsElement element, SocketError expectedResut, int bytesExpected) { SendPackets(type, new SendPacketsElement[] { element }, expectedResut, bytesExpected); } private void SendPackets(SocketImplementationType type, SendPacketsElement[] elements, SocketError expectedResut, int bytesExpected) { Assert.True(Capability.IPv6Support()); EventWaitHandle completed = new ManualResetEvent(false); int port; using (SocketTestServer.SocketTestServerFactory(type, _serverAddress, out port)) { using (Socket sock = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp)) { sock.Connect(new IPEndPoint(_serverAddress, port)); using (SocketAsyncEventArgs args = new SocketAsyncEventArgs()) { args.Completed += OnCompleted; args.UserToken = completed; args.SendPacketsElements = elements; if (sock.SendPacketsAsync(args)) { Assert.True(completed.WaitOne(TestSettings.PassingTestTimeout), "Timed out"); } Assert.Equal(expectedResut, args.SocketError); Assert.Equal(bytesExpected, args.BytesTransferred); } } } } private void OnCompleted(object sender, SocketAsyncEventArgs e) { EventWaitHandle handle = (EventWaitHandle)e.UserToken; handle.Set(); } #endregion Helpers } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using ReactNative.Reflection; using ReactNative.UIManager; using ReactNative.UIManager.Annotations; using System.Collections.Generic; #if WINDOWS_UWP using Windows.UI.Text; using Windows.UI.Xaml.Documents; using Windows.UI.Xaml.Media; #else using System.Windows; using System.Windows.Documents; using System.Windows.Media; #endif namespace ReactNative.Views.Text { /// <summary> /// Shadow node for virtual text nodes. /// </summary> public class ReactSpanShadowNode : ReactInlineShadowNode { private double? _fontSize; private int? _letterSpacing; private FontStyle? _fontStyle; private FontWeight? _fontWeight; private string _fontFamily; /// <summary> /// Sets the font size for the node. /// </summary> /// <param name="fontSize">The font size.</param> [ReactProp(ViewProps.FontSize)] public void SetFontSize(double? fontSize) { if (_fontSize != fontSize) { _fontSize = fontSize; MarkUpdated(); } } /// <summary> /// Sets the font family for the node. /// </summary> /// <param name="fontFamily">The font family.</param> [ReactProp(ViewProps.FontFamily)] public void SetFontFamily(string fontFamily) { if (_fontFamily != fontFamily) { _fontFamily = fontFamily; MarkUpdated(); } } /// <summary> /// Sets the font weight for the node. /// </summary> /// <param name="fontWeightValue">The font weight string.</param> [ReactProp(ViewProps.FontWeight)] public void SetFontWeight(string fontWeightValue) { var fontWeight = FontStyleHelpers.ParseFontWeight(fontWeightValue); if (_fontWeight.HasValue != fontWeight.HasValue || (_fontWeight.HasValue && fontWeight.HasValue && #if WINDOWS_UWP _fontWeight.Value.Weight != fontWeight.Value.Weight)) #else _fontWeight.Value != fontWeight.Value)) #endif { _fontWeight = fontWeight; MarkUpdated(); } } /// <summary> /// Sets the font style for the node. /// </summary> /// <param name="fontStyleValue">The font style string.</param> [ReactProp(ViewProps.FontStyle)] public void SetFontStyle(string fontStyleValue) { var fontStyle = EnumHelpers.ParseNullable<FontStyle>(fontStyleValue); if (_fontStyle != fontStyle) { _fontStyle = fontStyle; MarkUpdated(); } } /// <summary> /// Sets the letter spacing for the node. /// </summary> /// <param name="letterSpacing">The letter spacing.</param> [ReactProp(ViewProps.LetterSpacing)] public void SetLetterSpacing(int? letterSpacing) { if (_letterSpacing != letterSpacing) { _letterSpacing = letterSpacing; MarkUpdated(); } } /// <summary> /// Create the <see cref="Span"/> instance for the measurement calculation. /// </summary> /// <param name="children">The children.</param> /// <returns>The instance.</returns> public override Inline MakeInline(IList<Inline> children) { var span = new Span(); UpdateInline(span); foreach (var child in children) { span.Inlines.Add(child); } return span; } /// <summary> /// Update the properties on the inline instance. /// </summary> /// <param name="inline">The instance.</param> public override void UpdateInline(Inline inline) { #if WINDOWS_UWP if (_letterSpacing.HasValue) { var spacing = 50 * _letterSpacing.Value; // TODO: Find exact multiplier (50) to match iOS inline.CharacterSpacing = spacing; } else { inline.ClearValue(Inline.CharacterSpacingProperty); } #endif if (_fontStyle.HasValue) { inline.FontStyle = _fontStyle.Value; } else { inline.ClearValue(Inline.FontStyleProperty); } if (!string.IsNullOrEmpty(_fontFamily)) { inline.FontFamily = new FontFamily(_fontFamily); } else { inline.ClearValue(Inline.FontFamilyProperty); } if (_fontSize.HasValue) { inline.FontSize = _fontSize.Value; } else { inline.ClearValue(Inline.FontSizeProperty); } if (_fontWeight.HasValue) { inline.FontWeight = _fontWeight.Value; } else { inline.ClearValue(Inline.FontWeightProperty); } } /// <summary> /// This method will be called by <see cref="UIManagerModule"/> once /// per batch, before calculating layout. This will only be called for /// nodes that are marked as updated with <see cref="ReactShadowNode.MarkUpdated"/> or /// require layout (i.e., marked with <see cref="ReactShadowNode.dirty"/> ). /// </summary> public override void OnBeforeLayout() { // Run flexbox on the children which are inline views. for (var i = 0; i < ChildCount; ++i) { var child = GetChildAt(i); if (!(child is ReactInlineShadowNode)) { child.CalculateLayout(); } } } } }
using Orchard.ContentManagement; using Orchard.Localization; using Orchard.Logging; using Orchard.Mvc; using Orchard.Mvc.Extensions; using Orchard.Security; using Orchard.Themes; using Orchard.UI.Notify; using Orchard.Users.Events; using Orchard.Users.Models; using Orchard.Users.Services; using Orchard.Utility.Extensions; using System; using System.Diagnostics.CodeAnalysis; using System.Text.RegularExpressions; using System.Web.Mvc; using System.Web.Security; using Orchard.Services; using System.Collections.Generic; namespace Orchard.Users.Controllers { [HandleError, Themed] public class AccountController : Controller { private readonly IAuthenticationService _authenticationService; private readonly IMembershipService _membershipService; private readonly IUserService _userService; private readonly IOrchardServices _orchardServices; private readonly IUserEventHandler _userEventHandler; private readonly IClock _clock; public AccountController( IAuthenticationService authenticationService, IMembershipService membershipService, IUserService userService, IOrchardServices orchardServices, IUserEventHandler userEventHandler, IClock clock) { _authenticationService = authenticationService; _membershipService = membershipService; _userService = userService; _orchardServices = orchardServices; _userEventHandler = userEventHandler; _clock = clock; Logger = NullLogger.Instance; T = NullLocalizer.Instance; } public ILogger Logger { get; set; } public Localizer T { get; set; } [AlwaysAccessible] public ActionResult AccessDenied() { var returnUrl = Request.QueryString["ReturnUrl"]; var currentUser = _authenticationService.GetAuthenticatedUser(); if (currentUser == null) { Logger.Information("Access denied to anonymous request on {0}", returnUrl); var shape = _orchardServices.New.LogOn().Title(T("Access Denied").Text); return new ShapeResult(this, shape); } //TODO: (erikpo) Add a setting for whether or not to log access denieds since these can fill up a database pretty fast from bots on a high traffic site //Suggestion: Could instead use the new AccessDenined IUserEventHandler method and let modules decide if they want to log this event? Logger.Information("Access denied to user #{0} '{1}' on {2}", currentUser.Id, currentUser.UserName, returnUrl); _userEventHandler.AccessDenied(currentUser); return View(); } [AlwaysAccessible] public ActionResult LogOn(string returnUrl) { if (_authenticationService.GetAuthenticatedUser() != null) return this.RedirectLocal(returnUrl); var shape = _orchardServices.New.LogOn().Title(T("Log On").Text); return new ShapeResult(this, shape); } [HttpPost] [AlwaysAccessible] [ValidateInput(false)] [SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", Justification = "Needs to take same parameter type as Controller.Redirect()")] public ActionResult LogOn(string userNameOrEmail, string password, string returnUrl, bool rememberMe = false) { _userEventHandler.LoggingIn(userNameOrEmail, password); var user = ValidateLogOn(userNameOrEmail, password); if (!ModelState.IsValid) { var shape = _orchardServices.New.LogOn().Title(T("Log On").Text); return new ShapeResult(this, shape); } var membershipSettings = _membershipService.GetSettings(); if (user != null && membershipSettings.EnableCustomPasswordPolicy && membershipSettings.EnablePasswordExpiration && _membershipService.PasswordIsExpired(user, membershipSettings.PasswordExpirationTimeInDays)) { return RedirectToAction("ChangeExpiredPassword", new { username = user.UserName }); } _authenticationService.SignIn(user, rememberMe); _userEventHandler.LoggedIn(user); return this.RedirectLocal(returnUrl); } public ActionResult LogOff(string returnUrl) { _authenticationService.SignOut(); var loggedUser = _authenticationService.GetAuthenticatedUser(); if (loggedUser != null) { _userEventHandler.LoggedOut(loggedUser); } return this.RedirectLocal(returnUrl); } [AlwaysAccessible] public ActionResult Register() { // ensure users can register var membershipSettings = _membershipService.GetSettings(); if (!membershipSettings.UsersCanRegister) { return HttpNotFound(); } ViewData["PasswordLength"] = membershipSettings.GetMinimumPasswordLength(); var shape = _orchardServices.New.Register(); return new ShapeResult(this, shape); } [HttpPost] [AlwaysAccessible] [ValidateInput(false)] public ActionResult Register(string userName, string email, string password, string confirmPassword, string returnUrl = null) { // ensure users can register var membershipSettings = _membershipService.GetSettings(); if (!membershipSettings.UsersCanRegister) { return HttpNotFound(); } ViewData["PasswordLength"] = membershipSettings.GetMinimumPasswordLength(); if (ValidateRegistration(userName, email, password, confirmPassword)) { // Attempt to register the user // No need to report this to IUserEventHandler because _membershipService does that for us var user = _membershipService.CreateUser(new CreateUserParams(userName, password, email, null, null, false)); if (user != null) { if (user.As<UserPart>().EmailStatus == UserStatus.Pending) { var siteUrl = _orchardServices.WorkContext.CurrentSite.BaseUrl; if (String.IsNullOrWhiteSpace(siteUrl)) { siteUrl = HttpContext.Request.ToRootUrlString(); } _userService.SendChallengeEmail(user.As<UserPart>(), nonce => Url.MakeAbsolute(Url.Action("ChallengeEmail", "Account", new { Area = "Orchard.Users", nonce = nonce }), siteUrl)); _userEventHandler.SentChallengeEmail(user); return RedirectToAction("ChallengeEmailSent", new { ReturnUrl = returnUrl }); } if (user.As<UserPart>().RegistrationStatus == UserStatus.Pending) { return RedirectToAction("RegistrationPending", new { ReturnUrl = returnUrl }); } _userEventHandler.LoggingIn(userName, password); _authenticationService.SignIn(user, false /* createPersistentCookie */); _userEventHandler.LoggedIn(user); return this.RedirectLocal(returnUrl); } ModelState.AddModelError("_FORM", T(ErrorCodeToString(/*createStatus*/MembershipCreateStatus.ProviderError))); } // If we got this far, something failed, redisplay form var shape = _orchardServices.New.Register(); return new ShapeResult(this, shape); } [AlwaysAccessible] public ActionResult RequestLostPassword() { // ensure users can request lost password var membershipSettings = _membershipService.GetSettings(); if (!membershipSettings.EnableLostPassword) { return HttpNotFound(); } return View(); } [HttpPost] [AlwaysAccessible] public ActionResult RequestLostPassword(string username) { // ensure users can request lost password var membershipSettings = _membershipService.GetSettings(); if (!membershipSettings.EnableLostPassword) { return HttpNotFound(); } if (String.IsNullOrWhiteSpace(username)) { ModelState.AddModelError("username", T("You must specify a username or e-mail.")); return View(); } var siteUrl = _orchardServices.WorkContext.CurrentSite.BaseUrl; if (String.IsNullOrWhiteSpace(siteUrl)) { siteUrl = HttpContext.Request.ToRootUrlString(); } _userService.SendLostPasswordEmail(username, nonce => Url.MakeAbsolute(Url.Action("LostPassword", "Account", new { Area = "Orchard.Users", nonce = nonce }), siteUrl)); _orchardServices.Notifier.Information(T("Check your e-mail for the confirmation link.")); return RedirectToAction("LogOn"); } [Authorize] [AlwaysAccessible] public ActionResult ChangePassword() { var membershipSettings = _membershipService.GetSettings(); ViewData["PasswordLength"] = membershipSettings.GetMinimumPasswordLength(); return View(); } [Authorize] [HttpPost] [AlwaysAccessible] [ValidateInput(false)] [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Exceptions result in password not being changed.")] public ActionResult ChangePassword(string currentPassword, string newPassword, string confirmPassword) { var membershipSettings = _membershipService.GetSettings(); ViewData["PasswordLength"] = membershipSettings.GetMinimumPasswordLength(); ; if (!ValidateChangePassword(currentPassword, newPassword, confirmPassword)) { return View(); } if (PasswordChangeIsSuccess(currentPassword, newPassword, _orchardServices.WorkContext.CurrentUser.UserName)) { return RedirectToAction("ChangePasswordSuccess"); } else { return ChangePassword(); } } [AlwaysAccessible] public ActionResult ChangeExpiredPassword(string username) { var membershipSettings = _membershipService.GetSettings(); var lastPasswordChangeUtc = _membershipService.GetUser(username).As<UserPart>().LastPasswordChangeUtc; if (lastPasswordChangeUtc.Value.AddDays(membershipSettings.PasswordExpirationTimeInDays) > _clock.UtcNow) { return RedirectToAction("LogOn"); } var viewModel = _orchardServices.New.ViewModel( Username: username, PasswordLength: membershipSettings.GetMinimumPasswordLength()); return View(viewModel); } [HttpPost, AlwaysAccessible, ValidateInput(false)] public ActionResult ChangeExpiredPassword(string currentPassword, string newPassword, string confirmPassword, string username) { var membershipSettings = _membershipService.GetSettings(); var viewModel = _orchardServices.New.ViewModel( Username: username, PasswordLength: membershipSettings.GetMinimumPasswordLength()); if (!ValidateChangePassword(currentPassword, newPassword, confirmPassword)) { return View(viewModel); } if (PasswordChangeIsSuccess(currentPassword, newPassword, username)) { return RedirectToAction("ChangePasswordSuccess"); } else { return View(viewModel); } } private bool PasswordChangeIsSuccess(string currentPassword, string newPassword, string username) { try { var validated = _membershipService.ValidateUser(username, currentPassword); if (validated != null) { _membershipService.SetPassword(validated, newPassword); _userEventHandler.ChangedPassword(validated); return true; } ModelState.AddModelError("_FORM", T("The current password is incorrect or the new password is invalid.")); return false; } catch { ModelState.AddModelError("_FORM", T("The current password is incorrect or the new password is invalid.")); return false; } } [AlwaysAccessible] public ActionResult LostPassword(string nonce) { if ( _userService.ValidateLostPassword(nonce) == null ) { return RedirectToAction("LogOn"); } var membershipSettings = _membershipService.GetSettings(); ViewData["PasswordLength"] = membershipSettings.GetMinimumPasswordLength(); return View(); } [HttpPost] [AlwaysAccessible] [ValidateInput(false)] public ActionResult LostPassword(string nonce, string newPassword, string confirmPassword) { IUser user; if ( (user = _userService.ValidateLostPassword(nonce)) == null ) { return Redirect("~/"); } var membershipSettings = _membershipService.GetSettings(); ViewData["PasswordLength"] = membershipSettings.GetMinimumPasswordLength(); ValidatePassword(newPassword); if (!String.Equals(newPassword, confirmPassword, StringComparison.Ordinal)) { ModelState.AddModelError("_FORM", T("The new password and confirmation password do not match.")); } if (!ModelState.IsValid) { return View(); } _membershipService.SetPassword(user, newPassword); _userEventHandler.ChangedPassword(user); return RedirectToAction("ChangePasswordSuccess"); } [AlwaysAccessible] public ActionResult ChangePasswordSuccess() { return View(); } public ActionResult RegistrationPending() { return View(); } public ActionResult ChallengeEmailSent() { return View(); } public ActionResult ChallengeEmailSuccess() { return View(); } public ActionResult ChallengeEmailFail() { return View(); } public ActionResult ChallengeEmail(string nonce) { var user = _userService.ValidateChallenge(nonce); if ( user != null ) { _userEventHandler.ConfirmedEmail(user); return RedirectToAction("ChallengeEmailSuccess"); } return RedirectToAction("ChallengeEmailFail"); } #region Validation Methods private bool ValidateChangePassword(string currentPassword, string newPassword, string confirmPassword) { if ( String.IsNullOrEmpty(currentPassword) ) { ModelState.AddModelError("currentPassword", T("You must specify a current password.")); } if (String.Equals(currentPassword, newPassword, StringComparison.Ordinal)) { ModelState.AddModelError("newPassword", T("The new password must be different from the current password.")); } ValidatePassword(newPassword); if ( !String.Equals(newPassword, confirmPassword, StringComparison.Ordinal) ) { ModelState.AddModelError("_FORM", T("The new password and confirmation password do not match.")); } return ModelState.IsValid; } private IUser ValidateLogOn(string userNameOrEmail, string password) { bool validate = true; if (String.IsNullOrEmpty(userNameOrEmail)) { ModelState.AddModelError("userNameOrEmail", T("You must specify a username or e-mail.")); validate = false; } if (String.IsNullOrEmpty(password)) { ModelState.AddModelError("password", T("You must specify a password.")); validate = false; } if (!validate) return null; var user = _membershipService.ValidateUser(userNameOrEmail, password); if (user == null) { _userEventHandler.LogInFailed(userNameOrEmail, password); ModelState.AddModelError("_FORM", T("The username or e-mail or password provided is incorrect.")); } return user; } private bool ValidateRegistration(string userName, string email, string password, string confirmPassword) { bool validate = true; if (String.IsNullOrEmpty(userName)) { ModelState.AddModelError("username", T("You must specify a username.")); validate = false; } else { if (userName.Length >= UserPart.MaxUserNameLength) { ModelState.AddModelError("username", T("The username you provided is too long.")); validate = false; } } if (String.IsNullOrEmpty(email)) { ModelState.AddModelError("email", T("You must specify an email address.")); validate = false; } else if (email.Length >= UserPart.MaxEmailLength) { ModelState.AddModelError("email", T("The email address you provided is too long.")); validate = false; } else if (!Regex.IsMatch(email, UserPart.EmailPattern, RegexOptions.IgnoreCase)) { // http://haacked.com/archive/2007/08/21/i-knew-how-to-validate-an-email-address-until-i.aspx ModelState.AddModelError("email", T("You must specify a valid email address.")); validate = false; } if (!validate) return false; if (!_userService.VerifyUserUnicity(userName, email)) { ModelState.AddModelError("userExists", T("User with that username and/or email already exists.")); } ValidatePassword(password); if (!String.Equals(password, confirmPassword, StringComparison.Ordinal)) { ModelState.AddModelError("_FORM", T("The new password and confirmation password do not match.")); } return ModelState.IsValid; } private void ValidatePassword(string password) { IDictionary<string, LocalizedString> validationErrors; if (!_userService.PasswordMeetsPolicies(password, out validationErrors)) { foreach (var error in validationErrors) { ModelState.AddModelError(error.Key, error.Value); } } } private static string ErrorCodeToString(MembershipCreateStatus createStatus) { // See http://msdn.microsoft.com/en-us/library/system.web.security.membershipcreatestatus.aspx for // a full list of status codes. switch (createStatus) { case MembershipCreateStatus.DuplicateUserName: return "Username already exists. Please enter a different user name."; case MembershipCreateStatus.DuplicateEmail: return "A username for that e-mail address already exists. Please enter a different e-mail address."; case MembershipCreateStatus.InvalidPassword: return "The password provided is invalid. Please enter a valid password value."; case MembershipCreateStatus.InvalidEmail: return "The e-mail address provided is invalid. Please check the value and try again."; case MembershipCreateStatus.InvalidAnswer: return "The password retrieval answer provided is invalid. Please check the value and try again."; case MembershipCreateStatus.InvalidQuestion: return "The password retrieval question provided is invalid. Please check the value and try again."; case MembershipCreateStatus.InvalidUserName: return "The user name provided is invalid. Please check the value and try again."; case MembershipCreateStatus.ProviderError: return "The authentication provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator."; case MembershipCreateStatus.UserRejected: return "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator."; default: return "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator."; } } #endregion } }