context
stringlengths
2.52k
185k
gt
stringclasses
1 value
/////////////////////////////////////////////////////////////////////////////////////////////// // // This File is Part of the CallButler Open Source PBX (http://www.codeplex.com/callbutler // // Copyright (c) 2005-2008, Jim Heising // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation and/or // other materials provided with the distribution. // // * Neither the name of Jim Heising 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.Text; using System.Drawing; using System.ComponentModel; using System.Drawing; using System.Drawing.Imaging; namespace Controls { [Serializable] public enum BlurType { Both, HorizontalOnly, VerticalOnly, } [Serializable] public class Blur { private int _radius = 6; private int[] _kernel; private int _kernelSum; private int[,] _multable; private BlurType _blurType; public Blur() { PreCalculateSomeStuff(); } public Blur(int radius) { _radius = radius; PreCalculateSomeStuff(); } private void PreCalculateSomeStuff() { int sz = _radius * 2 + 1; _kernel = new int[sz]; _multable = new int[sz, 256]; for (int i = 1; i <= _radius; i++) { int szi = _radius - i; int szj = _radius + i; _kernel[szj] = _kernel[szi] = (szi + 1) * (szi + 1); _kernelSum += (_kernel[szj] + _kernel[szi]); for (int j = 0; j < 256; j++) { _multable[szj, j] = _multable[szi, j] = _kernel[szj] * j; } } _kernel[_radius] = (_radius + 1) * (_radius + 1); _kernelSum += _kernel[_radius]; for (int j = 0; j < 256; j++) { _multable[_radius, j] = _kernel[_radius] * j; } } public Image ProcessImage(Image inputImage) { Bitmap origin = new Bitmap(inputImage); Bitmap blurred = new Bitmap(inputImage.Width, inputImage.Height); using (RawBitmap src = new RawBitmap(origin)) { using (RawBitmap dest = new RawBitmap(blurred)) { int pixelCount = src.Width * src.Height; int[] b = new int[pixelCount]; int[] g = new int[pixelCount]; int[] r = new int[pixelCount]; int[] a = new int[pixelCount]; int[] b2 = new int[pixelCount]; int[] g2 = new int[pixelCount]; int[] r2 = new int[pixelCount]; int[] a2 = new int[pixelCount]; int offset = src.GetOffset(); int index = 0; unsafe { byte* ptr = src.Begin; for (int i = 0; i < src.Height; i++) { for (int j = 0; j < src.Width; j++) { b[index] = *ptr; ptr++; g[index] = *ptr; ptr++; r[index] = *ptr; ptr++; a[index] = *ptr; ptr++; ++index; } ptr += offset; } int bsum; int gsum; int rsum; int asum; int sum; int read; int start = 0; index = 0; if (_blurType != BlurType.VerticalOnly) { for (int i = 0; i < src.Height; i++) { for (int j = 0; j < src.Width; j++) { bsum = gsum = rsum = asum = sum = 0; read = index - _radius; for (int z = 0; z < _kernel.Length; z++) { if (read >= start && read < start + src.Width) { bsum += _multable[z, b[read]]; gsum += _multable[z, g[read]]; rsum += _multable[z, r[read]]; asum += _multable[z, a[read]]; sum += _kernel[z]; } ++read; } b2[index] = (bsum / sum); g2[index] = (gsum / sum); r2[index] = (rsum / sum); a2[index] = (asum / sum); if (_blurType == BlurType.HorizontalOnly) { byte* pcell = dest[j, i]; pcell[0] = (byte)(bsum / sum); pcell[1] = (byte)(gsum / sum); pcell[2] = (byte)(rsum / sum); pcell[3] = (byte)(asum / sum); } ++index; } start += src.Width; } } if (_blurType == BlurType.HorizontalOnly) { return blurred; } int tempy; for (int i = 0; i < src.Height; i++) { int y = i - _radius; start = y * src.Width; for (int j = 0; j < src.Width; j++) { bsum = gsum = rsum = asum = sum = 0; read = start + j; tempy = y; for (int z = 0; z < _kernel.Length; z++) { if (tempy >= 0 && tempy < src.Height) { if (_blurType == BlurType.VerticalOnly) { bsum += _multable[z, b[read]]; gsum += _multable[z, g[read]]; rsum += _multable[z, r[read]]; asum += _multable[z, a[read]]; } else { bsum += _multable[z, b2[read]]; gsum += _multable[z, g2[read]]; rsum += _multable[z, r2[read]]; asum += _multable[z, a2[read]]; } sum += _kernel[z]; } read += src.Width; ++tempy; } byte* pcell = dest[j, i]; pcell[0] = (byte)(bsum / sum); pcell[1] = (byte)(gsum / sum); pcell[2] = (byte)(rsum / sum); pcell[3] = (byte)(asum / sum); } } } } } return blurred; } public int Radius { get { return _radius; } set { if (value < 2) { throw new InvalidOperationException("Radius must be greater then 1"); } _radius = value; PreCalculateSomeStuff(); } } public BlurType BlurType { get { return _blurType; } set { _blurType = value; } } } }
/* Copyright 2020 Esri Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows.Input; using System.Threading.Tasks; using ArcGIS.Core.CIM; using ArcGIS.Core.Data; using ArcGIS.Core.Geometry; using ArcGIS.Desktop.Catalog; using ArcGIS.Desktop.Core; using ArcGIS.Desktop.Editing; using ArcGIS.Desktop.Extensions; using ArcGIS.Desktop.Framework; using ArcGIS.Desktop.Framework.Contracts; using ArcGIS.Desktop.Framework.Dialogs; using ArcGIS.Desktop.Framework.Threading.Tasks; using ArcGIS.Desktop.Mapping; namespace OverlayGroundSurface { /// <summary> /// OverlayGroundSurface illustrates how to draw geometries over a ground surface using AddOverlay. /// </summary> /// <remarks> /// 1. Download the Community Sample data (see under the 'Resources' section for downloading sample data). The sample data contains a folder called 'C:\Data\Configurations\Projects' with sample data required for this solution. Make sure that the Sample data (specifically CommunitySampleData-3D-mm-dd-yyyy.zip) is unzipped into c:\data and c:\data\PolyTest is available. /// 1. This solution is using the **Newtonsoft.Json NuGet**. If needed, you can install the NuGet from the "NuGet Package Manager Console" by using this script: "Install-Package Newtonsoft.Json". /// 1. In Visual Studio click the Build menu. Then select Build Solution. /// 1. Click Start button to debug ArcGIS Pro. /// 1. Open the Pro project file: PolyTest.aprx in the C:\Data\PolyTest\ folder. Open the 'Graphic Test' tab in ArcGIS Pro. /// ![UI](Screenshots/Screen1.png) /// 1. Make sure that the 'Scene' is selected as the active map in ArcGIS Pro and then click on the 'Create 3D Polygon Tool'. /// 1. Digitize a polygon on the map. Once a polygon has been digitized the buttons under the 'Polygon 2 Graphic' group are now enabled. These buttons can be used to 'slice' the digitized polygon into smaller parts. /// ![UI](Screenshots/Screen2.png) /// 1. Note that the number of slices across the X axis can be controlled with the Resolution pull-down. The 'Elevation' pull-down can be used add an additional elevation offset to the Z axis when the polygon is rendered in a scene. /// 1. Select: Resolution 4 and Elevation 5 on the respective pull-down and click the 'Make Ring MultiPatch' button. /// 1. The Add-in now converts the digitized polygon into a multipatch geometry and renders the multipatch in 2D and 3D. /// ![UI](Screenshots/Screen3.png) /// 1. Select: Resolution 50 and Elevation 20 on the respective pull-down and click the 'Make Ring MultiPatch' button. /// 1. The Add-in now converts the digitized polygon into a higher resolution multipatch geometry and renders the multipatch in 3D and 3D. /// ![UI](Screenshots/Screen4.png) /// </remarks> internal class Module1 : Module { private static Module1 _this = null; /// <summary> /// Retrieve the singleton instance to this module here /// </summary> public static Module1 Current { get { return _this ?? (_this = (Module1)FrameworkApplication.FindModule("OverlayGroundSurface_Module")); } } internal static MapView CurrentMapView { get; set; } #region UI properties and states private static List<Geometry> _geometries = new List<Geometry>(); private static bool _hasImportData = false; internal static bool HasImportData { get { return _hasImportData; } set { _hasImportData = value; } } internal static bool HasGeometries { get { return HasImportData && _geometries.Count > 0; } } internal static List<Geometry> Geometries { get { return _geometries; } set { if (value == null) _geometries = null; else { _geometries.Clear(); if (value != null) { foreach (var geom in value) { _geometries.Add(geom.Clone()); } } } SetState("has_geometry_state", _geometries != null && _geometries.Count > 0); } } private static Polygon _polygon = null; internal static Polygon Polygon { get { return _polygon; } set { if (value == null) _polygon = null; else _polygon = value.Clone() as Polygon; SetState("has_polygon_state", _polygon != null); foreach (var mv in _graphics.Keys) { ClearGraphics(mv); } var mvs = new List<MapView>(); foreach (var mv in _graphic.Keys) { if (_graphic[mv] != null) mvs.Add(mv); } foreach (var mv in mvs) { _graphic[mv]?.Dispose(); _graphic[mv] = null; } HasImportData = false; } } internal static void SetState(string stateName, bool active) { if (FrameworkApplication.State.Contains(stateName) == active) return; // toggle the state if (FrameworkApplication.State.Contains(stateName)) { //deactivates the state FrameworkApplication.State.Deactivate(stateName); } else { //activates the state FrameworkApplication.State.Activate(stateName); } } internal static double Resolution { get; set; } = 1.00; internal static double Elevation { get; set; } = 1.00; #endregion UI properties and states #region Overlay Helpers private static Dictionary<MapView, IDisposable> _graphic = new Dictionary<MapView, IDisposable>(); internal static void AddOrUpdateOverlay(Geometry geom, CIMSymbolReference symRef) { var mapView = Module1.CurrentMapView; if (mapView == null) return; ClearGraphics(mapView); if (!_graphic.ContainsKey(mapView)) { _graphic.Add(mapView, mapView.AddOverlay(geom, symRef)); return; } if (_graphic[mapView] == null) { if (geom is Multipatch) { var cimMpGraphic = new CIMMultiPatchGraphic { MultiPatch = geom as Multipatch, Symbol = symRef, Transparency = 64 }; _graphic[mapView] = mapView.AddOverlay(geom, symRef); } else _graphic[mapView] = mapView.AddOverlay(geom, symRef); } else mapView.UpdateOverlay(_graphic[mapView], geom, symRef); } internal static void ClearGraphic(MapView mapView) { if (mapView == null) return; if (_graphic.ContainsKey(mapView)) { _graphic[mapView]?.Dispose(); _graphic[mapView] = null; } } private static Dictionary<MapView, List<IDisposable>> _graphics = new Dictionary<MapView, List<IDisposable>>(); private static void ClearGraphics(MapView mapView) { if (_graphics.ContainsKey(mapView)) { foreach (var g in _graphics[mapView]) g.Dispose(); _graphics[mapView].Clear(); } } internal static void MultiAddOrUpdateOverlay(bool bFirst, Geometry geom, CIMSymbolReference symRef) { var mapView = Module1.CurrentMapView; if (mapView == null) return; if (bFirst) { ClearGraphic(mapView); ClearGraphics(mapView); } if (!_graphics.ContainsKey(mapView)) { _graphics.Add(mapView, new List<IDisposable>()); } _graphics[mapView].Add(Module1.CurrentMapView?.AddOverlay(geom, symRef)); } #endregion Overlay Helpers #region Utility Helpers internal static bool Is3D => (Module1.CurrentMapView?.ViewingMode == MapViewingMode.SceneGlobal || Module1.CurrentMapView?.ViewingMode == MapViewingMode.SceneLocal); internal static double GetFishnetIntervalDistance(Envelope env) { return ((env.XMax - env.XMin) + (env.XMax - env.XMin) * 0.01) / Resolution; } #endregion Utility Helpers #region Polygon Helpers internal static List<Geometry> MakeFishnetPolygons(Polygon inputPoly) { List<Geometry> polygons = new List<Geometry>(); Envelope envPoly = inputPoly.Extent; var interval = GetFishnetIntervalDistance(envPoly); for (var dX = envPoly.XMin; dX < envPoly.XMax + interval; dX += interval) { for (var dY = envPoly.YMin; dY < envPoly.YMax + interval; dY += interval) { var cutEnv = EnvelopeBuilder.CreateEnvelope(dX, dY, dX + interval, dY + interval, envPoly.SpatialReference); if (GeometryEngine.Instance.Intersects(cutEnv, inputPoly)) { var addPolygonPart = GeometryEngine.Instance.Clip(inputPoly, cutEnv); polygons.Add(addPolygonPart); } } } return polygons; } internal static Geometry MakeFishnetPolygon(Polygon inputPoly) { Envelope envPoly = inputPoly.Extent; var interval = GetFishnetIntervalDistance(envPoly); var pb = new PolygonBuilder(inputPoly.SpatialReference) { HasZ = true }; for (var dX = envPoly.XMin; dX < envPoly.XMax + interval; dX += interval) { for (var dY = envPoly.YMin; dY < envPoly.YMax + interval; dY += interval) { var cutEnv = EnvelopeBuilder.CreateEnvelope(dX, dY, dX + interval, dY + interval, envPoly.SpatialReference); if (GeometryEngine.Instance.Intersects(cutEnv, inputPoly)) { var addPolygonPart = GeometryEngine.Instance.Clip(inputPoly, cutEnv) as Polygon; if (addPolygonPart.Area < 0) { System.Diagnostics.Debug.WriteLine($@"area: {addPolygonPart.Area}"); } pb.AddPart(addPolygonPart.Points); } } } return pb.ToGeometry(); } #endregion Polygon Helpers #region MultiPatch Helpers internal static async Task<Geometry> MakeFishnetMultiPatchAsync(Polygon inputPoly) { Envelope envPoly = inputPoly.Extent; var interval = GetFishnetIntervalDistance(envPoly); var mColor = System.Windows.Media.Colors.LightCyan; var materialRed = new BasicMaterial { Color = mColor, EdgeColor = mColor, EdgeWidth = 0 }; // create the multipatchBuilderEx object var mpb = new MultipatchBuilderEx(); // create a list of patch objects var patches = new List<Patch>(); for (var dX = envPoly.XMin; dX < envPoly.XMax + interval; dX += interval) { for (var dY = envPoly.YMin; dY < envPoly.YMax + interval; dY += interval) { var cutEnv = EnvelopeBuilder.CreateEnvelope(dX, dY, dX + interval, dY + interval, envPoly.SpatialReference); if (GeometryEngine.Instance.Intersects(cutEnv, inputPoly)) { var addPolygonPart = GeometryEngine.Instance.Clip(inputPoly, cutEnv) as Polygon; if (addPolygonPart.Area < 0) { System.Diagnostics.Debug.WriteLine($@"area: {addPolygonPart.Area}"); } var result = await Module1.CurrentMapView.Map.GetZsFromSurfaceAsync(addPolygonPart); if (result.Status == SurfaceZsResultStatus.Ok) { addPolygonPart = GeometryEngine.Instance.Move(result.Geometry, 0, 0, Module1.Elevation) as Polygon; } var patch = mpb.MakePatch(esriPatchType.TriangleStrip); patch.Coords = GetPolygonAsTriangleStrip(addPolygonPart); patch.Material = materialRed; patches.Add(patch); } } } // assign the patches to the multipatchBuilder mpb.Patches = patches; // call ToGeometry to get the multipatch return mpb.ToGeometry(); } internal static async Task<Multipatch> MakeFishnetRingMultiPatchAsync(Polygon inputPoly) { Envelope envPoly = inputPoly.Extent; var interval = GetFishnetIntervalDistance(envPoly); var mColor = System.Windows.Media.Colors.LightCyan; var materialRed = new BasicMaterial { Color = mColor, EdgeColor = mColor, EdgeWidth = 0 }; // create the multipatchBuilderEx object var mpb = new MultipatchBuilderEx(); // create a list of patch objects var patches = new List<Patch>(); var first = true; for (var dX = envPoly.XMin; dX < envPoly.XMax + interval; dX += interval) { for (var dY = envPoly.YMin; dY < envPoly.YMax + interval; dY += interval) { var cutEnv = EnvelopeBuilder.CreateEnvelope(dX, dY, dX + interval, dY + interval, envPoly.SpatialReference); if (GeometryEngine.Instance.Intersects(cutEnv, inputPoly)) { var addPolygonPart = GeometryEngine.Instance.Clip(inputPoly, cutEnv) as Polygon; if (addPolygonPart.Area < 0) { System.Diagnostics.Debug.WriteLine($@"area: {addPolygonPart.Area}"); } var result = await Module1.CurrentMapView.Map.GetZsFromSurfaceAsync(addPolygonPart); if (result.Status == SurfaceZsResultStatus.Ok) { addPolygonPart = GeometryEngine.Instance.Move(result.Geometry, 0, 0, Module1.Elevation) as Polygon; } var patch = mpb.MakePatch(first ? esriPatchType.FirstRing : esriPatchType.Ring); first = false; patch.InsertPoints(0, addPolygonPart.Points); patch.Material = materialRed; patches.Add(patch); } } } // assign the patches to the multipatchBuilder mpb.Patches = patches; // call ToGeometry to get the multipatch return mpb.ToGeometry() as Multipatch; } internal static List<Coordinate3D> GetPolygonAsTriangleStrip(Polygon poly) { if (poly.PointCount < 4) { throw new Exception($@"Polygon 2 Triangle failed, too few vertices: {poly.PointCount}"); } int maxPoints = poly.PointCount - 1; Coordinate3D[] coords = new Coordinate3D[maxPoints]; int iNext = 0; foreach (var coord in poly.Copy3DCoordinatesToList()) { if (iNext < maxPoints) coords[iNext++] = coord; } var lstCoords = new List<Coordinate3D>(); int iTop = maxPoints - 1; int iBottom = 0; lstCoords.Add(DebugCoord(iBottom, coords[iBottom++])); lstCoords.Add(DebugCoord(iBottom, coords[iBottom++])); lstCoords.Add(DebugCoord(iTop, coords[iTop--])); var tick = true; for (; iTop >= iBottom; tick = !tick) { lstCoords.Add(tick ? DebugCoord(iBottom, coords[iBottom++]) : DebugCoord(iTop, coords[iTop--])); } // get the coordinates in triangle strip order return lstCoords; } internal static Coordinate3D DebugCoord(int idx, Coordinate3D coord) { // System.Diagnostics.Debug.WriteLine($@"Pnt: {idx} {coord.X} {coord.Y} {coord.Z} "); return coord; } /// <summary> /// Call from MCT. /// </summary> /// <returns></returns> internal static CIMSymbolReference GetDefaultMeshSymbol() { // find a 3d symbol var spi = Project.Current.GetItems<StyleProjectItem>().First(s => s.Name == "ArcGIS 3D"); if (spi == null) return null; // create new structural features var style_item = spi.SearchSymbols(StyleItemType.MeshSymbol, "").FirstOrDefault(si => si.Name.StartsWith("Gray 40%")); var symbol = style_item?.Symbol as CIMMeshSymbol; if (symbol == null) return null; var meshSymbol = symbol.MakeSymbolReference(); return meshSymbol; } #endregion MultiPatch Helpers #region Symbol Helpers private static CIMSymbolReference _polySymbolRef = null; internal static CIMSymbolReference GetPolygonSymbolRef() { if (_polySymbolRef != null) return _polySymbolRef; //Creating a polygon with a red fill and blue outline. CIMStroke outline = SymbolFactory.Instance.ConstructStroke( ColorFactory.Instance.BlueRGB, 2.0, SimpleLineStyle.Solid); _polySymbolRef = SymbolFactory.Instance.ConstructPolygonSymbol( ColorFactory.Instance.CreateRGBColor(255, 190, 190), SimpleFillStyle.Solid, outline).MakeSymbolReference(); return _polySymbolRef; } private static CIMSymbolReference _lineSymbolRef = null; /// <summary> /// Get a line symbol /// Must be called from the MCT. Use QueuedTask.Run. /// </summary> /// <returns></returns> internal static CIMSymbolReference GetLineSymbolRef() { if (_lineSymbolRef != null) return _lineSymbolRef; _lineSymbolRef = SymbolFactory.Instance.ConstructLineSymbol( ColorFactory.Instance.RedRGB, 4, SimpleLineStyle.Solid).MakeSymbolReference(); return _lineSymbolRef; } private static CIMSymbolReference _point3DSymbolRef = null; private static CIMSymbolReference _point2DSymbolRef = null; internal static CIMSymbolReference GetPointSymbolRef() { if (Is3D) { if (_point3DSymbolRef != null) return _point3DSymbolRef; var pointSymbol = GetPointSymbol("ArcGIS 3D", @"Pushpin 2"); CIMPointSymbol pnt3DSym = pointSymbol.Symbol as CIMPointSymbol; pnt3DSym.SetSize(200); pnt3DSym.SetRealWorldUnits(true); _point3DSymbolRef = pnt3DSym.MakeSymbolReference(); return _point3DSymbolRef; } if (_point2DSymbolRef != null) return _point2DSymbolRef; CIMPointSymbol pntSym = SymbolFactory.Instance.ConstructPointSymbol(ColorFactory.Instance.RedRGB, 8, SimpleMarkerStyle.Circle); _point2DSymbolRef = pntSym.MakeSymbolReference(); return _point2DSymbolRef; } private static SymbolStyleItem GetPointSymbol(string styleProjectItemName, string symbolStyleName) { var style3DProjectItem = Project.Current.GetItems<StyleProjectItem>().Where(p => p.Name == styleProjectItemName).FirstOrDefault(); var symbolStyle = style3DProjectItem.SearchSymbols(StyleItemType.PointSymbol, symbolStyleName).FirstOrDefault(); return symbolStyle; } #endregion Symbol Helper #region Overrides /// <summary> /// Called by Framework when ArcGIS Pro is closing /// </summary> /// <returns>False to prevent Pro from closing, otherwise True</returns> protected override bool CanUnload() { //TODO - add your business logic //return false to ~cancel~ Application close return true; } #endregion Overrides } }
using System; using System.Collections; using System.IO.Ports; using System.Text; using System.Threading; using Microsoft.SPOT; using PervasiveDigital.Utilities; namespace PervasiveDigital.Hardware.ESP8266 { public delegate void HardwareFaultHandler(object sender, int cause); internal class Esp8266Serial { public delegate void DataReceivedHandler(object sender, byte[] stream, int channel); public delegate void SocketOpenedHandler(object sender, int channel, out bool fHandled); public delegate void SocketClosedHandler(object sender, int channel); public const int DefaultCommandTimeout = 10000; private readonly SerialPort _port; private readonly Queue _responseQueue = new Queue(); private readonly AutoResetEvent _responseReceived = new AutoResetEvent(false); private readonly AutoResetEvent _newDataReceived = new AutoResetEvent(false); private readonly Queue _receivedDataQueue = new Queue(); private readonly object _lockSendExpect = new object(); private readonly byte[] _ipdSequence; // Circular buffers that will grow in 256-byte increments - one for commands and one for received streams private readonly CircularBuffer _buffer = new CircularBuffer(512, 1, 256); private readonly CircularBuffer _stream = new CircularBuffer(512, 1, 256); public event DataReceivedHandler DataReceived; public event SocketOpenedHandler SocketOpened; public event SocketClosedHandler SocketClosed; public event HardwareFaultHandler Fault; private int _cbStream = 0; private int _receivingOnChannel; private object _readLoopMonitor = new object(); private readonly ManualResetEvent _noStreamRead = new ManualResetEvent(true); private bool _enableDebugOutput; private bool _enableVerboseOutput; public Esp8266Serial(SerialPort port) { this.CommandTimeout = DefaultCommandTimeout; _port = port; _ipdSequence = Encoding.UTF8.GetBytes("+IPD"); } public void Start() { _port.DataReceived += PortOnDataReceived; _port.Open(); } public void Stop() { _port.Close(); _port.DataReceived -= PortOnDataReceived; } public int CommandTimeout { get; set; } public bool EnableDebugOutput { get { return _enableDebugOutput; } set { _enableDebugOutput = value; } } public bool EnableVerboseOutput { get { return _enableVerboseOutput; } set { _enableVerboseOutput = value; } } public void SendCommand(string send) { lock (_lockSendExpect) { DiscardBufferedInput(); WriteCommand(send); } } public void SendAndExpect(string send, string expect) { SendAndExpect(send, expect, DefaultCommandTimeout); } public void SendAndExpect(string send, string[] accept, string expect) { SendAndExpect(send, accept, expect, DefaultCommandTimeout); } public void SendAndExpect(string send, string expect, int timeout) { lock (_lockSendExpect) { DiscardBufferedInput(); WriteCommand(send); Expect(new[] { send, "no change" }, expect, timeout); } } public void SendAndExpect(string send, string[] accept, string expect, int timeout) { lock (_lockSendExpect) { DiscardBufferedInput(); WriteCommand(send); var acceptList = new string[accept.Length + 1]; acceptList[0] = send; Array.Copy(accept, 0, acceptList, 1, accept.Length); Expect(acceptList, expect, timeout); } } public string[] SendAndReadUntil(string send, string terminator) { return SendAndReadUntil(send, terminator, DefaultCommandTimeout); } public void Find(string successString) { Find(successString, DefaultCommandTimeout); } public void Find(string successString, int timeout) { SendAndReadUntil(null, successString, timeout); } public string[] SendAndReadUntil(string send, string terminator, int timeout) { ArrayList result = new ArrayList(); if (send != null) SendCommand(send); do { var line = GetReplyWithTimeout(timeout); if (line != null && line.Length > 0) { // in case echo is on if (send != null && line.IndexOf(send) == 0) continue; // read until we see the magic termination string - usually 'OK' if (line.IndexOf(terminator) == 0) break; result.Add(line); } } while (true); return (string[])result.ToArray(typeof(string)); } public string SendCommandAndReadReply(string command) { return SendCommandAndReadReply(command, DefaultCommandTimeout); } public string SendCommandAndReadReply(string command, int timeout) { string response; lock (_lockSendExpect) { DiscardBufferedInput(); WriteCommand(command); do { response = GetReplyWithTimeout(timeout); } while (response == null || response == "" || response == command); } return response; } public void Expect(string expect) { Expect(null, expect, DefaultCommandTimeout); } public void Expect(string expect, int timeout) { Expect(null, expect, timeout); } public void Expect(string[] accept, string expect) { Expect(accept, expect, DefaultCommandTimeout); } public void Expect(string[] accept, string expect, int timeout) { if (accept == null) accept = new[] { "" }; bool acceptableInputFound; string response; do { acceptableInputFound = false; response = GetReplyWithTimeout(timeout); foreach (var s in accept) { #if MF_FRAMEWORK if (response == "" || string.Equals(response.ToLower(), s.ToLower())) #else if (response=="" || string.Equals(response, s, StringComparison.OrdinalIgnoreCase)) #endif { acceptableInputFound = true; break; } } } while (acceptableInputFound); #if MF_FRAMEWORK if (!string.Equals(response.ToLower(), expect.ToLower())) #else if (!string.Equals(response, expect, StringComparison.OrdinalIgnoreCase)) #endif { throw new FailedExpectException(expect, response); } } public string GetReplyWithTimeout(int timeout) { string response = null; bool haveNewData; do { lock (_responseQueue.SyncRoot) { if (_responseQueue.Count > 0) { response = (string)_responseQueue.Dequeue(); } else { _responseReceived.Reset(); } } // If nothing was waiting in the queue, then wait for new data to arrive haveNewData = false; if (response == null) haveNewData = _responseReceived.WaitOne(timeout, false); } while (response == null && haveNewData); // We have received no data, and the WaitOne timed out if (response == null && !haveNewData) { throw new CommandTimeoutException(); } if (_enableDebugOutput) Debug.Print("Consumed: " + response); return response; } private byte[] ReadExistingBinary() { int arraySize = _port.BytesToRead; byte[] received = new byte[arraySize]; _port.Read(received, 0, arraySize); if (_enableVerboseOutput) Dump("RECV:", received); return received; } public void DiscardBufferedInput() { // you cannot discard input if a stream read is in progress _noStreamRead.WaitOne(); Monitor.Enter(_readLoopMonitor); try { lock (_responseQueue.SyncRoot) { _responseQueue.Clear(); _responseReceived.Reset(); _buffer.Clear(); _port.DiscardInBuffer(); _stream.Clear(); } if (_enableVerboseOutput) Debug.Print("BUFFER CLEARED"); } finally { Monitor.Exit(_readLoopMonitor); } } public void Write(string txt) { this.Write(Encoding.UTF8.GetBytes(txt)); } public void Write(byte[] payload) { if (_enableVerboseOutput) Dump("SEND:", payload); _port.Write(payload, 0, payload.Length); } private void WriteCommand(string txt) { if (_enableDebugOutput) Log("Sent command : " + txt); this.Write(txt + "\r\n"); } private void PortOnDataReceived(object sender, SerialDataReceivedEventArgs serialDataReceivedEventArgs) { if (serialDataReceivedEventArgs.EventType == SerialData.Chars) { // Keep doing this while there are bytes to read - don't rely on just event notification // The ESP8266 is very timing sensitive and subject to buffer overrun - keep the loop tight. var newInput = ReadExistingBinary(); if (newInput != null && newInput.Length > 0) { _buffer.Put(newInput); } ProcessBufferedInput(); } } private void ProcessBufferedInput() { do { Monitor.Enter(_readLoopMonitor); try { // if _cbstream is non-zero, then we are reading a counted stream of bytes, not crlf-delimited input if (_cbStream != 0) { // If we are capturing an input stream, then copy characters from the serial port // until the count of desired characters == 0 while (_cbStream > 0 && _buffer.Size > 0) { var eat = _cbStream; if (_buffer.Size < _cbStream) eat = _buffer.Size; _stream.Put(_buffer.Get(eat)); _cbStream -= eat; if (_enableDebugOutput) { Debug.Print("STREAM: Copied " + eat + " characters to stream. Buffer contains:" + _buffer.Size + " Stream contains : " + _stream.Size + " Still need:" + _cbStream); } } // If we have fulfilled the stream request, then dispatch the received data to the datareceived handler if (_cbStream == 0) { if (DataReceived != null) { try { var channel = _receivingOnChannel; var data = _stream.Get(_stream.Size); _noStreamRead.Set(); // Run this in the background so as not to slow down the read loop ThreadPool.QueueUserWorkItem(DataReceivedThunk ,new object[] { data, channel }); //new Thread(() => { DataReceived(this, data, channel); }).Start(); } catch (Exception) { // mask exceptions in the callback so that they don't kill our read loop } } _receivingOnChannel = -1; _stream.Clear(); } } if (_cbStream == 0) { // process whatever is left in the buffer (after fulfilling any stream requests) var idxNewline = _buffer.IndexOf(0x0A); var idxIPD = _buffer.IndexOf(_ipdSequence); while ((idxNewline != -1 || idxIPD != -1) && _cbStream == 0) { string line = ""; if ((idxIPD == -1 && idxNewline!=-1) || (idxNewline != -1 && idxNewline < idxIPD)) { if (idxNewline == 0) line = ""; else line = StringUtilities.ConvertToString(_buffer.Get(idxNewline)).Trim(); // eat the newline too _buffer.Skip(1); if (!StringUtilities.IsNullOrEmpty(line)) { if (_enableDebugOutput) Log("Received : " + line); if (line.StartsWith("ets ")) { // we're rebooting var idxCause = line.IndexOf("rst cause:"); int iCause = -1; if (idxCause != -1) { var start = idxCause + 10; var idxComma = line.Substring(start).IndexOf(','); iCause = int.Parse(line.Substring(start, idxComma)); } if (this.Fault != null) this.Fault(this, iCause); } if (line.StartsWith("wdt ") || line.StartsWith("load ") || line.StartsWith("tail ") || line.StartsWith("chksum ") || line.StartsWith("csum ")) return; // Handle async notifications and command responses var idxClosed = line.IndexOf(",CLOSED"); if (idxClosed != -1) { // Handle socket-closed notification var channel = int.Parse(line.Substring(0, idxClosed)); if (this.SocketClosed != null) this.SocketClosed(this, channel); } else { var idxConnect = line.IndexOf(",CONNECT"); if (idxConnect != -1) { // Handle socket-opened notification bool fHandled = false; var channel = int.Parse(line.Substring(0, idxConnect)); if (this.SocketOpened != null) this.SocketOpened(this, channel, out fHandled); if (!fHandled) EnqueueLine(line); } else EnqueueLine(line); } } } else if (idxIPD!=-1) // idxIPD found before newline { // find the colon which ends the data-stream introducer var idxColon = _buffer.IndexOf(0x3A); // we did not get the full introducer - we have to wait for more chars to come in if (idxColon == -1) break; // Convert the introducer _buffer.Skip(idxIPD); line = StringUtilities.ConvertToString(_buffer.Get(idxColon - idxIPD)).Trim(); _buffer.Skip(1); // eat the colon if (line != null && line.Length > 0) { var tokens = line.Split(','); _receivingOnChannel = int.Parse(tokens[1]); _cbStream = int.Parse(tokens[2]); // block anything that would interfere with the stream read - this is used in the DiscardBufferedInput call that preceeds the sending of every command _noStreamRead.Reset(); if (_enableDebugOutput) Log("Reading a stream of " + _cbStream + " bytes for channel " + _receivingOnChannel); } } // What next? idxNewline = _buffer.IndexOf(0x0A); idxIPD = _buffer.IndexOf(_ipdSequence); } } } catch (Exception exc) { // Ignore exceptions - this loop needs to keep running Debug.Print("Exception in Esp8266.ReadLoop() : " + exc); } finally { Monitor.Exit(_readLoopMonitor); } } while (_cbStream > 0 && _buffer.Size > 0); } private void DataReceivedThunk(object state) { var args = (object[])state; if (DataReceived != null) { try { DataReceived(this, (byte[])args[0], (int)args[1]); } catch { } } } private void EnqueueLine(string line) { lock (_responseQueue.SyncRoot) { _responseQueue.Enqueue(line); _responseReceived.Set(); } } private static void Log(string msg) { Debug.Print(msg); } private static void Dump(string tag, byte[] data) { StringBuilder sbLeft = new StringBuilder(); StringBuilder sbRight = new StringBuilder(); sbLeft.Append(tag); // round up the length to make for pretty output var length = (data.Length + 15) / 16 * 16; var actualLen = data.Length; for (int i = 0 ; i < length ; ++i) { if (i < actualLen) { var b = data[i]; sbLeft.Append(b.ToHex() + ' '); if (b > 32 && b < 127) sbRight.Append((char) b); else sbRight.Append('.'); } else { sbLeft.Append(" "); sbRight.Append(' '); } if ((i + 1) % 8 == 0) sbLeft.Append(" "); if ((i + 1) % 16 == 0) { sbLeft.Append(sbRight); Debug.Print(sbLeft.ToString()); sbLeft.Clear(); sbRight.Clear(); for (var j = 0; j < tag.Length; ++j) sbLeft.Append(' '); } } if (sbRight.Length > 0) { sbLeft.Append(sbRight + " "); Debug.Print(sbLeft.ToString()); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Text; using System.Runtime.Versioning; #if !HIDE_XSL using System.Xml.Xsl.Runtime; #endif namespace System.Xml { public enum XmlOutputMethod { Xml = 0, // Use Xml 1.0 rules to serialize Html = 1, // Use Html rules specified by Xslt specification to serialize Text = 2, // Only serialize text blocks AutoDetect = 3, // Choose between Xml and Html output methods at runtime (using Xslt rules to do so) } /// <summary> /// Three-state logic enumeration. /// </summary> internal enum TriState { Unknown = -1, False = 0, True = 1, }; internal enum XmlStandalone { // Do not change the constants - XmlBinaryWriter depends in it Omit = 0, Yes = 1, No = 2, } // XmlWriterSettings class specifies basic features of an XmlWriter. public sealed class XmlWriterSettings { // // Fields // private bool _useAsync; // Text settings private Encoding _encoding; #if FEATURE_LEGACYNETCF private bool dontWriteEncodingTag; #endif private bool _omitXmlDecl; private NewLineHandling _newLineHandling; private string _newLineChars; private TriState _indent; private string _indentChars; private bool _newLineOnAttributes; private bool _closeOutput; private NamespaceHandling _namespaceHandling; // Conformance settings private ConformanceLevel _conformanceLevel; private bool _checkCharacters; private bool _writeEndDocumentOnClose; // Xslt settings private XmlOutputMethod _outputMethod; private List<XmlQualifiedName> _cdataSections = new List<XmlQualifiedName>(); private bool _doNotEscapeUriAttributes; private bool _mergeCDataSections; private string _mediaType; private string _docTypeSystem; private string _docTypePublic; private XmlStandalone _standalone; private bool _autoXmlDecl; // read-only flag private bool _isReadOnly; // // Constructor // public XmlWriterSettings() { Initialize(); } // // Properties // public bool Async { get { return _useAsync; } set { CheckReadOnly(nameof(Async)); _useAsync = value; } } // Text public Encoding Encoding { get { return _encoding; } set { CheckReadOnly(nameof(Encoding)); _encoding = value; } } #if FEATURE_LEGACYNETCF internal bool DontWriteEncodingTag { get { return dontWriteEncodingTag; } set { CheckReadOnly(nameof(DontWriteEncodingTag)); dontWriteEncodingTag = value; } } #endif // True if an xml declaration should *not* be written. public bool OmitXmlDeclaration { get { return _omitXmlDecl; } set { CheckReadOnly(nameof(OmitXmlDeclaration)); _omitXmlDecl = value; } } // See NewLineHandling enum for details. public NewLineHandling NewLineHandling { get { return _newLineHandling; } set { CheckReadOnly(nameof(NewLineHandling)); if (unchecked((uint)value) > (uint)NewLineHandling.None) { throw new ArgumentOutOfRangeException(nameof(value)); } _newLineHandling = value; } } // Line terminator string. By default, this is a carriage return followed by a line feed ("\r\n"). public string NewLineChars { get { return _newLineChars; } set { CheckReadOnly(nameof(NewLineChars)); if (value == null) { throw new ArgumentNullException(nameof(value)); } _newLineChars = value; } } // True if output should be indented using rules that are appropriate to the output rules (i.e. Xml, Html, etc). public bool Indent { get { return _indent == TriState.True; } set { CheckReadOnly(nameof(Indent)); _indent = value ? TriState.True : TriState.False; } } // Characters to use when indenting. This is usually tab or some spaces, but can be anything. public string IndentChars { get { return _indentChars; } set { CheckReadOnly(nameof(IndentChars)); if (value == null) { throw new ArgumentNullException(nameof(value)); } _indentChars = value; } } // Whether or not indent attributes on new lines. public bool NewLineOnAttributes { get { return _newLineOnAttributes; } set { CheckReadOnly(nameof(NewLineOnAttributes)); _newLineOnAttributes = value; } } // Whether or not the XmlWriter should close the underlying stream or TextWriter when Close is called on the XmlWriter. public bool CloseOutput { get { return _closeOutput; } set { CheckReadOnly(nameof(CloseOutput)); _closeOutput = value; } } // Conformance // See ConformanceLevel enum for details. public ConformanceLevel ConformanceLevel { get { return _conformanceLevel; } set { CheckReadOnly(nameof(ConformanceLevel)); if (unchecked((uint)value) > (uint)ConformanceLevel.Document) { throw new ArgumentOutOfRangeException(nameof(value)); } _conformanceLevel = value; } } // Whether or not to check content characters that they are valid XML characters. public bool CheckCharacters { get { return _checkCharacters; } set { CheckReadOnly(nameof(CheckCharacters)); _checkCharacters = value; } } // Whether or not to remove duplicate namespace declarations public NamespaceHandling NamespaceHandling { get { return _namespaceHandling; } set { CheckReadOnly(nameof(NamespaceHandling)); if (unchecked((uint)value) > (uint)(NamespaceHandling.OmitDuplicates)) { throw new ArgumentOutOfRangeException(nameof(value)); } _namespaceHandling = value; } } //Whether or not to auto complete end-element when close/dispose public bool WriteEndDocumentOnClose { get { return _writeEndDocumentOnClose; } set { CheckReadOnly(nameof(WriteEndDocumentOnClose)); _writeEndDocumentOnClose = value; } } // Specifies the method (Html, Xml, etc.) that will be used to serialize the result tree. public XmlOutputMethod OutputMethod { get { return _outputMethod; } internal set { _outputMethod = value; } } // // Public methods // public void Reset() { CheckReadOnly(nameof(Reset)); Initialize(); } // Deep clone all settings (except read-only, which is always set to false). The original and new objects // can now be set independently of each other. public XmlWriterSettings Clone() { XmlWriterSettings clonedSettings = MemberwiseClone() as XmlWriterSettings; // Deep clone shared settings that are not immutable clonedSettings._cdataSections = new List<XmlQualifiedName>(_cdataSections); clonedSettings._isReadOnly = false; return clonedSettings; } // // Internal properties // // Set of XmlQualifiedNames that identify any elements that need to have text children wrapped in CData sections. internal List<XmlQualifiedName> CDataSectionElements { get { Debug.Assert(_cdataSections != null); return _cdataSections; } } // Used in Html writer to disable encoding of uri attributes public bool DoNotEscapeUriAttributes { get { return _doNotEscapeUriAttributes; } set { CheckReadOnly("DoNotEscapeUriAttributes"); _doNotEscapeUriAttributes = value; } } internal bool MergeCDataSections { get { return _mergeCDataSections; } set { CheckReadOnly("MergeCDataSections"); _mergeCDataSections = value; } } // Used in Html writer when writing Meta element. Null denotes the default media type. internal string MediaType { get { return _mediaType; } set { CheckReadOnly("MediaType"); _mediaType = value; } } // System Id in doc-type declaration. Null denotes the absence of the system Id. internal string DocTypeSystem { get { return _docTypeSystem; } set { CheckReadOnly("DocTypeSystem"); _docTypeSystem = value; } } // Public Id in doc-type declaration. Null denotes the absence of the public Id. internal string DocTypePublic { get { return _docTypePublic; } set { CheckReadOnly("DocTypePublic"); _docTypePublic = value; } } // Yes for standalone="yes", No for standalone="no", and Omit for no standalone. internal XmlStandalone Standalone { get { return _standalone; } set { CheckReadOnly("Standalone"); _standalone = value; } } // True if an xml declaration should automatically be output (no need to call WriteStartDocument) internal bool AutoXmlDeclaration { get { return _autoXmlDecl; } set { CheckReadOnly("AutoXmlDeclaration"); _autoXmlDecl = value; } } // If TriState.Unknown, then Indent property was not explicitly set. In this case, the AutoDetect output // method will default to Indent=true for Html and Indent=false for Xml. internal TriState IndentInternal { get { return _indent; } set { _indent = value; } } internal bool IsQuerySpecific { get { return _cdataSections.Count != 0 || _docTypePublic != null || _docTypeSystem != null || _standalone == XmlStandalone.Yes; } } internal XmlWriter CreateWriter(string outputFileName) { if (outputFileName == null) { throw new ArgumentNullException(nameof(outputFileName)); } // need to clone the settigns so that we can set CloseOutput to true to make sure the stream gets closed in the end XmlWriterSettings newSettings = this; if (!newSettings.CloseOutput) { newSettings = newSettings.Clone(); newSettings.CloseOutput = true; } FileStream fs = null; try { // open file stream fs = new FileStream(outputFileName, FileMode.Create, FileAccess.Write, FileShare.Read, 0x1000, _useAsync); // create writer return newSettings.CreateWriter(fs); } catch { if (fs != null) { fs.Dispose(); } throw; } } internal XmlWriter CreateWriter(Stream output) { if (output == null) { throw new ArgumentNullException(nameof(output)); } XmlWriter writer; // create raw writer Debug.Assert(Encoding.UTF8.WebName == "utf-8"); if (this.Encoding.WebName == "utf-8") { // Encoding.CodePage is not supported in Silverlight // create raw UTF-8 writer switch (this.OutputMethod) { case XmlOutputMethod.Xml: if (this.Indent) { writer = new XmlUtf8RawTextWriterIndent(output, this); } else { writer = new XmlUtf8RawTextWriter(output, this); } break; case XmlOutputMethod.Html: if (this.Indent) { writer = new HtmlUtf8RawTextWriterIndent(output, this); } else { writer = new HtmlUtf8RawTextWriter(output, this); } break; case XmlOutputMethod.Text: writer = new TextUtf8RawTextWriter(output, this); break; case XmlOutputMethod.AutoDetect: writer = new XmlAutoDetectWriter(output, this); break; default: Debug.Fail("Invalid XmlOutputMethod setting."); return null; } } else { // Otherwise, create a general-purpose writer than can do any encoding switch (this.OutputMethod) { case XmlOutputMethod.Xml: if (this.Indent) { writer = new XmlEncodedRawTextWriterIndent(output, this); } else { writer = new XmlEncodedRawTextWriter(output, this); } break; case XmlOutputMethod.Html: if (this.Indent) { writer = new HtmlEncodedRawTextWriterIndent(output, this); } else { writer = new HtmlEncodedRawTextWriter(output, this); } break; case XmlOutputMethod.Text: writer = new TextEncodedRawTextWriter(output, this); break; case XmlOutputMethod.AutoDetect: writer = new XmlAutoDetectWriter(output, this); break; default: Debug.Fail("Invalid XmlOutputMethod setting."); return null; } } // Wrap with Xslt/XQuery specific writer if needed; // XmlOutputMethod.AutoDetect writer does this lazily when it creates the underlying Xml or Html writer. if (this.OutputMethod != XmlOutputMethod.AutoDetect) { if (this.IsQuerySpecific) { // Create QueryOutputWriter if CData sections or DocType need to be tracked writer = new QueryOutputWriter((XmlRawWriter)writer, this); } } // wrap with well-formed writer writer = new XmlWellFormedWriter(writer, this); if (_useAsync) { writer = new XmlAsyncCheckWriter(writer); } return writer; } internal XmlWriter CreateWriter(TextWriter output) { if (output == null) { throw new ArgumentNullException(nameof(output)); } XmlWriter writer; // create raw writer switch (this.OutputMethod) { case XmlOutputMethod.Xml: if (this.Indent) { writer = new XmlEncodedRawTextWriterIndent(output, this); } else { writer = new XmlEncodedRawTextWriter(output, this); } break; case XmlOutputMethod.Html: if (this.Indent) { writer = new HtmlEncodedRawTextWriterIndent(output, this); } else { writer = new HtmlEncodedRawTextWriter(output, this); } break; case XmlOutputMethod.Text: writer = new TextEncodedRawTextWriter(output, this); break; case XmlOutputMethod.AutoDetect: writer = new XmlAutoDetectWriter(output, this); break; default: Debug.Fail("Invalid XmlOutputMethod setting."); return null; } // XmlOutputMethod.AutoDetect writer does this lazily when it creates the underlying Xml or Html writer. if (this.OutputMethod != XmlOutputMethod.AutoDetect) { if (this.IsQuerySpecific) { // Create QueryOutputWriter if CData sections or DocType need to be tracked writer = new QueryOutputWriter((XmlRawWriter)writer, this); } } // wrap with well-formed writer writer = new XmlWellFormedWriter(writer, this); if (_useAsync) { writer = new XmlAsyncCheckWriter(writer); } return writer; } internal XmlWriter CreateWriter(XmlWriter output) { if (output == null) { throw new ArgumentNullException(nameof(output)); } return AddConformanceWrapper(output); } internal bool ReadOnly { get { return _isReadOnly; } set { _isReadOnly = value; } } private void CheckReadOnly(string propertyName) { if (_isReadOnly) { throw new XmlException(SR.Xml_ReadOnlyProperty, this.GetType().Name + '.' + propertyName); } } // // Private methods // private void Initialize() { _encoding = Encoding.UTF8; _omitXmlDecl = false; _newLineHandling = NewLineHandling.Replace; _newLineChars = Environment.NewLine; // "\r\n" on Windows, "\n" on Unix _indent = TriState.Unknown; _indentChars = " "; _newLineOnAttributes = false; _closeOutput = false; _namespaceHandling = NamespaceHandling.Default; _conformanceLevel = ConformanceLevel.Document; _checkCharacters = true; _writeEndDocumentOnClose = true; _outputMethod = XmlOutputMethod.Xml; _cdataSections.Clear(); _mergeCDataSections = false; _mediaType = null; _docTypeSystem = null; _docTypePublic = null; _standalone = XmlStandalone.Omit; _doNotEscapeUriAttributes = false; _useAsync = false; _isReadOnly = false; } private XmlWriter AddConformanceWrapper(XmlWriter baseWriter) { ConformanceLevel confLevel = ConformanceLevel.Auto; XmlWriterSettings baseWriterSettings = baseWriter.Settings; bool checkValues = false; bool checkNames = false; bool replaceNewLines = false; bool needWrap = false; if (baseWriterSettings == null) { // assume the V1 writer already do all conformance checking; // wrap only if NewLineHandling == Replace or CheckCharacters is true if (_newLineHandling == NewLineHandling.Replace) { replaceNewLines = true; needWrap = true; } if (_checkCharacters) { checkValues = true; needWrap = true; } } else { if (_conformanceLevel != baseWriterSettings.ConformanceLevel) { confLevel = this.ConformanceLevel; needWrap = true; } if (_checkCharacters && !baseWriterSettings.CheckCharacters) { checkValues = true; checkNames = confLevel == ConformanceLevel.Auto; needWrap = true; } if (_newLineHandling == NewLineHandling.Replace && baseWriterSettings.NewLineHandling == NewLineHandling.None) { replaceNewLines = true; needWrap = true; } } XmlWriter writer = baseWriter; if (needWrap) { if (confLevel != ConformanceLevel.Auto) { writer = new XmlWellFormedWriter(writer, this); } if (checkValues || replaceNewLines) { writer = new XmlCharCheckingWriter(writer, checkValues, checkNames, replaceNewLines, this.NewLineChars); } } if (this.IsQuerySpecific && (baseWriterSettings == null || !baseWriterSettings.IsQuerySpecific)) { // Create QueryOutputWriterV1 if CData sections or DocType need to be tracked writer = new QueryOutputWriterV1(writer, this); } return writer; } // // Internal methods // /// <summary> /// Serialize the object to BinaryWriter. /// </summary> internal void GetObjectData(XmlQueryDataWriter writer) { // Encoding encoding; // NOTE: For Encoding we serialize only CodePage, and ignore EncoderFallback/DecoderFallback. // It suffices for XSLT purposes, but not in the general case. Debug.Assert(Encoding.Equals(Encoding.GetEncoding(Encoding.CodePage)), "Cannot serialize encoding correctly"); writer.Write(Encoding.CodePage); // bool omitXmlDecl; writer.Write(OmitXmlDeclaration); // NewLineHandling newLineHandling; writer.Write((sbyte)NewLineHandling); // string newLineChars; writer.WriteStringQ(NewLineChars); // TriState indent; writer.Write((sbyte)IndentInternal); // string indentChars; writer.WriteStringQ(IndentChars); // bool newLineOnAttributes; writer.Write(NewLineOnAttributes); // bool closeOutput; writer.Write(CloseOutput); // ConformanceLevel conformanceLevel; writer.Write((sbyte)ConformanceLevel); // bool checkCharacters; writer.Write(CheckCharacters); // XmlOutputMethod outputMethod; writer.Write((sbyte)_outputMethod); // List<XmlQualifiedName> cdataSections; writer.Write(_cdataSections.Count); foreach (XmlQualifiedName qname in _cdataSections) { writer.Write(qname.Name); writer.Write(qname.Namespace); } // bool mergeCDataSections; writer.Write(_mergeCDataSections); // string mediaType; writer.WriteStringQ(_mediaType); // string docTypeSystem; writer.WriteStringQ(_docTypeSystem); // string docTypePublic; writer.WriteStringQ(_docTypePublic); // XmlStandalone standalone; writer.Write((sbyte)_standalone); // bool autoXmlDecl; writer.Write(_autoXmlDecl); // bool isReadOnly; writer.Write(ReadOnly); } /// <summary> /// Deserialize the object from BinaryReader. /// </summary> internal XmlWriterSettings(XmlQueryDataReader reader) { // Encoding encoding; Encoding = Encoding.GetEncoding(reader.ReadInt32()); // bool omitXmlDecl; OmitXmlDeclaration = reader.ReadBoolean(); // NewLineHandling newLineHandling; NewLineHandling = (NewLineHandling)reader.ReadSByte(0, (sbyte)NewLineHandling.None); // string newLineChars; NewLineChars = reader.ReadStringQ(); // TriState indent; IndentInternal = (TriState)reader.ReadSByte((sbyte)TriState.Unknown, (sbyte)TriState.True); // string indentChars; IndentChars = reader.ReadStringQ(); // bool newLineOnAttributes; NewLineOnAttributes = reader.ReadBoolean(); // bool closeOutput; CloseOutput = reader.ReadBoolean(); // ConformanceLevel conformanceLevel; ConformanceLevel = (ConformanceLevel)reader.ReadSByte(0, (sbyte)ConformanceLevel.Document); // bool checkCharacters; CheckCharacters = reader.ReadBoolean(); // XmlOutputMethod outputMethod; _outputMethod = (XmlOutputMethod)reader.ReadSByte(0, (sbyte)XmlOutputMethod.AutoDetect); // List<XmlQualifiedName> cdataSections; int length = reader.ReadInt32(); _cdataSections = new List<XmlQualifiedName>(length); for (int idx = 0; idx < length; idx++) { _cdataSections.Add(new XmlQualifiedName(reader.ReadString(), reader.ReadString())); } // bool mergeCDataSections; _mergeCDataSections = reader.ReadBoolean(); // string mediaType; _mediaType = reader.ReadStringQ(); // string docTypeSystem; _docTypeSystem = reader.ReadStringQ(); // string docTypePublic; _docTypePublic = reader.ReadStringQ(); // XmlStandalone standalone; Standalone = (XmlStandalone)reader.ReadSByte(0, (sbyte)XmlStandalone.No); // bool autoXmlDecl; _autoXmlDecl = reader.ReadBoolean(); // bool isReadOnly; ReadOnly = reader.ReadBoolean(); } } }
//---------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. //---------------------------------------------------------------------------- namespace System.ServiceModel.Diagnostics { using System.Diagnostics; using System.Reflection; using System.Runtime; using System.Runtime.CompilerServices; using System.Runtime.Diagnostics; using System.ServiceModel.Channels; using System.ServiceModel.Dispatcher; using System.Threading; using System.Security; using System.ServiceModel.Configuration; using System.ServiceModel.Activation; using System.Xml; using System.ServiceModel.Diagnostics.Application; using System.Globalization; using System.Collections.Generic; static class TraceUtility { const string ActivityIdKey = "ActivityId"; const string AsyncOperationActivityKey = "AsyncOperationActivity"; const string AsyncOperationStartTimeKey = "AsyncOperationStartTime"; static bool shouldPropagateActivity; static bool shouldPropagateActivityGlobal; static bool activityTracing; static bool messageFlowTracing; static bool messageFlowTracingOnly; static long messageNumber = 0; static Func<Action<AsyncCallback, IAsyncResult>> asyncCallbackGenerator; static SortedList<int, string> traceCodes = new SortedList<int, string>(382) { // Administration trace codes (TraceCode.Administration) { TraceCode.WmiPut, "WmiPut" }, // Diagnostic trace codes (TraceCode.Diagnostics) { TraceCode.AppDomainUnload, "AppDomainUnload" }, { TraceCode.EventLog, "EventLog" }, { TraceCode.ThrowingException, "ThrowingException" }, { TraceCode.TraceHandledException, "TraceHandledException" }, { TraceCode.UnhandledException, "UnhandledException" }, { TraceCode.FailedToAddAnActivityIdHeader, "FailedToAddAnActivityIdHeader" }, { TraceCode.FailedToReadAnActivityIdHeader, "FailedToReadAnActivityIdHeader" }, { TraceCode.FilterNotMatchedNodeQuotaExceeded, "FilterNotMatchedNodeQuotaExceeded" }, { TraceCode.MessageCountLimitExceeded, "MessageCountLimitExceeded" }, { TraceCode.DiagnosticsFailedMessageTrace, "DiagnosticsFailedMessageTrace" }, { TraceCode.MessageNotLoggedQuotaExceeded, "MessageNotLoggedQuotaExceeded" }, { TraceCode.TraceTruncatedQuotaExceeded, "TraceTruncatedQuotaExceeded" }, { TraceCode.ActivityBoundary, "ActivityBoundary" }, // Serialization trace codes (TraceCode.Serialization) { TraceCode.ElementIgnored, "" }, // shared by ServiceModel, need to investigate if should put this one in the SM section // Channels trace codes (TraceCode.Channels) { TraceCode.ConnectionAbandoned, "ConnectionAbandoned" }, { TraceCode.ConnectionPoolCloseException, "ConnectionPoolCloseException" }, { TraceCode.ConnectionPoolIdleTimeoutReached, "ConnectionPoolIdleTimeoutReached" }, { TraceCode.ConnectionPoolLeaseTimeoutReached, "ConnectionPoolLeaseTimeoutReached" }, { TraceCode.ConnectionPoolMaxOutboundConnectionsPerEndpointQuotaReached, "ConnectionPoolMaxOutboundConnectionsPerEndpointQuotaReached" }, { TraceCode.ServerMaxPooledConnectionsQuotaReached, "ServerMaxPooledConnectionsQuotaReached" }, { TraceCode.EndpointListenerClose, "EndpointListenerClose" }, { TraceCode.EndpointListenerOpen, "EndpointListenerOpen" }, { TraceCode.HttpResponseReceived, "HttpResponseReceived" }, { TraceCode.HttpChannelConcurrentReceiveQuotaReached, "HttpChannelConcurrentReceiveQuotaReached" }, { TraceCode.HttpChannelMessageReceiveFailed, "HttpChannelMessageReceiveFailed" }, { TraceCode.HttpChannelUnexpectedResponse, "HttpChannelUnexpectedResponse" }, { TraceCode.HttpChannelRequestAborted, "HttpChannelRequestAborted" }, { TraceCode.HttpChannelResponseAborted, "HttpChannelResponseAborted" }, { TraceCode.HttpsClientCertificateInvalid, "HttpsClientCertificateInvalid" }, { TraceCode.HttpsClientCertificateNotPresent, "HttpsClientCertificateNotPresent" }, { TraceCode.NamedPipeChannelMessageReceiveFailed, "NamedPipeChannelMessageReceiveFailed" }, { TraceCode.NamedPipeChannelMessageReceived, "NamedPipeChannelMessageReceived" }, { TraceCode.MessageReceived, "MessageReceived" }, { TraceCode.MessageSent, "MessageSent" }, { TraceCode.RequestChannelReplyReceived, "RequestChannelReplyReceived" }, { TraceCode.TcpChannelMessageReceiveFailed, "TcpChannelMessageReceiveFailed" }, { TraceCode.TcpChannelMessageReceived, "TcpChannelMessageReceived" }, { TraceCode.ConnectToIPEndpoint, "ConnectToIPEndpoint" }, { TraceCode.SocketConnectionCreate, "SocketConnectionCreate" }, { TraceCode.SocketConnectionClose, "SocketConnectionClose" }, { TraceCode.SocketConnectionAbort, "SocketConnectionAbort" }, { TraceCode.SocketConnectionAbortClose, "SocketConnectionAbortClose" }, { TraceCode.PipeConnectionAbort, "PipeConnectionAbort" }, { TraceCode.RequestContextAbort, "RequestContextAbort" }, { TraceCode.ChannelCreated, "ChannelCreated" }, { TraceCode.ChannelDisposed, "ChannelDisposed" }, { TraceCode.ListenerCreated, "ListenerCreated" }, { TraceCode.ListenerDisposed, "ListenerDisposed" }, { TraceCode.PrematureDatagramEof, "PrematureDatagramEof" }, { TraceCode.MaxPendingConnectionsReached, "MaxPendingConnectionsReached" }, { TraceCode.MaxAcceptedChannelsReached, "MaxAcceptedChannelsReached" }, { TraceCode.ChannelConnectionDropped, "ChannelConnectionDropped" }, { TraceCode.HttpAuthFailed, "HttpAuthFailed" }, { TraceCode.NoExistingTransportManager, "NoExistingTransportManager" }, { TraceCode.IncompatibleExistingTransportManager, "IncompatibleExistingTransportManager" }, { TraceCode.InitiatingNamedPipeConnection, "InitiatingNamedPipeConnection" }, { TraceCode.InitiatingTcpConnection, "InitiatingTcpConnection" }, { TraceCode.OpenedListener, "OpenedListener" }, { TraceCode.SslClientCertMissing, "SslClientCertMissing" }, { TraceCode.StreamSecurityUpgradeAccepted, "StreamSecurityUpgradeAccepted" }, { TraceCode.TcpConnectError, "TcpConnectError" }, { TraceCode.FailedAcceptFromPool, "FailedAcceptFromPool" }, { TraceCode.FailedPipeConnect, "FailedPipeConnect" }, { TraceCode.SystemTimeResolution, "SystemTimeResolution" }, { TraceCode.PeerNeighborCloseFailed, "PeerNeighborCloseFailed" }, { TraceCode.PeerNeighborClosingFailed, "PeerNeighborClosingFailed" }, { TraceCode.PeerNeighborNotAccepted, "PeerNeighborNotAccepted" }, { TraceCode.PeerNeighborNotFound, "PeerNeighborNotFound" }, { TraceCode.PeerNeighborOpenFailed, "PeerNeighborOpenFailed" }, { TraceCode.PeerNeighborStateChanged, "PeerNeighborStateChanged" }, { TraceCode.PeerNeighborStateChangeFailed, "PeerNeighborStateChangeFailed" }, { TraceCode.PeerNeighborMessageReceived, "PeerNeighborMessageReceived" }, { TraceCode.PeerNeighborManagerOffline, "PeerNeighborManagerOffline" }, { TraceCode.PeerNeighborManagerOnline, "PeerNeighborManagerOnline" }, { TraceCode.PeerChannelMessageReceived, "PeerChannelMessageReceived" }, { TraceCode.PeerChannelMessageSent, "PeerChannelMessageSent" }, { TraceCode.PeerNodeAddressChanged, "PeerNodeAddressChanged" }, { TraceCode.PeerNodeOpening, "PeerNodeOpening" }, { TraceCode.PeerNodeOpened, "PeerNodeOpened" }, { TraceCode.PeerNodeOpenFailed, "PeerNodeOpenFailed" }, { TraceCode.PeerNodeClosing, "PeerNodeClosing" }, { TraceCode.PeerNodeClosed, "PeerNodeClosed" }, { TraceCode.PeerFloodedMessageReceived, "PeerFloodedMessageReceived" }, { TraceCode.PeerFloodedMessageNotPropagated, "PeerFloodedMessageNotPropagated" }, { TraceCode.PeerFloodedMessageNotMatched, "PeerFloodedMessageNotMatched" }, { TraceCode.PnrpRegisteredAddresses, "PnrpRegisteredAddresses" }, { TraceCode.PnrpUnregisteredAddresses, "PnrpUnregisteredAddresses" }, { TraceCode.PnrpResolvedAddresses, "PnrpResolvedAddresses" }, { TraceCode.PnrpResolveException, "PnrpResolveException" }, { TraceCode.PeerReceiveMessageAuthenticationFailure, "PeerReceiveMessageAuthenticationFailure" }, { TraceCode.PeerNodeAuthenticationFailure, "PeerNodeAuthenticationFailure" }, { TraceCode.PeerNodeAuthenticationTimeout, "PeerNodeAuthenticationTimeout" }, { TraceCode.PeerFlooderReceiveMessageQuotaExceeded, "PeerFlooderReceiveMessageQuotaExceeded" }, { TraceCode.PeerServiceOpened, "PeerServiceOpened" }, { TraceCode.PeerMaintainerActivity, "PeerMaintainerActivity" }, { TraceCode.MsmqCannotPeekOnQueue, "MsmqCannotPeekOnQueue" }, { TraceCode.MsmqCannotReadQueues, "MsmqCannotReadQueues" }, { TraceCode.MsmqDatagramSent, "MsmqDatagramSent" }, { TraceCode.MsmqDatagramReceived, "MsmqDatagramReceived" }, { TraceCode.MsmqDetected, "MsmqDetected" }, { TraceCode.MsmqEnteredBatch, "MsmqEnteredBatch" }, { TraceCode.MsmqExpectedException, "MsmqExpectedException" }, { TraceCode.MsmqFoundBaseAddress, "MsmqFoundBaseAddress" }, { TraceCode.MsmqLeftBatch, "MsmqLeftBatch" }, { TraceCode.MsmqMatchedApplicationFound, "MsmqMatchedApplicationFound" }, { TraceCode.MsmqMessageDropped, "MsmqMessageDropped" }, { TraceCode.MsmqMessageLockedUnderTheTransaction, "MsmqMessageLockedUnderTheTransaction" }, { TraceCode.MsmqMessageRejected, "MsmqMessageRejected" }, { TraceCode.MsmqMoveOrDeleteAttemptFailed, "MsmqMoveOrDeleteAttemptFailed" }, { TraceCode.MsmqPoisonMessageMovedPoison, "MsmqPoisonMessageMovedPoison" }, { TraceCode.MsmqPoisonMessageMovedRetry, "MsmqPoisonMessageMovedRetry" }, { TraceCode.MsmqPoisonMessageRejected, "MsmqPoisonMessageRejected" }, { TraceCode.MsmqPoolFull, "MsmqPoolFull" }, { TraceCode.MsmqPotentiallyPoisonMessageDetected, "MsmqPotentiallyPoisonMessageDetected" }, { TraceCode.MsmqQueueClosed, "MsmqQueueClosed" }, { TraceCode.MsmqQueueOpened, "MsmqQueueOpened" }, { TraceCode.MsmqQueueTransactionalStatusUnknown, "MsmqQueueTransactionalStatusUnknown" }, { TraceCode.MsmqScanStarted, "MsmqScanStarted" }, { TraceCode.MsmqSessiongramReceived, "MsmqSessiongramReceived" }, { TraceCode.MsmqSessiongramSent, "MsmqSessiongramSent" }, { TraceCode.MsmqStartingApplication, "MsmqStartingApplication" }, { TraceCode.MsmqStartingService, "MsmqStartingService" }, { TraceCode.MsmqUnexpectedAcknowledgment, "MsmqUnexpectedAcknowledgment" }, { TraceCode.WsrmNegativeElapsedTimeDetected, "WsrmNegativeElapsedTimeDetected" }, { TraceCode.TcpTransferError, "TcpTransferError" }, { TraceCode.TcpConnectionResetError, "TcpConnectionResetError" }, { TraceCode.TcpConnectionTimedOut, "TcpConnectionTimedOut" }, // ComIntegration trace codes (TraceCode.ComIntegration) { TraceCode.ComIntegrationServiceHostStartingService, "ComIntegrationServiceHostStartingService" }, { TraceCode.ComIntegrationServiceHostStartedService, "ComIntegrationServiceHostStartedService" }, { TraceCode.ComIntegrationServiceHostCreatedServiceContract, "ComIntegrationServiceHostCreatedServiceContract" }, { TraceCode.ComIntegrationServiceHostStartedServiceDetails, "ComIntegrationServiceHostStartedServiceDetails" }, { TraceCode.ComIntegrationServiceHostCreatedServiceEndpoint, "ComIntegrationServiceHostCreatedServiceEndpoint" }, { TraceCode.ComIntegrationServiceHostStoppingService, "ComIntegrationServiceHostStoppingService" }, { TraceCode.ComIntegrationServiceHostStoppedService, "ComIntegrationServiceHostStoppedService" }, { TraceCode.ComIntegrationDllHostInitializerStarting, "ComIntegrationDllHostInitializerStarting" }, { TraceCode.ComIntegrationDllHostInitializerAddingHost, "ComIntegrationDllHostInitializerAddingHost" }, { TraceCode.ComIntegrationDllHostInitializerStarted, "ComIntegrationDllHostInitializerStarted" }, { TraceCode.ComIntegrationDllHostInitializerStopping, "ComIntegrationDllHostInitializerStopping" }, { TraceCode.ComIntegrationDllHostInitializerStopped, "ComIntegrationDllHostInitializerStopped" }, { TraceCode.ComIntegrationTLBImportStarting, "ComIntegrationTLBImportStarting" }, { TraceCode.ComIntegrationTLBImportFromAssembly, "ComIntegrationTLBImportFromAssembly" }, { TraceCode.ComIntegrationTLBImportFromTypelib, "ComIntegrationTLBImportFromTypelib" }, { TraceCode.ComIntegrationTLBImportConverterEvent, "ComIntegrationTLBImportConverterEvent" }, { TraceCode.ComIntegrationTLBImportFinished, "ComIntegrationTLBImportFinished" }, { TraceCode.ComIntegrationInstanceCreationRequest, "ComIntegrationInstanceCreationRequest" }, { TraceCode.ComIntegrationInstanceCreationSuccess, "ComIntegrationInstanceCreationSuccess" }, { TraceCode.ComIntegrationInstanceReleased, "ComIntegrationInstanceReleased" }, { TraceCode.ComIntegrationEnteringActivity, "ComIntegrationEnteringActivity" }, { TraceCode.ComIntegrationExecutingCall, "ComIntegrationExecutingCall" }, { TraceCode.ComIntegrationLeftActivity, "ComIntegrationLeftActivity" }, { TraceCode.ComIntegrationInvokingMethod, "ComIntegrationInvokingMethod" }, { TraceCode.ComIntegrationInvokedMethod, "ComIntegrationInvokedMethod" }, { TraceCode.ComIntegrationInvokingMethodNewTransaction, "ComIntegrationInvokingMethodNewTransaction" }, { TraceCode.ComIntegrationInvokingMethodContextTransaction, "ComIntegrationInvokingMethodContextTransaction" }, { TraceCode.ComIntegrationServiceMonikerParsed, "ComIntegrationServiceMonikerParsed" }, { TraceCode.ComIntegrationWsdlChannelBuilderLoaded, "ComIntegrationWsdlChannelBuilderLoaded" }, { TraceCode.ComIntegrationTypedChannelBuilderLoaded, "ComIntegrationTypedChannelBuilderLoaded" }, { TraceCode.ComIntegrationChannelCreated, "ComIntegrationChannelCreated" }, { TraceCode.ComIntegrationDispatchMethod, "ComIntegrationDispatchMethod" }, { TraceCode.ComIntegrationTxProxyTxCommitted, "ComIntegrationTxProxyTxCommitted" }, { TraceCode.ComIntegrationTxProxyTxAbortedByContext, "ComIntegrationTxProxyTxAbortedByContext" }, { TraceCode.ComIntegrationTxProxyTxAbortedByTM, "ComIntegrationTxProxyTxAbortedByTM" }, { TraceCode.ComIntegrationMexMonikerMetadataExchangeComplete, "ComIntegrationMexMonikerMetadataExchangeComplete" }, { TraceCode.ComIntegrationMexChannelBuilderLoaded, "ComIntegrationMexChannelBuilderLoaded" }, // Security trace codes (TraceCode.Security) { TraceCode.Security, "Security" }, { TraceCode.SecurityIdentityVerificationSuccess, "SecurityIdentityVerificationSuccess" }, { TraceCode.SecurityIdentityVerificationFailure, "SecurityIdentityVerificationFailure" }, { TraceCode.SecurityIdentityDeterminationSuccess, "SecurityIdentityDeterminationSuccess" }, { TraceCode.SecurityIdentityDeterminationFailure, "SecurityIdentityDeterminationFailure" }, { TraceCode.SecurityIdentityHostNameNormalizationFailure, "SecurityIdentityHostNameNormalizationFailure" }, { TraceCode.SecurityImpersonationSuccess, "SecurityImpersonationSuccess" }, { TraceCode.SecurityImpersonationFailure, "SecurityImpersonationFailure" }, { TraceCode.SecurityNegotiationProcessingFailure, "SecurityNegotiationProcessingFailure" }, { TraceCode.IssuanceTokenProviderRemovedCachedToken, "IssuanceTokenProviderRemovedCachedToken" }, { TraceCode.IssuanceTokenProviderUsingCachedToken, "IssuanceTokenProviderUsingCachedToken" }, { TraceCode.IssuanceTokenProviderBeginSecurityNegotiation, "IssuanceTokenProviderBeginSecurityNegotiation" }, { TraceCode.IssuanceTokenProviderEndSecurityNegotiation, "IssuanceTokenProviderEndSecurityNegotiation" }, { TraceCode.IssuanceTokenProviderRedirectApplied, "IssuanceTokenProviderRedirectApplied" }, { TraceCode.IssuanceTokenProviderServiceTokenCacheFull, "IssuanceTokenProviderServiceTokenCacheFull" }, { TraceCode.NegotiationTokenProviderAttached, "NegotiationTokenProviderAttached" }, { TraceCode.SpnegoClientNegotiationCompleted, "SpnegoClientNegotiationCompleted" }, { TraceCode.SpnegoServiceNegotiationCompleted, "SpnegoServiceNegotiationCompleted" }, { TraceCode.SpnegoClientNegotiation, "SpnegoClientNegotiation" }, { TraceCode.SpnegoServiceNegotiation, "SpnegoServiceNegotiation" }, { TraceCode.NegotiationAuthenticatorAttached, "NegotiationAuthenticatorAttached" }, { TraceCode.ServiceSecurityNegotiationCompleted, "ServiceSecurityNegotiationCompleted" }, { TraceCode.SecurityContextTokenCacheFull, "SecurityContextTokenCacheFull" }, { TraceCode.ExportSecurityChannelBindingEntry, "ExportSecurityChannelBindingEntry" }, { TraceCode.ExportSecurityChannelBindingExit, "ExportSecurityChannelBindingExit" }, { TraceCode.ImportSecurityChannelBindingEntry, "ImportSecurityChannelBindingEntry" }, { TraceCode.ImportSecurityChannelBindingExit, "ImportSecurityChannelBindingExit" }, { TraceCode.SecurityTokenProviderOpened, "SecurityTokenProviderOpened" }, { TraceCode.SecurityTokenProviderClosed, "SecurityTokenProviderClosed" }, { TraceCode.SecurityTokenAuthenticatorOpened, "SecurityTokenAuthenticatorOpened" }, { TraceCode.SecurityTokenAuthenticatorClosed, "SecurityTokenAuthenticatorClosed" }, { TraceCode.SecurityBindingOutgoingMessageSecured, "SecurityBindingOutgoingMessageSecured" }, { TraceCode.SecurityBindingIncomingMessageVerified, "SecurityBindingIncomingMessageVerified" }, { TraceCode.SecurityBindingSecureOutgoingMessageFailure, "SecurityBindingSecureOutgoingMessageFailure" }, { TraceCode.SecurityBindingVerifyIncomingMessageFailure, "SecurityBindingVerifyIncomingMessageFailure" }, { TraceCode.SecuritySpnToSidMappingFailure, "SecuritySpnToSidMappingFailure" }, { TraceCode.SecuritySessionRedirectApplied, "SecuritySessionRedirectApplied" }, { TraceCode.SecurityClientSessionCloseSent, "SecurityClientSessionCloseSent" }, { TraceCode.SecurityClientSessionCloseResponseSent, "SecurityClientSessionCloseResponseSent" }, { TraceCode.SecurityClientSessionCloseMessageReceived, "SecurityClientSessionCloseMessageReceived" }, { TraceCode.SecuritySessionKeyRenewalFaultReceived, "SecuritySessionKeyRenewalFaultReceived" }, { TraceCode.SecuritySessionAbortedFaultReceived, "SecuritySessionAbortedFaultReceived" }, { TraceCode.SecuritySessionClosedResponseReceived, "SecuritySessionClosedResponseReceived" }, { TraceCode.SecurityClientSessionPreviousKeyDiscarded, "SecurityClientSessionPreviousKeyDiscarded" }, { TraceCode.SecurityClientSessionKeyRenewed, "SecurityClientSessionKeyRenewed" }, { TraceCode.SecurityPendingServerSessionAdded, "SecurityPendingServerSessionAdded" }, { TraceCode.SecurityPendingServerSessionClosed, "SecurityPendingServerSessionClosed" }, { TraceCode.SecurityPendingServerSessionActivated, "SecurityPendingServerSessionActivated" }, { TraceCode.SecurityActiveServerSessionRemoved, "SecurityActiveServerSessionRemoved" }, { TraceCode.SecurityNewServerSessionKeyIssued, "SecurityNewServerSessionKeyIssued" }, { TraceCode.SecurityInactiveSessionFaulted, "SecurityInactiveSessionFaulted" }, { TraceCode.SecurityServerSessionKeyUpdated, "SecurityServerSessionKeyUpdated" }, { TraceCode.SecurityServerSessionCloseReceived, "SecurityServerSessionCloseReceived" }, { TraceCode.SecurityServerSessionRenewalFaultSent, "SecurityServerSessionRenewalFaultSent" }, { TraceCode.SecurityServerSessionAbortedFaultSent, "SecurityServerSessionAbortedFaultSent" }, { TraceCode.SecuritySessionCloseResponseSent, "SecuritySessionCloseResponseSent" }, { TraceCode.SecuritySessionServerCloseSent, "SecuritySessionServerCloseSent" }, { TraceCode.SecurityServerSessionCloseResponseReceived, "SecurityServerSessionCloseResponseReceived" }, { TraceCode.SecuritySessionRenewFaultSendFailure, "SecuritySessionRenewFaultSendFailure" }, { TraceCode.SecuritySessionAbortedFaultSendFailure, "SecuritySessionAbortedFaultSendFailure" }, { TraceCode.SecuritySessionClosedResponseSendFailure, "SecuritySessionClosedResponseSendFailure" }, { TraceCode.SecuritySessionServerCloseSendFailure, "SecuritySessionServerCloseSendFailure" }, { TraceCode.SecuritySessionRequestorStartOperation, "SecuritySessionRequestorStartOperation" }, { TraceCode.SecuritySessionRequestorOperationSuccess, "SecuritySessionRequestorOperationSuccess" }, { TraceCode.SecuritySessionRequestorOperationFailure, "SecuritySessionRequestorOperationFailure" }, { TraceCode.SecuritySessionResponderOperationFailure, "SecuritySessionResponderOperationFailure" }, { TraceCode.SecuritySessionDemuxFailure, "SecuritySessionDemuxFailure" }, { TraceCode.SecurityAuditWrittenSuccess, "SecurityAuditWrittenSuccess" }, { TraceCode.SecurityAuditWrittenFailure, "SecurityAuditWrittenFailure" }, // ServiceModel trace codes (TraceCode.ServiceModel) { TraceCode.AsyncCallbackThrewException, "AsyncCallbackThrewException" }, { TraceCode.CommunicationObjectAborted, "CommunicationObjectAborted" }, { TraceCode.CommunicationObjectAbortFailed, "CommunicationObjectAbortFailed" }, { TraceCode.CommunicationObjectCloseFailed, "CommunicationObjectCloseFailed" }, { TraceCode.CommunicationObjectOpenFailed, "CommunicationObjectOpenFailed" }, { TraceCode.CommunicationObjectClosing, "CommunicationObjectClosing" }, { TraceCode.CommunicationObjectClosed, "CommunicationObjectClosed" }, { TraceCode.CommunicationObjectCreated, "CommunicationObjectCreated" }, { TraceCode.CommunicationObjectDisposing, "CommunicationObjectDisposing" }, { TraceCode.CommunicationObjectFaultReason, "CommunicationObjectFaultReason" }, { TraceCode.CommunicationObjectFaulted, "CommunicationObjectFaulted" }, { TraceCode.CommunicationObjectOpening, "CommunicationObjectOpening" }, { TraceCode.CommunicationObjectOpened, "CommunicationObjectOpened" }, { TraceCode.DidNotUnderstandMessageHeader, "DidNotUnderstandMessageHeader" }, { TraceCode.UnderstoodMessageHeader, "UnderstoodMessageHeader" }, { TraceCode.MessageClosed, "MessageClosed" }, { TraceCode.MessageClosedAgain, "MessageClosedAgain" }, { TraceCode.MessageCopied, "MessageCopied" }, { TraceCode.MessageRead, "MessageRead" }, { TraceCode.MessageWritten, "MessageWritten" }, { TraceCode.BeginExecuteMethod, "BeginExecuteMethod" }, { TraceCode.ConfigurationIsReadOnly, "ConfigurationIsReadOnly" }, { TraceCode.ConfiguredExtensionTypeNotFound, "ConfiguredExtensionTypeNotFound" }, { TraceCode.EvaluationContextNotFound, "EvaluationContextNotFound" }, { TraceCode.EndExecuteMethod, "EndExecuteMethod" }, { TraceCode.ExtensionCollectionDoesNotExist, "ExtensionCollectionDoesNotExist" }, { TraceCode.ExtensionCollectionNameNotFound, "ExtensionCollectionNameNotFound" }, { TraceCode.ExtensionCollectionIsEmpty, "ExtensionCollectionIsEmpty" }, { TraceCode.ExtensionElementAlreadyExistsInCollection, "ExtensionElementAlreadyExistsInCollection" }, { TraceCode.ElementTypeDoesntMatchConfiguredType, "ElementTypeDoesntMatchConfiguredType" }, { TraceCode.ErrorInvokingUserCode, "ErrorInvokingUserCode" }, { TraceCode.GetBehaviorElement, "GetBehaviorElement" }, { TraceCode.GetCommonBehaviors, "GetCommonBehaviors" }, { TraceCode.GetConfiguredBinding, "GetConfiguredBinding" }, { TraceCode.GetChannelEndpointElement, "GetChannelEndpointElement" }, { TraceCode.GetConfigurationSection, "GetConfigurationSection" }, { TraceCode.GetDefaultConfiguredBinding, "GetDefaultConfiguredBinding" }, { TraceCode.GetServiceElement, "GetServiceElement" }, { TraceCode.MessageProcessingPaused, "MessageProcessingPaused" }, { TraceCode.ManualFlowThrottleLimitReached, "ManualFlowThrottleLimitReached" }, { TraceCode.OverridingDuplicateConfigurationKey, "OverridingDuplicateConfigurationKey" }, { TraceCode.RemoveBehavior, "RemoveBehavior" }, { TraceCode.ServiceChannelLifetime, "ServiceChannelLifetime" }, { TraceCode.ServiceHostCreation, "ServiceHostCreation" }, { TraceCode.ServiceHostBaseAddresses, "ServiceHostBaseAddresses" }, { TraceCode.ServiceHostTimeoutOnClose, "ServiceHostTimeoutOnClose" }, { TraceCode.ServiceHostFaulted, "ServiceHostFaulted" }, { TraceCode.ServiceHostErrorOnReleasePerformanceCounter, "ServiceHostErrorOnReleasePerformanceCounter" }, { TraceCode.ServiceThrottleLimitReached, "ServiceThrottleLimitReached" }, { TraceCode.ServiceOperationMissingReply, "ServiceOperationMissingReply" }, { TraceCode.ServiceOperationMissingReplyContext, "ServiceOperationMissingReplyContext" }, { TraceCode.ServiceOperationExceptionOnReply, "ServiceOperationExceptionOnReply" }, { TraceCode.SkipBehavior, "SkipBehavior" }, { TraceCode.TransportListen, "TransportListen" }, { TraceCode.UnhandledAction, "UnhandledAction" }, { TraceCode.PerformanceCounterFailedToLoad, "PerformanceCounterFailedToLoad" }, { TraceCode.PerformanceCountersFailed, "PerformanceCountersFailed" }, { TraceCode.PerformanceCountersFailedDuringUpdate, "PerformanceCountersFailedDuringUpdate" }, { TraceCode.PerformanceCountersFailedForService, "PerformanceCountersFailedForService" }, { TraceCode.PerformanceCountersFailedOnRelease, "PerformanceCountersFailedOnRelease" }, { TraceCode.WsmexNonCriticalWsdlExportError, "WsmexNonCriticalWsdlExportError" }, { TraceCode.WsmexNonCriticalWsdlImportError, "WsmexNonCriticalWsdlImportError" }, { TraceCode.FailedToOpenIncomingChannel, "FailedToOpenIncomingChannel" }, { TraceCode.UnhandledExceptionInUserOperation, "UnhandledExceptionInUserOperation" }, { TraceCode.DroppedAMessage, "DroppedAMessage" }, { TraceCode.CannotBeImportedInCurrentFormat, "CannotBeImportedInCurrentFormat" }, { TraceCode.GetConfiguredEndpoint, "GetConfiguredEndpoint" }, { TraceCode.GetDefaultConfiguredEndpoint, "GetDefaultConfiguredEndpoint" }, { TraceCode.ExtensionTypeNotFound, "ExtensionTypeNotFound" }, { TraceCode.DefaultEndpointsAdded, "DefaultEndpointsAdded" }, //ServiceModel Metadata codes { TraceCode.MetadataExchangeClientSendRequest, "MetadataExchangeClientSendRequest" }, { TraceCode.MetadataExchangeClientReceiveReply, "MetadataExchangeClientReceiveReply" }, { TraceCode.WarnHelpPageEnabledNoBaseAddress, "WarnHelpPageEnabledNoBaseAddress" }, // PortSharingtrace codes (TraceCode.PortSharing) { TraceCode.PortSharingClosed, "PortSharingClosed" }, { TraceCode.PortSharingDuplicatedPipe, "PortSharingDuplicatedPipe" }, { TraceCode.PortSharingDupHandleGranted, "PortSharingDupHandleGranted" }, { TraceCode.PortSharingDuplicatedSocket, "PortSharingDuplicatedSocket" }, { TraceCode.PortSharingListening, "PortSharingListening" }, { TraceCode.SharedManagerServiceEndpointNotExist, "SharedManagerServiceEndpointNotExist" }, //Indigo Tx trace codes (TraceCode.ServiceModelTransaction) { TraceCode.TxSourceTxScopeRequiredIsTransactedTransport, "TxSourceTxScopeRequiredIsTransactedTransport" }, { TraceCode.TxSourceTxScopeRequiredIsTransactionFlow, "TxSourceTxScopeRequiredIsTransactionFlow" }, { TraceCode.TxSourceTxScopeRequiredIsAttachedTransaction, "TxSourceTxScopeRequiredIsAttachedTransaction" }, { TraceCode.TxSourceTxScopeRequiredIsCreateNewTransaction, "TxSourceTxScopeRequiredIsCreateNewTransaction" }, { TraceCode.TxCompletionStatusCompletedForAutocomplete, "TxCompletionStatusCompletedForAutocomplete" }, { TraceCode.TxCompletionStatusCompletedForError, "TxCompletionStatusCompletedForError" }, { TraceCode.TxCompletionStatusCompletedForSetComplete, "TxCompletionStatusCompletedForSetComplete" }, { TraceCode.TxCompletionStatusCompletedForTACOSC, "TxCompletionStatusCompletedForTACOSC" }, { TraceCode.TxCompletionStatusCompletedForAsyncAbort, "TxCompletionStatusCompletedForAsyncAbort" }, { TraceCode.TxCompletionStatusRemainsAttached, "TxCompletionStatusRemainsAttached" }, { TraceCode.TxCompletionStatusAbortedOnSessionClose, "TxCompletionStatusAbortedOnSessionClose" }, { TraceCode.TxReleaseServiceInstanceOnCompletion, "TxReleaseServiceInstanceOnCompletion" }, { TraceCode.TxAsyncAbort, "TxAsyncAbort" }, { TraceCode.TxFailedToNegotiateOleTx, "TxFailedToNegotiateOleTx" }, { TraceCode.TxSourceTxScopeRequiredUsingExistingTransaction, "TxSourceTxScopeRequiredUsingExistingTransaction" }, //CfxGreen trace codes (TraceCode.NetFx35) { TraceCode.ActivatingMessageReceived, "ActivatingMessageReceived" }, { TraceCode.InstanceContextBoundToDurableInstance, "InstanceContextBoundToDurableInstance" }, { TraceCode.InstanceContextDetachedFromDurableInstance, "InstanceContextDetachedFromDurableInstance" }, { TraceCode.ContextChannelFactoryChannelCreated, "ContextChannelFactoryChannelCreated" }, { TraceCode.ContextChannelListenerChannelAccepted, "ContextChannelListenerChannelAccepted" }, { TraceCode.ContextProtocolContextAddedToMessage, "ContextProtocolContextAddedToMessage" }, { TraceCode.ContextProtocolContextRetrievedFromMessage, "ContextProtocolContextRetrievedFromMessage" }, { TraceCode.DICPInstanceContextCached, "DICPInstanceContextCached" }, { TraceCode.DICPInstanceContextRemovedFromCache, "DICPInstanceContextRemovedFromCache" }, { TraceCode.ServiceDurableInstanceDeleted, "ServiceDurableInstanceDeleted" }, { TraceCode.ServiceDurableInstanceDisposed, "ServiceDurableInstanceDisposed" }, { TraceCode.ServiceDurableInstanceLoaded, "ServiceDurableInstanceLoaded" }, { TraceCode.ServiceDurableInstanceSaved, "ServiceDurableInstanceSaved" }, { TraceCode.SqlPersistenceProviderSQLCallStart, "SqlPersistenceProviderSQLCallStart" }, { TraceCode.SqlPersistenceProviderSQLCallEnd, "SqlPersistenceProviderSQLCallEnd" }, { TraceCode.SqlPersistenceProviderOpenParameters, "SqlPersistenceProviderOpenParameters" }, { TraceCode.SyncContextSchedulerServiceTimerCancelled, "SyncContextSchedulerServiceTimerCancelled" }, { TraceCode.SyncContextSchedulerServiceTimerCreated, "SyncContextSchedulerServiceTimerCreated" }, { TraceCode.WorkflowDurableInstanceLoaded, "WorkflowDurableInstanceLoaded" }, { TraceCode.WorkflowDurableInstanceAborted, "WorkflowDurableInstanceAborted" }, { TraceCode.WorkflowDurableInstanceActivated, "WorkflowDurableInstanceActivated" }, { TraceCode.WorkflowOperationInvokerItemQueued, "WorkflowOperationInvokerItemQueued" }, { TraceCode.WorkflowRequestContextReplySent, "WorkflowRequestContextReplySent" }, { TraceCode.WorkflowRequestContextFaultSent, "WorkflowRequestContextFaultSent" }, { TraceCode.WorkflowServiceHostCreated, "WorkflowServiceHostCreated" }, { TraceCode.SyndicationReadFeedBegin, "SyndicationReadFeedBegin" }, { TraceCode.SyndicationReadFeedEnd, "SyndicationReadFeedEnd" }, { TraceCode.SyndicationReadItemBegin, "SyndicationReadItemBegin" }, { TraceCode.SyndicationReadItemEnd, "SyndicationReadItemEnd" }, { TraceCode.SyndicationWriteFeedBegin, "SyndicationWriteFeedBegin" }, { TraceCode.SyndicationWriteFeedEnd, "SyndicationWriteFeedEnd" }, { TraceCode.SyndicationWriteItemBegin, "SyndicationWriteItemBegin" }, { TraceCode.SyndicationWriteItemEnd, "SyndicationWriteItemEnd" }, { TraceCode.SyndicationProtocolElementIgnoredOnRead, "SyndicationProtocolElementIgnoredOnRead" }, { TraceCode.SyndicationProtocolElementIgnoredOnWrite, "SyndicationProtocolElementIgnoredOnWrite" }, { TraceCode.SyndicationProtocolElementInvalid, "SyndicationProtocolElementInvalid" }, { TraceCode.WebUnknownQueryParameterIgnored, "WebUnknownQueryParameterIgnored" }, { TraceCode.WebRequestMatchesOperation, "WebRequestMatchesOperation" }, { TraceCode.WebRequestDoesNotMatchOperations, "WebRequestDoesNotMatchOperations" }, { TraceCode.WebRequestRedirect, "WebRequestRedirect" }, { TraceCode.SyndicationReadServiceDocumentBegin, "SyndicationReadServiceDocumentBegin" }, { TraceCode.SyndicationReadServiceDocumentEnd, "SyndicationReadServiceDocumentEnd" }, { TraceCode.SyndicationReadCategoriesDocumentBegin, "SyndicationReadCategoriesDocumentBegin" }, { TraceCode.SyndicationReadCategoriesDocumentEnd, "SyndicationReadCategoriesDocumentEnd" }, { TraceCode.SyndicationWriteServiceDocumentBegin, "SyndicationWriteServiceDocumentBegin" }, { TraceCode.SyndicationWriteServiceDocumentEnd, "SyndicationWriteServiceDocumentEnd" }, { TraceCode.SyndicationWriteCategoriesDocumentBegin, "SyndicationWriteCategoriesDocumentBegin" }, { TraceCode.SyndicationWriteCategoriesDocumentEnd, "SyndicationWriteCategoriesDocumentEnd" }, { TraceCode.AutomaticFormatSelectedOperationDefault, "AutomaticFormatSelectedOperationDefault" }, { TraceCode.AutomaticFormatSelectedRequestBased, "AutomaticFormatSelectedRequestBased" }, { TraceCode.RequestFormatSelectedFromContentTypeMapper, "RequestFormatSelectedFromContentTypeMapper" }, { TraceCode.RequestFormatSelectedByEncoderDefaults, "RequestFormatSelectedByEncoderDefaults" }, { TraceCode.AddingResponseToOutputCache, "AddingResponseToOutputCache" }, { TraceCode.AddingAuthenticatedResponseToOutputCache, "AddingAuthenticatedResponseToOutputCache" }, { TraceCode.JsonpCallbackNameSet, "JsonpCallbackNameSet" }, }; public const string E2EActivityId = "E2EActivityId"; public const string TraceApplicationReference = "TraceApplicationReference"; public static InputQueue<T> CreateInputQueue<T>() where T : class { if (asyncCallbackGenerator == null) { asyncCallbackGenerator = new Func<Action<AsyncCallback, IAsyncResult>>(CallbackGenerator); } return new InputQueue<T>(asyncCallbackGenerator) { DisposeItemCallback = value => { if (value is ICommunicationObject) { ((ICommunicationObject)value).Abort(); } } }; } static Action<AsyncCallback, IAsyncResult> CallbackGenerator() { if (DiagnosticUtility.ShouldUseActivity) { ServiceModelActivity callbackActivity = ServiceModelActivity.Current; if (callbackActivity != null) { return delegate(AsyncCallback callback, IAsyncResult result) { using (ServiceModelActivity.BoundOperation(callbackActivity)) { callback(result); } }; } } return null; } static internal void AddActivityHeader(Message message) { try { ActivityIdHeader activityIdHeader = new ActivityIdHeader(TraceUtility.ExtractActivityId(message)); activityIdHeader.AddTo(message); } #pragma warning suppress 56500 // covered by FxCOP catch (Exception e) { if (Fx.IsFatal(e)) { throw; } TraceUtility.TraceEvent(TraceEventType.Error, TraceCode.FailedToAddAnActivityIdHeader, SR.GetString(SR.TraceCodeFailedToAddAnActivityIdHeader), e, message); } } static internal void AddAmbientActivityToMessage(Message message) { try { ActivityIdHeader activityIdHeader = new ActivityIdHeader(DiagnosticTraceBase.ActivityId); activityIdHeader.AddTo(message); } #pragma warning suppress 56500 // covered by FxCOP catch (Exception e) { if (Fx.IsFatal(e)) { throw; } TraceUtility.TraceEvent(TraceEventType.Error, TraceCode.FailedToAddAnActivityIdHeader, SR.GetString(SR.TraceCodeFailedToAddAnActivityIdHeader), e, message); } } static internal void CopyActivity(Message source, Message destination) { if (DiagnosticUtility.ShouldUseActivity) { TraceUtility.SetActivity(destination, TraceUtility.ExtractActivity(source)); } } internal static long GetUtcBasedDurationForTrace(long startTicks) { if (startTicks > 0) { TimeSpan elapsedTime = new TimeSpan(DateTime.UtcNow.Ticks - startTicks); return (long)elapsedTime.TotalMilliseconds; } return 0; } internal static ServiceModelActivity ExtractActivity(Message message) { ServiceModelActivity retval = null; if ((DiagnosticUtility.ShouldUseActivity || TraceUtility.ShouldPropagateActivityGlobal) && (message != null) && (message.State != MessageState.Closed)) { object property; if (message.Properties.TryGetValue(TraceUtility.ActivityIdKey, out property)) { retval = property as ServiceModelActivity; } } return retval; } internal static Guid ExtractActivityId(Message message) { if (TraceUtility.MessageFlowTracingOnly) { return ActivityIdHeader.ExtractActivityId(message); } ServiceModelActivity activity = ExtractActivity(message); return activity == null ? Guid.Empty : activity.Id; } internal static Guid GetReceivedActivityId(OperationContext operationContext) { object activityIdFromProprties; if (!operationContext.IncomingMessageProperties.TryGetValue(E2EActivityId, out activityIdFromProprties)) { return TraceUtility.ExtractActivityId(operationContext.IncomingMessage); } else { return (Guid)activityIdFromProprties; } } internal static ServiceModelActivity ExtractAndRemoveActivity(Message message) { ServiceModelActivity retval = TraceUtility.ExtractActivity(message); if (retval != null) { // If the property is just removed, the item is disposed and we don't want the thing // to be disposed of. message.Properties[TraceUtility.ActivityIdKey] = false; } return retval; } internal static void ProcessIncomingMessage(Message message, EventTraceActivity eventTraceActivity) { ServiceModelActivity activity = ServiceModelActivity.Current; if (activity != null && DiagnosticUtility.ShouldUseActivity) { ServiceModelActivity incomingActivity = TraceUtility.ExtractActivity(message); if (null != incomingActivity && incomingActivity.Id != activity.Id) { using (ServiceModelActivity.BoundOperation(incomingActivity)) { if (null != FxTrace.Trace) { FxTrace.Trace.TraceTransfer(activity.Id); } } } TraceUtility.SetActivity(message, activity); } TraceUtility.MessageFlowAtMessageReceived(message, null, eventTraceActivity, true); if (MessageLogger.LogMessagesAtServiceLevel) { MessageLogger.LogMessage(ref message, MessageLoggingSource.ServiceLevelReceiveReply | MessageLoggingSource.LastChance); } } internal static void ProcessOutgoingMessage(Message message, EventTraceActivity eventTraceActivity) { ServiceModelActivity activity = ServiceModelActivity.Current; if (DiagnosticUtility.ShouldUseActivity) { TraceUtility.SetActivity(message, activity); } if (TraceUtility.PropagateUserActivity || TraceUtility.ShouldPropagateActivity) { TraceUtility.AddAmbientActivityToMessage(message); } TraceUtility.MessageFlowAtMessageSent(message, eventTraceActivity); if (MessageLogger.LogMessagesAtServiceLevel) { MessageLogger.LogMessage(ref message, MessageLoggingSource.ServiceLevelSendRequest | MessageLoggingSource.LastChance); } } internal static void SetActivity(Message message, ServiceModelActivity activity) { if (DiagnosticUtility.ShouldUseActivity && message != null && message.State != MessageState.Closed) { message.Properties[TraceUtility.ActivityIdKey] = activity; } } internal static void TraceDroppedMessage(Message message, EndpointDispatcher dispatcher) { if (DiagnosticUtility.ShouldTraceInformation) { EndpointAddress endpointAddress = null; if (dispatcher != null) { endpointAddress = dispatcher.EndpointAddress; } TraceUtility.TraceEvent(TraceEventType.Information, TraceCode.DroppedAMessage, SR.GetString(SR.TraceCodeDroppedAMessage), new MessageDroppedTraceRecord(message, endpointAddress)); } } internal static void TraceEvent(TraceEventType severity, int traceCode, string traceDescription) { TraceEvent(severity, traceCode, traceDescription, null, traceDescription, (Exception)null); } internal static void TraceEvent(TraceEventType severity, int traceCode, string traceDescription, TraceRecord extendedData) { TraceEvent(severity, traceCode, traceDescription, extendedData, null, (Exception)null); } internal static void TraceEvent(TraceEventType severity, int traceCode, string traceDescription, object source) { TraceEvent(severity, traceCode, traceDescription, null, source, (Exception)null); } internal static void TraceEvent(TraceEventType severity, int traceCode, string traceDescription, object source, Exception exception) { TraceEvent(severity, traceCode, traceDescription, null, source, exception); } internal static void TraceEvent(TraceEventType severity, int traceCode, string traceDescription, Message message) { if (message == null) { TraceEvent(severity, traceCode, traceDescription, null, (Exception)null); } else { TraceEvent(severity, traceCode, traceDescription, message, message); } } internal static void TraceEvent(TraceEventType severity, int traceCode, string traceDescription, object source, Message message) { Guid activityId = TraceUtility.ExtractActivityId(message); if (DiagnosticUtility.ShouldTrace(severity)) { DiagnosticUtility.DiagnosticTrace.TraceEvent(severity, traceCode, GenerateMsdnTraceCode(traceCode), traceDescription, new MessageTraceRecord(message), null, activityId, message); } } internal static void TraceEvent(TraceEventType severity, int traceCode, string traceDescription, Exception exception, Message message) { Guid activityId = TraceUtility.ExtractActivityId(message); if (DiagnosticUtility.ShouldTrace(severity)) { DiagnosticUtility.DiagnosticTrace.TraceEvent(severity, traceCode, GenerateMsdnTraceCode(traceCode), traceDescription, new MessageTraceRecord(message), exception, activityId, null); } } internal static void TraceEventNoCheck(TraceEventType severity, int traceCode, string traceDescription, TraceRecord extendedData, object source, Exception exception) { DiagnosticUtility.DiagnosticTrace.TraceEvent(severity, traceCode, GenerateMsdnTraceCode(traceCode), traceDescription, extendedData, exception, source); } // These methods require a TraceRecord to be allocated, so we want them to show up on profiles if the caller didn't avoid // allocating the TraceRecord by using ShouldTrace. [MethodImpl(MethodImplOptions.NoInlining)] internal static void TraceEvent(TraceEventType severity, int traceCode, string traceDescription, TraceRecord extendedData, object source, Exception exception) { if (DiagnosticUtility.ShouldTrace(severity)) { DiagnosticUtility.DiagnosticTrace.TraceEvent(severity, traceCode, GenerateMsdnTraceCode(traceCode), traceDescription, extendedData, exception, source); } } [MethodImpl(MethodImplOptions.NoInlining)] internal static void TraceEvent(TraceEventType severity, int traceCode, string traceDescription, TraceRecord extendedData, object source, Exception exception, Message message) { Guid activityId = TraceUtility.ExtractActivityId(message); if (DiagnosticUtility.ShouldTrace(severity)) { DiagnosticUtility.DiagnosticTrace.TraceEvent(severity, traceCode, GenerateMsdnTraceCode(traceCode), traceDescription, extendedData, exception, activityId, source); } } internal static void TraceEventNoCheck(TraceEventType severity, int traceCode, string traceDescription, TraceRecord extendedData, object source, Exception exception, Guid activityId) { DiagnosticUtility.DiagnosticTrace.TraceEvent(severity, traceCode, GenerateMsdnTraceCode(traceCode), traceDescription, extendedData, exception, activityId, source); } [MethodImpl(MethodImplOptions.NoInlining)] internal static void TraceEvent(TraceEventType severity, int traceCode, string traceDescription, TraceRecord extendedData, object source, Exception exception, Guid activityId) { if (DiagnosticUtility.ShouldTrace(severity)) { DiagnosticUtility.DiagnosticTrace.TraceEvent(severity, traceCode, GenerateMsdnTraceCode(traceCode), traceDescription, extendedData, exception, activityId, source); } } static string GenerateMsdnTraceCode(int traceCode) { int group = (int)(traceCode & 0xFFFF0000); string terminatorUri = null; switch (group) { case TraceCode.Administration: terminatorUri = "System.ServiceModel.Administration"; break; case TraceCode.Channels: terminatorUri = "System.ServiceModel.Channels"; break; case TraceCode.ComIntegration: terminatorUri = "System.ServiceModel.ComIntegration"; break; case TraceCode.Diagnostics: terminatorUri = "System.ServiceModel.Diagnostics"; break; case TraceCode.PortSharing: terminatorUri = "System.ServiceModel.PortSharing"; break; case TraceCode.Security: terminatorUri = "System.ServiceModel.Security"; break; case TraceCode.Serialization: terminatorUri = "System.Runtime.Serialization"; break; case TraceCode.ServiceModel: case TraceCode.ServiceModelTransaction: terminatorUri = "System.ServiceModel"; break; default: terminatorUri = string.Empty; break; } Fx.Assert(traceCodes.ContainsKey(traceCode), string.Format(CultureInfo.InvariantCulture, "Unsupported trace code: Please add trace code 0x{0} to the SortedList TraceUtility.traceCodes in {1}", traceCode.ToString("X", CultureInfo.InvariantCulture), typeof(TraceUtility))); return LegacyDiagnosticTrace.GenerateMsdnTraceCode(terminatorUri, traceCodes[traceCode]); } internal static Exception ThrowHelperError(Exception exception, Message message) { // If the message is closed, we won't get an activity Guid activityId = TraceUtility.ExtractActivityId(message); if (DiagnosticUtility.ShouldTraceError) { DiagnosticUtility.DiagnosticTrace.TraceEvent(TraceEventType.Error, TraceCode.ThrowingException, GenerateMsdnTraceCode(TraceCode.ThrowingException), TraceSR.GetString(TraceSR.ThrowingException), null, exception, activityId, null); } return exception; } internal static Exception ThrowHelperError(Exception exception, Guid activityId, object source) { if (DiagnosticUtility.ShouldTraceError) { DiagnosticUtility.DiagnosticTrace.TraceEvent(TraceEventType.Error, TraceCode.ThrowingException, GenerateMsdnTraceCode(TraceCode.ThrowingException), TraceSR.GetString(TraceSR.ThrowingException), null, exception, activityId, source); } return exception; } internal static Exception ThrowHelperWarning(Exception exception, Message message) { if (DiagnosticUtility.ShouldTraceWarning) { Guid activityId = TraceUtility.ExtractActivityId(message); DiagnosticUtility.DiagnosticTrace.TraceEvent(TraceEventType.Warning, TraceCode.ThrowingException, GenerateMsdnTraceCode(TraceCode.ThrowingException), TraceSR.GetString(TraceSR.ThrowingException), null, exception, activityId, null); } return exception; } internal static ArgumentException ThrowHelperArgument(string paramName, string message, Message msg) { return (ArgumentException)TraceUtility.ThrowHelperError(new ArgumentException(message, paramName), msg); } internal static ArgumentNullException ThrowHelperArgumentNull(string paramName, Message message) { return (ArgumentNullException)TraceUtility.ThrowHelperError(new ArgumentNullException(paramName), message); } internal static string CreateSourceString(object source) { return source.GetType().ToString() + "/" + source.GetHashCode().ToString(CultureInfo.CurrentCulture); } internal static void TraceHttpConnectionInformation(string localEndpoint, string remoteEndpoint, object source) { if (DiagnosticUtility.ShouldTraceInformation) { Dictionary<string, string> values = new Dictionary<string, string>(2) { { "LocalEndpoint", localEndpoint }, { "RemoteEndpoint", remoteEndpoint } }; TraceUtility.TraceEvent(TraceEventType.Information, TraceCode.ConnectToIPEndpoint, SR.GetString(SR.TraceCodeConnectToIPEndpoint), new DictionaryTraceRecord(values), source, null); } } internal static void TraceUserCodeException(Exception e, MethodInfo method) { if (DiagnosticUtility.ShouldTraceWarning) { StringTraceRecord record = new StringTraceRecord("Comment", SR.GetString(SR.SFxUserCodeThrewException, method.DeclaringType.FullName, method.Name)); DiagnosticUtility.DiagnosticTrace.TraceEvent(TraceEventType.Warning, TraceCode.UnhandledExceptionInUserOperation, GenerateMsdnTraceCode(TraceCode.UnhandledExceptionInUserOperation), SR.GetString(SR.TraceCodeUnhandledExceptionInUserOperation, method.DeclaringType.FullName, method.Name), record, e, null); } } static TraceUtility() { //Maintain the order of calls TraceUtility.SetEtwProviderId(); TraceUtility.SetEndToEndTracingFlags(); if (DiagnosticUtility.DiagnosticTrace != null) { DiagnosticTraceSource ts = (DiagnosticTraceSource)DiagnosticUtility.DiagnosticTrace.TraceSource; TraceUtility.shouldPropagateActivity = (ts.PropagateActivity || TraceUtility.shouldPropagateActivityGlobal); } } [Fx.Tag.SecurityNote(Critical = "Calls critical method DiagnosticSection.UnsafeGetSection.", Safe = "Doesn't leak config section instance, just reads and stores bool values.")] [SecuritySafeCritical] static void SetEndToEndTracingFlags() { EndToEndTracingElement element = DiagnosticSection.UnsafeGetSection().EndToEndTracing; TraceUtility.shouldPropagateActivityGlobal = element.PropagateActivity; // if Sys.Diag trace is not enabled then the value is true if shouldPropagateActivityGlobal is true TraceUtility.shouldPropagateActivity = TraceUtility.shouldPropagateActivityGlobal || TraceUtility.shouldPropagateActivity; //Activity tracing is enabled by either of the flags (Sys.Diag trace source or E2E config element) DiagnosticUtility.ShouldUseActivity = (DiagnosticUtility.ShouldUseActivity || element.ActivityTracing); TraceUtility.activityTracing = DiagnosticUtility.ShouldUseActivity; TraceUtility.messageFlowTracing = element.MessageFlowTracing || TraceUtility.activityTracing; TraceUtility.messageFlowTracingOnly = element.MessageFlowTracing && !element.ActivityTracing; //Set the flag if activity tracing is enabled through the E2E config element as well DiagnosticUtility.TracingEnabled = (DiagnosticUtility.TracingEnabled || TraceUtility.activityTracing); } static public long RetrieveMessageNumber() { return Interlocked.Increment(ref TraceUtility.messageNumber); } static public bool PropagateUserActivity { get { return TraceUtility.ShouldPropagateActivity && TraceUtility.PropagateUserActivityCore; } } // Most of the time, shouldPropagateActivity will be false. // This property will rarely be executed as a result. static bool PropagateUserActivityCore { [MethodImpl(MethodImplOptions.NoInlining)] get { return !(DiagnosticUtility.TracingEnabled) && DiagnosticTraceBase.ActivityId != Guid.Empty; } } static internal string GetCallerInfo(OperationContext context) { if (context != null && context.IncomingMessageProperties != null) { object endpointMessageProperty; if (context.IncomingMessageProperties.TryGetValue(RemoteEndpointMessageProperty.Name, out endpointMessageProperty)) { RemoteEndpointMessageProperty endpoint = endpointMessageProperty as RemoteEndpointMessageProperty; if (endpoint != null) { return string.Format(CultureInfo.InvariantCulture, "{0}:{1}", endpoint.Address, endpoint.Port); } } } return "null"; } [Fx.Tag.SecurityNote(Critical = "Calls critical method DiagnosticSection.UnsafeGetSection.", Safe = "Doesn't leak config section instance, just reads and stores string values for Guid")] [SecuritySafeCritical] static internal void SetEtwProviderId() { // Get section should not trace as the ETW provider id is not set yet DiagnosticSection diagnostics = DiagnosticSection.UnsafeGetSectionNoTrace(); Guid etwProviderId = Guid.Empty; //set the Id in PT if specified in the config file. If not, ETW tracing is off. if (PartialTrustHelpers.HasEtwPermissions() || diagnostics.IsEtwProviderIdFromConfigFile()) { etwProviderId = Fx.CreateGuid(diagnostics.EtwProviderId); } System.Runtime.Diagnostics.EtwDiagnosticTrace.DefaultEtwProviderId = etwProviderId; } static internal void SetActivityId(MessageProperties properties) { Guid activityId; if ((null != properties) && properties.TryGetValue(TraceUtility.E2EActivityId, out activityId)) { DiagnosticTraceBase.ActivityId = activityId; } } static internal bool ShouldPropagateActivity { get { return TraceUtility.shouldPropagateActivity; } } static internal bool ShouldPropagateActivityGlobal { get { return TraceUtility.shouldPropagateActivityGlobal; } } static internal bool ActivityTracing { get { return TraceUtility.activityTracing; } } static internal bool MessageFlowTracing { get { return TraceUtility.messageFlowTracing; } } static internal bool MessageFlowTracingOnly { get { return TraceUtility.messageFlowTracingOnly; } } static internal void MessageFlowAtMessageSent(Message message, EventTraceActivity eventTraceActivity) { if (TraceUtility.MessageFlowTracing) { Guid activityId; Guid correlationId; bool activityIdFound = ActivityIdHeader.ExtractActivityAndCorrelationId(message, out activityId, out correlationId); if (TraceUtility.MessageFlowTracingOnly) { if (activityIdFound && activityId != DiagnosticTraceBase.ActivityId) { DiagnosticTraceBase.ActivityId = activityId; } } if (TD.MessageSentToTransportIsEnabled()) { TD.MessageSentToTransport(eventTraceActivity, correlationId); } } } static internal void MessageFlowAtMessageReceived(Message message, OperationContext context, EventTraceActivity eventTraceActivity, bool createNewActivityId) { if (TraceUtility.MessageFlowTracing) { Guid activityId; Guid correlationId; bool activityIdFound = ActivityIdHeader.ExtractActivityAndCorrelationId(message, out activityId, out correlationId); if (TraceUtility.MessageFlowTracingOnly) { if (createNewActivityId) { if (!activityIdFound) { activityId = Guid.NewGuid(); activityIdFound = true; } //message flow tracing only - start fresh DiagnosticTraceBase.ActivityId = Guid.Empty; } if (activityIdFound) { FxTrace.Trace.SetAndTraceTransfer(activityId, !createNewActivityId); message.Properties[TraceUtility.E2EActivityId] = Trace.CorrelationManager.ActivityId; } } if (TD.MessageReceivedFromTransportIsEnabled()) { if (context == null) { context = OperationContext.Current; } TD.MessageReceivedFromTransport(eventTraceActivity, correlationId, TraceUtility.GetAnnotation(context)); } } } internal static string GetAnnotation(OperationContext context) { object hostReference; if (context != null && null != context.IncomingMessage && (MessageState.Closed != context.IncomingMessage.State)) { if (!context.IncomingMessageProperties.TryGetValue(TraceApplicationReference, out hostReference)) { hostReference = AspNetEnvironment.Current.GetAnnotationFromHost(context.Host); context.IncomingMessageProperties.Add(TraceApplicationReference, hostReference); } } else { hostReference = AspNetEnvironment.Current.GetAnnotationFromHost(null); } return (string)hostReference; } internal static void TransferFromTransport(Message message) { if (message != null && DiagnosticUtility.ShouldUseActivity) { Guid guid = Guid.Empty; // Only look if we are allowing user propagation if (TraceUtility.ShouldPropagateActivity) { guid = ActivityIdHeader.ExtractActivityId(message); } if (guid == Guid.Empty) { guid = Guid.NewGuid(); } ServiceModelActivity activity = null; bool emitStart = true; if (ServiceModelActivity.Current != null) { if ((ServiceModelActivity.Current.Id == guid) || (ServiceModelActivity.Current.ActivityType == ActivityType.ProcessAction)) { activity = ServiceModelActivity.Current; emitStart = false; } else if (ServiceModelActivity.Current.PreviousActivity != null && ServiceModelActivity.Current.PreviousActivity.Id == guid) { activity = ServiceModelActivity.Current.PreviousActivity; emitStart = false; } } if (activity == null) { activity = ServiceModelActivity.CreateActivity(guid); } if (DiagnosticUtility.ShouldUseActivity) { if (emitStart) { if (null != FxTrace.Trace) { FxTrace.Trace.TraceTransfer(guid); } ServiceModelActivity.Start(activity, SR.GetString(SR.ActivityProcessAction, message.Headers.Action), ActivityType.ProcessAction); } } message.Properties[TraceUtility.ActivityIdKey] = activity; } } static internal void UpdateAsyncOperationContextWithActivity(object activity) { if (OperationContext.Current != null && activity != null) { OperationContext.Current.OutgoingMessageProperties[TraceUtility.AsyncOperationActivityKey] = activity; } } static internal object ExtractAsyncOperationContextActivity() { object data = null; if (OperationContext.Current != null && OperationContext.Current.OutgoingMessageProperties.TryGetValue(TraceUtility.AsyncOperationActivityKey, out data)) { OperationContext.Current.OutgoingMessageProperties.Remove(TraceUtility.AsyncOperationActivityKey); } return data; } static internal void UpdateAsyncOperationContextWithStartTime(EventTraceActivity eventTraceActivity, long startTime) { if (OperationContext.Current != null) { OperationContext.Current.OutgoingMessageProperties[TraceUtility.AsyncOperationStartTimeKey] = new EventTraceActivityTimeProperty(eventTraceActivity, startTime); } } static internal void ExtractAsyncOperationStartTime(out EventTraceActivity eventTraceActivity, out long startTime) { EventTraceActivityTimeProperty data = null; eventTraceActivity = null; startTime = 0; if (OperationContext.Current != null && OperationContext.Current.OutgoingMessageProperties.TryGetValue<EventTraceActivityTimeProperty>(TraceUtility.AsyncOperationStartTimeKey, out data)) { OperationContext.Current.OutgoingMessageProperties.Remove(TraceUtility.AsyncOperationStartTimeKey); eventTraceActivity = data.EventTraceActivity; startTime = data.StartTime; } } internal class TracingAsyncCallbackState { object innerState; Guid activityId; internal TracingAsyncCallbackState(object innerState) { this.innerState = innerState; this.activityId = DiagnosticTraceBase.ActivityId; } internal object InnerState { get { return this.innerState; } } internal Guid ActivityId { get { return this.activityId; } } } internal static AsyncCallback WrapExecuteUserCodeAsyncCallback(AsyncCallback callback) { return (DiagnosticUtility.ShouldUseActivity && callback != null) ? (new ExecuteUserCodeAsync(callback)).Callback : callback; } sealed class ExecuteUserCodeAsync { AsyncCallback callback; public ExecuteUserCodeAsync(AsyncCallback callback) { this.callback = callback; } public AsyncCallback Callback { get { return Fx.ThunkCallback(new AsyncCallback(this.ExecuteUserCode)); } } void ExecuteUserCode(IAsyncResult result) { using (ServiceModelActivity activity = ServiceModelActivity.CreateBoundedActivity()) { ServiceModelActivity.Start(activity, SR.GetString(SR.ActivityCallback), ActivityType.ExecuteUserCode); this.callback(result); } } } class EventTraceActivityTimeProperty { long startTime; EventTraceActivity eventTraceActivity; public EventTraceActivityTimeProperty(EventTraceActivity eventTraceActivity, long startTime) { this.eventTraceActivity = eventTraceActivity; this.startTime = startTime; } internal long StartTime { get { return this.startTime; } } internal EventTraceActivity EventTraceActivity { get { return this.eventTraceActivity; } } } internal static string GetRemoteEndpointAddressPort(Net.IPEndPoint iPEndPoint) { //We really don't want any exceptions out of TraceUtility. if (iPEndPoint != null) { try { return iPEndPoint.Address.ToString() + ":" + iPEndPoint.Port; } catch (Exception exception) { if (Fx.IsFatal(exception)) { throw; } //ignore and continue with all non-fatal exceptions. } } return string.Empty; } internal static string GetRemoteEndpointAddressPort(RemoteEndpointMessageProperty remoteEndpointMessageProperty) { try { if (remoteEndpointMessageProperty != null) { return remoteEndpointMessageProperty.Address + ":" + remoteEndpointMessageProperty.Port; } } catch (Exception exception) { if (Fx.IsFatal(exception)) { throw; } //ignore and continue with all non-fatal exceptions. } return string.Empty; } } }
// Copyright Bastian Eicher // Licensed under the MIT License using System.Collections.ObjectModel; namespace NanoByte.Common.Collections; /// <summary> /// A collection that can easily be monitored for changes via events. /// </summary> /// <typeparam name="T">The type of elements in the collection.</typeparam> public class MonitoredCollection<T> : Collection<T> { #region Events /// <summary> /// Occurs whenever something in the collection changes. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")] [Description("Occurs whenever something in the collection changes.")] public event Action? Changed; /// <summary> /// Occurs when a new item has just been added to the collection. /// </summary> [Description("Occurs when a new item has just been added to the collection.")] [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "The normal event signature would have been unnecessarily verbose")] public event Action<T>? Added; /// <summary> /// Occurs when an item is just about to be removed from the collection. /// </summary> [Description("Occurs when an item is just about to be removed from the collection.")] [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "The normal event signature would have been unnecessarily verbose")] public event Action<T>? Removing; /// <summary> /// Occurs when an item has just been removed from the collection. /// </summary> [Description("Occurs when an item has just been removed from the collection.")] [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "The normal event signature would have been unnecessarily verbose")] public event Action<T>? Removed; private void OnChanged() { if (!_dontRaiseEvents) Changed?.Invoke(); } private void OnAdded(T item) { if (!_dontRaiseEvents) Added?.Invoke(item); } // Note: This event cannot be blocked! private void OnRemoving(T item) => Removing?.Invoke(item); private void OnRemoved(T item) { if (!_dontRaiseEvents) Removed?.Invoke(item); } #endregion #region Variables /// <summary>Do not raise the <see cref="Added"/> and <see cref="Removed"/> events while <c>true</c>. /// <see cref="Removing"/> cannot be blocked!</summary> private bool _dontRaiseEvents; #endregion #region Properties /// <summary> /// The maximum number of elements; 0 for no limit. /// </summary> public int MaxElements { get; } #endregion #region Constructor /// <summary> /// Creates a new monitored collection. /// </summary> public MonitoredCollection() {} /// <summary> /// Creates a new monitored collection with an upper limit to the number of elements. /// </summary> /// <param name="maxElements">The maximum number of elements; 0 for no limit.</param> public MonitoredCollection(int maxElements) { MaxElements = maxElements; } #endregion //--------------------// #region Hooks /// <inheritdoc/> protected override void InsertItem(int index, T item) { if (MaxElements != 0 && Count == MaxElements) throw new InvalidOperationException(Resources.MaxElementsExceeded); base.InsertItem(index, item); OnAdded(item); OnChanged(); } /// <inheritdoc/> protected override void SetItem(int index, T item) { var oldItem = Items[index]; OnRemoving(oldItem); base.SetItem(index, item); OnRemoved(oldItem); OnAdded(item); OnChanged(); } /// <inheritdoc/> protected override void RemoveItem(int index) { var oldItem = Items[index]; OnRemoving(oldItem); base.RemoveItem(index); OnRemoved(oldItem); } /// <inheritdoc/> protected override void ClearItems() { foreach (var item in this) OnRemoving(item); // Create backup of collection to be able to dispatch Removed events afterwards var oldItems = new List<T>(this); base.ClearItems(); // Raise the events afterwards en bloc foreach (var item in oldItems) OnRemoved(item); OnChanged(); } #endregion //--------------------// #region Mass access /// <summary> /// Adds all the items in <paramref name="collection"/> to the collection that weren't already there. /// </summary> /// <param name="collection">A collection of items to add to the collection.</param> /// <remarks> /// <para>All events are raised en bloc after the items have been added.</para> /// <para>After calling this method this collection will contain a superset of the items in <paramref name="collection"/>, but not necessarily in the same order.</para> /// </remarks> public void AddMany([InstantHandle] IEnumerable<T> collection) { #region Sanity checks if (collection == null) throw new ArgumentNullException(nameof(collection)); if (ReferenceEquals(collection, this)) throw new ArgumentException(Resources.CannotAddCollectionToSelf, nameof(collection)); #endregion // Create separate collection to be able to dispatch events afterwards var added = new LinkedList<T>(); // Add all items without raising the events yet _dontRaiseEvents = true; foreach (var item in collection.Where(item => !Contains(item))) { Add(item); added.AddLast(item); } _dontRaiseEvents = false; // Raise the events afterwards en bloc foreach (var item in added) OnAdded(item); OnChanged(); } /// <summary> /// Adds all the items in <paramref name="enumeration"/> to the collection that weren't already there and /// removes all items in the collection that are not in <paramref name="enumeration"/>. /// </summary> /// <param name="enumeration">An enumeration with items to add to the collection.</param> /// <remarks> /// <para>All events are raised en bloc after the items have been added.</para> /// <para>After calling this method this collection will contain the same items as <paramref name="enumeration"/>, but not necessarily in the same order.</para> /// </remarks> public void SetMany([InstantHandle] IEnumerable<T> enumeration) { #region Sanity checks if (enumeration == null) throw new ArgumentNullException(nameof(enumeration)); if (ReferenceEquals(enumeration, this)) throw new ArgumentException(Resources.CannotAddCollectionToSelf, nameof(enumeration)); #endregion // Create backup of collection to be able to remove while enumerating var copy = new List<T>(this); // Create separate collection to be able to dispatch events afterwards var removed = new LinkedList<T>(); // Remove superfluous items without raising the events yet _dontRaiseEvents = true; foreach (var item in copy.Where(item => !enumeration.Contains(item))) { Remove(item); removed.AddLast(item); } _dontRaiseEvents = false; // Raise the events afterwards en bloc foreach (var item in removed) Removed?.Invoke(item); // Add any new items (raising all events en bloc) AddMany(enumeration); } #endregion }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Xunit; namespace System.Tests { public static class MathTests { [Fact] public static void Cos() { Assert.Equal(0.54030230586814, Math.Cos(1.0), 10); Assert.Equal(1.0, Math.Cos(0.0)); Assert.Equal(0.54030230586814, Math.Cos(-1.0), 10); Assert.Equal(double.NaN, Math.Cos(double.NaN)); Assert.Equal(double.NaN, Math.Cos(double.PositiveInfinity)); Assert.Equal(double.NaN, Math.Cos(double.NegativeInfinity)); } [Fact] public static void Sin() { Assert.Equal(0.841470984807897, Math.Sin(1.0), 10); Assert.Equal(0.0, Math.Sin(0.0)); Assert.Equal(-0.841470984807897, Math.Sin(-1.0), 10); Assert.Equal(double.NaN, Math.Sin(double.NaN)); Assert.Equal(double.NaN, Math.Sin(double.PositiveInfinity)); Assert.Equal(double.NaN, Math.Sin(double.NegativeInfinity)); } [Fact] public static void Tan() { Assert.Equal(1.5574077246549, Math.Tan(1.0), 10); Assert.Equal(0.0, Math.Tan(0.0)); Assert.Equal(-1.5574077246549, Math.Tan(-1.0), 10); Assert.Equal(double.NaN, Math.Tan(double.NaN)); Assert.Equal(double.NaN, Math.Tan(double.PositiveInfinity)); Assert.Equal(double.NaN, Math.Tan(double.NegativeInfinity)); } [Fact] public static void Cosh() { Assert.Equal(1.54308063481524, Math.Cosh(1.0), 10); Assert.Equal(1.0, Math.Cosh(0.0)); Assert.Equal(1.54308063481524, Math.Cosh(-1.0), 10); Assert.Equal(double.NaN, Math.Cosh(double.NaN)); Assert.Equal(double.PositiveInfinity, Math.Cosh(double.PositiveInfinity)); Assert.Equal(double.PositiveInfinity, Math.Cosh(double.NegativeInfinity)); } [Fact] public static void Sinh() { Assert.Equal(1.1752011936438, Math.Sinh(1.0), 10); Assert.Equal(0.0, Math.Sinh(0.0)); Assert.Equal(-1.1752011936438, Math.Sinh(-1.0), 10); Assert.Equal(double.NaN, Math.Sinh(double.NaN)); Assert.Equal(double.PositiveInfinity, Math.Sinh(double.PositiveInfinity)); Assert.Equal(double.NegativeInfinity, Math.Sinh(double.NegativeInfinity)); } [Fact] public static void Tanh() { Assert.Equal(0.761594155955765, Math.Tanh(1.0), 10); Assert.Equal(0.0, Math.Tanh(0.0)); Assert.Equal(-0.761594155955765, Math.Tanh(-1.0), 10); Assert.Equal(double.NaN, Math.Tanh(double.NaN)); Assert.Equal(1.0, Math.Tanh(double.PositiveInfinity)); Assert.Equal(-1.0, Math.Tanh(double.NegativeInfinity)); } [Fact] public static void Acos() { Assert.Equal(0.0, Math.Acos(1.0)); Assert.Equal(1.5707963267949, Math.Acos(0.0), 10); Assert.Equal(3.14159265358979, Math.Acos(-1.0), 10); Assert.Equal(double.NaN, Math.Acos(double.NaN)); Assert.Equal(double.NaN, Math.Acos(double.PositiveInfinity)); Assert.Equal(double.NaN, Math.Acos(double.NegativeInfinity)); } [Fact] public static void Asin() { Assert.Equal(1.5707963267949, Math.Asin(1.0), 10); Assert.Equal(0.0, Math.Asin(0.0)); Assert.Equal(-1.5707963267949, Math.Asin(-1.0), 10); Assert.Equal(double.NaN, Math.Asin(double.NaN)); Assert.Equal(double.NaN, Math.Asin(double.PositiveInfinity)); Assert.Equal(double.NaN, Math.Asin(double.NegativeInfinity)); } [Fact] public static void Atan() { Assert.Equal(0.785398163397448, Math.Atan(1.0), 10); Assert.Equal(0.0, Math.Atan(0.0)); Assert.Equal(-0.785398163397448, Math.Atan(-1.0), 10); Assert.Equal(double.NaN, Math.Atan(double.NaN)); Assert.Equal(1.5707963267949, Math.Atan(double.PositiveInfinity), 4); Assert.Equal(-1.5707963267949, Math.Atan(double.NegativeInfinity), 4); } [Fact] public static void Atan2() { Assert.Equal(0.0, Math.Atan2(0.0, 0.0)); Assert.Equal(1.5707963267949, Math.Atan2(1.0, 0.0), 10); Assert.Equal(0.588002603547568, Math.Atan2(2.0, 3.0), 10); Assert.Equal(0.0, Math.Atan2(0.0, 3.0)); Assert.Equal(-0.588002603547568, Math.Atan2(-2.0, 3.0), 10); Assert.Equal(double.NaN, Math.Atan2(double.NaN, 1.0)); Assert.Equal(double.NaN, Math.Atan2(1.0, double.NaN)); Assert.Equal(1.5707963267949, Math.Atan2(double.PositiveInfinity, 1.0), 10); Assert.Equal(-1.5707963267949, Math.Atan2(double.NegativeInfinity, 1.0), 10); Assert.Equal(0.0, Math.Atan2(1.0, double.PositiveInfinity)); Assert.Equal(3.14159265358979, Math.Atan2(1.0, double.NegativeInfinity), 10); } [Fact] public static void Ceiling_Decimal() { Assert.Equal(2.0m, Math.Ceiling(1.1m)); Assert.Equal(2.0m, Math.Ceiling(1.9m)); Assert.Equal(-1.0m, Math.Ceiling(-1.1m)); } [Fact] public static void Ceiling_Double() { Assert.Equal(2.0, Math.Ceiling(1.1)); Assert.Equal(2.0, Math.Ceiling(1.9)); Assert.Equal(-1.0, Math.Ceiling(-1.1)); Assert.Equal(double.NaN, Math.Ceiling(double.NaN)); Assert.Equal(double.PositiveInfinity, Math.Ceiling(double.PositiveInfinity)); Assert.Equal(double.NegativeInfinity, Math.Ceiling(double.NegativeInfinity)); } [Fact] public static void Floor_Decimal() { Assert.Equal(1.0m, Math.Floor(1.1m)); Assert.Equal(1.0m, Math.Floor(1.9m)); Assert.Equal(-2.0m, Math.Floor(-1.1m)); } [Fact] public static void Floor_Double() { Assert.Equal(1.0, Math.Floor(1.1)); Assert.Equal(1.0, Math.Floor(1.9)); Assert.Equal(-2.0, Math.Floor(-1.1)); Assert.Equal(double.NaN, Math.Floor(double.NaN)); Assert.Equal(double.PositiveInfinity, Math.Floor(double.PositiveInfinity)); Assert.Equal(double.NegativeInfinity, Math.Floor(double.NegativeInfinity)); } [Fact] public static void Round_Decimal() { Assert.Equal(0.0m, Math.Round(0.0m)); Assert.Equal(1.0m, Math.Round(1.4m)); Assert.Equal(2.0m, Math.Round(1.5m)); Assert.Equal(2e16m, Math.Round(2e16m)); Assert.Equal(0.0m, Math.Round(-0.0m)); Assert.Equal(-1.0m, Math.Round(-1.4m)); Assert.Equal(-2.0m, Math.Round(-1.5m)); Assert.Equal(-2e16m, Math.Round(-2e16m)); } [Fact] public static void Round_Decimal_Digits() { Assert.Equal(3.422m, Math.Round(3.42156m, 3, MidpointRounding.AwayFromZero)); Assert.Equal(-3.422m, Math.Round(-3.42156m, 3, MidpointRounding.AwayFromZero)); Assert.Equal(Decimal.Zero, Math.Round(Decimal.Zero, 3, MidpointRounding.AwayFromZero)); } [Fact] public static void Round_Double() { Assert.Equal(0.0, Math.Round(0.0)); Assert.Equal(1.0, Math.Round(1.4)); Assert.Equal(2.0, Math.Round(1.5)); Assert.Equal(2e16, Math.Round(2e16)); Assert.Equal(0.0, Math.Round(-0.0)); Assert.Equal(-1.0, Math.Round(-1.4)); Assert.Equal(-2.0, Math.Round(-1.5)); Assert.Equal(-2e16, Math.Round(-2e16)); } [Fact] public static void Round_Double_Digits() { Assert.Equal(3.422, Math.Round(3.42156, 3, MidpointRounding.AwayFromZero), 10); Assert.Equal(-3.422, Math.Round(-3.42156, 3, MidpointRounding.AwayFromZero), 10); Assert.Equal(0.0, Math.Round(0.0, 3, MidpointRounding.AwayFromZero)); Assert.Equal(double.NaN, Math.Round(double.NaN, 3, MidpointRounding.AwayFromZero)); Assert.Equal(double.PositiveInfinity, Math.Round(double.PositiveInfinity, 3, MidpointRounding.AwayFromZero)); Assert.Equal(double.NegativeInfinity, Math.Round(double.NegativeInfinity, 3, MidpointRounding.AwayFromZero)); } [Fact] public static void Sqrt() { Assert.Equal(1.73205080756888, Math.Sqrt(3.0), 10); Assert.Equal(0.0, Math.Sqrt(0.0)); Assert.Equal(double.NaN, Math.Sqrt(-3.0)); Assert.Equal(double.NaN, Math.Sqrt(double.NaN)); Assert.Equal(double.PositiveInfinity, Math.Sqrt(double.PositiveInfinity)); Assert.Equal(double.NaN, Math.Sqrt(double.NegativeInfinity)); } [Fact] public static void Log() { Assert.Equal(1.09861228866811, Math.Log(3.0), 10); Assert.Equal(double.NegativeInfinity, Math.Log(0.0)); Assert.Equal(double.NaN, Math.Log(-3.0)); Assert.Equal(double.NaN, Math.Log(double.NaN)); Assert.Equal(double.PositiveInfinity, Math.Log(double.PositiveInfinity)); Assert.Equal(double.NaN, Math.Log(double.NegativeInfinity)); } [Fact] public static void LogWithBase() { Assert.Equal(1.0, Math.Log(3.0, 3.0)); Assert.Equal(2.40217350273, Math.Log(14, 3.0), 10); Assert.Equal(double.NegativeInfinity, Math.Log(0.0, 3.0)); Assert.Equal(double.NaN, Math.Log(-3.0, 3.0)); Assert.Equal(double.NaN, Math.Log(double.NaN, 3.0)); Assert.Equal(double.PositiveInfinity, Math.Log(double.PositiveInfinity, 3.0)); Assert.Equal(double.NaN, Math.Log(double.NegativeInfinity, 3.0)); } [Fact] public static void Log10() { Assert.Equal(0.477121254719662, Math.Log10(3.0), 10); Assert.Equal(double.NegativeInfinity, Math.Log10(0.0)); Assert.Equal(double.NaN, Math.Log10(-3.0)); Assert.Equal(double.NaN, Math.Log10(double.NaN)); Assert.Equal(double.PositiveInfinity, Math.Log10(double.PositiveInfinity)); Assert.Equal(double.NaN, Math.Log10(double.NegativeInfinity)); } [Fact] public static void Pow() { Assert.Equal(1.0, Math.Pow(0.0, 0.0)); Assert.Equal(1.0, Math.Pow(1.0, 0.0)); Assert.Equal(8.0, Math.Pow(2.0, 3.0)); Assert.Equal(0.0, Math.Pow(0.0, 3.0)); Assert.Equal(-8.0, Math.Pow(-2.0, 3.0)); Assert.Equal(double.NaN, Math.Pow(double.NaN, 1.0)); Assert.Equal(double.NaN, Math.Pow(1.0, double.NaN)); Assert.Equal(double.PositiveInfinity, Math.Pow(double.PositiveInfinity, 1.0)); Assert.Equal(double.NegativeInfinity, Math.Pow(double.NegativeInfinity, 1.0)); Assert.Equal(1.0, Math.Pow(1.0, double.PositiveInfinity)); Assert.Equal(1.0, Math.Pow(1.0, double.NegativeInfinity)); Assert.Equal(double.NaN, Math.Pow(-1.0, double.PositiveInfinity)); Assert.Equal(double.NaN, Math.Pow(-1.0, double.NegativeInfinity)); Assert.Equal(double.PositiveInfinity, Math.Pow(1.1, double.PositiveInfinity)); Assert.Equal(0.0, Math.Pow(1.1, double.NegativeInfinity)); } [Fact] public static void Abs_Decimal() { Assert.Equal(3.0m, Math.Abs(3.0m)); Assert.Equal(0.0m, Math.Abs(0.0m)); Assert.Equal(0.0m, Math.Abs(-0.0m)); Assert.Equal(3.0m, Math.Abs(-3.0m)); Assert.Equal(Decimal.MaxValue, Math.Abs(Decimal.MinValue)); } [Fact] public static void Abs_Double() { Assert.Equal(3.0, Math.Abs(3.0)); Assert.Equal(0.0, Math.Abs(0.0)); Assert.Equal(3.0, Math.Abs(-3.0)); Assert.Equal(double.NaN, Math.Abs(double.NaN)); Assert.Equal(double.PositiveInfinity, Math.Abs(double.PositiveInfinity)); Assert.Equal(double.PositiveInfinity, Math.Abs(double.NegativeInfinity)); } [Fact] public static void Abs_Short() { Assert.Equal((short)3, Math.Abs((short)3)); Assert.Equal((short)0, Math.Abs((short)0)); Assert.Equal((short)3, Math.Abs((short)(-3))); Assert.Throws<OverflowException>(() => Math.Abs(short.MinValue)); } [Fact] public static void Abs_Int() { Assert.Equal(3, Math.Abs(3)); Assert.Equal(0, Math.Abs(0)); Assert.Equal(3, Math.Abs(-3)); Assert.Throws<OverflowException>(() => Math.Abs(int.MinValue)); } [Fact] public static void Abs_Long() { Assert.Equal(3L, Math.Abs(3L)); Assert.Equal(0L, Math.Abs(0L)); Assert.Equal(3L, Math.Abs(-3L)); Assert.Throws<OverflowException>(() => Math.Abs(long.MinValue)); } [Fact] public static void Abs_SByte() { Assert.Equal((sbyte)3, Math.Abs((sbyte)3)); Assert.Equal((sbyte)0, Math.Abs((sbyte)0)); Assert.Equal((sbyte)3, Math.Abs((sbyte)(-3))); Assert.Throws<OverflowException>(() => Math.Abs(sbyte.MinValue)); } [Fact] public static void Abs_Float() { Assert.Equal(3.0, Math.Abs(3.0f)); Assert.Equal(0.0, Math.Abs(0.0f)); Assert.Equal(3.0, Math.Abs(-3.0f)); Assert.Equal(float.NaN, Math.Abs(float.NaN)); Assert.Equal(float.PositiveInfinity, Math.Abs(float.PositiveInfinity)); Assert.Equal(float.PositiveInfinity, Math.Abs(float.NegativeInfinity)); } [Fact] public static void Exp() { Assert.Equal(20.0855369231877, Math.Exp(3.0), 10); Assert.Equal(1.0, Math.Exp(0.0)); Assert.Equal(0.0497870683678639, Math.Exp(-3.0), 10); Assert.Equal(double.NaN, Math.Exp(double.NaN)); Assert.Equal(double.PositiveInfinity, Math.Exp(double.PositiveInfinity)); Assert.Equal(0.0, Math.Exp(double.NegativeInfinity)); } [Fact] public static void IEEERemainder() { Assert.Equal(-1.0, Math.IEEERemainder(3, 2)); Assert.Equal(0.0, Math.IEEERemainder(4, 2)); Assert.Equal(1.0, Math.IEEERemainder(10, 3)); Assert.Equal(-1.0, Math.IEEERemainder(11, 3)); Assert.Equal(-2.0, Math.IEEERemainder(28, 5)); Assert.Equal(1.8, Math.IEEERemainder(17.8, 4), 10); Assert.Equal(1.4, Math.IEEERemainder(17.8, 4.1), 10); Assert.Equal(0.0999999999999979, Math.IEEERemainder(-16.3, 4.1), 10); Assert.Equal(1.4, Math.IEEERemainder(17.8, -4.1), 10); Assert.Equal(-1.4, Math.IEEERemainder(-17.8, -4.1), 10); } [Fact] public static void Min_Byte() { Assert.Equal((byte)2, Math.Min((byte)3, (byte)2)); Assert.Equal(byte.MinValue, Math.Min(byte.MinValue, byte.MaxValue)); } [Fact] public static void Min_Decimal() { Assert.Equal(-2.0m, Math.Min(3.0m, -2.0m)); Assert.Equal(decimal.MinValue, Math.Min(decimal.MinValue, decimal.MaxValue)); } [Fact] public static void Min_Double() { Assert.Equal(-2.0, Math.Min(3.0, -2.0)); Assert.Equal(double.MinValue, Math.Min(double.MinValue, double.MaxValue)); Assert.Equal(double.NegativeInfinity, Math.Min(double.NegativeInfinity, double.PositiveInfinity)); Assert.Equal(double.NaN, Math.Min(double.NegativeInfinity, double.NaN)); Assert.Equal(double.NaN, Math.Min(double.NaN, double.NaN)); } [Fact] public static void Min_Short() { Assert.Equal((short)(-2), Math.Min((short)3, (short)(-2))); Assert.Equal(short.MinValue, Math.Min(short.MinValue, short.MaxValue)); } [Fact] public static void Min_Int() { Assert.Equal(-2, Math.Min(3, -2)); Assert.Equal(int.MinValue, Math.Min(int.MinValue, int.MaxValue)); } [Fact] public static void Min_Long() { Assert.Equal(-2L, Math.Min(3L, -2L)); Assert.Equal(long.MinValue, Math.Min(long.MinValue, long.MaxValue)); } [Fact] public static void Min_SByte() { Assert.Equal((sbyte)(-2), Math.Min((sbyte)3, (sbyte)(-2))); Assert.Equal(sbyte.MinValue, Math.Min(sbyte.MinValue, sbyte.MaxValue)); } [Fact] public static void Min_Float() { Assert.Equal(-2.0f, Math.Min(3.0f, -2.0f)); Assert.Equal(float.MinValue, Math.Min(float.MinValue, float.MaxValue)); Assert.Equal(float.NegativeInfinity, Math.Min(float.NegativeInfinity, float.PositiveInfinity)); Assert.Equal(float.NaN, Math.Min(float.NegativeInfinity, float.NaN)); Assert.Equal(float.NaN, Math.Min(float.NaN, float.NaN)); } [Fact] public static void Min_UShort() { Assert.Equal((ushort)2, Math.Min((ushort)3, (ushort)2)); Assert.Equal(ushort.MinValue, Math.Min(ushort.MinValue, ushort.MaxValue)); } [Fact] public static void Min_UInt() { Assert.Equal((uint)2, Math.Min((uint)3, (uint)2)); Assert.Equal(uint.MinValue, Math.Min(uint.MinValue, uint.MaxValue)); } [Fact] public static void Min_ULong() { Assert.Equal((ulong)2, Math.Min((ulong)3, (ulong)2)); Assert.Equal(ulong.MinValue, Math.Min(ulong.MinValue, ulong.MaxValue)); } [Fact] public static void Max_Byte() { Assert.Equal((byte)3, Math.Max((byte)2, (byte)3)); Assert.Equal(byte.MaxValue, Math.Max(byte.MinValue, byte.MaxValue)); } [Fact] public static void Max_Decimal() { Assert.Equal(3.0m, Math.Max(-2.0m, 3.0m)); Assert.Equal(decimal.MaxValue, Math.Max(decimal.MinValue, decimal.MaxValue)); } [Fact] public static void Max_Double() { Assert.Equal(3.0, Math.Max(3.0, -2.0)); Assert.Equal(double.MaxValue, Math.Max(double.MinValue, double.MaxValue)); Assert.Equal(double.PositiveInfinity, Math.Max(double.NegativeInfinity, double.PositiveInfinity)); Assert.Equal(double.NaN, Math.Max(double.PositiveInfinity, double.NaN)); Assert.Equal(double.NaN, Math.Max(double.NaN, double.NaN)); } [Fact] public static void Max_Short() { Assert.Equal((short)3, Math.Max((short)(-2), (short)3)); Assert.Equal(short.MaxValue, Math.Max(short.MinValue, short.MaxValue)); } [Fact] public static void Max_Int() { Assert.Equal(3, Math.Max(-2, 3)); Assert.Equal(int.MaxValue, Math.Max(int.MinValue, int.MaxValue)); } [Fact] public static void Max_Long() { Assert.Equal(3L, Math.Max(-2L, 3L)); Assert.Equal(long.MaxValue, Math.Max(long.MinValue, long.MaxValue)); } [Fact] public static void Max_SByte() { Assert.Equal((sbyte)3, Math.Max((sbyte)(-2), (sbyte)3)); Assert.Equal(sbyte.MaxValue, Math.Max(sbyte.MinValue, sbyte.MaxValue)); } [Fact] public static void Max_Float() { Assert.Equal(3.0f, Math.Max(3.0f, -2.0f)); Assert.Equal(float.MaxValue, Math.Max(float.MinValue, float.MaxValue)); Assert.Equal(float.PositiveInfinity, Math.Max(float.NegativeInfinity, float.PositiveInfinity)); Assert.Equal(float.NaN, Math.Max(float.PositiveInfinity, float.NaN)); Assert.Equal(float.NaN, Math.Max(float.NaN, float.NaN)); } [Fact] public static void Max_UShort() { Assert.Equal((ushort)3, Math.Max((ushort)2, (ushort)3)); Assert.Equal(ushort.MaxValue, Math.Max(ushort.MinValue, ushort.MaxValue)); } [Fact] public static void Max_UInt() { Assert.Equal((uint)3, Math.Max((uint)2, (uint)3)); Assert.Equal(uint.MaxValue, Math.Max(uint.MinValue, uint.MaxValue)); } [Fact] public static void Max_ULong() { Assert.Equal((ulong)3, Math.Max((ulong)2, (ulong)3)); Assert.Equal(ulong.MaxValue, Math.Max(ulong.MinValue, ulong.MaxValue)); } [Fact] public static void Sign_Decimal() { Assert.Equal(0, Math.Sign(0.0m)); Assert.Equal(0, Math.Sign(-0.0m)); Assert.Equal(-1, Math.Sign(-3.14m)); Assert.Equal(1, Math.Sign(3.14m)); } [Fact] public static void Sign_Double() { Assert.Equal(0, Math.Sign(0.0)); Assert.Equal(0, Math.Sign(-0.0)); Assert.Equal(-1, Math.Sign(-3.14)); Assert.Equal(1, Math.Sign(3.14)); Assert.Equal(-1, Math.Sign(double.NegativeInfinity)); Assert.Equal(1, Math.Sign(double.PositiveInfinity)); Assert.Throws<ArithmeticException>(() => Math.Sign(double.NaN)); } [Fact] public static void Sign_Short() { Assert.Equal(0, Math.Sign((short)0)); Assert.Equal(-1, Math.Sign((short)(-3))); Assert.Equal(1, Math.Sign((short)3)); } [Fact] public static void Sign_Int() { Assert.Equal(0, Math.Sign(0)); Assert.Equal(-1, Math.Sign(-3)); Assert.Equal(1, Math.Sign(3)); } [Fact] public static void Sign_Long() { Assert.Equal(0, Math.Sign(0)); Assert.Equal(-1, Math.Sign(-3)); Assert.Equal(1, Math.Sign(3)); } [Fact] public static void Sign_SByte() { Assert.Equal(0, Math.Sign((sbyte)0)); Assert.Equal(-1, Math.Sign((sbyte)(-3))); Assert.Equal(1, Math.Sign((sbyte)3)); } [Fact] public static void Sign_Float() { Assert.Equal(0, Math.Sign(0.0f)); Assert.Equal(0, Math.Sign(-0.0f)); Assert.Equal(-1, Math.Sign(-3.14f)); Assert.Equal(1, Math.Sign(3.14f)); Assert.Equal(-1, Math.Sign(float.NegativeInfinity)); Assert.Equal(1, Math.Sign(float.PositiveInfinity)); Assert.Throws<ArithmeticException>(() => Math.Sign(float.NaN)); } [Fact] public static void Truncate_Decimal() { Assert.Equal(0.0m, Math.Truncate(0.12345m)); Assert.Equal(3.0m, Math.Truncate(3.14159m)); Assert.Equal(-3.0m, Math.Truncate(-3.14159m)); } [Fact] public static void Truncate_Double() { Assert.Equal(0.0, Math.Truncate(0.12345)); Assert.Equal(3.0, Math.Truncate(3.14159)); Assert.Equal(-3.0, Math.Truncate(-3.14159)); } } }
using System; using System.Collections.Generic; using System.Linq; using Nop.Core; using Nop.Core.Domain.Orders; using Nop.Core.Domain.Payments; using Nop.Core.Plugins; using Nop.Services.Catalog; using Nop.Services.Configuration; namespace Nop.Services.Payments { /// <summary> /// Payment service /// </summary> public partial class PaymentService : IPaymentService { #region Fields private readonly PaymentSettings _paymentSettings; private readonly IPluginFinder _pluginFinder; private readonly ISettingService _settingService; private readonly ShoppingCartSettings _shoppingCartSettings; #endregion #region Ctor /// <summary> /// Ctor /// </summary> /// <param name="paymentSettings">Payment settings</param> /// <param name="pluginFinder">Plugin finder</param> /// <param name="settingService">Setting service</param> /// <param name="shoppingCartSettings">Shopping cart settings</param> public PaymentService(PaymentSettings paymentSettings, IPluginFinder pluginFinder, ISettingService settingService, ShoppingCartSettings shoppingCartSettings) { this._paymentSettings = paymentSettings; this._pluginFinder = pluginFinder; this._settingService = settingService; this._shoppingCartSettings = shoppingCartSettings; } #endregion #region Methods /// <summary> /// Load active payment methods /// </summary> /// <param name="filterByCustomerId">Filter payment methods by customer; null to load all records</param> /// <param name="storeId">Load records allowed only in a specified store; pass 0 to load all records</param> /// <param name="filterByCountryId">Load records allowed only in a specified country; pass 0 to load all records</param> /// <returns>Payment methods</returns> public virtual IList<IPaymentMethod> LoadActivePaymentMethods(int? filterByCustomerId = null, int storeId = 0, int filterByCountryId = 0) { return LoadAllPaymentMethods(storeId, filterByCountryId) .Where(provider => _paymentSettings.ActivePaymentMethodSystemNames.Contains(provider.PluginDescriptor.SystemName, StringComparer.InvariantCultureIgnoreCase)) .ToList(); } /// <summary> /// Load payment provider by system name /// </summary> /// <param name="systemName">System name</param> /// <returns>Found payment provider</returns> public virtual IPaymentMethod LoadPaymentMethodBySystemName(string systemName) { var descriptor = _pluginFinder.GetPluginDescriptorBySystemName<IPaymentMethod>(systemName); if (descriptor != null) return descriptor.Instance<IPaymentMethod>(); return null; } /// <summary> /// Load all payment providers /// </summary> /// <param name="storeId">Load records allowed only in a specified store; pass 0 to load all records</param> /// <param name="filterByCountryId">Load records allowed only in a specified country; pass 0 to load all records</param> /// <returns>Payment providers</returns> public virtual IList<IPaymentMethod> LoadAllPaymentMethods(int storeId = 0, int filterByCountryId = 0) { var paymentMethods = _pluginFinder.GetPlugins<IPaymentMethod>(storeId: storeId).ToList(); if (filterByCountryId == 0) return paymentMethods; //filter by country var paymentMetodsByCountry = new List<IPaymentMethod>(); foreach (var pm in paymentMethods) { var restictedCountryIds = GetRestictedCountryIds(pm); if (!restictedCountryIds.Contains(filterByCountryId)) { paymentMetodsByCountry.Add(pm); } } return paymentMetodsByCountry; } /// <summary> /// Gets a list of coutnry identifiers in which a certain payment method is now allowed /// </summary> /// <param name="paymentMethod">Payment method</param> /// <returns>A list of country identifiers</returns> public virtual IList<int> GetRestictedCountryIds(IPaymentMethod paymentMethod) { if (paymentMethod == null) throw new ArgumentNullException("paymentMethod"); var settingKey = string.Format("PaymentMethodRestictions.{0}", paymentMethod.PluginDescriptor.SystemName); var restictedCountryIds = _settingService.GetSettingByKey<List<int>>(settingKey); if (restictedCountryIds == null) restictedCountryIds = new List<int>(); return restictedCountryIds; } /// <summary> /// Saves a list of coutnry identifiers in which a certain payment method is now allowed /// </summary> /// <param name="paymentMethod">Payment method</param> /// <param name="countryIds">A list of country identifiers</param> public virtual void SaveRestictedCountryIds(IPaymentMethod paymentMethod, List<int> countryIds) { if (paymentMethod == null) throw new ArgumentNullException("paymentMethod"); //we should be sure that countryIds is of type List<int> (not IList<int>) var settingKey = string.Format("PaymentMethodRestictions.{0}", paymentMethod.PluginDescriptor.SystemName); _settingService.SetSetting(settingKey, countryIds); } /// <summary> /// Process a payment /// </summary> /// <param name="processPaymentRequest">Payment info required for an order processing</param> /// <returns>Process payment result</returns> public virtual ProcessPaymentResult ProcessPayment(ProcessPaymentRequest processPaymentRequest) { if (processPaymentRequest.OrderTotal == decimal.Zero) { var result = new ProcessPaymentResult { NewPaymentStatus = PaymentStatus.Paid }; return result; } //We should strip out any white space or dash in the CC number entered. if (!String.IsNullOrWhiteSpace(processPaymentRequest.CreditCardNumber)) { processPaymentRequest.CreditCardNumber = processPaymentRequest.CreditCardNumber.Replace(" ", ""); processPaymentRequest.CreditCardNumber = processPaymentRequest.CreditCardNumber.Replace("-", ""); } var paymentMethod = LoadPaymentMethodBySystemName(processPaymentRequest.PaymentMethodSystemName); if (paymentMethod == null) throw new NopException("Payment method couldn't be loaded"); return paymentMethod.ProcessPayment(processPaymentRequest); } /// <summary> /// Post process payment (used by payment gateways that require redirecting to a third-party URL) /// </summary> /// <param name="postProcessPaymentRequest">Payment info required for an order processing</param> public virtual void PostProcessPayment(PostProcessPaymentRequest postProcessPaymentRequest) { //already paid or order.OrderTotal == decimal.Zero if (postProcessPaymentRequest.Order.PaymentStatus == PaymentStatus.Paid) return; var paymentMethod = LoadPaymentMethodBySystemName(postProcessPaymentRequest.Order.PaymentMethodSystemName); if (paymentMethod == null) throw new NopException("Payment method couldn't be loaded"); paymentMethod.PostProcessPayment(postProcessPaymentRequest); } /// <summary> /// Gets a value indicating whether customers can complete a payment after order is placed but not completed (for redirection payment methods) /// </summary> /// <param name="order">Order</param> /// <returns>Result</returns> public virtual bool CanRePostProcessPayment(Order order) { if (order == null) throw new ArgumentNullException("order"); if (!_paymentSettings.AllowRePostingPayments) return false; var paymentMethod = LoadPaymentMethodBySystemName(order.PaymentMethodSystemName); if (paymentMethod == null) return false; //Payment method couldn't be loaded (for example, was uninstalled) if (paymentMethod.PaymentMethodType != PaymentMethodType.Redirection) return false; //this option is available only for redirection payment methods if (order.Deleted) return false; //do not allow for deleted orders if (order.OrderStatus == OrderStatus.Cancelled) return false; //do not allow for cancelled orders if (order.PaymentStatus != PaymentStatus.Pending) return false; //payment status should be Pending return paymentMethod.CanRePostProcessPayment(order); } /// <summary> /// Gets an additional handling fee of a payment method /// </summary> /// <param name="cart">Shoping cart</param> /// <param name="paymentMethodSystemName">Payment method system name</param> /// <returns>Additional handling fee</returns> public virtual decimal GetAdditionalHandlingFee(IList<ShoppingCartItem> cart, string paymentMethodSystemName) { if (String.IsNullOrEmpty(paymentMethodSystemName)) return decimal.Zero; var paymentMethod = LoadPaymentMethodBySystemName(paymentMethodSystemName); if (paymentMethod == null) return decimal.Zero; decimal result = paymentMethod.GetAdditionalHandlingFee(cart); if (result < decimal.Zero) result = decimal.Zero; if (_shoppingCartSettings.RoundPricesDuringCalculation) { result = RoundingHelper.RoundPrice(result); } return result; } /// <summary> /// Gets a value indicating whether capture is supported by payment method /// </summary> /// <param name="paymentMethodSystemName">Payment method system name</param> /// <returns>A value indicating whether capture is supported</returns> public virtual bool SupportCapture(string paymentMethodSystemName) { var paymentMethod = LoadPaymentMethodBySystemName(paymentMethodSystemName); if (paymentMethod == null) return false; return paymentMethod.SupportCapture; } /// <summary> /// Captures payment /// </summary> /// <param name="capturePaymentRequest">Capture payment request</param> /// <returns>Capture payment result</returns> public virtual CapturePaymentResult Capture(CapturePaymentRequest capturePaymentRequest) { var paymentMethod = LoadPaymentMethodBySystemName(capturePaymentRequest.Order.PaymentMethodSystemName); if (paymentMethod == null) throw new NopException("Payment method couldn't be loaded"); return paymentMethod.Capture(capturePaymentRequest); } /// <summary> /// Gets a value indicating whether partial refund is supported by payment method /// </summary> /// <param name="paymentMethodSystemName">Payment method system name</param> /// <returns>A value indicating whether partial refund is supported</returns> public virtual bool SupportPartiallyRefund(string paymentMethodSystemName) { var paymentMethod = LoadPaymentMethodBySystemName(paymentMethodSystemName); if (paymentMethod == null) return false; return paymentMethod.SupportPartiallyRefund; } /// <summary> /// Gets a value indicating whether refund is supported by payment method /// </summary> /// <param name="paymentMethodSystemName">Payment method system name</param> /// <returns>A value indicating whether refund is supported</returns> public virtual bool SupportRefund(string paymentMethodSystemName) { var paymentMethod = LoadPaymentMethodBySystemName(paymentMethodSystemName); if (paymentMethod == null) return false; return paymentMethod.SupportRefund; } /// <summary> /// Refunds a payment /// </summary> /// <param name="refundPaymentRequest">Request</param> /// <returns>Result</returns> public virtual RefundPaymentResult Refund(RefundPaymentRequest refundPaymentRequest) { var paymentMethod = LoadPaymentMethodBySystemName(refundPaymentRequest.Order.PaymentMethodSystemName); if (paymentMethod == null) throw new NopException("Payment method couldn't be loaded"); return paymentMethod.Refund(refundPaymentRequest); } /// <summary> /// Gets a value indicating whether void is supported by payment method /// </summary> /// <param name="paymentMethodSystemName">Payment method system name</param> /// <returns>A value indicating whether void is supported</returns> public virtual bool SupportVoid(string paymentMethodSystemName) { var paymentMethod = LoadPaymentMethodBySystemName(paymentMethodSystemName); if (paymentMethod == null) return false; return paymentMethod.SupportVoid; } /// <summary> /// Voids a payment /// </summary> /// <param name="voidPaymentRequest">Request</param> /// <returns>Result</returns> public virtual VoidPaymentResult Void(VoidPaymentRequest voidPaymentRequest) { var paymentMethod = LoadPaymentMethodBySystemName(voidPaymentRequest.Order.PaymentMethodSystemName); if (paymentMethod == null) throw new NopException("Payment method couldn't be loaded"); return paymentMethod.Void(voidPaymentRequest); } /// <summary> /// Gets a recurring payment type of payment method /// </summary> /// <param name="paymentMethodSystemName">Payment method system name</param> /// <returns>A recurring payment type of payment method</returns> public virtual RecurringPaymentType GetRecurringPaymentType(string paymentMethodSystemName) { var paymentMethod = LoadPaymentMethodBySystemName(paymentMethodSystemName); if (paymentMethod == null) return RecurringPaymentType.NotSupported; return paymentMethod.RecurringPaymentType; } /// <summary> /// Process recurring payment /// </summary> /// <param name="processPaymentRequest">Payment info required for an order processing</param> /// <returns>Process payment result</returns> public virtual ProcessPaymentResult ProcessRecurringPayment(ProcessPaymentRequest processPaymentRequest) { if (processPaymentRequest.OrderTotal == decimal.Zero) { var result = new ProcessPaymentResult { NewPaymentStatus = PaymentStatus.Paid }; return result; } var paymentMethod = LoadPaymentMethodBySystemName(processPaymentRequest.PaymentMethodSystemName); if (paymentMethod == null) throw new NopException("Payment method couldn't be loaded"); return paymentMethod.ProcessRecurringPayment(processPaymentRequest); } /// <summary> /// Cancels a recurring payment /// </summary> /// <param name="cancelPaymentRequest">Request</param> /// <returns>Result</returns> public virtual CancelRecurringPaymentResult CancelRecurringPayment(CancelRecurringPaymentRequest cancelPaymentRequest) { if (cancelPaymentRequest.Order.OrderTotal == decimal.Zero) return new CancelRecurringPaymentResult(); var paymentMethod = LoadPaymentMethodBySystemName(cancelPaymentRequest.Order.PaymentMethodSystemName); if (paymentMethod == null) throw new NopException("Payment method couldn't be loaded"); return paymentMethod.CancelRecurringPayment(cancelPaymentRequest); } /// <summary> /// Gets a payment method type /// </summary> /// <param name="paymentMethodSystemName">Payment method system name</param> /// <returns>A payment method type</returns> public virtual PaymentMethodType GetPaymentMethodType(string paymentMethodSystemName) { var paymentMethod = LoadPaymentMethodBySystemName(paymentMethodSystemName); if (paymentMethod == null) return PaymentMethodType.Unknown; return paymentMethod.PaymentMethodType; } /// <summary> /// Gets masked credit card number /// </summary> /// <param name="creditCardNumber">Credit card number</param> /// <returns>Masked credit card number</returns> public virtual string GetMaskedCreditCardNumber(string creditCardNumber) { if (String.IsNullOrEmpty(creditCardNumber)) return string.Empty; if (creditCardNumber.Length <= 4) return creditCardNumber; string last4 = creditCardNumber.Substring(creditCardNumber.Length - 4, 4); string maskedChars = string.Empty; for (int i = 0; i < creditCardNumber.Length - 4; i++) { maskedChars += "*"; } return maskedChars + last4; } #endregion } }
using System; using System.IO; using System.Linq; using GitVersion.Extensions; using GitVersion.Logging; using LibGit2Sharp; using Microsoft.Extensions.Options; namespace GitVersion { public class GitPreparer : IGitPreparer { private readonly ILog log; private readonly IEnvironment environment; private readonly IOptions<GitVersionOptions> options; private readonly ICurrentBuildAgent buildAgent; private const string DefaultRemoteName = "origin"; public GitPreparer(ILog log, IEnvironment environment, ICurrentBuildAgent buildAgent, IOptions<GitVersionOptions> options) { this.log = log ?? throw new ArgumentNullException(nameof(log)); this.environment = environment ?? throw new ArgumentNullException(nameof(environment)); this.options = options ?? throw new ArgumentNullException(nameof(options)); this.buildAgent = buildAgent; } public void Prepare() { var gitVersionOptions = options.Value; // Normalize if we are running on build server var normalizeGitDirectory = !gitVersionOptions.Settings.NoNormalize && buildAgent != null; var shouldCleanUpRemotes = buildAgent != null && buildAgent.ShouldCleanUpRemotes(); var currentBranch = ResolveCurrentBranch(); var dotGitDirectory = gitVersionOptions.DotGitDirectory; var projectRoot = gitVersionOptions.ProjectRootDirectory; log.Info($"Project root is: {projectRoot}"); log.Info($"DotGit directory is: {dotGitDirectory}"); if (string.IsNullOrEmpty(dotGitDirectory) || string.IsNullOrEmpty(projectRoot)) { throw new Exception($"Failed to prepare or find the .git directory in path '{gitVersionOptions.WorkingDirectory}'."); } PrepareInternal(normalizeGitDirectory, currentBranch, shouldCleanUpRemotes); } private void PrepareInternal(bool normalizeGitDirectory, string currentBranch, bool shouldCleanUpRemotes = false) { var gitVersionOptions = options.Value; if (!string.IsNullOrWhiteSpace(gitVersionOptions.RepositoryInfo.TargetUrl)) { CreateDynamicRepository(currentBranch); } else { if (normalizeGitDirectory) { if (shouldCleanUpRemotes) { CleanupDuplicateOrigin(); } NormalizeGitDirectory(currentBranch, gitVersionOptions.DotGitDirectory, false); } } } private string ResolveCurrentBranch() { var gitVersionOptions = options.Value; var targetBranch = gitVersionOptions.RepositoryInfo.TargetBranch; if (buildAgent == null) { return targetBranch; } var isDynamicRepository = !string.IsNullOrWhiteSpace(gitVersionOptions.RepositoryInfo.DynamicRepositoryClonePath); var currentBranch = buildAgent.GetCurrentBranch(isDynamicRepository) ?? targetBranch; log.Info("Branch from build environment: " + currentBranch); return currentBranch; } private void CleanupDuplicateOrigin() { var remoteToKeep = DefaultRemoteName; using var repo = new Repository(options.Value.GitRootPath); // check that we have a remote that matches defaultRemoteName if not take the first remote if (!repo.Network.Remotes.Any(remote => remote.Name.Equals(DefaultRemoteName, StringComparison.InvariantCultureIgnoreCase))) { remoteToKeep = repo.Network.Remotes.First().Name; } var duplicateRepos = repo.Network .Remotes .Where(remote => !remote.Name.Equals(remoteToKeep, StringComparison.InvariantCultureIgnoreCase)) .Select(remote => remote.Name); // remove all remotes that are considered duplicates foreach (var repoName in duplicateRepos) { repo.Network.Remotes.Remove(repoName); } } private void CreateDynamicRepository(string targetBranch) { var gitVersionOptions = options.Value; if (string.IsNullOrWhiteSpace(targetBranch)) { throw new Exception("Dynamic Git repositories must have a target branch (/b)"); } var repositoryInfo = gitVersionOptions.RepositoryInfo; var gitDirectory = gitVersionOptions.DynamicGitRepositoryPath; using (log.IndentLog($"Creating dynamic repository at '{gitDirectory}'")) { var authentication = gitVersionOptions.Authentication; if (!Directory.Exists(gitDirectory)) { CloneRepository(repositoryInfo.TargetUrl, gitDirectory, authentication); } else { log.Info("Git repository already exists"); } NormalizeGitDirectory(targetBranch, gitDirectory, true); } } private void NormalizeGitDirectory(string targetBranch, string gitDirectory, bool isDynamicRepository) { using (log.IndentLog($"Normalizing git directory for branch '{targetBranch}'")) { // Normalize (download branches) before using the branch NormalizeGitDirectory(gitDirectory, options.Value.Settings.NoFetch, targetBranch, isDynamicRepository); } } private void CloneRepository(string repositoryUrl, string gitDirectory, AuthenticationInfo auth) { Credentials credentials = null; if (auth != null) { if (!string.IsNullOrWhiteSpace(auth.Username)) { log.Info($"Setting up credentials using name '{auth.Username}'"); credentials = new UsernamePasswordCredentials { Username = auth.Username, Password = auth.Password ?? string.Empty }; } } try { using (log.IndentLog($"Cloning repository from url '{repositoryUrl}'")) { var cloneOptions = new CloneOptions { Checkout = false, CredentialsProvider = (url, usernameFromUrl, types) => credentials }; var returnedPath = Repository.Clone(repositoryUrl, gitDirectory, cloneOptions); log.Info($"Returned path after repository clone: {returnedPath}"); } } catch (LibGit2SharpException ex) { var message = ex.Message; if (message.Contains("401")) { throw new Exception("Unauthorized: Incorrect username/password"); } if (message.Contains("403")) { throw new Exception("Forbidden: Possibly Incorrect username/password"); } if (message.Contains("404")) { throw new Exception("Not found: The repository was not found"); } throw new Exception("There was an unknown problem with the Git repository you provided", ex); } } /// <summary> /// Normalization of a git directory turns all remote branches into local branches, turns pull request refs into a real branch and a few other things. This is designed to be run *only on the build server* which checks out repositories in different ways. /// It is not recommended to run normalization against a local repository /// </summary> private void NormalizeGitDirectory(string gitDirectory, bool noFetch, string currentBranch, bool isDynamicRepository) { var authentication = options.Value.Authentication; using var repository = new GitRepository(() => gitDirectory); // Need to ensure the HEAD does not move, this is essentially a BugCheck var expectedSha = repository.Head.Tip.Sha; var expectedBranchName = repository.Head.CanonicalName; try { var remote = repository.EnsureOnlyOneRemoteIsDefined(log); repository.AddMissingRefSpecs(log, remote); //If noFetch is enabled, then GitVersion will assume that the git repository is normalized before execution, so that fetching from remotes is not required. if (noFetch) { log.Info("Skipping fetching, if GitVersion does not calculate your version as expected you might need to allow fetching or use dynamic repositories"); } else { log.Info($"Fetching from remote '{remote.Name}' using the following refspecs: {string.Join(", ", remote.FetchRefSpecs.Select(r => r.Specification))}."); repository.Commands.Fetch(remote.Name, new string[0], authentication.ToFetchOptions(), null); } repository.EnsureLocalBranchExistsForCurrentBranch(log, remote, currentBranch); repository.CreateOrUpdateLocalBranchesFromRemoteTrackingOnes(log, remote.Name); // Bug fix for https://github.com/GitTools/GitVersion/issues/1754, head maybe have been changed // if this is a dynamic repository. But only allow this in case the branches are different (branch switch) if (expectedSha != repository.Head.Tip.Sha && (isDynamicRepository || !expectedBranchName.IsBranch(currentBranch))) { var newExpectedSha = repository.Head.Tip.Sha; var newExpectedBranchName = repository.Head.CanonicalName; log.Info($"Head has moved from '{expectedBranchName} | {expectedSha}' => '{newExpectedBranchName} | {newExpectedSha}', allowed since this is a dynamic repository"); expectedSha = newExpectedSha; } var headSha = repository.Refs.Head.TargetIdentifier; if (!repository.Info.IsHeadDetached) { log.Info($"HEAD points at branch '{headSha}'."); return; } log.Info($"HEAD is detached and points at commit '{headSha}'."); log.Info($"Local Refs:{System.Environment.NewLine}" + string.Join(System.Environment.NewLine, repository.Refs.FromGlob("*").Select(r => $"{r.CanonicalName} ({r.TargetIdentifier})"))); // In order to decide whether a fake branch is required or not, first check to see if any local branches have the same commit SHA of the head SHA. // If they do, go ahead and checkout that branch // If no, go ahead and check out a new branch, using the known commit SHA as the pointer var localBranchesWhereCommitShaIsHead = repository.Branches.Where(b => !b.IsRemote && b.Tip.Sha == headSha).ToList(); var matchingCurrentBranch = !string.IsNullOrEmpty(currentBranch) ? localBranchesWhereCommitShaIsHead.SingleOrDefault(b => b.CanonicalName.Replace("/heads/", "/") == currentBranch.Replace("/heads/", "/")) : null; if (matchingCurrentBranch != null) { log.Info($"Checking out local branch '{currentBranch}'."); repository.Commands.Checkout(matchingCurrentBranch); } else if (localBranchesWhereCommitShaIsHead.Count > 1) { var branchNames = localBranchesWhereCommitShaIsHead.Select(r => r.CanonicalName); var csvNames = string.Join(", ", branchNames); const string moveBranchMsg = "Move one of the branches along a commit to remove warning"; log.Warning($"Found more than one local branch pointing at the commit '{headSha}' ({csvNames})."); var master = localBranchesWhereCommitShaIsHead.SingleOrDefault(n => n.FriendlyName.IsEquivalentTo("master")); if (master != null) { log.Warning("Because one of the branches is 'master', will build master." + moveBranchMsg); repository.Commands.Checkout(master); } else { var branchesWithoutSeparators = localBranchesWhereCommitShaIsHead.Where(b => !b.FriendlyName.Contains('/') && !b.FriendlyName.Contains('-')).ToList(); if (branchesWithoutSeparators.Count == 1) { var branchWithoutSeparator = branchesWithoutSeparators[0]; log.Warning($"Choosing {branchWithoutSeparator.CanonicalName} as it is the only branch without / or - in it. " + moveBranchMsg); repository.Commands.Checkout(branchWithoutSeparator); } else { throw new WarningException("Failed to try and guess branch to use. " + moveBranchMsg); } } } else if (localBranchesWhereCommitShaIsHead.Count == 0) { log.Info($"No local branch pointing at the commit '{headSha}'. Fake branch needs to be created."); repository.CreateFakeBranchPointingAtThePullRequestTip(log, authentication); } else { log.Info($"Checking out local branch 'refs/heads/{localBranchesWhereCommitShaIsHead[0].FriendlyName}'."); repository.Commands.Checkout(repository.Branches[localBranchesWhereCommitShaIsHead[0].FriendlyName]); } } finally { if (repository.Head.Tip.Sha != expectedSha) { if (environment.GetEnvironmentVariable("IGNORE_NORMALISATION_GIT_HEAD_MOVE") != "1") { // Whoa, HEAD has moved, it shouldn't have. We need to blow up because there is a bug in normalisation throw new BugException($@"GitVersion has a bug, your HEAD has moved after repo normalisation. To disable this error set an environmental variable called IGNORE_NORMALISATION_GIT_HEAD_MOVE to 1 Please run `git {LibGitExtensions.CreateGitLogArgs(100)}` and submit it along with your build log (with personal info removed) in a new issue at https://github.com/GitTools/GitVersion"); } } } } } }
using System; using System.Collections.Generic; using System.Threading.Tasks; using Avalonia.Layout; using Avalonia.Platform; using Avalonia.Rendering; using Avalonia.UnitTests; using Moq; using Xunit; namespace Avalonia.Controls.UnitTests { public class WindowTests { [Fact] public void Setting_Title_Should_Set_Impl_Title() { var windowImpl = new Mock<IWindowImpl>(); var windowingPlatform = new MockWindowingPlatform(() => windowImpl.Object); using (UnitTestApplication.Start(new TestServices(windowingPlatform: windowingPlatform))) { var target = new Window(); target.Title = "Hello World"; windowImpl.Verify(x => x.SetTitle("Hello World")); } } [Fact] public void IsVisible_Should_Initially_Be_False() { using (UnitTestApplication.Start(TestServices.MockWindowingPlatform)) { var window = new Window(); Assert.False(window.IsVisible); } } [Fact] public void IsVisible_Should_Be_True_After_Show() { using (UnitTestApplication.Start(TestServices.StyledWindow)) { var window = new Window(); window.Show(); Assert.True(window.IsVisible); } } [Fact] public void IsVisible_Should_Be_True_After_ShowDialog() { using (UnitTestApplication.Start(TestServices.StyledWindow)) { var parent = new Window(); parent.Show(); var window = new Window(); var task = window.ShowDialog(parent); Assert.True(window.IsVisible); } } [Fact] public void IsVisible_Should_Be_False_After_Hide() { using (UnitTestApplication.Start(TestServices.StyledWindow)) { var window = new Window(); window.Show(); window.Hide(); Assert.False(window.IsVisible); } } [Fact] public void IsVisible_Should_Be_False_After_Close() { using (UnitTestApplication.Start(TestServices.StyledWindow)) { var window = new Window(); window.Show(); window.Close(); Assert.False(window.IsVisible); } } [Fact] public void IsVisible_Should_Be_False_After_Impl_Signals_Close() { var windowImpl = new Mock<IWindowImpl>(); windowImpl.SetupProperty(x => x.Closed); windowImpl.Setup(x => x.DesktopScaling).Returns(1); windowImpl.Setup(x => x.RenderScaling).Returns(1); var services = TestServices.StyledWindow.With( windowingPlatform: new MockWindowingPlatform(() => windowImpl.Object)); using (UnitTestApplication.Start(services)) { var window = new Window(); window.Show(); windowImpl.Object.Closed(); Assert.False(window.IsVisible); } } [Fact] public void Closing_Should_Only_Be_Invoked_Once() { using (UnitTestApplication.Start(TestServices.StyledWindow)) { var window = new Window(); var count = 0; window.Closing += (sender, e) => { count++; }; window.Show(); window.Close(); Assert.Equal(1, count); } } [Fact] public void Showing_Should_Start_Renderer() { using (UnitTestApplication.Start(TestServices.StyledWindow)) { var renderer = new Mock<IRenderer>(); var target = new Window(CreateImpl(renderer)); target.Show(); renderer.Verify(x => x.Start(), Times.Once); } } [Fact] public void ShowDialog_Should_Start_Renderer() { using (UnitTestApplication.Start(TestServices.StyledWindow)) { var parent = Mock.Of<Window>(); var renderer = new Mock<IRenderer>(); var target = new Window(CreateImpl(renderer)); target.ShowDialog<object>(parent); renderer.Verify(x => x.Start(), Times.Once); } } [Fact] public void ShowDialog_Should_Raise_Opened() { using (UnitTestApplication.Start(TestServices.StyledWindow)) { var parent = Mock.Of<Window>(); var target = new Window(); var raised = false; target.Opened += (s, e) => raised = true; target.ShowDialog<object>(parent); Assert.True(raised); } } [Fact] public void Hiding_Should_Stop_Renderer() { using (UnitTestApplication.Start(TestServices.StyledWindow)) { var renderer = new Mock<IRenderer>(); var target = new Window(CreateImpl(renderer)); target.Show(); target.Hide(); renderer.Verify(x => x.Stop(), Times.Once); } } [Fact] public async Task ShowDialog_With_ValueType_Returns_Default_When_Closed() { using (UnitTestApplication.Start(TestServices.StyledWindow)) { var parent = new Mock<Window>(); var windowImpl = new Mock<IWindowImpl>(); windowImpl.SetupProperty(x => x.Closed); windowImpl.Setup(x => x.DesktopScaling).Returns(1); windowImpl.Setup(x => x.RenderScaling).Returns(1); var target = new Window(windowImpl.Object); var task = target.ShowDialog<bool>(parent.Object); windowImpl.Object.Closed(); var result = await task; Assert.False(result); } } [Fact] public void Calling_Show_On_Closed_Window_Should_Throw() { using (UnitTestApplication.Start(TestServices.StyledWindow)) { var target = new Window(); target.Show(); target.Close(); var openedRaised = false; target.Opened += (s, e) => openedRaised = true; var ex = Assert.Throws<InvalidOperationException>(() => target.Show()); Assert.Equal("Cannot re-show a closed window.", ex.Message); Assert.False(openedRaised); } } [Fact] public async Task Calling_ShowDialog_On_Closed_Window_Should_Throw() { using (UnitTestApplication.Start(TestServices.StyledWindow)) { var parent = new Mock<Window>(); var windowImpl = new Mock<IWindowImpl>(); windowImpl.SetupProperty(x => x.Closed); windowImpl.Setup(x => x.DesktopScaling).Returns(1); windowImpl.Setup(x => x.RenderScaling).Returns(1); var target = new Window(windowImpl.Object); var task = target.ShowDialog<bool>(parent.Object); windowImpl.Object.Closed(); await task; var openedRaised = false; target.Opened += (s, e) => openedRaised = true; var ex = await Assert.ThrowsAsync<InvalidOperationException>(() => target.ShowDialog<bool>(parent.Object)); Assert.Equal("Cannot re-show a closed window.", ex.Message); Assert.False(openedRaised); } } [Fact] public void Window_Should_Be_Centered_When_WindowStartupLocation_Is_CenterScreen() { var screen1 = new Mock<Screen>(1.0, new PixelRect(new PixelSize(1920, 1080)), new PixelRect(new PixelSize(1920, 1040)), true); var screen2 = new Mock<Screen>(1.0, new PixelRect(new PixelSize(1366, 768)), new PixelRect(new PixelSize(1366, 728)), false); var screens = new Mock<IScreenImpl>(); screens.Setup(x => x.AllScreens).Returns(new Screen[] { screen1.Object, screen2.Object }); var windowImpl = MockWindowingPlatform.CreateWindowMock(); windowImpl.Setup(x => x.ClientSize).Returns(new Size(800, 480)); windowImpl.Setup(x => x.DesktopScaling).Returns(1); windowImpl.Setup(x => x.RenderScaling).Returns(1); windowImpl.Setup(x => x.Screen).Returns(screens.Object); using (UnitTestApplication.Start(TestServices.StyledWindow)) { var window = new Window(windowImpl.Object); window.WindowStartupLocation = WindowStartupLocation.CenterScreen; window.Position = new PixelPoint(60, 40); window.Show(); var expectedPosition = new PixelPoint( (int)(screen1.Object.WorkingArea.Size.Width / 2 - window.ClientSize.Width / 2), (int)(screen1.Object.WorkingArea.Size.Height / 2 - window.ClientSize.Height / 2)); Assert.Equal(window.Position, expectedPosition); } } [Fact] public void Window_Should_Be_Centered_Relative_To_Owner_When_WindowStartupLocation_Is_CenterOwner() { var parentWindowImpl = MockWindowingPlatform.CreateWindowMock(); parentWindowImpl.Setup(x => x.ClientSize).Returns(new Size(800, 480)); parentWindowImpl.Setup(x => x.MaxAutoSizeHint).Returns(new Size(1920, 1080)); parentWindowImpl.Setup(x => x.DesktopScaling).Returns(1); parentWindowImpl.Setup(x => x.RenderScaling).Returns(1); var windowImpl = MockWindowingPlatform.CreateWindowMock(); windowImpl.Setup(x => x.ClientSize).Returns(new Size(320, 200)); windowImpl.Setup(x => x.MaxAutoSizeHint).Returns(new Size(1920, 1080)); windowImpl.Setup(x => x.DesktopScaling).Returns(1); windowImpl.Setup(x => x.RenderScaling).Returns(1); var parentWindowServices = TestServices.StyledWindow.With( windowingPlatform: new MockWindowingPlatform(() => parentWindowImpl.Object)); var windowServices = TestServices.StyledWindow.With( windowingPlatform: new MockWindowingPlatform(() => windowImpl.Object)); using (UnitTestApplication.Start(parentWindowServices)) { var parentWindow = new Window(); parentWindow.Position = new PixelPoint(60, 40); parentWindow.Show(); using (UnitTestApplication.Start(windowServices)) { var window = new Window(); window.WindowStartupLocation = WindowStartupLocation.CenterOwner; window.Position = new PixelPoint(60, 40); window.ShowDialog(parentWindow); var expectedPosition = new PixelPoint( (int)(parentWindow.Position.X + parentWindow.ClientSize.Width / 2 - window.ClientSize.Width / 2), (int)(parentWindow.Position.Y + parentWindow.ClientSize.Height / 2 - window.ClientSize.Height / 2)); Assert.Equal(window.Position, expectedPosition); } } } public class SizingTests { [Fact] public void Child_Should_Be_Measured_With_Width_And_Height_If_SizeToContent_Is_Manual() { using (UnitTestApplication.Start(TestServices.StyledWindow)) { var child = new ChildControl(); var target = new Window { Width = 100, Height = 50, SizeToContent = SizeToContent.Manual, Content = child }; Show(target); Assert.Equal(1, child.MeasureSizes.Count); Assert.Equal(new Size(100, 50), child.MeasureSizes[0]); } } [Fact] public void Child_Should_Be_Measured_With_ClientSize_If_SizeToContent_Is_Manual_And_No_Width_Height_Specified() { using (UnitTestApplication.Start(TestServices.StyledWindow)) { var windowImpl = MockWindowingPlatform.CreateWindowMock(); windowImpl.Setup(x => x.ClientSize).Returns(new Size(550, 450)); var child = new ChildControl(); var target = new Window(windowImpl.Object) { SizeToContent = SizeToContent.Manual, Content = child }; Show(target); Assert.Equal(1, child.MeasureSizes.Count); Assert.Equal(new Size(550, 450), child.MeasureSizes[0]); } } [Fact] public void Child_Should_Be_Measured_With_MaxAutoSizeHint_If_SizeToContent_Is_WidthAndHeight() { using (UnitTestApplication.Start(TestServices.StyledWindow)) { var windowImpl = MockWindowingPlatform.CreateWindowMock(); windowImpl.Setup(x => x.MaxAutoSizeHint).Returns(new Size(1200, 1000)); var child = new ChildControl(); var target = new Window(windowImpl.Object) { Width = 100, Height = 50, SizeToContent = SizeToContent.WidthAndHeight, Content = child }; target.Show(); Assert.Equal(1, child.MeasureSizes.Count); Assert.Equal(new Size(1200, 1000), child.MeasureSizes[0]); } } [Fact] public void Should_Not_Have_Offset_On_Bounds_When_Content_Larger_Than_Max_Window_Size() { // Issue #3784. using (UnitTestApplication.Start(TestServices.StyledWindow)) { var windowImpl = MockWindowingPlatform.CreateWindowMock(); var clientSize = new Size(200, 200); var maxClientSize = new Size(480, 480); windowImpl.Setup(x => x.Resize(It.IsAny<Size>())).Callback<Size>(size => { clientSize = size.Constrain(maxClientSize); windowImpl.Object.Resized?.Invoke(clientSize); }); windowImpl.Setup(x => x.ClientSize).Returns(() => clientSize); var child = new Canvas { Width = 400, Height = 800, }; var target = new Window(windowImpl.Object) { SizeToContent = SizeToContent.WidthAndHeight, Content = child }; Show(target); Assert.Equal(new Size(400, 480), target.Bounds.Size); // Issue #3784 causes this to be (0, 160) which makes no sense as Window has no // parent control to be offset against. Assert.Equal(new Point(0, 0), target.Bounds.Position); } } [Fact] public void Width_Height_Should_Not_Be_NaN_After_Show_With_SizeToContent_WidthAndHeight() { using (UnitTestApplication.Start(TestServices.StyledWindow)) { var child = new Canvas { Width = 400, Height = 800, }; var target = new Window() { SizeToContent = SizeToContent.WidthAndHeight, Content = child }; Show(target); Assert.Equal(400, target.Width); Assert.Equal(800, target.Height); } } [Fact] public void SizeToContent_Should_Not_Be_Lost_On_Show() { using (UnitTestApplication.Start(TestServices.StyledWindow)) { var child = new Canvas { Width = 400, Height = 800, }; var target = new Window() { SizeToContent = SizeToContent.WidthAndHeight, Content = child }; Show(target); Assert.Equal(SizeToContent.WidthAndHeight, target.SizeToContent); } } [Fact] public void Width_Height_Should_Be_Updated_When_SizeToContent_Is_WidthAndHeight() { using (UnitTestApplication.Start(TestServices.StyledWindow)) { var child = new Canvas { Width = 400, Height = 800, }; var target = new Window() { SizeToContent = SizeToContent.WidthAndHeight, Content = child }; Show(target); Assert.Equal(400, target.Width); Assert.Equal(800, target.Height); child.Width = 410; target.LayoutManager.ExecuteLayoutPass(); Assert.Equal(410, target.Width); Assert.Equal(800, target.Height); Assert.Equal(SizeToContent.WidthAndHeight, target.SizeToContent); } } [Fact] public void Setting_Width_Should_Resize_WindowImpl() { // Issue #3796 using (UnitTestApplication.Start(TestServices.StyledWindow)) { var target = new Window() { Width = 400, Height = 800, }; Show(target); Assert.Equal(400, target.Width); Assert.Equal(800, target.Height); target.Width = 410; target.LayoutManager.ExecuteLayoutPass(); var windowImpl = Mock.Get(target.PlatformImpl); windowImpl.Verify(x => x.Resize(new Size(410, 800))); Assert.Equal(410, target.Width); } } protected virtual void Show(Window window) { window.Show(); } } public class DialogSizingTests : SizingTests { protected override void Show(Window window) { var owner = new Window(); window.ShowDialog(owner); } } private IWindowImpl CreateImpl(Mock<IRenderer> renderer) { return Mock.Of<IWindowImpl>(x => x.RenderScaling == 1 && x.CreateRenderer(It.IsAny<IRenderRoot>()) == renderer.Object); } private class ChildControl : Control { public List<Size> MeasureSizes { get; } = new List<Size>(); protected override Size MeasureOverride(Size availableSize) { MeasureSizes.Add(availableSize); return base.MeasureOverride(availableSize); } } } }
/* Copyright (c) Citrix Systems, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, * with or without modification, are permitted provided * that the following conditions are met: * * * Redistributions of source code must retain the above * copyright notice, this list of conditions and the * following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the * following disclaimer in the documentation and/or other * materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ using System; using System.ComponentModel; using System.Linq; using XenAdmin.Core; using XenAdmin.Network; using XenAdmin.Utils; using XenAPI; namespace XenAdmin.Dialogs { public interface ILicenseStatus : IDisposable { LicenseStatus.HostState CurrentState { get; } Host.Edition LicenseEdition { get; } TimeSpan LicenseExpiresIn { get; } TimeSpan LicenseExpiresExactlyIn { get; } DateTime? ExpiryDate { get; } event LicenseStatus.StatusUpdatedEvent ItemUpdated; bool Updated { get; } void BeginUpdate(); Host LicencedHost { get; } LicenseStatus.LicensingModel PoolLicensingModel { get; } string LicenseEntitlements { get; } } public class LicenseStatus : ILicenseStatus { public enum HostState { Unknown, Expired, ExpiresSoon, RegularGrace, UpgradeGrace, Licensed, PartiallyLicensed, Free, Unavailable } private readonly EventHandlerList events = new EventHandlerList(); protected EventHandlerList Events { get { return events; } } private const string StatusUpdatedEventKey = "LicenseStatusStatusUpdatedEventKey"; private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); public Host LicencedHost { get; private set; } private readonly AsyncServerTime serverTime = new AsyncServerTime(); public delegate void StatusUpdatedEvent(object sender, EventArgs e); public static bool IsInfinite(TimeSpan span) { return span.TotalDays >= 3653; } public static bool IsGraceLicence(TimeSpan span) { return span.TotalDays < 30; } private IXenObject XenObject { get; set; } public bool Updated { get; set; } public LicenseStatus(IXenObject xo) { SetDefaultOptions(); XenObject = xo; if (XenObject is Host) LicencedHost = XenObject as Host; if (XenObject is Pool) { Pool pool = XenObject as Pool; SetMinimumLicenseValueHost(pool); } serverTime.ServerTimeObtained -= ServerTimeUpdatedEventHandler; serverTime.ServerTimeObtained += ServerTimeUpdatedEventHandler; if (XenObject != null) { XenObject.Connection.ConnectionStateChanged -= Connection_ConnectionStateChanged; XenObject.Connection.ConnectionStateChanged += Connection_ConnectionStateChanged; } } void Connection_ConnectionStateChanged(object sender, EventArgs e) { if (LicencedHost != null) { TriggerStatusUpdatedEvent(); } } private void SetMinimumLicenseValueHost(Pool pool) { LicencedHost = pool.Connection.Resolve(pool.master); if(LicencedHost == null) return; foreach (Host host in pool.Connection.Cache.Hosts) { if(host.LicenseExpiryUTC() < LicencedHost.LicenseExpiryUTC()) LicencedHost = host; } } private void SetDefaultOptions() { CurrentState = HostState.Unknown; Updated = false; LicenseExpiresExactlyIn = new TimeSpan(); } public void BeginUpdate() { SetDefaultOptions(); serverTime.Fetch(LicencedHost); } private void ServerTimeUpdatedEventHandler(object sender, AsyncServerTimeEventArgs e) { if (!e.Success) { if(e.QueriedHost == null) { log.ErrorFormat("Couldn't get the server time because: {0}", e.Failure.Message); return; } log.ErrorFormat("Couldn't get the server time for {0} because: {1}", e.QueriedHost.name_label, e.Failure.Message); return; } if (LicencedHost != null) { CalculateLicenseState(); TriggerStatusUpdatedEvent(); } } protected void CalculateLicenseState() { PoolLicensingModel = GetLicensingModel(XenObject.Connection); LicenseExpiresExactlyIn = CalculateLicenceExpiresIn(); CurrentState = CalculateCurrentState(); Updated = true; } private void TriggerStatusUpdatedEvent() { StatusUpdatedEvent handler = Events[StatusUpdatedEventKey] as StatusUpdatedEvent; if (handler != null) handler.Invoke(this, EventArgs.Empty); } private bool InRegularGrace { get { return LicencedHost.license_params != null && LicencedHost.license_params.ContainsKey("grace") && LicenseExpiresIn.Ticks > 0 && LicencedHost.license_params["grace"] == "regular grace"; } } private bool InUpgradeGrace { get { return LicencedHost.license_params != null && LicencedHost.license_params.ContainsKey("grace") && LicenseExpiresIn.Ticks > 0 && LicencedHost.license_params["grace"] == "upgrade grace"; } } protected virtual TimeSpan CalculateLicenceExpiresIn() { //ServerTime is UTC DateTime currentRefTime = serverTime.ServerTime; return LicencedHost.LicenseExpiryUTC().Subtract(currentRefTime); } internal static bool PoolIsMixedFreeAndExpiring(IXenObject xenObject) { if (xenObject is Pool) { if (xenObject.Connection.Cache.Hosts.Length == 1) return false; int freeCount = xenObject.Connection.Cache.Hosts.Count(h => Host.GetEdition(h.edition) == Host.Edition.Free); if (freeCount == 0 || freeCount < xenObject.Connection.Cache.Hosts.Length) return false; var expiryGroups = from Host h in xenObject.Connection.Cache.Hosts let exp = h.LicenseExpiryUTC() group h by exp into g select new { ExpiryDate = g.Key, Hosts = g }; if(expiryGroups.Count() > 1) { expiryGroups.OrderBy(g => g.ExpiryDate); if ((expiryGroups.ElementAt(1).ExpiryDate - expiryGroups.ElementAt(0).ExpiryDate).TotalDays > 30) return true; } } return false; } internal static bool PoolIsPartiallyLicensed(IXenObject xenObject) { if (xenObject is Pool) { if (xenObject.Connection.Cache.Hosts.Length == 1) return false; int freeCount = xenObject.Connection.Cache.Hosts.Count(h => Host.GetEdition(h.edition) == Host.Edition.Free); return freeCount > 0 && freeCount < xenObject.Connection.Cache.Hosts.Length; } return false; } internal static bool PoolHasMixedLicenses(IXenObject xenObject) { var pool = xenObject as Pool; if (pool != null) { if (xenObject.Connection.Cache.Hosts.Length == 1) return false; if (xenObject.Connection.Cache.Hosts.Any(h => Host.GetEdition(h.edition) == Host.Edition.Free)) return false; var licenseGroups = from Host h in xenObject.Connection.Cache.Hosts let ed = Host.GetEdition(h.edition) group h by ed; return licenseGroups.Count() > 1; } return false; } private HostState CalculateCurrentState() { if (ExpiryDate.HasValue && ExpiryDate.Value.Day == 1 && ExpiryDate.Value.Month == 1 && ExpiryDate.Value.Year == 1970) { return HostState.Unavailable; } if (PoolIsPartiallyLicensed(XenObject)) return HostState.PartiallyLicensed; if (LicenseEdition == Host.Edition.Free) return HostState.Free; if (!IsGraceLicence(LicenseExpiresIn)) return HostState.Licensed; if (IsInfinite(LicenseExpiresIn)) { return HostState.Licensed; } if (LicenseExpiresIn.Ticks <= 0) { return HostState.Expired; } if (IsGraceLicence(LicenseExpiresIn)) { if (InRegularGrace) return HostState.RegularGrace; if (InUpgradeGrace) return HostState.UpgradeGrace; return HostState.ExpiresSoon; } return LicenseEdition == Host.Edition.Free ? HostState.Free : HostState.Licensed; } #region ILicenseStatus Members public event StatusUpdatedEvent ItemUpdated { add { Events.AddHandler(StatusUpdatedEventKey, value); } remove { Events.RemoveHandler(StatusUpdatedEventKey, value); } } public Host.Edition LicenseEdition { get { return Host.GetEdition(LicencedHost.edition); } } public HostState CurrentState { get; private set; } public TimeSpan LicenseExpiresExactlyIn { get; private set; } /// <summary> /// License expiry, just days, hrs, mins /// </summary> public TimeSpan LicenseExpiresIn { get { return new TimeSpan(LicenseExpiresExactlyIn.Days, LicenseExpiresExactlyIn.Hours, LicenseExpiresExactlyIn.Minutes, 0, 0); } } public DateTime? ExpiryDate { get { if (LicencedHost.license_params != null && LicencedHost.license_params.ContainsKey("expiry")) return LicencedHost.LicenseExpiryUTC().ToLocalTime(); return null; } } public LicensingModel PoolLicensingModel { get; private set; } public string LicenseEntitlements { get { if (PoolLicensingModel == LicensingModel.Creedence && CurrentState == HostState.Licensed) { if (XenObject.Connection.Cache.Hosts.All(h => h.EnterpriseFeaturesEnabled())) return Messages.LICENSE_SUPPORT_AND_ENTERPRISE_FEATURES_ENABLED; if (XenObject.Connection.Cache.Hosts.All(h => h.DesktopPlusFeaturesEnabled())) return Messages.LICENSE_SUPPORT_AND_DESKTOP_PLUS_FEATURES_ENABLED; if (XenObject.Connection.Cache.Hosts.All(h => h.DesktopFeaturesEnabled())) return Messages.LICENSE_SUPPORT_AND_DESKTOP_FEATURES_ENABLED; if (XenObject.Connection.Cache.Hosts.All(h => h.PremiumFeaturesEnabled())) return Messages.LICENSE_SUPPORT_AND_PREMIUM_FEATURES_ENABLED; if (XenObject.Connection.Cache.Hosts.All(h => h.StandardFeaturesEnabled())) return Messages.LICENSE_SUPPORT_AND_STANDARD_FEATURES_ENABLED; if (XenObject.Connection.Cache.Hosts.All(h => h.EligibleForSupport())) return Messages.LICENSE_SUPPORT_AND_STANDARD_FEATURES_ENABLED; return Messages.LICENSE_NOT_ELIGIBLE_FOR_SUPPORT; } if (CurrentState == HostState.Free) { return Messages.LICENSE_NOT_ELIGIBLE_FOR_SUPPORT; } return Messages.UNKNOWN; } } #endregion #region LicensingModel public enum LicensingModel { Clearwater, Creedence } public static LicensingModel GetLicensingModel(IXenConnection connection) { if (Helpers.CreedenceOrGreater(connection)) return LicensingModel.Creedence; return LicensingModel.Clearwater; } #endregion #region IDisposable Members public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } private bool disposed; public void Dispose(bool disposing) { if(!disposed) { if(disposing) { if (serverTime != null) serverTime.ServerTimeObtained -= ServerTimeUpdatedEventHandler; if (XenObject != null && XenObject.Connection != null) XenObject.Connection.ConnectionStateChanged -= Connection_ConnectionStateChanged; Events.Dispose(); } disposed = true; } } #endregion } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Xunit; namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.method.Oneclass.Oneparam.param012.param012 { using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.method.Oneclass.Oneparam.param012.param012; // <Title>Call methods that have different parameter modifiers with dynamic</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> //<Expects Status=warning>\(23,23\).*CS0649</Expects> public struct myStruct { public int Field; } public class Foo { public void Method(params int[] x) { } } public class Test { public static int Status; [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { Foo f = new Foo(); dynamic d = "foo"; try { f.Method(d); } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e) { if (ErrorVerifier.Verify(ErrorMessageId.BadArgTypes, e.Message, "Foo.Method(params int[])")) return 0; } return 1; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.method.Oneclass.Oneparam.param014.param014 { using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.method.Oneclass.Oneparam.param014.param014; // <Title>Call methods that have different parameter modifiers with dynamic</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public struct myStruct { public int Field; } public class Foo { public void Method(params int[] x) { } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { Foo f = new Foo(); dynamic d = "foo"; dynamic d2 = 3; try { f.Method(d2, d); } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e) { if (ErrorVerifier.Verify(ErrorMessageId.BadArgTypes, e.Message, "Foo.Method(params int[])")) return 0; } return 1; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.method.Oneclass.Oneparam.param022.param022 { using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.method.Oneclass.Oneparam.param022.param022; // <Title>Make sure that the cache is not blown away by the rules the binder generates</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> // <Expects Status=success><Expects> // <Code> using System; public class A { public Action Baz { get; set; } } public class C { public void Baz() { Program.Status = 1; } } public class D<T> { public T Baz; } public struct E { public dynamic Baz; } public class F : I { public void Baz() { System.Console.WriteLine("E.Baz"); Program.Status = 1; } public Action Bar { get; set; } public dynamic Foo { get; set; } } public interface I { void Baz(); Action Bar { get; set; } dynamic Foo { get; set; } } public class Program { public static int Status = 0; private static void CallBaz(dynamic x) { x.Baz(); } private static void CallBar(dynamic x) { x.Bar(); } private static void CallFoo(dynamic x) { x.Foo(); } public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { var a = new C(); var b = new { Baz = new Action(() => Program.Status = 1) } ; var d = new D<Func<int>>() { Baz = new Func<int>(() => Program.Status = 1) } ; var e = new E() { Baz = new Action(() => Program.Status = 1) } ; var x = new { Baz = (Action)delegate { Program.Status = 1; } } ; var f = new F(); int rez = 0; int tests = 0; tests++; Program.Status = 0; x.Baz(); rez += Program.Status; f.Bar = f.Baz; f.Foo = (Action)f.Baz; I i = f; tests++; Program.Status = 0; CallBar(i); rez += Program.Status; tests++; Program.Status = 0; CallFoo(i); rez += Program.Status; tests++; Program.Status = 0; CallBaz(a); rez += Program.Status; tests++; Program.Status = 0; CallBaz(b); rez += Program.Status; tests++; Program.Status = 0; CallBaz(a); rez += Program.Status; tests++; Program.Status = 0; CallBaz(a); rez += Program.Status; tests++; Program.Status = 0; CallBaz(b); rez += Program.Status; tests++; Program.Status = 0; CallBaz(a); rez += Program.Status; tests++; Program.Status = 0; CallBaz(d); rez += Program.Status; tests++; Program.Status = 0; CallBaz(a); rez += Program.Status; tests++; Program.Status = 0; CallBaz(b); rez += Program.Status; tests++; Program.Status = 0; CallBaz(e); rez += Program.Status; tests++; Program.Status = 0; CallBaz(d); rez += Program.Status; tests++; Program.Status = 0; CallBaz(a); rez += Program.Status; tests++; Program.Status = 0; CallBaz(b); rez += Program.Status; tests++; Program.Status = 0; CallBaz(i); rez += Program.Status; tests++; Program.Status = 0; CallBaz(a); rez += Program.Status; tests++; Program.Status = 0; CallBaz(i); rez += Program.Status; tests++; Program.Status = 0; CallBaz(a); rez += Program.Status; return rez == tests ? 0 : 1; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.method.Oneclass.Oneparam.nullable001.nullable001 { using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.method.Oneclass.Oneparam.nullable001.nullable001; public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic d = new Test(); int? x = 5; int rez = d.M(x) == 1 ? 0 : 1; //we pass in the compile time type x = null; rez += d.M(x) == 1 ? 0 : 1; //we pass in the compile time type x = 5; dynamic dyn = x; rez += d.M(dyn) == 2 ? 0 : 1; //we boxed the int -> runtime type is int x = null; dyn = x; rez += d.M(dyn) == 1 ? 0 : 1; //we are passing in null -> the only overload is the nullable one return rez > 0 ? 1 : 0; } public int M(int? x) { return 1; } public int M(int x) { return 2; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.method.Oneclass.Oneparam.regr001.regr001 { using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.method.Oneclass.Oneparam.regr001.regr001; // <Title>Overload resolution of methods involving pointer types</Title> // <Description> // Method overload resolution with dynamic argument resolving to array parameter with the corresponding pointer type as the parameter for the other method // </Description> //<Expects Status=warning>\(19,9\).*CS0169</Expects> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> //using System; //enum color { Red, Blue, Green }; //public struct S //{ //int i; //} //class Program //{ //unsafe public static int Test1(char* c) //{ //return 1; //} //public static int Test1(char[] c) //{ //return 0; //} //unsafe public static int Test2(int* c) //{ //return 1; //} //public static int Test2(int[] c) //{ //return 0; //} //unsafe public static int Test3(byte* c) //{ //return 1; //} //public static int Test3(byte[] c) //{ //return 0; //} //unsafe public static int Test4(sbyte* c) //{ //return 1; //} //public static int Test4(sbyte[] c) //{ //return 0; //} //unsafe public static int Test5(short* c) //{ //return 1; //} //public static int Test5(short[] c) //{ //return 0; //} //unsafe public static int Test6(ushort* c) //{ //return 1; //} //public static int Test6(ushort[] c) //{ //return 0; //} //unsafe public static int Test7(uint* c) //{ //return 1; //} //public static int Test7(uint[] c) //{ //return 0; //} //unsafe public static int Test8(long* c) //{ //return 1; //} //public static int Test8(long[] c) //{ //return 0; //} //unsafe public static int Test9(ulong* c) //{ //return 1; //} //public static int Test9(ulong[] c) //{ //return 0; //} //unsafe public static int Test10(float* c) //{ //return 1; //} //public static int Test10(float[] c) //{ //return 0; //} //unsafe public static int Test11(double* c) //{ //return 1; //} //public static int Test11(double[] c) //{ //return 0; //} //unsafe public static int Test12(decimal* c) //{ //return 1; //} //public static int Test12(decimal[] c) //{ //return 0; //} //unsafe public static int Test13(bool* c) //{ //return 1; //} //public static int Test13(bool[] c) //{ //return 0; //} //unsafe public static int Test14(color* c) //{ //return 1; //} //public static int Test14(color[] c) //{ //return 0; //} //unsafe public static int Test15(S* c) //{ //return 1; //} //public static int Test15(S[] c) //{ //return 0; //} //[Test][Priority(Priority.Priority2)]public void DynamicCSharpRunTest(){Assert.AreEqual(0, MainMethod());} public static int MainMethod() //{ //dynamic c1 = "Testing".ToCharArray(); //if (Test1(c1) == 1) return 1; //dynamic c2 = new int[] { 4, 5, 6 }; //if (Test2(c2) == 1) return 1; //dynamic c3 = new byte[] { 4, 5, 6 }; //if (Test3(c3) == 1) return 1; //dynamic c4 = new sbyte[] { 4, 5, 6 }; //if (Test4(c4) == 1) return 1; //dynamic c5 = new short[] { 4, 5, 6 }; //if (Test5(c5) == 1) return 1; //dynamic c6 = new ushort[] { 4, 5, 6 }; //if (Test6(c6) == 1) return 1; //dynamic c7 = new uint[] { 4, 5, 6 }; //if (Test7(c7) == 1) return 1; //dynamic c8 = new long[] { 4, 5, 6 }; //if (Test8(c8) == 1) return 1; //dynamic c9 = new ulong[] { 4, 5, 6 }; //if (Test9(c9) == 1) return 1; //dynamic c10 = new float[] { 4.5f, 5.6f, 6.7f }; //if (Test10(c10) == 1) return 1; //dynamic c11 = new double[] { 4.5d, 5.4d, 6.9d }; //if (Test11(c11) == 1) return 1; //dynamic c12 = new decimal[] { 4.5m, 5.3m, 6.8m }; //if (Test12(c12) == 1) return 1; //dynamic c13 = new bool[] { true }; //if (Test13(c13) == 1) return 1; //dynamic c14 = new color[] { }; //if (Test14(c14) == 1) return 1; //dynamic c15 = new S[] { }; //if (Test15(c15) == 1) return 1; //return 0; //} //} // </Code> } #if CAP_PointerType namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.method.Oneclass.Oneparam.regr002.regr002 { using ManagedTests.DynamicCSharp.Test; using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.method.Oneclass.Oneparam.regr002.regr002; // <Title>Overload resolution of methods involving pointer types</Title> // <Description> // Method overload resolution with dynamic argument resolving to array parameter with the corresponding pointer type as the parameter for the other method // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System; public class Program { [Test] [Priority(Priority.Priority2)] public void DynamicCSharpRunTest() { Assert.AreEqual(0, MainMethod()); } public static int MainMethod() { var c = "abc".ToCharArray(); var a = new string(c); var b = new string((dynamic)c); return 0; } } // </Code> } #endif
namespace XenAdmin.Dialogs { partial class RoleSelectionDialog { /// <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 Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(RoleSelectionDialog)); System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle2 = new System.Windows.Forms.DataGridViewCellStyle(); System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle1 = new System.Windows.Forms.DataGridViewCellStyle(); System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle3 = new System.Windows.Forms.DataGridViewCellStyle(); this.buttonSave = new System.Windows.Forms.Button(); this.buttonCancel = new System.Windows.Forms.Button(); this.labelBlurb = new System.Windows.Forms.Label(); this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel(); this.labelDescription = new System.Windows.Forms.Label(); this.gridRoles = new System.Windows.Forms.DataGridView(); this.ColumnRolesCheckBox = new System.Windows.Forms.DataGridViewCheckBoxColumn(); this.dataGridViewTextBoxColumn1 = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.pictureBoxSubjectType = new System.Windows.Forms.PictureBox(); this.dataGridViewTextBoxColumn2 = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.dataGridViewTextBoxColumn3 = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.tableLayoutPanel2 = new System.Windows.Forms.TableLayoutPanel(); this.tableLayoutPanel1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.gridRoles)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.pictureBoxSubjectType)).BeginInit(); this.tableLayoutPanel2.SuspendLayout(); this.SuspendLayout(); // // buttonSave // resources.ApplyResources(this.buttonSave, "buttonSave"); this.buttonSave.Name = "buttonSave"; this.buttonSave.UseVisualStyleBackColor = true; this.buttonSave.Click += new System.EventHandler(this.buttonSave_Click); // // buttonCancel // resources.ApplyResources(this.buttonCancel, "buttonCancel"); this.buttonCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.buttonCancel.Name = "buttonCancel"; this.buttonCancel.UseVisualStyleBackColor = true; this.buttonCancel.Click += new System.EventHandler(this.buttonCancel_Click); // // labelBlurb // resources.ApplyResources(this.labelBlurb, "labelBlurb"); this.labelBlurb.Name = "labelBlurb"; // // tableLayoutPanel1 // resources.ApplyResources(this.tableLayoutPanel1, "tableLayoutPanel1"); this.tableLayoutPanel1.Controls.Add(this.labelDescription, 1, 0); this.tableLayoutPanel1.Controls.Add(this.gridRoles, 0, 0); this.tableLayoutPanel1.Name = "tableLayoutPanel1"; // // labelDescription // resources.ApplyResources(this.labelDescription, "labelDescription"); this.labelDescription.Name = "labelDescription"; // // gridRoles // this.gridRoles.AllowUserToAddRows = false; this.gridRoles.AllowUserToDeleteRows = false; this.gridRoles.AllowUserToResizeColumns = false; this.gridRoles.AllowUserToResizeRows = false; this.gridRoles.BackgroundColor = System.Drawing.SystemColors.Window; this.gridRoles.CellBorderStyle = System.Windows.Forms.DataGridViewCellBorderStyle.None; this.gridRoles.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; this.gridRoles.ColumnHeadersVisible = false; this.gridRoles.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] { this.ColumnRolesCheckBox, this.dataGridViewTextBoxColumn1}); resources.ApplyResources(this.gridRoles, "gridRoles"); this.gridRoles.MultiSelect = false; this.gridRoles.Name = "gridRoles"; dataGridViewCellStyle2.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft; dataGridViewCellStyle2.BackColor = System.Drawing.SystemColors.Control; dataGridViewCellStyle2.Font = new System.Drawing.Font("Segoe UI", 9F); dataGridViewCellStyle2.ForeColor = System.Drawing.SystemColors.WindowText; dataGridViewCellStyle2.SelectionBackColor = System.Drawing.SystemColors.Highlight; dataGridViewCellStyle2.SelectionForeColor = System.Drawing.SystemColors.HighlightText; dataGridViewCellStyle2.WrapMode = System.Windows.Forms.DataGridViewTriState.True; this.gridRoles.RowHeadersDefaultCellStyle = dataGridViewCellStyle2; this.gridRoles.RowHeadersVisible = false; this.gridRoles.RowHeadersWidthSizeMode = System.Windows.Forms.DataGridViewRowHeadersWidthSizeMode.DisableResizing; this.gridRoles.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect; this.gridRoles.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.gridRoles_KeyPress); this.gridRoles.SelectionChanged += new System.EventHandler(this.gridRoles_SelectionChanged); this.gridRoles.CellContentClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.gridRoles_CellContentClick); // // ColumnRolesCheckBox // this.ColumnRolesCheckBox.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.None; resources.ApplyResources(this.ColumnRolesCheckBox, "ColumnRolesCheckBox"); this.ColumnRolesCheckBox.Name = "ColumnRolesCheckBox"; this.ColumnRolesCheckBox.ReadOnly = true; this.ColumnRolesCheckBox.Resizable = System.Windows.Forms.DataGridViewTriState.False; // // dataGridViewTextBoxColumn1 // this.dataGridViewTextBoxColumn1.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill; dataGridViewCellStyle1.WrapMode = System.Windows.Forms.DataGridViewTriState.True; this.dataGridViewTextBoxColumn1.DefaultCellStyle = dataGridViewCellStyle1; resources.ApplyResources(this.dataGridViewTextBoxColumn1, "dataGridViewTextBoxColumn1"); this.dataGridViewTextBoxColumn1.Name = "dataGridViewTextBoxColumn1"; this.dataGridViewTextBoxColumn1.ReadOnly = true; this.dataGridViewTextBoxColumn1.Resizable = System.Windows.Forms.DataGridViewTriState.False; this.dataGridViewTextBoxColumn1.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.NotSortable; // // pictureBoxSubjectType // resources.ApplyResources(this.pictureBoxSubjectType, "pictureBoxSubjectType"); this.pictureBoxSubjectType.Image = global::XenAdmin.Properties.Resources._000_UserAndGroup_h32bit_32; this.pictureBoxSubjectType.Name = "pictureBoxSubjectType"; this.pictureBoxSubjectType.TabStop = false; // // dataGridViewTextBoxColumn2 // this.dataGridViewTextBoxColumn2.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill; dataGridViewCellStyle3.WrapMode = System.Windows.Forms.DataGridViewTriState.True; this.dataGridViewTextBoxColumn2.DefaultCellStyle = dataGridViewCellStyle3; resources.ApplyResources(this.dataGridViewTextBoxColumn2, "dataGridViewTextBoxColumn2"); this.dataGridViewTextBoxColumn2.Name = "dataGridViewTextBoxColumn2"; this.dataGridViewTextBoxColumn2.ReadOnly = true; this.dataGridViewTextBoxColumn2.Resizable = System.Windows.Forms.DataGridViewTriState.False; this.dataGridViewTextBoxColumn2.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.NotSortable; // // dataGridViewTextBoxColumn3 // this.dataGridViewTextBoxColumn3.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill; resources.ApplyResources(this.dataGridViewTextBoxColumn3, "dataGridViewTextBoxColumn3"); this.dataGridViewTextBoxColumn3.Name = "dataGridViewTextBoxColumn3"; this.dataGridViewTextBoxColumn3.ReadOnly = true; // // tableLayoutPanel2 // resources.ApplyResources(this.tableLayoutPanel2, "tableLayoutPanel2"); this.tableLayoutPanel2.Controls.Add(this.labelBlurb, 1, 0); this.tableLayoutPanel2.Controls.Add(this.pictureBoxSubjectType, 0, 0); this.tableLayoutPanel2.Name = "tableLayoutPanel2"; // // RoleSelectionDialog // this.AcceptButton = this.buttonSave; resources.ApplyResources(this, "$this"); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi; this.CancelButton = this.buttonCancel; this.Controls.Add(this.tableLayoutPanel2); this.Controls.Add(this.tableLayoutPanel1); this.Controls.Add(this.buttonCancel); this.Controls.Add(this.buttonSave); this.Name = "RoleSelectionDialog"; this.tableLayoutPanel1.ResumeLayout(false); this.tableLayoutPanel1.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.gridRoles)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.pictureBoxSubjectType)).EndInit(); this.tableLayoutPanel2.ResumeLayout(false); this.tableLayoutPanel2.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Button buttonSave; private System.Windows.Forms.Button buttonCancel; private System.Windows.Forms.Label labelBlurb; private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1; private System.Windows.Forms.DataGridView gridRoles; private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn2; private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn3; private System.Windows.Forms.Label labelDescription; private System.Windows.Forms.PictureBox pictureBoxSubjectType; private System.Windows.Forms.DataGridViewCheckBoxColumn ColumnRolesCheckBox; private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn1; private System.Windows.Forms.TableLayoutPanel tableLayoutPanel2; } }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #region Using directives using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Management.Automation; #endregion namespace Microsoft.Management.Infrastructure.CimCmdlets { /// <summary> /// <para> /// Enables the user to enumerate the list of CIM Classes under a specific /// Namespace. If no list of classes is given, the Cmdlet returns all /// classes in the given namespace. /// </para> /// <para> /// NOTES: The class instance contains the Namespace properties /// Should the class remember what Session it came from? No. /// </para> /// </summary> [Alias("gcls")] [Cmdlet(VerbsCommon.Get, GetCimClassCommand.Noun, DefaultParameterSetName = ComputerSetName, HelpUri = "https://go.microsoft.com/fwlink/?LinkId=227959")] [OutputType(typeof(CimClass))] public class GetCimClassCommand : CimBaseCommand { #region constructor /// <summary> /// Initializes a new instance of the <see cref="GetCimClassCommand"/> class. /// </summary> public GetCimClassCommand() : base(parameters, parameterSets) { DebugHelper.WriteLogEx(); } #endregion #region parameters /// <summary> /// <para> /// The following is the definition of the input parameter "ClassName". /// </para> /// <para> /// Wildcard expansion should be allowed. /// </para> /// </summary> [Parameter( Position = 0, ValueFromPipelineByPropertyName = true)] public string ClassName { get; set; } /// <summary> /// <para> /// The following is the definition of the input parameter "Namespace". /// Specifies the Namespace under which to look for the specified class name. /// If no class name is specified, the cmdlet should return all classes under /// the specified Namespace. /// </para> /// <para> /// Default namespace is root\cimv2 /// </para> /// </summary> [Parameter( Position = 1, ValueFromPipelineByPropertyName = true)] public string Namespace { get; set; } /// <summary> /// The following is the definition of the input parameter "OperationTimeoutSec". /// Enables the user to specify the operation timeout in Seconds. This value /// overwrites the value specified by the CimSession Operation timeout. /// </summary> [Alias(AliasOT)] [Parameter(ValueFromPipelineByPropertyName = true)] public uint OperationTimeoutSec { get; set; } /// <summary> /// The following is the definition of the input parameter "Session". /// Uses a CimSession context. /// </summary> [Parameter( Mandatory = true, ValueFromPipeline = true, ParameterSetName = SessionSetName)] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public CimSession[] CimSession { get { return cimSession; } set { cimSession = value; base.SetParameter(value, nameCimSession); } } private CimSession[] cimSession; /// <summary> /// <para>The following is the definition of the input parameter "ComputerName". /// Provides the name of the computer from which to retrieve the <see cref="CimClass"/> /// </para> /// <para> /// If no ComputerName is specified the default value is "localhost" /// </para> /// </summary> [Alias(AliasCN, AliasServerName)] [Parameter( ValueFromPipelineByPropertyName = true, ParameterSetName = ComputerSetName)] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public string[] ComputerName { get { return computerName; } set { computerName = value; base.SetParameter(value, nameComputerName); } } private string[] computerName; /// <summary> /// <para> /// The following is the definition of the input parameter "MethodName", /// Which may contains wildchar. /// Then Filter the <see cref="CimClass"/> by given methodname /// </para> /// </summary> [Parameter(ValueFromPipelineByPropertyName = true)] public string MethodName { get; set; } /// <summary> /// <para> /// The following is the definition of the input parameter "PropertyName", /// Which may contains wildchar. /// Filter the <see cref="CimClass"/> by given property name. /// </para> /// </summary> [Parameter(ValueFromPipelineByPropertyName = true)] public string PropertyName { get; set; } /// <summary> /// <para> /// The following is the definition of the input parameter "QualifierName", /// Which may contains wildchar. /// Filter the <see cref="CimClass"/> by given methodname /// </para> /// </summary> [Parameter(ValueFromPipelineByPropertyName = true)] public string QualifierName { get; set; } #endregion #region cmdlet methods /// <summary> /// BeginProcessing method. /// </summary> protected override void BeginProcessing() { this.CmdletOperation = new CmdletOperationBase(this); this.AtBeginProcess = false; } /// <summary> /// ProcessRecord method. /// </summary> protected override void ProcessRecord() { base.CheckParameterSet(); CimGetCimClass cimGetCimClass = this.GetOperationAgent() ?? CreateOperationAgent(); cimGetCimClass.GetCimClass(this); cimGetCimClass.ProcessActions(this.CmdletOperation); } /// <summary> /// EndProcessing method. /// </summary> protected override void EndProcessing() { CimGetCimClass cimGetCimClass = this.GetOperationAgent(); if (cimGetCimClass != null) { cimGetCimClass.ProcessRemainActions(this.CmdletOperation); } } #endregion #region helper methods /// <summary> /// <para> /// Get <see cref="CimNewCimInstance"/> object, which is /// used to delegate all New-CimInstance operations. /// </para> /// </summary> private CimGetCimClass GetOperationAgent() { return this.AsyncOperation as CimGetCimClass; } /// <summary> /// <para> /// Create <see cref="CimGetCimClass"/> object, which is /// used to delegate all Get-CimClass operations. /// </para> /// </summary> /// <returns></returns> private CimGetCimClass CreateOperationAgent() { CimGetCimClass cimGetCimClass = new(); this.AsyncOperation = cimGetCimClass; return cimGetCimClass; } #endregion #region internal const strings /// <summary> /// Noun of current cmdlet. /// </summary> internal const string Noun = @"CimClass"; #endregion #region private members #region const string of parameter names internal const string nameCimSession = "CimSession"; internal const string nameComputerName = "ComputerName"; #endregion /// <summary> /// Static parameter definition entries. /// </summary> private static readonly Dictionary<string, HashSet<ParameterDefinitionEntry>> parameters = new() { { nameCimSession, new HashSet<ParameterDefinitionEntry> { new ParameterDefinitionEntry(CimBaseCommand.SessionSetName, true), } }, { nameComputerName, new HashSet<ParameterDefinitionEntry> { new ParameterDefinitionEntry(CimBaseCommand.ComputerSetName, false), } }, }; /// <summary> /// Static parameter set entries. /// </summary> private static readonly Dictionary<string, ParameterSetEntry> parameterSets = new() { { CimBaseCommand.SessionSetName, new ParameterSetEntry(1) }, { CimBaseCommand.ComputerSetName, new ParameterSetEntry(0, true) }, }; #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections; using System.Globalization; using System.Net.NetworkInformation; using System.Runtime.Serialization; using System.Text.RegularExpressions; namespace System.Net { public class WebProxy : IWebProxy, ISerializable { private ArrayList _bypassList; private Regex[] _regExBypassList; public WebProxy() : this((Uri)null, false, null, null) { } public WebProxy(Uri Address) : this(Address, false, null, null) { } public WebProxy(Uri Address, bool BypassOnLocal) : this(Address, BypassOnLocal, null, null) { } public WebProxy(Uri Address, bool BypassOnLocal, string[] BypassList) : this(Address, BypassOnLocal, BypassList, null) { } public WebProxy(Uri Address, bool BypassOnLocal, string[] BypassList, ICredentials Credentials) { this.Address = Address; this.Credentials = Credentials; this.BypassProxyOnLocal = BypassOnLocal; if (BypassList != null) { _bypassList = new ArrayList(BypassList); UpdateRegExList(true); } } public WebProxy(string Host, int Port) : this(new Uri("http://" + Host + ":" + Port.ToString(CultureInfo.InvariantCulture)), false, null, null) { } public WebProxy(string Address) : this(CreateProxyUri(Address), false, null, null) { } public WebProxy(string Address, bool BypassOnLocal) : this(CreateProxyUri(Address), BypassOnLocal, null, null) { } public WebProxy(string Address, bool BypassOnLocal, string[] BypassList) : this(CreateProxyUri(Address), BypassOnLocal, BypassList, null) { } public WebProxy(string Address, bool BypassOnLocal, string[] BypassList, ICredentials Credentials) : this(CreateProxyUri(Address), BypassOnLocal, BypassList, Credentials) { } public Uri Address { get; set; } public bool BypassProxyOnLocal { get; set; } public string[] BypassList { get { return _bypassList != null ? (string[])_bypassList.ToArray(typeof(string)) : Array.Empty<string>(); } set { _bypassList = new ArrayList(value); UpdateRegExList(true); } } public ArrayList BypassArrayList => _bypassList ?? (_bypassList = new ArrayList()); public ICredentials Credentials { get; set; } public bool UseDefaultCredentials { get { return Credentials == CredentialCache.DefaultCredentials; } set { Credentials = value ? CredentialCache.DefaultCredentials : null; } } public Uri GetProxy(Uri destination) { if (destination == null) { throw new ArgumentNullException(nameof(destination)); } return IsBypassed(destination) ? destination : Address; } private static Uri CreateProxyUri(string address) => address == null ? null : address.IndexOf("://") == -1 ? new Uri("http://" + address) : new Uri(address); private void UpdateRegExList(bool canThrow) { Regex[] regExBypassList = null; ArrayList bypassList = _bypassList; try { if (bypassList != null && bypassList.Count > 0) { regExBypassList = new Regex[bypassList.Count]; for (int i = 0; i < bypassList.Count; i++) { regExBypassList[i] = new Regex((string)bypassList[i], RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); } } } catch { if (!canThrow) { _regExBypassList = null; return; } throw; } // Update field here, as it could throw earlier in the loop _regExBypassList = regExBypassList; } private bool IsMatchInBypassList(Uri input) { UpdateRegExList(false); if (_regExBypassList != null) { string matchUriString = input.IsDefaultPort ? input.Scheme + "://" + input.Host : input.Scheme + "://" + input.Host + ":" + input.Port.ToString(); foreach (Regex r in _regExBypassList) { if (r.IsMatch(matchUriString)) { return true; } } } return false; } private bool IsLocal(Uri host) { string hostString = host.Host; IPAddress hostAddress; if (IPAddress.TryParse(hostString, out hostAddress)) { return IPAddress.IsLoopback(hostAddress) || IsAddressLocal(hostAddress); } // No dot? Local. int dot = hostString.IndexOf('.'); if (dot == -1) { return true; } // If it matches the primary domain, it's local. (Whether or not the hostname matches.) string local = "." + IPGlobalProperties.GetIPGlobalProperties().DomainName; return local.Length == (hostString.Length - dot) && string.Compare(local, 0, hostString, dot, local.Length, StringComparison.OrdinalIgnoreCase) == 0; } private static bool IsAddressLocal(IPAddress ipAddress) { // Perf note: The .NET Framework caches this and then uses network change notifications to track // whether the set should be recomputed. We could consider doing the same if this is observed as // a bottleneck, but that tracking has its own costs. IPAddress[] localAddresses = Dns.GetHostEntryAsync(Dns.GetHostName()).GetAwaiter().GetResult().AddressList; // TODO: Use synchronous GetHostEntry when available for (int i = 0; i < localAddresses.Length; i++) { if (ipAddress.Equals(localAddresses[i])) { return true; } } return false; } public bool IsBypassed(Uri host) { if (host == null) { throw new ArgumentNullException(nameof(host)); } return Address == null || host.IsLoopback || (BypassProxyOnLocal && IsLocal(host)) || IsMatchInBypassList(host); } protected WebProxy(SerializationInfo serializationInfo, StreamingContext streamingContext) { throw new PlatformNotSupportedException(); } void ISerializable.GetObjectData(SerializationInfo serializationInfo, StreamingContext streamingContext) { throw new PlatformNotSupportedException(); } protected virtual void GetObjectData(SerializationInfo serializationInfo, StreamingContext streamingContext) { throw new PlatformNotSupportedException(); } [Obsolete("This method has been deprecated. Please use the proxy selected for you by default. https://go.microsoft.com/fwlink/?linkid=14202")] public static WebProxy GetDefaultProxy() { // The .NET Framework here returns a proxy that fetches IE settings and // executes JavaScript to determine the correct proxy. throw new PlatformNotSupportedException(); } } }
using System; using System.Collections.Generic; using System.Text; using System.Xml; using System.IO; namespace Krystals4ObjectLibrary { /// <summary> /// A two dimensional array of unsigned integers used for modulating krystals. /// </summary> public sealed class Modulator : INamedComparable { #region constructors public Modulator(string filepath) { using(XmlReader r = XmlReader.Create(filepath)) { _name = Path.GetFileName(filepath); ; K.ReadToXmlElementTag(r, "modulator"); // check that this is a modulator K.ReadToXmlElementTag(r, "array"); for(int i = 0 ; i < 2 ; i++) { r.MoveToAttribute(i); switch(r.Name) { case "xdim": _xDim = int.Parse(r.Value); break; case "ydim": _yDim = int.Parse(r.Value); break; } } List<uint> valueList = K.GetUIntList(r.ReadString()); if(valueList.Count != (_xDim * _yDim)) { string msg = "Error in file: incorrect dimensions for modulator array."; throw new ApplicationException(msg); } _array = new int[_xDim, _yDim]; int valueIndex = 0; for(int y = 0 ; y < _yDim ; y++) for(int x = 0 ; x < _xDim ; x++) _array[x, y] = (int) valueList[valueIndex++]; } } public Modulator(int xDim, int yDim) { //_name = K.UntitledModulatorName; _name = ""; // is set when the modulator is saved _xDim = xDim; _yDim = yDim; _array = new int[xDim, yDim]; } #endregion constructors #region public functions public void Save() { bool equivalentExists = false; string pathname = ""; if(string.IsNullOrEmpty(_name)) // this is a new or newly edited modulator { DirectoryInfo dir = new DirectoryInfo(K.ModulationOperatorsFolder); foreach(FileInfo fileInfo in dir.GetFiles("m*.kmod")) { Modulator otherModulator = new Modulator(K.ModulationOperatorsFolder + @"\" + fileInfo.Name); if(this.CompareTo(otherModulator) == 0) { equivalentExists = true; _name = otherModulator.Name; pathname = K.ModulationOperatorsFolder + @"\" + _name; break; } } if(!equivalentExists) // generate a new name { int fileIndex = 1; do { _name = String.Format("m{0}x{1}({2})-{3}{4}", _xDim, _yDim, MaxValue, fileIndex, K.ModulatorFilenameSuffix); pathname = K.ModulationOperatorsFolder + @"\" + _name; fileIndex++; } while(File.Exists(pathname)); } } else pathname = K.ModulationOperatorsFolder + @"\" + _name; if(MaxValueHasChanged()) // rename the current modulator { File.Delete(pathname); _name = ""; Save(); // recursive call saves under a new name } else if(!equivalentExists) { XmlWriterSettings settings = new XmlWriterSettings { Indent = true, IndentChars = ("\t"), CloseOutput = true }; using(XmlWriter w = XmlWriter.Create(pathname, settings)) { w.WriteStartDocument(); w.WriteComment("created: " + K.Now); w.WriteStartElement("modulator"); w.WriteAttributeString("xmlns", "xsi", null, "http://www.w3.org/2001/XMLSchema-instance"); w.WriteAttributeString("xsi", "noNamespaceSchemaLocation", null, K.MoritzXmlSchemasFolder + @"\krystals.xsd"); w.WriteStartElement("array"); w.WriteAttributeString("xdim", _xDim.ToString()); w.WriteAttributeString("ydim", _yDim.ToString()); w.WriteString(MatrixAsString); w.WriteEndElement(); // array w.WriteEndElement(); // modulator w.Close(); } } } /// <summary> /// Returns 0 if both matrices are identical, otherwise compares the two names. /// </summary> /// <param name="other"></param> /// <returns></returns> public int CompareTo(object other) { if(!(other is Modulator otherModulator)) throw new ArgumentException(); bool modulatorsAreEquivalent = false; if(this.XDim == otherModulator.XDim && this.YDim == otherModulator.YDim) { modulatorsAreEquivalent = true; for(int x = 0 ; x < this.XDim ; x++) { for(int y = 0 ; y < this.YDim ; y++) { if(this.Array[x, y] != otherModulator.Array[x, y]) { modulatorsAreEquivalent = false; break; } } if(modulatorsAreEquivalent == false) break; } } if(modulatorsAreEquivalent) return 0; else return this.Name.CompareTo(otherModulator.Name); } private bool MaxValueHasChanged() { string[] segs = _name.Split('(', ')'); uint max = uint.Parse(segs[1]); if(max == MaxValue) return false; else return true; } public override string ToString() { return this.Name; } #endregion public functions #region properties public string Name { get { return _name; } set { _name = value; } } public int XDim { get { return _xDim; } set { _xDim = value; } } public int YDim { get { return _yDim; } set { _yDim = value; } } public int[,] Array { get { return _array; } set { _array = value; } } private string MatrixAsString { get { StringBuilder s = new StringBuilder(); string introTabs = "\n\t\t\t\t"; for(int y = 0 ; y < _yDim ; y++) { s.Append(introTabs); for(int x = 0 ; x < _xDim ; x++) { s.Append(_array[x, y].ToString()); s.Append("\t"); } } s.Append("\n\t\t\t"); return s.ToString(); } } private int MaxValue { get { int maxValue = 0; for(int y = 0 ; y < _yDim ; y++) for(int x = 0 ; x < _xDim ; x++) maxValue = maxValue < _array[x, y] ? _array[x, y] : maxValue; return maxValue; } } #endregion properties #region private variables private string _name; private int _xDim = 1; private int _yDim = 1; private int[,] _array = new int[1, 1]; #endregion private variables } }
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.Net; namespace Microsoft.Zelig.Test { public class WebHeaderCollectionTests : TestBase, ITestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests."); // Add your functionality here. return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { Log.Comment("Cleaning up after the tests."); // TODO: Add your clean up steps here. } public override TestResult Run( string[] args ) { return TestResult.Pass; } //--// //--// //--// #region Helper methods private TestResult VerifyHttpHeaders(System.Net.WebHeaderCollection wrc, System.Net.WebHeaderCollection wrs) { TestResult result = TestResult.Pass; try { string[] headers = wrc.AllKeys; string sValue = String.Empty; for (int i = 0; i < wrc.Count; i++) { sValue = wrc[headers[i]]; if (sValue != wrs[headers[i]]) { Log.Exception(headers[i] + "property value is incorrect."); result = TestResult.Fail; } } } catch (Exception ex) { if (!HttpTests.ValidateException(ex, typeof(InvalidOperationException))) result = TestResult.Fail; } return result; } private bool VerifyAddHeaderIsIllegal(WebHeaderCollection wrc, string header, string content, Type exceptionType) { bool res = true; try { Log.Comment("Set Headers Properties for header: '" + header + "', with value: '" + content + "'"); if (null == content) wrc.Add(header); else wrc.Add(header, content); Log.Comment("Illegal header was set: Failed."); res = false; } catch (Exception ex) { if (!HttpTests.ValidateException(ex, exceptionType)) { res = false; } } return res; } private bool VerifyHeaderIsLegal(WebHeaderCollection wrc, string header, string content, Type exceptionType) { bool res = true; try { Log.Comment("Set Headers Properties for header: '" + header + "', with value: '" + content + "'"); if(null == content) wrc.Add(header); else wrc.Add(header, content); } catch (Exception ex) { Log.Exception("Exception thrown for legal header: '" + header + "'", ex); res = false; } return res; } #endregion Helper methods #region Test [TestMethod] public TestResult TestWebHeaderCollectionAddIllegal() { TestResult result = TestResult.Pass; HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("http://127.0.0.1:" + HttpServer.s_CurrentPort.ToString() + "/"); //expect 200 - OK wr.UserAgent = ".Net Micro Framwork Device/4.0"; Log.Comment("Initial version: " + wr.ProtocolVersion); //Default version is 1.1 Log.Comment("Set Version 1.1"); wr.ProtocolVersion = new Version(1, 1); try { WebHeaderCollection wrc = wr.Headers; //Attempt to add Restricted header if (!VerifyAddHeaderIsIllegal(wrc, HttpKnownHeaderNames.Accept, null, typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyAddHeaderIsIllegal(wrc, HttpKnownHeaderNames.Connection, null, typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyAddHeaderIsIllegal(wrc, HttpKnownHeaderNames.ContentLength, null, typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyAddHeaderIsIllegal(wrc, HttpKnownHeaderNames.ContentType, null, typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyAddHeaderIsIllegal(wrc, HttpKnownHeaderNames.Date, null, typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyAddHeaderIsIllegal(wrc, HttpKnownHeaderNames.Expect, null, typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyAddHeaderIsIllegal(wrc, HttpKnownHeaderNames.Host, null, typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyAddHeaderIsIllegal(wrc, HttpKnownHeaderNames.IfModifiedSince, null, typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyAddHeaderIsIllegal(wrc, HttpKnownHeaderNames.Range, null, typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyAddHeaderIsIllegal(wrc, HttpKnownHeaderNames.Referer, null, typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyAddHeaderIsIllegal(wrc, HttpKnownHeaderNames.TransferEncoding, null, typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyAddHeaderIsIllegal(wrc, HttpKnownHeaderNames.UserAgent, null, typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyAddHeaderIsIllegal(wrc, HttpKnownHeaderNames.ProxyConnection, null, typeof(ArgumentException))) result = TestResult.Fail; } catch (Exception ex) { Log.Exception("[Client] Unexpected Exception", ex); result = TestResult.Fail; } return result; } [TestMethod] public TestResult TestWebHeaderCollectionAddIllegal2() { TestResult result = TestResult.Pass; HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("http://127.0.0.1:" + HttpServer.s_CurrentPort.ToString() + "/"); //expect 200 - OK wr.UserAgent = ".Net Micro Framwork Device/4.0"; Log.Comment("Initial version: " + wr.ProtocolVersion); //Default version is 1.1 Log.Comment("Set Version 1.1"); wr.ProtocolVersion = new Version(1, 1); try { WebHeaderCollection wrc = wr.Headers; //Attempt to add Restricted header if (!VerifyAddHeaderIsIllegal(wrc, HttpKnownHeaderNames.Accept, "text/plain; q=0.5, text/html, text/x-dvi; q=0.8, text/x-c", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyAddHeaderIsIllegal(wrc, HttpKnownHeaderNames.Connection, "close", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyAddHeaderIsIllegal(wrc, HttpKnownHeaderNames.ContentLength, "26012", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyAddHeaderIsIllegal(wrc, HttpKnownHeaderNames.ContentType, "image/gif", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyAddHeaderIsIllegal(wrc, HttpKnownHeaderNames.Date, System.DateTime.Today.ToString(), typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyAddHeaderIsIllegal(wrc, HttpKnownHeaderNames.Expect, "100", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyAddHeaderIsIllegal(wrc, HttpKnownHeaderNames.Host, "www.w3.org", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyAddHeaderIsIllegal(wrc, HttpKnownHeaderNames.IfModifiedSince, "Sat, 23 May 2009 19:43:31 GMT", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyAddHeaderIsIllegal(wrc, HttpKnownHeaderNames.Range, "500-999", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyAddHeaderIsIllegal(wrc, HttpKnownHeaderNames.Referer, "http://www.w3.org/hypertext/DataSources/Overview.html", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyAddHeaderIsIllegal(wrc, HttpKnownHeaderNames.TransferEncoding, "chunked", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyAddHeaderIsIllegal(wrc, HttpKnownHeaderNames.UserAgent, ".NetMicroFramework", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyAddHeaderIsIllegal(wrc, HttpKnownHeaderNames.ProxyConnection, "www.microsoft.com", typeof(ArgumentException))) result = TestResult.Fail; } catch (Exception ex) { Log.Exception("[Client] Unexpected Exception", ex); result = TestResult.Fail; } return result; } [TestMethod] public TestResult TestWebHeaderCollectionAddLegal2() { TestResult result = TestResult.Pass; HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("http://127.0.0.1:" + HttpServer.s_CurrentPort.ToString() + "/"); wr.UserAgent = ".Net Micro Framwork Device/4.0"; Log.Comment("Initial version: " + wr.ProtocolVersion); //Default version is 1.1 Log.Comment("Set Version 1.0"); wr.ProtocolVersion = new Version(1, 1); try { System.Net.WebHeaderCollection wrc = wr.Headers; if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.AcceptCharset, "iso-8859-5, unicode-1-1;q=0.8", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.AcceptEncoding, "compress;q=0.5, gzip;q=1.0", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.AcceptLanguage, "en-US", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.Age, "2 days", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.Allow, "GET, PUT", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.CacheControl, "no-cache", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.ContentEncoding, "gzip", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.ContentLanguage, "mi, en", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.ContentMD5, "60e985979f1d55ab7542440fbb9659e5", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.ContentRange, "bytes 21010-47021/47022", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.Cookie, "www.google.com", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.Expires, "Thu, 01 Dec 1994 16:00:00 GMT", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.From, "webmaster@w3.org", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.IfMatch, "r2d2xxxx", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.IfNoneMatch, "xyzzy", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.IfRange, "TestIfRange: Need to have Range Header.", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.IfUnmodifiedSince, "Fri, 22 May 2009 12:43:31 GMT", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.KeepAlive, "true", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.LastModified, "Fri, 22 May 2009 12:43:31 GMT", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.MaxForwards, "10", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.Pragma, "no-cache", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.ProxyAuthenticate, "", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.ProxyAuthorization, "", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.RetryAfter, "100000", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.Server, "", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.SetCookie, "www.microsoft.com", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.SetCookie2, "www.bing.com", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.TE, "trailers, deflate;q=0.5", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.Trailer, "Test Code", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.Upgrade, "HTTP/2.0, SHTTP/1.3, IRC/6.9, RTA/x11", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.Via, "1.0 fred, 1.1 nowhere.com (Apache/1.1)", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.Vary, "*", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.Warning, "TestWarning", typeof(ArgumentException))) result = TestResult.Fail; if (!VerifyHeaderIsLegal(wrc, HttpKnownHeaderNames.WWWAuthenticate, "WWW-Authenticate", typeof(ArgumentException))) result = TestResult.Fail; } catch (Exception ex) { Log.Exception("[Client] Unexpected Exception", ex); result = TestResult.Fail; } return result; } [TestMethod] public TestResult TestWebHeaderCollectionIsRestricted() { TestResult result = TestResult.Pass; HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("http://127.0.0.1:" + HttpServer.s_CurrentPort.ToString() + "/"); //expect 200 - OK wr.UserAgent = ".Net Micro Framwork Device/4.0"; Log.Comment("Initial version: " + wr.ProtocolVersion); //Default version is 1.1 Log.Comment("Set Version 1.1"); wr.ProtocolVersion = new Version(1, 1); try { WebHeaderCollection wrc = wr.Headers; //Attempt to add Restricted header if (!WebHeaderCollection.IsRestricted(HttpKnownHeaderNames.Accept)) result = TestResult.Fail; if (!WebHeaderCollection.IsRestricted(HttpKnownHeaderNames.Connection)) result = TestResult.Fail; if (!WebHeaderCollection.IsRestricted(HttpKnownHeaderNames.ContentLength)) result = TestResult.Fail; if (!WebHeaderCollection.IsRestricted(HttpKnownHeaderNames.ContentType)) result = TestResult.Fail; if (!WebHeaderCollection.IsRestricted(HttpKnownHeaderNames.Date)) result = TestResult.Fail; if (!WebHeaderCollection.IsRestricted(HttpKnownHeaderNames.Expect)) result = TestResult.Fail; if (!WebHeaderCollection.IsRestricted(HttpKnownHeaderNames.Host)) result = TestResult.Fail; if (!WebHeaderCollection.IsRestricted(HttpKnownHeaderNames.IfModifiedSince)) result = TestResult.Fail; if (!WebHeaderCollection.IsRestricted(HttpKnownHeaderNames.Range)) result = TestResult.Fail; if (!WebHeaderCollection.IsRestricted(HttpKnownHeaderNames.Referer)) result = TestResult.Fail; if (!WebHeaderCollection.IsRestricted(HttpKnownHeaderNames.TransferEncoding)) result = TestResult.Fail; if (!WebHeaderCollection.IsRestricted(HttpKnownHeaderNames.UserAgent)) result = TestResult.Fail; if (!WebHeaderCollection.IsRestricted(HttpKnownHeaderNames.ProxyConnection)) result = TestResult.Fail; } catch (Exception ex) { Log.Exception("[Client] Unexpected Exception", ex); result = TestResult.Fail; } return result; } [TestMethod] public TestResult TestWebHeaderCollectionRemove() { TestResult result = TestResult.Pass; HttpWebRequest wr = (HttpWebRequest)WebRequest.Create("http://127.0.0.1:" + HttpServer.s_CurrentPort.ToString() + "/"); wr.UserAgent = ".Net Micro Framwork Device/4.0"; Log.Comment("Initial version: " + wr.ProtocolVersion); //Default version is 1.1 Log.Comment("Set Version 1.0"); wr.ProtocolVersion = new Version(1, 1); try { System.Net.WebHeaderCollection wrc = wr.Headers; int initialCount = wrc.Count; //set and remove individual header Log.Comment("Set and Remove HttpKnownHeaderNames.AcceptCharset"); wrc.Set(HttpKnownHeaderNames.AcceptCharset, "iso-8859-5, unicode-1-1;q=0.8"); wrc.Remove(HttpKnownHeaderNames.AcceptCharset); if (wrc.Count != initialCount) { result = TestResult.Fail; } Log.Comment("Set and Remove HttpKnownHeaderNames.AcceptEncoding"); wrc.Set(HttpKnownHeaderNames.AcceptEncoding, "compress;q=0.5, gzip;q=1.0"); wrc.Remove(HttpKnownHeaderNames.AcceptEncoding); if (wrc.Count != initialCount) { result = TestResult.Fail; } Log.Comment("Set and Remove HttpKnownHeaderNames.AcceptLanguage"); wrc.Set(HttpKnownHeaderNames.AcceptLanguage, "en-US"); wrc.Remove(HttpKnownHeaderNames.AcceptLanguage); if (wrc.Count != initialCount) { result = TestResult.Fail; } //Set and remove group of headers Log.Comment("Set group of headers..."); wrc.Set(HttpKnownHeaderNames.Age, "2 days"); wrc.Set(HttpKnownHeaderNames.Allow, "GET, PUT"); wrc.Set(HttpKnownHeaderNames.CacheControl, "no-cache"); wrc.Set(HttpKnownHeaderNames.ContentEncoding, "gzip"); wrc.Set(HttpKnownHeaderNames.ContentLanguage, "mi, en"); wrc.Set(HttpKnownHeaderNames.ContentMD5, "60e985979f1d55ab7542440fbb9659e5"); wrc.Set(HttpKnownHeaderNames.ContentRange, "bytes 21010-47021/47022"); wrc.Set(HttpKnownHeaderNames.Cookie, "www.google.com"); wrc.Set(HttpKnownHeaderNames.Expires, "Thu, 01 Dec 1994 16:00:00 GMT"); wrc.Set(HttpKnownHeaderNames.From, "webmaster@w3.org"); wrc.Set(HttpKnownHeaderNames.IfMatch, "r2d2xxxx"); wrc.Set(HttpKnownHeaderNames.IfNoneMatch, "xyzzy"); wrc.Set(HttpKnownHeaderNames.IfRange, "TestIfRange: Need to have Range Header."); wrc.Set(HttpKnownHeaderNames.IfUnmodifiedSince, "Fri, 22 May 2009 12:43:31 GMT"); wrc.Set(HttpKnownHeaderNames.KeepAlive, "true"); wrc.Set(HttpKnownHeaderNames.LastModified, "Fri, 22 May 2009 12:43:31 GMT"); wrc.Set(HttpKnownHeaderNames.MaxForwards, "10"); wrc.Set(HttpKnownHeaderNames.Pragma, "no-cache"); wrc.Set(HttpKnownHeaderNames.ProxyAuthenticate, ""); wrc.Set(HttpKnownHeaderNames.ProxyAuthorization, ""); wrc.Set(HttpKnownHeaderNames.RetryAfter, "100000"); wrc.Set(HttpKnownHeaderNames.Server, ""); wrc.Set(HttpKnownHeaderNames.SetCookie, "www.microsoft.com"); wrc.Set(HttpKnownHeaderNames.SetCookie2, "www.bing.com"); wrc.Set(HttpKnownHeaderNames.TE, "trailers, deflate;q=0.5"); wrc.Set(HttpKnownHeaderNames.Trailer, "Test Code"); wrc.Set(HttpKnownHeaderNames.Upgrade, "HTTP/2.0, SHTTP/1.3, IRC/6.9, RTA/x11"); wrc.Set(HttpKnownHeaderNames.Via, "1.0 fred, 1.1 nowhere.com (Apache/1.1)"); wrc.Set(HttpKnownHeaderNames.Vary, "*"); wrc.Set(HttpKnownHeaderNames.Warning, "TestWarning"); wrc.Set(HttpKnownHeaderNames.WWWAuthenticate, "WWW-Authenticate"); //remove headers Log.Comment("Remove group of headers..."); wrc.Remove(HttpKnownHeaderNames.Age); wrc.Remove(HttpKnownHeaderNames.Allow); wrc.Remove(HttpKnownHeaderNames.CacheControl); wrc.Remove(HttpKnownHeaderNames.ContentEncoding); wrc.Remove(HttpKnownHeaderNames.ContentLanguage); wrc.Remove(HttpKnownHeaderNames.ContentMD5); wrc.Remove(HttpKnownHeaderNames.ContentRange); wrc.Remove(HttpKnownHeaderNames.Cookie); wrc.Remove(HttpKnownHeaderNames.Expires); wrc.Remove(HttpKnownHeaderNames.From); wrc.Remove(HttpKnownHeaderNames.IfMatch); wrc.Remove(HttpKnownHeaderNames.IfNoneMatch); wrc.Remove(HttpKnownHeaderNames.IfRange); wrc.Remove(HttpKnownHeaderNames.IfUnmodifiedSince); wrc.Remove(HttpKnownHeaderNames.KeepAlive); wrc.Remove(HttpKnownHeaderNames.LastModified); wrc.Remove(HttpKnownHeaderNames.MaxForwards); wrc.Remove(HttpKnownHeaderNames.Pragma); wrc.Remove(HttpKnownHeaderNames.ProxyAuthenticate); wrc.Remove(HttpKnownHeaderNames.ProxyAuthorization); wrc.Remove(HttpKnownHeaderNames.RetryAfter); wrc.Remove(HttpKnownHeaderNames.Server); wrc.Remove(HttpKnownHeaderNames.SetCookie); wrc.Remove(HttpKnownHeaderNames.SetCookie2); wrc.Remove(HttpKnownHeaderNames.TE); wrc.Remove(HttpKnownHeaderNames.Trailer); wrc.Remove(HttpKnownHeaderNames.Upgrade); wrc.Remove(HttpKnownHeaderNames.Via); wrc.Remove(HttpKnownHeaderNames.Vary); wrc.Remove(HttpKnownHeaderNames.Warning); wrc.Remove(HttpKnownHeaderNames.WWWAuthenticate); if (wrc.Count != initialCount) { result = TestResult.Fail; } } catch (Exception ex) { Log.Exception("[Client] Unexpected Exception", ex); result = TestResult.Fail; } return result; } #endregion Test } }
// 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 Internal.TypeSystem; using Debug = System.Diagnostics.Debug; namespace Internal.IL.Stubs { /// <summary> /// Base class for all delegate invocation thunks. /// </summary> public abstract partial class DelegateThunk : ILStubMethod { private DelegateInfo _delegateInfo; public DelegateThunk(DelegateInfo delegateInfo) { _delegateInfo = delegateInfo; } public sealed override TypeSystemContext Context { get { return _delegateInfo.Type.Context; } } public sealed override TypeDesc OwningType { get { return _delegateInfo.Type; } } public sealed override MethodSignature Signature { get { return _delegateInfo.Signature; } } public sealed override Instantiation Instantiation { get { return Instantiation.Empty; } } protected TypeDesc SystemDelegateType { get { return Context.GetWellKnownType(WellKnownType.MulticastDelegate).BaseType; } } protected FieldDesc ExtraFunctionPointerOrDataField { get { return SystemDelegateType.GetKnownField("m_extraFunctionPointerOrData"); } } protected FieldDesc HelperObjectField { get { return SystemDelegateType.GetKnownField("m_helperObject"); } } protected FieldDesc FirstParameterField { get { return SystemDelegateType.GetKnownField("m_firstParameter"); } } protected FieldDesc FunctionPointerField { get { return SystemDelegateType.GetKnownField("m_functionPointer"); } } } /// <summary> /// Invoke thunk for open delegates to static methods. Loads all arguments except /// the 'this' pointer and performs an indirect call to the delegate target. /// This method is injected into delegate types. /// </summary> public sealed partial class DelegateInvokeOpenStaticThunk : DelegateThunk { internal DelegateInvokeOpenStaticThunk(DelegateInfo delegateInfo) : base(delegateInfo) { } public override MethodIL EmitIL() { // Target has the same signature as the Invoke method, except it's static. MethodSignatureBuilder builder = new MethodSignatureBuilder(Signature); builder.Flags = Signature.Flags | MethodSignatureFlags.Static; var emitter = new ILEmitter(); ILCodeStream codeStream = emitter.NewCodeStream(); // Load all arguments except 'this' for (int i = 0; i < Signature.Length; i++) { codeStream.EmitLdArg(i + 1); } // Indirectly call the delegate target static method. codeStream.EmitLdArg(0); codeStream.Emit(ILOpcode.ldfld, emitter.NewToken(ExtraFunctionPointerOrDataField)); codeStream.Emit(ILOpcode.calli, emitter.NewToken(builder.ToSignature())); codeStream.Emit(ILOpcode.ret); return emitter.Link(this); } public override string Name { get { return "InvokeOpenStaticThunk"; } } } /// <summary> /// Invoke thunk for open delegates to instance methods. This kind of thunk /// uses the first parameter as `this` that gets passed to the target instance method. /// The thunk also performs virtual resolution if necessary. /// This kind of delegates is typically created with Delegate.CreateDelegate /// and MethodInfo.CreateDelegate at runtime. /// </summary> public sealed partial class DelegateInvokeOpenInstanceThunk : DelegateThunk { internal DelegateInvokeOpenInstanceThunk(DelegateInfo delegateInfo) : base(delegateInfo) { } public override MethodIL EmitIL() { Debug.Assert(Signature.Length > 0); var emitter = new ILEmitter(); ILCodeStream codeStream = emitter.NewCodeStream(); // Load all arguments except delegate's 'this' TypeDesc boxThisType = null; TypeDesc[] parameters = new TypeDesc[Signature.Length - 1]; for (int i = 0; i < Signature.Length; i++) { codeStream.EmitLdArg(i + 1); if (i == 0) { // Ensure that we're working with an object type by boxing it here. // This is to allow delegates which are generic over thier first parameter // to have valid code in their thunk. if (Signature[i].IsSignatureVariable) { boxThisType = Signature[i]; codeStream.Emit(ILOpcode.box, emitter.NewToken(boxThisType)); } } else { parameters[i - 1] = Signature[i]; } } // Call a helper to get the actual method target codeStream.EmitLdArg(0); if (Signature[0].IsByRef) { codeStream.Emit(ILOpcode.ldnull); } else { codeStream.EmitLdArg(1); if (boxThisType != null) { codeStream.Emit(ILOpcode.box, emitter.NewToken(boxThisType)); } } codeStream.Emit(ILOpcode.call, emitter.NewToken(SystemDelegateType.GetKnownMethod("GetActualTargetFunctionPointer", null))); MethodSignature targetSignature = new MethodSignature(0, 0, Signature.ReturnType, parameters); codeStream.Emit(ILOpcode.calli, emitter.NewToken(targetSignature)); codeStream.Emit(ILOpcode.ret); return emitter.Link(this); } public override string Name { get { return "InvokeOpenInstanceThunk"; } } } /// <summary> /// Invoke thunk for closed delegates to static methods. The target /// is a static method, but the first argument is captured by the delegate. /// The signature of the target has an extra object-typed argument, followed /// by the arguments that are delegate-compatible with the thunk signature. /// This method is injected into delegate types. /// </summary> public sealed partial class DelegateInvokeClosedStaticThunk : DelegateThunk { internal DelegateInvokeClosedStaticThunk(DelegateInfo delegateInfo) : base(delegateInfo) { } public override MethodIL EmitIL() { TypeDesc[] targetMethodParameters = new TypeDesc[Signature.Length + 1]; targetMethodParameters[0] = Context.GetWellKnownType(WellKnownType.Object); for (int i = 0; i < Signature.Length; i++) { targetMethodParameters[i + 1] = Signature[i]; } var targetMethodSignature = new MethodSignature( Signature.Flags | MethodSignatureFlags.Static, 0, Signature.ReturnType, targetMethodParameters); var emitter = new ILEmitter(); ILCodeStream codeStream = emitter.NewCodeStream(); // Load the stored 'this' codeStream.EmitLdArg(0); codeStream.Emit(ILOpcode.ldfld, emitter.NewToken(HelperObjectField)); // Load all arguments except 'this' for (int i = 0; i < Signature.Length; i++) { codeStream.EmitLdArg(i + 1); } // Indirectly call the delegate target static method. codeStream.EmitLdArg(0); codeStream.Emit(ILOpcode.ldfld, emitter.NewToken(ExtraFunctionPointerOrDataField)); codeStream.Emit(ILOpcode.calli, emitter.NewToken(targetMethodSignature)); codeStream.Emit(ILOpcode.ret); return emitter.Link(this); } public override string Name { get { return "InvokeClosedStaticThunk"; } } } /// <summary> /// Multicast invoke thunk for delegates that are a result of Delegate.Combine. /// Passes it's arguments to each of the delegates that got combined and calls them /// one by one. Returns the value of the last delegate executed. /// This method is injected into delegate types. /// </summary> public sealed partial class DelegateInvokeMulticastThunk : DelegateThunk { internal DelegateInvokeMulticastThunk(DelegateInfo delegateInfo) : base(delegateInfo) { } public override MethodIL EmitIL() { ILEmitter emitter = new ILEmitter(); ILCodeStream codeStream = emitter.NewCodeStream(); ArrayType invocationListArrayType = SystemDelegateType.MakeArrayType(); ILLocalVariable delegateArrayLocal = emitter.NewLocal(invocationListArrayType); ILLocalVariable invocationCountLocal = emitter.NewLocal(Context.GetWellKnownType(WellKnownType.Int32)); ILLocalVariable iteratorLocal = emitter.NewLocal(Context.GetWellKnownType(WellKnownType.Int32)); ILLocalVariable delegateToCallLocal = emitter.NewLocal(SystemDelegateType); ILLocalVariable returnValueLocal = 0; if (!Signature.ReturnType.IsVoid) { returnValueLocal = emitter.NewLocal(Signature.ReturnType); } // Fill in delegateArrayLocal // Delegate[] delegateArrayLocal = (Delegate[])this.m_helperObject // ldarg.0 (this pointer) // ldfld Delegate.HelperObjectField // castclass Delegate[] // stloc delegateArrayLocal codeStream.EmitLdArg(0); codeStream.Emit(ILOpcode.ldfld, emitter.NewToken(HelperObjectField)); codeStream.Emit(ILOpcode.castclass, emitter.NewToken(invocationListArrayType)); codeStream.EmitStLoc(delegateArrayLocal); // Fill in invocationCountLocal // int invocationCountLocal = this.m_extraFunctionPointerOrData // ldarg.0 (this pointer) // ldfld Delegate.m_extraFunctionPointerOrData // stloc invocationCountLocal codeStream.EmitLdArg(0); codeStream.Emit(ILOpcode.ldfld, emitter.NewToken(ExtraFunctionPointerOrDataField)); codeStream.EmitStLoc(invocationCountLocal); // Fill in iteratorLocal // int iteratorLocal = 0; // ldc.0 // stloc iteratorLocal codeStream.EmitLdc(0); codeStream.EmitStLoc(iteratorLocal); // Loop across every element of the array. ILCodeLabel startOfLoopLabel = emitter.NewCodeLabel(); codeStream.EmitLabel(startOfLoopLabel); // Implement as do/while loop. We only have this stub in play if we're in the multicast situation // Find the delegate to call // Delegate = delegateToCallLocal = delegateArrayLocal[iteratorLocal]; // ldloc delegateArrayLocal // ldloc iteratorLocal // ldelem System.Delegate // stloc delegateToCallLocal codeStream.EmitLdLoc(delegateArrayLocal); codeStream.EmitLdLoc(iteratorLocal); codeStream.Emit(ILOpcode.ldelem, emitter.NewToken(SystemDelegateType)); codeStream.EmitStLoc(delegateToCallLocal); // Call the delegate // returnValueLocal = delegateToCallLocal(...); // ldloc delegateToCallLocal // ldfld System.Delegate.m_firstParameter // ldarg 1, n // ldloc delegateToCallLocal // ldfld System.Delegate.m_functionPointer // calli returnValueType thiscall (all the params) // IF there is a return value // stloc returnValueLocal codeStream.EmitLdLoc(delegateToCallLocal); codeStream.Emit(ILOpcode.ldfld, emitter.NewToken(FirstParameterField)); for (int i = 0; i < Signature.Length; i++) { codeStream.EmitLdArg(i + 1); } codeStream.EmitLdLoc(delegateToCallLocal); codeStream.Emit(ILOpcode.ldfld, emitter.NewToken(FunctionPointerField)); codeStream.Emit(ILOpcode.calli, emitter.NewToken(Signature)); if (returnValueLocal != 0) codeStream.EmitStLoc(returnValueLocal); // Increment iteratorLocal // ++iteratorLocal; // ldloc iteratorLocal // ldc.i4.1 // add // stloc iteratorLocal codeStream.EmitLdLoc(iteratorLocal); codeStream.EmitLdc(1); codeStream.Emit(ILOpcode.add); codeStream.EmitStLoc(iteratorLocal); // Check to see if the loop is done codeStream.EmitLdLoc(invocationCountLocal); codeStream.EmitLdLoc(iteratorLocal); codeStream.Emit(ILOpcode.bne_un, startOfLoopLabel); // Return to caller. If the delegate has a return value, be certain to return that. // return returnValueLocal; // ldloc returnValueLocal // ret if (returnValueLocal != 0) codeStream.EmitLdLoc(returnValueLocal); codeStream.Emit(ILOpcode.ret); return emitter.Link(this); } public override string Name { get { return "InvokeMulticastThunk"; } } } /// <summary> /// Invoke thunk for delegates that point to closed instance generic methods. /// These need a thunk because the function pointer to invoke might be a fat function /// pointer and we need a calli to unwrap it, inject the hidden argument, shuffle the /// rest of the arguments, and call the unwrapped function pointer. /// </summary> public sealed partial class DelegateInvokeInstanceClosedOverGenericMethodThunk : DelegateThunk { internal DelegateInvokeInstanceClosedOverGenericMethodThunk(DelegateInfo delegateInfo) : base(delegateInfo) { } public override MethodIL EmitIL() { var emitter = new ILEmitter(); ILCodeStream codeStream = emitter.NewCodeStream(); // Load the stored 'this' codeStream.EmitLdArg(0); codeStream.Emit(ILOpcode.ldfld, emitter.NewToken(HelperObjectField)); // Load all arguments except 'this' for (int i = 0; i < Signature.Length; i++) { codeStream.EmitLdArg(i + 1); } // Indirectly call the delegate target codeStream.EmitLdArg(0); codeStream.Emit(ILOpcode.ldfld, emitter.NewToken(ExtraFunctionPointerOrDataField)); codeStream.Emit(ILOpcode.calli, emitter.NewToken(Signature)); codeStream.Emit(ILOpcode.ret); return emitter.Link(this); } public override string Name { get { return "InvokeInstanceClosedOverGenericMethodThunk"; } } } public sealed partial class DelegateReversePInvokeThunk : DelegateThunk { internal DelegateReversePInvokeThunk(DelegateInfo delegateInfo) : base(delegateInfo) { } public override MethodIL EmitIL() { var emitter = new ILEmitter(); ILCodeStream codeStream = emitter.NewCodeStream(); MetadataType throwHelpersType = Context.SystemModule.GetKnownType("Internal.Runtime.CompilerHelpers", "ThrowHelpers"); MethodDesc throwHelper = throwHelpersType.GetKnownMethod("ThrowNotSupportedException", null); codeStream.EmitCallThrowHelper(emitter, throwHelper); return emitter.Link(this); } public override string Name { get { return "InvokeReversePInvokeThunk"; } } } /// <summary> /// Reverse invocation stub which goes from the strongly typed parameters the delegate /// accepts, converts them into an object array, and invokes a delegate with the /// object array, and then casts and returns the result back. /// This is used to support delegates pointing to the LINQ expression interpreter. /// </summary> public sealed partial class DelegateInvokeObjectArrayThunk : DelegateThunk { internal DelegateInvokeObjectArrayThunk(DelegateInfo delegateInfo) : base(delegateInfo) { } public override MethodIL EmitIL() { // We will generate the following code: // // object ret; // object[] args = new object[parameterCount]; // args[0] = param0; // args[1] = param1; // ... // try { // ret = ((Func<object[], object>)dlg.m_helperObject)(args); // } finally { // param0 = (T0)args[0]; // only generated for each byref argument // } // return (TRet)ret; ILEmitter emitter = new ILEmitter(); ILCodeStream codeStream = emitter.NewCodeStream(); TypeDesc objectType = Context.GetWellKnownType(WellKnownType.Object); TypeDesc objectArrayType = objectType.MakeArrayType(); ILLocalVariable argsLocal = emitter.NewLocal(objectArrayType); bool hasReturnValue = !Signature.ReturnType.IsVoid; bool hasRefArgs = false; if (Signature.Length > 0) { codeStream.EmitLdc(Signature.Length); codeStream.Emit(ILOpcode.newarr, emitter.NewToken(objectType)); codeStream.EmitStLoc(argsLocal); for (int i = 0; i < Signature.Length; i++) { TypeDesc paramType = Signature[i]; bool paramIsByRef = false; if (paramType.IsByRef) { hasRefArgs |= paramType.IsByRef; paramIsByRef = true; paramType = ((ByRefType)paramType).ParameterType; } hasRefArgs |= paramType.IsByRef; codeStream.EmitLdLoc(argsLocal); codeStream.EmitLdc(i); codeStream.EmitLdArg(i + 1); ILToken paramToken = emitter.NewToken(paramType); if (paramIsByRef) { codeStream.Emit(ILOpcode.ldobj, paramToken); } codeStream.Emit(ILOpcode.box, paramToken); codeStream.Emit(ILOpcode.stelem_ref); } } else { MethodDesc emptyObjectArrayMethod = Context.GetHelperEntryPoint("DelegateHelpers", "GetEmptyObjectArray"); codeStream.Emit(ILOpcode.call, emitter.NewToken(emptyObjectArrayMethod)); codeStream.EmitStLoc(argsLocal); } if (hasRefArgs) { // we emit a try/finally to update the args array even if an exception is thrown // ilgen.BeginTryBody(); } codeStream.EmitLdArg(0); codeStream.Emit(ILOpcode.ldfld, emitter.NewToken(HelperObjectField)); MetadataType funcType = Context.SystemModule.GetKnownType("System", "Func`2"); TypeDesc instantiatedFunc = funcType.MakeInstantiatedType(objectArrayType, objectType); codeStream.Emit(ILOpcode.castclass, emitter.NewToken(instantiatedFunc)); codeStream.EmitLdLoc(argsLocal); MethodDesc invokeMethod = instantiatedFunc.GetKnownMethod("Invoke", null); codeStream.Emit(ILOpcode.callvirt, emitter.NewToken(invokeMethod)); ILLocalVariable retLocal = (ILLocalVariable)(-1); if (hasReturnValue) { retLocal = emitter.NewLocal(objectType); codeStream.EmitStLoc(retLocal); } else { codeStream.Emit(ILOpcode.pop); } if (hasRefArgs) { // ILGeneratorLabel returnLabel = new ILGeneratorLabel(); // ilgen.Emit(OperationCode.Leave, returnLabel); // copy back ref/out args //ilgen.BeginFinallyBlock(); for (int i = 0; i < Signature.Length; i++) { TypeDesc paramType = Signature[i]; if (paramType.IsByRef) { paramType = ((ByRefType)paramType).ParameterType; ILToken paramToken = emitter.NewToken(paramType); // Update parameter codeStream.EmitLdArg(i + 1); codeStream.EmitLdLoc(argsLocal); codeStream.EmitLdc(i); codeStream.Emit(ILOpcode.ldelem_ref); codeStream.Emit(ILOpcode.unbox_any, paramToken); codeStream.Emit(ILOpcode.stobj, paramToken); } } // ilgen.Emit(OperationCode.Endfinally); // ilgen.EndTryBody(); // ilgen.MarkLabel(returnLabel); } if (hasReturnValue) { codeStream.EmitLdLoc(retLocal); codeStream.Emit(ILOpcode.unbox_any, emitter.NewToken(Signature.ReturnType)); } codeStream.Emit(ILOpcode.ret); return emitter.Link(this); } public override string Name { get { return "InvokeObjectArrayThunk"; } } } /// <summary> /// Synthetic method override of "IntPtr Delegate.GetThunk(Int32)". This method is injected /// into all delegate types and provides means for System.Delegate to access the various thunks /// generated by the compiler. /// </summary> public sealed partial class DelegateGetThunkMethodOverride : ILStubMethod { private DelegateInfo _delegateInfo; private MethodSignature _signature; internal DelegateGetThunkMethodOverride(DelegateInfo delegateInfo) { _delegateInfo = delegateInfo; } public override TypeSystemContext Context { get { return _delegateInfo.Type.Context; } } public override TypeDesc OwningType { get { return _delegateInfo.Type; } } public override MethodSignature Signature { get { if (_signature == null) { TypeSystemContext context = _delegateInfo.Type.Context; TypeDesc intPtrType = context.GetWellKnownType(WellKnownType.IntPtr); TypeDesc int32Type = context.GetWellKnownType(WellKnownType.Int32); _signature = new MethodSignature(0, 0, intPtrType, new[] { int32Type }); } return _signature; } } public override MethodIL EmitIL() { ILEmitter emitter = new ILEmitter(); var codeStream = emitter.NewCodeStream(); ILCodeLabel returnNullLabel = emitter.NewCodeLabel(); bool hasDynamicInvokeThunk = (_delegateInfo.SupportedFeatures & DelegateFeature.DynamicInvoke) != 0 && DynamicInvokeMethodThunk.SupportsSignature(_delegateInfo.Signature); ILCodeLabel[] labels = new ILCodeLabel[(int)DelegateThunkCollection.MaxThunkKind]; for (DelegateThunkKind i = 0; i < DelegateThunkCollection.MaxThunkKind; i++) { MethodDesc thunk = _delegateInfo.Thunks[i]; if (thunk != null || (i == DelegateThunkKind.DelegateInvokeThunk && hasDynamicInvokeThunk)) labels[(int)i] = emitter.NewCodeLabel(); else labels[(int)i] = returnNullLabel; } codeStream.EmitLdArg(1); codeStream.EmitSwitch(labels); codeStream.Emit(ILOpcode.br, returnNullLabel); for (DelegateThunkKind i = 0; i < DelegateThunkCollection.MaxThunkKind; i++) { MethodDesc targetMethod = null; // Dynamic invoke thunk is special since we're calling into a shared helper if (i == DelegateThunkKind.DelegateInvokeThunk && hasDynamicInvokeThunk) { Debug.Assert(_delegateInfo.Thunks[i] == null); var sig = new DynamicInvokeMethodSignature(_delegateInfo.Signature); MethodDesc thunk = Context.GetDynamicInvokeThunk(sig); if (thunk.HasInstantiation) { TypeDesc[] inst = DynamicInvokeMethodThunk.GetThunkInstantiationForMethod(_delegateInfo.Type.InstantiateAsOpen().GetMethod("Invoke", null)); targetMethod = Context.GetInstantiatedMethod(thunk, new Instantiation(inst)); } else { targetMethod = thunk; } } else { MethodDesc thunk = _delegateInfo.Thunks[i]; if (thunk != null) { targetMethod = thunk.InstantiateAsOpen(); } } if (targetMethod != null) { codeStream.EmitLabel(labels[(int)i]); codeStream.Emit(ILOpcode.ldftn, emitter.NewToken(targetMethod)); codeStream.Emit(ILOpcode.ret); } } codeStream.EmitLabel(returnNullLabel); codeStream.EmitLdc(0); codeStream.Emit(ILOpcode.conv_i); codeStream.Emit(ILOpcode.ret); return emitter.Link(this); } public override Instantiation Instantiation { get { return Instantiation.Empty; } } public override bool IsVirtual { get { return true; } } public override string Name { get { return "GetThunk"; } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. /*============================================================ ** ** ** ** Purpose: Some floating-point math operations ** ** ===========================================================*/ namespace System { //This class contains only static members and doesn't require serialization. using System; using System.Runtime; using System.Runtime.CompilerServices; using System.Runtime.ConstrainedExecution; using System.Runtime.Versioning; using System.Diagnostics.Contracts; public static class Math { private static double doubleRoundLimit = 1e16d; private const int maxRoundingDigits = 15; // This table is required for the Round function which can specify the number of digits to round to private static double[] roundPower10Double = new double[] { 1E0, 1E1, 1E2, 1E3, 1E4, 1E5, 1E6, 1E7, 1E8, 1E9, 1E10, 1E11, 1E12, 1E13, 1E14, 1E15 }; public const double PI = 3.14159265358979323846; public const double E = 2.7182818284590452354; [System.Security.SecuritySafeCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern double Acos(double d); [System.Security.SecuritySafeCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern double Asin(double d); [System.Security.SecuritySafeCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern double Atan(double d); [System.Security.SecuritySafeCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern double Atan2(double y,double x); public static Decimal Ceiling(Decimal d) { return Decimal.Ceiling(d); } [System.Security.SecuritySafeCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern double Ceiling(double a); [System.Security.SecuritySafeCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern double Cos (double d); [System.Security.SecuritySafeCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern double Cosh(double value); public static Decimal Floor(Decimal d) { return Decimal.Floor(d); } [System.Security.SecuritySafeCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern double Floor(double d); [System.Security.SecuritySafeCritical] // auto-generated private static unsafe double InternalRound(double value, int digits, MidpointRounding mode) { if (Abs(value) < doubleRoundLimit) { Double power10 = roundPower10Double[digits]; value *= power10; if (mode == MidpointRounding.AwayFromZero) { double fraction = SplitFractionDouble(&value); if (Abs(fraction) >= 0.5d) { value += Sign(fraction); } } else { // On X86 this can be inlined to just a few instructions value = Round(value); } value /= power10; } return value; } [System.Security.SecuritySafeCritical] // auto-generated private unsafe static double InternalTruncate(double d) { SplitFractionDouble(&d); return d; } [System.Security.SecuritySafeCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern double Sin(double a); [System.Security.SecuritySafeCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern double Tan(double a); [System.Security.SecuritySafeCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern double Sinh(double value); [System.Security.SecuritySafeCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern double Tanh(double value); [System.Security.SecuritySafeCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern double Round(double a); public static double Round(double value, int digits) { if ((digits < 0) || (digits > maxRoundingDigits)) throw new ArgumentOutOfRangeException("digits", Environment.GetResourceString("ArgumentOutOfRange_RoundingDigits")); Contract.EndContractBlock(); return InternalRound(value, digits, MidpointRounding.ToEven); } public static double Round(double value, MidpointRounding mode) { return Round(value, 0, mode); } public static double Round(double value, int digits, MidpointRounding mode) { if ((digits < 0) || (digits > maxRoundingDigits)) throw new ArgumentOutOfRangeException("digits", Environment.GetResourceString("ArgumentOutOfRange_RoundingDigits")); if (mode < MidpointRounding.ToEven || mode > MidpointRounding.AwayFromZero) { throw new ArgumentException(Environment.GetResourceString("Argument_InvalidEnumValue", mode, "MidpointRounding"), "mode"); } Contract.EndContractBlock(); return InternalRound(value, digits, mode); } public static Decimal Round(Decimal d) { return Decimal.Round(d,0); } public static Decimal Round(Decimal d, int decimals) { return Decimal.Round(d,decimals); } public static Decimal Round(Decimal d, MidpointRounding mode) { return Decimal.Round(d, 0, mode); } public static Decimal Round(Decimal d, int decimals, MidpointRounding mode) { return Decimal.Round(d, decimals, mode); } [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] private static unsafe extern double SplitFractionDouble(double* value); public static Decimal Truncate(Decimal d) { return Decimal.Truncate(d); } public static double Truncate(double d) { return InternalTruncate(d); } [System.Security.SecuritySafeCritical] // auto-generated [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern double Sqrt(double d); [System.Security.SecuritySafeCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern double Log (double d); [System.Security.SecuritySafeCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern double Log10(double d); [System.Security.SecuritySafeCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern double Exp(double d); [System.Security.SecuritySafeCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern double Pow(double x, double y); public static double IEEERemainder(double x, double y) { if (Double.IsNaN(x)) { return x; // IEEE 754-2008: NaN payload must be preserved } if (Double.IsNaN(y)) { return y; // IEEE 754-2008: NaN payload must be preserved } double regularMod = x % y; if (Double.IsNaN(regularMod)) { return Double.NaN; } if (regularMod == 0) { if (Double.IsNegative(x)) { return Double.NegativeZero; } } double alternativeResult; alternativeResult = regularMod - (Math.Abs(y) * Math.Sign(x)); if (Math.Abs(alternativeResult) == Math.Abs(regularMod)) { double divisionResult = x/y; double roundedResult = Math.Round(divisionResult); if (Math.Abs(roundedResult) > Math.Abs(divisionResult)) { return alternativeResult; } else { return regularMod; } } if (Math.Abs(alternativeResult) < Math.Abs(regularMod)) { return alternativeResult; } else { return regularMod; } } /*================================Abs========================================= **Returns the absolute value of it's argument. ============================================================================*/ [CLSCompliant(false)] public static sbyte Abs(sbyte value) { if (value >= 0) return value; else return AbsHelper(value); } private static sbyte AbsHelper(sbyte value) { Contract.Requires(value < 0, "AbsHelper should only be called for negative values! (workaround for JIT inlining)"); if (value == SByte.MinValue) throw new OverflowException(Environment.GetResourceString("Overflow_NegateTwosCompNum")); Contract.EndContractBlock(); return ((sbyte)(-value)); } public static short Abs(short value) { if (value >= 0) return value; else return AbsHelper(value); } private static short AbsHelper(short value) { Contract.Requires(value < 0, "AbsHelper should only be called for negative values! (workaround for JIT inlining)"); if (value == Int16.MinValue) throw new OverflowException(Environment.GetResourceString("Overflow_NegateTwosCompNum")); Contract.EndContractBlock(); return (short) -value; } public static int Abs(int value) { if (value >= 0) return value; else return AbsHelper(value); } private static int AbsHelper(int value) { Contract.Requires(value < 0, "AbsHelper should only be called for negative values! (workaround for JIT inlining)"); if (value == Int32.MinValue) throw new OverflowException(Environment.GetResourceString("Overflow_NegateTwosCompNum")); Contract.EndContractBlock(); return -value; } public static long Abs(long value) { if (value >= 0) return value; else return AbsHelper(value); } private static long AbsHelper(long value) { Contract.Requires(value < 0, "AbsHelper should only be called for negative values! (workaround for JIT inlining)"); if (value == Int64.MinValue) throw new OverflowException(Environment.GetResourceString("Overflow_NegateTwosCompNum")); Contract.EndContractBlock(); return -value; } [System.Security.SecuritySafeCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] extern public static float Abs(float value); // This is special code to handle NaN (We need to make sure NaN's aren't // negated). In CSharp, the else clause here should always be taken if // value is NaN, since the normal case is taken if and only if value < 0. // To illustrate this completely, a compiler has translated this into: // "load value; load 0; bge; ret -value ; ret value". // The bge command branches for comparisons with the unordered NaN. So // it runs the else case, which returns +value instead of negating it. // return (value < 0) ? -value : value; [System.Security.SecuritySafeCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] extern public static double Abs(double value); // This is special code to handle NaN (We need to make sure NaN's aren't // negated). In CSharp, the else clause here should always be taken if // value is NaN, since the normal case is taken if and only if value < 0. // To illustrate this completely, a compiler has translated this into: // "load value; load 0; bge; ret -value ; ret value". // The bge command branches for comparisons with the unordered NaN. So // it runs the else case, which returns +value instead of negating it. // return (value < 0) ? -value : value; public static Decimal Abs(Decimal value) { return Decimal.Abs(value); } /*================================MAX========================================= **Returns the larger of val1 and val2 ============================================================================*/ [CLSCompliant(false)] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [System.Runtime.Versioning.NonVersionable] public static sbyte Max(sbyte val1, sbyte val2) { return (val1>=val2)?val1:val2; } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [System.Runtime.Versioning.NonVersionable] public static byte Max(byte val1, byte val2) { return (val1>=val2)?val1:val2; } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [System.Runtime.Versioning.NonVersionable] public static short Max(short val1, short val2) { return (val1>=val2)?val1:val2; } [CLSCompliant(false)] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [System.Runtime.Versioning.NonVersionable] public static ushort Max(ushort val1, ushort val2) { return (val1>=val2)?val1:val2; } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [System.Runtime.Versioning.NonVersionable] public static int Max(int val1, int val2) { return (val1>=val2)?val1:val2; } [CLSCompliant(false)] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [System.Runtime.Versioning.NonVersionable] public static uint Max(uint val1, uint val2) { return (val1>=val2)?val1:val2; } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [System.Runtime.Versioning.NonVersionable] public static long Max(long val1, long val2) { return (val1>=val2)?val1:val2; } [CLSCompliant(false)] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [System.Runtime.Versioning.NonVersionable] public static ulong Max(ulong val1, ulong val2) { return (val1>=val2)?val1:val2; } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] public static float Max(float val1, float val2) { if (val1 > val2) return val1; if (Single.IsNaN(val1)) return val1; return val2; } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] public static double Max(double val1, double val2) { if (val1 > val2) return val1; if (Double.IsNaN(val1)) return val1; return val2; } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] public static Decimal Max(Decimal val1, Decimal val2) { return Decimal.Max(val1,val2); } /*================================MIN========================================= **Returns the smaller of val1 and val2. ============================================================================*/ [CLSCompliant(false)] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [System.Runtime.Versioning.NonVersionable] public static sbyte Min(sbyte val1, sbyte val2) { return (val1<=val2)?val1:val2; } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [System.Runtime.Versioning.NonVersionable] public static byte Min(byte val1, byte val2) { return (val1<=val2)?val1:val2; } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [System.Runtime.Versioning.NonVersionable] public static short Min(short val1, short val2) { return (val1<=val2)?val1:val2; } [CLSCompliant(false)] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [System.Runtime.Versioning.NonVersionable] public static ushort Min(ushort val1, ushort val2) { return (val1<=val2)?val1:val2; } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [System.Runtime.Versioning.NonVersionable] public static int Min(int val1, int val2) { return (val1<=val2)?val1:val2; } [CLSCompliant(false)] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [System.Runtime.Versioning.NonVersionable] public static uint Min(uint val1, uint val2) { return (val1<=val2)?val1:val2; } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [System.Runtime.Versioning.NonVersionable] public static long Min(long val1, long val2) { return (val1<=val2)?val1:val2; } [CLSCompliant(false)] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [System.Runtime.Versioning.NonVersionable] public static ulong Min(ulong val1, ulong val2) { return (val1<=val2)?val1:val2; } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] public static float Min(float val1, float val2) { if (val1 < val2) return val1; if (Single.IsNaN(val1)) return val1; return val2; } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] public static double Min(double val1, double val2) { if (val1 < val2) return val1; if (Double.IsNaN(val1)) return val1; return val2; } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] public static Decimal Min(Decimal val1, Decimal val2) { return Decimal.Min(val1,val2); } /*=====================================Log====================================== ** ==============================================================================*/ public static double Log(double a, double newBase) { if (Double.IsNaN(a)) { return a; // IEEE 754-2008: NaN payload must be preserved } if (Double.IsNaN(newBase)) { return newBase; // IEEE 754-2008: NaN payload must be preserved } if (newBase == 1) return Double.NaN; if (a != 1 && (newBase == 0 || Double.IsPositiveInfinity(newBase))) return Double.NaN; return (Log(a)/Log(newBase)); } // Sign function for VB. Returns -1, 0, or 1 if the sign of the number // is negative, 0, or positive. Throws for floating point NaN's. [CLSCompliant(false)] public static int Sign(sbyte value) { if (value < 0) return -1; else if (value > 0) return 1; else return 0; } // Sign function for VB. Returns -1, 0, or 1 if the sign of the number // is negative, 0, or positive. Throws for floating point NaN's. public static int Sign(short value) { if (value < 0) return -1; else if (value > 0) return 1; else return 0; } // Sign function for VB. Returns -1, 0, or 1 if the sign of the number // is negative, 0, or positive. Throws for floating point NaN's. public static int Sign(int value) { if (value < 0) return -1; else if (value > 0) return 1; else return 0; } public static int Sign(long value) { if (value < 0) return -1; else if (value > 0) return 1; else return 0; } public static int Sign (float value) { if (value < 0) return -1; else if (value > 0) return 1; else if (value == 0) return 0; throw new ArithmeticException(Environment.GetResourceString("Arithmetic_NaN")); } public static int Sign(double value) { if (value < 0) return -1; else if (value > 0) return 1; else if (value == 0) return 0; throw new ArithmeticException(Environment.GetResourceString("Arithmetic_NaN")); } public static int Sign(Decimal value) { if (value < 0) return -1; else if (value > 0) return 1; else return 0; } public static long BigMul(int a, int b) { return ((long)a) * b; } public static int DivRem(int a, int b, out int result) { result = a%b; return a/b; } public static long DivRem(long a, long b, out long result) { result = a%b; return a/b; } } }
/* * Control.cs - Implementation of the * "System.Windows.Forms.StatusBar" class. * * Copyright (C) 2003 Southern Storm Software, Pty Ltd. * * Contributions from Simon Guindon * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ using System; using System.Collections; using System.ComponentModel; using System.Drawing; using System.Drawing.Text; using System.Windows.Forms; namespace System.Windows.Forms { public class StatusBar : Control { public event StatusBarDrawItemEventHandler DrawItem; public event StatusBarPanelClickEventHandler PanelClick; private StatusBarPanelCollection panels; private bool showPanels; private bool sizingGrip; public StatusBar() { Name = "StatusBar"; Height = 22; Dock = DockStyle.Bottom; showPanels = false; sizingGrip = true; BackColor = SystemColors.Control; panels = new StatusBarPanelCollection(this); } ~StatusBar() { Dispose(false); } /// Clean up any resources being used. protected override void Dispose(bool disposing) { if(disposing) { } base.Dispose(disposing); } protected override void OnPaint(PaintEventArgs e) { if (showPanels == false) { DrawSimpleText(e, 0, 0, Width, Height, Text); } else { int left = 0; Border3DStyle style = Border3DStyle.Sunken; if (panels.Count <1) { int panelWidth; if (sizingGrip == true) { panelWidth = Width - 16; } else { panelWidth = Width; } ControlPaint.DrawBorder3D(e.Graphics, 0, 2, panelWidth, Height - 2, Border3DStyle.SunkenOuter, Border3DSide.All); } else { for (int i=0;i<panels.Count;i++) { switch (panels[i].BorderStyle) { case StatusBarPanelBorderStyle.None: style = Border3DStyle.Flat; break; case StatusBarPanelBorderStyle.Raised: style = Border3DStyle.Raised; break; case StatusBarPanelBorderStyle.Sunken: style = Border3DStyle.SunkenOuter; break; } ControlPaint.DrawBorder3D(e.Graphics, left, 4, panels[i].Width, Height -4, style, Border3DSide.All); if (panels[i].Style == StatusBarPanelStyle.Text) { StringAlignment align = 0; switch (panels[i].Alignment) { case HorizontalAlignment.Center: align = StringAlignment.Center; break; case HorizontalAlignment.Left: align = StringAlignment.Near; break; case HorizontalAlignment.Right: align = StringAlignment.Far; break; } DrawSimpleText(e, left, 4, left + panels[i].Width, Height, panels[i].Text, align); } else { // Owner drawn StatusBarDrawItemEventArgs args = new StatusBarDrawItemEventArgs(e.Graphics, this.Font, new Rectangle(0, 0, panels[i].Width, Height), i, DrawItemState.None, panels[i]); OnDrawItem(args); } left += panels[i].Width +2; } } } if (sizingGrip == true) { ControlPaint.DrawSizeGrip(e.Graphics, BackColor, new Rectangle(Width - 16, Height - 16, Width, Height)); } base.OnPaint(e); } private void DrawSimpleText(PaintEventArgs e, int left, int top, int right, int bottom, string text) { DrawSimpleText(e, left, top, right, bottom, text, StringAlignment.Near); } private void DrawSimpleText(PaintEventArgs e, int left, int top, int right, int bottom, string text, StringAlignment align) { // Draw the text within the statusbar. Font font = Font; RectangleF layout = (RectangleF)Rectangle.FromLTRB(left, top, right, bottom); StringFormat format = new StringFormat(); format.Alignment = align; format.LineAlignment = StringAlignment.Center; if(text != null && text != String.Empty) { if(Enabled) { Brush brush = new SolidBrush(ForeColor); e.Graphics.DrawString(text, font, brush, layout, format); brush.Dispose(); } else { Brush brush = new SolidBrush(ForeColor); e.Graphics.DrawString(text, font, brush, layout, format); brush.Dispose(); } } } public override Color BackColor { get { return base.BackColor; } set { base.BackColor = value; } } public override Image BackgroundImage { get { return base.BackgroundImage; } set { base.BackgroundImage = value; } } public override DockStyle Dock { get { return base.Dock; } set { base.Dock = value; } } public override Font Font { get { return base.Font; } set { base.Font = value; } } #if CONFIG_COMPONENT_MODEL [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] #endif public StatusBarPanelCollection Panels { get { return panels; } } public bool ShowPanels { get { return showPanels; } set { showPanels = value; Invalidate(); } } public bool SizingGrip { get { return sizingGrip; } set { sizingGrip = value; Invalidate(); } } public override string Text { get { return base.Text; } set { base.Text = value; Invalidate(); } } protected override CreateParams CreateParams { get { return base.CreateParams; } } protected override ImeMode DefaultImeMode { get { return base.DefaultImeMode; } } protected override Size DefaultSize { get { return base.DefaultSize; } } protected override void CreateHandle() { base.CreateHandle(); } protected virtual void OnDrawItem(StatusBarDrawItemEventArgs e) { if (DrawItem != null) { DrawItem(this, e); } } protected override void OnHandleCreated(EventArgs e) { base.OnHandleCreated(e); } protected override void OnHandleDestroyed(EventArgs e) { base.OnHandleDestroyed(e); } protected override void OnLayout(LayoutEventArgs e) { base.OnLayout(e); } protected override void OnMouseUp(MouseEventArgs e) { int left = 0; for (int i=0;i < panels.Count;i++) { if (e.X >= left && e.X < left + panels[i].Width) { StatusBarPanelClickEventArgs args = new StatusBarPanelClickEventArgs(panels[i], e.Button, e.Clicks, e.X, e.Y); OnPanelClick(args); } left += panels[i].Width + 2; } base.OnMouseUp(e); } protected override void OnMouseDown(MouseEventArgs e) { base.OnMouseDown(e); } protected virtual void OnPanelClick(StatusBarPanelClickEventArgs e) { if (PanelClick != null) { PanelClick(this, e); } } protected override void OnResize(EventArgs e) { Invalidate(); base.OnResize(e); } public override String ToString() { return base.ToString() + " Panels.Count: " + panels.Count.ToString(); } #if !CONFIG_COMPACT_FORMS // Process a message. protected override void WndProc(ref Message m) { base.WndProc(ref m); } #endif // !CONFIG_COMPACT_FORMS public class StatusBarPanelCollection : IList { private StatusBar owner; private ArrayList list; public StatusBarPanelCollection(StatusBar owner) { this.owner = owner; list = new ArrayList(); } // Implement the ICollection interface. void ICollection.CopyTo(Array array, int index) { List.CopyTo(array, index); } public virtual int Count { get { return List.Count; } } bool ICollection.IsSynchronized { get { return false; } } Object ICollection.SyncRoot { get { return this; } } // Implement the IEnumerable interface. public IEnumerator GetEnumerator() { return List.GetEnumerator(); } // Determine if the collection is read-only. public bool IsReadOnly { get { return false; } } bool IList.IsFixedSize { get { return false; } } // Get the array list that underlies this collection Object IList.this[int index] { get { return List[index]; } set { List[index] = value; } } public StatusBarPanel this[int index] { get { return (StatusBarPanel)List[index]; } set { List[index] = value; } } protected virtual ArrayList List { get { return list; } } int IList.Add(Object value) { return Add(value as StatusBarPanel); } public virtual int Add(StatusBarPanel value) { int result = list.Add(value); value.parent = owner; owner.Invalidate(); return result; } public virtual StatusBarPanel Add(string text) { StatusBarPanel panel = new StatusBarPanel(); panel.Text = text; List.Add(panel); return panel; } public virtual void AddRange(StatusBarPanel[] panels) { List.AddRange(panels); owner.Invalidate(); } public virtual void Clear() { List.Clear(); owner.Invalidate(); } bool IList.Contains(Object value) { return List.Contains(value); } public bool Contains(StatusBarPanel panel) { return List.Contains(panel); } int IList.IndexOf(Object value) { return List.IndexOf(value); } public int IndexOf(StatusBarPanel panel) { return List.IndexOf(panel); } void IList.Insert(int index, Object value) { List.Insert(index, value); owner.Invalidate(); } public virtual void Insert(int index, StatusBarPanel value) { List.Insert(index, value); } void IList.Remove(Object value) { List.Remove(value); owner.Invalidate(); } public virtual void Remove(StatusBarPanel value) { List.Remove(value); } void IList.RemoveAt(int index) { List.RemoveAt(index); } } } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: src/proto/grpc/testing/stats.proto #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace Grpc.Testing { /// <summary>Holder for reflection information generated from src/proto/grpc/testing/stats.proto</summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public static partial class StatsReflection { #region Descriptor /// <summary>File descriptor for src/proto/grpc/testing/stats.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static StatsReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "CiJzcmMvcHJvdG8vZ3JwYy90ZXN0aW5nL3N0YXRzLnByb3RvEgxncnBjLnRl", "c3RpbmciSwoLU2VydmVyU3RhdHMSFAoMdGltZV9lbGFwc2VkGAEgASgBEhEK", "CXRpbWVfdXNlchgCIAEoARITCgt0aW1lX3N5c3RlbRgDIAEoASI7Cg9IaXN0", "b2dyYW1QYXJhbXMSEgoKcmVzb2x1dGlvbhgBIAEoARIUCgxtYXhfcG9zc2li", "bGUYAiABKAEidwoNSGlzdG9ncmFtRGF0YRIOCgZidWNrZXQYASADKA0SEAoI", "bWluX3NlZW4YAiABKAESEAoIbWF4X3NlZW4YAyABKAESCwoDc3VtGAQgASgB", "EhYKDnN1bV9vZl9zcXVhcmVzGAUgASgBEg0KBWNvdW50GAYgASgBInsKC0Ns", "aWVudFN0YXRzEi4KCWxhdGVuY2llcxgBIAEoCzIbLmdycGMudGVzdGluZy5I", "aXN0b2dyYW1EYXRhEhQKDHRpbWVfZWxhcHNlZBgCIAEoARIRCgl0aW1lX3Vz", "ZXIYAyABKAESEwoLdGltZV9zeXN0ZW0YBCABKAFiBnByb3RvMw==")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { }, new pbr::GeneratedCodeInfo(null, new pbr::GeneratedCodeInfo[] { new pbr::GeneratedCodeInfo(typeof(global::Grpc.Testing.ServerStats), global::Grpc.Testing.ServerStats.Parser, new[]{ "TimeElapsed", "TimeUser", "TimeSystem" }, null, null, null), new pbr::GeneratedCodeInfo(typeof(global::Grpc.Testing.HistogramParams), global::Grpc.Testing.HistogramParams.Parser, new[]{ "Resolution", "MaxPossible" }, null, null, null), new pbr::GeneratedCodeInfo(typeof(global::Grpc.Testing.HistogramData), global::Grpc.Testing.HistogramData.Parser, new[]{ "Bucket", "MinSeen", "MaxSeen", "Sum", "SumOfSquares", "Count" }, null, null, null), new pbr::GeneratedCodeInfo(typeof(global::Grpc.Testing.ClientStats), global::Grpc.Testing.ClientStats.Parser, new[]{ "Latencies", "TimeElapsed", "TimeUser", "TimeSystem" }, null, null, null) })); } #endregion } #region Messages [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public sealed partial class ServerStats : pb::IMessage<ServerStats> { private static readonly pb::MessageParser<ServerStats> _parser = new pb::MessageParser<ServerStats>(() => new ServerStats()); public static pb::MessageParser<ServerStats> Parser { get { return _parser; } } public static pbr::MessageDescriptor Descriptor { get { return global::Grpc.Testing.StatsReflection.Descriptor.MessageTypes[0]; } } pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } public ServerStats() { OnConstruction(); } partial void OnConstruction(); public ServerStats(ServerStats other) : this() { timeElapsed_ = other.timeElapsed_; timeUser_ = other.timeUser_; timeSystem_ = other.timeSystem_; } public ServerStats Clone() { return new ServerStats(this); } /// <summary>Field number for the "time_elapsed" field.</summary> public const int TimeElapsedFieldNumber = 1; private double timeElapsed_; /// <summary> /// wall clock time change in seconds since last reset /// </summary> public double TimeElapsed { get { return timeElapsed_; } set { timeElapsed_ = value; } } /// <summary>Field number for the "time_user" field.</summary> public const int TimeUserFieldNumber = 2; private double timeUser_; /// <summary> /// change in user time (in seconds) used by the server since last reset /// </summary> public double TimeUser { get { return timeUser_; } set { timeUser_ = value; } } /// <summary>Field number for the "time_system" field.</summary> public const int TimeSystemFieldNumber = 3; private double timeSystem_; /// <summary> /// change in server time (in seconds) used by the server process and all /// threads since last reset /// </summary> public double TimeSystem { get { return timeSystem_; } set { timeSystem_ = value; } } public override bool Equals(object other) { return Equals(other as ServerStats); } public bool Equals(ServerStats other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (TimeElapsed != other.TimeElapsed) return false; if (TimeUser != other.TimeUser) return false; if (TimeSystem != other.TimeSystem) return false; return true; } public override int GetHashCode() { int hash = 1; if (TimeElapsed != 0D) hash ^= TimeElapsed.GetHashCode(); if (TimeUser != 0D) hash ^= TimeUser.GetHashCode(); if (TimeSystem != 0D) hash ^= TimeSystem.GetHashCode(); return hash; } public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } public void WriteTo(pb::CodedOutputStream output) { if (TimeElapsed != 0D) { output.WriteRawTag(9); output.WriteDouble(TimeElapsed); } if (TimeUser != 0D) { output.WriteRawTag(17); output.WriteDouble(TimeUser); } if (TimeSystem != 0D) { output.WriteRawTag(25); output.WriteDouble(TimeSystem); } } public int CalculateSize() { int size = 0; if (TimeElapsed != 0D) { size += 1 + 8; } if (TimeUser != 0D) { size += 1 + 8; } if (TimeSystem != 0D) { size += 1 + 8; } return size; } public void MergeFrom(ServerStats other) { if (other == null) { return; } if (other.TimeElapsed != 0D) { TimeElapsed = other.TimeElapsed; } if (other.TimeUser != 0D) { TimeUser = other.TimeUser; } if (other.TimeSystem != 0D) { TimeSystem = other.TimeSystem; } } public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 9: { TimeElapsed = input.ReadDouble(); break; } case 17: { TimeUser = input.ReadDouble(); break; } case 25: { TimeSystem = input.ReadDouble(); break; } } } } } /// <summary> /// Histogram params based on grpc/support/histogram.c /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public sealed partial class HistogramParams : pb::IMessage<HistogramParams> { private static readonly pb::MessageParser<HistogramParams> _parser = new pb::MessageParser<HistogramParams>(() => new HistogramParams()); public static pb::MessageParser<HistogramParams> Parser { get { return _parser; } } public static pbr::MessageDescriptor Descriptor { get { return global::Grpc.Testing.StatsReflection.Descriptor.MessageTypes[1]; } } pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } public HistogramParams() { OnConstruction(); } partial void OnConstruction(); public HistogramParams(HistogramParams other) : this() { resolution_ = other.resolution_; maxPossible_ = other.maxPossible_; } public HistogramParams Clone() { return new HistogramParams(this); } /// <summary>Field number for the "resolution" field.</summary> public const int ResolutionFieldNumber = 1; private double resolution_; /// <summary> /// first bucket is [0, 1 + resolution) /// </summary> public double Resolution { get { return resolution_; } set { resolution_ = value; } } /// <summary>Field number for the "max_possible" field.</summary> public const int MaxPossibleFieldNumber = 2; private double maxPossible_; /// <summary> /// use enough buckets to allow this value /// </summary> public double MaxPossible { get { return maxPossible_; } set { maxPossible_ = value; } } public override bool Equals(object other) { return Equals(other as HistogramParams); } public bool Equals(HistogramParams other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Resolution != other.Resolution) return false; if (MaxPossible != other.MaxPossible) return false; return true; } public override int GetHashCode() { int hash = 1; if (Resolution != 0D) hash ^= Resolution.GetHashCode(); if (MaxPossible != 0D) hash ^= MaxPossible.GetHashCode(); return hash; } public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } public void WriteTo(pb::CodedOutputStream output) { if (Resolution != 0D) { output.WriteRawTag(9); output.WriteDouble(Resolution); } if (MaxPossible != 0D) { output.WriteRawTag(17); output.WriteDouble(MaxPossible); } } public int CalculateSize() { int size = 0; if (Resolution != 0D) { size += 1 + 8; } if (MaxPossible != 0D) { size += 1 + 8; } return size; } public void MergeFrom(HistogramParams other) { if (other == null) { return; } if (other.Resolution != 0D) { Resolution = other.Resolution; } if (other.MaxPossible != 0D) { MaxPossible = other.MaxPossible; } } public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 9: { Resolution = input.ReadDouble(); break; } case 17: { MaxPossible = input.ReadDouble(); break; } } } } } /// <summary> /// Histogram data based on grpc/support/histogram.c /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public sealed partial class HistogramData : pb::IMessage<HistogramData> { private static readonly pb::MessageParser<HistogramData> _parser = new pb::MessageParser<HistogramData>(() => new HistogramData()); public static pb::MessageParser<HistogramData> Parser { get { return _parser; } } public static pbr::MessageDescriptor Descriptor { get { return global::Grpc.Testing.StatsReflection.Descriptor.MessageTypes[2]; } } pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } public HistogramData() { OnConstruction(); } partial void OnConstruction(); public HistogramData(HistogramData other) : this() { bucket_ = other.bucket_.Clone(); minSeen_ = other.minSeen_; maxSeen_ = other.maxSeen_; sum_ = other.sum_; sumOfSquares_ = other.sumOfSquares_; count_ = other.count_; } public HistogramData Clone() { return new HistogramData(this); } /// <summary>Field number for the "bucket" field.</summary> public const int BucketFieldNumber = 1; private static readonly pb::FieldCodec<uint> _repeated_bucket_codec = pb::FieldCodec.ForUInt32(10); private readonly pbc::RepeatedField<uint> bucket_ = new pbc::RepeatedField<uint>(); public pbc::RepeatedField<uint> Bucket { get { return bucket_; } } /// <summary>Field number for the "min_seen" field.</summary> public const int MinSeenFieldNumber = 2; private double minSeen_; public double MinSeen { get { return minSeen_; } set { minSeen_ = value; } } /// <summary>Field number for the "max_seen" field.</summary> public const int MaxSeenFieldNumber = 3; private double maxSeen_; public double MaxSeen { get { return maxSeen_; } set { maxSeen_ = value; } } /// <summary>Field number for the "sum" field.</summary> public const int SumFieldNumber = 4; private double sum_; public double Sum { get { return sum_; } set { sum_ = value; } } /// <summary>Field number for the "sum_of_squares" field.</summary> public const int SumOfSquaresFieldNumber = 5; private double sumOfSquares_; public double SumOfSquares { get { return sumOfSquares_; } set { sumOfSquares_ = value; } } /// <summary>Field number for the "count" field.</summary> public const int CountFieldNumber = 6; private double count_; public double Count { get { return count_; } set { count_ = value; } } public override bool Equals(object other) { return Equals(other as HistogramData); } public bool Equals(HistogramData other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if(!bucket_.Equals(other.bucket_)) return false; if (MinSeen != other.MinSeen) return false; if (MaxSeen != other.MaxSeen) return false; if (Sum != other.Sum) return false; if (SumOfSquares != other.SumOfSquares) return false; if (Count != other.Count) return false; return true; } public override int GetHashCode() { int hash = 1; hash ^= bucket_.GetHashCode(); if (MinSeen != 0D) hash ^= MinSeen.GetHashCode(); if (MaxSeen != 0D) hash ^= MaxSeen.GetHashCode(); if (Sum != 0D) hash ^= Sum.GetHashCode(); if (SumOfSquares != 0D) hash ^= SumOfSquares.GetHashCode(); if (Count != 0D) hash ^= Count.GetHashCode(); return hash; } public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } public void WriteTo(pb::CodedOutputStream output) { bucket_.WriteTo(output, _repeated_bucket_codec); if (MinSeen != 0D) { output.WriteRawTag(17); output.WriteDouble(MinSeen); } if (MaxSeen != 0D) { output.WriteRawTag(25); output.WriteDouble(MaxSeen); } if (Sum != 0D) { output.WriteRawTag(33); output.WriteDouble(Sum); } if (SumOfSquares != 0D) { output.WriteRawTag(41); output.WriteDouble(SumOfSquares); } if (Count != 0D) { output.WriteRawTag(49); output.WriteDouble(Count); } } public int CalculateSize() { int size = 0; size += bucket_.CalculateSize(_repeated_bucket_codec); if (MinSeen != 0D) { size += 1 + 8; } if (MaxSeen != 0D) { size += 1 + 8; } if (Sum != 0D) { size += 1 + 8; } if (SumOfSquares != 0D) { size += 1 + 8; } if (Count != 0D) { size += 1 + 8; } return size; } public void MergeFrom(HistogramData other) { if (other == null) { return; } bucket_.Add(other.bucket_); if (other.MinSeen != 0D) { MinSeen = other.MinSeen; } if (other.MaxSeen != 0D) { MaxSeen = other.MaxSeen; } if (other.Sum != 0D) { Sum = other.Sum; } if (other.SumOfSquares != 0D) { SumOfSquares = other.SumOfSquares; } if (other.Count != 0D) { Count = other.Count; } } public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: case 8: { bucket_.AddEntriesFrom(input, _repeated_bucket_codec); break; } case 17: { MinSeen = input.ReadDouble(); break; } case 25: { MaxSeen = input.ReadDouble(); break; } case 33: { Sum = input.ReadDouble(); break; } case 41: { SumOfSquares = input.ReadDouble(); break; } case 49: { Count = input.ReadDouble(); break; } } } } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public sealed partial class ClientStats : pb::IMessage<ClientStats> { private static readonly pb::MessageParser<ClientStats> _parser = new pb::MessageParser<ClientStats>(() => new ClientStats()); public static pb::MessageParser<ClientStats> Parser { get { return _parser; } } public static pbr::MessageDescriptor Descriptor { get { return global::Grpc.Testing.StatsReflection.Descriptor.MessageTypes[3]; } } pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } public ClientStats() { OnConstruction(); } partial void OnConstruction(); public ClientStats(ClientStats other) : this() { Latencies = other.latencies_ != null ? other.Latencies.Clone() : null; timeElapsed_ = other.timeElapsed_; timeUser_ = other.timeUser_; timeSystem_ = other.timeSystem_; } public ClientStats Clone() { return new ClientStats(this); } /// <summary>Field number for the "latencies" field.</summary> public const int LatenciesFieldNumber = 1; private global::Grpc.Testing.HistogramData latencies_; /// <summary> /// Latency histogram. Data points are in nanoseconds. /// </summary> public global::Grpc.Testing.HistogramData Latencies { get { return latencies_; } set { latencies_ = value; } } /// <summary>Field number for the "time_elapsed" field.</summary> public const int TimeElapsedFieldNumber = 2; private double timeElapsed_; /// <summary> /// See ServerStats for details. /// </summary> public double TimeElapsed { get { return timeElapsed_; } set { timeElapsed_ = value; } } /// <summary>Field number for the "time_user" field.</summary> public const int TimeUserFieldNumber = 3; private double timeUser_; public double TimeUser { get { return timeUser_; } set { timeUser_ = value; } } /// <summary>Field number for the "time_system" field.</summary> public const int TimeSystemFieldNumber = 4; private double timeSystem_; public double TimeSystem { get { return timeSystem_; } set { timeSystem_ = value; } } public override bool Equals(object other) { return Equals(other as ClientStats); } public bool Equals(ClientStats other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (!object.Equals(Latencies, other.Latencies)) return false; if (TimeElapsed != other.TimeElapsed) return false; if (TimeUser != other.TimeUser) return false; if (TimeSystem != other.TimeSystem) return false; return true; } public override int GetHashCode() { int hash = 1; if (latencies_ != null) hash ^= Latencies.GetHashCode(); if (TimeElapsed != 0D) hash ^= TimeElapsed.GetHashCode(); if (TimeUser != 0D) hash ^= TimeUser.GetHashCode(); if (TimeSystem != 0D) hash ^= TimeSystem.GetHashCode(); return hash; } public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } public void WriteTo(pb::CodedOutputStream output) { if (latencies_ != null) { output.WriteRawTag(10); output.WriteMessage(Latencies); } if (TimeElapsed != 0D) { output.WriteRawTag(17); output.WriteDouble(TimeElapsed); } if (TimeUser != 0D) { output.WriteRawTag(25); output.WriteDouble(TimeUser); } if (TimeSystem != 0D) { output.WriteRawTag(33); output.WriteDouble(TimeSystem); } } public int CalculateSize() { int size = 0; if (latencies_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Latencies); } if (TimeElapsed != 0D) { size += 1 + 8; } if (TimeUser != 0D) { size += 1 + 8; } if (TimeSystem != 0D) { size += 1 + 8; } return size; } public void MergeFrom(ClientStats other) { if (other == null) { return; } if (other.latencies_ != null) { if (latencies_ == null) { latencies_ = new global::Grpc.Testing.HistogramData(); } Latencies.MergeFrom(other.Latencies); } if (other.TimeElapsed != 0D) { TimeElapsed = other.TimeElapsed; } if (other.TimeUser != 0D) { TimeUser = other.TimeUser; } if (other.TimeSystem != 0D) { TimeSystem = other.TimeSystem; } } public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { if (latencies_ == null) { latencies_ = new global::Grpc.Testing.HistogramData(); } input.ReadMessage(latencies_); break; } case 17: { TimeElapsed = input.ReadDouble(); break; } case 25: { TimeUser = input.ReadDouble(); break; } case 33: { TimeSystem = input.ReadDouble(); break; } } } } } #endregion } #endregion Designer generated code
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Runtime; using System.ServiceModel.Channels; using System.ServiceModel.Description; using System.ServiceModel.Diagnostics; using System.ServiceModel.Security; using System.Threading.Tasks; namespace System.ServiceModel { public abstract class ChannelFactory : CommunicationObject, IChannelFactory, IDisposable { private string _configurationName; private IChannelFactory _innerFactory; private ServiceEndpoint _serviceEndpoint; private ClientCredentials _readOnlyClientCredentials; private object _openLock = new object(); //Overload for activation DuplexChannelFactory protected ChannelFactory() : base() { TraceUtility.SetEtwProviderId(); this.TraceOpenAndClose = true; } public ClientCredentials Credentials { get { if (this.Endpoint == null) return null; if (this.State == CommunicationState.Created || this.State == CommunicationState.Opening) { return EnsureCredentials(this.Endpoint); } else { if (_readOnlyClientCredentials == null) { ClientCredentials c = new ClientCredentials(); c.MakeReadOnly(); _readOnlyClientCredentials = c; } return _readOnlyClientCredentials; } } } protected override TimeSpan DefaultCloseTimeout { get { if (this.Endpoint != null && this.Endpoint.Binding != null) { return this.Endpoint.Binding.CloseTimeout; } else { return ServiceDefaults.CloseTimeout; } } } protected override TimeSpan DefaultOpenTimeout { get { if (this.Endpoint != null && this.Endpoint.Binding != null) { return this.Endpoint.Binding.OpenTimeout; } else { return ServiceDefaults.OpenTimeout; } } } public ServiceEndpoint Endpoint { get { return _serviceEndpoint; } } internal IChannelFactory InnerFactory { get { return _innerFactory; } } // This boolean is used to determine if we should read ahead by a single // Message for IDuplexSessionChannels in order to detect null and // autoclose the underlying channel in that case. // Currently only accessed from the Send activity. [Fx.Tag.FriendAccessAllowed("System.ServiceModel.Activities")] internal bool UseActiveAutoClose { get; set; } protected internal void EnsureOpened() { base.ThrowIfDisposed(); if (this.State != CommunicationState.Opened) { lock (_openLock) { if (this.State != CommunicationState.Opened) { this.Open(); } } } } // configurationName can be: // 1. null: don't bind any per-endpoint config (load common behaviors only) // 2. "*" (wildcard): match any endpoint config provided there's exactly 1 // 3. anything else (including ""): match the endpoint config with the same name protected virtual void ApplyConfiguration(string configurationName) { // This method is in the public contract but is not supported on CORECLR or NETNATIVE if (!String.IsNullOrEmpty(configurationName)) { throw ExceptionHelper.PlatformNotSupported(); } } protected abstract ServiceEndpoint CreateDescription(); internal EndpointAddress CreateEndpointAddress(ServiceEndpoint endpoint) { if (endpoint.Address == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.SFxChannelFactoryEndpointAddressUri)); } return endpoint.Address; } protected virtual IChannelFactory CreateFactory() { if (this.Endpoint == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.SFxChannelFactoryCannotCreateFactoryWithoutDescription)); } if (this.Endpoint.Binding == null) { if (_configurationName != null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.SFxChannelFactoryNoBindingFoundInConfig1, _configurationName))); } else { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.SFxChannelFactoryNoBindingFoundInConfigOrCode)); } } return ServiceChannelFactory.BuildChannelFactory(this.Endpoint, this.UseActiveAutoClose); } void IDisposable.Dispose() { this.Close(); } private void EnsureSecurityCredentialsManager(ServiceEndpoint endpoint) { Fx.Assert(this.State == CommunicationState.Created || this.State == CommunicationState.Opening, ""); if (endpoint.Behaviors.Find<SecurityCredentialsManager>() == null) { endpoint.Behaviors.Add(new ClientCredentials()); } } private ClientCredentials EnsureCredentials(ServiceEndpoint endpoint) { Fx.Assert(this.State == CommunicationState.Created || this.State == CommunicationState.Opening, ""); ClientCredentials c = endpoint.Behaviors.Find<ClientCredentials>(); if (c == null) { c = new ClientCredentials(); endpoint.Behaviors.Add(c); } return c; } public T GetProperty<T>() where T : class { if (_innerFactory != null) { return _innerFactory.GetProperty<T>(); } else { return null; } } internal bool HasDuplexOperations() { OperationDescriptionCollection operations = this.Endpoint.Contract.Operations; for (int i = 0; i < operations.Count; i++) { OperationDescription operation = operations[i]; if (operation.IsServerInitiated()) { return true; } } return false; } protected void InitializeEndpoint(string configurationName, EndpointAddress address) { _serviceEndpoint = this.CreateDescription(); ServiceEndpoint serviceEndpointFromConfig = null; // Project N and K do not support System.Configuration, but this method is part of Windows Store contract. // The configurationName==null path occurs in normal use. if (configurationName != null) { throw ExceptionHelper.PlatformNotSupported(); // serviceEndpointFromConfig = ConfigLoader.LookupEndpoint(configurationName, address, this.serviceEndpoint.Contract); } if (serviceEndpointFromConfig != null) { _serviceEndpoint = serviceEndpointFromConfig; } else { if (address != null) { this.Endpoint.Address = address; } ApplyConfiguration(configurationName); } _configurationName = configurationName; EnsureSecurityCredentialsManager(_serviceEndpoint); } protected void InitializeEndpoint(ServiceEndpoint endpoint) { if (endpoint == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("endpoint"); } _serviceEndpoint = endpoint; ApplyConfiguration(null); EnsureSecurityCredentialsManager(_serviceEndpoint); } protected void InitializeEndpoint(Binding binding, EndpointAddress address) { _serviceEndpoint = this.CreateDescription(); if (binding != null) { this.Endpoint.Binding = binding; } if (address != null) { this.Endpoint.Address = address; } ApplyConfiguration(null); EnsureSecurityCredentialsManager(_serviceEndpoint); } protected override void OnOpened() { // if a client credentials has been configured cache a readonly snapshot of it if (this.Endpoint != null) { ClientCredentials credentials = this.Endpoint.Behaviors.Find<ClientCredentials>(); if (credentials != null) { ClientCredentials credentialsCopy = credentials.Clone(); credentialsCopy.MakeReadOnly(); _readOnlyClientCredentials = credentialsCopy; } } base.OnOpened(); } protected override void OnAbort() { if (_innerFactory != null) { _innerFactory.Abort(); } } protected override IAsyncResult OnBeginClose(TimeSpan timeout, AsyncCallback callback, object state) { return CommunicationObjectInternal.OnBeginClose(this, timeout, callback, state); } protected override void OnEndClose(IAsyncResult result) { CommunicationObjectInternal.OnEnd(result); } internal protected override async Task OnCloseAsync(TimeSpan timeout) { if (_innerFactory != null) { await CloseOtherAsync(_innerFactory, timeout); } } protected override IAsyncResult OnBeginOpen(TimeSpan timeout, AsyncCallback callback, object state) { return CommunicationObjectInternal.OnBeginOpen(this, timeout, callback, state); } protected override void OnEndOpen(IAsyncResult result) { CommunicationObjectInternal.OnEnd(result); } protected internal override async Task OnOpenAsync(TimeSpan timeout) { if (_innerFactory != null) { await OpenOtherAsync(_innerFactory, timeout); } } protected override void OnClose(TimeSpan timeout) { if (_innerFactory != null) { _innerFactory.Close(timeout); } } protected override void OnOpen(TimeSpan timeout) { _innerFactory.Open(timeout); } protected override void OnOpening() { base.OnOpening(); _innerFactory = CreateFactory(); if (WcfEventSource.Instance.ChannelFactoryCreatedIsEnabled()) { WcfEventSource.Instance.ChannelFactoryCreated(this); } if (_innerFactory == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.InnerChannelFactoryWasNotSet)); } } public class ChannelFactory<TChannel> : ChannelFactory, IChannelFactory<TChannel> { private InstanceContext _callbackInstance; private Type _channelType; private TypeLoader _typeLoader; private Type _callbackType; //Overload for activation DuplexChannelFactory protected ChannelFactory(Type channelType) : base() { if (channelType == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("channelType"); } if (!channelType.IsInterface()) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.SFxChannelFactoryTypeMustBeInterface)); } _channelType = channelType; } // TChannel provides ContractDescription public ChannelFactory() : this(typeof(TChannel)) { using (ServiceModelActivity activity = DiagnosticUtility.ShouldUseActivity ? ServiceModelActivity.CreateBoundedActivity() : null) { if (DiagnosticUtility.ShouldUseActivity) { ServiceModelActivity.Start(activity, SR.Format(SR.ActivityConstructChannelFactory, typeof(TChannel).FullName), ActivityType.Construct); } this.InitializeEndpoint((string)null, null); } } // TChannel provides ContractDescription, attr/config [TChannel,name] provides Address,Binding public ChannelFactory(string endpointConfigurationName) : this(endpointConfigurationName, null) { } // TChannel provides ContractDescription, attr/config [TChannel,name] provides Binding, provide Address explicitly public ChannelFactory(string endpointConfigurationName, EndpointAddress remoteAddress) : this(typeof(TChannel)) { using (ServiceModelActivity activity = DiagnosticUtility.ShouldUseActivity ? ServiceModelActivity.CreateBoundedActivity() : null) { if (DiagnosticUtility.ShouldUseActivity) { ServiceModelActivity.Start(activity, SR.Format(SR.ActivityConstructChannelFactory, typeof(TChannel).FullName), ActivityType.Construct); } if (endpointConfigurationName == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("endpointConfigurationName"); } this.InitializeEndpoint(endpointConfigurationName, remoteAddress); } } // TChannel provides ContractDescription, attr/config [TChannel,name] provides Address,Binding public ChannelFactory(Binding binding) : this(binding, (EndpointAddress)null) { } public ChannelFactory(Binding binding, String remoteAddress) : this(binding, new EndpointAddress(remoteAddress)) { } // TChannel provides ContractDescription, provide Address,Binding explicitly public ChannelFactory(Binding binding, EndpointAddress remoteAddress) : this(typeof(TChannel)) { using (ServiceModelActivity activity = DiagnosticUtility.ShouldUseActivity ? ServiceModelActivity.CreateBoundedActivity() : null) { if (DiagnosticUtility.ShouldUseActivity) { ServiceModelActivity.Start(activity, SR.Format(SR.ActivityConstructChannelFactory, typeof(TChannel).FullName), ActivityType.Construct); } if (binding == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("binding"); } this.InitializeEndpoint(binding, remoteAddress); } } // provide ContractDescription,Address,Binding explicitly public ChannelFactory(ServiceEndpoint endpoint) : this(typeof(TChannel)) { using (ServiceModelActivity activity = DiagnosticUtility.ShouldUseActivity ? ServiceModelActivity.CreateBoundedActivity() : null) { if (DiagnosticUtility.ShouldUseActivity) { ServiceModelActivity.Start(activity, SR.Format(SR.ActivityConstructChannelFactory, typeof(TChannel).FullName), ActivityType.Construct); } if (endpoint == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("endpoint"); } this.InitializeEndpoint(endpoint); } } internal InstanceContext CallbackInstance { get { return _callbackInstance; } set { _callbackInstance = value; } } internal Type CallbackType { get { return _callbackType; } set { _callbackType = value; } } internal ServiceChannelFactory ServiceChannelFactory { get { return (ServiceChannelFactory)InnerFactory; } } internal TypeLoader TypeLoader { get { if (_typeLoader == null) { _typeLoader = new TypeLoader(); } return _typeLoader; } } public TChannel CreateChannel(EndpointAddress address) { if (address == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("address"); } return CreateChannel(address, address.Uri); } public virtual TChannel CreateChannel(EndpointAddress address, Uri via) { bool traceOpenAndClose = this.TraceOpenAndClose; try { if (address == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("address"); } if (this.HasDuplexOperations()) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.SFxCreateNonDuplexChannel1, this.Endpoint.Contract.Name))); } EnsureOpened(); return (TChannel)this.ServiceChannelFactory.CreateChannel<TChannel>(address, via); } finally { this.TraceOpenAndClose = traceOpenAndClose; } } public TChannel CreateChannel() { return CreateChannel(this.CreateEndpointAddress(this.Endpoint), null); } protected override ServiceEndpoint CreateDescription() { ContractDescription contractDescription = this.TypeLoader.LoadContractDescription(_channelType); ServiceEndpoint endpoint = new ServiceEndpoint(contractDescription); ReflectOnCallbackInstance(endpoint); this.TypeLoader.AddBehaviorsSFx(endpoint, _channelType); return endpoint; } private void ReflectOnCallbackInstance(ServiceEndpoint endpoint) { if (_callbackType != null) { if (endpoint.Contract.CallbackContractType == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.SfxCallbackTypeCannotBeNull, endpoint.Contract.ContractType.FullName))); } this.TypeLoader.AddBehaviorsFromImplementationType(endpoint, _callbackType); } else if (this.CallbackInstance != null && this.CallbackInstance.UserObject != null) { if (endpoint.Contract.CallbackContractType == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.SfxCallbackTypeCannotBeNull, endpoint.Contract.ContractType.FullName))); } object implementation = this.CallbackInstance.UserObject; Type implementationType = implementation.GetType(); this.TypeLoader.AddBehaviorsFromImplementationType(endpoint, implementationType); IEndpointBehavior channelBehavior = implementation as IEndpointBehavior; if (channelBehavior != null) { endpoint.Behaviors.Add(channelBehavior); } IContractBehavior contractBehavior = implementation as IContractBehavior; if (contractBehavior != null) { endpoint.Contract.Behaviors.Add(contractBehavior); } } } //Static funtions to create channels protected static TChannel CreateChannel(String endpointConfigurationName) { ChannelFactory<TChannel> channelFactory = new ChannelFactory<TChannel>(endpointConfigurationName); if (channelFactory.HasDuplexOperations()) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.SFxInvalidStaticOverloadCalledForDuplexChannelFactory1, channelFactory._channelType.Name))); } TChannel channel = channelFactory.CreateChannel(); SetFactoryToAutoClose(channel); return channel; } public static TChannel CreateChannel(Binding binding, EndpointAddress endpointAddress) { ChannelFactory<TChannel> channelFactory = new ChannelFactory<TChannel>(binding, endpointAddress); if (channelFactory.HasDuplexOperations()) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.SFxInvalidStaticOverloadCalledForDuplexChannelFactory1, channelFactory._channelType.Name))); } TChannel channel = channelFactory.CreateChannel(); SetFactoryToAutoClose(channel); return channel; } public static TChannel CreateChannel(Binding binding, EndpointAddress endpointAddress, Uri via) { ChannelFactory<TChannel> channelFactory = new ChannelFactory<TChannel>(binding); if (channelFactory.HasDuplexOperations()) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.SFxInvalidStaticOverloadCalledForDuplexChannelFactory1, channelFactory._channelType.Name))); } TChannel channel = channelFactory.CreateChannel(endpointAddress, via); SetFactoryToAutoClose(channel); return channel; } internal static void SetFactoryToAutoClose(TChannel channel) { //Set the Channel to auto close its ChannelFactory. ServiceChannel serviceChannel = ServiceChannelFactory.GetServiceChannel(channel); serviceChannel.CloseFactory = true; } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; namespace Fonlow.TraceHub.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create /// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
namespace Webhooks.API; public class Startup { public IConfiguration Configuration { get; } public Startup(IConfiguration configuration) { Configuration = configuration; } public IServiceProvider ConfigureServices(IServiceCollection services) { services .AddAppInsight(Configuration) .AddCustomRouting(Configuration) .AddCustomDbContext(Configuration) .AddSwagger(Configuration) .AddCustomHealthCheck(Configuration) .AddDevspaces() .AddHttpClientServices(Configuration) .AddIntegrationServices(Configuration) .AddEventBus(Configuration) .AddCustomAuthentication(Configuration) .AddSingleton<IHttpContextAccessor, HttpContextAccessor>() .AddTransient<IIdentityService, IdentityService>() .AddTransient<IGrantUrlTesterService, GrantUrlTesterService>() .AddTransient<IWebhooksRetriever, WebhooksRetriever>() .AddTransient<IWebhooksSender, WebhooksSender>(); var container = new ContainerBuilder(); container.Populate(services); return new AutofacServiceProvider(container.Build()); } public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory) { var pathBase = Configuration["PATH_BASE"]; if (!string.IsNullOrEmpty(pathBase)) { loggerFactory.CreateLogger("init").LogDebug("Using PATH BASE '{PathBase}'", pathBase); app.UsePathBase(pathBase); } app.UseRouting(); app.UseCors("CorsPolicy"); ConfigureAuth(app); app.UseEndpoints(endpoints => { endpoints.MapDefaultControllerRoute(); endpoints.MapControllers(); endpoints.MapHealthChecks("/hc", new HealthCheckOptions() { Predicate = _ => true, ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse }); endpoints.MapHealthChecks("/liveness", new HealthCheckOptions { Predicate = r => r.Name.Contains("self") }); }); app.UseSwagger() .UseSwaggerUI(c => { c.SwaggerEndpoint($"{ (!string.IsNullOrEmpty(pathBase) ? pathBase : string.Empty) }/swagger/v1/swagger.json", "Webhooks.API V1"); c.OAuthClientId("webhooksswaggerui"); c.OAuthAppName("WebHooks Service Swagger UI"); }); ConfigureEventBus(app); } protected virtual void ConfigureAuth(IApplicationBuilder app) { app.UseAuthentication(); app.UseAuthorization(); } protected virtual void ConfigureEventBus(IApplicationBuilder app) { var eventBus = app.ApplicationServices.GetRequiredService<IEventBus>(); eventBus.Subscribe<ProductPriceChangedIntegrationEvent, ProductPriceChangedIntegrationEventHandler>(); eventBus.Subscribe<OrderStatusChangedToShippedIntegrationEvent, OrderStatusChangedToShippedIntegrationEventHandler>(); eventBus.Subscribe<OrderStatusChangedToPaidIntegrationEvent, OrderStatusChangedToPaidIntegrationEventHandler>(); } } static class CustomExtensionMethods { public static IServiceCollection AddAppInsight(this IServiceCollection services, IConfiguration configuration) { services.AddApplicationInsightsTelemetry(configuration); services.AddApplicationInsightsKubernetesEnricher(); return services; } public static IServiceCollection AddCustomRouting(this IServiceCollection services, IConfiguration configuration) { services.AddControllers(options => { options.Filters.Add(typeof(HttpGlobalExceptionFilter)); }); services.AddCors(options => { options.AddPolicy("CorsPolicy", builder => builder .SetIsOriginAllowed((host) => true) .AllowAnyMethod() .AllowAnyHeader() .AllowCredentials()); }); return services; } public static IServiceCollection AddCustomDbContext(this IServiceCollection services, IConfiguration configuration) { services.AddEntityFrameworkSqlServer() .AddDbContext<WebhooksContext>(options => { options.UseSqlServer(configuration["ConnectionString"], sqlServerOptionsAction: sqlOptions => { sqlOptions.MigrationsAssembly(typeof(Startup).GetTypeInfo().Assembly.GetName().Name); //Configuring Connection Resiliency: https://docs.microsoft.com/en-us/ef/core/miscellaneous/connection-resiliency sqlOptions.EnableRetryOnFailure(maxRetryCount: 15, maxRetryDelay: TimeSpan.FromSeconds(30), errorNumbersToAdd: null); }); }); return services; } public static IServiceCollection AddSwagger(this IServiceCollection services, IConfiguration configuration) { services.AddSwaggerGen(options => { options.SwaggerDoc("v1", new OpenApiInfo { Title = "eShopOnContainers - Webhooks HTTP API", Version = "v1", Description = "The Webhooks Microservice HTTP API. This is a simple webhooks CRUD registration entrypoint" }); options.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme { Type = SecuritySchemeType.OAuth2, Flows = new OpenApiOAuthFlows() { Implicit = new OpenApiOAuthFlow() { AuthorizationUrl = new Uri($"{configuration.GetValue<string>("IdentityUrlExternal")}/connect/authorize"), TokenUrl = new Uri($"{configuration.GetValue<string>("IdentityUrlExternal")}/connect/token"), Scopes = new Dictionary<string, string>() { { "webhooks", "Webhooks API" } } } } }); options.OperationFilter<AuthorizeCheckOperationFilter>(); }); return services; } public static IServiceCollection AddEventBus(this IServiceCollection services, IConfiguration configuration) { if (configuration.GetValue<bool>("AzureServiceBusEnabled")) { services.AddSingleton<IEventBus, EventBusServiceBus>(sp => { var serviceBusPersisterConnection = sp.GetRequiredService<IServiceBusPersisterConnection>(); var iLifetimeScope = sp.GetRequiredService<ILifetimeScope>(); var logger = sp.GetRequiredService<ILogger<EventBusServiceBus>>(); var eventBusSubcriptionsManager = sp.GetRequiredService<IEventBusSubscriptionsManager>(); string subscriptionName = configuration["SubscriptionClientName"]; return new EventBusServiceBus(serviceBusPersisterConnection, logger, eventBusSubcriptionsManager, iLifetimeScope, subscriptionName); }); } else { services.AddSingleton<IEventBus, EventBusRabbitMQ>(sp => { var subscriptionClientName = configuration["SubscriptionClientName"]; var rabbitMQPersistentConnection = sp.GetRequiredService<IRabbitMQPersistentConnection>(); var iLifetimeScope = sp.GetRequiredService<ILifetimeScope>(); var logger = sp.GetRequiredService<ILogger<EventBusRabbitMQ>>(); var eventBusSubcriptionsManager = sp.GetRequiredService<IEventBusSubscriptionsManager>(); var retryCount = 5; if (!string.IsNullOrEmpty(configuration["EventBusRetryCount"])) { retryCount = int.Parse(configuration["EventBusRetryCount"]); } return new EventBusRabbitMQ(rabbitMQPersistentConnection, logger, iLifetimeScope, eventBusSubcriptionsManager, subscriptionClientName, retryCount); }); } services.AddSingleton<IEventBusSubscriptionsManager, InMemoryEventBusSubscriptionsManager>(); services.AddTransient<ProductPriceChangedIntegrationEventHandler>(); services.AddTransient<OrderStatusChangedToShippedIntegrationEventHandler>(); services.AddTransient<OrderStatusChangedToPaidIntegrationEventHandler>(); return services; } public static IServiceCollection AddCustomHealthCheck(this IServiceCollection services, IConfiguration configuration) { var accountName = configuration.GetValue<string>("AzureStorageAccountName"); var accountKey = configuration.GetValue<string>("AzureStorageAccountKey"); var hcBuilder = services.AddHealthChecks(); hcBuilder .AddCheck("self", () => HealthCheckResult.Healthy()) .AddSqlServer( configuration["ConnectionString"], name: "WebhooksApiDb-check", tags: new string[] { "webhooksdb" }); return services; } public static IServiceCollection AddHttpClientServices(this IServiceCollection services, IConfiguration configuration) { services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>(); services.AddHttpClient("extendedhandlerlifetime").SetHandlerLifetime(Timeout.InfiniteTimeSpan); //add http client services services.AddHttpClient("GrantClient") .SetHandlerLifetime(TimeSpan.FromMinutes(5)) .AddDevspacesSupport(); return services; } public static IServiceCollection AddIntegrationServices(this IServiceCollection services, IConfiguration configuration) { services.AddTransient<Func<DbConnection, IIntegrationEventLogService>>( sp => (DbConnection c) => new IntegrationEventLogService(c)); if (configuration.GetValue<bool>("AzureServiceBusEnabled")) { services.AddSingleton<IServiceBusPersisterConnection>(sp => { var subscriptionClientName = configuration["SubscriptionClientName"]; return new DefaultServiceBusPersisterConnection(configuration["EventBusConnection"]); }); } else { services.AddSingleton<IRabbitMQPersistentConnection>(sp => { var logger = sp.GetRequiredService<ILogger<DefaultRabbitMQPersistentConnection>>(); var factory = new ConnectionFactory() { HostName = configuration["EventBusConnection"], DispatchConsumersAsync = true }; if (!string.IsNullOrEmpty(configuration["EventBusUserName"])) { factory.UserName = configuration["EventBusUserName"]; } if (!string.IsNullOrEmpty(configuration["EventBusPassword"])) { factory.Password = configuration["EventBusPassword"]; } var retryCount = 5; if (!string.IsNullOrEmpty(configuration["EventBusRetryCount"])) { retryCount = int.Parse(configuration["EventBusRetryCount"]); } return new DefaultRabbitMQPersistentConnection(factory, logger, retryCount); }); } return services; } public static IServiceCollection AddCustomAuthentication(this IServiceCollection services, IConfiguration configuration) { // prevent from mapping "sub" claim to nameidentifier. JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Remove("sub"); var identityUrl = configuration.GetValue<string>("IdentityUrl"); services.AddAuthentication(options => { options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }).AddJwtBearer(options => { options.Authority = identityUrl; options.RequireHttpsMetadata = false; options.Audience = "webhooks"; }); return services; } }
#region File Description //----------------------------------------------------------------------------- // LoadingScreen.cs // // Microsoft XNA Community Game Platform // Copyright (C) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- #endregion #region Using Statements using System; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using XNA8DFramework; #endregion namespace GameStateManagement { /// <summary> /// The loading screen coordinates transitions between the menu system and the /// game itself. Normally one screen will transition off at the same time as /// the next screen is transitioning on, but for larger transitions that can /// take a longer time to load their data, we want the menu system to be entirely /// gone before we start loading the game. This is done as follows: /// /// - Tell all the existing screens to transition off. /// - Activate a loading screen, which will transition on at the same time. /// - The loading screen watches the state of the previous screens. /// - When it sees they have finished transitioning off, it activates the real /// next screen, which may take a long time to load its data. The loading /// screen will be the only thing displayed while this load is taking place. /// </summary> public class LoadingScreen : GameScreen { #region Fields readonly bool _loadingIsSlow; bool _otherScreensAreGone; readonly GameScreen[] _screensToLoad; bool _showText = true; string _backgroundTexture = ""; Texture2D _background; float _fadeBackBufferToWhiteAlpha; #endregion #region Initialization /// <summary> /// The constructor is private: loading screens should /// be activated via the static Load method instead. /// </summary> private LoadingScreen(bool loadingIsSlow, GameScreen[] screensToLoad) { _loadingIsSlow = loadingIsSlow; _screensToLoad = screensToLoad; // we don't serialize loading screens. if the user exits while the // game is at a loading screen, the game will resume at the screen // before the loading screen. IsSerializable = false; TransitionOnTime = TimeSpan.FromSeconds(0.5); } public static void Load(ScreenManager screenManager, bool loadingIsSlow, bool closeOtherWindows, params GameScreen[] screensToLoad) { Load(screenManager, loadingIsSlow, closeOtherWindows, "", true, 0.0f, screensToLoad); } /// <summary> /// Activates the loading screen. /// </summary> public static void Load(ScreenManager screenManager, bool loadingIsSlow, bool closeOtherWindows, string backgroundTexture, bool showText, float fadeBackBufferToWhiteAlpha, params GameScreen[] screensToLoad) { if (closeOtherWindows) { // Tell all the current screens to transition off. foreach (GameScreen screen in screenManager.GetScreens()) screen.ExitScreen(); } //screenManager.Game.Content.Unload(); // Create and activate the loading screen. var loadingScreen = new LoadingScreen(loadingIsSlow, screensToLoad) { _backgroundTexture = backgroundTexture, _showText = showText, _fadeBackBufferToWhiteAlpha = fadeBackBufferToWhiteAlpha }; if (!closeOtherWindows) loadingScreen._otherScreensAreGone = true; screenManager.AddScreen(loadingScreen); } public override void Activate(bool instancePreserved) { if (!instancePreserved) { if (!string.IsNullOrEmpty(_backgroundTexture)) _background = content.LoadLocalized<Texture2D>(_backgroundTexture); } } #endregion #region Update and Draw /// <summary> /// Updates the loading screen. /// </summary> public override void Update(GameTime gameTime, bool otherScreenHasFocus, bool coveredByOtherScreen) { base.Update(gameTime, otherScreenHasFocus, coveredByOtherScreen); // If all the previous screens have finished transitioning // off, it is time to actually perform the load. if (_otherScreensAreGone) { ScreenManager.RemoveScreen(this); foreach (GameScreen screen in _screensToLoad) { if (screen != null) { ScreenManager.AddScreen(screen); } } // Once the load has finished, we use ResetElapsedTime to tell // the game timing mechanism that we have just finished a very // long frame, and that it should not try to catch up. #if !SILVERLIGHT ScreenManager.Game.ResetElapsedTime(); #endif } } /// <summary> /// Draws the loading screen. /// </summary> public override void Draw(GameTime gameTime) { // If we are the only active screen, that means all the previous screens // must have finished transitioning off. We check for this in the Draw // method, rather than in Update, because it isn't enough just for the // screens to be gone: in order for the transition to look good we must // have actually drawn a frame without them before we perform the load. if ((ScreenState == ScreenState.Active) && (ScreenManager.GetScreens().Length == 1)) { _otherScreensAreGone = true; } // The gameplay screen takes a while to load, so we display a loading // message while that is going on, but the menus load very quickly, and // it would look silly if we flashed this up for just a fraction of a // second while returning from the game to the menus. This parameter // tells us how long the loading is going to take, so we know whether // to bother drawing the message. if (_loadingIsSlow) { SpriteBatch spriteBatch = ScreenManager.SpriteBatch; spriteBatch.Begin(); #if IPHONE var screenSize = new Vector2(ScreenManager.Graphics.PreferredBackBufferWidth, ScreenManager.Graphics.PreferredBackBufferHeight); #else var screenSize = new Vector2(ScreenManager.GraphicsDevice.Viewport.Width, ScreenManager.GraphicsDevice.Viewport.Height); #endif if (_background != null) spriteBatch.Draw(_background, screenSize / 2, null, Color.White, 0, new Vector2(_background.Width, _background.Height) / 2, 1, SpriteEffects.None, 0); if (_showText) { SpriteFont font = ScreenManager.Font; const string message = "Loading..."; // Center the text in the screen. Vector2 textSize = font.MeasureString(message); Vector2 textPosition = (screenSize - textSize) / 2; #if SILVERLIGHT var color = new Color(Color.White, MathHelper.Clamp(TransitionAlpha, 0, 1)); #else var color = Color.White * TransitionAlpha; #endif // Draw the text. spriteBatch.DrawString(font, message, textPosition, color); } spriteBatch.End(); // Fix for Silversprite spriteBatch.Begin(); spriteBatch.End(); if (_fadeBackBufferToWhiteAlpha > 0) ScreenManager.FadeBackBufferToWhite(_fadeBackBufferToWhiteAlpha); } } #endregion } }
// Copyright (c) DotSpatial Team. All rights reserved. // Licensed under the MIT license. See License.txt file in the project root for full license information. using System; using System.Collections; using System.Collections.Generic; using System.Drawing; using System.Linq; using DotSpatial.Data; using NetTopologySuite.Geometries; namespace DotSpatial.Symbology { /// <summary> /// Group of layers. /// </summary> public class Group : Layer, IGroup { #region Fields private ILayerCollection _layers; #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="Group"/> class. /// </summary> public Group() { Configure(); } /// <summary> /// Initializes a new instance of the <see cref="Group"/> class that sits in a layer list and uses the specified progress handler. /// </summary> /// <param name="frame">The map frame the group belongs to.</param> /// <param name="progressHandler">the progress handler.</param> public Group(IFrame frame, IProgressHandler progressHandler) : base(progressHandler) { MapFrame = frame; Configure(); } /// <summary> /// Initializes a new instance of the <see cref="Group"/> class that sits in a layer list and uses the specified progress handler. /// </summary> /// <param name="container">the layer list.</param> /// <param name="frame">The map frame the group belongs to.</param> /// <param name="progressHandler">the progress handler.</param> public Group(ICollection<ILayer> container, IFrame frame, IProgressHandler progressHandler) : base(container, progressHandler) { MapFrame = frame; Configure(); } #endregion #region Events /// <summary> /// This occurs when a new layer is added either to this group, or one of the child groups within this group. /// </summary> public event EventHandler<LayerEventArgs> LayerAdded; /// <summary> /// This occurs when a layer is removed from this group. /// </summary> public event EventHandler<LayerEventArgs> LayerRemoved; #endregion #region Properties /// <inheritdoc /> public virtual int Count => _layers.Count; /// <inheritdoc /> public virtual bool EventsSuspended => _layers.EventsSuspended; /// <summary> /// Gets the envelope that contains all of the layers for this data frame. Essentially this would be /// the extents to use if you want to zoom to the world view. /// </summary> public override Extent Extent { get { var layers = GetLayers(); if (layers == null) return null; Extent ext = null; // changed by jany (2015-07-17) don't add extents of empty layers, because they cause a wrong overall extent foreach (var extent in layers.Select(layer => layer.Extent).Where(extent => extent != null && !extent.IsEmpty())) { if (ext == null) ext = (Extent)extent.Clone(); else ext.ExpandToInclude(extent); } return ext; } } /// <summary> /// Gets or sets the integer handle for this group. /// </summary> public int Handle { get; protected set; } /// <summary> /// Gets or sets the icon. /// </summary> public Image Icon { get; set; } /// <summary> /// Gets the currently invalidated region as a union of all the /// invalidated regions of individual layers in this group. /// </summary> public override Extent InvalidRegion { get { Extent result = new Extent(); foreach (ILayer lyr in GetLayers()) { if (lyr.InvalidRegion != null) result.ExpandToInclude(lyr.InvalidRegion); } return result; } } /// <inheritdoc /> public virtual bool IsReadOnly => _layers.IsReadOnly; /// <summary> /// Gets or sets a value indicating whether any sub-layers in the group are visible. Setting this /// will force all the layers in this group to become visible. /// </summary> public override bool IsVisible { get { if (MapFrame.AutoDisplayGroupChildren) { // classic way of processing group children's visibility. Setting this will force all the // layers in this group to become visible. return GetLayers().Any(lyr => lyr.IsVisible); } else { // alternative way of processing group children's visibility. Setting this will have the effect // of de-coupling the group visibility with its children's visibility. they should be independent // and a child layer's visibility should be True if every one of its parent groups is ON. This is // consistent with other GIS/layering apps that support nested groups. return Checked; } } set { // group children should not be set on/off when the parent group is set on/off. this is // consistent with other GIS/layering apps that support nested groups. if (MapFrame.AutoDisplayGroupChildren) { // classic way of processing group children's visibility. Setting this will force all the // layers in this group to become visible. foreach (var lyr in GetLayers()) { lyr.IsVisible = value; } } else { // alternative way of processing grouup children's visibility. Setting this will have the effect // of de-coupling the group visibility with its children's visibility. they should be independent // and a child layer's visibility should be True if every one of its parent groups is ON. This is // consistent with other GIS/layering apps that support nested groups. base.IsVisible = value; } } } /// <summary> /// Gets the count of the layers that are currently stored in this map frame. /// </summary> public int LayerCount => _layers.Count; /// <summary> /// Gets or sets a value indicating whether any of the immediate layers or groups contained within this /// control are visible. Setting this will set the visibility for each of the members of this /// map frame. /// </summary> public bool LayersVisible { get { return GetLayers().Any(layer => layer.IsVisible); } set { foreach (var layer in GetLayers()) { layer.IsVisible = value; } } } /// <summary> /// Gets the layers cast as legend items. This allows easier cycling in recursive legend code. /// </summary> public override IEnumerable<ILegendItem> LegendItems => _layers; /// <summary> /// Gets or sets the parent group of this group. /// </summary> public IGroup ParentGroup { get; protected set; } /// <summary> /// Gets or sets the progress handler to use. Setting this will set the progress handler for each of the layers in this map frame. /// </summary> public override IProgressHandler ProgressHandler { get { return base.ProgressHandler; } set { base.ProgressHandler = value; foreach (ILayer layer in GetLayers()) { layer.ProgressHandler = value; } } } /// <summary> /// Gets or sets a value indicating whether the groups state is locked. This prevents the user from changing the visual state /// except layer by layer. /// </summary> public bool StateLocked { get; set; } /// <summary> /// gets or sets the list of layers. /// </summary> [ShallowCopy] protected ILayerCollection Layers { get { return _layers; } set { if (Layers != null) { IgnoreLayerEvents(_layers); } _layers = value; if (_layers != null) { HandleLayerEvents(value); _layers.ParentGroup = this; _layers.MapFrame = MapFrame; } } } #endregion #region Indexers /// <inheritdoc /> public virtual ILayer this[int index] { get { return _layers[index]; } set { _layers[index] = value; } } #endregion #region Methods /// <inheritdoc /> public virtual void Add(ILayer layer) { _layers.Add(layer); } /// <inheritdoc /> public override bool CanReceiveItem(ILegendItem item) { ILayer lyr = item as ILayer; if (lyr != null) { if (lyr != this) return true; // don't allow groups to add to themselves } return false; } /// <inheritdoc /> public virtual void Clear() { _layers.Clear(); } /// <inheritdoc /> public override bool ClearSelection(out Envelope affectedAreas, bool force = false) { affectedAreas = new Envelope(); bool changed = false; MapFrame.SuspendEvents(); foreach (ILayer layer in GetAllLayers()) { Envelope layerArea; if (layer.ClearSelection(out layerArea, force)) { changed = true; affectedAreas.ExpandToInclude(layerArea); } } MapFrame.ResumeEvents(); OnSelectionChanged(); // fires only AFTER the individual layers have fired their events. return changed; } /// <inheritdoc /> public virtual bool Contains(ILayer item) { return _layers.Contains(item); } /// <inheritdoc /> public virtual void CopyTo(ILayer[] array, int arrayIndex) { _layers.CopyTo(array, arrayIndex); } /// <inheritdoc /> public virtual IEnumerator<ILayer> GetEnumerator() { return _layers.GetEnumerator(); } /// <inheritdoc /> public int GetLayerCount(bool recursive) { // if this is not overridden, this just looks at the Layers collection int count = 0; IList<ILayer> layers = GetLayers(); foreach (ILayer item in layers) { IGroup grp = item as IGroup; if (grp != null) { if (recursive) count += grp.GetLayerCount(true); } else { count++; } } return count; } /// <summary> /// Gets all feature layers of this group including feature layers which are nested /// within child groups. The group objects themselves are not included in this list. /// </summary> /// <returns>The list of the feature layers.</returns> public List<IFeatureLayer> GetAllFeatureLayers() { return GetAllTypeLayers<IFeatureLayer>(); } /// <summary> /// Gets all map groups in this group including the nested groups. /// </summary> /// <returns>the list of the groups.</returns> public List<IGroup> GetAllGroups() { var groupList = new List<IGroup>(); GetNestedGroups(this, groupList); return groupList; } /// <summary> /// Gets all image layers of this group including image layers which are nested /// within child groups. The group objects themselves are not included in this list. /// </summary> /// <returns>The list of the image layers.</returns> public List<IImageLayer> GetAllImageLayers() { return GetAllTypeLayers<IImageLayer>(); } /// <summary> /// Gets all layers of this group including layers which are nested /// within child groups. The group objects themselves are not included in this list, /// but all FeatureLayers, RasterLayers, ImageLayers and other layers are included. /// </summary> /// <returns>The list of the layers.</returns> public List<ILayer> GetAllLayers() { return GetAllTypeLayers<ILayer>(); } /// <summary> /// Gets all line layers of this group including line layers which are nested /// within child groups. The group objects themselves are not included in this list. /// </summary> /// <returns>The list of the line layers.</returns> public List<ILineLayer> GetAllLineLayers() { return GetAllTypeLayers<ILineLayer>(); } /// <summary> /// Gets all point layers of this group including point layers which are nested /// within child groups. The group objects themselves are not included in this list. /// </summary> /// <returns>The list of the point layers.</returns> public List<IPointLayer> GetAllPointLayers() { return GetAllTypeLayers<IPointLayer>(); } /// <summary> /// Gets all polygon layers of this group including polygon layers which are nested /// within child groups. The group objects themselves are not included in this list. /// </summary> /// <returns>The list of the polygon layers.</returns> public List<IPolygonLayer> GetAllPolygonLayers() { return GetAllTypeLayers<IPolygonLayer>(); } /// <summary> /// Gets all raster layers of this group including raster layers which are nested /// within child groups. The group objects themselves are not included in this list. /// </summary> /// <returns>The list of the raster layers.</returns> public List<IRasterLayer> GetAllRasterLayers() { return GetAllTypeLayers<IRasterLayer>(); } /// <inheritdoc /> public virtual IList<ILayer> GetLayers() { return _layers.ToList(); } /// <inheritdoc /> public override Size GetLegendSymbolSize() { return new Size(16, 16); } /// <inheritdoc /> public virtual int IndexOf(ILayer item) { return _layers.IndexOf(item); } /// <inheritdoc /> public virtual void Insert(int index, ILayer layer) { _layers.Insert(index, layer); } /// <inheritdoc /> public override void Invalidate(Extent region) { foreach (ILayer layer in GetLayers()) { layer.Invalidate(region); } } /// <inheritdoc /> public override void Invalidate() { foreach (ILayer layer in GetLayers()) { layer.Invalidate(); } } /// <inheritdoc /> public override bool InvertSelection(Envelope tolerant, Envelope strict, SelectionMode mode, out Envelope affectedArea) { affectedArea = new Envelope(); bool somethingChanged = false; MapFrame.SuspendEvents(); foreach (ILayer s in GetAllLayers().Where(_ => _.SelectionEnabled && _.IsVisible)) { Envelope layerArea; if (s.InvertSelection(tolerant, strict, mode, out layerArea)) { somethingChanged = true; affectedArea.ExpandToInclude(layerArea); } } MapFrame.ResumeEvents(); OnSelectionChanged(); // fires only AFTER the individual layers have fired their events. return somethingChanged; } /// <summary> /// Gets the layer handle of the specified layer. /// </summary> /// <param name="positionInGroup">0 based index into list of layers.</param> /// <returns>Layer's handle on success, -1 on failure.</returns> public int LayerHandle(int positionInGroup) { throw new NotSupportedException(); } /// <inheritdoc /> public Bitmap LegendSnapShot(int imgWidth) { // bool TO_DO_GROUP_LEGEND_SNAPSHOT; // return new Bitmap(100, 100); throw new NotImplementedException(); } /// <inheritdoc /> public virtual bool Remove(ILayer layer) { return _layers.Remove(layer); } /// <inheritdoc /> public virtual void RemoveAt(int index) { _layers.RemoveAt(index); } /// <inheritdoc /> public virtual void ResumeEvents() { _layers.ResumeEvents(); } /// <inheritdoc /> public override bool Select(Envelope tolerant, Envelope strict, SelectionMode mode, out Envelope affectedArea, ClearStates clear) { affectedArea = new Envelope(); bool somethingChanged = false; MapFrame.SuspendEvents(); foreach (var s in GetAllLayers().Where(_ => _.SelectionEnabled && _.IsVisible)) { Envelope layerArea; if (s.Select(tolerant, strict, mode, out layerArea, clear)) { somethingChanged = true; affectedArea.ExpandToInclude(layerArea); } } MapFrame.ResumeEvents(); OnSelectionChanged(); // fires only AFTER the individual layers have fired their events. return somethingChanged; } /// <inheritdoc /> public virtual void SuspendEvents() { _layers.SuspendEvents(); } /// <inheritdoc /> public override bool UnSelect(Envelope tolerant, Envelope strict, SelectionMode mode, out Envelope affectedArea) { affectedArea = new Envelope(); bool somethingChanged = false; SuspendEvents(); foreach (ILayer s in GetAllLayers().Where(_ => _.SelectionEnabled && _.IsVisible)) { Envelope layerArea; if (s.UnSelect(tolerant, strict, mode, out layerArea)) { somethingChanged = true; affectedArea.ExpandToInclude(layerArea); } } ResumeEvents(); OnSelectionChanged(); // fires only AFTER the individual layers have fired their events. return somethingChanged; } /// <inheritdoc /> IEnumerator IEnumerable.GetEnumerator() { return _layers.GetEnumerator(); } /// <summary> /// Zoom to group. /// </summary> internal void ZoomToGroup() { var extent = Extent; if (extent != null) { OnZoomToLayer(extent.ToEnvelope()); } } /// <summary> /// Disposes the unmanaged resourced of this group. If disposeManagedResources is true, then this will /// also dispose the resources of the child layers and groups unless they are dispose locked. /// </summary> /// <param name="disposeManagedResources">Boolean, true to dispose child objects and set managed members to null.</param> protected override void Dispose(bool disposeManagedResources) { if (disposeManagedResources) { ParentGroup = null; _layers?.Dispose(); } Icon?.Dispose(); base.Dispose(disposeManagedResources); } /// <summary> /// Given a new LayerCollection, we need to be sensitive to certain events. /// </summary> /// <param name="collection">Collection events get added to.</param> protected virtual void HandleLayerEvents(ILayerEvents collection) { if (collection == null) return; collection.LayerVisibleChanged += LayersLayerVisibleChanged; collection.ItemChanged += LayersItemChanged; collection.ZoomToLayer += LayersZoomToLayer; collection.SelectionChanging += CollectionSelectionChanging; collection.LayerSelected += CollectionLayerSelected; collection.LayerAdded += LayersLayerAdded; collection.LayerRemoved += LayersLayerRemoved; collection.SelectionChanged += CollectionSelectionChanged; } /// <summary> /// When setting an old layer collection it is advisable to not only add /// new handlers to the new collection, but remove the handlers related to the old collection. /// </summary> /// <param name="collection">Collection events get removed from.</param> protected virtual void IgnoreLayerEvents(ILayerEvents collection) { if (collection == null) return; collection.LayerVisibleChanged -= LayersLayerVisibleChanged; collection.ItemChanged -= LayersItemChanged; collection.ZoomToLayer -= LayersZoomToLayer; collection.SelectionChanging -= CollectionSelectionChanging; collection.LayerSelected -= CollectionLayerSelected; collection.LayerAdded -= LayersLayerAdded; collection.LayerRemoved -= LayersLayerRemoved; collection.SelectionChanged -= CollectionSelectionChanged; } /// <summary> /// Creates a virtual method when sub-groups are being created. /// </summary> protected virtual void OnCreateGroup() { Group grp = new Group(Layers, MapFrame, ProgressHandler) { LegendText = "New Group" }; } /// <summary> /// Simply echo this event out to members above this group that might be listening to it. /// </summary> /// <param name="sender">Sender that raised the event.</param> /// <param name="e">The event args.</param> protected virtual void OnLayerAdded(object sender, LayerEventArgs e) { LayerAdded?.Invoke(sender, e); } /// <summary> /// Occurs when removing a layer. This also fires the LayerRemoved event. /// </summary> /// <param name="sender">Sender that raised the event.</param> /// <param name="e">The event args.</param> protected virtual void OnLayerRemoved(object sender, LayerEventArgs e) { LayerRemoved?.Invoke(sender, e); } /// <summary> /// Recursively adds all the groups to groupList. /// </summary> /// <param name="grp">Group to search through.</param> /// <param name="groupList">The list the groups should be added to.</param> private static void GetNestedGroups(IGroup grp, List<IGroup> groupList) { // initialize the layer list if required if (groupList == null) groupList = new List<IGroup>(); // recursive function -- all nested groups and layers are considered foreach (var lyr in grp.GetLayers()) { grp = lyr as IGroup; if (grp != null) { GetNestedGroups(grp, groupList); groupList.Add(grp); } } } /// <summary> /// Recursively adds all the layers of the given type that are found in group to layerList. /// </summary> /// <typeparam name="T">Type of the layers that should be included.</typeparam> /// <param name="group">Group that contains the layers.</param> /// <param name="layerList">The list the layers should be added to.</param> private static void GetNestedLayers<T>(IGroup group, List<T> layerList) where T : class { if (layerList == null) layerList = new List<T>(); foreach (var layer in group.GetLayers()) { var grp = layer as IGroup; if (grp != null) { GetNestedLayers(grp, layerList); } else { var tlayer = layer as T; if (tlayer != null) { layerList.Add(tlayer); } } } } private void CollectionLayerSelected(object sender, LayerSelectedEventArgs e) { OnLayerSelected(e.Layer, e.IsSelected); } private void CollectionSelectionChanged(object sender, EventArgs e) { OnSelectionChanged(); } private void CollectionSelectionChanging(object sender, FeatureLayerSelectionEventArgs e) { OnSelectionChanged(); } private void Configure() { Layers = new LayerCollection(MapFrame, this); StateLocked = false; IsDragable = true; IsExpanded = true; ContextMenuItems = new List<SymbologyMenuItem> { new SymbologyMenuItem("Remove Group", RemoveClick), new SymbologyMenuItem("Zoom to Group", (sender, args) => ZoomToGroup()), new SymbologyMenuItem("Create new Group", CreateGroupClick) }; } private void CreateGroupClick(object sender, EventArgs e) { OnCreateGroup(); } /// <summary> /// Gets all the layers of the given type. /// </summary> /// <typeparam name="T">Type of the layers that should be included.</typeparam> /// <returns>The list of the layers with the given type.</returns> private List<T> GetAllTypeLayers<T>() where T : class { var layerList = new List<T>(); GetNestedLayers(this, layerList); return layerList; } private void LayersItemChanged(object sender, EventArgs e) { OnItemChanged(sender); } private void LayersLayerAdded(object sender, LayerEventArgs e) { OnLayerAdded(sender, e); } private void LayersLayerRemoved(object sender, LayerEventArgs e) { OnLayerRemoved(sender, e); } private void LayersLayerVisibleChanged(object sender, EventArgs e) { OnVisibleChanged(sender, e); } private void LayersZoomToLayer(object sender, EnvelopeArgs e) { OnZoomToLayer(e.Envelope); } private void RemoveClick(object sender, EventArgs e) { OnRemoveItem(); } #endregion } }
/* ** $Id: ltable.c,v 2.32.1.2 2007/12/28 15:32:23 roberto Exp $ ** Lua tables (hash) ** See Copyright Notice in lua.h */ using System; using System.Collections.Generic; using System.Text; using System.Diagnostics; using System.Runtime.InteropServices; namespace SharpLua { using TValue = Lua.lua_TValue; using StkId = Lua.lua_TValue; using lua_Number = System.Double; public partial class Lua { /* ** Implementation of tables (aka arrays, objects, or hash tables). ** Tables keep its elements in two parts: an array part and a hash part. ** Non-negative integer keys are all candidates to be kept in the array ** part. The actual size of the array is the largest `n' such that at ** least half the slots between 0 and n are in use. ** Hash uses a mix of chained scatter table with Brent's variation. ** A main invariant of these tables is that, if an element is not ** in its main position (i.e. the `original' position that its hash gives ** to it), then the colliding element is in its own main position. ** Hence even when the load factor reaches 100%, performance remains good. */ internal static Node gnode(Table t, int i) { return t.node[i]; } internal static TKey_nk gkey(Node n) { return n.i_key.nk; } internal static TValue gval(Node n) { return n.i_val; } internal static Node gnext(Node n) { return n.i_key.nk.next; } internal static void gnext_set(Node n, Node v) { n.i_key.nk.next = v; } internal static TValue key2tval(Node n) { return n.i_key.tvk; } /* ** max size of array part is 2^MAXBITS */ //#if LUAI_BITSINT > 26 public const int MAXBITS = 26; /* in the dotnet port LUAI_BITSINT is 32 */ //#else //public const int MAXBITS = (LUAI_BITSINT-2); //#endif public const int MAXASIZE = (1 << MAXBITS); //public static Node gnode(table t, int i) {return t.node[i];} internal static Node hashpow2(Table t, lua_Number n) { return gnode(t, (int)lmod(n, sizenode(t))); } public static Node hashstr(Table t, TString str) {return hashpow2(t, str.tsv.hash);} public static Node hashboolean(Table t, int p) {return hashpow2(t, p);} /* ** for some types, it is better to avoid modulus by power of 2, as ** they tend to have many 2 factors. */ public static Node hashmod(Table t, int n) { return gnode(t, ( (n & int.MaxValue) % ((sizenode(t) - 1) | 1))); } public static Node hashpointer(Table t, object p) { return hashmod(t, p.GetHashCode()); } /* ** number of ints inside a lua_Number */ public const int numints = sizeof(lua_Number) / sizeof(int); //static const Node dummynode_ = { //{{null}, LUA_TNIL}, /* value */ //{{{null}, LUA_TNIL, null}} /* key */ //}; public static Node dummynode_ = new Node(new TValue(new Value(), LUA_TNIL), new TKey(new Value(), LUA_TNIL, null)); public static Node dummynode = dummynode_; /* ** hash for lua_Numbers */ private static Node hashnum (Table t, lua_Number n) { byte[] a = BitConverter.GetBytes(n); for (int i = 1; i < a.Length; i++) a[0] += a[i]; return hashmod(t, (int)a[0]); } /* ** returns the `main' position of an element in a table (that is, the index ** of its hash value) */ private static Node mainposition (Table t, TValue key) { switch (ttype(key)) { case LUA_TNUMBER: return hashnum(t, nvalue(key)); case LUA_TSTRING: return hashstr(t, rawtsvalue(key)); case LUA_TBOOLEAN: return hashboolean(t, bvalue(key)); case LUA_TLIGHTUSERDATA: return hashpointer(t, pvalue(key)); default: return hashpointer(t, gcvalue(key)); } } /* ** returns the index for `key' if `key' is an appropriate key to live in ** the array part of the table, -1 otherwise. */ private static int arrayindex (TValue key) { if (ttisnumber(key)) { lua_Number n = nvalue(key); int k; lua_number2int(out k, n); if (luai_numeq(cast_num(k), n)) return k; } return -1; /* `key' did not match some condition */ } /* ** returns the index of a `key' for table traversals. First goes all ** elements in the array part, then elements in the hash part. The ** beginning of a traversal is signalled by -1. */ private static int findindex (LuaState L, Table t, StkId key) { int i; if (ttisnil(key)) return -1; /* first iteration */ i = arrayindex(key); if (0 < i && i <= t.sizearray) /* is `key' inside array part? */ return i-1; /* yes; that's the index (corrected to C) */ else { Node n = mainposition(t, key); do { /* check whether `key' is somewhere in the chain */ /* key may be dead already, but it is ok to use it in `next' */ if ((luaO_rawequalObj(key2tval(n), key) != 0) || (ttype(gkey(n)) == LUA_TDEADKEY && iscollectable(key) && gcvalue(gkey(n)) == gcvalue(key))) { i = cast_int(n - gnode(t, 0)); /* key index in hash table */ /* hash elements are numbered after array ones */ return i + t.sizearray; } else n = gnext(n); } while (n != null); luaG_runerror(L, "invalid key to " + LUA_QL("next")); /* key not found */ return 0; /* to avoid warnings */ } } public static int luaH_next (LuaState L, Table t, StkId key) { int i = findindex(L, t, key); /* find original element */ for (i++; i < t.sizearray; i++) { /* try first array part */ if (!ttisnil(t.array[i])) { /* a non-nil value? */ setnvalue(key, cast_num(i+1)); setobj2s(L, key+1, t.array[i]); return 1; } } for (i -= t.sizearray; i < sizenode(t); i++) { /* then hash part */ if (!ttisnil(gval(gnode(t, i)))) { /* a non-nil value? */ setobj2s(L, key, key2tval(gnode(t, i))); setobj2s(L, key+1, gval(gnode(t, i))); return 1; } } return 0; /* no more elements */ } /* ** {============================================================= ** Rehash ** ============================================================== */ private static int computesizes (int[] nums, ref int narray) { int i; int twotoi; /* 2^i */ int a = 0; /* number of elements smaller than 2^i */ int na = 0; /* number of elements to go to array part */ int n = 0; /* optimal size for array part */ for (i = 0, twotoi = 1; twotoi/2 < narray; i++, twotoi *= 2) { if (nums[i] > 0) { a += nums[i]; if (a > twotoi/2) { /* more than half elements present? */ n = twotoi; /* optimal size (till now) */ na = a; /* all elements smaller than n will go to array part */ } } if (a == narray) break; /* all elements already counted */ } narray = n; lua_assert(narray/2 <= na && na <= narray); return na; } private static int countint (TValue key, int[] nums) { int k = arrayindex(key); if (0 < k && k <= MAXASIZE) { /* is `key' an appropriate array index? */ nums[ceillog2(k)]++; /* count as such */ return 1; } else return 0; } private static int numusearray (Table t, int[] nums) { int lg; int ttlg; /* 2^lg */ int ause = 0; /* summation of `nums' */ int i = 1; /* count to traverse all array keys */ for (lg=0, ttlg=1; lg<=MAXBITS; lg++, ttlg*=2) { /* for each slice */ int lc = 0; /* counter */ int lim = ttlg; if (lim > t.sizearray) { lim = t.sizearray; /* adjust upper limit */ if (i > lim) break; /* no more elements to count */ } /* count elements in range (2^(lg-1), 2^lg] */ for (; i <= lim; i++) { if (!ttisnil(t.array[i-1])) lc++; } nums[lg] += lc; ause += lc; } return ause; } private static int numusehash (Table t, int[] nums, ref int pnasize) { int totaluse = 0; /* total number of elements */ int ause = 0; /* summation of `nums' */ int i = sizenode(t); while ((i--) != 0) { Node n = t.node[i]; if (!ttisnil(gval(n))) { ause += countint(key2tval(n), nums); totaluse++; } } pnasize += ause; return totaluse; } private static void setarrayvector (LuaState L, Table t, int size) { int i; luaM_reallocvector<TValue>(L, ref t.array, t.sizearray, size/*, TValue*/); for (i=t.sizearray; i<size; i++) setnilvalue(t.array[i]); t.sizearray = size; } private static void setnodevector (LuaState L, Table t, int size) { int lsize; if (size == 0) { /* no elements to hash part? */ t.node = new Node[] { dummynode }; /* use common `dummynode' */ lsize = 0; } else { int i; lsize = ceillog2(size); if (lsize > MAXBITS) luaG_runerror(L, "table overflow"); size = twoto(lsize); Node[] nodes = luaM_newvector<Node>(L, size); t.node = nodes; for (i=0; i<size; i++) { Node n = gnode(t, i); gnext_set(n, null); setnilvalue(gkey(n)); setnilvalue(gval(n)); } } t.lsizenode = cast_byte(lsize); t.lastfree = size; /* all positions are free */ } private static void resize (LuaState L, Table t, int nasize, int nhsize) { int i; int oldasize = t.sizearray; int oldhsize = t.lsizenode; Node[] nold = t.node; /* save old hash ... */ if (nasize > oldasize) /* array part must grow? */ setarrayvector(L, t, nasize); /* create new hash part with appropriate size */ setnodevector(L, t, nhsize); if (nasize < oldasize) { /* array part must shrink? */ t.sizearray = nasize; /* re-insert elements from vanishing slice */ for (i=nasize; i<oldasize; i++) { if (!ttisnil(t.array[i])) setobjt2t(L, luaH_setnum(L, t, i+1), t.array[i]); } /* shrink array */ luaM_reallocvector<TValue>(L, ref t.array, oldasize, nasize/*, TValue*/); } /* re-insert elements from hash part */ for (i = twoto(oldhsize) - 1; i >= 0; i--) { Node old = nold[i]; if (!ttisnil(gval(old))) setobjt2t(L, luaH_set(L, t, key2tval(old)), gval(old)); } if (nold[0] != dummynode) luaM_freearray(L, nold); /* free old array */ } public static void luaH_resizearray (LuaState L, Table t, int nasize) { int nsize = (t.node[0] == dummynode) ? 0 : sizenode(t); resize(L, t, nasize, nsize); } private static void rehash (LuaState L, Table t, TValue ek) { int nasize, na; int[] nums = new int[MAXBITS+1]; /* nums[i] = number of keys between 2^(i-1) and 2^i */ int i; int totaluse; for (i=0; i<=MAXBITS; i++) nums[i] = 0; /* reset counts */ nasize = numusearray(t, nums); /* count keys in array part */ totaluse = nasize; /* all those keys are integer keys */ totaluse += numusehash(t, nums, ref nasize); /* count keys in hash part */ /* count extra key */ nasize += countint(ek, nums); totaluse++; /* compute new size for array part */ na = computesizes(nums, ref nasize); /* resize the table to new computed sizes */ resize(L, t, nasize, totaluse - na); } /* ** }============================================================= */ public static Table luaH_new (LuaState L, int narray, int nhash) { Table t = luaM_new<Table>(L); luaC_link(L, obj2gco(t), LUA_TTABLE); t.metatable = null; t.flags = cast_byte(~0); /* temporary values (kept only if some malloc fails) */ t.array = null; t.sizearray = 0; t.lsizenode = 0; t.node = new Node[] { dummynode }; setarrayvector(L, t, narray); setnodevector(L, t, nhash); return t; } public static void luaH_free (LuaState L, Table t) { if (t.node[0] != dummynode) luaM_freearray(L, t.node); luaM_freearray(L, t.array); luaM_free(L, t); } private static Node getfreepos (Table t) { while (t.lastfree-- > 0) { if (ttisnil(gkey(t.node[t.lastfree]))) return t.node[t.lastfree]; } return null; /* could not find a free place */ } /* ** inserts a new key into a hash table; first, check whether key's main ** position is free. If not, check whether colliding node is in its main ** position or not: if it is not, move colliding node to an empty place and ** put new key in its main position; otherwise (colliding node is in its main ** position), new key goes to an empty position. */ private static TValue newkey (LuaState L, Table t, TValue key) { Node mp = mainposition(t, key); if (!ttisnil(gval(mp)) || mp == dummynode) { Node othern; Node n = getfreepos(t); /* get a free place */ if (n == null) { /* cannot find a free place? */ rehash(L, t, key); /* grow table */ return luaH_set(L, t, key); /* re-insert key into grown table */ } lua_assert(n != dummynode); othern = mainposition(t, key2tval(mp)); if (othern != mp) { /* is colliding node out of its main position? */ /* yes; move colliding node into free position */ while (gnext(othern) != mp) othern = gnext(othern); /* find previous */ gnext_set(othern, n); /* redo the chain with `n' in place of `mp' */ n.i_val = new TValue(mp.i_val); /* copy colliding node into free pos. (mp.next also goes) */ n.i_key = new TKey(mp.i_key); gnext_set(mp, null); /* now `mp' is free */ setnilvalue(gval(mp)); } else { /* colliding node is in its own main position */ /* new node will go into free position */ gnext_set(n, gnext(mp)); /* chain new position */ gnext_set(mp, n); mp = n; } } gkey(mp).value.Copy(key.value); gkey(mp).tt = key.tt; luaC_barriert(L, t, key); lua_assert(ttisnil(gval(mp))); return gval(mp); } /* ** search function for integers */ public static TValue luaH_getnum(Table t, int key) { /* (1 <= key && key <= t.sizearray) */ if ((uint)(key-1) < (uint)t.sizearray) return t.array[key-1]; else { lua_Number nk = cast_num(key); Node n = hashnum(t, nk); do { /* check whether `key' is somewhere in the chain */ if (ttisnumber(gkey(n)) && luai_numeq(nvalue(gkey(n)), nk)) return gval(n); /* that's it */ else n = gnext(n); } while (n != null); return luaO_nilobject; } } /* ** search function for strings */ public static TValue luaH_getstr (Table t, TString key) { Node n = hashstr(t, key); do { /* check whether `key' is somewhere in the chain */ if (ttisstring(gkey(n)) && rawtsvalue(gkey(n)) == key) return gval(n); /* that's it */ else n = gnext(n); } while (n != null); return luaO_nilobject; } /* ** main search function */ public static TValue luaH_get (Table t, TValue key) { switch (ttype(key)) { case LUA_TNIL: return luaO_nilobject; case LUA_TSTRING: return luaH_getstr(t, rawtsvalue(key)); case LUA_TNUMBER: { int k; lua_Number n = nvalue(key); lua_number2int(out k, n); if (luai_numeq(cast_num(k), nvalue(key))) /* index is int? */ return luaH_getnum(t, k); /* use specialized version */ /* else go through ... actually on second thoughts don't, because this is C#*/ Node node = mainposition(t, key); do { /* check whether `key' is somewhere in the chain */ if (luaO_rawequalObj(key2tval(node), key) != 0) return gval(node); /* that's it */ else node = gnext(node); } while (node != null); return luaO_nilobject; } default: { Node node = mainposition(t, key); do { /* check whether `key' is somewhere in the chain */ if (luaO_rawequalObj(key2tval(node), key) != 0) return gval(node); /* that's it */ else node = gnext(node); } while (node != null); return luaO_nilobject; } } } public static TValue luaH_set (LuaState L, Table t, TValue key) { TValue p = luaH_get(t, key); t.flags = 0; if (p != luaO_nilobject) return (TValue)p; else { if (ttisnil(key)) luaG_runerror(L, "table index is nil"); else if (ttisnumber(key) && luai_numisnan(nvalue(key))) luaG_runerror(L, "table index is NaN"); return newkey(L, t, key); } } public static TValue luaH_setnum (LuaState L, Table t, int key) { TValue p = luaH_getnum(t, key); if (p != luaO_nilobject) return (TValue)p; else { TValue k = new TValue(); setnvalue(k, cast_num(key)); return newkey(L, t, k); } } public static TValue luaH_setstr (LuaState L, Table t, TString key) { TValue p = luaH_getstr(t, key); if (p != luaO_nilobject) return (TValue)p; else { TValue k = new TValue(); setsvalue(L, k, key); return newkey(L, t, k); } } public static int unbound_search (Table t, uint j) { uint i = j; /* i is zero or a present index */ j++; /* find `i' and `j' such that i is present and j is not */ while (!ttisnil(luaH_getnum(t, (int)j))) { i = j; j *= 2; if (j > (uint)MAX_INT) { /* overflow? */ /* table was built with bad purposes: resort to linear search */ i = 1; while (!ttisnil(luaH_getnum(t, (int)i))) i++; return (int)(i - 1); } } /* now do a binary search between them */ while (j - i > 1) { uint m = (i+j)/2; if (ttisnil(luaH_getnum(t, (int)m))) j = m; else i = m; } return (int)i; } /* ** Try to find a boundary in table `t'. A `boundary' is an integer index ** such that t[i] is non-nil and t[i+1] is nil (and 0 if t[1] is nil). */ public static int luaH_getn (Table t) { uint j = (uint)t.sizearray; if (j > 0 && ttisnil(t.array[j - 1])) { /* there is a boundary in the array part: (binary) search for it */ uint i = 0; while (j - i > 1) { uint m = (i+j)/2; if (ttisnil(t.array[m - 1])) j = m; else i = m; } return (int)i; } /* else must find a boundary in hash part */ else if (t.node[0] == dummynode) /* hash part is empty? */ return (int)j; /* that is easy... */ else return unbound_search(t, j); } //#if defined(LUA_DEBUG) //Node *luaH_mainposition (const table *t, const TValue *key) { // return mainposition(t, key); //} //int luaH_isdummy (Node *n) { return n == dummynode; } //#endif } }
//! \file ArcNPA.cs //! \date Fri Jul 18 04:07:42 2014 //! \brief NPA archive format implementation. // // Copyright (C) 2014 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.Text; using System.ComponentModel.Composition; using System.Collections.Generic; using System.Diagnostics; using System.Runtime.InteropServices; using GameRes.Compression; using GameRes.Formats.Strings; using GameRes.Formats.Properties; using GameRes.Strings; namespace GameRes.Formats.NitroPlus { internal class NpaEntry : PackedEntry { public byte[] RawName; public int FolderId; } internal class NpaArchive : ArcFile { public EncryptionScheme Scheme { get; private set; } public int Key { get; private set; } public byte[] KeyTable { get { return m_key_table.Value; } } private Lazy<byte[]> m_key_table; public NpaArchive (ArcView arc, ArchiveFormat impl, ICollection<Entry> dir, EncryptionScheme scheme, int key) : base (arc, impl, dir) { Scheme = scheme; Key = key; m_key_table = new Lazy<byte[]> (() => NpaOpener.GenerateKeyTable (scheme)); } } [Serializable] public class EncryptionScheme { public NpaTitleId TitleId; public uint NameKey; public byte[] Order; public EncryptionScheme (NpaTitleId id, uint key, byte[] order) { TitleId = id; NameKey = key; Order = order; } } [Serializable] public class NpaScheme : ResourceScheme { public Dictionary<string, EncryptionScheme> KnownSchemes; } public enum NpaTitleId { NotEncrypted, CHAOSHEAD, CHAOSHEADTR1, CHAOSHEADTR2, MURAMASATR, MURAMASA, SUMAGA, DJANGO, DJANGOTR, LAMENTO, SWEETPOOL, SUMAGASP, DEMONBANE, MURAMASAAD, AXANAEL, KIKOKUGAI, SONICOMITR2, SUMAGA3P, SONICOMI, LOSTX, LOSTXTRAILER, DRAMATICALMURDER, TOTONO, PHENOMENO, NEKODA, HANACHIRASU } public class NpaOptions : ResourceOptions { public EncryptionScheme Scheme { get; set; } public bool CompressContents { get; set; } public int Key1 { get; set; } public int Key2 { get; set; } } [Export(typeof(ArchiveFormat))] public class NpaOpener : ArchiveFormat { public override string Tag { get { return "NPA"; } } public override string Description { get { return arcStrings.NPADescription; } } public override uint Signature { get { return 0x0141504e; } } // NPA\x01 public override bool IsHierarchic { get { return true; } } public override bool CanWrite { get { return true; } } public static Dictionary<string, EncryptionScheme> KnownSchemes = new Dictionary<string, EncryptionScheme>(); public override ResourceScheme Scheme { get { return new NpaScheme { KnownSchemes = KnownSchemes }; } set { KnownSchemes = ((NpaScheme)value).KnownSchemes; } } public const int DefaultKey1 = 0x4147414e; public const int DefaultKey2 = 0x21214f54; public override ArcFile TryOpen (ArcView file) { int key1 = file.View.ReadInt32 (7); int key2 = file.View.ReadInt32 (11); bool compressed = 0 != file.View.ReadByte (15); bool encrypted = 0 != file.View.ReadByte (16); int total_count = file.View.ReadInt32 (17); int folder_count = file.View.ReadInt32 (21); int file_count = file.View.ReadInt32 (25); if (total_count < folder_count + file_count) return null; uint dir_size = file.View.ReadUInt32 (37); if (dir_size >= file.MaxOffset) return null; EncryptionScheme enc = null; var game_id = NpaTitleId.NotEncrypted; if (encrypted) { enc = QueryGameEncryption (file.Name); if (null == enc) throw new OperationCanceledException (garStrings.MsgUnknownEncryption); game_id = enc.TitleId; } int key = GetArchiveKey (game_id, key1, key2); long cur_offset = 41; var dir = new List<Entry> (file_count); for (int i = 0; i < total_count; ++i) { int name_size = file.View.ReadInt32 (cur_offset); if ((uint)name_size >= dir_size) return null; int type = file.View.ReadByte (cur_offset+4+name_size); if (1 != type) // ignore directory entries { var raw_name = new byte[name_size]; file.View.Read (cur_offset+4, raw_name, 0, (uint)name_size); for (int x = 0; x < name_size; ++x) raw_name[x] += DecryptName (x, i, key); var info_offset = cur_offset + 5 + name_size; int id = file.View.ReadInt32 (info_offset); uint offset = file.View.ReadUInt32 (info_offset+4); uint size = file.View.ReadUInt32 (info_offset+8); uint unpacked_size = file.View.ReadUInt32 (info_offset+12); var entry = new NpaEntry { Name = Encodings.cp932.GetString (raw_name), Offset = dir_size+offset+41, Size = size, UnpackedSize = unpacked_size, RawName = raw_name, FolderId = id, }; if (!entry.CheckPlacement (file.MaxOffset)) return null; entry.Type = FormatCatalog.Instance.GetTypeFromName (entry.Name); entry.IsPacked = compressed && entry.Type != "image"; dir.Add (entry); } cur_offset += 4 + name_size + 17; } if (enc != null) return new NpaArchive (file, this, dir, enc, key); else return new ArcFile (file, this, dir); } public override void Create (Stream output, IEnumerable<Entry> list, ResourceOptions options, EntryCallback callback) { var npa_options = GetOptions<NpaOptions> (options); int callback_count = 0; // build file index var index = new Indexer (list, npa_options); output.Position = 41 + index.Size; long data_offset = 0; // write files foreach (var entry in index.Entries.Where (e => e.Type != "directory")) { if (data_offset > uint.MaxValue) throw new FileSizeException(); if (null != callback) callback (callback_count++, entry, arcStrings.MsgAddingFile); using (var file = File.OpenRead (entry.Name)) { var size = file.Length; if (size > uint.MaxValue) throw new FileSizeException(); entry.Offset = data_offset; entry.UnpackedSize = (uint)size; Stream destination = output; if (null != npa_options.Scheme) destination = new EncryptedStream (output, entry, npa_options.Scheme, index.Key); try { if (entry.IsPacked) { var start = destination.Position; using (var zstream = new ZLibStream (destination, CompressionMode.Compress, CompressionLevel.Level9, true)) { file.CopyTo (zstream); } entry.Size = (uint)(destination.Position - start); } else { file.CopyTo (destination); entry.Size = entry.UnpackedSize; } } finally { if (destination is EncryptedStream) destination.Dispose(); } data_offset += entry.Size; } } if (null != callback) callback (callback_count++, null, arcStrings.MsgWritingIndex); output.Position = 0; using (var header = new BinaryWriter (output, Encoding.ASCII, true)) { header.Write (Signature); header.Write ((short)0); header.Write ((byte)0); header.Write (npa_options.Key1); header.Write (npa_options.Key2); header.Write (npa_options.CompressContents); header.Write (npa_options.Scheme != null); header.Write (index.TotalCount); header.Write (index.FolderCount); header.Write (index.FileCount); header.Write ((long)0); header.Write (index.Size); int entry_number = 0; foreach (var entry in index.Entries) { header.Write (entry.RawName.Length); for (int i = 0; i < entry.RawName.Length; ++i) { header.Write ((byte)(entry.RawName[i] - DecryptName (i, entry_number, index.Key))); } header.Write ((byte)("directory" == entry.Type ? 1 : 2)); header.Write (entry.FolderId); header.Write ((uint)entry.Offset); header.Write (entry.Size); header.Write (entry.UnpackedSize); ++entry_number; } } } public override Stream OpenEntry (ArcFile arc, Entry entry) { Stream input; if (arc is NpaArchive && entry is NpaEntry) input = new EncryptedStream (arc as NpaArchive, entry as NpaEntry); else input = arc.File.CreateStream (entry.Offset, entry.Size); return UnpackEntry (input, entry as PackedEntry); } private Stream UnpackEntry (Stream input, PackedEntry entry) { if (null != entry && entry.IsPacked) return new ZLibStream (input, CompressionMode.Decompress); return input; } internal static byte DecryptName (int index, int curfile, int arc_key) { int key = 0xFC*index; key -= arc_key >> 0x18; key -= arc_key >> 0x10; key -= arc_key >> 0x08; key -= arc_key & 0xff; key -= curfile >> 0x18; key -= curfile >> 0x10; key -= curfile >> 0x08; key -= curfile; return (byte)(key & 0xff); } internal static int GetArchiveKey (NpaTitleId game_id, int key1, int key2) { if (NpaTitleId.LAMENTO == game_id) return key1 + key2; else return key1 * key2; } internal static byte GetKeyFromEntry (NpaEntry entry, EncryptionScheme scheme, int arc_key) { int key = (int)scheme.NameKey; var name = entry.RawName; for (int i = 0; i < name.Length; ++i) key -= name[i]; key *= name.Length; if (scheme.TitleId != NpaTitleId.LAMENTO) // if the game is not Lamento { key += arc_key; key *= (int)entry.UnpackedSize; } return (byte)key; } public static byte[] GenerateKeyTable (EncryptionScheme scheme) { byte[] order = scheme.Order; if (null == order) throw new ArgumentException ("Encryption key table not defined", "title_id"); var table = new byte[256]; for (int i = 0; i < 256; ++i) { int edx = i << 4; int dl = (edx + order[i & 0x0f]) & 0xff; int dh = (edx + (order[i>>4] << 8)) & 0xff00; edx = (dh | dl) >> 4; var eax = BaseTable[i]; table[eax] = (byte)(edx & 0xff); } for (int i = 17; i < order.Length; i+=2) { int ecx = order[i-1]; int edx = order[i]; byte tmp = table[ecx]; table[ecx] = table[edx]; table[edx] = tmp; } if (NpaTitleId.TOTONO == scheme.TitleId) { var totono_table = new byte[256]; for (int i = 0; i < 256; ++i) { byte r = table[i]; r = table[r]; r = table[r]; totono_table[i] = (byte)~r; } table = totono_table; } return table; } public override ResourceOptions GetDefaultOptions () { return new NpaOptions { Scheme = GetScheme (Properties.Settings.Default.NPAScheme), CompressContents = Properties.Settings.Default.NPACompressContents, Key1 = (int)Properties.Settings.Default.NPAKey1, Key2 = (int)Properties.Settings.Default.NPAKey2, }; } public override object GetAccessWidget () { return new GUI.WidgetNPA(); } public override object GetCreationWidget () { return new GUI.CreateNPAWidget(); } EncryptionScheme QueryGameEncryption (string arc_name) { EncryptionScheme scheme = null; var title = FormatCatalog.Instance.LookupGame (arc_name); if (!string.IsNullOrEmpty (title)) scheme = GetScheme (title); if (null == scheme) { var options = Query<NpaOptions> (arcStrings.ArcEncryptedNotice); scheme = options.Scheme; } return scheme; } public static NpaTitleId GetTitleId (string title) { var scheme = GetScheme (title); return scheme != null ? scheme.TitleId : NpaTitleId.NotEncrypted; } public static EncryptionScheme GetScheme (string title) { EncryptionScheme scheme; if (KnownSchemes.TryGetValue (title, out scheme)) return scheme; else return null; } static readonly byte[] BaseTable = { 0x6F,0x05,0x6A,0xBF,0xA1,0xC7,0x8E,0xFB,0xD4,0x2F,0x80,0x58,0x4A,0x17,0x3B,0xB1, 0x89,0xEC,0xA0,0x9F,0xD3,0xFC,0xC2,0x04,0x68,0x03,0xF3,0x25,0xBE,0x24,0xF1,0xBD, 0xB8,0x41,0xC9,0x27,0x0E,0xA3,0xD8,0x7F,0x5B,0x8F,0x16,0x49,0xAA,0xB2,0x18,0xA7, 0x33,0xE4,0xDB,0x48,0xCA,0xDE,0xAE,0xCD,0x13,0x1F,0x15,0x2E,0x39,0xF5,0x1E,0xDD, 0x0F,0x88,0x4C,0x98,0x36,0xB4,0x3F,0x09,0x83,0xFD,0x32,0xBA,0x14,0x30,0x7A,0x63, 0xB9,0x56,0x95,0x61,0xCC,0x8B,0xEF,0xDA,0xE5,0x2C,0xDC,0x12,0x1A,0x67,0x23,0x50, 0xD1,0xC3,0x7E,0x6D,0xB6,0x90,0x3C,0xB3,0x0B,0xE2,0x91,0x70,0xA8,0xDF,0x44,0xC4, 0xF4,0x01,0x5C,0x10,0x06,0xE7,0x54,0x40,0x43,0x72,0x38,0xBC,0xE3,0x07,0xFA,0x34, 0x02,0xA4,0xF7,0x74,0xA9,0x4D,0x42,0xA5,0x85,0x35,0x79,0xD2,0x76,0x97,0x45,0x4F, 0x08,0x5A,0xB0,0xEE,0x51,0x73,0x69,0x9E,0x94,0x47,0x77,0x29,0xD9,0x64,0x11,0xEB, 0x37,0xAC,0x20,0x62,0x9A,0x6B,0x9C,0x75,0x22,0x87,0xAB,0x78,0x53,0xC8,0x5D,0xAD, 0x2A,0xF2,0xCB,0xB7,0x0D,0xED,0x86,0x55,0xFF,0x19,0x57,0xD7,0xD5,0x60,0xC6,0x3D, 0xEA,0xC1,0x6C,0xE1,0xC0,0x65,0x84,0xC5,0xE0,0x3E,0x7D,0x28,0x66,0xAF,0x1C,0x9B, 0xCF,0x81,0x4E,0x26,0x59,0x2B,0x5F,0x7B,0xE8,0x8D,0x52,0x7C,0xF8,0x82,0x0C,0xF9, 0x8C,0xE9,0xB5,0xE6,0x31,0x93,0x46,0x5E,0x1D,0x1B,0x4B,0x71,0xD6,0x92,0x3A,0xA6, 0x2D,0x00,0x9D,0xBB,0x6E,0xF0,0x99,0xCE,0x21,0x0A,0xD0,0xF6,0xFE,0xA2,0x8A,0x96, }; } /// <summary> /// Archive creation helper. /// </summary> internal class Indexer { List<NpaEntry> m_entries; Encoding m_encoding = Encodings.cp932.WithFatalFallback(); int m_key; int m_size = 0; int m_directory_count = 0; int m_file_count = 0; public IEnumerable<NpaEntry> Entries { get { return m_entries; } } public int Key { get { return m_key; } } public int Size { get { return m_size; } } public int TotalCount { get { return m_entries.Count; } } public int FolderCount { get { return m_directory_count; } } public int FileCount { get { return m_file_count; } } public Indexer (IEnumerable<Entry> source_list, NpaOptions options) { m_entries = new List<NpaEntry> (source_list.Count()); var title_id = null != options.Scheme ? options.Scheme.TitleId : NpaTitleId.NotEncrypted; m_key = NpaOpener.GetArchiveKey (title_id, options.Key1, options.Key2); foreach (var entry in source_list) { string name = entry.Name; try { var dir = Path.GetDirectoryName (name); int folder_id = 0; if (!string.IsNullOrEmpty (dir)) folder_id = AddDirectory (dir); bool compress = options.CompressContents; if (compress) // don't compress images compress = !FormatCatalog.Instance.LookupFileName (name).OfType<ImageFormat>().Any(); var npa_entry = new NpaEntry { Name = name, IsPacked = compress, RawName = m_encoding.GetBytes (name), FolderId = folder_id, }; ++m_file_count; AddEntry (npa_entry); } catch (EncoderFallbackException X) { throw new InvalidFileName (name, arcStrings.MsgIllegalCharacters, X); } } } void AddEntry (NpaEntry entry) { m_entries.Add (entry); m_size += 4 + entry.RawName.Length + 17; } Dictionary<string, int> m_directory_map = new Dictionary<string, int>(); int AddDirectory (string dir) { int folder_id = 0; if (m_directory_map.TryGetValue (dir, out folder_id)) return folder_id; string path = ""; foreach (var component in dir.Split (Path.DirectorySeparatorChar)) { path = Path.Combine (path, component); if (m_directory_map.TryGetValue (path, out folder_id)) continue; folder_id = ++m_directory_count; m_directory_map[path] = folder_id; var npa_entry = new NpaEntry { Name = path, Type = "directory", Offset = 0, Size = 0, UnpackedSize = 0, IsPacked = false, RawName = m_encoding.GetBytes (path), FolderId = folder_id, }; AddEntry (npa_entry); } return folder_id; } } /// <summary> /// Stream class for files stored in encrypted NPA archives. /// </summary> internal class EncryptedStream : Stream { private Stream m_stream; private Lazy<byte[]> m_encrypted; private int m_encrypted_length; private bool m_read_mode; private long m_base_pos; public override bool CanRead { get { return m_read_mode && m_stream.CanRead; } } public override bool CanSeek { get { return m_stream.CanSeek; } } public override bool CanWrite { get { return !m_read_mode && m_stream.CanWrite; } } public override long Length { get { return m_stream.Length - m_base_pos; } } public override long Position { get { return m_stream.Position - m_base_pos; } set { m_stream.Position = m_base_pos + value; } } delegate byte CryptFunc (int index, byte value); CryptFunc Encrypt; public EncryptedStream (NpaArchive arc, NpaEntry entry) { m_read_mode = true; m_encrypted_length = GetEncryptedLength (entry, arc.Scheme.TitleId); if (m_encrypted_length > entry.Size) m_encrypted_length = (int)entry.Size; int key = NpaOpener.GetKeyFromEntry (entry, arc.Scheme, arc.Key); m_stream = arc.File.CreateStream (entry.Offset, entry.Size); m_encrypted = new Lazy<byte[]> (() => InitEncrypted (key, arc.Scheme.TitleId, arc.KeyTable)); m_base_pos = m_stream.Position; } public EncryptedStream (Stream output, NpaEntry entry, EncryptionScheme scheme, int arc_key) { m_read_mode = false; m_encrypted_length = GetEncryptedLength (entry, scheme.TitleId); int key = NpaOpener.GetKeyFromEntry (entry, scheme, arc_key); m_stream = output; m_encrypted = new Lazy<byte[]> (() => new byte[m_encrypted_length]); m_base_pos = m_stream.Position; byte[] decrypt_table = NpaOpener.GenerateKeyTable (scheme); byte[] encrypt_table = new byte[256]; for (int i = 0; i < 256; ++i) encrypt_table[decrypt_table[i]] = (byte)i; if (NpaTitleId.LAMENTO == scheme.TitleId) { Encrypt = (i, x) => encrypt_table[(x + key) & 0xff]; } else { Encrypt = (i, x) => encrypt_table[(x + key + i) & 0xff]; } } int GetEncryptedLength (NpaEntry entry, NpaTitleId game_id) { int length = 0x1000; if (game_id != NpaTitleId.LAMENTO) length += entry.RawName.Length; return length; } byte[] InitEncrypted (int key, NpaTitleId game_id, byte[] key_table) { var position = Position; if (0 != position) Position = 0; byte[] buffer = new byte[m_encrypted_length]; m_encrypted_length = m_stream.Read (buffer, 0, m_encrypted_length); Position = position; if (game_id == NpaTitleId.LAMENTO) { for (int i = 0; i < m_encrypted_length; i++) buffer[i] = (byte)(key_table[buffer[i]] - key); } else { for (int i = 0; i < m_encrypted_length; i++) buffer[i] = (byte)(key_table[buffer[i]] - key - i); } return buffer; } #region System.IO.Stream methods public override void Flush() { m_stream.Flush(); } public override long Seek (long offset, SeekOrigin origin) { if (SeekOrigin.Begin == origin) offset += m_base_pos; offset = m_stream.Seek (offset, origin); return offset - m_base_pos; } public override void SetLength (long length) { throw new NotSupportedException ("EncryptedStream.SetLength is not supported"); } public override int Read (byte[] buffer, int offset, int count) { var position = Position; if (position >= m_encrypted_length) return m_stream.Read (buffer, offset, count); int read = Math.Min (m_encrypted_length - (int)position, count); Buffer.BlockCopy (m_encrypted.Value, (int)position, buffer, offset, read); m_stream.Seek (read, SeekOrigin.Current); if (read < count) { read += m_stream.Read (buffer, offset+read, count-read); } return read; } public override int ReadByte () { var position = Position; if (position >= m_encrypted_length) return m_stream.ReadByte(); m_stream.Seek (1, SeekOrigin.Current); return m_encrypted.Value[(int)position]; } public override void Write (byte[] buffer, int offset, int count) { var position = Position; if (position < m_encrypted_length) { int limit = (int)position + Math.Min (m_encrypted_length - (int)position, count); for (int i = (int)position; i < limit; ++i, ++offset, --count) { m_encrypted.Value[i] = Encrypt (i, buffer[offset]); } m_stream.Write (m_encrypted.Value, (int)position, limit-(int)position); } if (count > 0) m_stream.Write (buffer, offset, count); } public override void WriteByte (byte value) { var position = Position; if (position < m_encrypted_length) value = Encrypt ((int)position, value); m_stream.WriteByte (value); } #endregion #region IDisposable Members bool disposed = false; protected override void Dispose (bool disposing) { if (!disposed) { if (disposing && m_read_mode) { m_stream.Dispose(); } m_encrypted = null; disposed = true; base.Dispose (disposing); } } #endregion } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Reflection; using System.Text; using System.Threading; using System.Web; using log4net; namespace OpenSim.Framework.Communications { /// <summary> /// Implementation of a generic REST client /// </summary> /// <remarks> /// This class is a generic implementation of a REST (Representational State Transfer) web service. This /// class is designed to execute both synchronously and asynchronously. /// /// Internally the implementation works as a two stage asynchronous web-client. /// When the request is initiated, RestClient will query asynchronously for for a web-response, /// sleeping until the initial response is returned by the server. Once the initial response is retrieved /// the second stage of asynchronous requests will be triggered, in an attempt to read of the response /// object into a memorystream as a sequence of asynchronous reads. /// /// The asynchronisity of RestClient is designed to move as much processing into the back-ground, allowing /// other threads to execute, while it waits for a response from the web-service. RestClient itself can be /// invoked by the caller in either synchronous mode or asynchronous modes. /// </remarks> public class RestClient { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); // private string realuri; #region member variables /// <summary> /// The base Uri of the web-service e.g. http://www.google.com /// </summary> private string _url; /// <summary> /// Path elements of the query /// </summary> private List<string> _pathElements = new List<string>(); /// <summary> /// Parameter elements of the query, e.g. min=34 /// </summary> private Dictionary<string, string> _parameterElements = new Dictionary<string, string>(); /// <summary> /// Request method. E.g. GET, POST, PUT or DELETE /// </summary> private string _method; /// <summary> /// Temporary buffer used to store bytes temporarily as they come in from the server /// </summary> private byte[] _readbuf; /// <summary> /// MemoryStream representing the resultiong resource /// </summary> private Stream _resource; /// <summary> /// WebRequest object, held as a member variable /// </summary> private HttpWebRequest _request; /// <summary> /// WebResponse object, held as a member variable, so we can close it /// </summary> private HttpWebResponse _response; /// <summary> /// This flag will help block the main synchroneous method, in case we run in synchroneous mode /// </summary> //public static ManualResetEvent _allDone = new ManualResetEvent(false); /// <summary> /// Default time out period /// </summary> //private const int DefaultTimeout = 10*1000; // 10 seconds timeout /// <summary> /// Default Buffer size of a block requested from the web-server /// </summary> private const int BufferSize = 4096; // Read blocks of 4 KB. /// <summary> /// if an exception occours during async processing, we need to save it, so it can be /// rethrown on the primary thread; /// </summary> private Exception _asyncException; #endregion member variables #region constructors /// <summary> /// Instantiate a new RestClient /// </summary> /// <param name="url">Web-service to query, e.g. http://osgrid.org:8003</param> public RestClient(string url) { _url = url; _readbuf = new byte[BufferSize]; _resource = new MemoryStream(); _request = null; _response = null; _lock = new object(); } private object _lock; #endregion constructors /// <summary> /// Add a path element to the query, e.g. assets /// </summary> /// <param name="element">path entry</param> public void AddResourcePath(string element) { if (isSlashed(element)) _pathElements.Add(element.Substring(0, element.Length - 1)); else _pathElements.Add(element); } /// <summary> /// Add a query parameter to the Url /// </summary> /// <param name="name">Name of the parameter, e.g. min</param> /// <param name="value">Value of the parameter, e.g. 42</param> public void AddQueryParameter(string name, string value) { try { _parameterElements.Add(HttpUtility.UrlEncode(name), HttpUtility.UrlEncode(value)); } catch (ArgumentException) { m_log.Error("[REST]: Query parameter " + name + " is already added."); } catch (Exception e) { m_log.Error("[REST]: An exception was raised adding query parameter to dictionary. Exception: {0}",e); } } /// <summary> /// Add a query parameter to the Url /// </summary> /// <param name="name">Name of the parameter, e.g. min</param> public void AddQueryParameter(string name) { try { _parameterElements.Add(HttpUtility.UrlEncode(name), null); } catch (ArgumentException) { m_log.Error("[REST]: Query parameter " + name + " is already added."); } catch (Exception e) { m_log.Error("[REST]: An exception was raised adding query parameter to dictionary. Exception: {0}",e); } } /// <summary> /// Web-Request method, e.g. GET, PUT, POST, DELETE /// </summary> public string RequestMethod { get { return _method; } set { _method = value; } } /// <summary> /// True if string contains a trailing slash '/' /// </summary> /// <param name="s">string to be examined</param> /// <returns>true if slash is present</returns> private static bool isSlashed(string s) { return s.Substring(s.Length - 1, 1) == "/"; } /// <summary> /// Build a Uri based on the initial Url, path elements and parameters /// </summary> /// <returns>fully constructed Uri</returns> private Uri buildUri() { StringBuilder sb = new StringBuilder(); sb.Append(_url); foreach (string e in _pathElements) { sb.Append("/"); sb.Append(e); } bool firstElement = true; foreach (KeyValuePair<string, string> kv in _parameterElements) { if (firstElement) { sb.Append("?"); firstElement = false; } else sb.Append("&"); sb.Append(kv.Key); if (!string.IsNullOrEmpty(kv.Value)) { sb.Append("="); sb.Append(kv.Value); } } // realuri = sb.ToString(); //m_log.InfoFormat("[REST CLIENT]: RestURL: {0}", realuri); return new Uri(sb.ToString()); } #region Async communications with server /// <summary> /// Async method, invoked when a block of data has been received from the service /// </summary> /// <param name="ar"></param> private void StreamIsReadyDelegate(IAsyncResult ar) { try { Stream s = (Stream) ar.AsyncState; int read = s.EndRead(ar); if (read > 0) { _resource.Write(_readbuf, 0, read); // IAsyncResult asynchronousResult = // s.BeginRead(_readbuf, 0, BufferSize, new AsyncCallback(StreamIsReadyDelegate), s); s.BeginRead(_readbuf, 0, BufferSize, new AsyncCallback(StreamIsReadyDelegate), s); // TODO! Implement timeout, without killing the server //ThreadPool.RegisterWaitForSingleObject(asynchronousResult.AsyncWaitHandle, new WaitOrTimerCallback(TimeoutCallback), _request, DefaultTimeout, true); } else { s.Close(); //_allDone.Set(); } } catch (Exception e) { //_allDone.Set(); _asyncException = e; } } #endregion Async communications with server /// <summary> /// Perform a synchronous request /// </summary> public Stream Request() { lock (_lock) { _request = (HttpWebRequest) WebRequest.Create(buildUri()); _request.KeepAlive = false; _request.ContentType = "application/xml"; _request.Timeout = 200000; _request.Method = RequestMethod; _asyncException = null; // IAsyncResult responseAsyncResult = _request.BeginGetResponse(new AsyncCallback(ResponseIsReadyDelegate), _request); try { _response = (HttpWebResponse) _request.GetResponse(); } catch (WebException e) { HttpWebResponse errorResponse = e.Response as HttpWebResponse; if (null != errorResponse && HttpStatusCode.NotFound == errorResponse.StatusCode) { m_log.Warn("[REST CLIENT] Resource not found (404)"); } else { m_log.Error("[REST CLIENT] Error fetching resource from server " + _request.Address.ToString()); m_log.Debug(e.ToString()); } return null; } Stream src = _response.GetResponseStream(); int length = src.Read(_readbuf, 0, BufferSize); while (length > 0) { _resource.Write(_readbuf, 0, length); length = src.Read(_readbuf, 0, BufferSize); } // TODO! Implement timeout, without killing the server // this line implements the timeout, if there is a timeout, the callback fires and the request becomes aborted //ThreadPool.RegisterWaitForSingleObject(responseAsyncResult.AsyncWaitHandle, new WaitOrTimerCallback(TimeoutCallback), _request, DefaultTimeout, true); // _allDone.WaitOne(); if (_response != null) _response.Close(); if (_asyncException != null) throw _asyncException; if (_resource != null) { _resource.Flush(); _resource.Seek(0, SeekOrigin.Begin); } return _resource; } } public Stream Request(Stream src) { _request = (HttpWebRequest) WebRequest.Create(buildUri()); _request.KeepAlive = false; _request.ContentType = "application/xml"; _request.Timeout = 900000; _request.Method = RequestMethod; _asyncException = null; _request.ContentLength = src.Length; m_log.InfoFormat("[REST]: Request Length {0}", _request.ContentLength); m_log.InfoFormat("[REST]: Sending Web Request {0}", buildUri()); src.Seek(0, SeekOrigin.Begin); m_log.Info("[REST]: Seek is ok"); Stream dst = _request.GetRequestStream(); m_log.Info("[REST]: GetRequestStream is ok"); byte[] buf = new byte[1024]; int length = src.Read(buf, 0, 1024); m_log.Info("[REST]: First Read is ok"); while (length > 0) { dst.Write(buf, 0, length); length = src.Read(buf, 0, 1024); } _response = (HttpWebResponse) _request.GetResponse(); // IAsyncResult responseAsyncResult = _request.BeginGetResponse(new AsyncCallback(ResponseIsReadyDelegate), _request); // TODO! Implement timeout, without killing the server // this line implements the timeout, if there is a timeout, the callback fires and the request becomes aborted //ThreadPool.RegisterWaitForSingleObject(responseAsyncResult.AsyncWaitHandle, new WaitOrTimerCallback(TimeoutCallback), _request, DefaultTimeout, true); return null; } #region Async Invocation public IAsyncResult BeginRequest(AsyncCallback callback, object state) { /// <summary> /// In case, we are invoked asynchroneously this object will keep track of the state /// </summary> AsyncResult<Stream> ar = new AsyncResult<Stream>(callback, state); Util.FireAndForget(RequestHelper, ar); return ar; } public Stream EndRequest(IAsyncResult asyncResult) { AsyncResult<Stream> ar = (AsyncResult<Stream>) asyncResult; // Wait for operation to complete, then return result or // throw exception return ar.EndInvoke(); } private void RequestHelper(Object asyncResult) { // We know that it's really an AsyncResult<DateTime> object AsyncResult<Stream> ar = (AsyncResult<Stream>) asyncResult; try { // Perform the operation; if sucessful set the result Stream s = Request(); ar.SetAsCompleted(s, false); } catch (Exception e) { // If operation fails, set the exception ar.HandleException(e, false); } } #endregion Async Invocation } }
/** * \file NETGeographicLib\GeodesicPanel.cs * \brief NETGeographicLib.Geodesic example * * NETGeographicLib.Geodesic, * NETGeographicLib.GeodesicLine, * NETGeographicLib.GeodesicExact, * NETGeographicLib.GeodesicLineExact * * NETGeographicLib is copyright (c) Scott Heiman (2013) * GeographicLib is Copyright (c) Charles Karney (2010-2012) * <charles@karney.com> and licensed under the MIT/X11 License. * For more information, see * http://geographiclib.sourceforge.net/ **********************************************************************/ using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Linq; using System.Text; using System.Windows.Forms; using NETGeographicLib; namespace Projections { public partial class GeodesicPanel : UserControl { public string warning = "GeographicLib Error"; public string warning2 = "Data Conversion Error"; enum Function { Direct = 0, Inverse = 1 }; Function m_function = Function.Direct; enum Variable { Distance = 0, ArcLength = 2 }; Variable m_variable = Variable.Distance; enum Classes { GEODESIC = 0, GEODESICEXACT= 1, GEODESICLINE = 2, GEODESICLINEEXACT = 3 }; Classes m_class = Classes.GEODESIC; Geodesic m_geodesic = null; public GeodesicPanel() { InitializeComponent(); m_tooltips.SetToolTip(button1, "Performs the selected function with the selected class"); m_tooltips.SetToolTip(m_setButton, "Sets the ellipsoid attributes"); m_tooltips.SetToolTip(m_validateButton, "Validates Geodesic, GeodesicExact, GeodesicLine, and GeodesicLineExact interfaces"); try { m_geodesic = new Geodesic(); } catch (GeographicErr err) { MessageBox.Show(err.Message, warning, MessageBoxButtons.OK, MessageBoxIcon.Error); } m_majorRadiusTextBox.Text = m_geodesic.MajorRadius.ToString(); m_flatteningTextBox.Text = m_geodesic.Flattening.ToString(); m_functionComboBox.SelectedIndex = 0; m_classComboBox.SelectedIndex = 0; } // gets the major radius and flattening and creates a new Geodesic private void OnSet(object sender, EventArgs e) { try { double radius = Double.Parse(m_majorRadiusTextBox.Text); double flattening = Double.Parse(m_flatteningTextBox.Text); m_geodesic = new Geodesic(radius, flattening); } catch (GeographicErr err) { MessageBox.Show(err.Message, warning, MessageBoxButtons.OK, MessageBoxIcon.Error); } catch (Exception err2) { MessageBox.Show(err2.Message, warning2, MessageBoxButtons.OK, MessageBoxIcon.Error); } } // Gets the input parameters and calls the appropriate function private void OnForward(object sender, EventArgs e) { double origLatitude = 0.0, origLongitude = 0.0, origAzimuth = 0.0, distance = 0.0, finalLatitude = 0.0, finalLongitude = 0.0; // get & validate inputs try { if ( m_function == Function.Direct ) { distance = Double.Parse( m_variable == Variable.Distance ? m_distanceTextBox.Text : m_ArcLengthTextBox.Text ); origAzimuth = Double.Parse( m_originAzimuthTextBox.Text ); if ( origAzimuth < -180.0 || origAzimuth > 180.0 ) { m_originAzimuthTextBox.Focus(); throw new Exception( "Range Error: -180 <= initial azimuth <= 180 degrees" ); } } else { finalLatitude = Double.Parse( m_finalLatitudeTextBox.Text ); if (finalLatitude < -90.0 || finalLatitude > 90.0) { m_finalLatitudeTextBox.Focus(); throw new Exception("Range Error: -90 <= final latitude <= 90 degrees"); } finalLongitude = Double.Parse( m_finalLongitudeTextBox.Text ); if (finalLongitude < -540.0 || finalLongitude > 540.0) { m_finalLongitudeTextBox.Focus(); throw new Exception("Range Error: -540 <= final longitude <= 540 degrees"); } } origLatitude = Double.Parse( m_originLatitudeTextBox.Text ); if (origLatitude < -90.0 || origLatitude > 90.0) { m_originLatitudeTextBox.Focus(); throw new Exception("Range Error: -90 <= initial latitude <= 90 degrees"); } origLongitude = Double.Parse(m_originLongitudeTextBox.Text); if (origLongitude < -540.0 || origLongitude > 540.0) { m_originLongitudeTextBox.Focus(); throw new Exception("Range Error: -540 <= initial longitude <= 540 degrees"); } } catch ( Exception xcpt ) { MessageBox.Show(xcpt.Message, warning2, MessageBoxButtons.OK, MessageBoxIcon.Error); return; } // excute the appropriate function. double finalAzimuth = 0.0, reducedLength = 0.0, M12 = 0.0, M21 = 0.0, S12 = 0.0, arcDistance = 0.0; int sw = (int)m_function | (int)m_variable; if (sw == 3) sw = 1; // cases 1 & 3 are identical. try { switch (m_class) { case Classes.GEODESIC: switch (sw) { case 0: // function == Direct, variable == distance m_ArcLengthTextBox.Text = m_geodesic.Direct(origLatitude, origLongitude, origAzimuth, distance, out finalLatitude, out finalLongitude, out finalAzimuth, out reducedLength, out M12, out M21, out S12).ToString(); m_finalLatitudeTextBox.Text = finalLatitude.ToString(); m_finalLongitudeTextBox.Text = finalLongitude.ToString(); break; case 1: // function == Inverse, variable == distance m_ArcLengthTextBox.Text = m_geodesic.Inverse(origLatitude, origLongitude, finalLatitude, finalLongitude, out distance, out origAzimuth, out finalAzimuth, out reducedLength, out M12, out M21, out S12).ToString(); m_distanceTextBox.Text = distance.ToString(); m_originAzimuthTextBox.Text = origAzimuth.ToString(); break; case 2: // function == Direct, variable == arc length m_geodesic.ArcDirect(origLatitude, origLongitude, origAzimuth, distance, out finalLatitude, out finalLongitude, out finalAzimuth, out arcDistance, out reducedLength, out M12, out M21, out S12); m_distanceTextBox.Text = arcDistance.ToString(); m_finalLatitudeTextBox.Text = finalLatitude.ToString(); m_finalLongitudeTextBox.Text = finalLongitude.ToString(); break; } m_finalAzimuthTextBox.Text = finalAzimuth.ToString(); m_reducedLengthTextBox.Text = reducedLength.ToString(); m_M12TextBox.Text = M12.ToString(); m_M21TextBox.Text = M21.ToString(); m_S12TextBox.Text = S12.ToString(); break; case Classes.GEODESICEXACT: GeodesicExact ge = new GeodesicExact(m_geodesic.MajorRadius, m_geodesic.Flattening); switch (sw) { case 0: // function == Direct, variable == distance m_ArcLengthTextBox.Text = ge.Direct(origLatitude, origLongitude, origAzimuth, distance, out finalLatitude, out finalLongitude, out finalAzimuth, out reducedLength, out M12, out M21, out S12).ToString(); m_finalLatitudeTextBox.Text = finalLatitude.ToString(); m_finalLongitudeTextBox.Text = finalLongitude.ToString(); break; case 1: // function == Inverse, variable == distance m_ArcLengthTextBox.Text = ge.Inverse(origLatitude, origLongitude, finalLatitude, finalLongitude, out distance, out origAzimuth, out finalAzimuth, out reducedLength, out M12, out M21, out S12).ToString(); m_distanceTextBox.Text = distance.ToString(); m_originAzimuthTextBox.Text = origAzimuth.ToString(); break; case 2: // function == Direct, variable == arc length ge.ArcDirect(origLatitude, origLongitude, origAzimuth, distance, out finalLatitude, out finalLongitude, out finalAzimuth, out arcDistance, out reducedLength, out M12, out M21, out S12); m_distanceTextBox.Text = arcDistance.ToString(); m_finalLatitudeTextBox.Text = finalLatitude.ToString(); m_finalLongitudeTextBox.Text = finalLongitude.ToString(); break; } m_finalAzimuthTextBox.Text = finalAzimuth.ToString(); m_reducedLengthTextBox.Text = reducedLength.ToString(); m_M12TextBox.Text = M12.ToString(); m_M21TextBox.Text = M21.ToString(); m_S12TextBox.Text = S12.ToString(); break; case Classes.GEODESICLINE: GeodesicLine gl = new GeodesicLine(m_geodesic, origLatitude, origLongitude, origAzimuth, Mask.ALL); switch (sw) { case 0: // function == Direct, variable == distance m_ArcLengthTextBox.Text = gl.Position(distance, out finalLatitude, out finalLongitude, out finalAzimuth, out reducedLength, out M12, out M21, out S12).ToString(); m_finalLatitudeTextBox.Text = finalLatitude.ToString(); m_finalLongitudeTextBox.Text = finalLongitude.ToString(); break; case 1: // function == Inverse, variable == distance throw new Exception("GeodesicLine does not have an Inverse function"); case 2: // function == Direct, variable == arc length gl.ArcPosition(distance, out finalLatitude, out finalLongitude, out finalAzimuth, out arcDistance, out reducedLength, out M12, out M21, out S12); m_distanceTextBox.Text = arcDistance.ToString(); m_finalLatitudeTextBox.Text = finalLatitude.ToString(); m_finalLongitudeTextBox.Text = finalLongitude.ToString(); break; } m_finalAzimuthTextBox.Text = finalAzimuth.ToString(); m_reducedLengthTextBox.Text = reducedLength.ToString(); m_M12TextBox.Text = M12.ToString(); m_M21TextBox.Text = M21.ToString(); m_S12TextBox.Text = S12.ToString(); break; case Classes.GEODESICLINEEXACT: GeodesicLineExact gle = new GeodesicLineExact(origLatitude, origLongitude, origAzimuth, Mask.ALL); switch (sw) { case 0: // function == Direct, variable == distance m_ArcLengthTextBox.Text = gle.Position(distance, out finalLatitude, out finalLongitude, out finalAzimuth, out reducedLength, out M12, out M21, out S12).ToString(); m_finalLatitudeTextBox.Text = finalLatitude.ToString(); m_finalLongitudeTextBox.Text = finalLongitude.ToString(); break; case 1: // function == Inverse, variable == distance throw new Exception("GeodesicLineExact does not have an Inverse function"); case 2: // function == Direct, variable == arc length gle.ArcPosition(distance, out finalLatitude, out finalLongitude, out finalAzimuth, out arcDistance, out reducedLength, out M12, out M21, out S12); m_distanceTextBox.Text = arcDistance.ToString(); m_finalLatitudeTextBox.Text = finalLatitude.ToString(); m_finalLongitudeTextBox.Text = finalLongitude.ToString(); break; } m_finalAzimuthTextBox.Text = finalAzimuth.ToString(); m_reducedLengthTextBox.Text = reducedLength.ToString(); m_M12TextBox.Text = M12.ToString(); m_M21TextBox.Text = M21.ToString(); m_S12TextBox.Text = S12.ToString(); break; } } catch (Exception err) { MessageBox.Show(err.Message, warning, MessageBoxButtons.OK, MessageBoxIcon.Error); } } // gui stuff private void OnDistance(object sender, EventArgs e) { m_distanceTextBox.ReadOnly = false; m_ArcLengthTextBox.ReadOnly = true; m_variable = Variable.Distance; } // gui stuff private void OnArcLength(object sender, EventArgs e) { m_distanceTextBox.ReadOnly = true; m_ArcLengthTextBox.ReadOnly = false; m_variable = Variable.ArcLength; } // gui stuff private void OnFunction(object sender, EventArgs e) { m_function = (Function)m_functionComboBox.SelectedIndex; switch (m_function) { case Function.Direct: m_distanceTextBox.ReadOnly = m_variable == Variable.ArcLength; m_ArcLengthTextBox.ReadOnly = m_variable == Variable.Distance; m_originAzimuthTextBox.ReadOnly = false; m_finalLatitudeTextBox.ReadOnly = true; m_finalLongitudeTextBox.ReadOnly = true; break; case Function.Inverse: m_distanceTextBox.ReadOnly = true; m_ArcLengthTextBox.ReadOnly = true; m_originAzimuthTextBox.ReadOnly = true; m_finalLatitudeTextBox.ReadOnly = false; m_finalLongitudeTextBox.ReadOnly = false; break; } } // gui stuff private void OnClassChanged(object sender, EventArgs e) { m_class = (Classes)m_classComboBox.SelectedIndex; } // a simple validation function...does not change GUI elements private void OnValidate(object sender, EventArgs e) { double finalAzimuth = 0.0, reducedLength = 0.0, M12 = 0.0, M21 = 0.0, S12 = 0.0, arcDistance = 0.0, finalLatitude = 0.0, finalLongitude = 0.0, distance = 0.0; try { Geodesic g = new Geodesic(); g = new Geodesic(g.MajorRadius, g.Flattening); arcDistance = g.Direct(32.0, -86.0, 45.0, 20000.0, out finalLatitude, out finalLongitude, out finalAzimuth, out reducedLength, out M12, out M21, out S12); double flat = 0.0, flon = 0.0, faz = 0.0, frd = 0.0, fm12 = 0.0, fm21 = 0.0, fs12 = 0.0, fad = 0.0; fad = g.Direct(32.0, -86.0, 45.0, 20000.0, out flat, out flon); if (fad != arcDistance || flat != finalLatitude || flon != finalLongitude) throw new Exception("Geodesic.Direct #1 failed"); fad = g.Direct(32.0, -86.0, 45.0, 20000.0, out flat, out flon, out faz); if (fad != arcDistance || flat != finalLatitude || flon != finalLongitude || faz != finalAzimuth) throw new Exception("Geodesic.Direct #2 failed"); fad = g.Direct(32.0, -86.0, 45.0, 20000.0, out flat, out flon, out faz, out frd); if (fad != arcDistance || flat != finalLatitude || flon != finalLongitude || faz != finalAzimuth || frd != reducedLength) throw new Exception("Geodesic.Direct #3 failed"); fad = g.Direct(32.0, -86.0, 45.0, 20000.0, out flat, out flon, out faz, out fm12, out fm21); if (fad != arcDistance || flat != finalLatitude || flon != finalLongitude || faz != finalAzimuth || fm12 != M12 || fm21 != M21) throw new Exception("Geodesic.Direct #4 failed"); fad = g.Direct(32.0, -86.0, 45.0, 20000.0, out flat, out flon, out faz, out frd, out fm12, out fm21); if (fad != arcDistance || flat != finalLatitude || flon != finalLongitude || faz != finalAzimuth || frd != reducedLength || fm12 != M12 || fm21 != M21) throw new Exception("Geodesic.Direct #5 failed"); double outd = 0.0; fad = g.GenDirect(32.0, -86.0, 45.0, false, 20000.0, Mask.ALL, out flat, out flon, out faz, out outd, out frd, out fm12, out fm21, out fs12); if (fad != arcDistance || flat != finalLatitude || flon != finalLongitude || faz != finalAzimuth || frd != reducedLength || fm12 != M12 || fm21 != M21 || outd != 20000.0 || fs12 != S12) throw new Exception("Geodesic.GenDirect (false) failed"); g.ArcDirect(32.0, -86.0, 45.0, 1.0, out finalLatitude, out finalLongitude, out finalAzimuth, out arcDistance, out reducedLength, out M12, out M21, out S12); g.ArcDirect(32.0, -86.0, 45.0, 1.0, out flat, out flon); if (flat != finalLatitude || flon != finalLongitude) throw new Exception("Geodesic.ArcDirect #1 failed"); g.ArcDirect(32.0, -86.0, 45.0, 1.0, out flat, out flon, out faz); if (flat != finalLatitude || flon != finalLongitude || faz != finalAzimuth) throw new Exception("Geodesic.ArcDirect #2 failed"); g.ArcDirect(32.0, -86.0, 45.0, 1.0, out flat, out flon, out faz, out fad); if (flat != finalLatitude || flon != finalLongitude || faz != finalAzimuth || fad != arcDistance) throw new Exception("Geodesic.ArcDirect #3 failed"); g.ArcDirect(32.0, -86.0, 45.0, 1.0, out flat, out flon, out faz, out fad, out frd); if (flat != finalLatitude || flon != finalLongitude || faz != finalAzimuth || fad != arcDistance || frd != reducedLength) throw new Exception("Geodesic.ArcDirect #4 failed"); g.ArcDirect(32.0, -86.0, 45.0, 1.0, out flat, out flon, out faz, out fad, out fm12, out fm21); if (flat != finalLatitude || flon != finalLongitude || faz != finalAzimuth || fad != arcDistance || fm12 != M12 || fm21 != M21) throw new Exception("Geodesic.ArcDirect #5 failed"); fad = g.GenDirect(32.0, -86.0, 45.0, true, 1.0, Mask.ALL, out flat, out flon, out faz, out outd, out frd, out fm12, out fm21, out fs12); if (outd != arcDistance || flat != finalLatitude || flon != finalLongitude || faz != finalAzimuth || frd != reducedLength || fm12 != M12 || fm21 != M21 || fs12 != S12 || fad != 1.0) throw new Exception("Geodesic.GenDirect (true) failed"); double initAzimuth = 0.0, iaz = 0.0; arcDistance = g.Inverse(32.0, -86.0, 33.0, -87.0, out distance, out initAzimuth, out finalAzimuth, out reducedLength, out M12, out M21, out S12); fad = g.Inverse(32.0, -86.0, 33.0, -87.0, out outd); if (fad != arcDistance || outd != distance) throw new Exception("Geodesic.Inverse #1 failed"); fad = g.Inverse(32.0, -86.0, 33.0, -87.0, out iaz, out faz); if (fad != arcDistance || iaz != initAzimuth || faz != finalAzimuth) throw new Exception("Geodesic.Inverse #2 failed"); fad = g.Inverse(32.0, -86.0, 33.0, -87.0, out outd, out iaz, out faz); if (fad != arcDistance || outd != distance || faz != finalAzimuth || outd != distance) throw new Exception("Geodesic.Inverse #3 failed"); fad = g.Inverse(32.0, -86.0, 33.0, -87.0, out outd, out iaz, out faz, out frd); if (fad != arcDistance || outd != distance || faz != finalAzimuth || outd != distance || frd != reducedLength) throw new Exception("Geodesic.Inverse #4 failed"); fad = g.Inverse(32.0, -86.0, 33.0, -87.0, out outd, out iaz, out faz, out fm12, out fm21 ); if (fad != arcDistance || outd != distance || faz != finalAzimuth || outd != distance || fm12 != M12 || fm21 != M21 ) throw new Exception("Geodesic.Inverse #5 failed"); fad = g.Inverse(32.0, -86.0, 33.0, -87.0, out outd, out iaz, out faz, out frd, out fm12, out fm21); if (fad != arcDistance || outd != distance || faz != finalAzimuth || outd != distance || fm12 != M12 || fm21 != M21 || frd != reducedLength) throw new Exception("Geodesic.Inverse #6 failed"); GeodesicLine gl = g.Line(32.0, -86.0, 45.0, Mask.ALL); gl = new GeodesicLine(32.0, -86.0, 45.0, Mask.ALL); gl = new GeodesicLine(g, 32.0, -86.0, 45.0, Mask.ALL); arcDistance = gl.Position(10000.0, out finalLatitude, out finalLongitude, out finalAzimuth, out reducedLength, out M12, out M21, out S12); fad = gl.Position(10000.0, out flat, out flon); if (fad != arcDistance || flat != finalLatitude || flon != finalLongitude) throw new Exception("GeodesicLine.Position #1 failed"); fad = gl.Position(10000.0, out flat, out flon, out faz); if (fad != arcDistance || flat != finalLatitude || flon != finalLongitude || faz != finalAzimuth) throw new Exception("GeodesicLine.Position #2 failed"); fad = gl.Position(10000.0, out flat, out flon, out faz, out frd); if (fad != arcDistance || flat != finalLatitude || flon != finalLongitude || faz != finalAzimuth || frd != reducedLength) throw new Exception("GeodesicLine.Position #3 failed"); fad = gl.Position(10000.0, out flat, out flon, out faz, out fm12, out fm21); if (fad != arcDistance || flat != finalLatitude || flon != finalLongitude || faz != finalAzimuth || fm12 != M12 || fm21 != M21) throw new Exception("GeodesicLine.Position #4 failed"); fad = gl.Position(10000.0, out flat, out flon, out faz, out frd, out fm12, out fm21); if (fad != arcDistance || flat != finalLatitude || flon != finalLongitude || faz != finalAzimuth || fm12 != M12 || fm21 != M21 || frd != reducedLength ) throw new Exception("GeodesicLine.Position #5 failed"); fad = gl.GenPosition(false, 10000.0, Mask.ALL, out flat, out flon, out faz, out outd, out frd, out fm12, out fm21, out fs12); if (fad != arcDistance || flat != finalLatitude || flon != finalLongitude || faz != finalAzimuth || outd != 10000.0 || fm12 != M12 || fm21 != M21 || frd != reducedLength || fs12 != S12 ) throw new Exception("GeodesicLine.GenPosition (false) failed"); gl.ArcPosition(1.0, out finalLatitude, out finalLongitude, out finalAzimuth, out distance, out reducedLength, out M12, out M21, out S12); gl.ArcPosition(1.0, out flat, out flon); if (flat != finalLatitude || flon != finalLongitude) throw new Exception("GeodesicLine.ArcPosition #1 failed"); gl.ArcPosition(1.0, out flat, out flon, out faz); if (flat != finalLatitude || flon != finalLongitude || faz != finalAzimuth) throw new Exception("GeodesicLine.ArcPosition #2 failed"); gl.ArcPosition(1.0, out flat, out flon, out faz, out outd); if (flat != finalLatitude || flon != finalLongitude || faz != finalAzimuth || outd != distance) throw new Exception("GeodesicLine.ArcPosition #3 failed"); gl.ArcPosition(1.0, out flat, out flon, out faz, out outd, out frd); if (flat != finalLatitude || flon != finalLongitude || faz != finalAzimuth || outd != distance || frd != reducedLength) throw new Exception("GeodesicLine.ArcPosition #4 failed"); gl.ArcPosition(1.0, out flat, out flon, out faz, out outd, out fm12, out fm21); if (flat != finalLatitude || flon != finalLongitude || faz != finalAzimuth || outd != distance || fm12 != M12 || fm21 != M21) throw new Exception("GeodesicLine.ArcPosition #5 failed"); gl.ArcPosition(1.0, out flat, out flon, out faz, out outd, out frd, out fm12, out fm21); if (flat != finalLatitude || flon != finalLongitude || faz != finalAzimuth || outd != distance || fm12 != M12 || fm21 != M21 || frd != reducedLength) throw new Exception("GeodesicLine.ArcPosition #6 failed"); fad = gl.GenPosition(true, 1.0, Mask.ALL, out flat, out flon, out faz, out outd, out frd, out fm12, out fm21, out fs12); if (fad != 1.0 || flat != finalLatitude || flon != finalLongitude || faz != finalAzimuth || outd != distance || fm12 != M12 || fm21 != M21 || frd != reducedLength || fs12 != S12) throw new Exception("GeodesicLine.GenPosition (false) failed"); GeodesicExact ge = new GeodesicExact(); ge = new GeodesicExact(g.MajorRadius, g.Flattening); arcDistance = ge.Direct(32.0, -86.0, 45.0, 20000.0, out finalLatitude, out finalLongitude, out finalAzimuth, out reducedLength, out M12, out M21, out S12); fad = ge.Direct(32.0, -86.0, 45.0, 20000.0, out flat, out flon); if (fad != arcDistance || flat != finalLatitude || flon != finalLongitude) throw new Exception("GeodesicExact.Direct #1 failed"); fad = ge.Direct(32.0, -86.0, 45.0, 20000.0, out flat, out flon, out faz); if (fad != arcDistance || flat != finalLatitude || flon != finalLongitude || faz != finalAzimuth) throw new Exception("GeodesicExact.Direct #2 failed"); fad = ge.Direct(32.0, -86.0, 45.0, 20000.0, out flat, out flon, out faz, out frd); if (fad != arcDistance || flat != finalLatitude || flon != finalLongitude || faz != finalAzimuth || frd != reducedLength) throw new Exception("GeodesicExact.Direct #3 failed"); fad = ge.Direct(32.0, -86.0, 45.0, 20000.0, out flat, out flon, out faz, out fm12, out fm21); if (fad != arcDistance || flat != finalLatitude || flon != finalLongitude || faz != finalAzimuth || fm12 != M12 || fm21 != M21) throw new Exception("GeodesicExact.Direct #4 failed"); fad = ge.Direct(32.0, -86.0, 45.0, 20000.0, out flat, out flon, out faz, out frd, out fm12, out fm21); if (fad != arcDistance || flat != finalLatitude || flon != finalLongitude || faz != finalAzimuth || frd != reducedLength || fm12 != M12 || fm21 != M21) throw new Exception("GeodesicExact.Direct #5 failed"); fad = ge.GenDirect(32.0, -86.0, 45.0, false, 20000.0, Mask.ALL, out flat, out flon, out faz, out outd, out frd, out fm12, out fm21, out fs12); if (fad != arcDistance || flat != finalLatitude || flon != finalLongitude || faz != finalAzimuth || frd != reducedLength || fm12 != M12 || fm21 != M21 || outd != 20000.0 || fs12 != S12) throw new Exception("GeodesicExact.GenDirect (false) failed"); ge.ArcDirect(32.0, -86.0, 45.0, 1.0, out finalLatitude, out finalLongitude, out finalAzimuth, out arcDistance, out reducedLength, out M12, out M21, out S12); ge.ArcDirect(32.0, -86.0, 45.0, 1.0, out flat, out flon); if (flat != finalLatitude || flon != finalLongitude) throw new Exception("GeodesicExact.ArcDirect #1 failed"); ge.ArcDirect(32.0, -86.0, 45.0, 1.0, out flat, out flon, out faz); if (flat != finalLatitude || flon != finalLongitude || faz != finalAzimuth) throw new Exception("GeodesicExact.ArcDirect #2 failed"); ge.ArcDirect(32.0, -86.0, 45.0, 1.0, out flat, out flon, out faz, out fad); if (flat != finalLatitude || flon != finalLongitude || faz != finalAzimuth || fad != arcDistance) throw new Exception("GeodesicExact.ArcDirect #3 failed"); ge.ArcDirect(32.0, -86.0, 45.0, 1.0, out flat, out flon, out faz, out fad, out frd); if (flat != finalLatitude || flon != finalLongitude || faz != finalAzimuth || fad != arcDistance || frd != reducedLength) throw new Exception("GeodesicExact.ArcDirect #4 failed"); ge.ArcDirect(32.0, -86.0, 45.0, 1.0, out flat, out flon, out faz, out fad, out fm12, out fm21); if (flat != finalLatitude || flon != finalLongitude || faz != finalAzimuth || fad != arcDistance || fm12 != M12 || fm21 != M21) throw new Exception("GeodesicExact.ArcDirect #5 failed"); fad = ge.GenDirect(32.0, -86.0, 45.0, true, 1.0, Mask.ALL, out flat, out flon, out faz, out outd, out frd, out fm12, out fm21, out fs12); if (outd != arcDistance || flat != finalLatitude || flon != finalLongitude || faz != finalAzimuth || frd != reducedLength || fm12 != M12 || fm21 != M21 || fad != 1.0 || fs12 != S12) throw new Exception("GeodesicExact.GenDirect (true) failed"); arcDistance = ge.Inverse(32.0, -86.0, 33.0, -87.0, out distance, out initAzimuth, out finalAzimuth, out reducedLength, out M12, out M21, out S12); fad = ge.Inverse(32.0, -86.0, 33.0, -87.0, out outd); if (fad != arcDistance || outd != distance) throw new Exception("GeodesicExact.Inverse #1 failed"); fad = ge.Inverse(32.0, -86.0, 33.0, -87.0, out iaz, out faz); if (fad != arcDistance || iaz != initAzimuth || faz != finalAzimuth) throw new Exception("GeodesicExact.Inverse #2 failed"); fad = ge.Inverse(32.0, -86.0, 33.0, -87.0, out outd, out iaz, out faz); if (fad != arcDistance || outd != distance || faz != finalAzimuth || outd != distance) throw new Exception("GeodesicExact.Inverse #3 failed"); fad = ge.Inverse(32.0, -86.0, 33.0, -87.0, out outd, out iaz, out faz, out frd); if (fad != arcDistance || outd != distance || faz != finalAzimuth || outd != distance || frd != reducedLength) throw new Exception("GeodesicExact.Inverse #4 failed"); fad = ge.Inverse(32.0, -86.0, 33.0, -87.0, out outd, out iaz, out faz, out fm12, out fm21); if (fad != arcDistance || outd != distance || faz != finalAzimuth || outd != distance || fm12 != M12 || fm21 != M21) throw new Exception("GeodesicExact.Inverse #5 failed"); fad = ge.Inverse(32.0, -86.0, 33.0, -87.0, out outd, out iaz, out faz, out frd, out fm12, out fm21); if (fad != arcDistance || outd != distance || faz != finalAzimuth || outd != distance || fm12 != M12 || fm21 != M21 || frd != reducedLength) throw new Exception("GeodesicExact.Inverse #6 failed"); GeodesicLineExact gle = ge.Line(32.0, -86.0, 45.0, Mask.ALL); gle = new GeodesicLineExact(32.0, -86.0, 45.0, Mask.ALL); gle = new GeodesicLineExact(ge, 32.0, -86.0, 45.0, Mask.ALL); arcDistance = gle.Position(10000.0, out finalLatitude, out finalLongitude, out finalAzimuth, out reducedLength, out M12, out M21, out S12); fad = gle.Position(10000.0, out flat, out flon); if (fad != arcDistance || flat != finalLatitude || flon != finalLongitude) throw new Exception("GeodesicLineExact.Position #1 failed"); fad = gle.Position(10000.0, out flat, out flon, out faz); if (fad != arcDistance || flat != finalLatitude || flon != finalLongitude || faz != finalAzimuth) throw new Exception("GeodesicLineExact.Position #2 failed"); fad = gle.Position(10000.0, out flat, out flon, out faz, out frd); if (fad != arcDistance || flat != finalLatitude || flon != finalLongitude || faz != finalAzimuth || frd != reducedLength) throw new Exception("GeodesicLineExact.Position #3 failed"); fad = gle.Position(10000.0, out flat, out flon, out faz, out fm12, out fm21); if (fad != arcDistance || flat != finalLatitude || flon != finalLongitude || faz != finalAzimuth || fm12 != M12 || fm21 != M21) throw new Exception("GeodesicLineExact.Position #4 failed"); fad = gle.Position(10000.0, out flat, out flon, out faz, out frd, out fm12, out fm21); if (fad != arcDistance || flat != finalLatitude || flon != finalLongitude || faz != finalAzimuth || fm12 != M12 || fm21 != M21 || frd != reducedLength) throw new Exception("GeodesicLineExact.Position #5 failed"); fad = gle.GenPosition(false, 10000.0, Mask.ALL, out flat, out flon, out faz, out outd, out frd, out fm12, out fm21, out fs12); if (fad != arcDistance || flat != finalLatitude || flon != finalLongitude || faz != finalAzimuth || outd != 10000.0 || fm12 != M12 || fm21 != M21 || frd != reducedLength || fs12 != S12) throw new Exception("GeodesicLineExact.GenPosition (false) failed"); gle.ArcPosition(1.0, out finalLatitude, out finalLongitude, out finalAzimuth, out distance, out reducedLength, out M12, out M21, out S12); gle.ArcPosition(1.0, out flat, out flon); if (flat != finalLatitude || flon != finalLongitude) throw new Exception("GeodesicLineExact.ArcPosition #1 failed"); gle.ArcPosition(1.0, out flat, out flon, out faz); if (flat != finalLatitude || flon != finalLongitude || faz != finalAzimuth) throw new Exception("GeodesicLineExact.ArcPosition #2 failed"); gle.ArcPosition(1.0, out flat, out flon, out faz, out outd); if (flat != finalLatitude || flon != finalLongitude || faz != finalAzimuth || outd != distance) throw new Exception("GeodesicLineExact.ArcPosition #3 failed"); gle.ArcPosition(1.0, out flat, out flon, out faz, out outd, out frd); if (flat != finalLatitude || flon != finalLongitude || faz != finalAzimuth || outd != distance || frd != reducedLength) throw new Exception("GeodesicLineExact.ArcPosition #4 failed"); gle.ArcPosition(1.0, out flat, out flon, out faz, out outd, out fm12, out fm21); if (flat != finalLatitude || flon != finalLongitude || faz != finalAzimuth || outd != distance || fm12 != M12 || fm21 != M21) throw new Exception("GeodesicLineExact.ArcPosition #5 failed"); gle.ArcPosition(1.0, out flat, out flon, out faz, out outd, out frd, out fm12, out fm21); if (flat != finalLatitude || flon != finalLongitude || faz != finalAzimuth || outd != distance || fm12 != M12 || fm21 != M21 || frd != reducedLength) throw new Exception("GeodesicLineExact.ArcPosition #6 failed"); fad = gle.GenPosition(true, 1.0, Mask.ALL, out flat, out flon, out faz, out outd, out frd, out fm12, out fm21, out fs12); if (fad != 1.0 || flat != finalLatitude || flon != finalLongitude || faz != finalAzimuth || outd != distance || fm12 != M12 || fm21 != M21 || frd != reducedLength || fs12 != S12) throw new Exception("GeodesicLineExact.GenPosition (false) failed"); } catch (Exception xcpt) { MessageBox.Show(xcpt.Message, "Interface Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } MessageBox.Show("No errors detected", "Interfaces OK", MessageBoxButtons.OK, MessageBoxIcon.Information); } } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="EventManager.cs" company="Slash Games"> // Copyright (c) Slash Games. All rights reserved. // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Slash.ECS.Events { using System; using System.Collections.Generic; /// <summary> /// Allows listeners to register for game-related events and notifies them /// whenever one of these events is fired. /// </summary> public class EventManager { #region Fields /// <summary> /// Queue of events that are currently being processed. /// </summary> private readonly List<GameEvent> currentEvents; /// <summary> /// Events to be fired later. /// </summary> private readonly List<DelayedEvent> delayedEvents = new List<DelayedEvent>(); /// <summary> /// Delayed events to be fired now. /// </summary> private readonly List<DelayedEvent> elapsedEvents = new List<DelayedEvent>(); /// <summary> /// Listeners that are interested in events of specific types. /// </summary> private readonly Dictionary<object, EventDelegate> listeners; /// <summary> /// Queue of events to be processed. /// </summary> private readonly List<GameEvent> newEvents; /// <summary> /// Accumulated passed time to use for delayed events (in s). /// </summary> private float accumulatedPassedTime; /// <summary> /// Listeners which are interested in all events. /// </summary> private EventDelegate allEventListeners; /// <summary> /// Indicates if the event manager is currently processing events. /// </summary> private bool isProcessing; #endregion #region Constructors and Destructors /// <summary> /// Constructs a new event manager with an empty event queue and /// without any listeners. /// </summary> public EventManager() { this.newEvents = new List<GameEvent>(); this.currentEvents = new List<GameEvent>(); this.listeners = new Dictionary<object, EventDelegate>(); } #endregion #region Delegates /// <summary> /// Signature of the event callbacks. /// </summary> /// <param name="e"> Event which occurred. </param> public delegate void EventDelegate(GameEvent e); /// <summary> /// Delegate for the UnhandledEvent event. /// </summary> /// <param name="eventType">Type of unhandled event.</param> public delegate void UnhandledEventDelegate(object eventType); #endregion #region Events /// <summary> /// Callback for events no listener is registered for. Useful for improving performance. /// </summary> public event UnhandledEventDelegate UnhandledEvent; #endregion #region Properties /// <summary> /// Current number of events in the event queue. /// </summary> public int EventCount { get { return this.newEvents.Count; } } #endregion #region Public Methods and Operators /// <summary> /// Fires the passed event after a short delay. /// </summary> /// <param name="delay">Time to wait before firing the event, in seconds.</param> /// <param name="eventType"> Type of the event to fire. </param> /// <param name="eventData"> Data any listeners might be interested in. </param> public void FireDelayed(float delay, object eventType, object eventData = null) { this.FireDelayed(delay, new GameEvent(eventType, eventData)); } /// <summary> /// Fires the passed event after a short delay. /// </summary> /// <param name="delay">Time to wait before firing the event, in seconds.</param> /// <param name="e">Event to fire.</param> public void FireDelayed(float delay, GameEvent e) { if (delay > 0) { this.delayedEvents.Add(new DelayedEvent { TimeRemaining = delay, Event = e }); } else { this.FireImmediately(e); } } /// <summary> /// Fires the passed event immediately, notifying all listeners. /// </summary> /// <param name="eventType"> Type of the event to fire. </param> /// <param name="eventData"> Data any listeners might be interested in. </param> public void FireImmediately(object eventType, object eventData = null) { this.FireImmediately(new GameEvent(eventType, eventData)); } /// <summary> /// Fires the passed event immediately, notifying all listeners. /// </summary> /// <param name="e"> Event to fire. </param> public void FireImmediately(GameEvent e) { this.ProcessEvent(e); } /// <summary> /// Passes all queued events on to interested listeners and clears the /// event queue. /// </summary> /// <returns>Number of processed events.</returns> public int ProcessEvents() { return this.ProcessEvents(0.0f); } /// <summary> /// Passes all queued events on to interested listeners and clears the /// event queue. /// </summary> /// <param name="dt">Time passed since the last tick, in seconds.</param> /// <returns>Number of processed events.</returns> public int ProcessEvents(float dt) { // Add passed time. this.accumulatedPassedTime += dt; // If events are currently processed, we have to return as the events are // otherwise processed in the wrong order. if (this.isProcessing) { return 0; } this.isProcessing = true; int processedEvents = 0; // Process queues events. while (this.newEvents.Count > 0) { this.currentEvents.AddRange(this.newEvents); this.newEvents.Clear(); foreach (GameEvent e in this.currentEvents) { this.ProcessEvent(e); ++processedEvents; } this.currentEvents.Clear(); } // Process delayed events. while (this.accumulatedPassedTime > 0) { float passedTime = this.accumulatedPassedTime; // Collect elapsed events. this.elapsedEvents.Clear(); foreach (DelayedEvent e in this.delayedEvents) { e.TimeRemaining -= passedTime; if (e.TimeRemaining <= 0) { this.elapsedEvents.Add(e); } } // Process elapsed events. foreach (DelayedEvent e in this.elapsedEvents) { this.ProcessEvent(e.Event); this.delayedEvents.Remove(e); ++processedEvents; } this.accumulatedPassedTime -= passedTime; } this.isProcessing = false; return processedEvents; } /// <summary> /// Queues a new event of the specified type along without any event data. /// </summary> /// <param name="eventType"> Type of the event to queue. </param> public void QueueEvent(object eventType) { this.QueueEvent(eventType, null); } /// <summary> /// Queues a new event of the specified type along with the passed /// event data. /// </summary> /// <param name="eventType"> Type of the event to queue. </param> /// <param name="eventData"> Data any listeners might be interested in. </param> public void QueueEvent(object eventType, object eventData) { this.QueueEvent(new GameEvent(eventType, eventData)); } /// <summary> /// Queues the passed event to be processed later. /// </summary> /// <param name="e"> Event to queue. </param> public void QueueEvent(GameEvent e) { if (e == null) { throw new ArgumentNullException("e", "Event is null."); } this.newEvents.Add(e); } /// <summary> /// Registers the specified delegate for events of the specified type. /// </summary> /// <param name="eventType"> Type of the event the caller is interested in. </param> /// <param name="callback"> Delegate to invoke when specified type occurred. </param> /// <exception cref="ArgumentNullException">Specified delegate is null.</exception> /// <exception cref="ArgumentNullException">Specified event type is null.</exception> public void RegisterListener(object eventType, EventDelegate callback) { if (eventType == null) { throw new ArgumentNullException("eventType"); } if (callback == null) { throw new ArgumentNullException("callback"); } if (this.listeners.ContainsKey(eventType)) { this.listeners[eventType] += callback; } else { this.listeners[eventType] = callback; } } /// <summary> /// Registers the specified delegate for all events. Note that the /// delegate will be called twice if it is registered for a specific /// event type as well. Listeners for all events are always notified /// before listeners for specific events. /// </summary> /// <param name="callback"> Delegate to invoke when specified type occurred. </param> /// <exception cref="ArgumentNullException">Specified delegate is null.</exception> /// <exception cref="ArgumentNullException">Specified event type is null.</exception> public void RegisterListener(EventDelegate callback) { if (callback == null) { throw new ArgumentNullException("callback"); } this.allEventListeners += callback; } /// <summary> /// Unregisters the specified delegate for events of the specified type. /// </summary> /// <param name="eventType"> Type of the event the caller is no longer interested in. </param> /// <param name="callback"> Delegate to remove. </param> /// <exception cref="ArgumentNullException">Specified delegate is null.</exception> /// <exception cref="ArgumentNullException">Specified event type is null.</exception> public void RemoveListener(object eventType, EventDelegate callback) { if (eventType == null) { throw new ArgumentNullException("eventType"); } if (callback == null) { throw new ArgumentNullException("callback"); } if (this.listeners.ContainsKey(eventType)) { this.listeners[eventType] -= callback; } } /// <summary> /// Unregisters the specified delegate for all events. Note that this /// will remove the delegate from the list of listeners interested in /// all events, only: Calling this function will not remove the delegate /// from specific events. /// </summary> /// <param name="callback"> Delegate to remove. </param> /// <exception cref="ArgumentNullException">Specified delegate is null.</exception> /// <exception cref="ArgumentNullException">Specified event type is null.</exception> public void RemoveListener(EventDelegate callback) { if (callback == null) { throw new ArgumentNullException("callback"); } this.allEventListeners -= callback; } #endregion #region Methods private void OnUnhandledEvent(object eventType) { var handler = this.UnhandledEvent; if (handler != null) { handler(eventType); } } /// <summary> /// Notifies all interested listeners of the specified event. /// </summary> /// <param name="e">Event to pass to listeners.</param> private void ProcessEvent(GameEvent e) { // Check for listeners to all events. EventDelegate eventListeners = this.allEventListeners; if (eventListeners != null) { eventListeners(e); } if (this.listeners.TryGetValue(e.EventType, out eventListeners)) { if (eventListeners != null) { eventListeners(e); } else { this.OnUnhandledEvent(e.EventType); } } else { this.OnUnhandledEvent(e.EventType); } } #endregion /// <summary> /// Event to be fired later. /// </summary> private class DelayedEvent { #region Properties /// <summary> /// Event to be fired later. /// </summary> public GameEvent Event { get; set; } /// <summary> /// Time remaining before this event is to be fired, in seconds. /// </summary> public float TimeRemaining { get; set; } #endregion } } }
using UnityEngine; using System.Collections; using System.IO; // originally found in: http://forum.unity3d.com/threads/35617-TextManager-Localization-Script /// <summary> /// TextManager /// /// Reads PO files in the Assets\Resources\Languages directory into a Hashtable. /// Look for "PO editors" as that's a standard for translating software. /// /// Example: /// /// load the language file: /// TextManager.LoadLanguage("helptext-pt-br"); /// /// which has to contain at least two lines as such: /// msgid "HELLO WORLD" /// msgstr "OLA MUNDO" /// /// then we can retrieve the text by calling: /// TextManager.GetText("HELLO WORLD"); /// </summary> public class TextLocalizationManager : MonoBehaviour { private static TextLocalizationManager instance;// = new TextLocalizationManager(); private Hashtable textTable; //we can set both as properties in unity editor public string comment = "#"; public string separator = "="; //we can set both as properties in unity editor public string languageFilePrefix = "Language_"; //public string languageFileSuffix = ""; private const string DEFAULT_LANGUAGE_PREFIX = "en"; //set the support languages array public string [] supportedLanguages; //private constructor private TextLocalizationManager() { } void Awake() { // Register the singleton if (Instance != null) { Debug.LogError("Multiple instances of TextLocalizationManager!"); } else { instance = this; } } public static TextLocalizationManager Instance { get { if (instance == null) { instance = (TextLocalizationManager)FindObjectOfType(typeof(TextLocalizationManager)); //none loaded? if(instance==null) { //check in scripts hierarquy GameObject scripts = GameObject.FindGameObjectWithTag("Scripts"); if(scripts!=null) { instance = scripts.GetComponent<TextLocalizationManager>(); } else { // Because the TextManager is a component, we have to create a GameObject to attach it to. // Add the DynamicObjectManager component, and set it as the defaultCenter instance = (new GameObject("TextLocalizationManager")).AddComponent<TextLocalizationManager>(); } } } return instance; } } public bool LoadSystemLanguage(SystemLanguage language) { if(language==null) { return LoadLanguage(DEFAULT_LANGUAGE_PREFIX); } else if(language == SystemLanguage.Spanish) { return LoadLanguage("es"); } else if(language == SystemLanguage.Portuguese) { return LoadLanguage("pt"); } else if(language == SystemLanguage.French) { return LoadLanguage("fr"); } else if(language == SystemLanguage.Russian) { return LoadLanguage("ru"); } else if(language == SystemLanguage.Chinese) { return LoadLanguage("zh"); } else if(language == SystemLanguage.Japanese) { return LoadLanguage("jp"); } else { //english by default return LoadLanguage(DEFAULT_LANGUAGE_PREFIX); } } public bool LoadLanguage (string langPrefix) { if (langPrefix == null || supportedLanguages==null || supportedLanguages.Length == 0) { Debug.Log ("Loading default language."); textTable = null; // reset to default return false; // this means: call LoadLanguage with null to reset to default } else { bool exists = false; string lang = null; for(int i=0; i < supportedLanguages.Length; i++) { lang = supportedLanguages[i]; if(lang.ToLower().Equals(langPrefix.ToLower()) ) { exists = true; break; } } //this is a supported languages if(exists) { string filename = languageFilePrefix + lang; return ParseLanguageFile(filename); } Debug.Log ("Unable to find a language match. Loading default language."); textTable = null; // reset to default return false; } } /** * Parses the "properties" file * */ private bool ParseLanguageFile (string filename) { TextAsset textAsset = (TextAsset)Resources.Load (filename) as TextAsset; if (textAsset == null) { Debug.Log ("[TextManager] " + filename + " file not found."); return false; } if (textTable == null) { textTable = new Hashtable (); } textTable.Clear (); StringReader reader = new StringReader (textAsset.text); string line; string key = null; string val = null; int indexSeparator = 0; while ((line = reader.ReadLine()) != null) { if (line.StartsWith (comment)) { //ignore since is a comment continue; } else { //parse it if (line.Contains (separator)) { indexSeparator = line.IndexOf (separator); key = line.Substring (0, indexSeparator ); val = line.Substring (indexSeparator + 1); } if (key != null && val != null) { // TODO: add error handling here in case of duplicate keys if (!textTable.ContainsKey (key)) { textTable.Add (key, val); } else { Debug.Log ("Duplicated entry: " + key + " , ignoring it..."); } } key = val = null; } } reader.Close (); return true; } public string GetText (string key) { if (key != null && textTable != null) { if (textTable.ContainsKey(key)) { string result = (string)textTable[key]; if (result.Length > 0) { return result; } } } return key; } }
using System; using System.CodeDom.Compiler; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Globalization; using System.Linq; using System.Text; namespace EduHub.Data.Entities { /// <summary> /// Home Group History Data Set /// </summary> [GeneratedCode("EduHub Data", "0.9")] public sealed partial class KGCHIDataSet : EduHubDataSet<KGCHI> { /// <inheritdoc /> public override string Name { get { return "KGCHI"; } } /// <inheritdoc /> public override bool SupportsEntityLastModified { get { return false; } } internal KGCHIDataSet(EduHubContext Context) : base(Context) { Index_KGCHIKEY = new Lazy<Dictionary<int, KGCHI>>(() => this.ToDictionary(i => i.KGCHIKEY)); Index_KGCKEY = new Lazy<NullDictionary<string, IReadOnlyList<KGCHI>>>(() => this.ToGroupedNullDictionary(i => i.KGCKEY)); } /// <summary> /// Matches CSV file headers to actions, used to deserialize <see cref="KGCHI" /> /// </summary> /// <param name="Headers">The CSV column headers</param> /// <returns>An array of actions which deserialize <see cref="KGCHI" /> fields for each CSV column header</returns> internal override Action<KGCHI, string>[] BuildMapper(IReadOnlyList<string> Headers) { var mapper = new Action<KGCHI, string>[Headers.Count]; for (var i = 0; i < Headers.Count; i++) { switch (Headers[i]) { case "KGCHIKEY": mapper[i] = (e, v) => e.KGCHIKEY = int.Parse(v); break; case "KGCKEY": mapper[i] = (e, v) => e.KGCKEY = v; break; case "CREATION_USER": mapper[i] = (e, v) => e.CREATION_USER = v; break; case "CREATION_DATE": mapper[i] = (e, v) => e.CREATION_DATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture); break; case "CREATION_TIME": mapper[i] = (e, v) => e.CREATION_TIME = v == null ? (short?)null : short.Parse(v); break; case "OBSOLETE_USER": mapper[i] = (e, v) => e.OBSOLETE_USER = v; break; case "OBSOLETE_DATE": mapper[i] = (e, v) => e.OBSOLETE_DATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture); break; case "OBSOLETE_TIME": mapper[i] = (e, v) => e.OBSOLETE_TIME = v == null ? (short?)null : short.Parse(v); break; case "CAMPUS": mapper[i] = (e, v) => e.CAMPUS = v; break; case "TEACHER": mapper[i] = (e, v) => e.TEACHER = v; break; case "TEACHER_B": mapper[i] = (e, v) => e.TEACHER_B = v; break; case "ROOM": mapper[i] = (e, v) => e.ROOM = v; break; case "CHANGE_MADE": mapper[i] = (e, v) => e.CHANGE_MADE = v; break; default: mapper[i] = MapperNoOp; break; } } return mapper; } /// <summary> /// Merges <see cref="KGCHI" /> delta entities /// </summary> /// <param name="Entities">Iterator for base <see cref="KGCHI" /> entities</param> /// <param name="DeltaEntities">List of delta <see cref="KGCHI" /> entities</param> /// <returns>A merged <see cref="IEnumerable{KGCHI}"/> of entities</returns> internal override IEnumerable<KGCHI> ApplyDeltaEntities(IEnumerable<KGCHI> Entities, List<KGCHI> DeltaEntities) { HashSet<int> Index_KGCHIKEY = new HashSet<int>(DeltaEntities.Select(i => i.KGCHIKEY)); using (var deltaIterator = DeltaEntities.GetEnumerator()) { using (var entityIterator = Entities.GetEnumerator()) { while (deltaIterator.MoveNext()) { var deltaClusteredKey = deltaIterator.Current.KGCHIKEY; bool yieldEntity = false; while (entityIterator.MoveNext()) { var entity = entityIterator.Current; bool overwritten = Index_KGCHIKEY.Remove(entity.KGCHIKEY); if (entity.KGCHIKEY.CompareTo(deltaClusteredKey) <= 0) { if (!overwritten) { yield return entity; } } else { yieldEntity = !overwritten; break; } } yield return deltaIterator.Current; if (yieldEntity) { yield return entityIterator.Current; } } while (entityIterator.MoveNext()) { yield return entityIterator.Current; } } } } #region Index Fields private Lazy<Dictionary<int, KGCHI>> Index_KGCHIKEY; private Lazy<NullDictionary<string, IReadOnlyList<KGCHI>>> Index_KGCKEY; #endregion #region Index Methods /// <summary> /// Find KGCHI by KGCHIKEY field /// </summary> /// <param name="KGCHIKEY">KGCHIKEY value used to find KGCHI</param> /// <returns>Related KGCHI entity</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public KGCHI FindByKGCHIKEY(int KGCHIKEY) { return Index_KGCHIKEY.Value[KGCHIKEY]; } /// <summary> /// Attempt to find KGCHI by KGCHIKEY field /// </summary> /// <param name="KGCHIKEY">KGCHIKEY value used to find KGCHI</param> /// <param name="Value">Related KGCHI entity</param> /// <returns>True if the related KGCHI entity is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByKGCHIKEY(int KGCHIKEY, out KGCHI Value) { return Index_KGCHIKEY.Value.TryGetValue(KGCHIKEY, out Value); } /// <summary> /// Attempt to find KGCHI by KGCHIKEY field /// </summary> /// <param name="KGCHIKEY">KGCHIKEY value used to find KGCHI</param> /// <returns>Related KGCHI entity, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public KGCHI TryFindByKGCHIKEY(int KGCHIKEY) { KGCHI value; if (Index_KGCHIKEY.Value.TryGetValue(KGCHIKEY, out value)) { return value; } else { return null; } } /// <summary> /// Find KGCHI by KGCKEY field /// </summary> /// <param name="KGCKEY">KGCKEY value used to find KGCHI</param> /// <returns>List of related KGCHI entities</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<KGCHI> FindByKGCKEY(string KGCKEY) { return Index_KGCKEY.Value[KGCKEY]; } /// <summary> /// Attempt to find KGCHI by KGCKEY field /// </summary> /// <param name="KGCKEY">KGCKEY value used to find KGCHI</param> /// <param name="Value">List of related KGCHI entities</param> /// <returns>True if the list of related KGCHI entities is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByKGCKEY(string KGCKEY, out IReadOnlyList<KGCHI> Value) { return Index_KGCKEY.Value.TryGetValue(KGCKEY, out Value); } /// <summary> /// Attempt to find KGCHI by KGCKEY field /// </summary> /// <param name="KGCKEY">KGCKEY value used to find KGCHI</param> /// <returns>List of related KGCHI entities, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<KGCHI> TryFindByKGCKEY(string KGCKEY) { IReadOnlyList<KGCHI> value; if (Index_KGCKEY.Value.TryGetValue(KGCKEY, out value)) { return value; } else { return null; } } #endregion #region SQL Integration /// <summary> /// Returns a <see cref="SqlCommand"/> which checks for the existence of a KGCHI table, and if not found, creates the table and associated indexes. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> public override SqlCommand GetSqlCreateTableCommand(SqlConnection SqlConnection) { return new SqlCommand( connection: SqlConnection, cmdText: @"IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[KGCHI]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1) BEGIN CREATE TABLE [dbo].[KGCHI]( [KGCHIKEY] int IDENTITY NOT NULL, [KGCKEY] varchar(3) NULL, [CREATION_USER] varchar(128) NULL, [CREATION_DATE] datetime NULL, [CREATION_TIME] smallint NULL, [OBSOLETE_USER] varchar(128) NULL, [OBSOLETE_DATE] datetime NULL, [OBSOLETE_TIME] smallint NULL, [CAMPUS] varchar(45) NULL, [TEACHER] varchar(35) NULL, [TEACHER_B] varchar(35) NULL, [ROOM] varchar(30) NULL, [CHANGE_MADE] varchar(40) NULL, CONSTRAINT [KGCHI_Index_KGCHIKEY] PRIMARY KEY CLUSTERED ( [KGCHIKEY] ASC ) ); CREATE NONCLUSTERED INDEX [KGCHI_Index_KGCKEY] ON [dbo].[KGCHI] ( [KGCKEY] ASC ); END"); } /// <summary> /// Returns a <see cref="SqlCommand"/> which disables all non-clustered table indexes. /// Typically called before <see cref="SqlBulkCopy"/> to improve performance. /// <see cref="GetSqlRebuildIndexesCommand(SqlConnection)"/> should be called to rebuild and enable indexes after performance sensitive work is completed. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <returns>A <see cref="SqlCommand"/> which (when executed) will disable all non-clustered table indexes</returns> public override SqlCommand GetSqlDisableIndexesCommand(SqlConnection SqlConnection) { return new SqlCommand( connection: SqlConnection, cmdText: @"IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[KGCHI]') AND name = N'KGCHI_Index_KGCKEY') ALTER INDEX [KGCHI_Index_KGCKEY] ON [dbo].[KGCHI] DISABLE; "); } /// <summary> /// Returns a <see cref="SqlCommand"/> which rebuilds and enables all non-clustered table indexes. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <returns>A <see cref="SqlCommand"/> which (when executed) will rebuild and enable all non-clustered table indexes</returns> public override SqlCommand GetSqlRebuildIndexesCommand(SqlConnection SqlConnection) { return new SqlCommand( connection: SqlConnection, cmdText: @"IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[KGCHI]') AND name = N'KGCHI_Index_KGCKEY') ALTER INDEX [KGCHI_Index_KGCKEY] ON [dbo].[KGCHI] REBUILD PARTITION = ALL; "); } /// <summary> /// Returns a <see cref="SqlCommand"/> which deletes the <see cref="KGCHI"/> entities passed /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <param name="Entities">The <see cref="KGCHI"/> entities to be deleted</param> public override SqlCommand GetSqlDeleteCommand(SqlConnection SqlConnection, IEnumerable<KGCHI> Entities) { SqlCommand command = new SqlCommand(); int parameterIndex = 0; StringBuilder builder = new StringBuilder(); List<int> Index_KGCHIKEY = new List<int>(); foreach (var entity in Entities) { Index_KGCHIKEY.Add(entity.KGCHIKEY); } builder.AppendLine("DELETE [dbo].[KGCHI] WHERE"); // Index_KGCHIKEY builder.Append("[KGCHIKEY] IN ("); for (int index = 0; index < Index_KGCHIKEY.Count; index++) { if (index != 0) builder.Append(", "); // KGCHIKEY var parameterKGCHIKEY = $"@p{parameterIndex++}"; builder.Append(parameterKGCHIKEY); command.Parameters.Add(parameterKGCHIKEY, SqlDbType.Int).Value = Index_KGCHIKEY[index]; } builder.Append(");"); command.Connection = SqlConnection; command.CommandText = builder.ToString(); return command; } /// <summary> /// Provides a <see cref="IDataReader"/> for the KGCHI data set /// </summary> /// <returns>A <see cref="IDataReader"/> for the KGCHI data set</returns> public override EduHubDataSetDataReader<KGCHI> GetDataSetDataReader() { return new KGCHIDataReader(Load()); } /// <summary> /// Provides a <see cref="IDataReader"/> for the KGCHI data set /// </summary> /// <returns>A <see cref="IDataReader"/> for the KGCHI data set</returns> public override EduHubDataSetDataReader<KGCHI> GetDataSetDataReader(List<KGCHI> Entities) { return new KGCHIDataReader(new EduHubDataSetLoadedReader<KGCHI>(this, Entities)); } // Modest implementation to primarily support SqlBulkCopy private class KGCHIDataReader : EduHubDataSetDataReader<KGCHI> { public KGCHIDataReader(IEduHubDataSetReader<KGCHI> Reader) : base (Reader) { } public override int FieldCount { get { return 13; } } public override object GetValue(int i) { switch (i) { case 0: // KGCHIKEY return Current.KGCHIKEY; case 1: // KGCKEY return Current.KGCKEY; case 2: // CREATION_USER return Current.CREATION_USER; case 3: // CREATION_DATE return Current.CREATION_DATE; case 4: // CREATION_TIME return Current.CREATION_TIME; case 5: // OBSOLETE_USER return Current.OBSOLETE_USER; case 6: // OBSOLETE_DATE return Current.OBSOLETE_DATE; case 7: // OBSOLETE_TIME return Current.OBSOLETE_TIME; case 8: // CAMPUS return Current.CAMPUS; case 9: // TEACHER return Current.TEACHER; case 10: // TEACHER_B return Current.TEACHER_B; case 11: // ROOM return Current.ROOM; case 12: // CHANGE_MADE return Current.CHANGE_MADE; default: throw new ArgumentOutOfRangeException(nameof(i)); } } public override bool IsDBNull(int i) { switch (i) { case 1: // KGCKEY return Current.KGCKEY == null; case 2: // CREATION_USER return Current.CREATION_USER == null; case 3: // CREATION_DATE return Current.CREATION_DATE == null; case 4: // CREATION_TIME return Current.CREATION_TIME == null; case 5: // OBSOLETE_USER return Current.OBSOLETE_USER == null; case 6: // OBSOLETE_DATE return Current.OBSOLETE_DATE == null; case 7: // OBSOLETE_TIME return Current.OBSOLETE_TIME == null; case 8: // CAMPUS return Current.CAMPUS == null; case 9: // TEACHER return Current.TEACHER == null; case 10: // TEACHER_B return Current.TEACHER_B == null; case 11: // ROOM return Current.ROOM == null; case 12: // CHANGE_MADE return Current.CHANGE_MADE == null; default: return false; } } public override string GetName(int ordinal) { switch (ordinal) { case 0: // KGCHIKEY return "KGCHIKEY"; case 1: // KGCKEY return "KGCKEY"; case 2: // CREATION_USER return "CREATION_USER"; case 3: // CREATION_DATE return "CREATION_DATE"; case 4: // CREATION_TIME return "CREATION_TIME"; case 5: // OBSOLETE_USER return "OBSOLETE_USER"; case 6: // OBSOLETE_DATE return "OBSOLETE_DATE"; case 7: // OBSOLETE_TIME return "OBSOLETE_TIME"; case 8: // CAMPUS return "CAMPUS"; case 9: // TEACHER return "TEACHER"; case 10: // TEACHER_B return "TEACHER_B"; case 11: // ROOM return "ROOM"; case 12: // CHANGE_MADE return "CHANGE_MADE"; default: throw new ArgumentOutOfRangeException(nameof(ordinal)); } } public override int GetOrdinal(string name) { switch (name) { case "KGCHIKEY": return 0; case "KGCKEY": return 1; case "CREATION_USER": return 2; case "CREATION_DATE": return 3; case "CREATION_TIME": return 4; case "OBSOLETE_USER": return 5; case "OBSOLETE_DATE": return 6; case "OBSOLETE_TIME": return 7; case "CAMPUS": return 8; case "TEACHER": return 9; case "TEACHER_B": return 10; case "ROOM": return 11; case "CHANGE_MADE": return 12; default: throw new ArgumentOutOfRangeException(nameof(name)); } } } #endregion } }
//Copyright (C) 2006 Richard J. Northedge // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. //This file is based on the CountedSet.java source file found in the //original java implementation of OpenNLP. That source file contains the following header: //Copyright (C) 2003 Thomas Morton // //This library is free software; you can redistribute it and/or //modify it under the terms of the GNU Lesser General Public //License as published by the Free Software Foundation; either //version 2.1 of the License, or (at your option) any later version. // //This library is distributed in the hope that it will be useful, //but WITHOUT ANY WARRANTY; without even the implied warranty of //MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //GNU Lesser General Public License for more details. // //You should have received a copy of the GNU Lesser General Public //License along with this program; if not, write to the Free Software //Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Text; namespace OpenNLP.Tools.Util { /// <summary> /// Set which counts the number of times a values are added to it. /// This value can be accessed with the GetCount method. /// </summary> public class CountedSet<T> : ICollection<T> { private readonly IDictionary<T, int> mCountedSet; /// <summary> Creates a new counted set.</summary> public CountedSet() { mCountedSet = new Dictionary<T, int>(); } /// <summary> /// Creates a new counted set of the specified initial size. /// </summary> /// <param name="size"> /// The initial size of this set. /// </param> public CountedSet(int size) { mCountedSet = new Dictionary<T, int>(size); } #region ICollection<T> Members public void Add(T item) { if (mCountedSet.ContainsKey(item)) { mCountedSet[item]++; } else { mCountedSet.Add(item, 1); } } public void Clear() { mCountedSet.Clear(); } public bool Contains(T item) { return mCountedSet.ContainsKey(item); } public void CopyTo(T[] array, int arrayIndex) { throw new NotSupportedException("The method or operation is not implemented."); } public int Count { get { return mCountedSet.Count; } } public bool IsReadOnly { get { return false; } } public bool Remove(T item) { if (mCountedSet.ContainsKey(item)) { mCountedSet.Remove(item); return true; } return false; } #endregion /// <summary> /// Reduces the count associated with this object by 1. If this causes the count /// to become 0, then the object is removed form the set. /// </summary> /// <param name="item">The item whose count is being reduced. /// </param> public virtual void Subtract(T item) { if (mCountedSet.ContainsKey(item)) { if (mCountedSet[item] > 1) { mCountedSet[item]--; } else { mCountedSet.Remove(item); } } } /// <summary> /// Assigns the specified object the specified count in the set. /// </summary> /// <param name="item"> /// The item to be added or updated in the set. /// </param> /// <param name="count"> /// The count of the specified item. /// </param> public virtual void SetCount(T item, int count) { if (mCountedSet.ContainsKey(item)) { mCountedSet[item] = count; } else { mCountedSet.Add(item, count); } } /// <summary> Return the count of the specified object.</summary> /// <param name="item">the object whose count needs to be determined. /// </param> /// <returns> the count of the specified object. /// </returns> public virtual int GetCount(T item) { if (!mCountedSet.ContainsKey(item)) { return 0; } else { return mCountedSet[item]; } } #region Write methods public virtual void Write(string fileName, int countCutoff) { Write(fileName, countCutoff, " "); } public virtual void Write(string fileName, int countCutoff, string delim) { using (var fileStream = new FileStream(fileName, FileMode.Create)) { using (var writer = new StreamWriter(fileStream, Encoding.UTF7)) { foreach (T key in mCountedSet.Keys) { int count = this.GetCount(key); if (count >= countCutoff) { writer.WriteLine(count + delim + key); } } } } } public virtual void Write(string fileName, int countCutoff, string delim, System.Text.Encoding encoding) { using (var fileStream = new FileStream(fileName, FileMode.Create)) { using (var writer = new StreamWriter(fileStream, Encoding.UTF7)) { foreach (T key in mCountedSet.Keys) { int count = this.GetCount(key); if (count >= countCutoff) { writer.WriteLine(count + delim + key); } } } } } #endregion #region IEnumerable<T> Members public IEnumerator<T> GetEnumerator() { return new List<T>(mCountedSet.Keys).GetEnumerator(); } #endregion #region IEnumerable Members IEnumerator IEnumerable.GetEnumerator() { return new ArrayList((ICollection) mCountedSet.Keys).GetEnumerator(); } #endregion //public virtual System.Boolean AddAll(System.Collections.ICollection c) //{ // bool changed = false; // //UPGRADE_TODO: Method 'java.util.Iterator.hasNext' was converted to 'System.Collections.IEnumerator.MoveNext' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilIteratorhasNext'" // for (System.Collections.IEnumerator ci = c.GetEnumerator(); ci.MoveNext(); ) // { // //UPGRADE_TODO: Method 'java.util.Iterator.next' was converted to 'System.Collections.IEnumerator.Current' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilIteratornext'" // changed = changed || Add(ci.Current); // } // return changed; //} ///// <summary> ///// Adds all the elements contained in the specified collection. ///// </summary> ///// <param name="collection"> ///// The collection used to extract the elements that will be added. ///// </param> ///// <returns> ///// Returns true if all the elements were successfuly added. Otherwise returns false. ///// </returns> //public virtual bool AddAll(ICollection<T> collection) //{ // bool result = false; // if (collection != null) // { // foreach (T item in collection) // { // result = this.Add(item); // } // } // return result; //} ////UPGRADE_NOTE: The equivalent of method 'java.util.Set.containsAll' is not an override method. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1143'" //public virtual bool containsAll(System.Collections.ICollection c) //{ // //UPGRADE_TODO: Method 'java.util.Map.keySet' was converted to 'SupportClass.HashSetSupport' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilMapkeySet'" // return SupportClass.ICollectionSupport.ContainsAll(new HashSet<T>(mCountedSet.Keys), c); //} ////UPGRADE_NOTE: The equivalent of method 'java.util.Set.isEmpty' is not an override method. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1143'" //public virtual bool isEmpty() //{ // return (mCountedSet.Count == 0); //} ////UPGRADE_ISSUE: The equivalent in .NET for method 'java.util.Set.iterator' returns a different type. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1224'" ////GetEnumerator is not virtual in the List<T>, which is the eventual base class ////public override List<T>.Enumerator GetEnumerator() ////{ // //UPGRADE_TODO: Method 'java.util.Map.keySet' was converted to 'SupportClass.HashSetSupport' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilMapkeySet'" //// return new HashSet<T>(cset.Keys).GetEnumerator(); ////} ////UPGRADE_ISSUE: The equivalent in .NET for method 'java.util.Set.remove' returns a different type. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1224'" //public override bool Remove(T o) //{ // if (mCountedSet.ContainsKey(o)) // { // mCountedSet.Remove(o); // return true; // } // return false; //} ////UPGRADE_NOTE: The equivalent of method 'java.util.Set.removeAll' is not an override method. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1143'" //public virtual bool removeAll(ICollection<T> c) //{ // bool changed = false; // //UPGRADE_TODO: Method 'java.util.Map.keySet' was converted to 'SupportClass.HashSetSupport' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilMapkeySet'" // //UPGRADE_TODO: Method 'java.util.Iterator.hasNext' was converted to 'System.Collections.IEnumerator.MoveNext' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilIteratorhasNext'" // for (System.Collections.IEnumerator ki = new HashSet<T>(mCountedSet.Keys).GetEnumerator(); ki.MoveNext(); ) // { // System.Object tempObject; // //UPGRADE_TODO: Method 'java.util.Iterator.next' was converted to 'System.Collections.IEnumerator.Current' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilIteratornext'" // tempObject = mCountedSet[ki.Current]; // mCountedSet.Remove(ki.Current); // changed = changed || (tempObject != null); // } // return changed; //} ////UPGRADE_NOTE: The equivalent of method 'java.util.Set.retainAll' is not an override method. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1143'" //public virtual bool retainAll(System.Collections.ICollection c) //{ // bool changed = false; // //UPGRADE_TODO: Method 'java.util.Map.keySet' was converted to 'SupportClass.HashSetSupport' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilMapkeySet'" // //UPGRADE_TODO: Method 'java.util.Iterator.hasNext' was converted to 'System.Collections.IEnumerator.MoveNext' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilIteratorhasNext'" // for (System.Collections.IEnumerator ki = new SupportClass.HashSetSupport(mCountedSet.Keys).GetEnumerator(); ki.MoveNext(); ) // { // //UPGRADE_TODO: Method 'java.util.Iterator.next' was converted to 'System.Collections.IEnumerator.Current' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilIteratornext'" // System.Object key = ki.Current; // if (!SupportClass.ICollectionSupport.Contains(c, key)) // { // mCountedSet.Remove(key); // changed = true; // } // } // return changed; //} ////UPGRADE_NOTE: The equivalent of method 'java.util.Set.toArray' is not an override method. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1143'" //public virtual System.Object[] toArray() //{ // //UPGRADE_TODO: Method 'java.util.Map.keySet' was converted to 'SupportClass.HashSetSupport' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilMapkeySet'" // return SupportClass.ICollectionSupport.ToArray(new SupportClass.HashSetSupport(mCountedSet.Keys)); //} ////UPGRADE_NOTE: The equivalent of method 'java.util.Set.toArray' is not an override method. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1143'" //public virtual System.Object[] toArray(System.Object[] arg0) //{ // //UPGRADE_TODO: Method 'java.util.Map.keySet' was converted to 'SupportClass.HashSetSupport' which has a different behavior. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1073_javautilMapkeySet'" // return SupportClass.ICollectionSupport.ToArray(new SupportClass.HashSetSupport(mCountedSet.Keys), arg0); //} } }
using System; using System.CodeDom.Compiler; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Globalization; using System.Linq; using System.Text; namespace EduHub.Data.Entities { /// <summary> /// STPS Transfer Data Set /// </summary> [GeneratedCode("EduHub Data", "0.9")] public sealed partial class STPS_TFRDataSet : EduHubDataSet<STPS_TFR> { /// <inheritdoc /> public override string Name { get { return "STPS_TFR"; } } /// <inheritdoc /> public override bool SupportsEntityLastModified { get { return true; } } internal STPS_TFRDataSet(EduHubContext Context) : base(Context) { Index_ORIG_SCHOOL = new Lazy<Dictionary<string, IReadOnlyList<STPS_TFR>>>(() => this.ToGroupedDictionary(i => i.ORIG_SCHOOL)); Index_STPS_TRANS_ID = new Lazy<NullDictionary<string, STPS_TFR>>(() => this.ToNullDictionary(i => i.STPS_TRANS_ID)); Index_TID = new Lazy<Dictionary<int, STPS_TFR>>(() => this.ToDictionary(i => i.TID)); } /// <summary> /// Matches CSV file headers to actions, used to deserialize <see cref="STPS_TFR" /> /// </summary> /// <param name="Headers">The CSV column headers</param> /// <returns>An array of actions which deserialize <see cref="STPS_TFR" /> fields for each CSV column header</returns> internal override Action<STPS_TFR, string>[] BuildMapper(IReadOnlyList<string> Headers) { var mapper = new Action<STPS_TFR, string>[Headers.Count]; for (var i = 0; i < Headers.Count; i++) { switch (Headers[i]) { case "TID": mapper[i] = (e, v) => e.TID = int.Parse(v); break; case "ORIG_SCHOOL": mapper[i] = (e, v) => e.ORIG_SCHOOL = v; break; case "STPS_TRANS_ID": mapper[i] = (e, v) => e.STPS_TRANS_ID = v; break; case "SKEY": mapper[i] = (e, v) => e.SKEY = v; break; case "SKEY_NEW": mapper[i] = (e, v) => e.SKEY_NEW = v; break; case "SCHOOL": mapper[i] = (e, v) => e.SCHOOL = v; break; case "ENROL_DATE": mapper[i] = (e, v) => e.ENROL_DATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture); break; case "DEPART_DATE": mapper[i] = (e, v) => e.DEPART_DATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture); break; case "REASON_LEFT": mapper[i] = (e, v) => e.REASON_LEFT = v; break; case "ST_TRANS_ID": mapper[i] = (e, v) => e.ST_TRANS_ID = v; break; case "IMP_STATUS": mapper[i] = (e, v) => e.IMP_STATUS = v; break; case "IMP_DATE": mapper[i] = (e, v) => e.IMP_DATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture); break; case "LW_DATE": mapper[i] = (e, v) => e.LW_DATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture); break; case "LW_TIME": mapper[i] = (e, v) => e.LW_TIME = v == null ? (short?)null : short.Parse(v); break; case "LW_USER": mapper[i] = (e, v) => e.LW_USER = v; break; default: mapper[i] = MapperNoOp; break; } } return mapper; } /// <summary> /// Merges <see cref="STPS_TFR" /> delta entities /// </summary> /// <param name="Entities">Iterator for base <see cref="STPS_TFR" /> entities</param> /// <param name="DeltaEntities">List of delta <see cref="STPS_TFR" /> entities</param> /// <returns>A merged <see cref="IEnumerable{STPS_TFR}"/> of entities</returns> internal override IEnumerable<STPS_TFR> ApplyDeltaEntities(IEnumerable<STPS_TFR> Entities, List<STPS_TFR> DeltaEntities) { HashSet<string> Index_STPS_TRANS_ID = new HashSet<string>(DeltaEntities.Select(i => i.STPS_TRANS_ID)); HashSet<int> Index_TID = new HashSet<int>(DeltaEntities.Select(i => i.TID)); using (var deltaIterator = DeltaEntities.GetEnumerator()) { using (var entityIterator = Entities.GetEnumerator()) { while (deltaIterator.MoveNext()) { var deltaClusteredKey = deltaIterator.Current.ORIG_SCHOOL; bool yieldEntity = false; while (entityIterator.MoveNext()) { var entity = entityIterator.Current; bool overwritten = false; overwritten = overwritten || Index_STPS_TRANS_ID.Remove(entity.STPS_TRANS_ID); overwritten = overwritten || Index_TID.Remove(entity.TID); if (entity.ORIG_SCHOOL.CompareTo(deltaClusteredKey) <= 0) { if (!overwritten) { yield return entity; } } else { yieldEntity = !overwritten; break; } } yield return deltaIterator.Current; if (yieldEntity) { yield return entityIterator.Current; } } while (entityIterator.MoveNext()) { yield return entityIterator.Current; } } } } #region Index Fields private Lazy<Dictionary<string, IReadOnlyList<STPS_TFR>>> Index_ORIG_SCHOOL; private Lazy<NullDictionary<string, STPS_TFR>> Index_STPS_TRANS_ID; private Lazy<Dictionary<int, STPS_TFR>> Index_TID; #endregion #region Index Methods /// <summary> /// Find STPS_TFR by ORIG_SCHOOL field /// </summary> /// <param name="ORIG_SCHOOL">ORIG_SCHOOL value used to find STPS_TFR</param> /// <returns>List of related STPS_TFR entities</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<STPS_TFR> FindByORIG_SCHOOL(string ORIG_SCHOOL) { return Index_ORIG_SCHOOL.Value[ORIG_SCHOOL]; } /// <summary> /// Attempt to find STPS_TFR by ORIG_SCHOOL field /// </summary> /// <param name="ORIG_SCHOOL">ORIG_SCHOOL value used to find STPS_TFR</param> /// <param name="Value">List of related STPS_TFR entities</param> /// <returns>True if the list of related STPS_TFR entities is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByORIG_SCHOOL(string ORIG_SCHOOL, out IReadOnlyList<STPS_TFR> Value) { return Index_ORIG_SCHOOL.Value.TryGetValue(ORIG_SCHOOL, out Value); } /// <summary> /// Attempt to find STPS_TFR by ORIG_SCHOOL field /// </summary> /// <param name="ORIG_SCHOOL">ORIG_SCHOOL value used to find STPS_TFR</param> /// <returns>List of related STPS_TFR entities, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<STPS_TFR> TryFindByORIG_SCHOOL(string ORIG_SCHOOL) { IReadOnlyList<STPS_TFR> value; if (Index_ORIG_SCHOOL.Value.TryGetValue(ORIG_SCHOOL, out value)) { return value; } else { return null; } } /// <summary> /// Find STPS_TFR by STPS_TRANS_ID field /// </summary> /// <param name="STPS_TRANS_ID">STPS_TRANS_ID value used to find STPS_TFR</param> /// <returns>Related STPS_TFR entity</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public STPS_TFR FindBySTPS_TRANS_ID(string STPS_TRANS_ID) { return Index_STPS_TRANS_ID.Value[STPS_TRANS_ID]; } /// <summary> /// Attempt to find STPS_TFR by STPS_TRANS_ID field /// </summary> /// <param name="STPS_TRANS_ID">STPS_TRANS_ID value used to find STPS_TFR</param> /// <param name="Value">Related STPS_TFR entity</param> /// <returns>True if the related STPS_TFR entity is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindBySTPS_TRANS_ID(string STPS_TRANS_ID, out STPS_TFR Value) { return Index_STPS_TRANS_ID.Value.TryGetValue(STPS_TRANS_ID, out Value); } /// <summary> /// Attempt to find STPS_TFR by STPS_TRANS_ID field /// </summary> /// <param name="STPS_TRANS_ID">STPS_TRANS_ID value used to find STPS_TFR</param> /// <returns>Related STPS_TFR entity, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public STPS_TFR TryFindBySTPS_TRANS_ID(string STPS_TRANS_ID) { STPS_TFR value; if (Index_STPS_TRANS_ID.Value.TryGetValue(STPS_TRANS_ID, out value)) { return value; } else { return null; } } /// <summary> /// Find STPS_TFR by TID field /// </summary> /// <param name="TID">TID value used to find STPS_TFR</param> /// <returns>Related STPS_TFR entity</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public STPS_TFR FindByTID(int TID) { return Index_TID.Value[TID]; } /// <summary> /// Attempt to find STPS_TFR by TID field /// </summary> /// <param name="TID">TID value used to find STPS_TFR</param> /// <param name="Value">Related STPS_TFR entity</param> /// <returns>True if the related STPS_TFR entity is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByTID(int TID, out STPS_TFR Value) { return Index_TID.Value.TryGetValue(TID, out Value); } /// <summary> /// Attempt to find STPS_TFR by TID field /// </summary> /// <param name="TID">TID value used to find STPS_TFR</param> /// <returns>Related STPS_TFR entity, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public STPS_TFR TryFindByTID(int TID) { STPS_TFR value; if (Index_TID.Value.TryGetValue(TID, out value)) { return value; } else { return null; } } #endregion #region SQL Integration /// <summary> /// Returns a <see cref="SqlCommand"/> which checks for the existence of a STPS_TFR table, and if not found, creates the table and associated indexes. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> public override SqlCommand GetSqlCreateTableCommand(SqlConnection SqlConnection) { return new SqlCommand( connection: SqlConnection, cmdText: @"IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[STPS_TFR]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1) BEGIN CREATE TABLE [dbo].[STPS_TFR]( [TID] int IDENTITY NOT NULL, [ORIG_SCHOOL] varchar(8) NOT NULL, [STPS_TRANS_ID] varchar(30) NULL, [SKEY] varchar(10) NULL, [SKEY_NEW] varchar(10) NULL, [SCHOOL] varchar(8) NULL, [ENROL_DATE] datetime NULL, [DEPART_DATE] datetime NULL, [REASON_LEFT] varchar(MAX) NULL, [ST_TRANS_ID] varchar(30) NULL, [IMP_STATUS] varchar(15) NULL, [IMP_DATE] datetime NULL, [LW_DATE] datetime NULL, [LW_TIME] smallint NULL, [LW_USER] varchar(128) NULL, CONSTRAINT [STPS_TFR_Index_TID] PRIMARY KEY NONCLUSTERED ( [TID] ASC ) ); CREATE CLUSTERED INDEX [STPS_TFR_Index_ORIG_SCHOOL] ON [dbo].[STPS_TFR] ( [ORIG_SCHOOL] ASC ); CREATE NONCLUSTERED INDEX [STPS_TFR_Index_STPS_TRANS_ID] ON [dbo].[STPS_TFR] ( [STPS_TRANS_ID] ASC ); END"); } /// <summary> /// Returns a <see cref="SqlCommand"/> which disables all non-clustered table indexes. /// Typically called before <see cref="SqlBulkCopy"/> to improve performance. /// <see cref="GetSqlRebuildIndexesCommand(SqlConnection)"/> should be called to rebuild and enable indexes after performance sensitive work is completed. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <returns>A <see cref="SqlCommand"/> which (when executed) will disable all non-clustered table indexes</returns> public override SqlCommand GetSqlDisableIndexesCommand(SqlConnection SqlConnection) { return new SqlCommand( connection: SqlConnection, cmdText: @"IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[STPS_TFR]') AND name = N'STPS_TFR_Index_STPS_TRANS_ID') ALTER INDEX [STPS_TFR_Index_STPS_TRANS_ID] ON [dbo].[STPS_TFR] DISABLE; IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[STPS_TFR]') AND name = N'STPS_TFR_Index_TID') ALTER INDEX [STPS_TFR_Index_TID] ON [dbo].[STPS_TFR] DISABLE; "); } /// <summary> /// Returns a <see cref="SqlCommand"/> which rebuilds and enables all non-clustered table indexes. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <returns>A <see cref="SqlCommand"/> which (when executed) will rebuild and enable all non-clustered table indexes</returns> public override SqlCommand GetSqlRebuildIndexesCommand(SqlConnection SqlConnection) { return new SqlCommand( connection: SqlConnection, cmdText: @"IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[STPS_TFR]') AND name = N'STPS_TFR_Index_STPS_TRANS_ID') ALTER INDEX [STPS_TFR_Index_STPS_TRANS_ID] ON [dbo].[STPS_TFR] REBUILD PARTITION = ALL; IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[STPS_TFR]') AND name = N'STPS_TFR_Index_TID') ALTER INDEX [STPS_TFR_Index_TID] ON [dbo].[STPS_TFR] REBUILD PARTITION = ALL; "); } /// <summary> /// Returns a <see cref="SqlCommand"/> which deletes the <see cref="STPS_TFR"/> entities passed /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <param name="Entities">The <see cref="STPS_TFR"/> entities to be deleted</param> public override SqlCommand GetSqlDeleteCommand(SqlConnection SqlConnection, IEnumerable<STPS_TFR> Entities) { SqlCommand command = new SqlCommand(); int parameterIndex = 0; StringBuilder builder = new StringBuilder(); List<string> Index_STPS_TRANS_ID = new List<string>(); List<int> Index_TID = new List<int>(); foreach (var entity in Entities) { Index_STPS_TRANS_ID.Add(entity.STPS_TRANS_ID); Index_TID.Add(entity.TID); } builder.AppendLine("DELETE [dbo].[STPS_TFR] WHERE"); // Index_STPS_TRANS_ID builder.Append("[STPS_TRANS_ID] IN ("); for (int index = 0; index < Index_STPS_TRANS_ID.Count; index++) { if (index != 0) builder.Append(", "); // STPS_TRANS_ID var parameterSTPS_TRANS_ID = $"@p{parameterIndex++}"; builder.Append(parameterSTPS_TRANS_ID); command.Parameters.Add(parameterSTPS_TRANS_ID, SqlDbType.VarChar, 30).Value = (object)Index_STPS_TRANS_ID[index] ?? DBNull.Value; } builder.AppendLine(") OR"); // Index_TID builder.Append("[TID] IN ("); for (int index = 0; index < Index_TID.Count; index++) { if (index != 0) builder.Append(", "); // TID var parameterTID = $"@p{parameterIndex++}"; builder.Append(parameterTID); command.Parameters.Add(parameterTID, SqlDbType.Int).Value = Index_TID[index]; } builder.Append(");"); command.Connection = SqlConnection; command.CommandText = builder.ToString(); return command; } /// <summary> /// Provides a <see cref="IDataReader"/> for the STPS_TFR data set /// </summary> /// <returns>A <see cref="IDataReader"/> for the STPS_TFR data set</returns> public override EduHubDataSetDataReader<STPS_TFR> GetDataSetDataReader() { return new STPS_TFRDataReader(Load()); } /// <summary> /// Provides a <see cref="IDataReader"/> for the STPS_TFR data set /// </summary> /// <returns>A <see cref="IDataReader"/> for the STPS_TFR data set</returns> public override EduHubDataSetDataReader<STPS_TFR> GetDataSetDataReader(List<STPS_TFR> Entities) { return new STPS_TFRDataReader(new EduHubDataSetLoadedReader<STPS_TFR>(this, Entities)); } // Modest implementation to primarily support SqlBulkCopy private class STPS_TFRDataReader : EduHubDataSetDataReader<STPS_TFR> { public STPS_TFRDataReader(IEduHubDataSetReader<STPS_TFR> Reader) : base (Reader) { } public override int FieldCount { get { return 15; } } public override object GetValue(int i) { switch (i) { case 0: // TID return Current.TID; case 1: // ORIG_SCHOOL return Current.ORIG_SCHOOL; case 2: // STPS_TRANS_ID return Current.STPS_TRANS_ID; case 3: // SKEY return Current.SKEY; case 4: // SKEY_NEW return Current.SKEY_NEW; case 5: // SCHOOL return Current.SCHOOL; case 6: // ENROL_DATE return Current.ENROL_DATE; case 7: // DEPART_DATE return Current.DEPART_DATE; case 8: // REASON_LEFT return Current.REASON_LEFT; case 9: // ST_TRANS_ID return Current.ST_TRANS_ID; case 10: // IMP_STATUS return Current.IMP_STATUS; case 11: // IMP_DATE return Current.IMP_DATE; case 12: // LW_DATE return Current.LW_DATE; case 13: // LW_TIME return Current.LW_TIME; case 14: // LW_USER return Current.LW_USER; default: throw new ArgumentOutOfRangeException(nameof(i)); } } public override bool IsDBNull(int i) { switch (i) { case 2: // STPS_TRANS_ID return Current.STPS_TRANS_ID == null; case 3: // SKEY return Current.SKEY == null; case 4: // SKEY_NEW return Current.SKEY_NEW == null; case 5: // SCHOOL return Current.SCHOOL == null; case 6: // ENROL_DATE return Current.ENROL_DATE == null; case 7: // DEPART_DATE return Current.DEPART_DATE == null; case 8: // REASON_LEFT return Current.REASON_LEFT == null; case 9: // ST_TRANS_ID return Current.ST_TRANS_ID == null; case 10: // IMP_STATUS return Current.IMP_STATUS == null; case 11: // IMP_DATE return Current.IMP_DATE == null; case 12: // LW_DATE return Current.LW_DATE == null; case 13: // LW_TIME return Current.LW_TIME == null; case 14: // LW_USER return Current.LW_USER == null; default: return false; } } public override string GetName(int ordinal) { switch (ordinal) { case 0: // TID return "TID"; case 1: // ORIG_SCHOOL return "ORIG_SCHOOL"; case 2: // STPS_TRANS_ID return "STPS_TRANS_ID"; case 3: // SKEY return "SKEY"; case 4: // SKEY_NEW return "SKEY_NEW"; case 5: // SCHOOL return "SCHOOL"; case 6: // ENROL_DATE return "ENROL_DATE"; case 7: // DEPART_DATE return "DEPART_DATE"; case 8: // REASON_LEFT return "REASON_LEFT"; case 9: // ST_TRANS_ID return "ST_TRANS_ID"; case 10: // IMP_STATUS return "IMP_STATUS"; case 11: // IMP_DATE return "IMP_DATE"; case 12: // LW_DATE return "LW_DATE"; case 13: // LW_TIME return "LW_TIME"; case 14: // LW_USER return "LW_USER"; default: throw new ArgumentOutOfRangeException(nameof(ordinal)); } } public override int GetOrdinal(string name) { switch (name) { case "TID": return 0; case "ORIG_SCHOOL": return 1; case "STPS_TRANS_ID": return 2; case "SKEY": return 3; case "SKEY_NEW": return 4; case "SCHOOL": return 5; case "ENROL_DATE": return 6; case "DEPART_DATE": return 7; case "REASON_LEFT": return 8; case "ST_TRANS_ID": return 9; case "IMP_STATUS": return 10; case "IMP_DATE": return 11; case "LW_DATE": return 12; case "LW_TIME": return 13; case "LW_USER": return 14; default: throw new ArgumentOutOfRangeException(nameof(name)); } } } #endregion } }
using System; using NUnit.Framework; using Skahal.Infrastructure.Framework.Repositories; using TestSharp; using System.Linq; using Skahal.Infrastructure.Framework.People; using HelperSharp; namespace Skahal.Infrastructure.Framework.UnitTests.Repositories { [TestFixture()] public class MemoryRepositoryTest { #region Fields private MemoryUnitOfWork m_unitOfWork; private MemoryRepository<User> m_target; #endregion #region Initialize [SetUp] public void InitializeTest() { m_unitOfWork = new MemoryUnitOfWork (); m_target = new MemoryRepository<User> (m_unitOfWork, (u) => { return Guid.NewGuid().ToString(); }); } #endregion #region Tests [Test()] public void FindAll_Filter_EntitiesFiltered () { m_target.Add(new User() {} ); var user = new User (); m_target.Add(user); m_target.Add(new User() {} ); m_target.Add(new User() {} ); m_unitOfWork.Commit (); var actual = m_target.FindAll (f => f.Key == user.Key).ToList(); Assert.AreEqual (1, actual.Count); Assert.AreEqual (user.Key, actual[0].Key); } [Test()] public void FindAllAscending_NullOrder_ArgumentNullException() { ExceptionAssert.IsThrowing(new ArgumentNullException("orderBy"), () => { m_target.FindAllAscending<int>(0, 1, (o) => o.Name == null, null); }); } [Test()] public void FindAllAscending_FilterAndOrder_EntitiesFilteredAndOrdered() { m_target.Add(new User() { Name = "B" }); m_target.Add(new User() { Name = "C" }); m_target.Add(new User() { Name = "A" }); m_unitOfWork.Commit(); var actual = m_target.FindAllAscending(0, 3, (f) => true, (o) => o.Name).ToList(); Assert.AreEqual(3, actual.Count); Assert.AreEqual("A", actual[0].Name); Assert.AreEqual("B", actual[1].Name); Assert.AreEqual("C", actual[2].Name); actual = m_target.FindAllAscending(1, 3, (f) => true, (o) => o.Name).ToList(); Assert.AreEqual(2, actual.Count); Assert.AreEqual("B", actual[0].Name); Assert.AreEqual("C", actual[1].Name); actual = m_target.FindAllAscending(0, 2, (f) => true, (o) => o.Name).ToList(); Assert.AreEqual(2, actual.Count); Assert.AreEqual("A", actual[0].Name); Assert.AreEqual("B", actual[1].Name); } [Test()] public void FindAllDescending_NullOrder_ArgumentNullException() { ExceptionAssert.IsThrowing(new ArgumentNullException("orderBy"), () => { m_target.FindAllDescending<int>(0, 1, (o) => o.Name == null, null); }); } [Test()] public void FindAllDescending_FilterAndOrder_EntitiesFilteredAndOrdered() { m_target.Add(new User() { Name = "B" }); m_target.Add(new User() { Name = "C" }); m_target.Add(new User() { Name = "A" }); m_unitOfWork.Commit(); var actual = m_target.FindAllDescending(0, 3, (f) => true, (o) => o.Name).ToList(); Assert.AreEqual(3, actual.Count); Assert.AreEqual("C", actual[0].Name); Assert.AreEqual("B", actual[1].Name); Assert.AreEqual("A", actual[2].Name); actual = m_target.FindAllDescending(1, 3, (f) => true, (o) => o.Name).ToList(); Assert.AreEqual(2, actual.Count); Assert.AreEqual("B", actual[0].Name); Assert.AreEqual("A", actual[1].Name); actual = m_target.FindAllDescending(0, 2, (f) => true, (o) => o.Name).ToList(); Assert.AreEqual(2, actual.Count); Assert.AreEqual("C", actual[0].Name); Assert.AreEqual("B", actual[1].Name); } [Test()] public void CountAll_Filter_EntitiesFiltered () { m_target.Add(new User() { } ); m_target.Add(new User() { } ); m_target.Add(new User() { } ); m_target.Add(new User() { } ); m_unitOfWork.Commit(); var actual = m_target.CountAll (f => true); Assert.AreEqual (4, actual); } [Test()] public void Add_NullEntity_ArgumentNullException () { ExceptionAssert.IsThrowing (new ArgumentNullException("item"), () => { m_target.Add (null); }); } [Test()] public void Add_EntityAlreadyAdded_Exception() { var user = new User ("1"); m_target.Add(user); m_target.Add(user); ExceptionAssert.IsThrowing (new InvalidOperationException ("There is another entity with id '1'."), () => { m_unitOfWork.Commit (); }); var actual = m_target.FindAll(f => true).ToList(); Assert.AreEqual (1, actual.Count); Assert.AreEqual ("1", actual[0].Key); } [Test()] public void Add_Entity_Added () { m_target.Add(new User()); m_unitOfWork.Commit (); var actual = m_target.FindAll(f => true).ToList(); Assert.AreEqual (1, actual.Count); Assert.IsFalse (String.IsNullOrWhiteSpace((string)actual[0].Key)); } [Test()] public void Add_EntityWithIntId_AddedWithNewId() { var target = new MemoryRepository<EntityWithIntIdStub>((e) => 1); target.SetUnitOfWork(m_unitOfWork); target.Add(new EntityWithIntIdStub()); m_unitOfWork.Commit(); var actual = target.FindAll(f => true).ToList(); Assert.AreEqual(1, actual.Count); Assert.AreEqual(1, actual[0].Id); } [Test()] public void Delete_NullEntity_ArgumentNullException () { ExceptionAssert.IsThrowing (new ArgumentNullException("item"), () => { m_target.Remove(null); }); } [Test()] public void Delete_EntityWithIdDoesNotExists_ArgumentNullException () { var user = new User() { }; m_target.Remove(user); ExceptionAssert.IsThrowing ( new InvalidOperationException ("There is no entity with id '{0}'.".With(user.Key)), () => { m_unitOfWork.Commit(); }); } [Test()] public void Delete_Entity_EntityDeleted () { var user = new User () { }; m_target.Add (user); m_unitOfWork.Commit(); m_target.Remove (user); m_unitOfWork.Commit(); var actual = m_target.FindAll(f => true).ToList(); Assert.AreEqual (0, actual.Count); } [Test()] public void Modify_EntityWithIdDoesNotExist_Added () { var user = new User(); Assert.IsNull(user.Key); m_target[user.Key] = user; m_unitOfWork.Commit(); Assert.IsNotNull(user.Key); var actual = m_target.FindAll(f => true).ToList(); Assert.AreEqual (1, actual.Count); Assert.AreEqual (user.Key, actual[0].Key); } [Test()] public void Modify_Entity_EntityModified () { var user = new User (); m_target.Add (user); user = new User (); m_target.Add (user); m_unitOfWork.Commit(); var modifiedUser = new User(user.Key) { Name = "new name" }; m_target[user.Key] = modifiedUser; m_unitOfWork.Commit(); var actual = m_target.FindAll (f => f == user).FirstOrDefault (); Assert.AreEqual (user.Key, actual.Key); Assert.AreEqual ("new name", actual.Name); } #endregion } }
// <copyright file="PlayGamesLocalUser.cs" company="Google Inc."> // Copyright (C) 2014 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> #if (UNITY_ANDROID || (UNITY_IPHONE && !NO_GPGS)) namespace GooglePlayGames { using GooglePlayGames.BasicApi; using System; using UnityEngine.SocialPlatforms; /// <summary> /// Represents the Google Play Games local user. /// </summary> public class PlayGamesLocalUser : PlayGamesUserProfile, ILocalUser { internal PlayGamesPlatform mPlatform; private string emailAddress; private PlayerStats mStats; internal PlayGamesLocalUser(PlayGamesPlatform plaf) : base("localUser", string.Empty, string.Empty) { mPlatform = plaf; emailAddress = null; mStats = null; } /// <summary> /// Authenticates the local user. Equivalent to calling /// <see cref="PlayGamesPlatform.Authenticate" />. /// </summary> public void Authenticate(Action<bool> callback) { mPlatform.Authenticate(callback); } public void Authenticate(Action<bool, string> callback) { mPlatform.Authenticate(callback); } /// <summary> /// Authenticates the local user. Equivalent to calling /// <see cref="PlayGamesPlatform.Authenticate" />. /// </summary> public void Authenticate(Action<bool> callback, bool silent) { mPlatform.Authenticate(callback, silent); } /// <summary> /// Loads all friends of the authenticated user. /// </summary> public void LoadFriends(Action<bool> callback) { mPlatform.LoadFriends(this, callback); } /// <summary> /// Synchronous version of friends, returns null until loaded. /// </summary> public IUserProfile[] friends { get { return mPlatform.GetFriends(); } } /// <summary> /// Gets an id token for the user. /// NOTE: This property can only be accessed using the main Unity thread. /// </summary> /// <param name="idTokenCallback"> A callback to be invoked after token is retrieved. Will be passed null value /// on failure. </param> [Obsolete("Use PlayGamesPlatform.GetServerAuthCode()")] public void GetIdToken(Action<string> idTokenCallback) { if (authenticated) mPlatform.GetIdToken(idTokenCallback); else idTokenCallback(null); } /// <summary> /// Returns whether or not the local user is authenticated to Google Play Games. /// </summary> /// <returns> /// <c>true</c> if authenticated; otherwise, <c>false</c>. /// </returns> public bool authenticated { get { return mPlatform.IsAuthenticated(); } } /// <summary> /// Not implemented. As safety placeholder, returns true. /// </summary> public bool underage { get { return true; } } /// <summary> /// Gets the display name of the user. /// </summary> /// <returns> /// The display name of the user. /// </returns> public new string userName { get { string retval = string.Empty; if (authenticated) { retval = mPlatform.GetUserDisplayName(); if (!base.userName.Equals(retval)) { ResetIdentity(retval, mPlatform.GetUserId(), mPlatform.GetUserImageUrl()); } } return retval; } } /// <summary> /// Gets the user's Google id. /// </summary> /// <remarks> This id is persistent and uniquely identifies the user /// across all games that use Google Play Game Services. It is /// the preferred method of uniquely identifying a player instead /// of email address. /// </remarks> /// <returns> /// The user's Google id. /// </returns> public new string id { get { string retval = string.Empty; if (authenticated) { retval = mPlatform.GetUserId(); if (!base.id.Equals(retval)) { ResetIdentity(mPlatform.GetUserDisplayName(), retval, mPlatform.GetUserImageUrl()); } } return retval; } } /// <summary> /// Gets an access token for the user. /// NOTE: This property can only be accessed using the main Unity thread. /// </summary> /// <returns> /// An id token for the user. /// </returns> [Obsolete("Use PlayGamesPlatform.GetServerAuthCode()")] public string accessToken { get { return authenticated ? mPlatform.GetAccessToken() : string.Empty; } } /// <summary> /// Returns true (since this is the local user). /// </summary> public new bool isFriend { get { return true; } } /// <summary> /// Gets the local user's state. This is always <c>UserState.Online</c> for /// the local user. /// </summary> public new UserState state { get { return UserState.Online; } } public new string AvatarURL { get { string retval = string.Empty; if (authenticated) { retval = mPlatform.GetUserImageUrl(); if (!base.id.Equals(retval)) { ResetIdentity(mPlatform.GetUserDisplayName(), mPlatform.GetUserId(), retval); } } return retval; } } /// <summary>Gets the email of the signed in player.</summary> /// <remarks>If your game requires a persistent, unique id for the /// player, the use of PlayerId is recommendend since it does not /// require extra permission consent from the user. /// This is only available if the Requires Google Plus option /// is added to the setup (which enables additional /// permissions for the application). /// NOTE: This property can only be accessed using the main Unity thread. /// </remarks> /// <value>The email.</value> public string Email { get { // treat null as unitialized, empty as no email. This can // happen when the web client is not initialized. if (authenticated && string.IsNullOrEmpty(emailAddress)) { emailAddress = mPlatform.GetUserEmail(); emailAddress = emailAddress ?? string.Empty; } return authenticated ? emailAddress : string.Empty; } } /// <summary> /// Gets the player's stats. /// </summary> /// <param name="callback">Callback when they are available.</param> public void GetStats(Action<CommonStatusCodes, PlayerStats> callback) { if (mStats == null || !mStats.Valid) { mPlatform.GetPlayerStats((rc, stats) => { mStats = stats; callback(rc, stats); }); } else { // 0 = success callback(CommonStatusCodes.Success, mStats); } } } } #endif
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections; using System.IO; using System.Reflection; using System.Net; using System.Text; using OpenSim.Server.Base; using OpenSim.Server.Handlers.Base; using OpenSim.Services.Interfaces; using GridRegion = OpenSim.Services.Interfaces.GridRegion; using OpenSim.Framework; using OpenSim.Framework.Servers.HttpServer; using OpenMetaverse; using OpenMetaverse.StructuredData; using Nini.Config; using log4net; namespace OpenSim.Server.Handlers.Simulation { public class AgentHandler { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private ISimulationService m_SimulationService; public AgentHandler() { } public AgentHandler(ISimulationService sim) { m_SimulationService = sim; } public Hashtable Handler(Hashtable request) { // m_log.Debug("[CONNECTION DEBUGGING]: AgentHandler Called"); // // m_log.Debug("---------------------------"); // m_log.Debug(" >> uri=" + request["uri"]); // m_log.Debug(" >> content-type=" + request["content-type"]); // m_log.Debug(" >> http-method=" + request["http-method"]); // m_log.Debug("---------------------------\n"); Hashtable responsedata = new Hashtable(); responsedata["content_type"] = "text/html"; responsedata["keepalive"] = false; UUID agentID; UUID regionID; string action; if (!Utils.GetParams((string)request["uri"], out agentID, out regionID, out action)) { m_log.InfoFormat("[AGENT HANDLER]: Invalid parameters for agent message {0}", request["uri"]); responsedata["int_response_code"] = 404; responsedata["str_response_string"] = "false"; return responsedata; } // Next, let's parse the verb string method = (string)request["http-method"]; if (method.Equals("PUT")) { DoAgentPut(request, responsedata); return responsedata; } else if (method.Equals("POST")) { DoAgentPost(request, responsedata, agentID); return responsedata; } else if (method.Equals("GET")) { DoAgentGet(request, responsedata, agentID, regionID); return responsedata; } else if (method.Equals("DELETE")) { DoAgentDelete(request, responsedata, agentID, action, regionID); return responsedata; } else { m_log.InfoFormat("[AGENT HANDLER]: method {0} not supported in agent message", method); responsedata["int_response_code"] = HttpStatusCode.MethodNotAllowed; responsedata["str_response_string"] = "Method not allowed"; return responsedata; } } protected void DoAgentPost(Hashtable request, Hashtable responsedata, UUID id) { OSDMap args = Utils.GetOSDMap((string)request["body"]); if (args == null) { responsedata["int_response_code"] = HttpStatusCode.BadRequest; responsedata["str_response_string"] = "Bad request"; return; } // retrieve the input arguments int x = 0, y = 0; UUID uuid = UUID.Zero; string regionname = string.Empty; uint teleportFlags = 0; if (args.ContainsKey("destination_x") && args["destination_x"] != null) Int32.TryParse(args["destination_x"].AsString(), out x); else m_log.WarnFormat(" -- request didn't have destination_x"); if (args.ContainsKey("destination_y") && args["destination_y"] != null) Int32.TryParse(args["destination_y"].AsString(), out y); else m_log.WarnFormat(" -- request didn't have destination_y"); if (args.ContainsKey("destination_uuid") && args["destination_uuid"] != null) UUID.TryParse(args["destination_uuid"].AsString(), out uuid); if (args.ContainsKey("destination_name") && args["destination_name"] != null) regionname = args["destination_name"].ToString(); if (args.ContainsKey("teleport_flags") && args["teleport_flags"] != null) teleportFlags = args["teleport_flags"].AsUInteger(); GridRegion destination = new GridRegion(); destination.RegionID = uuid; destination.RegionLocX = x; destination.RegionLocY = y; destination.RegionName = regionname; AgentCircuitData aCircuit = new AgentCircuitData(); try { aCircuit.UnpackAgentCircuitData(args); } catch (Exception ex) { m_log.InfoFormat("[AGENT HANDLER]: exception on unpacking ChildCreate message {0}", ex.Message); responsedata["int_response_code"] = HttpStatusCode.BadRequest; responsedata["str_response_string"] = "Bad request"; return; } OSDMap resp = new OSDMap(2); string reason = String.Empty; // This is the meaning of POST agent //m_regionClient.AdjustUserInformation(aCircuit); //bool result = m_SimulationService.CreateAgent(destination, aCircuit, teleportFlags, out reason); bool result = CreateAgent(destination, aCircuit, teleportFlags, out reason); resp["reason"] = OSD.FromString(reason); resp["success"] = OSD.FromBoolean(result); // Let's also send out the IP address of the caller back to the caller (HG 1.5) resp["your_ip"] = OSD.FromString(GetCallerIP(request)); // TODO: add reason if not String.Empty? responsedata["int_response_code"] = HttpStatusCode.OK; responsedata["str_response_string"] = OSDParser.SerializeJsonString(resp); } // subclasses can override this protected virtual bool CreateAgent(GridRegion destination, AgentCircuitData aCircuit, uint teleportFlags, out string reason) { return m_SimulationService.CreateAgent(destination, aCircuit, teleportFlags, out reason); } protected void DoAgentPut(Hashtable request, Hashtable responsedata) { OSDMap args = Utils.GetOSDMap((string)request["body"]); if (args == null) { responsedata["int_response_code"] = HttpStatusCode.BadRequest; responsedata["str_response_string"] = "Bad request"; return; } // retrieve the input arguments int x = 0, y = 0; UUID uuid = UUID.Zero; string regionname = string.Empty; if (args.ContainsKey("destination_x") && args["destination_x"] != null) Int32.TryParse(args["destination_x"].AsString(), out x); if (args.ContainsKey("destination_y") && args["destination_y"] != null) Int32.TryParse(args["destination_y"].AsString(), out y); if (args.ContainsKey("destination_uuid") && args["destination_uuid"] != null) UUID.TryParse(args["destination_uuid"].AsString(), out uuid); if (args.ContainsKey("destination_name") && args["destination_name"] != null) regionname = args["destination_name"].ToString(); GridRegion destination = new GridRegion(); destination.RegionID = uuid; destination.RegionLocX = x; destination.RegionLocY = y; destination.RegionName = regionname; string messageType; if (args["message_type"] != null) messageType = args["message_type"].AsString(); else { m_log.Warn("[AGENT HANDLER]: Agent Put Message Type not found. "); messageType = "AgentData"; } bool result = true; if ("AgentData".Equals(messageType)) { AgentData agent = new AgentData(); try { agent.Unpack(args); } catch (Exception ex) { m_log.InfoFormat("[AGENT HANDLER]: exception on unpacking ChildAgentUpdate message {0}", ex.Message); responsedata["int_response_code"] = HttpStatusCode.BadRequest; responsedata["str_response_string"] = "Bad request"; return; } //agent.Dump(); // This is one of the meanings of PUT agent result = UpdateAgent(destination, agent); } else if ("AgentPosition".Equals(messageType)) { AgentPosition agent = new AgentPosition(); try { agent.Unpack(args); } catch (Exception ex) { m_log.InfoFormat("[AGENT HANDLER]: exception on unpacking ChildAgentUpdate message {0}", ex.Message); return; } //agent.Dump(); // This is one of the meanings of PUT agent result = m_SimulationService.UpdateAgent(destination, agent); } responsedata["int_response_code"] = HttpStatusCode.OK; responsedata["str_response_string"] = result.ToString(); //responsedata["str_response_string"] = OSDParser.SerializeJsonString(resp); ??? instead } // subclasses can override this protected virtual bool UpdateAgent(GridRegion destination, AgentData agent) { return m_SimulationService.UpdateAgent(destination, agent); } protected virtual void DoAgentGet(Hashtable request, Hashtable responsedata, UUID id, UUID regionID) { if (m_SimulationService == null) { m_log.Debug("[AGENT HANDLER]: Agent GET called. Harmless but useless."); responsedata["content_type"] = "application/json"; responsedata["int_response_code"] = HttpStatusCode.NotImplemented; responsedata["str_response_string"] = string.Empty; return; } GridRegion destination = new GridRegion(); destination.RegionID = regionID; IAgentData agent = null; bool result = m_SimulationService.RetrieveAgent(destination, id, out agent); OSDMap map = null; if (result) { if (agent != null) // just to make sure { map = agent.Pack(); string strBuffer = ""; try { strBuffer = OSDParser.SerializeJsonString(map); } catch (Exception e) { m_log.WarnFormat("[AGENT HANDLER]: Exception thrown on serialization of DoAgentGet: {0}", e.Message); responsedata["int_response_code"] = HttpStatusCode.InternalServerError; // ignore. buffer will be empty, caller should check. } responsedata["content_type"] = "application/json"; responsedata["int_response_code"] = HttpStatusCode.OK; responsedata["str_response_string"] = strBuffer; } else { responsedata["int_response_code"] = HttpStatusCode.InternalServerError; responsedata["str_response_string"] = "Internal error"; } } else { responsedata["int_response_code"] = HttpStatusCode.NotFound; responsedata["str_response_string"] = "Not Found"; } } protected void DoAgentDelete(Hashtable request, Hashtable responsedata, UUID id, string action, UUID regionID) { m_log.Debug(" >>> DoDelete action:" + action + "; RegionID:" + regionID); GridRegion destination = new GridRegion(); destination.RegionID = regionID; if (action.Equals("release")) ReleaseAgent(regionID, id); else m_SimulationService.CloseAgent(destination, id); responsedata["int_response_code"] = HttpStatusCode.OK; responsedata["str_response_string"] = "OpenSim agent " + id.ToString(); m_log.Debug("[AGENT HANDLER]: Agent Released/Deleted."); } protected virtual void ReleaseAgent(UUID regionID, UUID id) { m_SimulationService.ReleaseAgent(regionID, id, ""); } private string GetCallerIP(Hashtable req) { if (req.ContainsKey("headers")) { try { Hashtable headers = (Hashtable)req["headers"]; if (headers.ContainsKey("remote_addr") && headers["remote_addr"] != null) return headers["remote_addr"].ToString(); } catch (Exception e) { m_log.WarnFormat("[AGENT HANDLER]: exception in GetCallerIP: {0}", e.Message); } } return string.Empty; } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using Mono.Addins; using Nini.Config; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using System; using System.Collections; using System.Collections.Generic; using System.Text.RegularExpressions; using System.Threading; // using log4net; // using System.Reflection; /***************************************************** * * WorldCommModule * * * Holding place for world comms - basically llListen * function implementation. * * lLListen(integer channel, string name, key id, string msg) * The name, id, and msg arguments specify the filtering * criteria. You can pass the empty string * (or NULL_KEY for id) for these to set a completely * open filter; this causes the listen() event handler to be * invoked for all chat on the channel. To listen only * for chat spoken by a specific object or avatar, * specify the name and/or id arguments. To listen * only for a specific command, specify the * (case-sensitive) msg argument. If msg is not empty, * listener will only hear strings which are exactly equal * to msg. You can also use all the arguments to establish * the most restrictive filtering criteria. * * It might be useful for each listener to maintain a message * digest, with a list of recent messages by UUID. This can * be used to prevent in-world repeater loops. However, the * linden functions do not have this capability, so for now * thats the way it works. * Instead it blocks messages originating from the same prim. * (not Object!) * * For LSL compliance, note the following: * (Tested again 1.21.1 on May 2, 2008) * 1. 'id' has to be parsed into a UUID. None-UUID keys are * to be replaced by the ZeroID key. (Well, TryParse does * that for us. * 2. Setting up an listen event from the same script, with the * same filter settings (including step 1), returns the same * handle as the original filter. * 3. (TODO) handles should be script-local. Starting from 1. * Might be actually easier to map the global handle into * script-local handle in the ScriptEngine. Not sure if its * worth the effort tho. * * **************************************************/ namespace OpenSim.Region.CoreModules.Scripting.WorldComm { public class ListenerInfo : IWorldCommListenerInfo { /// <summary> /// Listener is active or not /// </summary> private bool m_active; /// <summary> /// Channel /// </summary> private int m_channel; /// <summary> /// Assigned handle of this listener /// </summary> private int m_handle; /// <summary> /// ID of the host/scene part /// </summary> private UUID m_hostID; /// <summary> /// ID to filter messages from /// </summary> private UUID m_id; /// <summary> /// ID of the host script engine /// </summary> private UUID m_itemID; /// <summary> /// Local ID from script engine /// </summary> private uint m_localID; /// <summary> /// The message /// </summary> private string m_message; /// <summary> /// Object name to filter messages from /// </summary> private string m_name; public ListenerInfo(int handle, uint localID, UUID ItemID, UUID hostID, int channel, string name, UUID id, string message) { Initialise(handle, localID, ItemID, hostID, channel, name, id, message, 0); } public ListenerInfo(int handle, uint localID, UUID ItemID, UUID hostID, int channel, string name, UUID id, string message, int regexBitfield) { Initialise(handle, localID, ItemID, hostID, channel, name, id, message, regexBitfield); } public ListenerInfo(ListenerInfo li, string name, UUID id, string message) { Initialise(li.m_handle, li.m_localID, li.m_itemID, li.m_hostID, li.m_channel, name, id, message, 0); } public ListenerInfo(ListenerInfo li, string name, UUID id, string message, int regexBitfield) { Initialise(li.m_handle, li.m_localID, li.m_itemID, li.m_hostID, li.m_channel, name, id, message, regexBitfield); } public int RegexBitfield { get; private set; } public static ListenerInfo FromData(uint localID, UUID ItemID, UUID hostID, Object[] data) { ListenerInfo linfo = new ListenerInfo((int)data[1], localID, ItemID, hostID, (int)data[2], (string)data[3], (UUID)data[4], (string)data[5]); linfo.m_active = (bool)data[0]; if (data.Length >= 7) { linfo.RegexBitfield = (int)data[6]; } return linfo; } public void Activate() { m_active = true; } public void Deactivate() { m_active = false; } public int GetChannel() { return m_channel; } public int GetHandle() { return m_handle; } public UUID GetHostID() { return m_hostID; } public UUID GetID() { return m_id; } public UUID GetItemID() { return m_itemID; } public uint GetLocalID() { return m_localID; } public string GetMessage() { return m_message; } public string GetName() { return m_name; } public Object[] GetSerializationData() { Object[] data = new Object[7]; data[0] = m_active; data[1] = m_handle; data[2] = m_channel; data[3] = m_name; data[4] = m_id; data[5] = m_message; data[6] = RegexBitfield; return data; } public bool IsActive() { return m_active; } private void Initialise(int handle, uint localID, UUID ItemID, UUID hostID, int channel, string name, UUID id, string message, int regexBitfield) { m_active = true; m_handle = handle; m_localID = localID; m_itemID = ItemID; m_hostID = hostID; m_channel = channel; m_name = name; m_id = id; m_message = message; RegexBitfield = regexBitfield; } } public class ListenerManager { private int m_curlisteners; private Dictionary<int, List<ListenerInfo>> m_listeners = new Dictionary<int, List<ListenerInfo>>(); private ReaderWriterLock m_ListenerRwLock = new ReaderWriterLock(); private int m_maxhandles; private int m_maxlisteners; public ListenerManager(int maxlisteners, int maxhandles) { m_maxlisteners = maxlisteners; m_maxhandles = maxhandles; m_curlisteners = 0; } /// <summary> /// Total number of listeners /// </summary> public int ListenerCount { get { m_ListenerRwLock.AcquireReaderLock(-1); try { return m_listeners.Count; } finally { m_ListenerRwLock.ReleaseReaderLock(); } } } public void Activate(UUID itemID, int handle) { m_ListenerRwLock.AcquireReaderLock(-1); try { foreach (KeyValuePair<int, List<ListenerInfo>> lis in m_listeners) { foreach (ListenerInfo li in lis.Value) { if (li.GetItemID().Equals(itemID) && li.GetHandle() == handle) { li.Activate(); // only one, bail out return; } } } } finally { m_ListenerRwLock.ReleaseReaderLock(); } } public void AddFromData(uint localID, UUID itemID, UUID hostID, Object[] data) { int idx = 0; Object[] item = new Object[6]; int dataItemLength = 6; while (idx < data.Length) { dataItemLength = (idx + 7 == data.Length || (idx + 7 < data.Length && data[idx + 7] is bool)) ? 7 : 6; item = new Object[dataItemLength]; Array.Copy(data, idx, item, 0, dataItemLength); ListenerInfo info = ListenerInfo.FromData(localID, itemID, hostID, item); m_ListenerRwLock.AcquireWriterLock(-1); try { if (!m_listeners.ContainsKey((int)item[2])) { m_listeners.Add((int)item[2], new List<ListenerInfo>()); } m_listeners[(int)item[2]].Add(info); } finally { m_ListenerRwLock.ReleaseWriterLock(); } idx += dataItemLength; } } public int AddListener(uint localID, UUID itemID, UUID hostID, int channel, string name, UUID id, string msg) { return AddListener(localID, itemID, hostID, channel, name, id, msg, 0); } public int AddListener(uint localID, UUID itemID, UUID hostID, int channel, string name, UUID id, string msg, int regexBitfield) { // do we already have a match on this particular filter event? List<ListenerInfo> coll = GetListeners(itemID, channel, name, id, msg); if (coll.Count > 0) { // special case, called with same filter settings, return same // handle (2008-05-02, tested on 1.21.1 server, still holds) return coll[0].GetHandle(); } if (m_curlisteners < m_maxlisteners) { m_ListenerRwLock.AcquireWriterLock(-1); try { int newHandle = GetNewHandle(itemID); if (newHandle > 0) { ListenerInfo li = new ListenerInfo(newHandle, localID, itemID, hostID, channel, name, id, msg, regexBitfield); List<ListenerInfo> listeners; if (!m_listeners.TryGetValue( channel, out listeners)) { listeners = new List<ListenerInfo>(); m_listeners.Add(channel, listeners); } listeners.Add(li); m_curlisteners++; return newHandle; } } finally { m_ListenerRwLock.ReleaseWriterLock(); } } return -1; } public void Dectivate(UUID itemID, int handle) { m_ListenerRwLock.AcquireReaderLock(-1); try { foreach (KeyValuePair<int, List<ListenerInfo>> lis in m_listeners) { foreach (ListenerInfo li in lis.Value) { if (li.GetItemID().Equals(itemID) && li.GetHandle() == handle) { li.Deactivate(); // only one, bail out return; } } } } finally { m_ListenerRwLock.ReleaseReaderLock(); } } public void DeleteListener(UUID itemID) { List<int> emptyChannels = new List<int>(); List<ListenerInfo> removedListeners = new List<ListenerInfo>(); m_ListenerRwLock.AcquireWriterLock(-1); try { foreach (KeyValuePair<int, List<ListenerInfo>> lis in m_listeners) { foreach (ListenerInfo li in lis.Value) { if (li.GetItemID().Equals(itemID)) { // store them first, else the enumerated bails on // us removedListeners.Add(li); } } foreach (ListenerInfo li in removedListeners) { lis.Value.Remove(li); m_curlisteners--; } removedListeners.Clear(); if (lis.Value.Count == 0) { // again, store first, remove later emptyChannels.Add(lis.Key); } } foreach (int channel in emptyChannels) { m_listeners.Remove(channel); } } finally { m_ListenerRwLock.ReleaseWriterLock(); } } /// <summary> /// Get listeners matching the input parameters. /// </summary> /// <remarks> /// Theres probably a more clever and efficient way to do this, maybe /// with regex. /// PM2008: Ha, one could even be smart and define a specialized /// Enumerator. /// </remarks> /// <param name="itemID"></param> /// <param name="channel"></param> /// <param name="name"></param> /// <param name="id"></param> /// <param name="msg"></param> /// <returns></returns> public List<ListenerInfo> GetListeners(UUID itemID, int channel, string name, UUID id, string msg) { List<ListenerInfo> collection = new List<ListenerInfo>(); m_ListenerRwLock.AcquireReaderLock(-1); try { List<ListenerInfo> listeners; if (!m_listeners.TryGetValue(channel, out listeners)) { return collection; } foreach (ListenerInfo li in listeners) { if (!li.IsActive()) { continue; } if (!itemID.Equals(UUID.Zero) && !li.GetItemID().Equals(itemID)) { continue; } if (li.GetName().Length > 0 && ( ((li.RegexBitfield & OS_LISTEN_REGEX_NAME) != OS_LISTEN_REGEX_NAME && !li.GetName().Equals(name)) || ((li.RegexBitfield & OS_LISTEN_REGEX_NAME) == OS_LISTEN_REGEX_NAME && !Regex.IsMatch(name, li.GetName())) )) { continue; } if (!li.GetID().Equals(UUID.Zero) && !li.GetID().Equals(id)) { continue; } if (li.GetMessage().Length > 0 && ( ((li.RegexBitfield & OS_LISTEN_REGEX_MESSAGE) != OS_LISTEN_REGEX_MESSAGE && !li.GetMessage().Equals(msg)) || ((li.RegexBitfield & OS_LISTEN_REGEX_MESSAGE) == OS_LISTEN_REGEX_MESSAGE && !Regex.IsMatch(msg, li.GetMessage())) )) { continue; } collection.Add(li); } } finally { m_ListenerRwLock.ReleaseReaderLock(); } return collection; } public Object[] GetSerializationData(UUID itemID) { List<Object> data = new List<Object>(); m_ListenerRwLock.AcquireReaderLock(-1); try { foreach (List<ListenerInfo> list in m_listeners.Values) { foreach (ListenerInfo l in list) { if (l.GetItemID() == itemID) data.AddRange(l.GetSerializationData()); } } } finally { m_ListenerRwLock.ReleaseReaderLock(); } return (Object[])data.ToArray(); } public void Remove(UUID itemID, int handle) { m_ListenerRwLock.AcquireWriterLock(-1); try { foreach (KeyValuePair<int, List<ListenerInfo>> lis in m_listeners) { foreach (ListenerInfo li in lis.Value) { if (li.GetItemID().Equals(itemID) && li.GetHandle().Equals(handle)) { lis.Value.Remove(li); if (lis.Value.Count == 0) { m_listeners.Remove(lis.Key); m_curlisteners--; } // there should be only one, so we bail out early return; } } } } finally { m_ListenerRwLock.ReleaseWriterLock(); } } /// <summary> /// non-locked access, since its always called in the context of the /// lock /// </summary> /// <param name="itemID"></param> /// <returns></returns> private int GetNewHandle(UUID itemID) { List<int> handles = new List<int>(); // build a list of used keys for this specific itemID... foreach (KeyValuePair<int, List<ListenerInfo>> lis in m_listeners) { foreach (ListenerInfo li in lis.Value) { if (li.GetItemID().Equals(itemID)) handles.Add(li.GetHandle()); } } // Note: 0 is NOT a valid handle for llListen() to return for (int i = 1; i <= m_maxhandles; i++) { if (!handles.Contains(i)) return i; } return -1; } /// These are duplicated from ScriptBaseClass /// http://opensimulator.org/mantis/view.php?id=6106#c21945 #region Constants for the bitfield parameter of osListenRegex /// <summary> /// process message parameter as regex /// </summary> public const int OS_LISTEN_REGEX_MESSAGE = 0x2; /// <summary> /// process name parameter as regex /// </summary> public const int OS_LISTEN_REGEX_NAME = 0x1; #endregion Constants for the bitfield parameter of osListenRegex } [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "WorldCommModule")] public class WorldCommModule : IWorldComm, INonSharedRegionModule { // private static readonly ILog m_log = // LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private ListenerManager m_listenerManager; private Queue m_pending; private Queue m_pendingQ; private int m_saydistance = 20; private Scene m_scene; private int m_shoutdistance = 100; private int m_whisperdistance = 10; #region INonSharedRegionModule Members public string Name { get { return "WorldCommModule"; } } public Type ReplaceableInterface { get { return null; } } public void AddRegion(Scene scene) { m_scene = scene; m_scene.RegisterModuleInterface<IWorldComm>(this); m_scene.EventManager.OnChatFromClient += DeliverClientMessage; m_scene.EventManager.OnChatBroadcast += DeliverClientMessage; } public void Close() { } public void Initialise(IConfigSource config) { // wrap this in a try block so that defaults will work if // the config file doesn't specify otherwise. int maxlisteners = 1000; int maxhandles = 64; try { m_whisperdistance = config.Configs["Chat"].GetInt( "whisper_distance", m_whisperdistance); m_saydistance = config.Configs["Chat"].GetInt( "say_distance", m_saydistance); m_shoutdistance = config.Configs["Chat"].GetInt( "shout_distance", m_shoutdistance); maxlisteners = config.Configs["LL-Functions"].GetInt( "max_listens_per_region", maxlisteners); maxhandles = config.Configs["LL-Functions"].GetInt( "max_listens_per_script", maxhandles); } catch (Exception) { } if (maxlisteners < 1) maxlisteners = int.MaxValue; if (maxhandles < 1) maxhandles = int.MaxValue; m_listenerManager = new ListenerManager(maxlisteners, maxhandles); m_pendingQ = new Queue(); m_pending = Queue.Synchronized(m_pendingQ); } public void PostInitialise() { } public void RegionLoaded(Scene scene) { } public void RemoveRegion(Scene scene) { if (scene != m_scene) return; m_scene.UnregisterModuleInterface<IWorldComm>(this); m_scene.EventManager.OnChatBroadcast -= DeliverClientMessage; m_scene.EventManager.OnChatBroadcast -= DeliverClientMessage; } #endregion INonSharedRegionModule Members #region IWorldComm Members protected static Vector3 CenterOfRegion = new Vector3(128, 128, 20); public int ListenerCount { get { return m_listenerManager.ListenerCount; } } /// <summary> /// Removes all listen event callbacks for the given itemID /// (script engine) /// </summary> /// <param name="itemID">UUID of the script engine</param> public void DeleteListener(UUID itemID) { m_listenerManager.DeleteListener(itemID); } public void DeliverMessage(ChatTypeEnum type, int channel, string name, UUID id, string msg) { Vector3 position; SceneObjectPart source; ScenePresence avatar; if ((source = m_scene.GetSceneObjectPart(id)) != null) position = source.AbsolutePosition; else if ((avatar = m_scene.GetScenePresence(id)) != null) position = avatar.AbsolutePosition; else if (ChatTypeEnum.Region == type) position = CenterOfRegion; else return; DeliverMessage(type, channel, name, id, msg, position); } /// <summary> /// This method scans over the objects which registered an interest in listen callbacks. /// For everyone it finds, it checks if it fits the given filter. If it does, then /// enqueue the message for delivery to the objects listen event handler. /// The enqueued ListenerInfo no longer has filter values, but the actually trigged values. /// Objects that do an llSay have their messages delivered here and for nearby avatars, /// the OnChatFromClient event is used. /// </summary> /// <param name="type">type of delvery (whisper,say,shout or regionwide)</param> /// <param name="channel">channel to sent on</param> /// <param name="name">name of sender (object or avatar)</param> /// <param name="id">key of sender (object or avatar)</param> /// <param name="msg">msg to sent</param> public void DeliverMessage(ChatTypeEnum type, int channel, string name, UUID id, string msg, Vector3 position) { // m_log.DebugFormat("[WorldComm] got[2] type {0}, channel {1}, name {2}, id {3}, msg {4}", // type, channel, name, id, msg); // Determine which listen event filters match the given set of arguments, this results // in a limited set of listeners, each belonging a host. If the host is in range, add them // to the pending queue. foreach (ListenerInfo li in m_listenerManager.GetListeners(UUID.Zero, channel, name, id, msg)) { // Dont process if this message is from yourself! if (li.GetHostID().Equals(id)) continue; SceneObjectPart sPart = m_scene.GetSceneObjectPart( li.GetHostID()); if (sPart == null) continue; double dis = Util.GetDistanceTo(sPart.AbsolutePosition, position); switch (type) { case ChatTypeEnum.Whisper: if (dis < m_whisperdistance) QueueMessage(new ListenerInfo(li, name, id, msg)); break; case ChatTypeEnum.Say: if (dis < m_saydistance) QueueMessage(new ListenerInfo(li, name, id, msg)); break; case ChatTypeEnum.Shout: if (dis < m_shoutdistance) QueueMessage(new ListenerInfo(li, name, id, msg)); break; case ChatTypeEnum.Region: QueueMessage(new ListenerInfo(li, name, id, msg)); break; } } } /// <summary> /// Delivers the message to a scene entity. /// </summary> /// <param name='target'> /// Target. /// </param> /// <param name='channel'> /// Channel. /// </param> /// <param name='name'> /// Name. /// </param> /// <param name='id'> /// Identifier. /// </param> /// <param name='msg'> /// Message. /// </param> public void DeliverMessageTo(UUID target, int channel, Vector3 pos, string name, UUID id, string msg) { // Is id an avatar? ScenePresence sp = m_scene.GetScenePresence(target); if (sp != null) { // ignore if a child agent this is restricted to inside one // region if (sp.IsChildAgent) return; // Send message to the avatar. // Channel zero only goes to the avatar // non zero channel messages only go to the attachments if (channel == 0) { m_scene.SimChatToAgent(target, Utils.StringToBytes(msg), pos, name, id, false); } else { List<SceneObjectGroup> attachments = sp.GetAttachments(); if (attachments.Count == 0) return; // Get uuid of attachments List<UUID> targets = new List<UUID>(); foreach (SceneObjectGroup sog in attachments) { if (!sog.IsDeleted) targets.Add(sog.UUID); } // Need to check each attachment foreach (ListenerInfo li in m_listenerManager.GetListeners(UUID.Zero, channel, name, id, msg)) { if (li.GetHostID().Equals(id)) continue; if (m_scene.GetSceneObjectPart( li.GetHostID()) == null) { continue; } if (targets.Contains(li.GetHostID())) QueueMessage(new ListenerInfo(li, name, id, msg)); } } return; } // No avatar found so look for an object foreach (ListenerInfo li in m_listenerManager.GetListeners(UUID.Zero, channel, name, id, msg)) { // Dont process if this message is from yourself! if (li.GetHostID().Equals(id)) continue; SceneObjectPart sPart = m_scene.GetSceneObjectPart( li.GetHostID()); if (sPart == null) continue; if (li.GetHostID().Equals(target)) { QueueMessage(new ListenerInfo(li, name, id, msg)); break; } } return; } /// <summary> /// Pop the first availlable listen event from the queue /// </summary> /// <returns>ListenerInfo with filter filled in</returns> public IWorldCommListenerInfo GetNextMessage() { ListenerInfo li = null; lock (m_pending.SyncRoot) { li = (ListenerInfo)m_pending.Dequeue(); } return li; } /// <summary> /// Are there any listen events ready to be dispatched? /// </summary> /// <returns>boolean indication</returns> public bool HasMessages() { return (m_pending.Count > 0); } /// <summary> /// Create a listen event callback with the specified filters. /// The parameters localID,itemID are needed to uniquely identify /// the script during 'peek' time. Parameter hostID is needed to /// determine the position of the script. /// </summary> /// <param name="localID">localID of the script engine</param> /// <param name="itemID">UUID of the script engine</param> /// <param name="hostID">UUID of the SceneObjectPart</param> /// <param name="channel">channel to listen on</param> /// <param name="name">name to filter on</param> /// <param name="id"> /// key to filter on (user given, could be totally faked) /// </param> /// <param name="msg">msg to filter on</param> /// <returns>number of the scripts handle</returns> public int Listen(uint localID, UUID itemID, UUID hostID, int channel, string name, UUID id, string msg) { return m_listenerManager.AddListener(localID, itemID, hostID, channel, name, id, msg); } /// <summary> /// Create a listen event callback with the specified filters. /// The parameters localID,itemID are needed to uniquely identify /// the script during 'peek' time. Parameter hostID is needed to /// determine the position of the script. /// </summary> /// <param name="localID">localID of the script engine</param> /// <param name="itemID">UUID of the script engine</param> /// <param name="hostID">UUID of the SceneObjectPart</param> /// <param name="channel">channel to listen on</param> /// <param name="name">name to filter on</param> /// <param name="id"> /// key to filter on (user given, could be totally faked) /// </param> /// <param name="msg">msg to filter on</param> /// <param name="regexBitfield"> /// Bitfield indicating which strings should be processed as regex. /// </param> /// <returns>number of the scripts handle</returns> public int Listen(uint localID, UUID itemID, UUID hostID, int channel, string name, UUID id, string msg, int regexBitfield) { return m_listenerManager.AddListener(localID, itemID, hostID, channel, name, id, msg, regexBitfield); } /// <summary> /// Sets the listen event with handle as active (active = TRUE) or inactive (active = FALSE). /// The handle used is returned from Listen() /// </summary> /// <param name="itemID">UUID of the script engine</param> /// <param name="handle">handle returned by Listen()</param> /// <param name="active">temp. activate or deactivate the Listen()</param> public void ListenControl(UUID itemID, int handle, int active) { if (active == 1) m_listenerManager.Activate(itemID, handle); else if (active == 0) m_listenerManager.Dectivate(itemID, handle); } /// <summary> /// Removes the listen event callback with handle /// </summary> /// <param name="itemID">UUID of the script engine</param> /// <param name="handle">handle returned by Listen()</param> public void ListenRemove(UUID itemID, int handle) { m_listenerManager.Remove(itemID, handle); } protected void QueueMessage(ListenerInfo li) { lock (m_pending.SyncRoot) { m_pending.Enqueue(li); } } #endregion IWorldComm Members /******************************************************************** * * Listener Stuff * * *****************************************************************/ public void CreateFromData(uint localID, UUID itemID, UUID hostID, Object[] data) { m_listenerManager.AddFromData(localID, itemID, hostID, data); } public Object[] GetSerializationData(UUID itemID) { return m_listenerManager.GetSerializationData(itemID); } private void DeliverClientMessage(Object sender, OSChatMessage e) { if (null != e.Sender) { DeliverMessage(e.Type, e.Channel, e.Sender.Name, e.Sender.AgentId, e.Message, e.Position); } else { DeliverMessage(e.Type, e.Channel, e.From, UUID.Zero, e.Message, e.Position); } } } }
//------------------------------------------------------------------------------ // <copyright file="DeviceSpecificDesigner.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Web.UI.Design.MobileControls { using System; using System.Collections; using System.ComponentModel; using System.ComponentModel.Design; using System.Globalization; using System.Diagnostics; using System.IO; using System.Text; using System.Web.UI; using System.Web.UI.Design; using System.Web.UI.Design.MobileControls.Adapters; using System.Web.UI.Design.MobileControls.Util; using System.Web.UI.MobileControls; using System.Windows.Forms; [ System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand, Flags=System.Security.Permissions.SecurityPermissionFlag.UnmanagedCode) ] [Obsolete("The System.Web.Mobile.dll assembly has been deprecated and should no longer be used. For information about how to develop ASP.NET mobile applications, see http://go.microsoft.com/fwlink/?LinkId=157231.")] internal class DeviceSpecificDesigner : MobileTemplatedControlDesigner, IDeviceSpecificDesigner { internal static BooleanSwitch DeviceSpecificDesignerSwitch = new BooleanSwitch("DeviceSpecificDesigner", "Enable DeviceSpecific designer general purpose traces."); private DeviceSpecific _ds; private bool _isDuplicate; private System.Web.UI.MobileControls.Panel _parentContainer; internal static readonly String _strictlyFormPanelContainmentErrorMessage = SR.GetString(SR.MobileControl_StrictlyFormPanelContainmentErrorMessage); private const String _designTimeHTML = @" <table cellpadding=4 cellspacing=0 width='100%' style='font-family:tahoma;font-size:8pt;color:buttontext;background-color:buttonface;border: solid 1px;border-top-color:buttonhighlight;border-left-color:buttonhighlight;border-bottom-color:buttonshadow;border-right-color:buttonshadow'> <tr><td colspan=2><span style='font-weight:bold'>DeviceSpecific</span> - {0}</td></tr> <tr><td style='padding-top:0;padding-bottom:0;width:55%;padding-left:10px;font-weight:bold'>Template Device Filter:</td><td style='padding-top:0;padding-bottom:0'>{1}</td></tr> <tr><td colspan=2 style='padding-top:4px'>{2}</td></tr> </table> "; private const String _duplicateDesignTimeHTML = @" <table cellpadding=4 cellspacing=0 width='100%' style='font-family:tahoma;font-size:8pt;color:buttontext;background-color:buttonface;border: solid 1px;border-top-color:buttonhighlight;border-left-color:buttonhighlight;border-bottom-color:buttonshadow;border-right-color:buttonshadow'> <tr><td colspan=2><span style='font-weight:bold'>DeviceSpecific</span> - {0}</td></tr> <tr><td style='padding-top:0;padding-bottom:0;width:55%;padding-left:10px;font-weight:bold'>Template Device Filter:</td><td colspan=2 style='padding-top:0;padding-bottom:0'>{1}</td></tr> <tr><td colspan=2 style='padding-top:4px'>{2}</td></tr> <tr><td colspan=2> <table style='font-size:8pt;color:window;background-color:ButtonShadow'> <tr><td valign='top'><img src='{3}'/></td><td>{4}</td></tr> </table> </td></tr> </table> "; private const String _propertyOverridesPropName = "PropertyOverrides"; private const String _dataBindingsPropName = "DataBindings"; private const int _headerFooterTemplates = 0; private const int _contentTemplate = 0; private bool FormDeviceSpecific { get { Debug.Assert(_parentContainer != null); return _parentContainer is System.Web.UI.MobileControls.Form; } } private static readonly String[] _templateFramesForForm = new String [] { Constants.HeaderTemplateTag, Constants.FooterTemplateTag }; private static readonly String[] _templateFramesForPanel = new String [] { Constants.ContentTemplateTag }; protected override void Dispose(bool disposing) { if (disposing) { ParentContainerInvalid(); } base.Dispose(disposing); } protected override TemplateEditingVerb[] GetCachedTemplateEditingVerbs() { if (_isDuplicate) { return null; } return base.GetCachedTemplateEditingVerbs(); } private void ParentContainerInvalid() { // MessageBox.Show("ParentContainerInvalid call"); if (null != _parentContainer && _ds == _parentContainer.DeviceSpecific) { _parentContainer.DeviceSpecific = null; // container's enabled deviceSpecific control is deleted. // another disabled deviceSpecific child may need to be enabled. foreach (System.Web.UI.Control control in _parentContainer.Controls) { if (control is DeviceSpecific && control != _ds) { // found a valid candidate DeviceSpecific newDS = (DeviceSpecific) control; if (newDS.Site != null) { IDesignerHost host = (IDesignerHost) newDS.Site.GetService(typeof(IDesignerHost)); Debug.Assert(host != null, "host is null in DeviceSpecificDesigner"); IDesigner designer = host.GetDesigner((IComponent) newDS); // this designer could be null if the page is disposing the controls (Page.Dispose). if (designer != null) { _parentContainer.DeviceSpecific = newDS; DeviceSpecificDesigner dsd = (DeviceSpecificDesigner) designer; dsd.TreatAsDuplicate(false); break; } } } } } } public override void Initialize(IComponent component) { Debug.Assert(component is System.Web.UI.MobileControls.DeviceSpecific, "DeviceSpecificControlDesigner.Initialize - Invalid DeviceSpecific Control"); _ds = (System.Web.UI.MobileControls.DeviceSpecific) component; base.Initialize(component); _isDuplicate = false; } public override DeviceSpecific CurrentDeviceSpecific { get { Debug.Assert(null != _ds); return _ds; } } protected override String GetDesignTimeNormalHtml() { String curChoice, message; bool _isNonHtmlSchema = false; if (null == CurrentChoice) { curChoice = SR.GetString(SR.DeviceSpecific_PropNotSet); message = SR.GetString(SR.DeviceSpecific_DefaultMessage); } else { if (CurrentChoice.Filter.Length == 0) { curChoice = SR.GetString(SR.DeviceFilter_DefaultChoice); } else { curChoice = HttpUtility.HtmlEncode(DesignerUtility.ChoiceToUniqueIdentifier(CurrentChoice)); } if (IsHTMLSchema(CurrentChoice)) { message = SR.GetString(SR.DeviceSpecific_TemplateEditingMessage); } else { _isNonHtmlSchema = true; message = SR.GetString(SR.DeviceSpecific_DefaultMessage); } } if (_isDuplicate || _isNonHtmlSchema) { return String.Format(CultureInfo.CurrentCulture, _duplicateDesignTimeHTML, new Object[] { _ds.Site.Name, curChoice, message, _isDuplicate ? MobileControlDesigner.errorIcon : MobileControlDesigner.infoIcon, _isDuplicate ? SR.GetString(SR.DeviceSpecific_DuplicateWarningMessage) : SR.GetString(SR.MobileControl_NonHtmlSchemaErrorMessage) }); } else { return String.Format(CultureInfo.CurrentCulture, _designTimeHTML, _ds.Site.Name, curChoice, message); } } private bool ValidContainment { get { return (ContainmentStatus == ContainmentStatus.InForm || ContainmentStatus == ContainmentStatus.InPanel); } } protected override String GetErrorMessage(out bool infoMode) { infoMode = false; if (!DesignerAdapterUtil.InMobileUserControl(_ds)) { if (DesignerAdapterUtil.InUserControl(_ds)) { infoMode = true; return MobileControlDesigner._userControlWarningMessage; } if (!DesignerAdapterUtil.InMobilePage(_ds)) { return MobileControlDesigner._mobilePageErrorMessage; } } if (!ValidContainment) { return _strictlyFormPanelContainmentErrorMessage; } // No error condition, return null; return null; } internal void TreatAsDuplicate(bool isDuplicate) { if (isDuplicate != _isDuplicate) { _isDuplicate = isDuplicate; SetTemplateVerbsDirty(); // MessageBox.Show("TreatAsDuplicate: Changing status of " + _ds.Site.Name + " to _isDuplicate=" + _isDuplicate.ToString()); } UpdateDesignTimeHtml(); } public override void OnSetParent() { // MessageBox.Show("OnSetParent call for _ds.Site.Name=" + _ds.Site.Name + ", _ds.ID=" + _ds.ID); base.OnSetParent(); Debug.Assert(_ds.Parent != null, "_ds.Parent is null"); if (null != _parentContainer) { ParentContainerInvalid(); } System.Web.UI.Control parentContainer = _ds.Parent; if (parentContainer is System.Web.UI.MobileControls.Panel) { _parentContainer = (System.Web.UI.MobileControls.Panel) parentContainer; _ds.SetOwner(_parentContainer); if (null != _parentContainer.DeviceSpecific && 0 != String.Compare(_ds.ID, _parentContainer.DeviceSpecific.ID, StringComparison.OrdinalIgnoreCase)) { // the parent container already has a deviceSpecific child. // this instance is a duplicate and needs to update its rendering. // MessageBox.Show("OnSetParent - this instance is a duplicate"); TreatAsDuplicate(true); // the current valid DeviceSpecific is intentionaly refreshed because // if this deviceSpecific instance is recreated via a Undo operation // the current valid DeviceSpecific appears as a duplicate if not refreshed. IDesignerHost host = (IDesignerHost) GetService(typeof(IDesignerHost)); Debug.Assert(host != null, "Did not get a valid IDesignerHost reference"); IDesigner designer = host.GetDesigner((IComponent) _parentContainer.DeviceSpecific); Debug.Assert(designer != null, "designer is null in DeviceSpecificDesigner"); DeviceSpecificDesigner dsd = (DeviceSpecificDesigner) designer; dsd.UpdateRendering(); } else { // MessageBox.Show("OnSetParent - this instance becomes the valid ds"); _parentContainer.DeviceSpecific = _ds; if (_isDuplicate) { TreatAsDuplicate(false); } } } else { _parentContainer = null; } // Invalidate the type descriptor so that the PropertyOverrides // property browsable status gets updated TypeDescriptor.Refresh(Component); } protected override String[] GetTemplateFrameNames(int index) { Debug.Assert(index == 0); return FormDeviceSpecific ? _templateFramesForForm : _templateFramesForPanel; } protected override void PreFilterProperties(IDictionary properties) { base.PreFilterProperties(properties); PropertyDescriptor prop = (PropertyDescriptor)properties[_propertyOverridesPropName]; Debug.Assert(prop != null); properties[_propertyOverridesPropName] = TypeDescriptor.CreateProperty( GetType(), prop, InTemplateMode || _parentContainer == null? BrowsableAttribute.No : BrowsableAttribute.Yes); } protected override TemplateEditingVerb[] GetTemplateVerbs() { TemplateEditingVerb[] templateVerbs = new TemplateEditingVerb[1]; if (FormDeviceSpecific) { templateVerbs[0] = new TemplateEditingVerb( SR.GetString(SR.TemplateFrame_HeaderFooterTemplates), _headerFooterTemplates, this); } else { templateVerbs[0] = new TemplateEditingVerb( SR.GetString(SR.TemplateFrame_ContentTemplate), _contentTemplate, this); } return templateVerbs; } //////////////////////////////////////////////////////////////////////// // Begin IDeviceSpecificDesigner Implementation //////////////////////////////////////////////////////////////////////// Object IDeviceSpecificDesigner.UnderlyingObject { get { return _parentContainer == null ? (Object)_ds : _parentContainer; } } //////////////////////////////////////////////////////////////////////// // End IDeviceSpecificDesigner Implementation //////////////////////////////////////////////////////////////////////// } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using System.Collections.Generic; using System.Runtime.CompilerServices; namespace Internal.TypeSystem { /// <summary> /// Represents the fundamental base type of all types within the type system. /// </summary> public abstract partial class TypeDesc : TypeSystemEntity { public static readonly TypeDesc[] EmptyTypes = new TypeDesc[0]; /// Inherited types are required to override, and should use the algorithms /// in TypeHashingAlgorithms in their implementation. public abstract override int GetHashCode(); public override bool Equals(Object o) { // Its only valid to compare two TypeDescs in the same context Debug.Assert(o == null || !(o is TypeDesc) || Object.ReferenceEquals(((TypeDesc)o).Context, this.Context)); return Object.ReferenceEquals(this, o); } #if DEBUG public static bool operator ==(TypeDesc left, TypeDesc right) { // Its only valid to compare two TypeDescs in the same context Debug.Assert(Object.ReferenceEquals(left, null) || Object.ReferenceEquals(right, null) || Object.ReferenceEquals(left.Context, right.Context)); return Object.ReferenceEquals(left, right); } public static bool operator !=(TypeDesc left, TypeDesc right) { // Its only valid to compare two TypeDescs in the same context Debug.Assert(Object.ReferenceEquals(left, null) || Object.ReferenceEquals(right, null) || Object.ReferenceEquals(left.Context, right.Context)); return !Object.ReferenceEquals(left, right); } #endif // The most frequently used type properties are cached here to avoid excesive virtual calls private TypeFlags _typeFlags; /// <summary> /// Gets the generic instantiation information of this type. /// For generic definitions, retrieves the generic parameters of the type. /// For generic instantiation, retrieves the generic arguments of the type. /// </summary> public virtual Instantiation Instantiation { get { return Instantiation.Empty; } } /// <summary> /// Gets a value indicating whether this type has a generic instantiation. /// This will be true for generic type instantiations and generic definitions. /// </summary> public bool HasInstantiation { get { return this.Instantiation.Length != 0; } } internal void SetWellKnownType(WellKnownType wellKnownType) { TypeFlags flags; switch (wellKnownType) { case WellKnownType.Void: case WellKnownType.Boolean: case WellKnownType.Char: case WellKnownType.SByte: case WellKnownType.Byte: case WellKnownType.Int16: case WellKnownType.UInt16: case WellKnownType.Int32: case WellKnownType.UInt32: case WellKnownType.Int64: case WellKnownType.UInt64: case WellKnownType.IntPtr: case WellKnownType.UIntPtr: case WellKnownType.Single: case WellKnownType.Double: flags = (TypeFlags)wellKnownType; break; case WellKnownType.ValueType: case WellKnownType.Enum: flags = TypeFlags.Class; break; case WellKnownType.Nullable: flags = TypeFlags.Nullable; break; case WellKnownType.Object: case WellKnownType.String: case WellKnownType.Array: case WellKnownType.MulticastDelegate: case WellKnownType.Exception: flags = TypeFlags.Class; break; case WellKnownType.RuntimeTypeHandle: case WellKnownType.RuntimeMethodHandle: case WellKnownType.RuntimeFieldHandle: case WellKnownType.TypedReference: case WellKnownType.ByReferenceOfT: flags = TypeFlags.ValueType; break; default: throw new ArgumentException(); } _typeFlags = flags; } protected abstract TypeFlags ComputeTypeFlags(TypeFlags mask); [MethodImpl(MethodImplOptions.NoInlining)] private TypeFlags InitializeTypeFlags(TypeFlags mask) { TypeFlags flags = ComputeTypeFlags(mask); if ((flags & mask) == 0) flags = Context.ComputeTypeFlags(this, flags, mask); Debug.Assert((flags & mask) != 0); _typeFlags |= flags; return flags & mask; } [MethodImpl(MethodImplOptions.AggressiveInlining)] protected internal TypeFlags GetTypeFlags(TypeFlags mask) { TypeFlags flags = _typeFlags & mask; if (flags != 0) return flags; return InitializeTypeFlags(mask); } /// <summary> /// Retrieves the category of the type. This is one of the possible values of /// <see cref="TypeFlags"/> less than <see cref="TypeFlags.CategoryMask"/>. /// </summary> public TypeFlags Category { get { return GetTypeFlags(TypeFlags.CategoryMask); } } /// <summary> /// Gets a value indicating whether this type is an interface type. /// </summary> public bool IsInterface { get { return GetTypeFlags(TypeFlags.CategoryMask) == TypeFlags.Interface; } } /// <summary> /// Gets a value indicating whether this type is a value type (not a reference type). /// </summary> public bool IsValueType { get { return GetTypeFlags(TypeFlags.CategoryMask) < TypeFlags.Class; } } /// <summary> /// Gets a value indicating whether this is one of the primitive types (boolean, char, void, /// a floating point, or an integer type). /// </summary> public bool IsPrimitive { get { return GetTypeFlags(TypeFlags.CategoryMask) < TypeFlags.ValueType; } } /// <summary> /// Gets a value indicating whether this is an enum type. /// Access <see cref="UnderlyingType"/> to retrieve the underlying integral type. /// </summary> public bool IsEnum { get { return GetTypeFlags(TypeFlags.CategoryMask) == TypeFlags.Enum; } } /// <summary> /// Gets a value indicating whether this is a delegate type. /// </summary> public bool IsDelegate { get { var baseType = this.BaseType; return (baseType != null) ? baseType.IsWellKnownType(WellKnownType.MulticastDelegate) : false; } } /// <summary> /// Gets a value indicating whether this is System.Void type. /// </summary> public bool IsVoid { get { return GetTypeFlags(TypeFlags.CategoryMask) == TypeFlags.Void; } } /// <summary> /// Gets a value indicating whether this is System.String type. /// </summary> public bool IsString { get { return this.IsWellKnownType(WellKnownType.String); } } /// <summary> /// Gets a value indicating whether this is System.Object type. /// </summary> public bool IsObject { get { return this.IsWellKnownType(WellKnownType.Object); } } /// <summary> /// Gets a value indicating whether this is a generic definition, or /// an instance of System.Nullable`1. /// </summary> public bool IsNullable { get { return this.GetTypeDefinition().IsWellKnownType(WellKnownType.Nullable); } } /// <summary> /// Gets a value indicating whether this is a generic definition, or /// an instance of System.ByReference`1. /// </summary> public bool IsByReferenceOfT { get { return this.GetTypeDefinition().IsWellKnownType(WellKnownType.ByReferenceOfT); } } /// <summary> /// Gets a value indicating whether this is an array type (<see cref="ArrayType"/>). /// Note this will return true for both multidimensional array types and vector types. /// Use <see cref="IsSzArray"/> to check for vector types. /// </summary> public bool IsArray { get { return this is ArrayType; } } /// <summary> /// Gets a value indicating whether this is a vector type. A vector is a single-dimensional /// array with a zero lower bound. To check for arrays in general, use <see cref="IsArray"/>. /// </summary> public bool IsSzArray { get { return this.IsArray && ((ArrayType)this).IsSzArray; } } /// <summary> /// Gets a value indicating whether this is a non-vector array type. /// To check for arrays in general, use <see cref="IsArray"/>. /// </summary> public bool IsMdArray { get { return this.IsArray && ((ArrayType)this).IsMdArray; } } /// <summary> /// Gets a value indicating whether this is a managed pointer type (<see cref="ByRefType"/>). /// </summary> public bool IsByRef { get { return this is ByRefType; } } /// <summary> /// Gets a value indicating whether this is an unmanaged pointer type (<see cref="PointerType"/>). /// </summary> public bool IsPointer { get { return this is PointerType; } } /// <summary> /// Gets a value indicating whether this is an unmanaged function pointer type (<see cref="FunctionPointerType"/>). /// </summary> public bool IsFunctionPointer { get { return this is FunctionPointerType; } } /// <summary> /// Gets a value indicating whether this is a <see cref="SignatureTypeVariable"/> or <see cref="SignatureMethodVariable"/>. /// </summary> public bool IsSignatureVariable { get { return this is SignatureTypeVariable || this is SignatureMethodVariable; } } /// <summary> /// Gets a value indicating whether this is a generic parameter (<see cref="GenericParameterDesc"/>). /// </summary> public bool IsGenericParameter { get { return GetTypeFlags(TypeFlags.CategoryMask) == TypeFlags.GenericParameter; } } /// <summary> /// Gets a value indicating whether this is a pointer, byref, array, or szarray type, /// and can be used as a ParameterizedType. /// </summary> public bool IsParameterizedType { get { TypeFlags flags = GetTypeFlags(TypeFlags.CategoryMask); Debug.Assert((flags >= TypeFlags.Array && flags <= TypeFlags.Pointer) == (this is ParameterizedType)); return (flags >= TypeFlags.Array && flags <= TypeFlags.Pointer); } } /// <summary> /// Gets a value indicating whether this is a class, an interface, a value type, or a /// generic instance of one of them. /// </summary> public bool IsDefType { get { Debug.Assert(GetTypeFlags(TypeFlags.CategoryMask) <= TypeFlags.Interface == this is DefType); return GetTypeFlags(TypeFlags.CategoryMask) <= TypeFlags.Interface; } } /// <summary> /// Gets a value indicating whether locations of this type refer to an object on the GC heap. /// </summary> public bool IsGCPointer { get { TypeFlags category = GetTypeFlags(TypeFlags.CategoryMask); return category == TypeFlags.Class || category == TypeFlags.Array || category == TypeFlags.SzArray || category == TypeFlags.Interface; } } /// <summary> /// Gets the type from which this type derives from, or null if there's no such type. /// </summary> public virtual DefType BaseType { get { return null; } } /// <summary> /// Gets a value indicating whether this type has a base type. /// </summary> public bool HasBaseType { get { return BaseType != null; } } /// <summary> /// If this is an enum type, gets the underlying integral type of the enum type. /// For all other types, returns 'this'. /// </summary> public virtual TypeDesc UnderlyingType { get { if (!this.IsEnum) return this; // TODO: Cache the result? foreach (var field in this.GetFields()) { if (!field.IsStatic) return field.FieldType; } ThrowHelper.ThrowTypeLoadException(ExceptionStringID.ClassLoadGeneral, this); return null; // Unreachable } } /// <summary> /// Gets a value indicating whether this type has a class constructor method. /// Use <see cref="GetStaticConstructor"/> to retrieve it. /// </summary> public bool HasStaticConstructor { get { return (GetTypeFlags(TypeFlags.HasStaticConstructor | TypeFlags.HasStaticConstructorComputed) & TypeFlags.HasStaticConstructor) != 0; } } /// <summary> /// Gets all methods on this type defined within the type's metadata. /// This will not include methods injected by the type system context. /// </summary> public virtual IEnumerable<MethodDesc> GetMethods() { return MethodDesc.EmptyMethods; } /// <summary> /// Gets a named method on the type. This method only looks at methods defined /// in type's metadata. The <paramref name="signature"/> parameter can be null. /// If signature is not specified and there are multiple matches, the first one /// is returned. Returns null if method not found. /// </summary> // TODO: Substitutions, generics, modopts, ... public virtual MethodDesc GetMethod(string name, MethodSignature signature) { foreach (var method in GetMethods()) { if (method.Name == name) { if (signature == null || signature.Equals(method.Signature)) return method; } } return null; } /// <summary> /// Retrieves the class constructor method of this type. /// </summary> /// <returns></returns> public virtual MethodDesc GetStaticConstructor() { return null; } /// <summary> /// Retrieves the public parameterless constructor method of the type, or null if there isn't one /// or the type is abstract. /// </summary> public virtual MethodDesc GetDefaultConstructor() { return null; } /// <summary> /// Gets all fields on the type as defined in the metadata. /// </summary> public virtual IEnumerable<FieldDesc> GetFields() { return FieldDesc.EmptyFields; } /// <summary> /// Gets a named field on the type. Returns null if the field wasn't found. /// </summary> // TODO: Substitutions, generics, modopts, ... // TODO: field signature public virtual FieldDesc GetField(string name) { foreach (var field in GetFields()) { if (field.Name == name) return field; } return null; } public virtual TypeDesc InstantiateSignature(Instantiation typeInstantiation, Instantiation methodInstantiation) { return this; } /// <summary> /// Gets the definition of the type. If this is a generic type instance, /// this method strips the instantiation (E.g C&lt;int&gt; -> C&lt;T&gt;) /// </summary> public virtual TypeDesc GetTypeDefinition() { return this; } /// <summary> /// Gets a value indicating whether this is a type definition. Returns false /// if this is an instantiated generic type. /// </summary> public bool IsTypeDefinition { get { return GetTypeDefinition() == this; } } /// <summary> /// Determine if two types share the same type definition /// </summary> public bool HasSameTypeDefinition(TypeDesc otherType) { return GetTypeDefinition() == otherType.GetTypeDefinition(); } /// <summary> /// Gets a value indicating whether this type has a finalizer method. /// Use <see cref="GetFinalizer"/> to retrieve the method. /// </summary> public bool HasFinalizer { get { return (GetTypeFlags(TypeFlags.HasFinalizer | TypeFlags.HasFinalizerComputed) & TypeFlags.HasFinalizer) != 0; } } /// <summary> /// Gets the finalizer method (an override of the System.Object::Finalize method) /// if this type has one. Returns null if the type doesn't define one. /// </summary> public virtual MethodDesc GetFinalizer() { return null; } /// <summary> /// Gets a value indicating whether this type has generic variance (the definition of the type /// has a generic parameter that is co- or contravariant). /// </summary> public bool HasVariance { get { return (GetTypeFlags(TypeFlags.HasGenericVariance | TypeFlags.HasGenericVarianceComputed) & TypeFlags.HasGenericVariance) != 0; } } /// <summary> /// Gets a value indicating whether this type is an uninstantiated definition of a generic type. /// </summary> public bool IsGenericDefinition { get { return HasInstantiation && IsTypeDefinition; } } } }
// 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 System.Reflection; using System.Runtime; using Internal.Metadata.NativeFormat; using Internal.Runtime.Augments; using Internal.TypeSystem; using Internal.Reflection.Execution; using Internal.Reflection.Core; using Internal.Runtime.TypeLoader; using AssemblyFlags = Internal.Metadata.NativeFormat.AssemblyFlags; namespace Internal.TypeSystem.NativeFormat { /// <summary> /// Represent a NativeFormat metadata file. These files can contain multiple logical ECMA metadata style assemblies. /// </summary> public sealed class NativeFormatMetadataUnit { private NativeFormatModuleInfo _module; private MetadataReader _metadataReader; private TypeSystemContext _context; internal interface IHandleObject { Handle Handle { get; } NativeFormatType Container { get; } } private sealed class NativeFormatObjectLookupWrapper : IHandleObject { private Handle _handle; private object _obj; private NativeFormatType _container; public NativeFormatObjectLookupWrapper(Handle handle, object obj, NativeFormatType container) { _obj = obj; _handle = handle; _container = container; } public Handle Handle { get { return _handle; } } public object Object { get { return _obj; } } public NativeFormatType Container { get { return _container; } } } internal struct NativeFormatObjectKey { private Handle _handle; private NativeFormatType _container; public NativeFormatObjectKey(Handle handle, NativeFormatType container) { _handle = handle; _container = container; } public Handle Handle { get { return _handle; } } public NativeFormatType Container { get { return _container; } } } internal class NativeFormatObjectLookupHashtable : LockFreeReaderHashtable<NativeFormatObjectKey, IHandleObject> { private NativeFormatMetadataUnit _metadataUnit; private MetadataReader _metadataReader; public NativeFormatObjectLookupHashtable(NativeFormatMetadataUnit metadataUnit, MetadataReader metadataReader) { _metadataUnit = metadataUnit; _metadataReader = metadataReader; } protected override int GetKeyHashCode(NativeFormatObjectKey key) { int hashcode = key.Handle.GetHashCode(); if (key.Container != null) { // Todo: Use a better hash combining function hashcode ^= key.Container.GetHashCode(); } return hashcode; } protected override int GetValueHashCode(IHandleObject value) { int hashcode = value.Handle.GetHashCode(); if (value.Container != null) { // Todo: Use a better hash combining function hashcode ^= value.Container.GetHashCode(); } return hashcode; } protected override bool CompareKeyToValue(NativeFormatObjectKey key, IHandleObject value) { return key.Handle.Equals(value.Handle) && Object.ReferenceEquals(key.Container, value.Container); } protected override bool CompareValueToValue(IHandleObject value1, IHandleObject value2) { if (Object.ReferenceEquals(value1, value2)) return true; else return value1.Handle.Equals(value2.Handle) && Object.ReferenceEquals(value1.Container, value2.Container); } protected override IHandleObject CreateValueFromKey(NativeFormatObjectKey key) { Handle handle = key.Handle; NativeFormatType container = key.Container; object item; switch (handle.HandleType) { case HandleType.TypeDefinition: item = new NativeFormatType(_metadataUnit, handle.ToTypeDefinitionHandle(_metadataReader)); break; case HandleType.Method: item = new NativeFormatMethod(container, handle.ToMethodHandle(_metadataReader)); break; case HandleType.Field: item = new NativeFormatField(container, handle.ToFieldHandle(_metadataReader)); break; case HandleType.TypeReference: item = _metadataUnit.ResolveTypeReference(handle.ToTypeReferenceHandle(_metadataReader)); break; case HandleType.MemberReference: item = _metadataUnit.ResolveMemberReference(handle.ToMemberReferenceHandle(_metadataReader)); break; case HandleType.QualifiedMethod: item = _metadataUnit.ResolveQualifiedMethod(handle.ToQualifiedMethodHandle(_metadataReader)); break; case HandleType.QualifiedField: item = _metadataUnit.ResolveQualifiedField(handle.ToQualifiedFieldHandle(_metadataReader)); break; case HandleType.ScopeReference: item = _metadataUnit.ResolveAssemblyReference(handle.ToScopeReferenceHandle(_metadataReader)); break; case HandleType.ScopeDefinition: { ScopeDefinition scope = handle.ToScopeDefinitionHandle(_metadataReader).GetScopeDefinition(_metadataReader); item = _metadataUnit.GetModuleFromAssemblyName(scope.Name.GetConstantStringValue(_metadataReader).Value); } break; case HandleType.TypeSpecification: case HandleType.TypeInstantiationSignature: case HandleType.SZArraySignature: case HandleType.ArraySignature: case HandleType.PointerSignature: case HandleType.ByReferenceSignature: case HandleType.TypeVariableSignature: case HandleType.MethodTypeVariableSignature: { NativeFormatSignatureParser parser = new NativeFormatSignatureParser(_metadataUnit, handle, _metadataReader); item = parser.ParseTypeSignature(); } break; case HandleType.MethodInstantiation: item = _metadataUnit.ResolveMethodInstantiation(handle.ToMethodInstantiationHandle(_metadataReader)); break; // TODO: Resolve other tokens default: throw new BadImageFormatException("Unknown metadata token type: " + handle.HandleType); } switch (handle.HandleType) { case HandleType.TypeDefinition: case HandleType.Field: case HandleType.Method: // type/method/field definitions directly correspond to their target item. return (IHandleObject)item; default: // Everything else is some form of reference which cannot be self-describing return new NativeFormatObjectLookupWrapper(handle, item, container); } } } private NativeFormatObjectLookupHashtable _resolvedTokens; public NativeFormatMetadataUnit(TypeSystemContext context, NativeFormatModuleInfo module, MetadataReader metadataReader) { _module = module; _metadataReader = metadataReader; _context = context; _resolvedTokens = new NativeFormatObjectLookupHashtable(this, _metadataReader); } public MetadataReader MetadataReader { get { return _metadataReader; } } public TypeSystemContext Context { get { return _context; } } public TypeManagerHandle RuntimeModule { get { return _module.Handle; } } public NativeFormatModuleInfo RuntimeModuleInfo { get { return _module; } } public TypeDesc GetType(Handle handle) { TypeDesc type = GetObject(handle, null) as TypeDesc; if (type == null) throw new BadImageFormatException("Type expected"); return type; } public MethodDesc GetMethod(Handle handle, NativeFormatType type) { MethodDesc method = GetObject(handle, type) as MethodDesc; if (method == null) throw new BadImageFormatException("Method expected"); return method; } public FieldDesc GetField(Handle handle, NativeFormatType type) { FieldDesc field = GetObject(handle, type) as FieldDesc; if (field == null) throw new BadImageFormatException("Field expected"); return field; } public ModuleDesc GetModule(ScopeReferenceHandle scopeHandle) { return (ModuleDesc)GetObject(scopeHandle, null); } public NativeFormatModule GetModule(ScopeDefinitionHandle scopeHandle) { return (NativeFormatModule)GetObject(scopeHandle, null); } public Object GetObject(Handle handle, NativeFormatType type) { IHandleObject obj = _resolvedTokens.GetOrCreateValue(new NativeFormatObjectKey(handle, type)); if (obj is NativeFormatObjectLookupWrapper) { return ((NativeFormatObjectLookupWrapper)obj).Object; } else { return obj; } } private Object ResolveMethodInstantiation(MethodInstantiationHandle handle) { MethodInstantiation methodInstantiation = _metadataReader.GetMethodInstantiation(handle); MethodDesc genericMethodDef = (MethodDesc)GetObject(methodInstantiation.Method, null); ArrayBuilder<TypeDesc> instantiation = new ArrayBuilder<TypeDesc>(); foreach (Handle genericArgHandle in methodInstantiation.GenericTypeArguments) { instantiation.Add(GetType(genericArgHandle)); } return Context.GetInstantiatedMethod(genericMethodDef, new Instantiation(instantiation.ToArray())); } private Object ResolveQualifiedMethod(QualifiedMethodHandle handle) { QualifiedMethod qualifiedMethod = _metadataReader.GetQualifiedMethod(handle); NativeFormatType enclosingType = (NativeFormatType)GetType(qualifiedMethod.EnclosingType); return GetMethod(qualifiedMethod.Method, enclosingType); } private Object ResolveQualifiedField(QualifiedFieldHandle handle) { QualifiedField qualifiedField = _metadataReader.GetQualifiedField(handle); NativeFormatType enclosingType = (NativeFormatType)GetType(qualifiedField.EnclosingType); return GetField(qualifiedField.Field, enclosingType); } private Object ResolveMemberReference(MemberReferenceHandle handle) { MemberReference memberReference = _metadataReader.GetMemberReference(handle); TypeDesc parent = GetType(memberReference.Parent); TypeDesc parentTypeDesc = parent as TypeDesc; if (parentTypeDesc != null) { NativeFormatSignatureParser parser = new NativeFormatSignatureParser(this, memberReference.Signature, _metadataReader); string name = _metadataReader.GetString(memberReference.Name); if (parser.IsFieldSignature) { FieldDesc field = parentTypeDesc.GetField(name); if (field != null) return field; // TODO: Better error message throw new MissingMemberException("Field not found " + parent.ToString() + "." + name); } else { MethodSignature sig = parser.ParseMethodSignature(); TypeDesc typeDescToInspect = parentTypeDesc; // Try to resolve the name and signature in the current type, or any of the base types. do { // TODO: handle substitutions MethodDesc method = typeDescToInspect.GetMethod(name, sig); if (method != null) { // If this resolved to one of the base types, make sure it's not a constructor. // Instance constructors are not inherited. if (typeDescToInspect != parentTypeDesc && method.IsConstructor) break; return method; } typeDescToInspect = typeDescToInspect.BaseType; } while (typeDescToInspect != null); // TODO: Better error message throw new MissingMemberException("Method not found " + parent.ToString() + "." + name); } } throw new BadImageFormatException(); } private DefType ResolveTypeReference(TypeReferenceHandle handle) { TypeReference typeReference = _metadataReader.GetTypeReference(handle); if (typeReference.ParentNamespaceOrType.HandleType == HandleType.TypeReference) { // Nested type case MetadataType containingType = (MetadataType)ResolveTypeReference(typeReference.ParentNamespaceOrType.ToTypeReferenceHandle(_metadataReader)); return containingType.GetNestedType(_metadataReader.GetString(typeReference.TypeName)); } else { // Cross-assembly reference // Get remote module, and then lookup by namespace/name ScopeReferenceHandle scopeReferenceHandle = default(ScopeReferenceHandle); NamespaceReferenceHandle initialNamespaceReferenceHandle = typeReference.ParentNamespaceOrType.ToNamespaceReferenceHandle(_metadataReader); NamespaceReferenceHandle namespaceReferenceHandle = initialNamespaceReferenceHandle; do { NamespaceReference namespaceReference = _metadataReader.GetNamespaceReference(namespaceReferenceHandle); if (namespaceReference.ParentScopeOrNamespace.HandleType == HandleType.ScopeReference) { scopeReferenceHandle = namespaceReference.ParentScopeOrNamespace.ToScopeReferenceHandle(_metadataReader); } else { namespaceReferenceHandle = namespaceReference.ParentScopeOrNamespace.ToNamespaceReferenceHandle(_metadataReader); } } while (scopeReferenceHandle.IsNull(_metadataReader)); ModuleDesc remoteModule = GetModule(scopeReferenceHandle); string namespaceName = _metadataReader.GetNamespaceName(initialNamespaceReferenceHandle); string typeName = _metadataReader.GetString(typeReference.TypeName); MetadataType resolvedType = remoteModule.GetType(namespaceName, typeName, throwIfNotFound: false); if (resolvedType != null) { return resolvedType; } // Special handling for the magic __Canon types cannot be currently put into // NativeFormatModule because GetType returns a MetadataType. if (remoteModule == _context.SystemModule) { string qualifiedTypeName = namespaceName + "." + typeName; if (qualifiedTypeName == CanonType.FullName) { return _context.CanonType; } if (qualifiedTypeName == UniversalCanonType.FullName) { return _context.UniversalCanonType; } } throw new NotImplementedException(); } } private Object ResolveAssemblyReference(ScopeReferenceHandle handle) { ScopeReference assemblyReference = _metadataReader.GetScopeReference(handle); AssemblyName an = new AssemblyName(); an.Name = _metadataReader.GetString(assemblyReference.Name); an.Version = new Version(assemblyReference.MajorVersion, assemblyReference.MinorVersion, assemblyReference.BuildNumber, assemblyReference.RevisionNumber); an.CultureName = _metadataReader.GetString(assemblyReference.Culture) ?? ""; var publicKeyOrToken = assemblyReference.PublicKeyOrToken.ConvertByteCollectionToArray(); if ((assemblyReference.Flags & AssemblyFlags.PublicKey) != 0) { an.SetPublicKey(publicKeyOrToken); } else { an.SetPublicKeyToken(publicKeyOrToken); } // TODO: ContentType - depends on newer version of the System.Reflection contract return Context.ResolveAssembly(an); } public NativeFormatModule GetModuleFromNamespaceDefinition(NamespaceDefinitionHandle handle) { while (true) { NamespaceDefinition namespaceDef = _metadataReader.GetNamespaceDefinition(handle); Handle parentScopeOrDefinitionHandle = namespaceDef.ParentScopeOrNamespace; if (parentScopeOrDefinitionHandle.HandleType == HandleType.ScopeDefinition) { return (NativeFormatModule)GetObject(parentScopeOrDefinitionHandle, null); } else { handle = parentScopeOrDefinitionHandle.ToNamespaceDefinitionHandle(_metadataReader); } } } public NativeFormatModule GetModuleFromAssemblyName(string assemblyNameString) { AssemblyBindResult bindResult; RuntimeAssemblyName assemblyName = AssemblyNameParser.Parse(assemblyNameString); Exception failureException; if (!AssemblyBinderImplementation.Instance.Bind(assemblyName, cacheMissedLookups: true, out bindResult, out failureException)) { throw failureException; } var moduleList = Internal.Runtime.TypeLoader.ModuleList.Instance; NativeFormatModuleInfo primaryModule = moduleList.GetModuleInfoForMetadataReader(bindResult.Reader); // If this isn't the primary module, defer to that module to load the MetadataUnit if (primaryModule != _module) { return Context.ResolveMetadataUnit(primaryModule).GetModule(bindResult.ScopeDefinitionHandle); } // Setup arguments and allocate the NativeFormatModule ArrayBuilder<NativeFormatModule.QualifiedScopeDefinition> qualifiedScopes = new ArrayBuilder<NativeFormatModule.QualifiedScopeDefinition>(); qualifiedScopes.Add(new NativeFormatModule.QualifiedScopeDefinition(this, bindResult.ScopeDefinitionHandle)); foreach (QScopeDefinition scope in bindResult.OverflowScopes) { NativeFormatModuleInfo module = moduleList.GetModuleInfoForMetadataReader(scope.Reader); ScopeDefinitionHandle scopeHandle = scope.Handle; NativeFormatMetadataUnit metadataUnit = Context.ResolveMetadataUnit(module); qualifiedScopes.Add(new NativeFormatModule.QualifiedScopeDefinition(metadataUnit, scopeHandle)); } return new NativeFormatModule(Context, qualifiedScopes.ToArray()); } } }
// // PathBar.cs // // Author: // Michael Hutchinson <mhutchinson@novell.com> // // Copyright (c) 2010 Novell, Inc. (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using System.Collections.Generic; using System.Linq; using Gtk; using Gdk; using Pinta.Docking; using Pinta.Docking.Gui; namespace MonoDevelop.Components { enum EntryPosition { Left, Right } class PathEntry { Gdk.Pixbuf darkIcon; public Gdk.Pixbuf Icon { get; private set; } public string Markup { get; private set; } public object Tag { get; set; } public bool IsPathEnd { get; set; } public EntryPosition Position { get; set; } public PathEntry (Gdk.Pixbuf icon, string markup) { this.Icon = icon; this.Markup = markup; } public PathEntry (string markup) { this.Markup = markup; } public override bool Equals (object obj) { if (obj == null) return false; if (ReferenceEquals (this, obj)) return true; if (obj.GetType () != typeof(PathEntry)) return false; MonoDevelop.Components.PathEntry other = (MonoDevelop.Components.PathEntry)obj; return Icon == other.Icon && Markup == other.Markup; } public override int GetHashCode () { unchecked { return (Icon != null ? Icon.GetHashCode () : 0) ^ (Markup != null ? Markup.GetHashCode () : 0); } } internal Gdk.Pixbuf DarkIcon { get { if (darkIcon == null && Icon != null) { darkIcon = Icon; /* if (Styles.BreadcrumbGreyscaleIcons) darkIcon = ImageService.MakeGrayscale (darkIcon); if (Styles.BreadcrumbInvertedIcons) darkIcon = ImageService.MakeInverted (darkIcon);*/ } return darkIcon; } } } class PathBar : Gtk.DrawingArea { PathEntry[] leftPath = new PathEntry[0]; PathEntry[] rightPath = new PathEntry[0]; Pango.Layout layout; Pango.AttrList boldAtts = new Pango.AttrList (); const char CR = (char)0x0D; const char LF = (char)0x0A; //HACK: a surrogate widget object to pass to style calls instead of "this" when using "button" hint. // This avoids GTK-Criticals in themes which try to cast the widget object to a button. Gtk.Button styleButton = new Gtk.Button (); // The widths array contains the widths of the items at the left and the right int[] widths; int height; int textHeight; bool pressed, hovering, menuVisible; int hoverIndex = -1; int activeIndex = -1; const int leftPadding = 6; const int rightPadding = 6; const int topPadding = 2; const int bottomPadding = 4; const int iconSpacing = 4; const int padding = 3; const int buttonPadding = 2; const int arrowLeftPadding = 10; const int arrowRightPadding = 10; const int arrowSize = 6; const int spacing = arrowLeftPadding + arrowRightPadding + arrowSize; const int minRegionSelectorWidth = 30; Func<int, Widget> createMenuForItem; Widget menuWidget; public PathBar (Func<int, Widget> createMenuForItem) { this.Events = EventMask.ExposureMask | EventMask.EnterNotifyMask | EventMask.LeaveNotifyMask | EventMask.ButtonPressMask | EventMask.ButtonReleaseMask | EventMask.KeyPressMask | EventMask.PointerMotionMask; boldAtts.Insert (new Pango.AttrWeight (Pango.Weight.Bold)); this.createMenuForItem = createMenuForItem; EnsureLayout (); } internal static string GetFirstLineFromMarkup (string markup) { var idx = markup.IndexOfAny (new [] { CR, LF }); if (idx >= 0) return markup.Substring (0, idx); return markup; } public new PathEntry[] Path { get; private set; } public int ActiveIndex { get { return activeIndex; } } public void SetPath (PathEntry[] path) { if (ArrSame (this.leftPath, path)) return; HideMenu (); this.Path = path ?? new PathEntry[0]; this.leftPath = Path.Where (p => p.Position == EntryPosition.Left).ToArray (); this.rightPath = Path.Where (p => p.Position == EntryPosition.Right).ToArray (); activeIndex = -1; widths = null; EnsureWidths (); QueueResize (); } bool ArrSame (PathEntry[] a, PathEntry[] b) { if ((a == null || b == null) && a != b) return false; if (a.Length != b.Length) return false; for (int i = 0; i < a.Length; i++) if (!a[i].Equals(b[i])) return false; return true; } public void SetActive (int index) { if (index >= leftPath.Length) throw new IndexOutOfRangeException (); if (activeIndex != index) { activeIndex = index; widths = null; QueueResize (); } } protected override void OnSizeRequested (ref Requisition requisition) { EnsureWidths (); requisition.Width = Math.Max (WidthRequest, 0); requisition.Height = height + topPadding + bottomPadding; } int[] GetCurrentWidths (out bool widthReduced) { int totalWidth = widths.Sum (); totalWidth += leftPadding + (arrowSize + arrowRightPadding) * leftPath.Length - 1; totalWidth += rightPadding + arrowSize * rightPath.Length - 1; int[] currentWidths = widths; widthReduced = false; int overflow = totalWidth - Allocation.Width; if (overflow > 0) { currentWidths = ReduceWidths (overflow); widthReduced = true; } return currentWidths; } protected override bool OnExposeEvent (EventExpose evnt) { using (var ctx = Gdk.CairoHelper.Create (GdkWindow)) { ctx.Rectangle (0, 0, Allocation.Width, Allocation.Height); using (var g = new Cairo.LinearGradient (0, 0, 0, Allocation.Height)) { g.AddColorStop (0, Styles.BreadcrumbBackgroundColor); g.AddColorStop (1, Styles.BreadcrumbGradientEndColor); ctx.SetSource (g); } ctx.Fill (); if (widths == null) return true; // Calculate the total required with, and the reduction to be applied in case it doesn't fit the available space bool widthReduced; var currentWidths = GetCurrentWidths (out widthReduced); // Render the paths int textTopPadding = topPadding + (height - textHeight) / 2; int xpos = leftPadding, ypos = topPadding; for (int i = 0; i < leftPath.Length; i++) { bool last = i == leftPath.Length - 1; // Reduce the item size when required int itemWidth = currentWidths [i]; int x = xpos; xpos += itemWidth; if (hoverIndex >= 0 && hoverIndex < Path.Length && leftPath [i] == Path [hoverIndex] && (menuVisible || pressed || hovering)) DrawButtonBorder (ctx, x - padding, itemWidth + padding + padding); int textOffset = 0; if (leftPath [i].DarkIcon != null) { int iy = (height - (int)leftPath [i].DarkIcon.Height) / 2 + topPadding; ctx.DrawImage (this, leftPath [i].DarkIcon, x, iy); textOffset += (int) leftPath [i].DarkIcon.Width + iconSpacing; } layout.Attributes = (i == activeIndex) ? boldAtts : null; layout.SetMarkup (GetFirstLineFromMarkup (leftPath [i].Markup)); ctx.Save (); // If size is being reduced, ellipsize it bool showText = true; if (widthReduced) { int w = itemWidth - textOffset; if (w > 0) { ctx.Rectangle (x + textOffset, textTopPadding, w, height); ctx.Clip (); } else showText = false; } else layout.Width = -1; if (showText) { // Text ctx.SetSourceColor (Styles.BreadcrumbTextColor.ToCairoColor ()); ctx.MoveTo (x + textOffset, textTopPadding); Pango.CairoHelper.ShowLayout (ctx, layout); } ctx.Restore (); if (!last) { xpos += arrowLeftPadding; if (leftPath [i].IsPathEnd) { Style.PaintVline (Style, GdkWindow, State, evnt.Area, this, "", ypos, ypos + height, xpos - arrowSize / 2); } else { int arrowH = Math.Min (height, arrowSize); int arrowY = ypos + (height - arrowH) / 2; DrawPathSeparator (ctx, xpos, arrowY, arrowH); } xpos += arrowSize + arrowRightPadding; } } int xposRight = Allocation.Width - rightPadding; for (int i = 0; i < rightPath.Length; i++) { // bool last = i == rightPath.Length - 1; // Reduce the item size when required int itemWidth = currentWidths [i + leftPath.Length]; xposRight -= itemWidth; xposRight -= arrowSize; int x = xposRight; if (hoverIndex >= 0 && hoverIndex < Path.Length && rightPath [i] == Path [hoverIndex] && (menuVisible || pressed || hovering)) DrawButtonBorder (ctx, x - padding, itemWidth + padding + padding); int textOffset = 0; if (rightPath [i].DarkIcon != null) { ctx.DrawImage (this, rightPath [i].DarkIcon, x, ypos); textOffset += (int) rightPath [i].DarkIcon.Width + padding; } layout.Attributes = (i == activeIndex) ? boldAtts : null; layout.SetMarkup (GetFirstLineFromMarkup (rightPath [i].Markup)); ctx.Save (); // If size is being reduced, ellipsize it bool showText = true; if (widthReduced) { int w = itemWidth - textOffset; if (w > 0) { ctx.Rectangle (x + textOffset, textTopPadding, w, height); ctx.Clip (); } else showText = false; } else layout.Width = -1; if (showText) { // Text ctx.SetSourceColor (Styles.BreadcrumbTextColor.ToCairoColor ()); ctx.MoveTo (x + textOffset, textTopPadding); Pango.CairoHelper.ShowLayout (ctx, layout); } ctx.Restore (); } ctx.MoveTo (0, Allocation.Height - 0.5); ctx.RelLineTo (Allocation.Width, 0); ctx.SetSourceColor (Styles.BreadcrumbBottomBorderColor); ctx.LineWidth = 1; ctx.Stroke (); } return true; } void DrawPathSeparator (Cairo.Context ctx, double x, double y, double size) { ctx.MoveTo (x, y); ctx.LineTo (x + arrowSize, y + size / 2); ctx.LineTo (x, y + size); ctx.ClosePath (); ctx.SetSourceColor (CairoExtensions.ColorShade (Style.Dark (State).ToCairoColor (), 0.6)); ctx.Fill (); } void DrawButtonBorder (Cairo.Context ctx, double x, double width) { x -= buttonPadding; width += buttonPadding; double y = topPadding - buttonPadding; double height = Allocation.Height - topPadding - bottomPadding + buttonPadding * 2; ctx.Rectangle (x, y, width, height); ctx.SetSourceColor (Styles.BreadcrumbButtonFillColor); ctx.Fill (); ctx.Rectangle (x + 0.5, y + 0.5, width - 1, height - 1); ctx.SetSourceColor (Styles.BreadcrumbButtonBorderColor); ctx.LineWidth = 1; ctx.Stroke (); } int[] ReduceWidths (int overflow) { int minItemWidth = 30; int[] currentWidths = new int[widths.Length]; Array.Copy (widths, currentWidths, widths.Length); int itemsToShrink = widths.Count (i => i > minItemWidth); while (overflow > 0 && itemsToShrink > 0) { int itemSizeReduction = overflow / itemsToShrink; if (itemSizeReduction == 0) itemSizeReduction = 1; int reduced = 0; for (int n = 0; n < widths.Length && reduced < overflow; n++) { if (currentWidths [n] > minItemWidth) { var nw = currentWidths [n] - itemSizeReduction; if (nw <= minItemWidth) { nw = minItemWidth; itemsToShrink--; } reduced += currentWidths [n] - nw; currentWidths [n] = nw; } } overflow -= reduced; } return currentWidths; } protected override bool OnButtonPressEvent (EventButton evnt) { HideMenu (); if (hovering) { pressed = true; QueueDraw (); } return true; } protected override bool OnButtonReleaseEvent (EventButton evnt) { pressed = false; if (hovering) { QueueDraw (); ShowMenu (); } return true; } void ShowMenu () { if (hoverIndex < 0) return; HideMenu (); menuWidget = createMenuForItem (hoverIndex); if (menuWidget == null) return; menuWidget.Hidden += delegate { menuVisible = false; QueueDraw (); //FIXME: for some reason the menu's children don't get activated if we destroy //directly here, so use a timeout to delay it GLib.Timeout.Add (100, delegate { HideMenu (); return false; }); }; menuVisible = true; if (menuWidget is Menu) { ((Menu)menuWidget).Popup (null, null, PositionFunc, 0, Gtk.Global.CurrentEventTime); } else { PositionWidget (menuWidget); menuWidget.ShowAll (); } } public void HideMenu () { if (menuWidget != null) { menuWidget.Destroy (); menuWidget = null; } } public int GetHoverXPosition (out int w) { bool widthReduced; int[] currentWidths = GetCurrentWidths (out widthReduced); if (Path[hoverIndex].Position == EntryPosition.Left) { int idx = leftPath.TakeWhile (p => p != Path[hoverIndex]).Count (); if (idx >= 0) { w = currentWidths[idx]; return currentWidths.Take (idx).Sum () + idx * spacing; } } else { int idx = rightPath.TakeWhile (p => p != Path[hoverIndex]).Count (); if (idx >= 0) { w = currentWidths[idx + leftPath.Length]; return Allocation.Width - padding - currentWidths[idx + leftPath.Length] - spacing; } } w = Allocation.Width; return 0; } void PositionWidget (Gtk.Widget widget) { if (!(widget is Gtk.Window)) return; int ox, oy; ParentWindow.GetOrigin (out ox, out oy); int w; int itemXPosition = GetHoverXPosition (out w); int dx = ox + this.Allocation.X + itemXPosition; int dy = oy + this.Allocation.Bottom; var req = widget.SizeRequest (); Gdk.Rectangle geometry = GtkWorkarounds.GetUsableMonitorGeometry (Screen, Screen.GetMonitorAtPoint (dx, dy)); int width = System.Math.Max (req.Width, w); if (width >= geometry.Width - spacing * 2) { width = geometry.Width - spacing * 2; dx = geometry.Left + spacing; } widget.WidthRequest = width; if (dy + req.Height > geometry.Bottom) dy = oy + this.Allocation.Y - req.Height; if (dx + width > geometry.Right) dx = geometry.Right - width; (widget as Gtk.Window).Move (dx, dy); (widget as Gtk.Window).Resize (width, req.Height); widget.GrabFocus (); } void PositionFunc (Menu mn, out int x, out int y, out bool push_in) { this.GdkWindow.GetOrigin (out x, out y); int w; var rect = this.Allocation; y += rect.Height; x += GetHoverXPosition (out w); //if the menu would be off the bottom of the screen, "drop" it upwards if (y + mn.Requisition.Height > this.Screen.Height) { y -= mn.Requisition.Height; y -= rect.Height; } //let GTK reposition the button if it still doesn't fit on the screen push_in = true; } protected override bool OnMotionNotifyEvent (EventMotion evnt) { SetHover (GetItemAt ((int)evnt.X, (int)evnt.Y)); return true; } protected override bool OnLeaveNotifyEvent (EventCrossing evnt) { pressed = false; SetHover (-1); return true; } protected override bool OnEnterNotifyEvent (EventCrossing evnt) { SetHover (GetItemAt ((int)evnt.X, (int)evnt.Y)); return true; } void SetHover (int i) { bool oldHovering = hovering; hovering = i > -1; if (hoverIndex != i || oldHovering != hovering) { if (hovering) hoverIndex = i; QueueDraw (); } } public int IndexOf (PathEntry entry) { return Path.TakeWhile (p => p != entry).Count (); } int GetItemAt (int x, int y) { int xpos = padding, xposRight = Allocation.Width - padding; if (widths == null || x < xpos || x > xposRight) return -1; bool widthReduced; int[] currentWidths = GetCurrentWidths (out widthReduced); for (int i = 0; i < rightPath.Length; i++) { xposRight -= currentWidths[i + leftPath.Length] + spacing; if (x > xposRight) return IndexOf (rightPath[i]); } for (int i = 0; i < leftPath.Length; i++) { xpos += currentWidths[i] + spacing; if (x < xpos) return IndexOf (leftPath[i]); } return -1; } void EnsureLayout () { if (layout != null) layout.Dispose (); layout = new Pango.Layout (PangoContext); } void CreateWidthArray (int[] result, int index, PathEntry[] path) { // Assume that there will be icons of at least 16 pixels. This avoids // annoying path bar height changes when switching between empty and full paths int maxIconHeight = 16; for (int i = 0; i < path.Length; i++) { layout.Attributes = (i == activeIndex)? boldAtts : null; layout.SetMarkup (GetFirstLineFromMarkup (path[i].Markup)); layout.Width = -1; int w, h; layout.GetPixelSize (out w, out h); textHeight = Math.Max (h, textHeight); if (path[i].DarkIcon != null) { maxIconHeight = Math.Max ((int)path[i].DarkIcon.Height, maxIconHeight); w += (int)path[i].DarkIcon.Width + iconSpacing; } result[i + index] = w; } height = Math.Max (height, maxIconHeight); height = Math.Max (height, textHeight); } void EnsureWidths () { if (widths != null) return; layout.SetText ("#"); int w; layout.GetPixelSize (out w, out this.height); textHeight = height; widths = new int [leftPath.Length + rightPath.Length]; CreateWidthArray (widths, 0, leftPath); CreateWidthArray (widths, leftPath.Length, rightPath); } protected override void OnStyleSet (Style previous) { base.OnStyleSet (previous); KillLayout (); EnsureLayout (); } void KillLayout () { if (layout == null) return; layout.Dispose (); layout = null; boldAtts.Dispose (); widths = null; } public override void Destroy () { base.Destroy (); styleButton.Destroy (); KillLayout (); this.boldAtts.Dispose (); } } }
using System; using System.Collections.Generic; using System.Linq; using Microsoft.TemplateEngine.Orchestrator.RunnableProjects.ValueForms; using Microsoft.TemplateEngine.TestHelper; using Newtonsoft.Json.Linq; using Xunit; namespace Microsoft.TemplateEngine.Orchestrator.RunnableProjects.UnitTests.TemplateConfigTests { public class SymbolConfigTests : TestBase { // Test that when a config doesn't include a name parameter, one gets added - with the proper value forms. [Fact(DisplayName = nameof(NameSymbolGetsAddedWithDefaultValueForms))] public void NameSymbolGetsAddedWithDefaultValueForms() { SimpleConfigModel configModel = SimpleConfigModel.FromJObject(EngineEnvironmentSettings, ArrayConfigForSymbolWithFormsButNotIdentity); Assert.True(configModel.Symbols.ContainsKey("name")); ISymbolModel symbolInfo = configModel.Symbols["name"]; Assert.True(symbolInfo is ParameterSymbol); ParameterSymbol nameSymbol = symbolInfo as ParameterSymbol; IList<string> configuredValueFormNames = nameSymbol.Forms.GlobalForms.ToList(); Assert.Equal(5, configuredValueFormNames.Count); Assert.Equal(IdentityValueForm.FormName, configuredValueFormNames[0]); Assert.Equal(DefaultSafeNameValueFormModel.FormName, configuredValueFormNames[1]); Assert.Equal(DefaultLowerSafeNameValueFormModel.FormName, configuredValueFormNames[2]); Assert.Equal(DefaultSafeNamespaceValueFormModel.FormName, configuredValueFormNames[3]); Assert.Equal(DefaultLowerSafeNamespaceValueFormModel.FormName, configuredValueFormNames[4]); } // Test that when a symbol doens't explicitly include the "identity" value form, it gets added as the first form. [Fact(DisplayName = nameof(ParameterSymbolWithoutIdentityValueFormGetsIdentityAddedAsFirst))] public void ParameterSymbolWithoutIdentityValueFormGetsIdentityAddedAsFirst() { SimpleConfigModel configModel = SimpleConfigModel.FromJObject(EngineEnvironmentSettings, ArrayConfigForSymbolWithFormsButNotIdentity); Assert.True(configModel.Symbols.ContainsKey("testSymbol")); ISymbolModel symbolInfo = configModel.Symbols["testSymbol"]; Assert.True(symbolInfo is ParameterSymbol); ParameterSymbol paramSymbol = symbolInfo as ParameterSymbol; Assert.Single(paramSymbol.Forms.GlobalForms.ToList() .Where(x => string.Equals(x, IdentityValueForm.FormName, StringComparison.OrdinalIgnoreCase)) ); Assert.Equal(0, paramSymbol.Forms.GlobalForms.ToList().IndexOf(IdentityValueForm.FormName)); } private static JObject ArrayConfigForSymbolWithFormsButNotIdentity { get { string configString = @" { ""author"": ""Test Asset"", ""classifications"": [ ""Test Asset"" ], ""name"": ""TemplateWithValueForms"", ""generatorVersions"": ""[1.0.0.0-*)"", ""groupIdentity"": ""TestAssets.TemplateWithValueForms"", ""precedence"": ""100"", ""identity"": ""TestAssets.TemplateWithValueForms"", ""shortName"": ""TestAssets.TemplateWithValueForms"", ""symbols"": { ""testSymbol"": { ""type"": ""parameter"", ""dataType"": ""string"", ""forms"": { ""global"": [ ""foo"", ""bar"", ""baz"" ] } } } }"; return JObject.Parse(configString); } } // Tests that a name symbol with explicitly defined value forms but no identity form // gets the identity form added as the first form. [Fact(DisplayName = nameof(ArrayConfigNameSymbolWithoutIdentityFormGetsIdentityFormAddedAsFirst))] public void ArrayConfigNameSymbolWithoutIdentityFormGetsIdentityFormAddedAsFirst() { SimpleConfigModel configModel = SimpleConfigModel.FromJObject(EngineEnvironmentSettings, ArrayConfigWithNameSymbolAndValueFormsButNotIdentity); Assert.True(configModel.Symbols.ContainsKey("name")); ISymbolModel symbolInfo = configModel.Symbols["name"]; Assert.True(symbolInfo is ParameterSymbol); ParameterSymbol nameSymbol = symbolInfo as ParameterSymbol; IList<string> configuredValueFormNames = nameSymbol.Forms.GlobalForms.ToList(); Assert.Equal(4, configuredValueFormNames.Count); Assert.Equal(IdentityValueForm.FormName, configuredValueFormNames[0]); Assert.Equal("foo", configuredValueFormNames[1]); Assert.Equal("bar", configuredValueFormNames[2]); Assert.Equal("baz", configuredValueFormNames[3]); } private static JObject ArrayConfigWithNameSymbolAndValueFormsButNotIdentity { get { string configString = @" { ""author"": ""Test Asset"", ""classifications"": [ ""Test Asset"" ], ""name"": ""TemplateWithValueForms"", ""generatorVersions"": ""[1.0.0.0-*)"", ""groupIdentity"": ""TestAssets.TemplateWithValueForms"", ""precedence"": ""100"", ""identity"": ""TestAssets.TemplateWithValueForms"", ""shortName"": ""TestAssets.TemplateWithValueForms"", ""symbols"": { ""name"": { ""type"": ""parameter"", ""dataType"": ""string"", ""forms"": { ""global"": [ ""foo"", ""bar"", ""baz"" ] } } } }"; return JObject.Parse(configString); } } [Fact(DisplayName = nameof(ExplicitNameSymbolWithoutBindingGetsDefaultNameBinding))] public void ExplicitNameSymbolWithoutBindingGetsDefaultNameBinding() { SimpleConfigModel configModel = SimpleConfigModel.FromJObject(EngineEnvironmentSettings, ConfigWithNameSymbolWithoutBinding); Assert.True(configModel.Symbols.ContainsKey("name")); ISymbolModel symbolInfo = configModel.Symbols["name"]; Assert.True(symbolInfo is ParameterSymbol); ParameterSymbol nameSymbol = symbolInfo as ParameterSymbol; Assert.Equal("name", symbolInfo.Binding); } private static JObject ConfigWithNameSymbolWithoutBinding { get { string configString = @" { ""author"": ""Test Asset"", ""classifications"": [ ""Test Asset"" ], ""name"": ""TemplateWithNameSymbolWithoutBinding"", ""generatorVersions"": ""[1.0.0.0-*)"", ""groupIdentity"": ""TestAssets.TemplateWithNameSymbolWithoutBinding"", ""precedence"": ""100"", ""identity"": ""TestAssets.TemplateWithNameSymbolWithoutBinding"", ""shortName"": ""TestAssets.TemplateWithNameSymbolWithoutBinding"", ""symbols"": { ""name"": { ""type"": ""parameter"", ""dataType"": ""string"", } } }"; return JObject.Parse(configString); } } [Fact(DisplayName = nameof(ExplicitNameSymbolWithCustomBindingRetainsCustomBinding))] public void ExplicitNameSymbolWithCustomBindingRetainsCustomBinding() { SimpleConfigModel configModel = SimpleConfigModel.FromJObject(EngineEnvironmentSettings, ConfigWithNameSymbolWithCustomBinding); Assert.True(configModel.Symbols.ContainsKey("name")); ISymbolModel symbolInfo = configModel.Symbols["name"]; Assert.True(symbolInfo is ParameterSymbol); ParameterSymbol nameSymbol = symbolInfo as ParameterSymbol; Assert.Equal("customBinding", symbolInfo.Binding); } private static JObject ConfigWithNameSymbolWithCustomBinding { get { string configString = @" { ""author"": ""Test Asset"", ""classifications"": [ ""Test Asset"" ], ""name"": ""ConfigWithNameSymbolWithCustomBinding"", ""generatorVersions"": ""[1.0.0.0-*)"", ""groupIdentity"": ""TestAssets.ConfigWithNameSymbolWithCustomBinding"", ""precedence"": ""100"", ""identity"": ""TestAssets.ConfigWithNameSymbolWithCustomBinding"", ""shortName"": ""TestAssets.ConfigWithNameSymbolWithCustomBinding"", ""symbols"": { ""name"": { ""type"": ""parameter"", ""dataType"": ""string"", ""binding"": ""customBinding"", } } }"; return JObject.Parse(configString); } } [Fact(DisplayName = nameof(ArrayConfigNameSymbolWithIdentityFormRetainsConfiguredFormsExactly))] public void ArrayConfigNameSymbolWithIdentityFormRetainsConfiguredFormsExactly() { SimpleConfigModel configModel = SimpleConfigModel.FromJObject(EngineEnvironmentSettings, ArrayConfigWithNameSymbolAndValueFormsWithIdentity); Assert.True(configModel.Symbols.ContainsKey("name")); ISymbolModel symbolInfo = configModel.Symbols["name"]; Assert.True(symbolInfo is ParameterSymbol); ParameterSymbol nameSymbol = symbolInfo as ParameterSymbol; IList<string> configuredValueFormNames = nameSymbol.Forms.GlobalForms.ToList(); Assert.Equal(4, configuredValueFormNames.Count); Assert.Equal("foo", configuredValueFormNames[0]); Assert.Equal("bar", configuredValueFormNames[1]); Assert.Equal("baz", configuredValueFormNames[2]); Assert.Equal(IdentityValueForm.FormName, configuredValueFormNames[3]); } private static JObject ArrayConfigWithNameSymbolAndValueFormsWithIdentity { get { string configString = @" { ""author"": ""Test Asset"", ""classifications"": [ ""Test Asset"" ], ""name"": ""TemplateWithValueForms"", ""generatorVersions"": ""[1.0.0.0-*)"", ""groupIdentity"": ""TestAssets.TemplateWithValueForms"", ""precedence"": ""100"", ""identity"": ""TestAssets.TemplateWithValueForms"", ""shortName"": ""TestAssets.TemplateWithValueForms"", ""symbols"": { ""name"": { ""type"": ""parameter"", ""dataType"": ""string"", ""forms"": { ""global"": [ ""foo"", ""bar"", ""baz"", ""identity"" ] } } } }"; return JObject.Parse(configString); } } [Fact(DisplayName = nameof(ObjectConfigNameSymbolWithIdentityFormAndAddIdentityFalseRetainsConfiguredFormsExactly))] public void ObjectConfigNameSymbolWithIdentityFormAndAddIdentityFalseRetainsConfiguredFormsExactly() { SimpleConfigModel configModel = SimpleConfigModel.FromJObject(EngineEnvironmentSettings, ObjectConfigNameSymbolWithIdentityFormAndAddIdentityFalse); Assert.True(configModel.Symbols.ContainsKey("name")); ISymbolModel symbolInfo = configModel.Symbols["name"]; Assert.True(symbolInfo is ParameterSymbol); ParameterSymbol nameSymbol = symbolInfo as ParameterSymbol; IList<string> configuredValueFormNames = nameSymbol.Forms.GlobalForms.ToList(); Assert.Equal(4, configuredValueFormNames.Count); Assert.Equal("foo", configuredValueFormNames[0]); Assert.Equal("bar", configuredValueFormNames[1]); Assert.Equal(IdentityValueForm.FormName, configuredValueFormNames[2]); Assert.Equal("baz", configuredValueFormNames[3]); } private static JObject ObjectConfigNameSymbolWithIdentityFormAndAddIdentityFalse { get { string configString = @" { ""author"": ""Test Asset"", ""classifications"": [ ""Test Asset"" ], ""name"": ""TemplateWithValueForms"", ""generatorVersions"": ""[1.0.0.0-*)"", ""groupIdentity"": ""TestAssets.TemplateWithValueForms"", ""precedence"": ""100"", ""identity"": ""TestAssets.TemplateWithValueForms"", ""shortName"": ""TestAssets.TemplateWithValueForms"", ""symbols"": { ""name"": { ""type"": ""parameter"", ""dataType"": ""string"", ""forms"": { ""global"": { ""forms"": [ ""foo"", ""bar"", ""identity"", ""baz"" ], ""addIdentity"": ""false"" } } } } }"; return JObject.Parse(configString); } } [Fact(DisplayName = nameof(ObjectConfigNameSymbolWithIdentityFormAndAddIdentityTrueRetainsConfiguredFormsExactly))] public void ObjectConfigNameSymbolWithIdentityFormAndAddIdentityTrueRetainsConfiguredFormsExactly() { SimpleConfigModel configModel = SimpleConfigModel.FromJObject(EngineEnvironmentSettings, ObjectConfigNameSymbolWithIdentityFormAndAddIdentityTrue); Assert.True(configModel.Symbols.ContainsKey("name")); ISymbolModel symbolInfo = configModel.Symbols["name"]; Assert.True(symbolInfo is ParameterSymbol); ParameterSymbol nameSymbol = symbolInfo as ParameterSymbol; IList<string> configuredValueFormNames = nameSymbol.Forms.GlobalForms.ToList(); Assert.Equal(4, configuredValueFormNames.Count); Assert.Equal("foo", configuredValueFormNames[0]); Assert.Equal("bar", configuredValueFormNames[1]); Assert.Equal(IdentityValueForm.FormName, configuredValueFormNames[2]); Assert.Equal("baz", configuredValueFormNames[3]); } private static JObject ObjectConfigNameSymbolWithIdentityFormAndAddIdentityTrue { get { string configString = @" { ""author"": ""Test Asset"", ""classifications"": [ ""Test Asset"" ], ""name"": ""TemplateWithValueForms"", ""generatorVersions"": ""[1.0.0.0-*)"", ""groupIdentity"": ""TestAssets.TemplateWithValueForms"", ""precedence"": ""100"", ""identity"": ""TestAssets.TemplateWithValueForms"", ""shortName"": ""TestAssets.TemplateWithValueForms"", ""symbols"": { ""name"": { ""type"": ""parameter"", ""dataType"": ""string"", ""forms"": { ""global"": { ""forms"": [ ""foo"", ""bar"", ""identity"", ""baz"" ], ""addIdentity"": ""true"" } } } } }"; return JObject.Parse(configString); } } private static JObject ConfigWithObjectValueFormDefinitionAddIdentityFalse { get { string configString = @" { ""author"": ""Test Asset"", ""classifications"": [ ""Test Asset"" ], ""name"": ""TemplateWithValueForms"", ""generatorVersions"": ""[1.0.0.0-*)"", ""groupIdentity"": ""TestAssets.TemplateWithValueForms"", ""precedence"": ""100"", ""identity"": ""TestAssets.TemplateWithValueForms"", ""shortName"": ""TestAssets.TemplateWithValueForms"", ""symbols"": { ""testSymbol"": { ""type"": ""parameter"", ""dataType"": ""string"", ""forms"": { ""global"": { ""forms"": [ ""foo"", ""bar"", ""baz"" ], ""addIdentity"": ""false"" } } } } }"; return JObject.Parse(configString); } } [Fact(DisplayName = nameof(NameSymbolObjectValueFormDefinitionRespectsAddIdentityTrue))] public void NameSymbolObjectValueFormDefinitionRespectsAddIdentityTrue() { SimpleConfigModel configModel = SimpleConfigModel.FromJObject(EngineEnvironmentSettings, NameConfigWithObjectValueFormDefinitionAddIdentityTrue); Assert.True(configModel.Symbols.ContainsKey("name")); ISymbolModel symbolInfo = configModel.Symbols["name"]; Assert.True(symbolInfo is ParameterSymbol); ParameterSymbol paramSymbol = symbolInfo as ParameterSymbol; IList<string> configuredValueFormNames = paramSymbol.Forms.GlobalForms.ToList(); Assert.Equal(4, configuredValueFormNames.Count); Assert.Equal(IdentityValueForm.FormName, configuredValueFormNames[0]); Assert.Equal("foo", configuredValueFormNames[1]); Assert.Equal("bar", configuredValueFormNames[2]); Assert.Equal("baz", configuredValueFormNames[3]); } private static JObject NameConfigWithObjectValueFormDefinitionAddIdentityTrue { get { string configString = @" { ""author"": ""Test Asset"", ""classifications"": [ ""Test Asset"" ], ""name"": ""TemplateWithValueForms"", ""generatorVersions"": ""[1.0.0.0-*)"", ""groupIdentity"": ""TestAssets.TemplateWithValueForms"", ""precedence"": ""100"", ""identity"": ""TestAssets.TemplateWithValueForms"", ""shortName"": ""TestAssets.TemplateWithValueForms"", ""symbols"": { ""name"": { ""type"": ""parameter"", ""dataType"": ""string"", ""forms"": { ""global"": { ""forms"": [ ""foo"", ""bar"", ""baz"" ], ""addIdentity"": ""true"" } } } } }"; return JObject.Parse(configString); } } [Fact(DisplayName = nameof(NameSymbolObjectValueFormDefinitionRespectsAddIdentityFalse))] public void NameSymbolObjectValueFormDefinitionRespectsAddIdentityFalse() { SimpleConfigModel configModel = SimpleConfigModel.FromJObject(EngineEnvironmentSettings, NameConfigWithObjectValueFormDefinitionAddIdentityFalse); Assert.True(configModel.Symbols.ContainsKey("name")); ISymbolModel symbolInfo = configModel.Symbols["name"]; Assert.True(symbolInfo is ParameterSymbol); ParameterSymbol paramSymbol = symbolInfo as ParameterSymbol; IList<string> configuredValueFormNames = paramSymbol.Forms.GlobalForms.ToList(); Assert.Equal(3, configuredValueFormNames.Count); Assert.Equal("foo", configuredValueFormNames[0]); Assert.Equal("bar", configuredValueFormNames[1]); Assert.Equal("baz", configuredValueFormNames[2]); } private static JObject NameConfigWithObjectValueFormDefinitionAddIdentityFalse { get { string configString = @" { ""author"": ""Test Asset"", ""classifications"": [ ""Test Asset"" ], ""name"": ""TemplateWithValueForms"", ""generatorVersions"": ""[1.0.0.0-*)"", ""groupIdentity"": ""TestAssets.TemplateWithValueForms"", ""precedence"": ""100"", ""identity"": ""TestAssets.TemplateWithValueForms"", ""shortName"": ""TestAssets.TemplateWithValueForms"", ""symbols"": { ""name"": { ""type"": ""parameter"", ""dataType"": ""string"", ""forms"": { ""global"": { ""forms"": [ ""foo"", ""bar"", ""baz"" ], ""addIdentity"": ""false"" } } } } }"; return JObject.Parse(configString); } } [Fact(DisplayName = nameof(NameSymbolObjectValueFormDefinitionInfersAddIdentityTrue))] public void NameSymbolObjectValueFormDefinitionInfersAddIdentityTrue() { SimpleConfigModel configModel = SimpleConfigModel.FromJObject(EngineEnvironmentSettings, NameConfigObjectValueFormWithoutIdentityAndAddIdentityUnspecified); Assert.True(configModel.Symbols.ContainsKey("name")); ISymbolModel symbolInfo = configModel.Symbols["name"]; Assert.True(symbolInfo is ParameterSymbol); ParameterSymbol paramSymbol = symbolInfo as ParameterSymbol; IList<string> configuredValueFormNames = paramSymbol.Forms.GlobalForms.ToList(); Assert.Equal(4, configuredValueFormNames.Count); Assert.Equal(IdentityValueForm.FormName, configuredValueFormNames[0]); Assert.Equal("foo", configuredValueFormNames[1]); Assert.Equal("bar", configuredValueFormNames[2]); Assert.Equal("baz", configuredValueFormNames[3]); } private static JObject NameConfigObjectValueFormWithoutIdentityAndAddIdentityUnspecified { get { string configString = @" { ""author"": ""Test Asset"", ""classifications"": [ ""Test Asset"" ], ""name"": ""TemplateWithValueForms"", ""generatorVersions"": ""[1.0.0.0-*)"", ""groupIdentity"": ""TestAssets.TemplateWithValueForms"", ""precedence"": ""100"", ""identity"": ""TestAssets.TemplateWithValueForms"", ""shortName"": ""TestAssets.TemplateWithValueForms"", ""symbols"": { ""name"": { ""type"": ""parameter"", ""dataType"": ""string"", ""forms"": { ""global"": { ""forms"": [ ""foo"", ""bar"", ""baz"" ], } } } } }"; return JObject.Parse(configString); } } [Fact(DisplayName = nameof(NameSymbolObjectValueFormWithIdentityWithoutAddIdentityRetainsConfiguredForms))] public void NameSymbolObjectValueFormWithIdentityWithoutAddIdentityRetainsConfiguredForms() { SimpleConfigModel configModel = SimpleConfigModel.FromJObject(EngineEnvironmentSettings, NameConfigObjectValueFormWithIdentityAndAddIdentityUnspecified); Assert.True(configModel.Symbols.ContainsKey("name")); ISymbolModel symbolInfo = configModel.Symbols["name"]; Assert.True(symbolInfo is ParameterSymbol); ParameterSymbol paramSymbol = symbolInfo as ParameterSymbol; IList<string> configuredValueFormNames = paramSymbol.Forms.GlobalForms.ToList(); Assert.Equal(4, configuredValueFormNames.Count); Assert.Equal("foo", configuredValueFormNames[0]); Assert.Equal("bar", configuredValueFormNames[1]); Assert.Equal("baz", configuredValueFormNames[2]); Assert.Equal(IdentityValueForm.FormName, configuredValueFormNames[3]); } private static JObject NameConfigObjectValueFormWithIdentityAndAddIdentityUnspecified { get { string configString = @" { ""author"": ""Test Asset"", ""classifications"": [ ""Test Asset"" ], ""name"": ""TemplateWithValueForms"", ""generatorVersions"": ""[1.0.0.0-*)"", ""groupIdentity"": ""TestAssets.TemplateWithValueForms"", ""precedence"": ""100"", ""identity"": ""TestAssets.TemplateWithValueForms"", ""shortName"": ""TestAssets.TemplateWithValueForms"", ""symbols"": { ""name"": { ""type"": ""parameter"", ""dataType"": ""string"", ""forms"": { ""global"": { ""forms"": [ ""foo"", ""bar"", ""baz"", ""identity"" ], } } } } }"; return JObject.Parse(configString); } } [Fact(DisplayName = nameof(ParameterSymbolWithNoValueFormsGetsIdentityFormAdded))] public void ParameterSymbolWithNoValueFormsGetsIdentityFormAdded() { SimpleConfigModel configModel = SimpleConfigModel.FromJObject(EngineEnvironmentSettings, ConfigForSymbolWithoutValueForms); Assert.True(configModel.Symbols.ContainsKey("testSymbol")); ISymbolModel symbolInfo = configModel.Symbols["testSymbol"]; Assert.True(symbolInfo is ParameterSymbol); ParameterSymbol paramSymbol = symbolInfo as ParameterSymbol; IList<string> configuredValueFormNames = paramSymbol.Forms.GlobalForms.ToList(); Assert.Equal(1, configuredValueFormNames.Count); Assert.Equal(IdentityValueForm.FormName, configuredValueFormNames[0]); } private static JObject ConfigForSymbolWithoutValueForms { get { string configString = @" { ""author"": ""Test Asset"", ""classifications"": [ ""Test Asset"" ], ""name"": ""TemplateWithValueForms"", ""generatorVersions"": ""[1.0.0.0-*)"", ""groupIdentity"": ""TestAssets.TemplateWithValueForms"", ""precedence"": ""100"", ""identity"": ""TestAssets.TemplateWithValueForms"", ""shortName"": ""TestAssets.TemplateWithValueForms"", ""symbols"": { ""testSymbol"": { ""type"": ""parameter"", ""dataType"": ""string"" } } }"; return JObject.Parse(configString); } } // Test that when a symbol explicitly includes the "identity" value form, the value forms for the symbol remain unmodified. [Fact(DisplayName = nameof(ParameterSymbolWithArrayIdentityValueFormRetainsFormsUnmodified))] public void ParameterSymbolWithArrayIdentityValueFormRetainsFormsUnmodified() { SimpleConfigModel configModel = SimpleConfigModel.FromJObject(EngineEnvironmentSettings, ArrayConfigForSymbolWithValueFormsIncludingIdentity); Assert.True(configModel.Symbols.ContainsKey("testSymbol")); ISymbolModel symbolInfo = configModel.Symbols["testSymbol"]; Assert.True(symbolInfo is ParameterSymbol); ParameterSymbol paramSymbol = symbolInfo as ParameterSymbol; IList<string> configuredValueFormNames = paramSymbol.Forms.GlobalForms.ToList(); Assert.Equal(4, configuredValueFormNames.Count); Assert.Equal("foo", configuredValueFormNames[0]); Assert.Equal("bar", configuredValueFormNames[1]); Assert.Equal("baz", configuredValueFormNames[2]); Assert.Equal(IdentityValueForm.FormName, configuredValueFormNames[3]); } private static JObject ArrayConfigForSymbolWithValueFormsIncludingIdentity { get { string configString = @" { ""author"": ""Test Asset"", ""classifications"": [ ""Test Asset"" ], ""name"": ""TemplateWithValueForms"", ""generatorVersions"": ""[1.0.0.0-*)"", ""groupIdentity"": ""TestAssets.TemplateWithValueForms"", ""precedence"": ""100"", ""identity"": ""TestAssets.TemplateWithValueForms"", ""shortName"": ""TestAssets.TemplateWithValueForms"", ""symbols"": { ""testSymbol"": { ""type"": ""parameter"", ""dataType"": ""string"", ""forms"": { ""global"": [ ""foo"", ""bar"", ""baz"", ""identity"" ] } } } }"; return JObject.Parse(configString); } } [Fact(DisplayName = nameof(ObjectValueFormDefinitionRespectsAddIdentityTrue))] public void ObjectValueFormDefinitionRespectsAddIdentityTrue() { SimpleConfigModel configModel = SimpleConfigModel.FromJObject(EngineEnvironmentSettings, ConfigWithObjectValueFormDefinitionAddIdentityTrue); Assert.True(configModel.Symbols.ContainsKey("testSymbol")); ISymbolModel symbolInfo = configModel.Symbols["testSymbol"]; Assert.True(symbolInfo is ParameterSymbol); ParameterSymbol paramSymbol = symbolInfo as ParameterSymbol; IList<string> configuredValueFormNames = paramSymbol.Forms.GlobalForms.ToList(); Assert.Equal(4, configuredValueFormNames.Count); Assert.Equal(IdentityValueForm.FormName, configuredValueFormNames[0]); Assert.Equal("foo", configuredValueFormNames[1]); Assert.Equal("bar", configuredValueFormNames[2]); Assert.Equal("baz", configuredValueFormNames[3]); } private static JObject ConfigWithObjectValueFormDefinitionAddIdentityTrue { get { string configString = @" { ""author"": ""Test Asset"", ""classifications"": [ ""Test Asset"" ], ""name"": ""TemplateWithValueForms"", ""generatorVersions"": ""[1.0.0.0-*)"", ""groupIdentity"": ""TestAssets.TemplateWithValueForms"", ""precedence"": ""100"", ""identity"": ""TestAssets.TemplateWithValueForms"", ""shortName"": ""TestAssets.TemplateWithValueForms"", ""symbols"": { ""testSymbol"": { ""type"": ""parameter"", ""dataType"": ""string"", ""forms"": { ""global"": { ""forms"": [ ""foo"", ""bar"", ""baz"" ], ""addIdentity"": ""true"" } } } } }"; return JObject.Parse(configString); } } [Fact(DisplayName = nameof(ObjectValueFormDefinitionRespectsAddIdentityFalse))] public void ObjectValueFormDefinitionRespectsAddIdentityFalse() { SimpleConfigModel configModel = SimpleConfigModel.FromJObject(EngineEnvironmentSettings, ConfigWithObjectValueFormDefinitionAddIdentityFalse); Assert.True(configModel.Symbols.ContainsKey("testSymbol")); ISymbolModel symbolInfo = configModel.Symbols["testSymbol"]; Assert.True(symbolInfo is ParameterSymbol); ParameterSymbol paramSymbol = symbolInfo as ParameterSymbol; IList<string> configuredValueFormNames = paramSymbol.Forms.GlobalForms.ToList(); Assert.Equal(3, configuredValueFormNames.Count); Assert.Equal("foo", configuredValueFormNames[0]); Assert.Equal("bar", configuredValueFormNames[1]); Assert.Equal("baz", configuredValueFormNames[2]); } [Fact(DisplayName = nameof(ObjectConfigParameterSymbolWithIdentityFormAndAddIdentityFalseRetainsConfiguredFormsExactly))] public void ObjectConfigParameterSymbolWithIdentityFormAndAddIdentityFalseRetainsConfiguredFormsExactly() { SimpleConfigModel configModel = SimpleConfigModel.FromJObject(EngineEnvironmentSettings, ObjectConfigParameterSymbolWithIdentityFormAndAddIdentityFalse); Assert.True(configModel.Symbols.ContainsKey("testSymbol")); ISymbolModel symbolInfo = configModel.Symbols["testSymbol"]; Assert.True(symbolInfo is ParameterSymbol); ParameterSymbol nameSymbol = symbolInfo as ParameterSymbol; IList<string> configuredValueFormNames = nameSymbol.Forms.GlobalForms.ToList(); Assert.Equal(4, configuredValueFormNames.Count); Assert.Equal("foo", configuredValueFormNames[0]); Assert.Equal("bar", configuredValueFormNames[1]); Assert.Equal(IdentityValueForm.FormName, configuredValueFormNames[2]); Assert.Equal("baz", configuredValueFormNames[3]); } private static JObject ObjectConfigParameterSymbolWithIdentityFormAndAddIdentityFalse { get { string configString = @" { ""author"": ""Test Asset"", ""classifications"": [ ""Test Asset"" ], ""name"": ""TemplateWithValueForms"", ""generatorVersions"": ""[1.0.0.0-*)"", ""groupIdentity"": ""TestAssets.TemplateWithValueForms"", ""precedence"": ""100"", ""identity"": ""TestAssets.TemplateWithValueForms"", ""shortName"": ""TestAssets.TemplateWithValueForms"", ""symbols"": { ""testSymbol"": { ""type"": ""parameter"", ""dataType"": ""string"", ""forms"": { ""global"": { ""forms"": [ ""foo"", ""bar"", ""identity"", ""baz"" ], ""addIdentity"": ""false"" } } } } }"; return JObject.Parse(configString); } } [Fact(DisplayName = nameof(ObjectConfigParameterSymbolWithIdentityFormAndAddIdentityTrueRetainsConfiguredFormsExactly))] public void ObjectConfigParameterSymbolWithIdentityFormAndAddIdentityTrueRetainsConfiguredFormsExactly() { SimpleConfigModel configModel = SimpleConfigModel.FromJObject(EngineEnvironmentSettings, ObjectConfigParameterSymbolWithIdentityFormAndAddIdentityTrue); Assert.True(configModel.Symbols.ContainsKey("testSymbol")); ISymbolModel symbolInfo = configModel.Symbols["testSymbol"]; Assert.True(symbolInfo is ParameterSymbol); ParameterSymbol nameSymbol = symbolInfo as ParameterSymbol; IList<string> configuredValueFormNames = nameSymbol.Forms.GlobalForms.ToList(); Assert.Equal(4, configuredValueFormNames.Count); Assert.Equal("foo", configuredValueFormNames[0]); Assert.Equal("bar", configuredValueFormNames[1]); Assert.Equal(IdentityValueForm.FormName, configuredValueFormNames[2]); Assert.Equal("baz", configuredValueFormNames[3]); } private static JObject ObjectConfigParameterSymbolWithIdentityFormAndAddIdentityTrue { get { string configString = @" { ""author"": ""Test Asset"", ""classifications"": [ ""Test Asset"" ], ""name"": ""TemplateWithValueForms"", ""generatorVersions"": ""[1.0.0.0-*)"", ""groupIdentity"": ""TestAssets.TemplateWithValueForms"", ""precedence"": ""100"", ""identity"": ""TestAssets.TemplateWithValueForms"", ""shortName"": ""TestAssets.TemplateWithValueForms"", ""symbols"": { ""testSymbol"": { ""type"": ""parameter"", ""dataType"": ""string"", ""forms"": { ""global"": { ""forms"": [ ""foo"", ""bar"", ""identity"", ""baz"" ], ""addIdentity"": ""true"" } } } } }"; return JObject.Parse(configString); } } [Fact(DisplayName = nameof(ParameterSymbolObjectValueFormWithIdentityWithoutAddIdentityRetainsConfiguredForms))] public void ParameterSymbolObjectValueFormWithIdentityWithoutAddIdentityRetainsConfiguredForms() { SimpleConfigModel configModel = SimpleConfigModel.FromJObject(EngineEnvironmentSettings, ParameterConfigObjectValueFormWithIdentityAndAddIdentityUnspecified); Assert.True(configModel.Symbols.ContainsKey("testSymbol")); ISymbolModel symbolInfo = configModel.Symbols["testSymbol"]; Assert.True(symbolInfo is ParameterSymbol); ParameterSymbol paramSymbol = symbolInfo as ParameterSymbol; IList<string> configuredValueFormNames = paramSymbol.Forms.GlobalForms.ToList(); Assert.Equal(4, configuredValueFormNames.Count); Assert.Equal("foo", configuredValueFormNames[0]); Assert.Equal("bar", configuredValueFormNames[1]); Assert.Equal("baz", configuredValueFormNames[2]); Assert.Equal(IdentityValueForm.FormName, configuredValueFormNames[3]); } private static JObject ParameterConfigObjectValueFormWithIdentityAndAddIdentityUnspecified { get { string configString = @" { ""author"": ""Test Asset"", ""classifications"": [ ""Test Asset"" ], ""name"": ""TemplateWithValueForms"", ""generatorVersions"": ""[1.0.0.0-*)"", ""groupIdentity"": ""TestAssets.TemplateWithValueForms"", ""precedence"": ""100"", ""identity"": ""TestAssets.TemplateWithValueForms"", ""shortName"": ""TestAssets.TemplateWithValueForms"", ""symbols"": { ""testSymbol"": { ""type"": ""parameter"", ""dataType"": ""string"", ""forms"": { ""global"": { ""forms"": [ ""foo"", ""bar"", ""baz"", ""identity"" ], } } } } }"; return JObject.Parse(configString); } } [Fact(DisplayName = nameof(ParameterSymbolObjectValueFormDefinitionInfersAddIdentityTrue))] public void ParameterSymbolObjectValueFormDefinitionInfersAddIdentityTrue() { SimpleConfigModel configModel = SimpleConfigModel.FromJObject(EngineEnvironmentSettings, ParameterConfigObjectValueFormWithoutIdentityAndAddIdentityUnspecified); Assert.True(configModel.Symbols.ContainsKey("testSymbol")); ISymbolModel symbolInfo = configModel.Symbols["testSymbol"]; Assert.True(symbolInfo is ParameterSymbol); ParameterSymbol paramSymbol = symbolInfo as ParameterSymbol; IList<string> configuredValueFormNames = paramSymbol.Forms.GlobalForms.ToList(); Assert.Equal(4, configuredValueFormNames.Count); Assert.Equal(IdentityValueForm.FormName, configuredValueFormNames[0]); Assert.Equal("foo", configuredValueFormNames[1]); Assert.Equal("bar", configuredValueFormNames[2]); Assert.Equal("baz", configuredValueFormNames[3]); } private static JObject ParameterConfigObjectValueFormWithoutIdentityAndAddIdentityUnspecified { get { string configString = @" { ""author"": ""Test Asset"", ""classifications"": [ ""Test Asset"" ], ""name"": ""TemplateWithValueForms"", ""generatorVersions"": ""[1.0.0.0-*)"", ""groupIdentity"": ""TestAssets.TemplateWithValueForms"", ""precedence"": ""100"", ""identity"": ""TestAssets.TemplateWithValueForms"", ""shortName"": ""TestAssets.TemplateWithValueForms"", ""symbols"": { ""testSymbol"": { ""type"": ""parameter"", ""dataType"": ""string"", ""forms"": { ""global"": { ""forms"": [ ""foo"", ""bar"", ""baz"" ], } } } } }"; return JObject.Parse(configString); } } } }
namespace KabMan.Forms { partial class DCCDetailList { /// <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 Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.layoutControl1 = new DevExpress.XtraLayout.LayoutControl(); this.DCCSan2Grid = new DevExpress.XtraGrid.GridControl(); this.CSan2View = new DevExpress.XtraGrid.Views.Grid.GridView(); this.gridColumn15 = new DevExpress.XtraGrid.Columns.GridColumn(); this.gridColumn26 = new DevExpress.XtraGrid.Columns.GridColumn(); this.gridColumn16 = new DevExpress.XtraGrid.Columns.GridColumn(); this.gridColumn17 = new DevExpress.XtraGrid.Columns.GridColumn(); this.repVtPort2San1 = new DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit(); this.gridColumn18 = new DevExpress.XtraGrid.Columns.GridColumn(); this.gridColumn19 = new DevExpress.XtraGrid.Columns.GridColumn(); this.repVtPort2San2 = new DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit(); this.gridColumn20 = new DevExpress.XtraGrid.Columns.GridColumn(); this.gridColumn23 = new DevExpress.XtraGrid.Columns.GridColumn(); this.gridColumn24 = new DevExpress.XtraGrid.Columns.GridColumn(); this.gridView3 = new DevExpress.XtraGrid.Views.Grid.GridView(); this.DCCSan1Grid = new DevExpress.XtraGrid.GridControl(); this.CSan1View = new DevExpress.XtraGrid.Views.Grid.GridView(); this.gridColumn1 = new DevExpress.XtraGrid.Columns.GridColumn(); this.gridColumn25 = new DevExpress.XtraGrid.Columns.GridColumn(); this.gridColumn2 = new DevExpress.XtraGrid.Columns.GridColumn(); this.gridColumn4 = new DevExpress.XtraGrid.Columns.GridColumn(); this.repVtPort1San1 = new DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit(); this.gridColumn3 = new DevExpress.XtraGrid.Columns.GridColumn(); this.gridColumn7 = new DevExpress.XtraGrid.Columns.GridColumn(); this.repVtPort1San2 = new DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit(); this.gridColumn5 = new DevExpress.XtraGrid.Columns.GridColumn(); this.gridColumn21 = new DevExpress.XtraGrid.Columns.GridColumn(); this.gridColumn22 = new DevExpress.XtraGrid.Columns.GridColumn(); this.gridColumn27 = new DevExpress.XtraGrid.Columns.GridColumn(); this.gridColumn28 = new DevExpress.XtraGrid.Columns.GridColumn(); this.gridView2 = new DevExpress.XtraGrid.Views.Grid.GridView(); this.layoutControlGroup1 = new DevExpress.XtraLayout.LayoutControlGroup(); this.layoutControlItem2 = new DevExpress.XtraLayout.LayoutControlItem(); this.layoutControlItem1 = new DevExpress.XtraLayout.LayoutControlItem(); this.gridColumn8 = new DevExpress.XtraGrid.Columns.GridColumn(); this.gridColumn9 = new DevExpress.XtraGrid.Columns.GridColumn(); this.gridColumn10 = new DevExpress.XtraGrid.Columns.GridColumn(); this.gridColumn11 = new DevExpress.XtraGrid.Columns.GridColumn(); this.gridColumn12 = new DevExpress.XtraGrid.Columns.GridColumn(); this.gridColumn13 = new DevExpress.XtraGrid.Columns.GridColumn(); this.gridColumn14 = new DevExpress.XtraGrid.Columns.GridColumn(); this.gridColumn6 = new DevExpress.XtraGrid.Columns.GridColumn(); ((System.ComponentModel.ISupportInitialize)(this.layoutControl1)).BeginInit(); this.layoutControl1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.DCCSan2Grid)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.CSan2View)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.repVtPort2San1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.repVtPort2San2)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.gridView3)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.DCCSan1Grid)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.CSan1View)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.repVtPort1San1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.repVtPort1San2)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.gridView2)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlGroup1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem2)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem1)).BeginInit(); this.SuspendLayout(); // // layoutControl1 // this.layoutControl1.Appearance.DisabledLayoutGroupCaption.ForeColor = System.Drawing.SystemColors.GrayText; this.layoutControl1.Appearance.DisabledLayoutGroupCaption.Options.UseForeColor = true; this.layoutControl1.Appearance.DisabledLayoutItem.ForeColor = System.Drawing.SystemColors.GrayText; this.layoutControl1.Appearance.DisabledLayoutItem.Options.UseForeColor = true; this.layoutControl1.Controls.Add(this.DCCSan2Grid); this.layoutControl1.Controls.Add(this.DCCSan1Grid); this.layoutControl1.Dock = System.Windows.Forms.DockStyle.Fill; this.layoutControl1.Location = new System.Drawing.Point(0, 0); this.layoutControl1.Name = "layoutControl1"; this.layoutControl1.Root = this.layoutControlGroup1; this.layoutControl1.Size = new System.Drawing.Size(730, 514); this.layoutControl1.TabIndex = 0; this.layoutControl1.Text = "layoutControl1"; // // DCCSan2Grid // this.DCCSan2Grid.Location = new System.Drawing.Point(7, 263); this.DCCSan2Grid.MainView = this.CSan2View; this.DCCSan2Grid.Name = "DCCSan2Grid"; this.DCCSan2Grid.RepositoryItems.AddRange(new DevExpress.XtraEditors.Repository.RepositoryItem[] { this.repVtPort2San1, this.repVtPort2San2}); this.DCCSan2Grid.Size = new System.Drawing.Size(717, 245); this.DCCSan2Grid.TabIndex = 6; this.DCCSan2Grid.ViewCollection.AddRange(new DevExpress.XtraGrid.Views.Base.BaseView[] { this.CSan2View, this.gridView3}); // // CSan2View // this.CSan2View.Columns.AddRange(new DevExpress.XtraGrid.Columns.GridColumn[] { this.gridColumn15, this.gridColumn26, this.gridColumn16, this.gridColumn17, this.gridColumn18, this.gridColumn19, this.gridColumn20, this.gridColumn23, this.gridColumn24}); this.CSan2View.GridControl = this.DCCSan2Grid; this.CSan2View.Name = "CSan2View"; this.CSan2View.OptionsView.ShowAutoFilterRow = true; this.CSan2View.OptionsView.ShowGroupPanel = false; this.CSan2View.OptionsView.ShowIndicator = false; this.CSan2View.CellValueChanged += new DevExpress.XtraGrid.Views.Base.CellValueChangedEventHandler(this.CSan2View_CellValueChanged); this.CSan2View.Click += new System.EventHandler(this.CSan2View_Click); this.CSan2View.ShownEditor += new System.EventHandler(this.CSan2View_ShownEditor); // // gridColumn15 // this.gridColumn15.Caption = "Name"; this.gridColumn15.FieldName = "Name"; this.gridColumn15.Name = "gridColumn15"; this.gridColumn15.OptionsColumn.AllowEdit = false; this.gridColumn15.Visible = true; this.gridColumn15.VisibleIndex = 0; this.gridColumn15.Width = 89; // // gridColumn26 // this.gridColumn26.Caption = "Connection Name"; this.gridColumn26.FieldName = "Target"; this.gridColumn26.Name = "gridColumn26"; this.gridColumn26.OptionsColumn.AllowEdit = false; this.gridColumn26.Visible = true; this.gridColumn26.VisibleIndex = 1; this.gridColumn26.Width = 95; // // gridColumn16 // this.gridColumn16.Caption = "URMURM 1"; this.gridColumn16.FieldName = "UrmUrm1"; this.gridColumn16.Name = "gridColumn16"; this.gridColumn16.OptionsColumn.AllowEdit = false; this.gridColumn16.Visible = true; this.gridColumn16.VisibleIndex = 2; this.gridColumn16.Width = 82; // // gridColumn17 // this.gridColumn17.Caption = "VT PORT SAN 1"; this.gridColumn17.FieldName = "VTPORT1"; this.gridColumn17.Name = "gridColumn17"; this.gridColumn17.Visible = true; this.gridColumn17.VisibleIndex = 3; this.gridColumn17.Width = 82; // // repVtPort2San1 // this.repVtPort2San1.AutoHeight = false; this.repVtPort2San1.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] { new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Combo)}); this.repVtPort2San1.Columns.AddRange(new DevExpress.XtraEditors.Controls.LookUpColumnInfo[] { new DevExpress.XtraEditors.Controls.LookUpColumnInfo("VTPORT1Id", "VTPORT1Id", 20, DevExpress.Utils.FormatType.None, "", false, DevExpress.Utils.HorzAlignment.Default), new DevExpress.XtraEditors.Controls.LookUpColumnInfo("VTPORT1", "VTPORT1")}); this.repVtPort2San1.DisplayMember = "VTPORT1"; this.repVtPort2San1.Name = "repVtPort2San1"; this.repVtPort2San1.NullText = ""; this.repVtPort2San1.ValueMember = "VTPORT1DetailId"; this.repVtPort2San1.Popup += new System.EventHandler(this.repVtPort2San1_Popup); this.repVtPort2San1.Closed += new DevExpress.XtraEditors.Controls.ClosedEventHandler(this.repVtPort2San1_Closed); // // gridColumn18 // this.gridColumn18.Caption = "Trunk Cable"; this.gridColumn18.FieldName = "TrunkCable"; this.gridColumn18.Name = "gridColumn18"; this.gridColumn18.OptionsColumn.AllowEdit = false; this.gridColumn18.Visible = true; this.gridColumn18.VisibleIndex = 4; this.gridColumn18.Width = 82; // // gridColumn19 // this.gridColumn19.Caption = "VT PORT SAN 2"; this.gridColumn19.FieldName = "VTPORT2"; this.gridColumn19.Name = "gridColumn19"; this.gridColumn19.Visible = true; this.gridColumn19.VisibleIndex = 5; // // repVtPort2San2 // this.repVtPort2San2.AutoHeight = false; this.repVtPort2San2.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] { new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Combo)}); this.repVtPort2San2.Columns.AddRange(new DevExpress.XtraEditors.Controls.LookUpColumnInfo[] { new DevExpress.XtraEditors.Controls.LookUpColumnInfo("VTPORT2", "VTPORT2"), new DevExpress.XtraEditors.Controls.LookUpColumnInfo("VTPORT2Id", "VTPORT2Id", 20, DevExpress.Utils.FormatType.None, "", false, DevExpress.Utils.HorzAlignment.Default)}); this.repVtPort2San2.DisplayMember = "VTPORT2"; this.repVtPort2San2.Name = "repVtPort2San2"; this.repVtPort2San2.NullText = ""; this.repVtPort2San2.ValueMember = "VTPORT2DetailId"; this.repVtPort2San2.Popup += new System.EventHandler(this.repVtPort2San2_Popup); this.repVtPort2San2.Closed += new DevExpress.XtraEditors.Controls.ClosedEventHandler(this.repVtPort2San2_Closed); // // gridColumn20 // this.gridColumn20.Caption = "URMURM 2"; this.gridColumn20.FieldName = "UrmUrm2"; this.gridColumn20.Name = "gridColumn20"; this.gridColumn20.OptionsColumn.AllowEdit = false; this.gridColumn20.Visible = true; this.gridColumn20.VisibleIndex = 6; this.gridColumn20.Width = 93; // // gridColumn23 // this.gridColumn23.Caption = "Reserved"; this.gridColumn23.FieldName = "Reserved"; this.gridColumn23.Name = "gridColumn23"; this.gridColumn23.OptionsColumn.AllowEdit = false; this.gridColumn23.Visible = true; this.gridColumn23.VisibleIndex = 7; this.gridColumn23.Width = 52; // // gridColumn24 // this.gridColumn24.Caption = "Connected"; this.gridColumn24.FieldName = "Connected"; this.gridColumn24.Name = "gridColumn24"; this.gridColumn24.OptionsColumn.AllowEdit = false; this.gridColumn24.Visible = true; this.gridColumn24.VisibleIndex = 8; this.gridColumn24.Width = 63; // // gridView3 // this.gridView3.GridControl = this.DCCSan2Grid; this.gridView3.Name = "gridView3"; // // DCCSan1Grid // this.DCCSan1Grid.Location = new System.Drawing.Point(7, 7); this.DCCSan1Grid.MainView = this.CSan1View; this.DCCSan1Grid.Name = "DCCSan1Grid"; this.DCCSan1Grid.RepositoryItems.AddRange(new DevExpress.XtraEditors.Repository.RepositoryItem[] { this.repVtPort1San1, this.repVtPort1San2}); this.DCCSan1Grid.Size = new System.Drawing.Size(717, 245); this.DCCSan1Grid.TabIndex = 5; this.DCCSan1Grid.ViewCollection.AddRange(new DevExpress.XtraGrid.Views.Base.BaseView[] { this.CSan1View, this.gridView2}); // // CSan1View // this.CSan1View.Columns.AddRange(new DevExpress.XtraGrid.Columns.GridColumn[] { this.gridColumn1, this.gridColumn25, this.gridColumn2, this.gridColumn4, this.gridColumn3, this.gridColumn7, this.gridColumn5, this.gridColumn21, this.gridColumn22, this.gridColumn27, this.gridColumn28}); this.CSan1View.GridControl = this.DCCSan1Grid; this.CSan1View.Name = "CSan1View"; this.CSan1View.OptionsView.ShowAutoFilterRow = true; this.CSan1View.OptionsView.ShowGroupPanel = false; this.CSan1View.OptionsView.ShowIndicator = false; this.CSan1View.RowClick += new DevExpress.XtraGrid.Views.Grid.RowClickEventHandler(this.CSan1View_RowClick); this.CSan1View.CellValueChanged += new DevExpress.XtraGrid.Views.Base.CellValueChangedEventHandler(this.CSan1View_CellValueChanged); this.CSan1View.Click += new System.EventHandler(this.CSan1View_Click); this.CSan1View.ShownEditor += new System.EventHandler(this.CSan1View_ShownEditor); // // gridColumn1 // this.gridColumn1.Caption = "Name"; this.gridColumn1.FieldName = "Name"; this.gridColumn1.Name = "gridColumn1"; this.gridColumn1.OptionsColumn.AllowEdit = false; this.gridColumn1.Visible = true; this.gridColumn1.VisibleIndex = 0; this.gridColumn1.Width = 88; // // gridColumn25 // this.gridColumn25.Caption = "Connection Name"; this.gridColumn25.FieldName = "Target"; this.gridColumn25.Name = "gridColumn25"; this.gridColumn25.OptionsColumn.AllowEdit = false; this.gridColumn25.Visible = true; this.gridColumn25.VisibleIndex = 1; this.gridColumn25.Width = 98; // // gridColumn2 // this.gridColumn2.Caption = "URMURM 1"; this.gridColumn2.FieldName = "UrmUrm1"; this.gridColumn2.Name = "gridColumn2"; this.gridColumn2.OptionsColumn.AllowEdit = false; this.gridColumn2.Visible = true; this.gridColumn2.VisibleIndex = 2; this.gridColumn2.Width = 81; // // gridColumn4 // this.gridColumn4.Caption = "VT PORT SAN 1"; this.gridColumn4.FieldName = "VTPORT1"; this.gridColumn4.Name = "gridColumn4"; this.gridColumn4.Visible = true; this.gridColumn4.VisibleIndex = 3; this.gridColumn4.Width = 81; // // repVtPort1San1 // this.repVtPort1San1.AutoHeight = false; this.repVtPort1San1.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] { new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Combo)}); this.repVtPort1San1.Columns.AddRange(new DevExpress.XtraEditors.Controls.LookUpColumnInfo[] { new DevExpress.XtraEditors.Controls.LookUpColumnInfo("VTPORT1Id", "VTPORT1Id", 20, DevExpress.Utils.FormatType.None, "", false, DevExpress.Utils.HorzAlignment.Default), new DevExpress.XtraEditors.Controls.LookUpColumnInfo("VTPORT1", "VTPORT1")}); this.repVtPort1San1.DisplayMember = "VTPORT1"; this.repVtPort1San1.Name = "repVtPort1San1"; this.repVtPort1San1.NullText = ""; this.repVtPort1San1.ValueMember = "VTPORT1DetailId"; this.repVtPort1San1.Popup += new System.EventHandler(this.repVtPort1San1_Popup); this.repVtPort1San1.Closed += new DevExpress.XtraEditors.Controls.ClosedEventHandler(this.repVtPort1San1_Closed); // // gridColumn3 // this.gridColumn3.Caption = "Trunk Cable"; this.gridColumn3.FieldName = "TrunkCable"; this.gridColumn3.Name = "gridColumn3"; this.gridColumn3.OptionsColumn.AllowEdit = false; this.gridColumn3.Visible = true; this.gridColumn3.VisibleIndex = 4; this.gridColumn3.Width = 81; // // gridColumn7 // this.gridColumn7.Caption = "VT PORT SAN 2"; this.gridColumn7.FieldName = "VTPORT2"; this.gridColumn7.Name = "gridColumn7"; this.gridColumn7.Visible = true; this.gridColumn7.VisibleIndex = 5; this.gridColumn7.Width = 81; // // repVtPort1San2 // this.repVtPort1San2.AutoHeight = false; this.repVtPort1San2.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] { new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Combo)}); this.repVtPort1San2.Columns.AddRange(new DevExpress.XtraEditors.Controls.LookUpColumnInfo[] { new DevExpress.XtraEditors.Controls.LookUpColumnInfo("VTPORT2Id", "VTPORT2Id", 20, DevExpress.Utils.FormatType.None, "", false, DevExpress.Utils.HorzAlignment.Default), new DevExpress.XtraEditors.Controls.LookUpColumnInfo("VTPORT2", "VTPORT2")}); this.repVtPort1San2.DisplayMember = "VTPORT2"; this.repVtPort1San2.Name = "repVtPort1San2"; this.repVtPort1San2.NullText = ""; this.repVtPort1San2.ValueMember = "VTPORT2DetailId"; this.repVtPort1San2.Popup += new System.EventHandler(this.repVtPort1San2_Popup); this.repVtPort1San2.Closed += new DevExpress.XtraEditors.Controls.ClosedEventHandler(this.repVtPort1San2_Closed); // // gridColumn5 // this.gridColumn5.Caption = "URMURM 2"; this.gridColumn5.FieldName = "UrmUrm2"; this.gridColumn5.Name = "gridColumn5"; this.gridColumn5.OptionsColumn.AllowEdit = false; this.gridColumn5.Visible = true; this.gridColumn5.VisibleIndex = 6; this.gridColumn5.Width = 91; // // gridColumn21 // this.gridColumn21.Caption = "Reserved"; this.gridColumn21.FieldName = "Reserved"; this.gridColumn21.Name = "gridColumn21"; this.gridColumn21.OptionsColumn.AllowEdit = false; this.gridColumn21.Visible = true; this.gridColumn21.VisibleIndex = 7; this.gridColumn21.Width = 52; // // gridColumn22 // this.gridColumn22.Caption = "Connected"; this.gridColumn22.FieldName = "Connected"; this.gridColumn22.Name = "gridColumn22"; this.gridColumn22.OptionsColumn.AllowEdit = false; this.gridColumn22.Visible = true; this.gridColumn22.VisibleIndex = 8; this.gridColumn22.Width = 60; // // gridColumn27 // this.gridColumn27.Caption = "VTPORT1Id"; this.gridColumn27.FieldName = "VTPORT1Id"; this.gridColumn27.Name = "gridColumn27"; // // gridColumn28 // this.gridColumn28.Caption = "VTPORT2Id"; this.gridColumn28.FieldName = "VTPORT2Id"; this.gridColumn28.Name = "gridColumn28"; // // gridView2 // this.gridView2.GridControl = this.DCCSan1Grid; this.gridView2.Name = "gridView2"; // // layoutControlGroup1 // this.layoutControlGroup1.CustomizationFormText = "layoutControlGroup1"; this.layoutControlGroup1.Items.AddRange(new DevExpress.XtraLayout.BaseLayoutItem[] { this.layoutControlItem2, this.layoutControlItem1}); this.layoutControlGroup1.Location = new System.Drawing.Point(0, 0); this.layoutControlGroup1.Name = "Root"; this.layoutControlGroup1.Size = new System.Drawing.Size(730, 514); this.layoutControlGroup1.Spacing = new DevExpress.XtraLayout.Utils.Padding(0, 0, 0, 0); this.layoutControlGroup1.Text = "Root"; this.layoutControlGroup1.TextVisible = false; // // layoutControlItem2 // this.layoutControlItem2.Control = this.DCCSan1Grid; this.layoutControlItem2.CustomizationFormText = "layoutControlItem2"; this.layoutControlItem2.Location = new System.Drawing.Point(0, 0); this.layoutControlItem2.Name = "layoutControlItem2"; this.layoutControlItem2.Size = new System.Drawing.Size(728, 256); this.layoutControlItem2.Text = "layoutControlItem2"; this.layoutControlItem2.TextLocation = DevExpress.Utils.Locations.Left; this.layoutControlItem2.TextSize = new System.Drawing.Size(0, 0); this.layoutControlItem2.TextToControlDistance = 0; this.layoutControlItem2.TextVisible = false; // // layoutControlItem1 // this.layoutControlItem1.Control = this.DCCSan2Grid; this.layoutControlItem1.CustomizationFormText = "layoutControlItem1"; this.layoutControlItem1.Location = new System.Drawing.Point(0, 256); this.layoutControlItem1.Name = "layoutControlItem1"; this.layoutControlItem1.Size = new System.Drawing.Size(728, 256); this.layoutControlItem1.Text = "layoutControlItem1"; this.layoutControlItem1.TextLocation = DevExpress.Utils.Locations.Left; this.layoutControlItem1.TextSize = new System.Drawing.Size(0, 0); this.layoutControlItem1.TextToControlDistance = 0; this.layoutControlItem1.TextVisible = false; // // gridColumn8 // this.gridColumn8.Caption = "ConnectionName"; this.gridColumn8.FieldName = "Name"; this.gridColumn8.Name = "gridColumn8"; this.gridColumn8.Visible = true; this.gridColumn8.VisibleIndex = 0; // // gridColumn9 // this.gridColumn9.Caption = "LC URM"; this.gridColumn9.FieldName = "LcUrmCable"; this.gridColumn9.Name = "gridColumn9"; this.gridColumn9.Visible = true; this.gridColumn9.VisibleIndex = 1; // // gridColumn10 // this.gridColumn10.Caption = "Blech"; this.gridColumn10.FieldName = "Blech"; this.gridColumn10.Name = "gridColumn10"; this.gridColumn10.Visible = true; this.gridColumn10.VisibleIndex = 2; // // gridColumn11 // this.gridColumn11.Caption = "Trunk Cable"; this.gridColumn11.FieldName = "TrunkCable"; this.gridColumn11.Name = "gridColumn11"; this.gridColumn11.Visible = true; this.gridColumn11.VisibleIndex = 3; // // gridColumn12 // this.gridColumn12.Caption = "VT Port"; this.gridColumn12.FieldName = "VTPort"; this.gridColumn12.Name = "gridColumn12"; this.gridColumn12.Visible = true; this.gridColumn12.VisibleIndex = 4; // // gridColumn13 // this.gridColumn13.Caption = "URM URM"; this.gridColumn13.FieldName = "UrmUrmCable"; this.gridColumn13.Name = "gridColumn13"; this.gridColumn13.Visible = true; this.gridColumn13.VisibleIndex = 5; // // gridColumn14 // this.gridColumn14.Caption = "Line Available"; this.gridColumn14.FieldName = "Available"; this.gridColumn14.Name = "gridColumn14"; this.gridColumn14.Visible = true; this.gridColumn14.VisibleIndex = 6; // // gridColumn6 // this.gridColumn6.Caption = "Line Available"; this.gridColumn6.FieldName = "Available"; this.gridColumn6.Name = "gridColumn6"; this.gridColumn6.Visible = true; this.gridColumn6.VisibleIndex = 6; // // DCCDetailList // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(730, 514); this.Controls.Add(this.layoutControl1); this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "DCCDetailList"; this.ShowInTaskbar = false; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; this.Text = "Data Center List"; this.Load += new System.EventHandler(this.DCCDetailList_Load); ((System.ComponentModel.ISupportInitialize)(this.layoutControl1)).EndInit(); this.layoutControl1.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.DCCSan2Grid)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.CSan2View)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.repVtPort2San1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.repVtPort2San2)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.gridView3)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.DCCSan1Grid)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.CSan1View)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.repVtPort1San1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.repVtPort1San2)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.gridView2)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlGroup1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem2)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem1)).EndInit(); this.ResumeLayout(false); } #endregion private DevExpress.XtraLayout.LayoutControl layoutControl1; private DevExpress.XtraLayout.LayoutControlGroup layoutControlGroup1; private DevExpress.XtraGrid.GridControl DCCSan1Grid; private DevExpress.XtraGrid.Views.Grid.GridView CSan1View; private DevExpress.XtraGrid.Columns.GridColumn gridColumn1; private DevExpress.XtraGrid.Columns.GridColumn gridColumn2; private DevExpress.XtraGrid.Columns.GridColumn gridColumn3; private DevExpress.XtraGrid.Columns.GridColumn gridColumn4; private DevExpress.XtraGrid.Columns.GridColumn gridColumn5; private DevExpress.XtraGrid.Views.Grid.GridView gridView2; private DevExpress.XtraLayout.LayoutControlItem layoutControlItem2; private DevExpress.XtraGrid.GridControl DCCSan2Grid; private DevExpress.XtraGrid.Views.Grid.GridView CSan2View; private DevExpress.XtraGrid.Columns.GridColumn gridColumn15; private DevExpress.XtraGrid.Columns.GridColumn gridColumn16; private DevExpress.XtraGrid.Columns.GridColumn gridColumn17; private DevExpress.XtraGrid.Columns.GridColumn gridColumn18; private DevExpress.XtraGrid.Columns.GridColumn gridColumn19; private DevExpress.XtraGrid.Columns.GridColumn gridColumn20; private DevExpress.XtraGrid.Views.Grid.GridView gridView3; private DevExpress.XtraGrid.Columns.GridColumn gridColumn7; private DevExpress.XtraLayout.LayoutControlItem layoutControlItem1; private DevExpress.XtraGrid.Columns.GridColumn gridColumn8; private DevExpress.XtraGrid.Columns.GridColumn gridColumn9; private DevExpress.XtraGrid.Columns.GridColumn gridColumn10; private DevExpress.XtraGrid.Columns.GridColumn gridColumn11; private DevExpress.XtraGrid.Columns.GridColumn gridColumn12; private DevExpress.XtraGrid.Columns.GridColumn gridColumn13; private DevExpress.XtraGrid.Columns.GridColumn gridColumn14; private DevExpress.XtraGrid.Columns.GridColumn gridColumn6; private DevExpress.XtraGrid.Columns.GridColumn gridColumn23; private DevExpress.XtraGrid.Columns.GridColumn gridColumn24; private DevExpress.XtraGrid.Columns.GridColumn gridColumn21; private DevExpress.XtraGrid.Columns.GridColumn gridColumn22; private DevExpress.XtraGrid.Columns.GridColumn gridColumn26; private DevExpress.XtraGrid.Columns.GridColumn gridColumn25; private DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit repVtPort1San2; private DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit repVtPort2San2; private DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit repVtPort1San1; private DevExpress.XtraEditors.Repository.RepositoryItemLookUpEdit repVtPort2San1; private DevExpress.XtraGrid.Columns.GridColumn gridColumn27; private DevExpress.XtraGrid.Columns.GridColumn gridColumn28; } }
// ---------------------------------------------------------------------------------- // // 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 System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq.Expressions; using System.Runtime.Serialization; using System.Security.Cryptography; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.Azure.Management.RecoveryServices.SiteRecovery.Models; using Microsoft.Azure.Portal.RecoveryServices.Models.Common; using Microsoft.Rest.Azure; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace Microsoft.Azure.Commands.RecoveryServices.SiteRecovery { /// <summary> /// Class to define Utility methods /// </summary> public static class Utilities { /// <summary> /// Deserialize the xml as T /// </summary> /// <typeparam name="T">the type name</typeparam> /// <param name="xml">the xml as string</param> /// <returns>the equivalent T</returns> [SuppressMessage( "StyleCop.CSharp.DocumentationRules", "SA1650:ElementDocumentationMustBeSpelledCorrectly", Justification = "Reviewed.")] public static T Deserialize<T>( string xml) { if (string.IsNullOrEmpty(xml)) { return default(T); } using (Stream stream = new MemoryStream()) { var data = Encoding.UTF8.GetBytes(xml); stream.Write( data, 0, data.Length); stream.Position = 0; var deserializer = new DataContractSerializer(typeof(T)); return (T)deserializer.ReadObject(stream); } } /// <summary> /// Generate cryptographically random key of given bit size. /// </summary> /// <param name="size">size of the key to be generated</param> /// <returns>the key</returns> public static string GenerateRandomKey( int size) { var key = new byte[size / 8]; var crypto = new RNGCryptoServiceProvider(); crypto.GetBytes(key); return Convert.ToBase64String(key); } public static List<IPage<T>> GetAllFurtherPages<T>( Func<string, Dictionary<string, List<string>>, CancellationToken, Task<AzureOperationResponse<IPage<T>>>> getNextPage, string NextPageLink, Dictionary<string, List<string>> customHeaders = null) { var result = new List<IPage<T>>(); while ((NextPageLink != null) && (getNextPage != null)) { var page = getNextPage( NextPageLink, customHeaders, default(CancellationToken)) .GetAwaiter() .GetResult() .Body; result.Add(page); NextPageLink = page.NextPageLink; } return result; } /// <summary> /// method to return the Downloads path for the current user. /// </summary> /// <returns>path as string.</returns> public static string GetDefaultPath() { var path = Path.GetTempPath(); return path; } /// <summary> /// Get the name of the member for memberExpression. /// </summary> /// <typeparam name="T">Generic type.</typeparam> /// <param name="memberExpression">Member Expression.</param> /// <returns>Name of the member.</returns> public static string GetMemberName<T>( Expression<Func<T>> memberExpression) { var expressionBody = (MemberExpression)memberExpression.Body; return expressionBody.Member.Name; } /// <summary> /// Returns provider namespace from ARM id. /// </summary> /// <param name="data">ARM Id of the resource.</param> /// <returns>Provider namespace.</returns> public static string GetProviderNameSpaceFromArmId( this string data) { return data.UnFormatArmId(ARMResourceIdPaths.SRSArmUrlPattern)[2]; } public static void GetResourceProviderNamespaceAndType( string resourceId, out string resourceProviderNamespace, out string resourceType) { var armFields = resourceId.Split('/'); var dictionary = new Dictionary<string, string>(); if (armFields.Length % 2 == 0) { throw new Exception("Invalid ARM ID"); } for (var i = 1; i < armFields.Length; i = i + 2) { dictionary.Add( armFields[i], armFields[i + 1]); } resourceProviderNamespace = dictionary[ARMResourceTypeConstants.Providers]; resourceType = dictionary.ContainsKey("SiteRecoveryVault") ? "SiteRecoveryVault" : "RecoveryServicesVault"; } /// <summary> /// Get Value from ARM ID /// </summary> /// <param name="size">size of the key to be generated</param> /// <returns>the key</returns> public static string GetValueFromArmId( string armId, string key) { var armFields = armId.Split('/'); var dictionary = new Dictionary<string, string>(); if (armFields.Length % 2 == 0) { throw new Exception("Invalid ARM ID"); } for (var i = 1; i < armFields.Length; i = i + 2) { dictionary.Add( armFields[i], armFields[i + 1]); } return dictionary[key]; } /// <summary> /// Returns ARM Id of the vault from ARM ID of the contained resource. /// </summary> /// <param name="data">ARM Id of the resource.</param> /// <returns>ARM Id of the vault.</returns> public static string GetVaultArmId( this string data) { return string.Format( ARMResourceIdPaths.SRSArmUrlPattern, data.UnFormatArmId(ARMResourceIdPaths.SRSArmUrlPattern)); } public static List<T> IpageToList<T>( List<IPage<T>> pages) { var result = new List<T>(); foreach (var page in pages) { foreach (var item in page) { result.Add(item); } } return result; } /// <summary> /// Serialize the T as xml using DataContract Serializer /// </summary> /// <typeparam name="T">the type name</typeparam> /// <param name="value">the T object.</param> /// <returns>the serialized object.</returns> [SuppressMessage( "StyleCop.CSharp.DocumentationRules", "SA1650:ElementDocumentationMustBeSpelledCorrectly", Justification = "Reviewed.")] public static string Serialize<T>( T value) { if (value == null) { return null; } string serializedValue; using (var memoryStream = new MemoryStream()) using (var reader = new StreamReader(memoryStream)) { var serializer = new DataContractSerializer(typeof(T)); serializer.WriteObject( memoryStream, value); memoryStream.Position = 0; serializedValue = reader.ReadToEnd(); } return serializedValue; } /// <summary> /// Converts Query object to query string to pass on. /// </summary> /// <param name="queryObject">Query object</param> /// <returns>Qeury string</returns> public static string ToQueryString( this object queryObject) { if (queryObject == null) { return string.Empty; } var objType = queryObject.GetType(); var properties = objType.GetProperties(); var queryString = new StringBuilder(); var propQuery = new List<string>(); foreach (var property in properties) { var propValue = property.GetValue( queryObject, null); if (propValue != null) { // IList is the only one we are handling var elems = propValue as IList; if ((elems != null) && (elems.Count != 0)) { var itemCount = 0; var multiPropQuery = new string[elems.Count]; foreach (var item in elems) { multiPropQuery[itemCount] = new StringBuilder().Append(property.Name) .Append(" eq '") .Append(item) .Append("'") .ToString(); itemCount++; } propQuery.Add( "( " + string.Join( " or ", multiPropQuery) + " )"); } /*Add DateTime, others if required*/ else { if (propValue.ToString() .Contains("Hyak.Common.LazyList")) { // Just skip the property. } else { propQuery.Add( new StringBuilder().Append(property.Name) .Append(" eq '") .Append(propValue) .Append("'") .ToString()); } } } } queryString.Append( string.Join( " and ", propQuery)); return queryString.ToString(); } /// <summary> /// Returns tokens based on format provided. This works on ARM IDs only. /// </summary> /// <param name="data">String to unformat.</param> /// <param name="format">Format reference.</param> /// <returns>Array of string tokens.</returns> public static string[] UnFormatArmId( this string data, string format) { // Creates a new copy of the strings. var dataCopy = string.Copy(data); var processFormat = string.Copy(format); try { var tokens = new List<string>(); var processData = string.Empty; if (string.IsNullOrEmpty(dataCopy)) { throw new Exception( "Null and empty strings are not valid resource Ids - " + data); } // First truncate data string to point from where format string starts. // We start from 1 index so that if url starts with / we avoid picking the first /. var firstTokenEnd = format.IndexOf( "/", 1); var matchIndex = dataCopy.ToLower() .IndexOf( format.Substring( 0, firstTokenEnd) .ToLower()); if (matchIndex == -1) { throw new Exception("Invalid resource Id - " + data); } processData = dataCopy.Substring(matchIndex); var counter = 0; while (true) { var markerStartIndex = processFormat.IndexOf("{" + counter + "}"); if (markerStartIndex == -1) { break; } var markerEndIndex = processData.IndexOf( "/", markerStartIndex); if (markerEndIndex == -1) { tokens.Add(processData.Substring(markerStartIndex)); } else { tokens.Add( processData.Substring( markerStartIndex, markerEndIndex - markerStartIndex)); processData = processData.Substring(markerEndIndex); processFormat = processFormat.Substring(markerStartIndex + 3); } counter++; } // Similar formats like /a/{0}/b/{1} and /c/{0}/d/{1} can return incorrect tokens // therefore, adding another check to ensure that the data is unformatted correctly. if (data.ToLower() .Contains( string.Format( format, tokens.ToArray()) .ToLower())) { return tokens.ToArray(); } throw new Exception("Invalid resource Id - " + data); } catch (Exception ex) { throw new Exception( string.Format( "Invalid resource Id - {0}. Exception - {1} ", data, ex)); } } /// <summary> /// Updates current Vault context. /// </summary> /// <param name="asrVaultCreds">ASR Vault credentials</param> public static void UpdateCurrentVaultContext( ASRVaultCreds asrVaultCreds) { var updateVaultContextOneAtATime = new object(); lock (updateVaultContextOneAtATime) { PSRecoveryServicesClient.asrVaultCreds.ResourceName = asrVaultCreds.ResourceName; PSRecoveryServicesClient.asrVaultCreds.ResourceGroupName = asrVaultCreds.ResourceGroupName; PSRecoveryServicesClient.asrVaultCreds.ChannelIntegrityKey = asrVaultCreds.ChannelIntegrityKey; PSRecoveryServicesClient.asrVaultCreds.ResourceNamespace = asrVaultCreds.ResourceNamespace; PSRecoveryServicesClient.asrVaultCreds.ARMResourceType = asrVaultCreds.ARMResourceType; } } /// <summary> /// Method to write content to a file. /// </summary> /// <typeparam name="T">Class to be serialized</typeparam> /// <param name="fileContent">content to be written to the file</param> /// <param name="filePath">the path where the file is to be created</param> /// <param name="fileName">name of the file to be created</param> /// <returns>file path with file name as string</returns> public static string WriteToFile<T>( T fileContent, string filePath, string fileName) { var fullFileName = Path.Combine( filePath, fileName); using (var file = new StreamWriter( fullFileName, false)) { var contentToWrite = Serialize(fileContent); file.WriteLine(contentToWrite); } return fullFileName; } } /// <summary> /// Custom Convertor for deserializing JSON /// </summary> /// <typeparam name="T"></typeparam> public abstract class JsonCreationConverter<T> : JsonConverter { /// <summary> /// Gets a value indicating whether this Newtonsoft.Json.JsonConverter can write JSON /// </summary> public override bool CanWrite => false; /// <summary> /// Determines whether this instance can convert the specified object type. /// </summary> /// <param name="objectType">Type of the object.</param> /// <returns>true if this instance can convert the specified object type; otherwise, false.</returns> public override bool CanConvert( Type objectType) { return typeof(T).IsAssignableFrom(objectType); } /// <summary> /// Reads the JSON representation of the object. /// </summary> /// <param name="reader">The Newtonsoft.Json.JsonReader to read from.</param> /// <param name="objectType">Type of the object.</param> /// <param name="existingValue">The existing value of object being read.</param> /// <param name="serializer">The calling serializer.</param> /// <returns>the type of object</returns> public override object ReadJson( JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { if (reader.TokenType == JsonToken.Null) { return null; } // Load JObject from stream var jObject = JObject.Load(reader); // Create target object based on JObject var target = this.Create( objectType, jObject); // Populate the object properties serializer.Populate( jObject.CreateReader(), target); return target; } /// <summary> /// Writes the JSON representation of the object. /// </summary> /// <param name="writer">The Newtonsoft.Json.JsonWriter to write to.</param> /// <param name="value">The value.</param> /// <param name="serializer">The calling serializer.</param> public override void WriteJson( JsonWriter writer, object value, JsonSerializer serializer) { throw new NotImplementedException(); } /// <summary> /// Create an instance of objectType, based on properties in the JSON object /// </summary> /// <param name="objectType">Type of the object.</param> /// <param name="jObject">Contents of JSON object that will be deserialized.</param> /// <returns>Returns object of type.</returns> protected abstract T Create( Type objectType, JObject jObject); } /// <summary> /// Custom Convertor for deserializing RecoveryPlanActionDetails(RecoveryPlan) object /// </summary> [JsonConverter(typeof(RecoveryPlanActionDetails))] public class RecoveryPlanActionDetailsConverter : JsonCreationConverter<RecoveryPlanActionDetails> { /// <summary> /// Creates recovery plan action custom details. /// </summary> /// <param name="objectType">Object type.</param> /// <param name="jObject">JSON object that will be deserialized.</param> /// <returns>Returns recovery plan action custom details.</returns> protected override RecoveryPlanActionDetails Create( Type objectType, JObject jObject) { RecoveryPlanActionDetails outputType = null; var actionType = (RecoveryPlanActionDetailsType)Enum.Parse( typeof(RecoveryPlanActionDetailsType), jObject.Value<string>(Constants.InstanceType)); switch (actionType) { case RecoveryPlanActionDetailsType.AutomationRunbookActionDetails: outputType = new RecoveryPlanAutomationRunbookActionDetails(); break; case RecoveryPlanActionDetailsType.ManualActionDetails: outputType = new RecoveryPlanManualActionDetails(); break; case RecoveryPlanActionDetailsType.ScriptActionDetails: outputType = new RecoveryPlanScriptActionDetails(); break; } return outputType; } } /// <summary> /// Recovery Plan Action Types /// </summary> public enum RecoveryPlanActionDetailsType { AutomationRunbookActionDetails, ManualActionDetails, ScriptActionDetails } }
#region Copyright notice and license // Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endregion using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; #if NET35 // Needed for ReadOnlyDictionary, which does not exist in .NET 3.5 using Google.Protobuf.Collections; #endif namespace Google.Protobuf.Reflection { /// <summary> /// Describes a message type. /// </summary> public sealed class MessageDescriptor : DescriptorBase { private static readonly HashSet<string> WellKnownTypeNames = new HashSet<string> { "google/protobuf/any.proto", "google/protobuf/api.proto", "google/protobuf/duration.proto", "google/protobuf/empty.proto", "google/protobuf/wrappers.proto", "google/protobuf/timestamp.proto", "google/protobuf/field_mask.proto", "google/protobuf/source_context.proto", "google/protobuf/struct.proto", "google/protobuf/type.proto", }; private readonly IList<FieldDescriptor> fieldsInDeclarationOrder; private readonly IList<FieldDescriptor> fieldsInNumberOrder; private readonly IDictionary<string, FieldDescriptor> jsonFieldMap; internal MessageDescriptor(DescriptorProto proto, FileDescriptor file, MessageDescriptor parent, int typeIndex, GeneratedClrTypeInfo generatedCodeInfo) : base(file, file.ComputeFullName(parent, proto.Name), typeIndex) { Proto = proto; Parser = generatedCodeInfo?.Parser; ClrType = generatedCodeInfo?.ClrType; ContainingType = parent; // If generatedCodeInfo is null, we just won't generate an accessor for any fields. Oneofs = DescriptorUtil.ConvertAndMakeReadOnly( proto.OneofDecl, (oneof, index) => new OneofDescriptor(oneof, file, this, index, generatedCodeInfo?.OneofNames[index])); NestedTypes = DescriptorUtil.ConvertAndMakeReadOnly( proto.NestedType, (type, index) => new MessageDescriptor(type, file, this, index, generatedCodeInfo?.NestedTypes[index])); EnumTypes = DescriptorUtil.ConvertAndMakeReadOnly( proto.EnumType, (type, index) => new EnumDescriptor(type, file, this, index, generatedCodeInfo?.NestedEnums[index])); Extensions = new ExtensionCollection(this, generatedCodeInfo?.Extensions); fieldsInDeclarationOrder = DescriptorUtil.ConvertAndMakeReadOnly( proto.Field, (field, index) => new FieldDescriptor(field, file, this, index, generatedCodeInfo?.PropertyNames[index], null)); fieldsInNumberOrder = new ReadOnlyCollection<FieldDescriptor>(fieldsInDeclarationOrder.OrderBy(field => field.FieldNumber).ToArray()); // TODO: Use field => field.Proto.JsonName when we're confident it's appropriate. (And then use it in the formatter, too.) jsonFieldMap = CreateJsonFieldMap(fieldsInNumberOrder); file.DescriptorPool.AddSymbol(this); Fields = new FieldCollection(this); } private static ReadOnlyDictionary<string, FieldDescriptor> CreateJsonFieldMap(IList<FieldDescriptor> fields) { var map = new Dictionary<string, FieldDescriptor>(); foreach (var field in fields) { map[field.Name] = field; map[field.JsonName] = field; } return new ReadOnlyDictionary<string, FieldDescriptor>(map); } /// <summary> /// The brief name of the descriptor's target. /// </summary> public override string Name => Proto.Name; internal override IReadOnlyList<DescriptorBase> GetNestedDescriptorListForField(int fieldNumber) { switch (fieldNumber) { case DescriptorProto.FieldFieldNumber: return (IReadOnlyList<DescriptorBase>) fieldsInDeclarationOrder; case DescriptorProto.NestedTypeFieldNumber: return (IReadOnlyList<DescriptorBase>) NestedTypes; case DescriptorProto.EnumTypeFieldNumber: return (IReadOnlyList<DescriptorBase>) EnumTypes; default: return null; } } internal DescriptorProto Proto { get; } /// <summary> /// The CLR type used to represent message instances from this descriptor. /// </summary> /// <remarks> /// <para> /// The value returned by this property will be non-null for all regular fields. However, /// if a message containing a map field is introspected, the list of nested messages will include /// an auto-generated nested key/value pair message for the field. This is not represented in any /// generated type, so this property will return null in such cases. /// </para> /// <para> /// For wrapper types (<see cref="Google.Protobuf.WellKnownTypes.StringValue"/> and the like), the type returned here /// will be the generated message type, not the native type used by reflection for fields of those types. Code /// using reflection should call <see cref="IsWrapperType"/> to determine whether a message descriptor represents /// a wrapper type, and handle the result appropriately. /// </para> /// </remarks> public Type ClrType { get; } /// <summary> /// A parser for this message type. /// </summary> /// <remarks> /// <para> /// As <see cref="MessageDescriptor"/> is not generic, this cannot be statically /// typed to the relevant type, but it should produce objects of a type compatible with <see cref="ClrType"/>. /// </para> /// <para> /// The value returned by this property will be non-null for all regular fields. However, /// if a message containing a map field is introspected, the list of nested messages will include /// an auto-generated nested key/value pair message for the field. No message parser object is created for /// such messages, so this property will return null in such cases. /// </para> /// <para> /// For wrapper types (<see cref="Google.Protobuf.WellKnownTypes.StringValue"/> and the like), the parser returned here /// will be the generated message type, not the native type used by reflection for fields of those types. Code /// using reflection should call <see cref="IsWrapperType"/> to determine whether a message descriptor represents /// a wrapper type, and handle the result appropriately. /// </para> /// </remarks> public MessageParser Parser { get; } /// <summary> /// Returns whether this message is one of the "well known types" which may have runtime/protoc support. /// </summary> internal bool IsWellKnownType => File.Package == "google.protobuf" && WellKnownTypeNames.Contains(File.Name); /// <summary> /// Returns whether this message is one of the "wrapper types" used for fields which represent primitive values /// with the addition of presence. /// </summary> internal bool IsWrapperType => File.Package == "google.protobuf" && File.Name == "google/protobuf/wrappers.proto"; /// <value> /// If this is a nested type, get the outer descriptor, otherwise null. /// </value> public MessageDescriptor ContainingType { get; } /// <value> /// A collection of fields, which can be retrieved by name or field number. /// </value> public FieldCollection Fields { get; } /// <summary> /// An unmodifiable list of extensions defined in this message's scrope /// </summary> public ExtensionCollection Extensions { get; } /// <value> /// An unmodifiable list of this message type's nested types. /// </value> public IList<MessageDescriptor> NestedTypes { get; } /// <value> /// An unmodifiable list of this message type's enum types. /// </value> public IList<EnumDescriptor> EnumTypes { get; } /// <value> /// An unmodifiable list of the "oneof" field collections in this message type. /// </value> public IList<OneofDescriptor> Oneofs { get; } /// <summary> /// Finds a field by field name. /// </summary> /// <param name="name">The unqualified name of the field (e.g. "foo").</param> /// <returns>The field's descriptor, or null if not found.</returns> public FieldDescriptor FindFieldByName(String name) => File.DescriptorPool.FindSymbol<FieldDescriptor>(FullName + "." + name); /// <summary> /// Finds a field by field number. /// </summary> /// <param name="number">The field number within this message type.</param> /// <returns>The field's descriptor, or null if not found.</returns> public FieldDescriptor FindFieldByNumber(int number) => File.DescriptorPool.FindFieldByNumber(this, number); /// <summary> /// Finds a nested descriptor by name. The is valid for fields, nested /// message types, oneofs and enums. /// </summary> /// <param name="name">The unqualified name of the descriptor, e.g. "Foo"</param> /// <returns>The descriptor, or null if not found.</returns> public T FindDescriptor<T>(string name) where T : class, IDescriptor => File.DescriptorPool.FindSymbol<T>(FullName + "." + name); /// <summary> /// The (possibly empty) set of custom options for this message. /// </summary> //[Obsolete("CustomOptions are obsolete. Use GetOption")] public CustomOptions CustomOptions => new CustomOptions(Proto.Options._extensions?.ValuesByNumber); /* // uncomment this in the full proto2 support PR /// <summary> /// Gets a single value enum option for this descriptor /// </summary> public T GetOption<T>(Extension<MessageOptions, T> extension) { var value = Proto.Options.GetExtension(extension); return value is IDeepCloneable<T> clonable ? clonable.Clone() : value; } /// <summary> /// Gets a repeated value enum option for this descriptor /// </summary> public Collections.RepeatedField<T> GetOption<T>(RepeatedExtension<MessageOptions, T> extension) { return Proto.Options.GetExtension(extension).Clone(); } */ /// <summary> /// Looks up and cross-links all fields and nested types. /// </summary> internal void CrossLink() { foreach (MessageDescriptor message in NestedTypes) { message.CrossLink(); } foreach (FieldDescriptor field in fieldsInDeclarationOrder) { field.CrossLink(); } foreach (OneofDescriptor oneof in Oneofs) { oneof.CrossLink(); } Extensions.CrossLink(); } /// <summary> /// A collection to simplify retrieving the field accessor for a particular field. /// </summary> public sealed class FieldCollection { private readonly MessageDescriptor messageDescriptor; internal FieldCollection(MessageDescriptor messageDescriptor) { this.messageDescriptor = messageDescriptor; } /// <value> /// Returns the fields in the message as an immutable list, in the order in which they /// are declared in the source .proto file. /// </value> public IList<FieldDescriptor> InDeclarationOrder() => messageDescriptor.fieldsInDeclarationOrder; /// <value> /// Returns the fields in the message as an immutable list, in ascending field number /// order. Field numbers need not be contiguous, so there is no direct mapping from the /// index in the list to the field number; to retrieve a field by field number, it is better /// to use the <see cref="FieldCollection"/> indexer. /// </value> public IList<FieldDescriptor> InFieldNumberOrder() => messageDescriptor.fieldsInNumberOrder; // TODO: consider making this public in the future. (Being conservative for now...) /// <value> /// Returns a read-only dictionary mapping the field names in this message as they're available /// in the JSON representation to the field descriptors. For example, a field <c>foo_bar</c> /// in the message would result two entries, one with a key <c>fooBar</c> and one with a key /// <c>foo_bar</c>, both referring to the same field. /// </value> internal IDictionary<string, FieldDescriptor> ByJsonName() => messageDescriptor.jsonFieldMap; /// <summary> /// Retrieves the descriptor for the field with the given number. /// </summary> /// <param name="number">Number of the field to retrieve the descriptor for</param> /// <returns>The accessor for the given field</returns> /// <exception cref="KeyNotFoundException">The message descriptor does not contain a field /// with the given number</exception> public FieldDescriptor this[int number] { get { var fieldDescriptor = messageDescriptor.FindFieldByNumber(number); if (fieldDescriptor == null) { throw new KeyNotFoundException("No such field number"); } return fieldDescriptor; } } /// <summary> /// Retrieves the descriptor for the field with the given name. /// </summary> /// <param name="name">Name of the field to retrieve the descriptor for</param> /// <returns>The descriptor for the given field</returns> /// <exception cref="KeyNotFoundException">The message descriptor does not contain a field /// with the given name</exception> public FieldDescriptor this[string name] { get { var fieldDescriptor = messageDescriptor.FindFieldByName(name); if (fieldDescriptor == null) { throw new KeyNotFoundException("No such field name"); } return fieldDescriptor; } } } } }
using System; using System.Collections.Generic; using System.Net.Http; using System.Security.Claims; using System.Security.Cryptography; using System.Threading.Tasks; using System.Web; using System.Web.Http; using System.Web.Http.ModelBinding; using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.EntityFramework; using Microsoft.AspNet.Identity.Owin; using Microsoft.Owin.Security; using Microsoft.Owin.Security.Cookies; using Microsoft.Owin.Security.OAuth; using WebApplication1.Models; using WebApplication1.Providers; using WebApplication1.Results; using System.Linq; using WebApplication1.Filters; namespace WebApplication1.Controllers { [Authorize] [RoutePrefix("api/Account")] public class AccountController : ApiController { private const string LocalLoginProvider = "Local"; private const string DefaultUserRole = "RegisteredUsers"; private ApplicationUserManager _userManager; public AccountController():this(Startup.OAuthOptions.AccessTokenFormat) { } public AccountController(ISecureDataFormat<AuthenticationTicket> accessTokenFormat) { // AccessTokenFormat = accessTokenFormat; } public ApplicationUserManager UserManager { get { return _userManager ?? Request.GetOwinContext().GetUserManager<ApplicationUserManager>(); } private set { _userManager = value; } } public ISecureDataFormat<AuthenticationTicket> AccessTokenFormat { get; private set; } // GET api/Account/UserInfo [HostAuthentication(DefaultAuthenticationTypes.ExternalBearer)] [Route("UserInfo")] public UserInfoViewModel GetUserInfo() { ExternalLoginData externalLogin = ExternalLoginData.FromIdentity(User.Identity as ClaimsIdentity); var roleClaimValues = ((ClaimsIdentity)User.Identity).FindAll(ClaimTypes.Role).Select(c => c.Value); var roles = string.Join(",", roleClaimValues); return new UserInfoViewModel { UserName = User.Identity.GetUserName(), Email = ((ClaimsIdentity) User.Identity).FindFirstValue(ClaimTypes.Email), HasRegistered = externalLogin == null, LoginProvider = externalLogin != null ? externalLogin.LoginProvider : null, UserRoles = roles }; } // POST api/Account/Logout [Route("Logout")] public IHttpActionResult Logout() { Authentication.SignOut(CookieAuthenticationDefaults.AuthenticationType); return Ok(); } // GET api/Account/ManageInfo?returnUrl=%2F&generateState=true [Route("ManageInfo")] public async Task<ManageInfoViewModel> GetManageInfo(string returnUrl, bool generateState = false) { IdentityUser user = await UserManager.FindByIdAsync(User.Identity.GetUserId()); if (user == null) { return null; } List<UserLoginInfoViewModel> logins = new List<UserLoginInfoViewModel>(); foreach (IdentityUserLogin linkedAccount in user.Logins) { logins.Add(new UserLoginInfoViewModel { LoginProvider = linkedAccount.LoginProvider, ProviderKey = linkedAccount.ProviderKey }); } if (user.PasswordHash != null) { logins.Add(new UserLoginInfoViewModel { LoginProvider = LocalLoginProvider, ProviderKey = user.UserName, }); } return new ManageInfoViewModel { LocalLoginProvider = LocalLoginProvider, Email = user.Email, UserName = user.UserName, Logins = logins, ExternalLoginProviders = GetExternalLogins(returnUrl, generateState) }; } // POST api/Account/ChangePassword [Route("ChangePassword")] public async Task<IHttpActionResult> ChangePassword(ChangePasswordBindingModel model) { if (!ModelState.IsValid) { return BadRequest(ModelState); } IdentityResult result = await UserManager.ChangePasswordAsync(User.Identity.GetUserId(), model.OldPassword, model.NewPassword); if (!result.Succeeded) { return GetErrorResult(result); } return Ok(); } // POST api/Account/SetPassword [Route("SetPassword")] public async Task<IHttpActionResult> SetPassword(SetPasswordBindingModel model) { if (!ModelState.IsValid) { return BadRequest(ModelState); } IdentityResult result = await UserManager.AddPasswordAsync(User.Identity.GetUserId(), model.NewPassword); if (!result.Succeeded) { return GetErrorResult(result); } return Ok(); } // POST api/Account/AddExternalLogin [Route("AddExternalLogin")] public async Task<IHttpActionResult> AddExternalLogin(AddExternalLoginBindingModel model) { if (!ModelState.IsValid) { return BadRequest(ModelState); } Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie); AuthenticationTicket ticket = AccessTokenFormat.Unprotect(model.ExternalAccessToken); if (ticket == null || ticket.Identity == null || (ticket.Properties != null && ticket.Properties.ExpiresUtc.HasValue && ticket.Properties.ExpiresUtc.Value < DateTimeOffset.UtcNow)) { return BadRequest("External login failure."); } ExternalLoginData externalData = ExternalLoginData.FromIdentity(ticket.Identity); if (externalData == null) { return BadRequest("The external login is already associated with an account."); } IdentityResult result = await UserManager.AddLoginAsync(User.Identity.GetUserId(), new UserLoginInfo(externalData.LoginProvider, externalData.ProviderKey)); if (!result.Succeeded) { return GetErrorResult(result); } return Ok(); } // POST api/Account/RemoveLogin [Route("RemoveLogin")] public async Task<IHttpActionResult> RemoveLogin(RemoveLoginBindingModel model) { if (!ModelState.IsValid) { return BadRequest(ModelState); } IdentityResult result; if (model.LoginProvider == LocalLoginProvider) { result = await UserManager.RemovePasswordAsync(User.Identity.GetUserId()); } else { result = await UserManager.RemoveLoginAsync(User.Identity.GetUserId(), new UserLoginInfo(model.LoginProvider, model.ProviderKey)); } if (!result.Succeeded) { return GetErrorResult(result); } return Ok(); } // GET api/Account/ExternalLogin [OverrideAuthentication] [HostAuthentication(DefaultAuthenticationTypes.ExternalCookie)] [AllowAnonymous] [Route("ExternalLogin", Name = "ExternalLogin")] public async Task<IHttpActionResult> GetExternalLogin(string provider, string error = null) { if (error != null) { return Redirect(Url.Content("~/") + "#error=" + Uri.EscapeDataString(error)); } if (!User.Identity.IsAuthenticated) { return new ChallengeResult(provider, this); } ExternalLoginData externalLogin = ExternalLoginData.FromIdentity(User.Identity as ClaimsIdentity); if (externalLogin == null) { return InternalServerError(); } if (externalLogin.LoginProvider != provider) { Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie); return new ChallengeResult(provider, this); } ApplicationUser user = await UserManager.FindAsync(new UserLoginInfo(externalLogin.LoginProvider, externalLogin.ProviderKey)); bool hasRegistered = user != null; if (hasRegistered) { Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie); ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(UserManager, OAuthDefaults.AuthenticationType); ClaimsIdentity cookieIdentity = await user.GenerateUserIdentityAsync(UserManager, CookieAuthenticationDefaults.AuthenticationType); AuthenticationProperties properties = ApplicationOAuthProvider.CreateProperties(oAuthIdentity); Authentication.SignIn(properties, oAuthIdentity, cookieIdentity); } else { IEnumerable<Claim> claims = externalLogin.GetClaims(); ClaimsIdentity identity = new ClaimsIdentity(claims, OAuthDefaults.AuthenticationType); Authentication.SignIn(identity); } return Ok(); } // GET api/Account/ExternalLogins?returnUrl=%2F&generateState=true [AllowAnonymous] [Route("ExternalLogins")] public IEnumerable<ExternalLoginViewModel> GetExternalLogins(string returnUrl, bool generateState = false) { IEnumerable<AuthenticationDescription> descriptions = Authentication.GetExternalAuthenticationTypes(); List<ExternalLoginViewModel> logins = new List<ExternalLoginViewModel>(); string state; if (generateState) { const int strengthInBits = 256; state = RandomOAuthStateGenerator.Generate(strengthInBits); } else { state = null; } foreach (AuthenticationDescription description in descriptions) { ExternalLoginViewModel login = new ExternalLoginViewModel { Name = description.Caption, Url = Url.Route("ExternalLogin", new { provider = description.AuthenticationType, response_type = "token", client_id = Startup.PublicClientId, redirect_uri = new Uri(Request.RequestUri, returnUrl).AbsoluteUri, state = state }), State = state }; logins.Add(login); } return logins; } // POST api/Account/Register [AllowAnonymous] [Route("Register")] public async Task<IHttpActionResult> Register(RegisterBindingModel model) { if (!ModelState.IsValid) { return BadRequest(ModelState); } var user = new ApplicationUser() { UserName = model.UserName, Email = model.Email }; IdentityResult result = await UserManager.CreateAsync(user, model.Password); if (!result.Succeeded) { return GetErrorResult(result); } result = await UserManager.AddToRoleAsync(user.Id,DefaultUserRole); if (!result.Succeeded) { return GetErrorResult(result); } return Ok(); } // POST api/Account/RegisterExternal [OverrideAuthentication] [HostAuthentication(DefaultAuthenticationTypes.ExternalBearer)] [Route("RegisterExternal")] public async Task<IHttpActionResult> RegisterExternal(RegisterExternalBindingModel model) { if (!ModelState.IsValid) { return BadRequest(ModelState); } var info = await Authentication.GetExternalLoginInfoAsync(); if (info == null) { return InternalServerError(); } var user = new ApplicationUser() { UserName = model.UserName, Email = model.Email != null ? model.Email : "" }; IdentityResult result = await UserManager.CreateAsync(user); if (!result.Succeeded) { return GetErrorResult(result); } result = await UserManager.AddLoginAsync(user.Id, info.Login); if (!result.Succeeded) { return GetErrorResult(result); } result = await UserManager.AddToRoleAsync(user.Id, DefaultUserRole); if (!result.Succeeded) { return GetErrorResult(result); } return Ok(); } protected override void Dispose(bool disposing) { if (disposing) { UserManager.Dispose(); } base.Dispose(disposing); } #region Helpers private IAuthenticationManager Authentication { get { return Request.GetOwinContext().Authentication; } } private IHttpActionResult GetErrorResult(IdentityResult result) { if (result == null) { return InternalServerError(); } if (!result.Succeeded) { if (result.Errors != null) { foreach (string error in result.Errors) { ModelState.AddModelError("", error); } } if (ModelState.IsValid) { // No ModelState errors are available to send, so just return an empty BadRequest. return BadRequest(); } return BadRequest(ModelState); } return null; } private class ExternalLoginData { public string LoginProvider { get; set; } public string ProviderKey { get; set; } public string UserName { get; set; } public string Email { get; set; } public IList<Claim> GetClaims() { IList<Claim> claims = new List<Claim>(); claims.Add(new Claim(ClaimTypes.NameIdentifier, ProviderKey, null, LoginProvider)); if (UserName != null) { claims.Add(new Claim(ClaimTypes.Name, UserName, null, LoginProvider)); } if (Email != null) { claims.Add(new Claim(ClaimTypes.Email, Email, null, LoginProvider)); } return claims; } public static ExternalLoginData FromIdentity(ClaimsIdentity identity) { if (identity == null) { return null; } Claim providerKeyClaim = identity.FindFirst(ClaimTypes.NameIdentifier); if (providerKeyClaim == null || String.IsNullOrEmpty(providerKeyClaim.Issuer) || String.IsNullOrEmpty(providerKeyClaim.Value)) { return null; } if (providerKeyClaim.Issuer == ClaimsIdentity.DefaultIssuer) { return null; } return new ExternalLoginData { LoginProvider = providerKeyClaim.Issuer, ProviderKey = providerKeyClaim.Value, UserName = identity.FindFirstValue(ClaimTypes.Name), Email = identity.FindFirstValue(ClaimTypes.Email) }; } } private static class RandomOAuthStateGenerator { private static RandomNumberGenerator _random = new RNGCryptoServiceProvider(); public static string Generate(int strengthInBits) { const int bitsPerByte = 8; if (strengthInBits % bitsPerByte != 0) { throw new ArgumentException("strengthInBits must be evenly divisible by 8.", "strengthInBits"); } int strengthInBytes = strengthInBits / bitsPerByte; byte[] data = new byte[strengthInBytes]; _random.GetBytes(data); return HttpServerUtility.UrlTokenEncode(data); } } #endregion } }
// NoteDataXML_GroupEm.cs // // Copyright (c) 2013 - 2014 Brent Knowles (http://www.brentknowles.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. // // Review documentation at http://www.yourothermind.com for updated implementation notes, license updates // or other general information/ // // Author information available at http://www.brentknowles.com or http://www.amazon.com/Brent-Knowles/e/B0035WW7OW // Full source code: https://github.com/BrentKnowles/YourOtherMind //### using System; using CoreUtilities; using System.Windows.Forms; using Storyboards; namespace Layout { public class NoteDataXML_GroupEm : NoteDataXML { #region properties xml bool factmode = false; /// <summary> /// Gets or sets a value indicating whether this <see cref="Layout.NoteDataXML_GroupEm"/> is factmode. /// /// This is used to hide some gui elements when using this Storyboard for Facts Or Search /// </summary> /// <value> /// <c>true</c> if factmode; otherwise, <c>false</c>. /// </value> public bool Factmode { get { return factmode; } set { factmode = value; } } View viewStyle = View.SmallIcon; public View ViewStyle { get{ return viewStyle;} set{viewStyle = value;} } bool storyboard_ShowPreview=false; public bool Storyboard_ShowPreview { get { return storyboard_ShowPreview; } set { storyboard_ShowPreview = value; } } int storyboard_SplitterSetting=0; public int Storyboard_SplitterSetting { get { return storyboard_SplitterSetting; } set { storyboard_SplitterSetting = value; } } #endregion #region gui Storyboard StoryBoard = null; #endregion public NoteDataXML_GroupEm () { } public NoteDataXML_GroupEm (int _height, int _width): base(_height, _width) { } public ListViewGroupCollection GetGroups () { return StoryBoard.Groups; } protected override void DoBuildChildren (LayoutPanelBase Layout) { base.DoBuildChildren (Layout); CaptionLabel.Dock = DockStyle.Top; StoryBoard = new Storyboard(); StoryBoard.Dock = DockStyle.Fill; ParentNotePanel.Controls.Add (StoryBoard); StoryBoard.BringToFront(); StoryBoard.Enter+= (object sender, EventArgs e) => BringToFrontAndShow();; StoryBoard.FactMode(this.Factmode); // // //moved to end to handle refersh issues StoryBoard.Source = this.GuidForNote;//((NotePanelStoryboard)note).groupEms1.Source = note.appearance.GUID; // We do not need to call the SetTable function because this is handled when a table isc reated StoryBoard.StickyTable = this.Layout.GetLinkTable(); StoryBoard.NeedSave += HandleNeedSave; StoryBoard.ViewStyle = this.ViewStyle; /*here*/ if (this.Storyboard_ShowPreview == true) { StoryBoard.ShowPreview(); } if (this.Storyboard_SplitterSetting > 0) { // make it run through autmoated test if (true == StoryBoard.Visible ) { StoryBoard.SplitterPosition = this.Storyboard_SplitterSetting; } } StoryBoard.GetNoteForGroupEmPreview += HandleGetNoteForGroupEmPreview; StoryBoard.GroupNameTruncateLength = 15; StoryBoard.ShowToolbar = true; StoryBoard.AddItemFromMenu += HandleAddItemFromMenu; StoryBoard.ClickItem += HandleStoryBoardClickItem; StoryBoard.InitializeGroupEmFromExternal(); // trying to get htis to work better LayoutDetails.Instance.UpdateAfterLoadList.Add (this); // will not add these unless I NEED them (I'm assuming some of this is for selecting things? // ((NotePanelStoryboard)note).groupEms1.DragNote += new GroupEm.groupEms.CustomEventHandler2(groupEms1_DragNote); // ((NotePanelStoryboard)note).groupEms1.listView.MouseDown += new MouseEventHandler(listView_MouseDown); // ((NotePanelStoryboard)note).groupEms1.listView.onScroll += new ScrollEventHandler(listView_onScroll); // ((NotePanelStoryboard)note).groupEms1.listView.MouseDown += findBar_MouseDown; // } public override void UpdateAfterLoad () { base.UpdateAfterLoad (); StoryBoard.HotFix(); } /// <summary> /// Handles the story board click item. Goes to the note /// </summary> /// <param name='sender'> /// Sender. /// </param> string HandleStoryBoardClickItem (object sender) { string TextToSearchFor = Constants.BLANK; CoreUtilities.Links.LinkTableRecord record = (CoreUtilities.Links.LinkTableRecord)sender; if (record != null) { TextToSearchFor = record.sText; if (TextToSearchFor.IndexOf(";") > -1) { // clean up text TextToSearchFor = TextToSearchFor.Replace("\t", ""); TextToSearchFor = TextToSearchFor.Replace("\n", ""); TextToSearchFor = TextToSearchFor.Replace("\r", ""); // just grab SECOND string of semicolon (first is the number string[] found = TextToSearchFor.Split(new char[1] { ';' }); if (found != null) { TextToSearchFor = found[1]; if (TextToSearchFor == "" && found[0] != "") { TextToSearchFor = found[0]; } } TextToSearchFor = TextToSearchFor.Trim(); } else { TextToSearchFor =Constants.BLANK; } if (General.IsGraphicFile(record.sFileName)) { //NewMessage.Show ("image"); Layout.GetNoteOnSameLayout(record.ExtraField, true); } else Layout.GetNoteOnSameLayout(record.sFileName, true, TextToSearchFor); } return ""; } string HandleAddItemFromMenu (object sender) { // Feb 2013 - Difference between this and old version will be that // instead of storing the data in different ways for different types // we keep it simple. // We store only the GUIDs. // The Display and Open Note (DoubleClick) functions, will have to handle the logic of figuring // out what to do with the GUID -- i.e., showing a picture instead of text // CORRECTION: I stuck with the original way of storing the data to not invalidate old data // so simply we need to extract a CAPTION and GUID and we are off System.Collections.Generic.List<NoteDataInterface> ListOfNotes = new System.Collections.Generic.List<NoteDataInterface>(); ListOfNotes.AddRange(Layout.GetAllNotes().ToArray (typeof(NoteDataInterface)) as NoteDataInterface[]); ListOfNotes.Sort (); LinkPickerForm linkpicker = new LinkPickerForm (LayoutDetails.Instance.MainFormIcon ,ListOfNotes); DialogResult result = linkpicker.ShowDialog (); if (result == DialogResult.OK) { if (linkpicker.GetNote != null) { string sCaption = Constants.BLANK; string sValue = Constants.BLANK; string extraField = Constants.BLANK; int type = 0; linkpicker.GetNote.GetStoryboardData(out sCaption, out sValue, out type, out extraField); StoryBoard.AddItem (sCaption, sValue, type, extraField); // StoryBoard.InitializeGroupEmFromExternal(); } // if (tempPanel != null) { // // testing if a picture // if (tempPanel.appearance.ShapeType == Appearance.shapetype.Picture) { // string sFile = tempPanel.appearance.File; // (sender as GroupEm.groupEms).AddItem (sText, sFile, 1); // } else { // // may 2010 -- tring to get the normal name not the fancy caption // // // add as link // (sender as GroupEm.groupEms).AddItem (tempPanel.appearance.Caption, sValue, 0); // } // // } } return ""; } /// <summary> /// Handles the get note for group em preview. (Is how we grab the required text or whatever from the preview /// </summary> /// <param name='sender'> /// Sender. /// </param> string HandleGetNoteForGroupEmPreview (object sender) { string sResult = ""; string sGUID = sender.ToString(); if (sGUID != null && sGUID != "") { LayoutPanelBase SuperParent = null; if (Layout.GetIsChild == true) SuperParent = Layout.GetAbsoluteParent (); else SuperParent = Layout; NoteDataInterface note = SuperParent.GetNoteOnSameLayout(sGUID, false); //NoteDataInterface note = SuperParent.FindNoteByGuid(sGUID); if (note != null) { if (note is NoteDataXML_LinkNote) { // because the text is stored this should just work sResult =note.GetStoryboardPreview; // if (File.Exists(panel.appearance.File) == true) // { // // Worgan2006.classPageMiddle importPage = // (Worgan2006.classPageMiddle)CoreUtilities.General.DeSerialize(panel.appearance.File, typeof(Worgan2006.classPageMiddle)); // // // // // if (importPage != null) // { // if (importPage.PageType == _Header.pagetype.VISUAL) // { // System.Type t = _Header.GetClassTypeByPageType(importPage.PageType); // importPage = // (Worgan2006.classPageMiddle)CoreUtilities.General.DeSerialize(panel.appearance.File, t); // // } // // sResult = importPage.GetBrainstormText; // if (sResult.IndexOf("rtf") == -1) sResult = ""; // importPage = null; // } // } } else { sResult = note.GetStoryboardPreview; } } } // Message Box.Show(myAppearance.Caption); return sResult; } string HandleNeedSave (object sender) { SetSaveRequired(true); return ""; } public override void Save () { if (StoryBoard != null) { this.ViewStyle = StoryBoard.ViewStyle; this.Storyboard_ShowPreview = StoryBoard.IsPreview; this.Storyboard_SplitterSetting = StoryBoard.SplitterPosition; } base.Save (); } public override string RegisterType () { return Loc.Instance.Cat.GetString("Storyboard"); } protected override void CommonConstructorBehavior () { base.CommonConstructorBehavior (); Caption = Loc.Instance.Cat.GetString("Storyboard"); } public int CountStoryBoardItems() { return StoryBoard.Items.Count; } // so far only being used by test routine public void Refresh() { StoryBoard.InitializeGroupEmFromExternal(); } public void DeleteRecordsForStoryboard () { StoryBoard.DeleteRecordsForStoryboard(); } public void SetFactMode () { Factmode = true; } public void RefreshGroupEm () { StoryBoard.InitializeGroupEmFromExternal(); } public void AddRecordDirectly (string sTitle,string sLinkUrl, string sGroup ) { StoryBoard.AddItemAndToGroup(sTitle, sLinkUrl, 0, sGroup); } public NoteDataXML_GroupEm(NoteDataInterface Note) : base(Note) { } public override void CopyNote (NoteDataInterface Note) { base.CopyNote (Note); } protected override AppearanceClass UpdateAppearance () { AppearanceClass app = base.UpdateAppearance (); if (app != null) { ParentNotePanel.BackColor = app.mainBackground; StoryBoard.ColorControls(app); } return app; } } }
// 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.Fluent; using Microsoft.Azure.Management.ResourceManager.Fluent; using Microsoft.Azure.Management.ResourceManager.Fluent.Core; using Microsoft.Azure.Management.Samples.Common; using Microsoft.Azure.Management.ServiceBus.Fluent; using System; using System.Linq; namespace ServiceBusPublishSubscribeAdvanceFeatures { public class Program { /** * Azure Service Bus basic scenario sample. * - Create namespace. * - Create a service bus subscription in the topic with session and dead-letter enabled. * - Create another subscription in the topic with auto deletion of idle entities. * - Create second topic with new Send Authorization rule, partitioning enabled and a new Service bus Subscription. * - Update second topic to change time for AutoDeleteOnIdle time, without Send rule and with a new manage authorization rule. * - Get the keys from default authorization rule to connect to topic. * - Send a "Hello" message to topic using Data plan sdk for Service Bus. * - Delete a topic * - Delete namespace */ public static void RunSample(IAzure azure) { var rgName = SdkContext.RandomResourceName("rgSB04_", 24); var namespaceName = SdkContext.RandomResourceName("namespace", 20); var topic1Name = SdkContext.RandomResourceName("topic1_", 24); var topic2Name = SdkContext.RandomResourceName("topic2_", 24); var subscription1Name = SdkContext.RandomResourceName("subs_", 24); var subscription2Name = SdkContext.RandomResourceName("subs_", 24); var subscription3Name = SdkContext.RandomResourceName("subs_", 24); var sendRuleName = "SendRule"; var manageRuleName = "ManageRule"; try { //============================================================ // Create a namespace. Utilities.Log("Creating name space " + namespaceName + " in resource group " + rgName + "..."); var serviceBusNamespace = azure.ServiceBusNamespaces .Define(namespaceName) .WithRegion(Region.USWest) .WithNewResourceGroup(rgName) .WithSku(NamespaceSku.PremiumCapacity1) .WithNewTopic(topic1Name, 1024) .Create(); Utilities.Log("Created service bus " + serviceBusNamespace.Name); Utilities.Print(serviceBusNamespace); Utilities.Log("Created topic following topic along with namespace " + namespaceName); var firstTopic = serviceBusNamespace.Topics.GetByName(topic1Name); Utilities.Print(firstTopic); //============================================================ // Create a service bus subscription in the topic with session and dead-letter enabled. Utilities.Log("Creating subscription " + subscription1Name + " in topic " + topic1Name + "..."); var firstSubscription = firstTopic.Subscriptions.Define(subscription1Name) .WithSession() .WithDefaultMessageTTL(TimeSpan.FromMinutes(20)) .WithMessageMovedToDeadLetterSubscriptionOnMaxDeliveryCount(20) .WithExpiredMessageMovedToDeadLetterSubscription() .WithMessageMovedToDeadLetterSubscriptionOnFilterEvaluationException() .Create(); Utilities.Log("Created subscription " + subscription1Name + " in topic " + topic1Name + "..."); Utilities.Print(firstSubscription); //============================================================ // Create another subscription in the topic with auto deletion of idle entities. Utilities.Log("Creating another subscription " + subscription2Name + " in topic " + topic1Name + "..."); var secondSubscription = firstTopic.Subscriptions.Define(subscription2Name) .WithSession() .WithDeleteOnIdleDurationInMinutes(20) .Create(); Utilities.Log("Created subscription " + subscription2Name + " in topic " + topic1Name + "..."); Utilities.Print(secondSubscription); //============================================================ // Create second topic with new Send Authorization rule, partitioning enabled and a new Service bus Subscription. Utilities.Log("Creating second topic " + topic2Name + ", with De-duplication and AutoDeleteOnIdle features..."); var secondTopic = serviceBusNamespace.Topics.Define(topic2Name) .WithNewSendRule(sendRuleName) .WithPartitioning() .WithNewSubscription(subscription3Name) .Create(); Utilities.Log("Created second topic in namespace"); Utilities.Print(secondTopic); Utilities.Log("Creating following authorization rules in second topic "); var authorizationRules = secondTopic.AuthorizationRules.List(); foreach (var authorizationRule in authorizationRules) { Utilities.Print(authorizationRule); } //============================================================ // Update second topic to change time for AutoDeleteOnIdle time, without Send rule and with a new manage authorization rule. Utilities.Log("Updating second topic " + topic2Name + "..."); secondTopic = secondTopic.Update() .WithDeleteOnIdleDurationInMinutes(5) .WithoutAuthorizationRule(sendRuleName) .WithNewManageRule(manageRuleName) .Apply(); Utilities.Log("Updated second topic to change its auto deletion time"); Utilities.Print(secondTopic); Utilities.Log("Updated following authorization rules in second topic, new list of authorization rules are "); authorizationRules = secondTopic.AuthorizationRules.List(); foreach (var authorizationRule in authorizationRules) { Utilities.Print(authorizationRule); } //============================================================= // Get connection string for default authorization rule of namespace var namespaceAuthorizationRules = serviceBusNamespace.AuthorizationRules.List(); Utilities.Log("Number of authorization rule for namespace :" + namespaceAuthorizationRules.Count()); foreach (var namespaceAuthorizationRule in namespaceAuthorizationRules) { Utilities.Print(namespaceAuthorizationRule); } Utilities.Log("Getting keys for authorization rule ..."); var keys = namespaceAuthorizationRules.FirstOrDefault().GetKeys(); Utilities.Print(keys); //============================================================= // Send a message to topic. Utilities.SendMessageToTopic(keys.PrimaryConnectionString, topic1Name, "Hello"); //============================================================= // Delete a topic and namespace Utilities.Log("Deleting topic " + topic1Name + "in namespace " + namespaceName + "..."); serviceBusNamespace.Topics.DeleteByName(topic1Name); Utilities.Log("Deleted topic " + topic1Name + "..."); Utilities.Log("Deleting namespace " + namespaceName + "..."); // This will delete the namespace and topic within it. try { azure.ServiceBusNamespaces.DeleteById(serviceBusNamespace.Id); } catch (Exception) { } Utilities.Log("Deleted namespace " + namespaceName + "..."); } finally { try { Utilities.Log("Deleting Resource Group: " + rgName); azure.ResourceGroups.BeginDeleteByName(rgName); Utilities.Log("Deleted Resource Group: " + rgName); } catch (NullReferenceException) { Utilities.Log("Did not create any resources in Azure. No clean up is necessary"); } catch (Exception g) { Utilities.Log(g); } } } public static void Main(string[] args) { try { //================================================================= // Authenticate var credentials = SdkContext.AzureCredentialsFactory.FromFile(Environment.GetEnvironmentVariable("AZURE_AUTH_LOCATION")); var azure = Azure .Configure() .WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic) .Authenticate(credentials) .WithDefaultSubscription(); // Print selected subscription Utilities.Log("Selected subscription: " + azure.SubscriptionId); RunSample(azure); } catch (Exception e) { Utilities.Log(e.ToString()); } } } }
using System; using System.Text; namespace TSQL.Tokens { public abstract class TSQLToken { internal protected TSQLToken( int beginPosition, string text) { BeginPosition = beginPosition; if (text == null) { throw new ArgumentNullException("text"); } Text = text; } public int BeginPosition { get; private set; } public int EndPosition { get { return BeginPosition + Length - 1; } } public int Length { get { return Text.Length; } } public string Text { get; private set; } public abstract TSQLTokenType Type { get; } public abstract bool IsComplete { get; } public override string ToString() { return $"[Type: {Type}; Text: \"{ToLiteral(Text)}\"; BeginPosition: {BeginPosition: #,##0}; Length: {Length: #,##0}]"; } // https://stackoverflow.com/a/14087738 private static string ToLiteral(string input) { StringBuilder literal = new StringBuilder(input.Length); foreach (var c in input) { switch (c) { case '\'': literal.Append(@"\'"); break; case '\"': literal.Append("\\\""); break; case '\\': literal.Append(@"\\"); break; case '\0': literal.Append(@"\0"); break; case '\a': literal.Append(@"\a"); break; case '\b': literal.Append(@"\b"); break; case '\f': literal.Append(@"\f"); break; case '\n': literal.Append(@"\n"); break; case '\r': literal.Append(@"\r"); break; case '\t': literal.Append(@"\t"); break; case '\v': literal.Append(@"\v"); break; default: // ASCII printable character if (c >= 0x20 && c <= 0x7e) { literal.Append(c); // As UTF16 escaped character } else { literal.Append(@"\u"); literal.Append(((int)c).ToString("x4")); } break; } } return literal.ToString(); } /// <summary> /// Fluent convenience shortcut for casting object /// as <see cref="TSQL.Tokens.TSQLBinaryLiteral"/>. /// </summary> public TSQLBinaryLiteral AsBinaryLiteral { get { return this as TSQLBinaryLiteral; } } /// <summary> /// Fluent convenience shortcut for casting object /// as <see cref="TSQL.Tokens.TSQLCharacter"/>. /// </summary> public TSQLCharacter AsCharacter { get { return this as TSQLCharacter; } } /// <summary> /// Fluent convenience shortcut for casting object /// as <see cref="TSQL.Tokens.TSQLComment"/>. /// </summary> public TSQLComment AsComment { get { return this as TSQLComment; } } /// <summary> /// Fluent convenience shortcut for casting object /// as <see cref="TSQL.Tokens.TSQLIdentifier"/>. /// </summary> public TSQLIdentifier AsIdentifier { get { return this as TSQLIdentifier; } } /// <summary> /// Fluent convenience shortcut for casting object /// as <see cref="TSQL.Tokens.TSQLSystemIdentifier"/>. /// </summary> public TSQLSystemIdentifier AsSystemIdentifier { get { return this as TSQLSystemIdentifier; } } /// <summary> /// Fluent convenience shortcut for casting object /// as <see cref="TSQL.Tokens.TSQLKeyword"/>. /// </summary> public TSQLKeyword AsKeyword { get { return this as TSQLKeyword; } } /// <summary> /// Fluent convenience shortcut for casting object /// as <see cref="TSQL.Tokens.TSQLLiteral"/>. /// </summary> public TSQLLiteral AsLiteral { get { return this as TSQLLiteral; } } /// <summary> /// Fluent convenience shortcut for casting object /// as <see cref="TSQL.Tokens.TSQLMultilineComment"/>. /// </summary> public TSQLMultilineComment AsMultilineComment { get { return this as TSQLMultilineComment; } } /// <summary> /// Fluent convenience shortcut for casting object /// as <see cref="TSQL.Tokens.TSQLNumericLiteral"/>. /// </summary> public TSQLNumericLiteral AsNumericLiteral { get { return this as TSQLNumericLiteral; } } /// <summary> /// Fluent convenience shortcut for casting object /// as <see cref="TSQL.Tokens.TSQLOperator"/>. /// </summary> public TSQLOperator AsOperator { get { return this as TSQLOperator; } } /// <summary> /// Fluent convenience shortcut for casting object /// as <see cref="TSQL.Tokens.TSQLSingleLineComment"/>. /// </summary> public TSQLSingleLineComment AsSingleLineComment { get { return this as TSQLSingleLineComment; } } /// <summary> /// Fluent convenience shortcut for casting object /// as <see cref="TSQL.Tokens.TSQLStringLiteral"/>. /// </summary> public TSQLStringLiteral AsStringLiteral { get { return this as TSQLStringLiteral; } } /// <summary> /// Fluent convenience shortcut for casting object /// as <see cref="TSQL.Tokens.TSQLVariable"/>. /// </summary> public TSQLVariable AsVariable { get { return this as TSQLVariable; } } /// <summary> /// Fluent convenience shortcut for casting object /// as <see cref="TSQL.Tokens.TSQLSystemVariable"/>. /// </summary> public TSQLSystemVariable AsSystemVariable { get { return this as TSQLSystemVariable; } } /// <summary> /// Fluent convenience shortcut for casting object /// as <see cref="TSQL.Tokens.TSQLWhitespace"/>. /// </summary> public TSQLWhitespace AsWhitespace { get { return this as TSQLWhitespace; } } /// <summary> /// Fluent convenience shortcut for casting object /// as <see cref="TSQL.Tokens.TSQLMoneyLiteral"/> /// </summary> public TSQLMoneyLiteral AsMoneyLiteral { get { return this as TSQLMoneyLiteral; } } } public static class TSQLTokenExtensions { public static bool IsKeyword(this TSQLToken token, TSQLKeywords keyword) { if (token == null) { return false; } if (token.Type != TSQLTokenType.Keyword) { return false; } if (token.AsKeyword.Keyword != keyword) { return false; } return true; } public static bool IsCharacter(this TSQLToken token, TSQLCharacters character) { if (token == null) { return false; } if (token.Type != TSQLTokenType.Character) { return false; } if (token.AsCharacter.Character != character) { return false; } return true; } public static bool IsWhitespace(this TSQLToken token) { if (token == null) { return false; } else { return token.Type == TSQLTokenType.Whitespace; } } public static bool IsComment(this TSQLToken token) { if (token == null) { return false; } else { return token.Type == TSQLTokenType.SingleLineComment || token.Type == TSQLTokenType.MultilineComment || token.Type == TSQLTokenType.IncompleteComment; } } public static bool IsFutureKeyword(this TSQLToken token, TSQLFutureKeywords keyword) { if (token == null) { return false; } else { return TSQLFutureKeywords.Parse(token.Text) == keyword; } } } }
/**************************************************************************** Tilde Copyright (c) 2008 Tantalus Media Pty Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ using System; using System.Collections.Generic; using System.Text; using System.Net.Sockets; using System.Threading; using System.IO; using Tilde.LuaDebugger; using Tilde.Framework; namespace Tilde.LuaSocketConnection { /// <summary> /// /// </summary> /// <note> /// Most of the functions in this class should be run from the debugger thread only. The exceptions /// are the constructor which runs in the main thread, and the two socket callback functions which /// are called from a .NET pooled thread. /// </note> public class SocketConnection : IConnection { SocketTransport m_transport; SocketHostInfo m_info; Socket m_socket; // ThreadedTarget m_target; private object m_lock = new Object(); byte[] m_asyncReadBuffer; AutoResetEvent m_asyncConnect; // AutoResetEvent m_asyncDataAvailable; // ReceiveMessageBuffer m_readBuffer; // SendMessageBuffer m_writeBuffer; public SocketConnection(SocketTransport transport, SocketHostInfo info) { m_transport = transport; m_info = info; m_asyncConnect = new AutoResetEvent(false); m_asyncReadBuffer = new byte[512 * 1024]; // m_asyncDataAvailable = new AutoResetEvent(false); // m_readBuffer = new ReceiveMessageBuffer(512 * 1024); // m_writeBuffer = new SendMessageBuffer(4 * 1024); } public event ConnectionClosedEventHandler ConnectionClosed; public event ConnectionAbortedEventHandler ConnectionAborted; public event ConnectionDataReceivedEventHandler DataReceived; public HostInfo HostInfo { get { return m_info; } } public void Send(byte[] buffer, int pos, int len) { lock (m_lock) { m_socket.Send(buffer, pos, len, SocketFlags.None); } } public bool DownloadFile(string fileName) { FileStream stream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read); int len = (int)stream.Length; byte[] buffer = new byte[len]; try { stream.Read(buffer, 0, len); } finally { stream.Close(); } int sendlen = SendMessageBuffer.RoundUp(len, 4); string normName = m_transport.DebugManager.FindTargetFile(fileName); //string normName = PathUtils.NormaliseFileName(fileName, m_transport.DebugManager.Manager.Project.BaseDirectory); TcpClient socket = new TcpClient(m_info.mHost, m_info.mPort + 2); char[] charBuffer = normName.ToCharArray(); byte[] nameBuffer = new byte[charBuffer.Length]; for (int index = 0; index < charBuffer.Length; ++index) nameBuffer[index] = (byte)charBuffer[index]; socket.GetStream().Write(nameBuffer, 0, nameBuffer.Length); socket.GetStream().WriteByte((byte)'\n'); socket.GetStream().Write(buffer, 0, len); socket.Close(); return true; } // This function is called from a pooled thread private static void ConnectCallback(IAsyncResult ar) { SocketConnection connection = (SocketConnection)ar.AsyncState; lock (connection.m_lock) { // if (connection.m_target.IsShutdown) if (connection.m_socket == null) return; try { connection.m_socket.EndConnect(ar); } catch (SocketException /*ex*/) { // connection.m_target.Abort(String.Format("Network connection to {0}:{1} failed!\r\n{2}", connection.m_info.mHost, connection.m_info.mPort, ex.ToString())); // connection.OnConnectionAborted(String.Format("Network connection to {0}:{1} failed!\r\n{2}", connection.m_info.mHost, connection.m_info.mPort, ex.ToString())); connection.m_socket = null; } connection.m_asyncConnect.Set(); } } // This function is called from a pooled thread private static void ReceiveCallback(IAsyncResult ar) { SocketConnection connection = (SocketConnection)ar.AsyncState; lock (connection.m_lock) { // if (connection.m_target.IsShutdown) if (connection.m_socket == null) return; try { // Process any messages received over the socket int bytes = connection.m_socket.EndReceive(ar); // The socket is closed, so don't ask for any more if (bytes == 0) { //connection.m_target.Abort(); connection.OnConnectionClosed(); } else { connection.OnDataReceived(connection.m_asyncReadBuffer, bytes); // connection.m_target.Receive(connection.m_asyncReadBuffer, bytes); // Array.Copy(connection.m_asyncReadBuffer, 0, connection.m_readBuffer.Buffer, connection.m_readBuffer.DataLength, bytes); // connection.m_readBuffer.DataLength += bytes; // connection.m_asyncDataAvailable.Set(); // Start a new asynchronous read // if (!connection.m_target.IsShutdown) connection.m_socket.BeginReceive(connection.m_asyncReadBuffer, 0, connection.m_asyncReadBuffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), connection); } } catch (SocketException ex) { // connection.m_target.Abort(ex.ToString()); connection.OnConnectionAborted(ex.ToString()); } } } public void Connect(/*ThreadedTarget target*/) { lock (m_lock) { // m_target = target; if (m_socket == null) { m_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); // Start an asynchronous connect m_socket.BeginConnect(m_info.mHost, m_info.mPort, new AsyncCallback(ConnectCallback), this); } } } public WaitHandle [] Handles { get { return new WaitHandle[] { m_asyncConnect, /* m_asyncDataAvailable */ }; } } public void OnSignalled(WaitHandle handle) { lock (m_lock) { if (handle == m_asyncConnect) { // Start an asynchronous read if (m_socket != null) m_socket.BeginReceive(m_asyncReadBuffer, 0, m_asyncReadBuffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), this); } /* else if(handle == m_asyncDataAvailable) { // Process any messages that have been sent from the target m_target.ProcessMessages(); } */ } } public void Shutdown() { lock (m_lock) { if (m_socket != null) { if (m_socket.Connected) { m_socket.Shutdown(SocketShutdown.Both); m_socket.Disconnect(false); } m_socket.Close(); m_socket = null; } } } private void OnConnectionClosed() { if (ConnectionClosed != null) ConnectionClosed(this); } private void OnConnectionAborted(string message) { if (ConnectionAborted != null) ConnectionAborted(this, message); } private void OnDataReceived(byte [] buffer, int bytes) { if (DataReceived != null) DataReceived(this, buffer, bytes); } } }
// 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.Globalization; using System.Net.Internals; using System.Net.Sockets; using System.Threading; using System.Threading.Tasks; namespace System.Net { /// <devdoc> /// <para>Provides simple /// domain name resolution functionality.</para> /// </devdoc> public static class Dns { // Host names any longer than this automatically fail at the winsock level. // If the host name is 255 chars, the last char must be a dot. private const int MaxHostName = 255; internal static IPHostEntry InternalGetHostByName(string hostName, bool includeIPv6) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(NetEventSource.ComponentType.Socket, "DNS", "GetHostByName", hostName); IPHostEntry ipHostEntry = null; if (GlobalLog.IsEnabled) { GlobalLog.Print("Dns.GetHostByName: " + hostName); } NameResolutionPal.EnsureSocketsAreInitialized(); if (hostName.Length > MaxHostName // If 255 chars, the last one must be a dot. || hostName.Length == MaxHostName && hostName[MaxHostName - 1] != '.') { throw new ArgumentOutOfRangeException("hostName", SR.Format(SR.net_toolong, "hostName", MaxHostName.ToString(NumberFormatInfo.CurrentInfo))); } // // IPv6 Changes: IPv6 requires the use of getaddrinfo() rather // than the traditional IPv4 gethostbyaddr() / gethostbyname(). // getaddrinfo() is also protocol independant in that it will also // resolve IPv4 names / addresses. As a result, it is the preferred // resolution mechanism on platforms that support it (Windows 5.1+). // If getaddrinfo() is unsupported, IPv6 resolution does not work. // // Consider : If IPv6 is disabled, we could detect IPv6 addresses // and throw an unsupported platform exception. // // Note : Whilst getaddrinfo is available on WinXP+, we only // use it if IPv6 is enabled (platform is part of that // decision). This is done to minimize the number of // possible tests that are needed. // if (includeIPv6 || SocketProtocolSupportPal.OSSupportsIPv6) { // // IPv6 enabled: use getaddrinfo() to obtain DNS information. // int nativeErrorCode; SocketError errorCode = NameResolutionPal.TryGetAddrInfo(hostName, out ipHostEntry, out nativeErrorCode); if (errorCode != SocketError.Success) { throw new InternalSocketException(errorCode, nativeErrorCode); } } else { ipHostEntry = NameResolutionPal.GetHostByName(hostName); } if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(NetEventSource.ComponentType.Socket, "DNS", "GetHostByName", ipHostEntry); return ipHostEntry; } // GetHostByName // Does internal IPAddress reverse and then forward lookups (for Legacy and current public methods). internal static IPHostEntry InternalGetHostByAddress(IPAddress address, bool includeIPv6) { if (GlobalLog.IsEnabled) { GlobalLog.Print("Dns.InternalGetHostByAddress: " + address.ToString()); } // // IPv6 Changes: We need to use the new getnameinfo / getaddrinfo functions // for resolution of IPv6 addresses. // if (SocketProtocolSupportPal.OSSupportsIPv6 || includeIPv6) { // // Try to get the data for the host from it's address // // We need to call getnameinfo first, because getaddrinfo w/ the ipaddress string // will only return that address and not the full list. // Do a reverse lookup to get the host name. SocketError errorCode; int nativeErrorCode; string name = NameResolutionPal.TryGetNameInfo(address, out errorCode, out nativeErrorCode); if (errorCode == SocketError.Success) { // Do the forward lookup to get the IPs for that host name IPHostEntry hostEntry; errorCode = NameResolutionPal.TryGetAddrInfo(name, out hostEntry, out nativeErrorCode); if (errorCode == SocketError.Success) return hostEntry; if (NetEventSource.Log.IsEnabled()) { NetEventSource.Exception(NetEventSource.ComponentType.Socket, "DNS", "InternalGetHostByAddress", new InternalSocketException(errorCode, nativeErrorCode)); } // One of two things happened: // 1. There was a ptr record in dns, but not a corollary A/AAA record. // 2. The IP was a local (non-loopback) IP that resolved to a connection specific dns suffix. // - Workaround, Check "Use this connection's dns suffix in dns registration" on that network // adapter's advanced dns settings. // Just return the resolved host name and no IPs. return hostEntry; } throw new InternalSocketException(errorCode, nativeErrorCode); } // // If IPv6 is not enabled (maybe config switch) but we've been // given an IPv6 address then we need to bail out now. // else { if (address.AddressFamily == AddressFamily.InterNetworkV6) { // // Protocol not supported // throw new SocketException((int)SocketError.ProtocolNotSupported); } // // Use gethostbyaddr() to try to resolve the IP address // // End IPv6 Changes // return NameResolutionPal.GetHostByAddr(address); } } // InternalGetHostByAddress /***************************************************************************** Function : gethostname Abstract: Queries the hostname from DNS Input Parameters: Returns: String ******************************************************************************/ /// <devdoc> /// <para>Gets the host name of the local machine.</para> /// </devdoc> public static string GetHostName() { if (GlobalLog.IsEnabled) { GlobalLog.Print("Dns.GetHostName"); } return NameResolutionPal.GetHostName(); } private class ResolveAsyncResult : ContextAwareResult { // Forward lookup internal ResolveAsyncResult(string hostName, object myObject, bool includeIPv6, object myState, AsyncCallback myCallBack) : base(myObject, myState, myCallBack) { this.hostName = hostName; this.includeIPv6 = includeIPv6; } // Reverse lookup internal ResolveAsyncResult(IPAddress address, object myObject, bool includeIPv6, object myState, AsyncCallback myCallBack) : base(myObject, myState, myCallBack) { this.includeIPv6 = includeIPv6; this.address = address; } internal readonly string hostName; internal bool includeIPv6; internal IPAddress address; } private static void ResolveCallback(object context) { ResolveAsyncResult result = (ResolveAsyncResult)context; IPHostEntry hostEntry; try { if (result.address != null) { hostEntry = InternalGetHostByAddress(result.address, result.includeIPv6); } else { hostEntry = InternalGetHostByName(result.hostName, result.includeIPv6); } } catch (OutOfMemoryException) { throw; } catch (Exception exception) { result.InvokeCallback(exception); return; } result.InvokeCallback(hostEntry); } // Helpers for async GetHostByName, ResolveToAddresses, and Resolve - they're almost identical // If hostName is an IPString and justReturnParsedIP==true then no reverse lookup will be attempted, but the orriginal address is returned. private static IAsyncResult HostResolutionBeginHelper(string hostName, bool justReturnParsedIp, AsyncCallback requestCallback, object state) { if (hostName == null) { throw new ArgumentNullException("hostName"); } if (GlobalLog.IsEnabled) { GlobalLog.Print("Dns.HostResolutionBeginHelper: " + hostName); } // See if it's an IP Address. IPAddress address; ResolveAsyncResult asyncResult; if (IPAddress.TryParse(hostName, out address)) { if ((address.Equals(IPAddress.Any) || address.Equals(IPAddress.IPv6Any))) { throw new ArgumentException(SR.net_invalid_ip_addr, "hostNameOrAddress"); } asyncResult = new ResolveAsyncResult(address, null, true, state, requestCallback); if (justReturnParsedIp) { IPHostEntry hostEntry = NameResolutionUtilities.GetUnresolvedAnswer(address); asyncResult.StartPostingAsyncOp(false); asyncResult.InvokeCallback(hostEntry); asyncResult.FinishPostingAsyncOp(); return asyncResult; } } else { asyncResult = new ResolveAsyncResult(hostName, null, true, state, requestCallback); } // Set up the context, possibly flow. asyncResult.StartPostingAsyncOp(false); // Start the resolve. Task.Factory.StartNew( s => ResolveCallback(s), asyncResult, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); // Finish the flowing, maybe it completed? This does nothing if we didn't initiate the flowing above. asyncResult.FinishPostingAsyncOp(); return asyncResult; } private static IAsyncResult HostResolutionBeginHelper(IPAddress address, bool flowContext, bool includeIPv6, AsyncCallback requestCallback, object state) { if (address == null) { throw new ArgumentNullException("address"); } if (address.Equals(IPAddress.Any) || address.Equals(IPAddress.IPv6Any)) { throw new ArgumentException(SR.net_invalid_ip_addr, "address"); } if (GlobalLog.IsEnabled) { GlobalLog.Print("Dns.HostResolutionBeginHelper: " + address); } // Set up the context, possibly flow. ResolveAsyncResult asyncResult = new ResolveAsyncResult(address, null, includeIPv6, state, requestCallback); if (flowContext) { asyncResult.StartPostingAsyncOp(false); } // Start the resolve. Task.Factory.StartNew( s => ResolveCallback(s), asyncResult, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); // Finish the flowing, maybe it completed? This does nothing if we didn't initiate the flowing above. asyncResult.FinishPostingAsyncOp(); return asyncResult; } private static IPHostEntry HostResolutionEndHelper(IAsyncResult asyncResult) { // // parameter validation // if (asyncResult == null) { throw new ArgumentNullException("asyncResult"); } ResolveAsyncResult castedResult = asyncResult as ResolveAsyncResult; if (castedResult == null) { throw new ArgumentException(SR.net_io_invalidasyncresult, "asyncResult"); } if (castedResult.EndCalled) { throw new InvalidOperationException(SR.Format(SR.net_io_invalidendcall, "EndResolve")); } if (GlobalLog.IsEnabled) { GlobalLog.Print("Dns.HostResolutionEndHelper"); } castedResult.InternalWaitForCompletion(); castedResult.EndCalled = true; Exception exception = castedResult.Result as Exception; if (exception != null) { throw exception; } return (IPHostEntry)castedResult.Result; } private static IAsyncResult BeginGetHostEntry(string hostNameOrAddress, AsyncCallback requestCallback, object stateObject) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(NetEventSource.ComponentType.Socket, "DNS", "BeginGetHostEntry", hostNameOrAddress); IAsyncResult asyncResult = HostResolutionBeginHelper(hostNameOrAddress, false, requestCallback, stateObject); if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(NetEventSource.ComponentType.Socket, "DNS", "BeginGetHostEntry", asyncResult); return asyncResult; } // BeginResolve private static IAsyncResult BeginGetHostEntry(IPAddress address, AsyncCallback requestCallback, object stateObject) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(NetEventSource.ComponentType.Socket, "DNS", "BeginGetHostEntry", address); IAsyncResult asyncResult = HostResolutionBeginHelper(address, true, true, requestCallback, stateObject); if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(NetEventSource.ComponentType.Socket, "DNS", "BeginGetHostEntry", asyncResult); return asyncResult; } // BeginResolve private static IPHostEntry EndGetHostEntry(IAsyncResult asyncResult) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(NetEventSource.ComponentType.Socket, "DNS", "EndGetHostEntry", asyncResult); IPHostEntry ipHostEntry = HostResolutionEndHelper(asyncResult); if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(NetEventSource.ComponentType.Socket, "DNS", "EndGetHostEntry", ipHostEntry); return ipHostEntry; } // EndResolve() private static IAsyncResult BeginGetHostAddresses(string hostNameOrAddress, AsyncCallback requestCallback, object state) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(NetEventSource.ComponentType.Socket, "DNS", "BeginGetHostAddresses", hostNameOrAddress); IAsyncResult asyncResult = HostResolutionBeginHelper(hostNameOrAddress, true, requestCallback, state); if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(NetEventSource.ComponentType.Socket, "DNS", "BeginGetHostAddresses", asyncResult); return asyncResult; } // BeginResolve private static IPAddress[] EndGetHostAddresses(IAsyncResult asyncResult) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Enter(NetEventSource.ComponentType.Socket, "DNS", "EndGetHostAddresses", asyncResult); IPHostEntry ipHostEntry = HostResolutionEndHelper(asyncResult); if (NetEventSource.Log.IsEnabled()) NetEventSource.Exit(NetEventSource.ComponentType.Socket, "DNS", "EndGetHostAddresses", ipHostEntry); return ipHostEntry.AddressList; } // EndResolveToAddresses //************* Task-based async public methods ************************* public static Task<IPAddress[]> GetHostAddressesAsync(string hostNameOrAddress) { return Task<IPAddress[]>.Factory.FromAsync( (arg, requestCallback, stateObject) => BeginGetHostAddresses(arg, requestCallback, stateObject), asyncResult => EndGetHostAddresses(asyncResult), hostNameOrAddress, null); } public static Task<IPHostEntry> GetHostEntryAsync(IPAddress address) { return Task<IPHostEntry>.Factory.FromAsync( (arg, requestCallback, stateObject) => BeginGetHostEntry(arg, requestCallback, stateObject), asyncResult => EndGetHostEntry(asyncResult), address, null); } public static Task<IPHostEntry> GetHostEntryAsync(string hostNameOrAddress) { return Task<IPHostEntry>.Factory.FromAsync( (arg, requestCallback, stateObject) => BeginGetHostEntry(arg, requestCallback, stateObject), asyncResult => EndGetHostEntry(asyncResult), hostNameOrAddress, null); } } }
// 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 gaxgrpc = Google.Api.Gax.Grpc; using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore; using proto = Google.Protobuf; using grpccore = Grpc.Core; using grpcinter = Grpc.Core.Interceptors; using sys = System; using scg = System.Collections.Generic; using sco = System.Collections.ObjectModel; using st = System.Threading; using stt = System.Threading.Tasks; namespace Google.Cloud.AIPlatform.V1 { /// <summary>Settings for <see cref="FeaturestoreOnlineServingServiceClient"/> instances.</summary> public sealed partial class FeaturestoreOnlineServingServiceSettings : gaxgrpc::ServiceSettingsBase { /// <summary>Get a new instance of the default <see cref="FeaturestoreOnlineServingServiceSettings"/>.</summary> /// <returns>A new instance of the default <see cref="FeaturestoreOnlineServingServiceSettings"/>.</returns> public static FeaturestoreOnlineServingServiceSettings GetDefault() => new FeaturestoreOnlineServingServiceSettings(); /// <summary> /// Constructs a new <see cref="FeaturestoreOnlineServingServiceSettings"/> object with default settings. /// </summary> public FeaturestoreOnlineServingServiceSettings() { } private FeaturestoreOnlineServingServiceSettings(FeaturestoreOnlineServingServiceSettings existing) : base(existing) { gax::GaxPreconditions.CheckNotNull(existing, nameof(existing)); ReadFeatureValuesSettings = existing.ReadFeatureValuesSettings; StreamingReadFeatureValuesSettings = existing.StreamingReadFeatureValuesSettings; OnCopy(existing); } partial void OnCopy(FeaturestoreOnlineServingServiceSettings existing); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>FeaturestoreOnlineServingServiceClient.ReadFeatureValues</c> and /// <c>FeaturestoreOnlineServingServiceClient.ReadFeatureValuesAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>This call will not be retried.</description></item> /// <item><description>No timeout is applied.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings ReadFeatureValuesSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.None); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>FeaturestoreOnlineServingServiceClient.StreamingReadFeatureValues</c> and /// <c>FeaturestoreOnlineServingServiceClient.StreamingReadFeatureValuesAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>This call will not be retried.</description></item> /// <item><description>No timeout is applied.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings StreamingReadFeatureValuesSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.None); /// <summary>Creates a deep clone of this object, with all the same property values.</summary> /// <returns>A deep clone of this <see cref="FeaturestoreOnlineServingServiceSettings"/> object.</returns> public FeaturestoreOnlineServingServiceSettings Clone() => new FeaturestoreOnlineServingServiceSettings(this); } /// <summary> /// Builder class for <see cref="FeaturestoreOnlineServingServiceClient"/> to provide simple configuration of /// credentials, endpoint etc. /// </summary> public sealed partial class FeaturestoreOnlineServingServiceClientBuilder : gaxgrpc::ClientBuilderBase<FeaturestoreOnlineServingServiceClient> { /// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary> public FeaturestoreOnlineServingServiceSettings Settings { get; set; } /// <summary>Creates a new builder with default settings.</summary> public FeaturestoreOnlineServingServiceClientBuilder() { UseJwtAccessWithScopes = FeaturestoreOnlineServingServiceClient.UseJwtAccessWithScopes; } partial void InterceptBuild(ref FeaturestoreOnlineServingServiceClient client); partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<FeaturestoreOnlineServingServiceClient> task); /// <summary>Builds the resulting client.</summary> public override FeaturestoreOnlineServingServiceClient Build() { FeaturestoreOnlineServingServiceClient client = null; InterceptBuild(ref client); return client ?? BuildImpl(); } /// <summary>Builds the resulting client asynchronously.</summary> public override stt::Task<FeaturestoreOnlineServingServiceClient> BuildAsync(st::CancellationToken cancellationToken = default) { stt::Task<FeaturestoreOnlineServingServiceClient> task = null; InterceptBuildAsync(cancellationToken, ref task); return task ?? BuildAsyncImpl(cancellationToken); } private FeaturestoreOnlineServingServiceClient BuildImpl() { Validate(); grpccore::CallInvoker callInvoker = CreateCallInvoker(); return FeaturestoreOnlineServingServiceClient.Create(callInvoker, Settings); } private async stt::Task<FeaturestoreOnlineServingServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken) { Validate(); grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false); return FeaturestoreOnlineServingServiceClient.Create(callInvoker, Settings); } /// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary> protected override string GetDefaultEndpoint() => FeaturestoreOnlineServingServiceClient.DefaultEndpoint; /// <summary> /// Returns the default scopes for this builder type, used if no scopes are otherwise specified. /// </summary> protected override scg::IReadOnlyList<string> GetDefaultScopes() => FeaturestoreOnlineServingServiceClient.DefaultScopes; /// <summary>Returns the channel pool to use when no other options are specified.</summary> protected override gaxgrpc::ChannelPool GetChannelPool() => FeaturestoreOnlineServingServiceClient.ChannelPool; /// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary> protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance; } /// <summary>FeaturestoreOnlineServingService client wrapper, for convenient use.</summary> /// <remarks> /// A service for serving online feature values. /// </remarks> public abstract partial class FeaturestoreOnlineServingServiceClient { /// <summary> /// The default endpoint for the FeaturestoreOnlineServingService service, which is a host of /// "aiplatform.googleapis.com" and a port of 443. /// </summary> public static string DefaultEndpoint { get; } = "aiplatform.googleapis.com:443"; /// <summary>The default FeaturestoreOnlineServingService scopes.</summary> /// <remarks> /// The default FeaturestoreOnlineServingService scopes are: /// <list type="bullet"> /// <item><description>https://www.googleapis.com/auth/cloud-platform</description></item> /// </list> /// </remarks> public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[] { "https://www.googleapis.com/auth/cloud-platform", }); internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes); internal static bool UseJwtAccessWithScopes { get { bool useJwtAccessWithScopes = true; MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes); return useJwtAccessWithScopes; } } static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes); /// <summary> /// Asynchronously creates a <see cref="FeaturestoreOnlineServingServiceClient"/> using the default credentials, /// endpoint and settings. To specify custom credentials or other settings, use /// <see cref="FeaturestoreOnlineServingServiceClientBuilder"/>. /// </summary> /// <param name="cancellationToken"> /// The <see cref="st::CancellationToken"/> to use while creating the client. /// </param> /// <returns>The task representing the created <see cref="FeaturestoreOnlineServingServiceClient"/>.</returns> public static stt::Task<FeaturestoreOnlineServingServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) => new FeaturestoreOnlineServingServiceClientBuilder().BuildAsync(cancellationToken); /// <summary> /// Synchronously creates a <see cref="FeaturestoreOnlineServingServiceClient"/> using the default credentials, /// endpoint and settings. To specify custom credentials or other settings, use /// <see cref="FeaturestoreOnlineServingServiceClientBuilder"/>. /// </summary> /// <returns>The created <see cref="FeaturestoreOnlineServingServiceClient"/>.</returns> public static FeaturestoreOnlineServingServiceClient Create() => new FeaturestoreOnlineServingServiceClientBuilder().Build(); /// <summary> /// Creates a <see cref="FeaturestoreOnlineServingServiceClient"/> which uses the specified call invoker for /// remote operations. /// </summary> /// <param name="callInvoker"> /// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null. /// </param> /// <param name="settings">Optional <see cref="FeaturestoreOnlineServingServiceSettings"/>.</param> /// <returns>The created <see cref="FeaturestoreOnlineServingServiceClient"/>.</returns> internal static FeaturestoreOnlineServingServiceClient Create(grpccore::CallInvoker callInvoker, FeaturestoreOnlineServingServiceSettings settings = null) { gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker)); grpcinter::Interceptor interceptor = settings?.Interceptor; if (interceptor != null) { callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor); } FeaturestoreOnlineServingService.FeaturestoreOnlineServingServiceClient grpcClient = new FeaturestoreOnlineServingService.FeaturestoreOnlineServingServiceClient(callInvoker); return new FeaturestoreOnlineServingServiceClientImpl(grpcClient, settings); } /// <summary> /// Shuts down any channels automatically created by <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not /// affected. /// </summary> /// <remarks> /// After calling this method, further calls to <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down /// by another call to this method. /// </remarks> /// <returns>A task representing the asynchronous shutdown operation.</returns> public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync(); /// <summary>The underlying gRPC FeaturestoreOnlineServingService client</summary> public virtual FeaturestoreOnlineServingService.FeaturestoreOnlineServingServiceClient GrpcClient => throw new sys::NotImplementedException(); /// <summary> /// Reads Feature values of a specific entity of an EntityType. For reading /// feature values of multiple entities of an EntityType, please use /// StreamingReadFeatureValues. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual ReadFeatureValuesResponse ReadFeatureValues(ReadFeatureValuesRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Reads Feature values of a specific entity of an EntityType. For reading /// feature values of multiple entities of an EntityType, please use /// StreamingReadFeatureValues. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<ReadFeatureValuesResponse> ReadFeatureValuesAsync(ReadFeatureValuesRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Reads Feature values of a specific entity of an EntityType. For reading /// feature values of multiple entities of an EntityType, please use /// StreamingReadFeatureValues. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<ReadFeatureValuesResponse> ReadFeatureValuesAsync(ReadFeatureValuesRequest request, st::CancellationToken cancellationToken) => ReadFeatureValuesAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Reads Feature values of a specific entity of an EntityType. For reading /// feature values of multiple entities of an EntityType, please use /// StreamingReadFeatureValues. /// </summary> /// <param name="entityType"> /// Required. The resource name of the EntityType for the entity being read. /// Value format: /// `projects/{project}/locations/{location}/featurestores/{featurestore}/entityTypes/{entityType}`. /// For example, for a machine learning model predicting user clicks on a /// website, an EntityType ID could be `user`. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual ReadFeatureValuesResponse ReadFeatureValues(string entityType, gaxgrpc::CallSettings callSettings = null) => ReadFeatureValues(new ReadFeatureValuesRequest { EntityType = gax::GaxPreconditions.CheckNotNullOrEmpty(entityType, nameof(entityType)), }, callSettings); /// <summary> /// Reads Feature values of a specific entity of an EntityType. For reading /// feature values of multiple entities of an EntityType, please use /// StreamingReadFeatureValues. /// </summary> /// <param name="entityType"> /// Required. The resource name of the EntityType for the entity being read. /// Value format: /// `projects/{project}/locations/{location}/featurestores/{featurestore}/entityTypes/{entityType}`. /// For example, for a machine learning model predicting user clicks on a /// website, an EntityType ID could be `user`. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<ReadFeatureValuesResponse> ReadFeatureValuesAsync(string entityType, gaxgrpc::CallSettings callSettings = null) => ReadFeatureValuesAsync(new ReadFeatureValuesRequest { EntityType = gax::GaxPreconditions.CheckNotNullOrEmpty(entityType, nameof(entityType)), }, callSettings); /// <summary> /// Reads Feature values of a specific entity of an EntityType. For reading /// feature values of multiple entities of an EntityType, please use /// StreamingReadFeatureValues. /// </summary> /// <param name="entityType"> /// Required. The resource name of the EntityType for the entity being read. /// Value format: /// `projects/{project}/locations/{location}/featurestores/{featurestore}/entityTypes/{entityType}`. /// For example, for a machine learning model predicting user clicks on a /// website, an EntityType ID could be `user`. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<ReadFeatureValuesResponse> ReadFeatureValuesAsync(string entityType, st::CancellationToken cancellationToken) => ReadFeatureValuesAsync(entityType, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Reads Feature values of a specific entity of an EntityType. For reading /// feature values of multiple entities of an EntityType, please use /// StreamingReadFeatureValues. /// </summary> /// <param name="entityType"> /// Required. The resource name of the EntityType for the entity being read. /// Value format: /// `projects/{project}/locations/{location}/featurestores/{featurestore}/entityTypes/{entityType}`. /// For example, for a machine learning model predicting user clicks on a /// website, an EntityType ID could be `user`. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual ReadFeatureValuesResponse ReadFeatureValues(EntityTypeName entityType, gaxgrpc::CallSettings callSettings = null) => ReadFeatureValues(new ReadFeatureValuesRequest { EntityTypeAsEntityTypeName = gax::GaxPreconditions.CheckNotNull(entityType, nameof(entityType)), }, callSettings); /// <summary> /// Reads Feature values of a specific entity of an EntityType. For reading /// feature values of multiple entities of an EntityType, please use /// StreamingReadFeatureValues. /// </summary> /// <param name="entityType"> /// Required. The resource name of the EntityType for the entity being read. /// Value format: /// `projects/{project}/locations/{location}/featurestores/{featurestore}/entityTypes/{entityType}`. /// For example, for a machine learning model predicting user clicks on a /// website, an EntityType ID could be `user`. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<ReadFeatureValuesResponse> ReadFeatureValuesAsync(EntityTypeName entityType, gaxgrpc::CallSettings callSettings = null) => ReadFeatureValuesAsync(new ReadFeatureValuesRequest { EntityTypeAsEntityTypeName = gax::GaxPreconditions.CheckNotNull(entityType, nameof(entityType)), }, callSettings); /// <summary> /// Reads Feature values of a specific entity of an EntityType. For reading /// feature values of multiple entities of an EntityType, please use /// StreamingReadFeatureValues. /// </summary> /// <param name="entityType"> /// Required. The resource name of the EntityType for the entity being read. /// Value format: /// `projects/{project}/locations/{location}/featurestores/{featurestore}/entityTypes/{entityType}`. /// For example, for a machine learning model predicting user clicks on a /// website, an EntityType ID could be `user`. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<ReadFeatureValuesResponse> ReadFeatureValuesAsync(EntityTypeName entityType, st::CancellationToken cancellationToken) => ReadFeatureValuesAsync(entityType, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Server streaming methods for /// <see cref="StreamingReadFeatureValues(StreamingReadFeatureValuesRequest,gaxgrpc::CallSettings)"/>. /// </summary> public abstract partial class StreamingReadFeatureValuesStream : gaxgrpc::ServerStreamingBase<ReadFeatureValuesResponse> { } /// <summary> /// Reads Feature values for multiple entities. Depending on their size, data /// for different entities may be broken /// up across multiple responses. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The server stream.</returns> public virtual StreamingReadFeatureValuesStream StreamingReadFeatureValues(StreamingReadFeatureValuesRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Reads Feature values for multiple entities. Depending on their size, data /// for different entities may be broken /// up across multiple responses. /// </summary> /// <param name="entityType"> /// Required. The resource name of the entities' type. /// Value format: /// `projects/{project}/locations/{location}/featurestores/{featurestore}/entityTypes/{entityType}`. /// For example, /// for a machine learning model predicting user clicks on a website, an /// EntityType ID could be `user`. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The server stream.</returns> public virtual StreamingReadFeatureValuesStream StreamingReadFeatureValues(string entityType, gaxgrpc::CallSettings callSettings = null) => StreamingReadFeatureValues(new StreamingReadFeatureValuesRequest { EntityType = gax::GaxPreconditions.CheckNotNullOrEmpty(entityType, nameof(entityType)), }, callSettings); /// <summary> /// Reads Feature values for multiple entities. Depending on their size, data /// for different entities may be broken /// up across multiple responses. /// </summary> /// <param name="entityType"> /// Required. The resource name of the entities' type. /// Value format: /// `projects/{project}/locations/{location}/featurestores/{featurestore}/entityTypes/{entityType}`. /// For example, /// for a machine learning model predicting user clicks on a website, an /// EntityType ID could be `user`. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The server stream.</returns> public virtual StreamingReadFeatureValuesStream StreamingReadFeatureValues(EntityTypeName entityType, gaxgrpc::CallSettings callSettings = null) => StreamingReadFeatureValues(new StreamingReadFeatureValuesRequest { EntityTypeAsEntityTypeName = gax::GaxPreconditions.CheckNotNull(entityType, nameof(entityType)), }, callSettings); } /// <summary>FeaturestoreOnlineServingService client wrapper implementation, for convenient use.</summary> /// <remarks> /// A service for serving online feature values. /// </remarks> public sealed partial class FeaturestoreOnlineServingServiceClientImpl : FeaturestoreOnlineServingServiceClient { private readonly gaxgrpc::ApiCall<ReadFeatureValuesRequest, ReadFeatureValuesResponse> _callReadFeatureValues; private readonly gaxgrpc::ApiServerStreamingCall<StreamingReadFeatureValuesRequest, ReadFeatureValuesResponse> _callStreamingReadFeatureValues; /// <summary> /// Constructs a client wrapper for the FeaturestoreOnlineServingService service, with the specified gRPC client /// and settings. /// </summary> /// <param name="grpcClient">The underlying gRPC client.</param> /// <param name="settings"> /// The base <see cref="FeaturestoreOnlineServingServiceSettings"/> used within this client. /// </param> public FeaturestoreOnlineServingServiceClientImpl(FeaturestoreOnlineServingService.FeaturestoreOnlineServingServiceClient grpcClient, FeaturestoreOnlineServingServiceSettings settings) { GrpcClient = grpcClient; FeaturestoreOnlineServingServiceSettings effectiveSettings = settings ?? FeaturestoreOnlineServingServiceSettings.GetDefault(); gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings); _callReadFeatureValues = clientHelper.BuildApiCall<ReadFeatureValuesRequest, ReadFeatureValuesResponse>(grpcClient.ReadFeatureValuesAsync, grpcClient.ReadFeatureValues, effectiveSettings.ReadFeatureValuesSettings).WithGoogleRequestParam("entity_type", request => request.EntityType); Modify_ApiCall(ref _callReadFeatureValues); Modify_ReadFeatureValuesApiCall(ref _callReadFeatureValues); _callStreamingReadFeatureValues = clientHelper.BuildApiCall<StreamingReadFeatureValuesRequest, ReadFeatureValuesResponse>(grpcClient.StreamingReadFeatureValues, effectiveSettings.StreamingReadFeatureValuesSettings).WithGoogleRequestParam("entity_type", request => request.EntityType); Modify_ApiCall(ref _callStreamingReadFeatureValues); Modify_StreamingReadFeatureValuesApiCall(ref _callStreamingReadFeatureValues); OnConstruction(grpcClient, effectiveSettings, clientHelper); } partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>; partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiServerStreamingCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>; partial void Modify_ReadFeatureValuesApiCall(ref gaxgrpc::ApiCall<ReadFeatureValuesRequest, ReadFeatureValuesResponse> call); partial void Modify_StreamingReadFeatureValuesApiCall(ref gaxgrpc::ApiServerStreamingCall<StreamingReadFeatureValuesRequest, ReadFeatureValuesResponse> call); partial void OnConstruction(FeaturestoreOnlineServingService.FeaturestoreOnlineServingServiceClient grpcClient, FeaturestoreOnlineServingServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper); /// <summary>The underlying gRPC FeaturestoreOnlineServingService client</summary> public override FeaturestoreOnlineServingService.FeaturestoreOnlineServingServiceClient GrpcClient { get; } partial void Modify_ReadFeatureValuesRequest(ref ReadFeatureValuesRequest request, ref gaxgrpc::CallSettings settings); partial void Modify_StreamingReadFeatureValuesRequest(ref StreamingReadFeatureValuesRequest request, ref gaxgrpc::CallSettings settings); /// <summary> /// Reads Feature values of a specific entity of an EntityType. For reading /// feature values of multiple entities of an EntityType, please use /// StreamingReadFeatureValues. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public override ReadFeatureValuesResponse ReadFeatureValues(ReadFeatureValuesRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_ReadFeatureValuesRequest(ref request, ref callSettings); return _callReadFeatureValues.Sync(request, callSettings); } /// <summary> /// Reads Feature values of a specific entity of an EntityType. For reading /// feature values of multiple entities of an EntityType, please use /// StreamingReadFeatureValues. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public override stt::Task<ReadFeatureValuesResponse> ReadFeatureValuesAsync(ReadFeatureValuesRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_ReadFeatureValuesRequest(ref request, ref callSettings); return _callReadFeatureValues.Async(request, callSettings); } internal sealed partial class StreamingReadFeatureValuesStreamImpl : StreamingReadFeatureValuesStream { /// <summary>Construct the server streaming method for <c>StreamingReadFeatureValues</c>.</summary> /// <param name="call">The underlying gRPC server streaming call.</param> public StreamingReadFeatureValuesStreamImpl(grpccore::AsyncServerStreamingCall<ReadFeatureValuesResponse> call) => GrpcCall = call; public override grpccore::AsyncServerStreamingCall<ReadFeatureValuesResponse> GrpcCall { get; } } /// <summary> /// Reads Feature values for multiple entities. Depending on their size, data /// for different entities may be broken /// up across multiple responses. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The server stream.</returns> public override FeaturestoreOnlineServingServiceClient.StreamingReadFeatureValuesStream StreamingReadFeatureValues(StreamingReadFeatureValuesRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_StreamingReadFeatureValuesRequest(ref request, ref callSettings); return new StreamingReadFeatureValuesStreamImpl(_callStreamingReadFeatureValues.Call(request, callSettings)); } } }
//********************************************************* // // Copyright (c) Microsoft. All rights reserved. // This code is licensed under the MIT License (MIT). // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. // //********************************************************* using SDKTemplate.Helpers; using SDKTemplate.Models; using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Windows.Media.Core; using Windows.Media.Playback; using Windows.Media.Streaming.Adaptive; using Windows.UI.Core; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Navigation; using Windows.Web.Http; namespace SDKTemplate { /// See the README.md for discussion of this scenario. /// /// Note: We register but do not unregister event handlers in this scenario, see the EventHandler /// scenario for patterns that can be used to clean up. public sealed partial class Scenario4_Tuning : Page { public Scenario4_Tuning() { this.InitializeComponent(); iconInboundBitsPerSecond.Symbol = (Symbol)0xE88A; } protected override void OnNavigatedFrom(NavigationEventArgs e) { ctsForInboundBitsPerSecondUiRefresh.Cancel(); // Cancel timer adaptiveMS = null; // release app instance of AdaptiveMediaSource mpItem = null; // release app instance of MediaPlaybackItem var mp = mediaPlayerElement.MediaPlayer; if (mp != null) { mp.DisposeSource(); mediaPlayerElement.SetMediaPlayer(null); mp.Dispose(); } } CancellationTokenSource ctsForInboundBitsPerSecondUiRefresh = new CancellationTokenSource(); private AdaptiveContentModel adaptiveContentModel; private AdaptiveMediaSource adaptiveMS; private MediaPlaybackItem mpItem; private BitrateHelper bitrateHelper; private async void Page_OnLoaded(object sender, RoutedEventArgs e) { var mediaPlayer = new MediaPlayer(); RegisterForMediaPlayerEvents(mediaPlayer); // Ensure we have PlayReady support, if the user enters a DASH/PR Uri in the text box: var prHelper = new PlayReadyHelper(LoggerControl); prHelper.SetUpProtectionManager(mediaPlayer); mediaPlayerElement.SetMediaPlayer(mediaPlayer); // Choose a default content. SelectedContent.ItemsSource = MainPage.ContentManagementSystemStub.ToArray(); adaptiveContentModel = MainPage.FindContentById(10); SelectedContent.SelectedItem = adaptiveContentModel; UriBox.Text = adaptiveContentModel.ManifestUri.ToString(); await LoadSourceFromUriAsync(adaptiveContentModel.ManifestUri); // There is no InboundBitsPerSecondChanged event, so we start a polling thread to update UI. PollForInboundBitsPerSecond(ctsForInboundBitsPerSecondUiRefresh); } private async void PollForInboundBitsPerSecond(CancellationTokenSource cts) { ulong InboundBitsPerSecondLast = 0; var refreshRate = TimeSpan.FromSeconds(2); while (!cts.IsCancellationRequested) { if (adaptiveMS != null) { if (InboundBitsPerSecondLast != adaptiveMS.InboundBitsPerSecond) { InboundBitsPerSecondLast = adaptiveMS.InboundBitsPerSecond; InboundBitsPerSecondText.Text = InboundBitsPerSecondLast.ToString(); } } await Task.Delay(refreshRate); } } #region Content Loading private void HideDescriptionOnSmallScreen() { // On small screens, hide the description text to make room for the video. DescriptionText.Visibility = (ActualHeight < 700) ? Visibility.Collapsed : Visibility.Visible; } private async void LoadId_Click(object sender, RoutedEventArgs e) { adaptiveContentModel = (AdaptiveContentModel)SelectedContent.SelectedItem; UriBox.Text = adaptiveContentModel.ManifestUri.ToString(); await LoadSourceFromUriAsync(adaptiveContentModel.ManifestUri); } private async void LoadUri_Click(object sender, RoutedEventArgs e) { Uri uri; if (!Uri.TryCreate(UriBox.Text, UriKind.Absolute, out uri)) { Log("Malformed Uri in Load text box."); } await LoadSourceFromUriAsync(uri); HideDescriptionOnSmallScreen(); } private void SetSource_Click(object sender, RoutedEventArgs e) { // It is at this point that the MediaSource (within a MediaPlaybackItem) will be fully resolved. // For an AdaptiveMediaSource, this is the point at which media is first requested and parsed. mediaPlayerElement.Source = mpItem; HideDescriptionOnSmallScreen(); } private async Task LoadSourceFromUriAsync(Uri uri, HttpClient httpClient = null) { mediaPlayerElement.MediaPlayer?.DisposeSource(); AdaptiveMediaSourceCreationResult result = null; if (httpClient != null) { result = await AdaptiveMediaSource.CreateFromUriAsync(uri, httpClient); } else { result = await AdaptiveMediaSource.CreateFromUriAsync(uri); } if (result.Status == AdaptiveMediaSourceCreationStatus.Success) { adaptiveMS = result.MediaSource; bitrateHelper = new BitrateHelper(adaptiveMS.AvailableBitrates); InitializeBitrateLists(adaptiveMS); // At this point, we have read the manifest of the media source, and all bitrates are known. await UpdatePlaybackBitrate(adaptiveMS.CurrentPlaybackBitrate); await UpdateDownloadBitrate(adaptiveMS.CurrentDownloadBitrate); // Register for events before resolving the MediaSource. RegisterForAdaptiveMediaSourceEvents(adaptiveMS); MediaSource source = MediaSource.CreateFromAdaptiveMediaSource(adaptiveMS); // You can save additional information in the CustomPropertySet for future retrieval. // Note: MediaSource.CustomProperties is a ValueSet and therefore can store // only serializable types. // Save the original Uri. source.CustomProperties.Add("uri", uri.ToString()); // You're likely to put a content tracking id into the CustomProperties. source.CustomProperties.Add("contentId", Guid.NewGuid()); mpItem = new MediaPlaybackItem(source); } else { Log("Error creating the AdaptiveMediaSource: " + result.Status); } } #endregion #region MediaPlayer Event Handlers private void RegisterForMediaPlayerEvents(MediaPlayer mediaPlayer) { mediaPlayer.PlaybackSession.NaturalVideoSizeChanged += (sender, args) => Log("PlaybackSession.NaturalVideoSizeChanged, NaturalVideoWidth: " + sender.NaturalVideoWidth + " NaturalVideoHeight: " + sender.NaturalVideoHeight); } #endregion #region Adaptive Bitrate control private void InitializeBitrateLists(AdaptiveMediaSource aMS) { var sortedBitrates = aMS.AvailableBitrates.OrderByDescending(br => br).Select(br => new BitrateItem(br)).ToArray(); InitialBitrateList.ItemsSource = sortedBitrates; var selected = sortedBitrates.First(item => item.Bitrate == aMS.InitialBitrate); InitialBitrateList.SelectedItem = sortedBitrates.FirstOrDefault(item => item.Bitrate == aMS.InitialBitrate); var nullableSortedBitrates = (new BitrateItem[] { new BitrateItem(null) }).Concat(sortedBitrates).ToArray(); DesiredMaxBitrateList.ItemsSource = DesiredMinBitrateList.ItemsSource = nullableSortedBitrates; DesiredMaxBitrateList.SelectedItem = nullableSortedBitrates.First(item => item.Bitrate == aMS.DesiredMaxBitrate); DesiredMinBitrateList.SelectedItem = nullableSortedBitrates.First(item => item.Bitrate == aMS.DesiredMinBitrate); } // An argument exception will be thrown if the following constraint is not met: // DesiredMinBitrate <= InitialBitrate <= DesiredMaxBitrate private bool IsValidBitrateCombination(uint? desiredMinBitrate, uint? desiredMaxBitrate, uint initialBitrate) { // The ">" operator returns false if either operand is null. We take advantage of this // by testing in this manner. Do NOT "optimize" this by reversing the sense of the test // to "return desiredMinBitrate <= initialBitrate && initialBitrate <= desiredMaxBitrate;" if (desiredMinBitrate > initialBitrate || initialBitrate > desiredMaxBitrate) { return false; } return true; } private void InitialBitrateList_SelectionChanged(object sender, SelectionChangedEventArgs e) { var selection = (e.AddedItems.Count > 0) ? (BitrateItem)e.AddedItems[0] : null; if (selection != null && adaptiveMS.InitialBitrate != selection.Bitrate) { if (IsValidBitrateCombination(adaptiveMS.DesiredMinBitrate, adaptiveMS.DesiredMaxBitrate, selection.Bitrate.Value)) { adaptiveMS.InitialBitrate = selection.Bitrate.Value; } else { InitialBitrateList.SelectedItem = e.RemovedItems[0]; } } } private void DesiredMinBitrateList_SelectionChanged(object sender, SelectionChangedEventArgs e) { var selection = (e.AddedItems.Count > 0) ? (BitrateItem)e.AddedItems[0] : null; if (selection != null && adaptiveMS.DesiredMinBitrate != selection.Bitrate) { if (IsValidBitrateCombination(selection.Bitrate, adaptiveMS.DesiredMaxBitrate, adaptiveMS.InitialBitrate)) { adaptiveMS.DesiredMinBitrate = selection.Bitrate; } else { DesiredMinBitrateList.SelectedItem = e.RemovedItems[0]; } } } private void DesiredMaxBitrateList_SelectionChanged(object sender, SelectionChangedEventArgs e) { var selection = (e.AddedItems.Count > 0) ? (BitrateItem)e.AddedItems[0] : null; if (selection != null && adaptiveMS.DesiredMaxBitrate != selection.Bitrate) { if (IsValidBitrateCombination(adaptiveMS.DesiredMinBitrate, selection.Bitrate, adaptiveMS.InitialBitrate)) { adaptiveMS.DesiredMaxBitrate = selection.Bitrate; } else { DesiredMaxBitrateList.SelectedItem = e.RemovedItems[0]; } } } private void SetBitrateDowngradeTriggerRatio_Click() { double ratio; if (double.TryParse(BitrateDowngradeTriggerRatioText.Text, out ratio)) { adaptiveMS.AdvancedSettings.BitrateDowngradeTriggerRatio = ratio; } } private void SetDesiredBitrateHeadroomRatio_Click() { double ratio; if (double.TryParse(BitrateDowngradeTriggerRatioText.Text, out ratio)) { adaptiveMS.AdvancedSettings.DesiredBitrateHeadroomRatio = ratio; } } #endregion #region AdaptiveMediaSource Event Handlers private void RegisterForAdaptiveMediaSourceEvents(AdaptiveMediaSource aMS) { aMS.DownloadFailed += DownloadFailed; aMS.DownloadBitrateChanged += DownloadBitrateChanged; aMS.PlaybackBitrateChanged += PlaybackBitrateChanged; } private void DownloadFailed(AdaptiveMediaSource sender, AdaptiveMediaSourceDownloadFailedEventArgs args) { Log($"DownloadFailed: {args.HttpResponseMessage}, {args.ResourceType}, {args.ResourceUri}"); } private async void DownloadBitrateChanged(AdaptiveMediaSource sender, AdaptiveMediaSourceDownloadBitrateChangedEventArgs args) { uint downloadBitrate = args.NewValue; await UpdateDownloadBitrate(downloadBitrate); } private async Task UpdateDownloadBitrate(uint downloadBitrate) { Log("DownloadBitrateChanged: " + downloadBitrate); await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, new DispatchedHandler(() => { iconDownloadBitrate.Symbol = bitrateHelper.GetBitrateSymbol(downloadBitrate); txtDownloadBitrate.Text = downloadBitrate.ToString(); })); } private async void PlaybackBitrateChanged(AdaptiveMediaSource sender, AdaptiveMediaSourcePlaybackBitrateChangedEventArgs args) { uint playbackBitrate = args.NewValue; await UpdatePlaybackBitrate(playbackBitrate); } private async Task UpdatePlaybackBitrate(uint playbackBitrate) { Log("PlaybackBitrateChanged: " + playbackBitrate); await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, new DispatchedHandler(() => { iconPlaybackBitrate.Symbol = bitrateHelper.GetBitrateSymbol(playbackBitrate); txtPlaybackBitrate.Text = playbackBitrate.ToString(); })); } #endregion #region Utilities private void Log(string message) { LoggerControl.Log(message); } #endregion } /// <summary> /// Item which provides a nicer display name for "null" bitrate. /// </summary> class BitrateItem { public uint? Bitrate { get; private set; } public BitrateItem(uint? bitrate) { Bitrate = bitrate; } public override string ToString() { return (Bitrate == null) ? "Not set" : Bitrate.ToString(); } } }
// // Copyright (c) 2006-2018 Erik Ylvisaker // // 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 Microsoft.Xna.Framework; using System; using YamlDotNet.Serialization; namespace AgateLib.Mathematics.Geometry { /// <summary> /// Replacement for System.Drawing.RectangleF structure. /// </summary> public struct RectangleF { private Vector2 pt; private SizeF sz; /// <summary> /// Constructs a RectangleF. /// </summary> /// <param name="x"></param> /// <param name="y"></param> /// <param name="width"></param> /// <param name="height"></param> public RectangleF(float x, float y, float width, float height) { this.pt = new Vector2(x, y); this.sz = new SizeF(width, height); } /// <summary> /// Construts a RectangleF. /// </summary> /// <param name="pt"></param> /// <param name="sz"></param> public RectangleF(Microsoft.Xna.Framework.Vector2 pt, SizeF sz) { this.pt = pt; this.sz = sz; } public static explicit operator RectangleF(Rectangle r) { return new RectangleF(r.X, r.Y, r.Width, r.Height); } /// <summary> /// Static method which returns a RectangleF with specified left, top, right and bottom. /// </summary> /// <param name="left"></param> /// <param name="top"></param> /// <param name="right"></param> /// <param name="bottom"></param> /// <returns></returns> public static RectangleF FromLTRB(float left, float top, float right, float bottom) { return new RectangleF(left, top, right - left, bottom - top); } /// <summary> /// X value /// </summary> public float X { get => pt.X; set => pt.X = value; } /// <summary> /// Y value /// </summary> public float Y { get => pt.Y; set => pt.Y = value; } /// <summary> /// Width /// </summary> public float Width { get => sz.Width; set => sz.Width = value; } /// <summary> /// Height /// </summary> public float Height { get => sz.Height; set => sz.Height = value; } /// <summary> /// Gets bottom. /// </summary> [YamlIgnore] public float Bottom => pt.Y + sz.Height; /// <summary> /// Gets left. /// </summary> [YamlIgnore] public float Left => pt.X; /// <summary> /// Gets top. /// </summary> [YamlIgnore] public float Top => pt.Y; /// <summary> /// Gets right. /// </summary> [YamlIgnore] public float Right => pt.X + sz.Width; /// <summary> /// Gets or sets top-left point. /// </summary> [YamlIgnore] public Vector2 Location { get => pt; set => pt = value; } /// <summary> /// Gets or sets size. /// </summary> [YamlIgnore] public SizeF Size { get => sz; set => sz = value; } /// <summary> /// Returns true if the RectangleF contains a point. /// </summary> /// <param name="x"></param> /// <param name="y"></param> /// <returns></returns> public bool Contains(float x, float y) { return Contains(new Vector2(x, y)); } /// <summary> /// Returns true if the RectangleF contains a point. /// </summary> /// <param name="pt"></param> /// <returns></returns> public bool Contains(Vector2 pt) { if (pt.X < Left) { return false; } if (pt.Y < Top) { return false; } if (pt.X > Right) { return false; } if (pt.Y > Bottom) { return false; } return true; } /// <summary> /// Returns true if the RectangleF entirely contains the specified RectangleF. /// </summary> /// <param name="rect"></param> /// <returns></returns> public bool Contains(RectangleF rect) { if (Contains(rect.Location) && Contains(Vector2.Add(rect.Location, (Vector2)rect.Size))) { return true; } else { return false; } } #region --- Operator Overloads --- /// <summary> /// Equality comparison test. /// </summary> /// <param name="a"></param> /// <param name="b"></param> /// <returns></returns> public static bool operator ==(RectangleF a, RectangleF b) { return a.Equals(b); } /// <summary> /// Inequality comparison test. /// </summary> /// <param name="a"></param> /// <param name="b"></param> /// <returns></returns> public static bool operator !=(RectangleF a, RectangleF b) { return !a.Equals(b); } /// <summary> /// Conversion to Rectangle structure. /// </summary> /// <param name="r"></param> /// <returns></returns> public static explicit operator Rectangle(RectangleF r) { return new Rectangle((int)r.X, (int)r.Y, (int)r.Width, (int)r.Height); } /// <summary> /// Converts the rectangle to a polygon object. /// </summary> /// <returns></returns> public Polygon ToPolygon() { Polygon result = new Polygon(); WriteToPolygon(result); return result; } /// <summary> /// Writes the rectangle vertices to the polygon. /// </summary> /// <param name="destination"></param> public void WriteToPolygon(Polygon destination) { destination.Points.Count = 4; destination[0] = new Microsoft.Xna.Framework.Vector2(Left, Top); destination[1] = new Microsoft.Xna.Framework.Vector2(Right, Top); destination[2] = new Microsoft.Xna.Framework.Vector2(Right, Bottom); destination[3] = new Microsoft.Xna.Framework.Vector2(Left, Bottom); } #endregion #region --- Object Overrides --- /// <summary> /// Gets a hash code. /// </summary> /// <returns></returns> public override int GetHashCode() { return pt.GetHashCode() ^ sz.GetHashCode(); } /// <summary> /// Creates a string representing this RectangleF. /// </summary> /// <returns></returns> public override string ToString() { return string.Format(System.Globalization.CultureInfo.CurrentCulture, "(X={0},Y={1},Width={2},Height={3})", X, Y, Width, Height); } /// <summary> /// Equality test. /// </summary> /// <param name="obj"></param> /// <returns></returns> public override bool Equals(object obj) { if (obj is RectangleF) { return Equals((RectangleF)obj); } else { return base.Equals(obj); } } /// <summary> /// Equality test. /// </summary> /// <param name="obj"></param> /// <returns></returns> public bool Equals(RectangleF obj) { if (pt == obj.pt && sz == obj.sz) { return true; } else { return false; } } #endregion /// <summary> /// Returns a rectangle contracted by the specified amount. The center of the rectangle remains in the same place, /// so this adds amount to X and Y, and subtracts amount*2 from Width and Height. /// </summary> /// <param name="amount"></param> public RectangleF Contract(float amount) { return Expand(-amount); } /// <summary> /// Returns a rectangle contracted by the specified amount. The center of the rectangle remains in the same place, /// so this adds amount to X and Y, and subtracts amount*2 from Width and Height. /// </summary> /// <param name="amount"></param> public RectangleF Contract(SizeF amount) { return Expand(new SizeF(-amount.Width, -amount.Height)); } /// <summary> /// Returns a rectangle contracted or expanded by the specified amount. /// The center of the rectangle remains in the same place, /// so this subtracts amount to X and Y, and adds amount*2 from Width and Height. /// </summary> /// <param name="amount">The amount to expand the rectangle by. If this value is negative, /// the rectangle is contracted.</param> public RectangleF Expand(float amount) { var result = this; result.X -= amount; result.Y -= amount; result.Width += amount * 2; result.Height += amount * 2; return result; } /// <summary> /// Returns a rectangle contracted or expanded by the specified amount. /// This subtracts amount.Width from X and adds amount.Width * 2 to the rectangle width. /// </summary> /// <param name="amount">The amount to expand the rectangle by. If this value is negative, /// the rectangle is contracted.</param> public RectangleF Expand(SizeF amount) { var result = this; result.X -= amount.Width; result.Y -= amount.Height; result.Width += amount.Width * 2; result.Height += amount.Height * 2; return result; } /// <summary> /// Returns true if this intersects another RectangleF. /// </summary> /// <param name="rect"></param> /// <returns></returns> public bool IntersectsWith(RectangleF rect) { if (this.Left > rect.Right) { return false; } if (rect.Left > this.Right) { return false; } if (this.Top > rect.Bottom) { return false; } if (rect.Top > this.Bottom) { return false; } return true; } /// <summary> /// Returns true if all members of the rectangle are zero. /// </summary> [YamlIgnore] public bool IsEmpty => pt.X == 0 && pt.Y == 0 && sz.IsZero; /// <summary> /// Empty RectangleF /// </summary> public static readonly RectangleF Empty = new RectangleF(0, 0, 0, 0); /// <summary> /// Static method returning the intersection of two RectangleFs. /// </summary> /// <param name="a"></param> /// <param name="b"></param> /// <returns></returns> public static RectangleF Intersection(RectangleF a, RectangleF b) { if (a.IntersectsWith(b)) { return RectangleF.FromLTRB( Math.Max(a.Left, b.Left), Math.Max(a.Top, b.Top), Math.Min(a.Right, b.Right), Math.Min(a.Bottom, b.Bottom)); } else { return Empty; } } [Obsolete("Use RectangleF.Intersection instead.", true)] public static RectangleF Intersect(RectangleF a, RectangleF b) { return Intersection(a, b); } } }
using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.ComponentModel; using System.Globalization; using System.Collections.Generic; using DSL.POS.Facade; using DSL.POS.DTO.DTO; using DSL.POS.BusinessLogicLayer.Interface; using DSL.POS.Common.Utility; public partial class ui_setup_ProductInfo : System.Web.UI.Page { ClsErrorHandle cls = new ClsErrorHandle(); Utility uti = new Utility(); protected void Page_Load(object sender, EventArgs e) { if (!Roles.IsUserInRole(ConfigurationManager.AppSettings["poweruserrolename"])) { Response.Redirect("~/CustomErrorPages/NotAuthorized.aspx"); } if (!IsPostBack) { this.ddlProductCategory.Focus(); this.ddlProductCategory.Attributes.Add("onkeypress", "clickbtn('" + btnClickProductCategory.ClientID + "')"); ddlProductSubCategory.Attributes.Add("onkeypress", "FocusControl_byEnter()"); ddlProductBrand.Attributes.Add("onkeypress", "FocusControl_byEnter()"); txtProductName.Attributes.Add("onkeypress", "FocusControl_byEnter()"); txtStyle.Attributes.Add("onkeypress", "FocusControl_byEnter()"); txtSalesPriceDate.Attributes.Add("onKeyUp", "formatSalesPriceDateField()"); txtCostPriceDate.Attributes.Add("onKeyUp", "formatCostPriceDateField()"); txtSalesPrice.Attributes.Add("onkeypress", "FocusControl_byEnter()"); txtSalesPriceDate.Attributes.Add("onkeypress", "FocusControl_byEnter()"); txtTax.Attributes.Add("onkeypress", "FocusControl_byEnter()"); txtVat.Attributes.Add("onkeypress", "FocusControl_byEnter()"); txtMinLevel.Attributes.Add("onkeypress", "FocusControl_byEnter()"); txtMaxLevel.Attributes.Add("onkeypress", "FocusControl_byEnter()"); txtCostPrice.Attributes.Add("onkeypress", "FocusControl_byEnter()"); txtCostPriceDate.Attributes.Add("onkeypress", "FocusControl_byEnter()"); txtDiscount.Attributes.Add("onkeypress", "FocusControl_byEnter()"); ddlProductUnit.Attributes.Add("onkeypress", "FocusControl_byEnter()"); txtReorderLevel.Attributes.Add("onkeypress", "FocusControl_byEnter()"); txtWarrantyMonth.Attributes.Add("onkeypress", "FocusControl_byEnter()"); chkWarranty.Attributes.Add("onkeypress", "FocusControl_byEnter()"); chkStatus.Attributes.Add("onkeypress", "FocusControl_byEnter()"); try { //Response.Write("it's not"); //this.txtSalesPriceDate.Text = DateTime.Now.ToString("dd/MM/yyyy"); //this.txtCostPriceDate.Text = DateTime.Now.ToString("dd/MM/yyyy"); Facade facade = Facade.GetInstance(); DropDownListCategory(facade); DropDownListSubCategory(facade); DropDownListBrand(facade); DropDownListUnit(facade); } catch (Exception Exp) { lblErrorMessage.Text = cls.ErrorString(Exp); } } else { //Response.Write("not not"); } } private void DropDownListUnit(Facade facade) { IProductUnitBL unitList = facade.GetProductUnitDataList(); List<ProductUnitInfoDTO> oUnitList = unitList.GetProductUnitInfo(); int i = 0; ddlProductUnit.Items.Clear(); ddlProductUnit.Items.Add("(Select any unit)"); this.ddlProductUnit.Items[i].Value = ""; foreach (ProductUnitInfoDTO newDto in oUnitList) { i++; this.ddlProductUnit.Items.Add(newDto.PU_Name); this.ddlProductUnit.Items[i].Value = newDto.PrimaryKey.ToString(); } } private void DropDownListBrand(Facade facade) { IProductBrandBL brandList = facade.GetProductBrandDataList(); List<ProductBrandInfoDTO> oBrandList = brandList.GetProductBrand(); int i = 0; ddlProductBrand.Items.Clear(); ddlProductBrand.Items.Add("(Select any brand)"); this.ddlProductBrand.Items[i].Value = ""; foreach (ProductBrandInfoDTO newDto in oBrandList) { i++; this.ddlProductBrand.Items.Add(newDto.PB_Name); this.ddlProductBrand.Items[i].Value = newDto.PrimaryKey.ToString(); } } private void DropDownListSubCategory(Facade facade) { IProductSubCategoryInfoBL subCategoryList = facade.createProductSubCategoryBL(); List<ProductSubCategoryInfoDTO> oSubCategoryList = subCategoryList.showDataSubCategoryInfo(); int i = 0; ddlProductSubCategory.Items.Clear(); ddlProductSubCategory.Items.Add("(Select any sub category)"); this.ddlProductSubCategory.Items[i].Value = ""; foreach (ProductSubCategoryInfoDTO newDto in oSubCategoryList) { i++; this.ddlProductSubCategory.Items.Add(newDto.PSC_Description); this.ddlProductSubCategory.Items[i].Value = newDto.PrimaryKey.ToString(); } } private void DropDownListCategory(Facade facade) { IProductCategoryBL categoryList = facade.createProductCategoryBL(); List<ProductCategoryInfoDTO> oCategoryList = categoryList.showData(); //uti.DropDownListFillUp(this.ddlProductCategory, dto, oProductCategoryInfoDTOList); int i = 0; ddlProductCategory.Items.Clear(); ddlProductCategory.Items.Add("(Select any category)"); this.ddlProductCategory.Items[i].Value = ""; foreach (ProductCategoryInfoDTO newDto in oCategoryList) { i++; this.ddlProductCategory.Items.Add(newDto.PC_Description); this.ddlProductCategory.Items[i].Value = newDto.PrimaryKey.ToString(); } } protected void btnSave_Click(object sender, EventArgs e) { try { if (this.lblErrorMessage.Text.Length != 0) { this.lblErrorMessage.Text = ""; } ProductInfoDTO pDTO = Populate(); IProductInfoBL facade = Facade.GetInstance().GetPBLImp(); facade.AddProductInfo(pDTO); this.lblErrorMessage.Text = "Data Save Successfully."; this.hfPrimaryKey.Value = ""; this.txtProductCode.Text = ""; this.ddlProductCategory.SelectedValue = ""; this.ddlProductSubCategory.SelectedValue = ""; this.ddlProductBrand.SelectedValue = ""; this.ddlProductUnit.SelectedValue = ""; this.txtProductName.Text = ""; this.txtStyle.Text = ""; this.txtSalesPrice.Text = ""; this.txtSalesPriceDate.Text = ""; this.txtVat.Text = ""; this.txtTax.Text = ""; this.txtMaxLevel.Text = ""; this.txtMinLevel.Text = ""; this.txtCostPrice.Text = ""; this.txtCostPriceDate.Text = ""; this.txtDiscount.Text = ""; this.txtReorderLevel.Text = ""; this.txtWarrantyMonth.Text = ""; this.chkWarranty.Checked = false; this.chkStatus.Checked = false; this.btnSave.Text = "Save"; GridView1.DataBind(); } catch(Exception Exp) { lblErrorMessage.Text = cls.ErrorString(Exp); } } /// <summary> /// All information set in domain class and return an object /// </summary> /// <returns></returns> private ProductInfoDTO Populate() { try { ProductInfoDTO pDTO = new ProductInfoDTO(); if (this.hfPrimaryKey.Value.ToString() != "") { pDTO.PrimaryKey = (Guid)TypeDescriptor.GetConverter(pDTO.PrimaryKey).ConvertFromString(this.hfPrimaryKey.Value); } if (this.ddlProductCategory.SelectedValue == "") { throw new Exception("Invalid category."); } //if (this.ddlProductSubCategory.SelectedValue == "") //{ // throw new Exception("Invalid sub category."); //} //if (this.ddlProductBrand.SelectedValue == "") //{ // throw new Exception("Invalid brand."); //} //if (this.ddlProductUnit.SelectedValue == "") //{ // throw new Exception("Invalid unit."); //} Guid nullGuid = Guid.NewGuid(); nullGuid = (Guid)TypeDescriptor.GetConverter(nullGuid).ConvertFromString("00000000-0000-0000-0000-000000000000"); string strPSC_PK = (string)this.ddlProductSubCategory.SelectedValue; string strPB_PK = (string)this.ddlProductBrand.SelectedValue; string strPU_PK = (string)this.ddlProductUnit.SelectedValue; pDTO.PC_PrimaryKey = (Guid)TypeDescriptor.GetConverter(pDTO.PC_PrimaryKey).ConvertFromString(this.ddlProductCategory.SelectedValue); pDTO.PSC_PrimaryKey = strPSC_PK == string.Empty ? nullGuid :(Guid)TypeDescriptor.GetConverter(pDTO.PSC_PrimaryKey).ConvertFromString(strPSC_PK); pDTO.PB_PrimaryKey = strPB_PK == string.Empty ? nullGuid :(Guid)TypeDescriptor.GetConverter(pDTO.PB_PrimaryKey).ConvertFromString(strPB_PK); pDTO.PU_PrimaryKey = strPU_PK == string.Empty ? nullGuid : (Guid)TypeDescriptor.GetConverter(pDTO.PU_PrimaryKey).ConvertFromString(strPU_PK); pDTO.P_Code = this.txtProductCode.Text; pDTO.P_Name = this.txtProductName.Text; pDTO.P_Style = this.txtStyle.Text; pDTO.P_SalesPrice = this.txtSalesPrice.Text == string.Empty ? 0 : Convert.ToDecimal(this.txtSalesPrice.Text); pDTO.P_CostPrice=this.txtCostPrice.Text==string.Empty ? 0 : Convert.ToDecimal(this.txtCostPrice.Text); pDTO.P_Tax = this.txtTax.Text == string.Empty ? 0 : Convert.ToDecimal(this.txtTax.Text); pDTO.P_VAT = this.txtVat.Text == string.Empty ? 0 : Convert.ToDecimal(this.txtVat.Text); pDTO.P_Discount = this.txtDiscount.Text == string.Empty ? 0 : Convert.ToDecimal(this.txtDiscount.Text); pDTO.P_MinLevel = this.txtMinLevel.Text == string.Empty ? 0 : Convert.ToDecimal(this.txtMinLevel.Text); pDTO.P_MaxLevel = this.txtMaxLevel.Text == string.Empty ? 0 : Convert.ToDecimal(this.txtMaxLevel.Text); pDTO.P_ReorderLevel = this.txtReorderLevel.Text == string.Empty ? 0 : Convert.ToDecimal(this.txtReorderLevel.Text); pDTO.P_Status = this.chkStatus.Checked; pDTO.P_SalesPriceDate = this.txtSalesPriceDate.Text == string.Empty ? DateTime.Now.Date : Convert.ToDateTime(this.txtSalesPriceDate.Text); pDTO.P_CostPriceDate = this.txtCostPriceDate.Text == string.Empty ? DateTime.Now.Date : Convert.ToDateTime(this.txtCostPriceDate.Text); pDTO.P_Warranty = this.chkWarranty.Checked; pDTO.P_WarrantyMonth = this.txtWarrantyMonth.Text==string.Empty ? 0 : Convert.ToInt32(this.txtWarrantyMonth.Text); pDTO.EntryBy = Constants.DEFULT_USER; pDTO.EntryDate = DateTime.Today; return pDTO; } catch(Exception Exp) { throw Exp; } } protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) { //if (e.Row.RowType == DataControlRowType.DataRow) //{ // try // { // Button b = (Button)e.Row.FindControl("Button1"); // b.Attributes.Add("onclick", "javascript:return " + // "confirm('Are you sure you want to delete this record " + // DataBinder.Eval(e.Row.DataItem, "P_Code") + "')"); // } // catch (Exception Exp) // { // lblErrorMessage.Text = cls.ErrorString(Exp); // } //} } protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e) { //try //{ // int index = e.RowIndex; // GridViewRow row = GridView1.Rows[index]; // ProductInfoDTO pDto = new ProductInfoDTO(); // DataKey dk = GridView1.DataKeys[index]; // this.hfPrimaryKey.Value = dk.Value.ToString(); // pDto.PrimaryKey = (Guid)TypeDescriptor.GetConverter(pDto.PrimaryKey).ConvertFromString(this.hfPrimaryKey.Value); // IProductInfoBL facade = Facade.GetInstance().GetPBLImp(); // facade.DelProductInfo(pDto); // this.hfPrimaryKey.Value = ""; // GridView1.DataBind(); //} //catch (Exception Exp) //{ // lblErrorMessage.Text = cls.ErrorString(Exp); //} } protected void GridView1_BeforeEditing(object sender, GridViewEditEventArgs e) { e.Cancel = true; } /// <summary> /// DDLPopulate method set primary key in domain class use for dropdown list Product Category . /// </summary> /// <returns></returns> private ProductInfoDTO DDLPopulate() { try { ProductInfoDTO ddlDTO = new ProductInfoDTO(); if (this.hfPrimaryKey.Value.ToString() != "") { ddlDTO.PrimaryKey = (Guid)TypeDescriptor.GetConverter(ddlDTO.PrimaryKey).ConvertFromString(this.hfPrimaryKey.Value); } if (this.ddlProductCategory.SelectedValue != "") { ddlDTO.PC_PrimaryKey = (Guid)TypeDescriptor.GetConverter(ddlDTO.PC_PrimaryKey).ConvertFromString(this.ddlProductCategory.SelectedValue); } else { return null ; } return ddlDTO; } catch (Exception Exp) { throw Exp; } } protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e) { try { if (e.CommandName == "Edit") { ProductInfoDTO pDto = new ProductInfoDTO(); int index = Convert.ToInt32(e.CommandArgument); GridViewRow row = GridView1.Rows[index]; DataKey dk = GridView1.DataKeys[index]; this.hfPrimaryKey.Value = dk.Value.ToString(); Facade facade = Facade.GetInstance(); DropDownListSubCategory(facade); pDto = facade.GetProductInfoDTO((Guid)TypeDescriptor.GetConverter(pDto.PrimaryKey).ConvertFromString(this.hfPrimaryKey.Value)); this.txtProductCode.Text = pDto.P_Code; this.txtProductName.Text = pDto.P_Name; this.txtStyle.Text = pDto.P_Style; this.txtSalesPrice.Text = pDto.P_SalesPrice.ToString(); this.txtCostPrice.Text = pDto.P_CostPrice.ToString(); this.txtTax.Text = pDto.P_Tax.ToString(); this.txtVat.Text = pDto.P_VAT.ToString(); this.txtDiscount.Text = pDto.P_Discount.ToString(); this.txtMinLevel.Text = pDto.P_MinLevel.ToString(); this.txtMaxLevel.Text = pDto.P_MaxLevel.ToString(); this.txtReorderLevel.Text = pDto.P_ReorderLevel.ToString(); this.chkStatus.Checked = pDto.P_Status; this.txtSalesPriceDate.Text = pDto.P_SalesPriceDate.ToString("MM/dd/yyyy"); this.txtCostPriceDate.Text = pDto.P_CostPriceDate.ToString("MM/dd/yyyy"); this.chkWarranty.Checked = pDto.P_Warranty; this.txtWarrantyMonth.Text = pDto.P_WarrantyMonth.ToString(); this.btnSave.Text = "Update"; ProductCategoryInfoDTO pcDto = new ProductCategoryInfoDTO(); pcDto = facade.GetProductCategoryInfo((Guid)pDto.PC_PrimaryKey); this.ddlProductCategory.SelectedValue = pcDto.PrimaryKey.ToString(); ProductSubCategoryInfoDTO pscDto = new ProductSubCategoryInfoDTO(); pscDto = facade.GetProductsubCategoryInfo((Guid)pDto.PSC_PrimaryKey); if (pscDto.PrimaryKey.ToString() == "00000000-0000-0000-0000-000000000000") { this.ddlProductSubCategory.SelectedValue = ""; } else this.ddlProductSubCategory.SelectedValue = pscDto.PrimaryKey.ToString(); ProductBrandInfoDTO pbDto = new ProductBrandInfoDTO(); pbDto = facade.GetProductBrandInfo((Guid)pDto.PB_PrimaryKey); if (pbDto.PrimaryKey.ToString() == "00000000-0000-0000-0000-000000000000") { this.ddlProductBrand.SelectedValue = ""; } else this.ddlProductBrand.SelectedValue = pbDto.PrimaryKey.ToString(); ProductUnitInfoDTO puDto = new ProductUnitInfoDTO(); puDto = facade.GetProductUnitInfo((Guid)pDto.PU_PrimaryKey); if (puDto.PrimaryKey.ToString() == "00000000-0000-0000-0000-000000000000") { this.ddlProductUnit.SelectedValue = ""; } else this.ddlProductUnit.SelectedValue = puDto.PrimaryKey.ToString(); } } catch (Exception Exp) { lblErrorMessage.Text = cls.ErrorString(Exp); } } protected void btnCancel_Click(object sender, EventArgs e) { Response.Redirect("~\\Default.aspx"); } protected void btnClickProductCategory_Click(object sender, EventArgs e) { try { if (this.ddlProductCategory.SelectedValue == "") { return; } ProductInfoDTO pddlDTO = DDLPopulate(); Facade facade = Facade.GetInstance(); IProductSubCategoryInfoBL subCategoryList = facade.createProductSubCategoryBL(); List<ProductSubCategoryInfoDTO> oArrayList = subCategoryList.showDataSubCategoryInfoByPC(pddlDTO.PC_PrimaryKey); int i = 0; ddlProductSubCategory.Items.Clear(); ddlProductSubCategory.Items.Add("(Select any sub category)"); this.ddlProductSubCategory.Items[i].Value = ""; foreach (ProductSubCategoryInfoDTO newDto in oArrayList) { i++; this.ddlProductSubCategory.Items.Add(newDto.PSC_Description); this.ddlProductSubCategory.Items[i].Value = newDto.PrimaryKey.ToString(); } } catch (Exception exp) { lblErrorMessage.Text = cls.ErrorString(exp); } finally { ScriptManager1.SetFocus(ddlProductSubCategory); } } protected void GridView1_RowDeleted(object sender, GridViewDeletedEventArgs e) { lblErrorMessage.Text = "Data Deleted Successfully"; } }
using System; using System.Collections.Generic; using GitVersion; using NUnit.Framework; using Shouldly; [TestFixture] public class ArgumentParserTests { [Test] public void Empty_means_use_current_directory() { var arguments = ArgumentParser.ParseArguments(""); arguments.TargetPath.ShouldBe(Environment.CurrentDirectory); arguments.LogFilePath.ShouldBe(null); arguments.IsHelp.ShouldBe(false); } [Test] public void Single_means_use_as_target_directory() { var arguments = ArgumentParser.ParseArguments("path"); arguments.TargetPath.ShouldBe("path"); arguments.LogFilePath.ShouldBe(null); arguments.IsHelp.ShouldBe(false); } [Test] public void No_path_and_logfile_should_use_current_directory_TargetDirectory() { var arguments = ArgumentParser.ParseArguments("-l logFilePath"); arguments.TargetPath.ShouldBe(Environment.CurrentDirectory); arguments.LogFilePath.ShouldBe("logFilePath"); arguments.IsHelp.ShouldBe(false); } [Test] public void h_means_IsHelp() { var arguments = ArgumentParser.ParseArguments("-h"); Assert.IsNull(arguments.TargetPath); Assert.IsNull(arguments.LogFilePath); arguments.IsHelp.ShouldBe(true); } [Test] public void exec() { var arguments = ArgumentParser.ParseArguments("-exec rake"); arguments.Exec.ShouldBe("rake"); } [Test] public void exec_with_args() { var arguments = ArgumentParser.ParseArguments(new List<string> { "-exec", "rake", "-execargs", "clean build" }); arguments.Exec.ShouldBe("rake"); arguments.ExecArgs.ShouldBe("clean build"); } [Test] public void msbuild() { var arguments = ArgumentParser.ParseArguments("-proj msbuild.proj"); arguments.Proj.ShouldBe("msbuild.proj"); } [Test] public void msbuild_with_args() { var arguments = ArgumentParser.ParseArguments(new List<string> { "-proj", "msbuild.proj", "-projargs", "/p:Configuration=Debug /p:Platform=AnyCPU" }); arguments.Proj.ShouldBe("msbuild.proj"); arguments.ProjArgs.ShouldBe("/p:Configuration=Debug /p:Platform=AnyCPU"); } [Test] public void execwith_targetdirectory() { var arguments = ArgumentParser.ParseArguments("targetDirectoryPath -exec rake"); arguments.TargetPath.ShouldBe("targetDirectoryPath"); arguments.Exec.ShouldBe("rake"); } [Test] public void TargetDirectory_and_LogFilePath_can_be_parsed() { var arguments = ArgumentParser.ParseArguments("targetDirectoryPath -l logFilePath"); arguments.TargetPath.ShouldBe("targetDirectoryPath"); arguments.LogFilePath.ShouldBe("logFilePath"); arguments.IsHelp.ShouldBe(false); } [Test] public void Username_and_Password_can_be_parsed() { var arguments = ArgumentParser.ParseArguments("targetDirectoryPath -u [username] -p [password]"); arguments.TargetPath.ShouldBe("targetDirectoryPath"); arguments.Authentication.Username.ShouldBe("[username]"); arguments.Authentication.Password.ShouldBe("[password]"); arguments.IsHelp.ShouldBe(false); } [Test] public void Unknown_output_should_throw() { var exception = Assert.Throws<WarningException>(() => ArgumentParser.ParseArguments("targetDirectoryPath -output invalid_value")); exception.Message.ShouldBe("Value 'invalid_value' cannot be parsed as output type, please use 'json' or 'buildserver'"); } [Test] public void Output_defaults_to_json() { var arguments = ArgumentParser.ParseArguments("targetDirectoryPath"); arguments.Output.ShouldBe(OutputType.Json); } [Test] public void Output_json_can_be_parsed() { var arguments = ArgumentParser.ParseArguments("targetDirectoryPath -output json"); arguments.Output.ShouldBe(OutputType.Json); } [Test] public void Output_buildserver_can_be_parsed() { var arguments = ArgumentParser.ParseArguments("targetDirectoryPath -output buildserver"); arguments.Output.ShouldBe(OutputType.BuildServer); } [Test] public void MultipleArgsAndFlag() { var arguments = ArgumentParser.ParseArguments("targetDirectoryPath -output buildserver -updateAssemblyInfo"); arguments.Output.ShouldBe(OutputType.BuildServer); } [Test] public void Url_and_BranchName_can_be_parsed() { var arguments = ArgumentParser.ParseArguments("targetDirectoryPath -url http://github.com/Particular/GitVersion.git -b somebranch"); arguments.TargetPath.ShouldBe("targetDirectoryPath"); arguments.TargetUrl.ShouldBe("http://github.com/Particular/GitVersion.git"); arguments.TargetBranch.ShouldBe("somebranch"); arguments.IsHelp.ShouldBe(false); } [Test] public void Wrong_number_of_arguments_should_throw() { var exception = Assert.Throws<WarningException>(() => ArgumentParser.ParseArguments("targetDirectoryPath -l logFilePath extraArg")); exception.Message.ShouldBe("Could not parse command line parameter 'extraArg'."); } [Test] public void Unknown_argument_should_throw() { var exception = Assert.Throws<WarningException>(() => ArgumentParser.ParseArguments("targetDirectoryPath -x logFilePath")); exception.Message.ShouldBe("Could not parse command line parameter '-x'."); } [TestCase("-updateAssemblyInfo true")] [TestCase("-updateAssemblyInfo 1")] [TestCase("-updateAssemblyInfo")] [TestCase("-updateAssemblyInfo -proj foo.sln")] public void update_assembly_info_true(string command) { var arguments = ArgumentParser.ParseArguments(command); arguments.UpdateAssemblyInfo.ShouldBe(true); } [TestCase("-updateAssemblyInfo false")] [TestCase("-updateAssemblyInfo 0")] public void update_assembly_info_false(string command) { var arguments = ArgumentParser.ParseArguments(command); arguments.UpdateAssemblyInfo.ShouldBe(false); } [Test] public void update_assembly_info_with_filename() { var arguments = ArgumentParser.ParseArguments("-updateAssemblyInfo CommonAssemblyInfo.cs"); arguments.UpdateAssemblyInfo.ShouldBe(true); arguments.UpdateAssemblyInfoFileName.ShouldBe("CommonAssemblyInfo.cs"); } [Test] public void update_assembly_info_with_relative_filename() { var arguments = ArgumentParser.ParseArguments("-updateAssemblyInfo ..\\..\\CommonAssemblyInfo.cs"); arguments.UpdateAssemblyInfo.ShouldBe(true); arguments.UpdateAssemblyInfoFileName.ShouldBe("..\\..\\CommonAssemblyInfo.cs"); } [Test] public void can_log_to_console() { var arguments = ArgumentParser.ParseArguments("-l console -proj foo.sln"); arguments.LogFilePath.ShouldBe("console"); } }
using System; using System.Drawing; using System.Drawing.Drawing2D; using System.Windows.Forms; using System.ComponentModel; namespace WeifenLuo.WinFormsUI.Docking { using WeifenLuo.WinFormsUI.ThemeVS2012Light; internal class VS2012LightDockPaneStrip : DockPaneStripBase { private class TabVS2012Light : Tab { public TabVS2012Light(IDockContent content) : base(content) { } private int m_tabX; public int TabX { get { return m_tabX; } set { m_tabX = value; } } private int m_tabWidth; public int TabWidth { get { return m_tabWidth; } set { m_tabWidth = value; } } private int m_maxWidth; public int MaxWidth { get { return m_maxWidth; } set { m_maxWidth = value; } } private bool m_flag; protected internal bool Flag { get { return m_flag; } set { m_flag = value; } } } protected override Tab CreateTab(IDockContent content) { return new TabVS2012Light(content); } private sealed class InertButton : InertButtonBase { private Bitmap m_image0, m_image1; public InertButton(Bitmap image0, Bitmap image1) : base() { m_image0 = image0; m_image1 = image1; } private int m_imageCategory = 0; public int ImageCategory { get { return m_imageCategory; } set { if (m_imageCategory == value) return; m_imageCategory = value; Invalidate(); } } public override Bitmap Image { get { return ImageCategory == 0 ? m_image0 : m_image1; } } } #region Constants private const int _ToolWindowStripGapTop = 0; private const int _ToolWindowStripGapBottom = 1; private const int _ToolWindowStripGapLeft = 0; private const int _ToolWindowStripGapRight = 0; private const int _ToolWindowImageHeight = 16; private const int _ToolWindowImageWidth = 0;//16; private const int _ToolWindowImageGapTop = 3; private const int _ToolWindowImageGapBottom = 1; private const int _ToolWindowImageGapLeft = 2; private const int _ToolWindowImageGapRight = 0; private const int _ToolWindowTextGapRight = 3; private const int _ToolWindowTabSeperatorGapTop = 3; private const int _ToolWindowTabSeperatorGapBottom = 3; private const int _DocumentStripGapTop = 0; private const int _DocumentStripGapBottom = 0; private const int _DocumentTabMaxWidth = 200; private const int _DocumentButtonGapTop = 3; private const int _DocumentButtonGapBottom = 3; private const int _DocumentButtonGapBetween = 0; private const int _DocumentButtonGapRight = 3; private const int _DocumentTabGapTop = 0;//3; private const int _DocumentTabGapLeft = 0;//3; private const int _DocumentTabGapRight = 0;//3; private const int _DocumentIconGapBottom = 2;//2; private const int _DocumentIconGapLeft = 8; private const int _DocumentIconGapRight = 0; private const int _DocumentIconHeight = 16; private const int _DocumentIconWidth = 16; private const int _DocumentTextGapRight = 6; #endregion #region Members private ContextMenuStrip m_selectMenu; private static Bitmap m_imageButtonClose; private InertButton m_buttonClose; private static Bitmap m_imageButtonWindowList; private static Bitmap m_imageButtonWindowListOverflow; private InertButton m_buttonWindowList; private IContainer m_components; private ToolTip m_toolTip; private Font m_font; private Font m_boldFont; private int m_startDisplayingTab = 0; private int m_endDisplayingTab = 0; private int m_firstDisplayingTab = 0; private bool m_documentTabsOverflow = false; private static string m_toolTipSelect; private static string m_toolTipClose; private bool m_closeButtonVisible = false; private Rectangle _activeClose; private int _selectMenuMargin = 5; #endregion #region Properties private Rectangle TabStripRectangle { get { if (Appearance == DockPane.AppearanceStyle.Document) return TabStripRectangle_Document; else return TabStripRectangle_ToolWindow; } } private Rectangle TabStripRectangle_ToolWindow { get { Rectangle rect = ClientRectangle; return new Rectangle(rect.X, rect.Top + ToolWindowStripGapTop, rect.Width, rect.Height - ToolWindowStripGapTop - ToolWindowStripGapBottom); } } private Rectangle TabStripRectangle_Document { get { Rectangle rect = ClientRectangle; return new Rectangle(rect.X, rect.Top + DocumentStripGapTop, rect.Width, rect.Height + DocumentStripGapTop - ToolWindowStripGapBottom); } } private Rectangle TabsRectangle { get { if (Appearance == DockPane.AppearanceStyle.ToolWindow) return TabStripRectangle; Rectangle rectWindow = TabStripRectangle; int x = rectWindow.X; int y = rectWindow.Y; int width = rectWindow.Width; int height = rectWindow.Height; x += DocumentTabGapLeft; width -= DocumentTabGapLeft + DocumentTabGapRight + DocumentButtonGapRight + ButtonClose.Width + ButtonWindowList.Width + 2 * DocumentButtonGapBetween; return new Rectangle(x, y, width, height); } } private ContextMenuStrip SelectMenu { get { return m_selectMenu; } } public int SelectMenuMargin { get { return _selectMenuMargin; } set { _selectMenuMargin = value; } } private static Bitmap ImageButtonClose { get { if (m_imageButtonClose == null) m_imageButtonClose = Resources.DockPane_Close; return m_imageButtonClose; } } private InertButton ButtonClose { get { if (m_buttonClose == null) { m_buttonClose = new InertButton(ImageButtonClose, ImageButtonClose); m_toolTip.SetToolTip(m_buttonClose, ToolTipClose); m_buttonClose.Click += new EventHandler(Close_Click); Controls.Add(m_buttonClose); } return m_buttonClose; } } private static Bitmap ImageButtonWindowList { get { if (m_imageButtonWindowList == null) m_imageButtonWindowList = Resources.DockPane_Option; return m_imageButtonWindowList; } } private static Bitmap ImageButtonWindowListOverflow { get { if (m_imageButtonWindowListOverflow == null) m_imageButtonWindowListOverflow = Resources.DockPane_OptionOverflow; return m_imageButtonWindowListOverflow; } } private InertButton ButtonWindowList { get { if (m_buttonWindowList == null) { m_buttonWindowList = new InertButton(ImageButtonWindowList, ImageButtonWindowListOverflow); m_toolTip.SetToolTip(m_buttonWindowList, ToolTipSelect); m_buttonWindowList.Click += new EventHandler(WindowList_Click); Controls.Add(m_buttonWindowList); } return m_buttonWindowList; } } private static GraphicsPath GraphicsPath { get { return VS2012LightAutoHideStrip.GraphicsPath; } } private IContainer Components { get { return m_components; } } public Font TextFont { get { return DockPane.DockPanel.Skin.DockPaneStripSkin.TextFont; } } private Font BoldFont { get { if (IsDisposed) return null; if (m_boldFont == null) { m_font = TextFont; m_boldFont = new Font(TextFont, FontStyle.Bold); } else if (m_font != TextFont) { m_boldFont.Dispose(); m_font = TextFont; m_boldFont = new Font(TextFont, FontStyle.Bold); } return m_boldFont; } } private int StartDisplayingTab { get { return m_startDisplayingTab; } set { m_startDisplayingTab = value; Invalidate(); } } private int EndDisplayingTab { get { return m_endDisplayingTab; } set { m_endDisplayingTab = value; } } private int FirstDisplayingTab { get { return m_firstDisplayingTab; } set { m_firstDisplayingTab = value; } } private bool DocumentTabsOverflow { set { if (m_documentTabsOverflow == value) return; m_documentTabsOverflow = value; if (value) ButtonWindowList.ImageCategory = 1; else ButtonWindowList.ImageCategory = 0; } } #region Customizable Properties private static int ToolWindowStripGapTop { get { return _ToolWindowStripGapTop; } } private static int ToolWindowStripGapBottom { get { return _ToolWindowStripGapBottom; } } private static int ToolWindowStripGapLeft { get { return _ToolWindowStripGapLeft; } } private static int ToolWindowStripGapRight { get { return _ToolWindowStripGapRight; } } private static int ToolWindowImageHeight { get { return _ToolWindowImageHeight; } } private static int ToolWindowImageWidth { get { return _ToolWindowImageWidth; } } private static int ToolWindowImageGapTop { get { return _ToolWindowImageGapTop; } } private static int ToolWindowImageGapBottom { get { return _ToolWindowImageGapBottom; } } private static int ToolWindowImageGapLeft { get { return _ToolWindowImageGapLeft; } } private static int ToolWindowImageGapRight { get { return _ToolWindowImageGapRight; } } private static int ToolWindowTextGapRight { get { return _ToolWindowTextGapRight; } } private static int ToolWindowTabSeperatorGapTop { get { return _ToolWindowTabSeperatorGapTop; } } private static int ToolWindowTabSeperatorGapBottom { get { return _ToolWindowTabSeperatorGapBottom; } } private static string ToolTipClose { get { if (m_toolTipClose == null) m_toolTipClose = Strings.DockPaneStrip_ToolTipClose; return m_toolTipClose; } } private static string ToolTipSelect { get { if (m_toolTipSelect == null) m_toolTipSelect = Strings.DockPaneStrip_ToolTipWindowList; return m_toolTipSelect; } } private TextFormatFlags ToolWindowTextFormat { get { TextFormatFlags textFormat = TextFormatFlags.EndEllipsis | TextFormatFlags.HorizontalCenter | TextFormatFlags.SingleLine | TextFormatFlags.VerticalCenter; if (RightToLeft == RightToLeft.Yes) return textFormat | TextFormatFlags.RightToLeft | TextFormatFlags.Right; else return textFormat; } } private static int DocumentStripGapTop { get { return _DocumentStripGapTop; } } private static int DocumentStripGapBottom { get { return _DocumentStripGapBottom; } } private TextFormatFlags DocumentTextFormat { get { TextFormatFlags textFormat = TextFormatFlags.EndEllipsis | TextFormatFlags.SingleLine | TextFormatFlags.VerticalCenter | TextFormatFlags.HorizontalCenter; if (RightToLeft == RightToLeft.Yes) return textFormat | TextFormatFlags.RightToLeft; else return textFormat; } } private static int DocumentTabMaxWidth { get { return _DocumentTabMaxWidth; } } private static int DocumentButtonGapTop { get { return _DocumentButtonGapTop; } } private static int DocumentButtonGapBottom { get { return _DocumentButtonGapBottom; } } private static int DocumentButtonGapBetween { get { return _DocumentButtonGapBetween; } } private static int DocumentButtonGapRight { get { return _DocumentButtonGapRight; } } private static int DocumentTabGapTop { get { return _DocumentTabGapTop; } } private static int DocumentTabGapLeft { get { return _DocumentTabGapLeft; } } private static int DocumentTabGapRight { get { return _DocumentTabGapRight; } } private static int DocumentIconGapBottom { get { return _DocumentIconGapBottom; } } private static int DocumentIconGapLeft { get { return _DocumentIconGapLeft; } } private static int DocumentIconGapRight { get { return _DocumentIconGapRight; } } private static int DocumentIconWidth { get { return _DocumentIconWidth; } } private static int DocumentIconHeight { get { return _DocumentIconHeight; } } private static int DocumentTextGapRight { get { return _DocumentTextGapRight; } } private static Pen PenToolWindowTabBorder { get { return SystemPens.ControlDark; } } private static Pen PenDocumentTabActiveBorder { get { return SystemPens.ControlDarkDark; } } private static Pen PenDocumentTabInactiveBorder { get { return SystemPens.GrayText; } } #endregion #endregion public VS2012LightDockPaneStrip(DockPane pane) : base(pane) { SetStyle(ControlStyles.ResizeRedraw | ControlStyles.UserPaint | ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer, true); SuspendLayout(); m_components = new Container(); m_toolTip = new ToolTip(Components); m_selectMenu = new ContextMenuStrip(Components); ResumeLayout(); } protected override void Dispose(bool disposing) { if (disposing) { Components.Dispose(); if (m_boldFont != null) { m_boldFont.Dispose(); m_boldFont = null; } } base.Dispose(disposing); } protected override int MeasureHeight() { if (Appearance == DockPane.AppearanceStyle.ToolWindow) return MeasureHeight_ToolWindow(); else return MeasureHeight_Document(); } private int MeasureHeight_ToolWindow() { if (DockPane.IsAutoHide || Tabs.Count <= 1) return 0; int height = Math.Max(TextFont.Height, ToolWindowImageHeight + ToolWindowImageGapTop + ToolWindowImageGapBottom) + ToolWindowStripGapTop + ToolWindowStripGapBottom; return height; } private int MeasureHeight_Document() { int height = Math.Max(TextFont.Height + DocumentTabGapTop, ButtonClose.Height + DocumentButtonGapTop + DocumentButtonGapBottom) + DocumentStripGapBottom + DocumentStripGapTop; return height; } protected override void OnPaint(PaintEventArgs e) { Rectangle rect = TabsRectangle; DockPanelGradient gradient = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.DockStripGradient; if (Appearance == DockPane.AppearanceStyle.Document) { rect.X -= DocumentTabGapLeft; // Add these values back in so that the DockStrip color is drawn // beneath the close button and window list button. // It is possible depending on the DockPanel DocumentStyle to have // a Document without a DockStrip. rect.Width += DocumentTabGapLeft + DocumentTabGapRight + DocumentButtonGapRight + ButtonClose.Width + ButtonWindowList.Width; } else { gradient = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.DockStripGradient; } Color startColor = gradient.StartColor; Color endColor = gradient.EndColor; LinearGradientMode gradientMode = gradient.LinearGradientMode; DrawingRoutines.SafelyDrawLinearGradient(rect, startColor, endColor, gradientMode, e.Graphics); base.OnPaint(e); CalculateTabs(); if (Appearance == DockPane.AppearanceStyle.Document && DockPane.ActiveContent != null) { if (EnsureDocumentTabVisible(DockPane.ActiveContent, false)) CalculateTabs(); } DrawTabStrip(e.Graphics); } protected override void OnRefreshChanges() { SetInertButtons(); Invalidate(); } public override GraphicsPath GetOutline(int index) { if (Appearance == DockPane.AppearanceStyle.Document) return GetOutline_Document(index); else return GetOutline_ToolWindow(index); } private GraphicsPath GetOutline_Document(int index) { Rectangle rectTab = GetTabRectangle(index); rectTab.X -= rectTab.Height / 2; rectTab.Intersect(TabsRectangle); rectTab = RectangleToScreen(DrawHelper.RtlTransform(this, rectTab)); Rectangle rectPaneClient = DockPane.RectangleToScreen(DockPane.ClientRectangle); GraphicsPath path = new GraphicsPath(); GraphicsPath pathTab = GetTabOutline_Document(Tabs[index], true, true, true); path.AddPath(pathTab, true); if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom) { path.AddLine(rectTab.Right, rectTab.Top, rectPaneClient.Right, rectTab.Top); path.AddLine(rectPaneClient.Right, rectTab.Top, rectPaneClient.Right, rectPaneClient.Top); path.AddLine(rectPaneClient.Right, rectPaneClient.Top, rectPaneClient.Left, rectPaneClient.Top); path.AddLine(rectPaneClient.Left, rectPaneClient.Top, rectPaneClient.Left, rectTab.Top); path.AddLine(rectPaneClient.Left, rectTab.Top, rectTab.Right, rectTab.Top); } else { path.AddLine(rectTab.Right, rectTab.Bottom, rectPaneClient.Right, rectTab.Bottom); path.AddLine(rectPaneClient.Right, rectTab.Bottom, rectPaneClient.Right, rectPaneClient.Bottom); path.AddLine(rectPaneClient.Right, rectPaneClient.Bottom, rectPaneClient.Left, rectPaneClient.Bottom); path.AddLine(rectPaneClient.Left, rectPaneClient.Bottom, rectPaneClient.Left, rectTab.Bottom); path.AddLine(rectPaneClient.Left, rectTab.Bottom, rectTab.Right, rectTab.Bottom); } return path; } private GraphicsPath GetOutline_ToolWindow(int index) { Rectangle rectTab = GetTabRectangle(index); rectTab.Intersect(TabsRectangle); rectTab = RectangleToScreen(DrawHelper.RtlTransform(this, rectTab)); Rectangle rectPaneClient = DockPane.RectangleToScreen(DockPane.ClientRectangle); GraphicsPath path = new GraphicsPath(); GraphicsPath pathTab = GetTabOutline(Tabs[index], true, true); path.AddPath(pathTab, true); path.AddLine(rectTab.Left, rectTab.Top, rectPaneClient.Left, rectTab.Top); path.AddLine(rectPaneClient.Left, rectTab.Top, rectPaneClient.Left, rectPaneClient.Top); path.AddLine(rectPaneClient.Left, rectPaneClient.Top, rectPaneClient.Right, rectPaneClient.Top); path.AddLine(rectPaneClient.Right, rectPaneClient.Top, rectPaneClient.Right, rectTab.Top); path.AddLine(rectPaneClient.Right, rectTab.Top, rectTab.Right, rectTab.Top); return path; } private void CalculateTabs() { if (Appearance == DockPane.AppearanceStyle.ToolWindow) CalculateTabs_ToolWindow(); else CalculateTabs_Document(); } private void CalculateTabs_ToolWindow() { if (Tabs.Count <= 1 || DockPane.IsAutoHide) return; Rectangle rectTabStrip = TabStripRectangle; // Calculate tab widths int countTabs = Tabs.Count; foreach (TabVS2012Light tab in Tabs) { tab.MaxWidth = GetMaxTabWidth(Tabs.IndexOf(tab)); tab.Flag = false; } // Set tab whose max width less than average width bool anyWidthWithinAverage = true; int totalWidth = rectTabStrip.Width - ToolWindowStripGapLeft - ToolWindowStripGapRight; int totalAllocatedWidth = 0; int averageWidth = totalWidth / countTabs; int remainedTabs = countTabs; for (anyWidthWithinAverage = true; anyWidthWithinAverage && remainedTabs > 0; ) { anyWidthWithinAverage = false; foreach (TabVS2012Light tab in Tabs) { if (tab.Flag) continue; if (tab.MaxWidth <= averageWidth) { tab.Flag = true; tab.TabWidth = tab.MaxWidth; totalAllocatedWidth += tab.TabWidth; anyWidthWithinAverage = true; remainedTabs--; } } if (remainedTabs != 0) averageWidth = (totalWidth - totalAllocatedWidth) / remainedTabs; } // If any tab width not set yet, set it to the average width if (remainedTabs > 0) { int roundUpWidth = (totalWidth - totalAllocatedWidth) - (averageWidth * remainedTabs); foreach (TabVS2012Light tab in Tabs) { if (tab.Flag) continue; tab.Flag = true; if (roundUpWidth > 0) { tab.TabWidth = averageWidth + 1; roundUpWidth--; } else tab.TabWidth = averageWidth; } } // Set the X position of the tabs int x = rectTabStrip.X + ToolWindowStripGapLeft; foreach (TabVS2012Light tab in Tabs) { tab.TabX = x; x += tab.TabWidth; } } private bool CalculateDocumentTab(Rectangle rectTabStrip, ref int x, int index) { bool overflow = false; var tab = Tabs[index] as TabVS2012Light; tab.MaxWidth = GetMaxTabWidth(index); int width = Math.Min(tab.MaxWidth, DocumentTabMaxWidth); if (x + width < rectTabStrip.Right || index == StartDisplayingTab) { tab.TabX = x; tab.TabWidth = width; EndDisplayingTab = index; } else { tab.TabX = 0; tab.TabWidth = 0; overflow = true; } x += width; return overflow; } /// <summary> /// Calculate which tabs are displayed and in what order. /// </summary> private void CalculateTabs_Document() { if (m_startDisplayingTab >= Tabs.Count) m_startDisplayingTab = 0; Rectangle rectTabStrip = TabsRectangle; int x = rectTabStrip.X; //+ rectTabStrip.Height / 2; bool overflow = false; // Originally all new documents that were considered overflow // (not enough pane strip space to show all tabs) were added to // the far left (assuming not right to left) and the tabs on the // right were dropped from view. If StartDisplayingTab is not 0 // then we are dealing with making sure a specific tab is kept in focus. if (m_startDisplayingTab > 0) { int tempX = x; var tab = Tabs[m_startDisplayingTab] as TabVS2012Light; tab.MaxWidth = GetMaxTabWidth(m_startDisplayingTab); // Add the active tab and tabs to the left for (int i = StartDisplayingTab; i >= 0; i--) CalculateDocumentTab(rectTabStrip, ref tempX, i); // Store which tab is the first one displayed so that it // will be drawn correctly (without part of the tab cut off) FirstDisplayingTab = EndDisplayingTab; tempX = x; // Reset X location because we are starting over // Start with the first tab displayed - name is a little misleading. // Loop through each tab and set its location. If there is not enough // room for all of them overflow will be returned. for (int i = EndDisplayingTab; i < Tabs.Count; i++) overflow = CalculateDocumentTab(rectTabStrip, ref tempX, i); // If not all tabs are shown then we have an overflow. if (FirstDisplayingTab != 0) overflow = true; } else { for (int i = StartDisplayingTab; i < Tabs.Count; i++) overflow = CalculateDocumentTab(rectTabStrip, ref x, i); for (int i = 0; i < StartDisplayingTab; i++) overflow = CalculateDocumentTab(rectTabStrip, ref x, i); FirstDisplayingTab = StartDisplayingTab; } if (!overflow) { m_startDisplayingTab = 0; FirstDisplayingTab = 0; x = rectTabStrip.X;// +rectTabStrip.Height / 2; foreach (TabVS2012Light tab in Tabs) { tab.TabX = x; x += tab.TabWidth; } } DocumentTabsOverflow = overflow; } protected override void EnsureTabVisible(IDockContent content) { if (Appearance != DockPane.AppearanceStyle.Document || !Tabs.Contains(content)) return; CalculateTabs(); EnsureDocumentTabVisible(content, true); } private bool EnsureDocumentTabVisible(IDockContent content, bool repaint) { int index = Tabs.IndexOf(content); var tab = Tabs[index] as TabVS2012Light; if (tab.TabWidth != 0) return false; StartDisplayingTab = index; if (repaint) Invalidate(); return true; } private int GetMaxTabWidth(int index) { if (Appearance == DockPane.AppearanceStyle.ToolWindow) return GetMaxTabWidth_ToolWindow(index); else return GetMaxTabWidth_Document(index); } private int GetMaxTabWidth_ToolWindow(int index) { IDockContent content = Tabs[index].Content; Size sizeString = TextRenderer.MeasureText(content.DockHandler.TabText, TextFont); return ToolWindowImageWidth + sizeString.Width + ToolWindowImageGapLeft + ToolWindowImageGapRight + ToolWindowTextGapRight; } private const int TAB_CLOSE_BUTTON_WIDTH = 30; private int GetMaxTabWidth_Document(int index) { IDockContent content = Tabs[index].Content; int height = GetTabRectangle_Document(index).Height; Size sizeText = TextRenderer.MeasureText(content.DockHandler.TabText, BoldFont, new Size(DocumentTabMaxWidth, height), DocumentTextFormat); int width; if (DockPane.DockPanel.ShowDocumentIcon) width = sizeText.Width + DocumentIconWidth + DocumentIconGapLeft + DocumentIconGapRight + DocumentTextGapRight; else width = sizeText.Width + DocumentIconGapLeft + DocumentTextGapRight; width += TAB_CLOSE_BUTTON_WIDTH; return width; } private void DrawTabStrip(Graphics g) { if (Appearance == DockPane.AppearanceStyle.Document) DrawTabStrip_Document(g); else DrawTabStrip_ToolWindow(g); } private void DrawTabStrip_Document(Graphics g) { int count = Tabs.Count; if (count == 0) return; Rectangle rectTabStrip = TabStripRectangle; rectTabStrip.Height += 1; // Draw the tabs Rectangle rectTabOnly = TabsRectangle; Rectangle rectTab = Rectangle.Empty; TabVS2012Light tabActive = null; g.SetClip(DrawHelper.RtlTransform(this, rectTabOnly)); for (int i = 0; i < count; i++) { rectTab = GetTabRectangle(i); if (Tabs[i].Content == DockPane.ActiveContent) { tabActive = Tabs[i] as TabVS2012Light; continue; } if (rectTab.IntersectsWith(rectTabOnly)) DrawTab(g, Tabs[i] as TabVS2012Light, rectTab); } g.SetClip(rectTabStrip); if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom) g.DrawLine(PenDocumentTabActiveBorder, rectTabStrip.Left, rectTabStrip.Top + 1, rectTabStrip.Right, rectTabStrip.Top + 1); else { Color tabUnderLineColor; if (tabActive != null && DockPane.IsActiveDocumentPane) tabUnderLineColor = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.ActiveTabGradient.StartColor; else tabUnderLineColor = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.ActiveTabGradient.EndColor; g.DrawLine(new Pen(tabUnderLineColor, 4), rectTabStrip.Left, rectTabStrip.Bottom, rectTabStrip.Right, rectTabStrip.Bottom); } g.SetClip(DrawHelper.RtlTransform(this, rectTabOnly)); if (tabActive != null) { rectTab = GetTabRectangle(Tabs.IndexOf(tabActive)); if (rectTab.IntersectsWith(rectTabOnly)) { rectTab.Intersect(rectTabOnly); DrawTab(g, tabActive, rectTab); } } } private void DrawTabStrip_ToolWindow(Graphics g) { Rectangle rectTabStrip = TabStripRectangle; g.DrawLine(PenToolWindowTabBorder, rectTabStrip.Left, rectTabStrip.Top, rectTabStrip.Right, rectTabStrip.Top); for (int i = 0; i < Tabs.Count; i++) DrawTab(g, Tabs[i] as TabVS2012Light, GetTabRectangle(i)); } private Rectangle GetTabRectangle(int index) { if (Appearance == DockPane.AppearanceStyle.ToolWindow) return GetTabRectangle_ToolWindow(index); else return GetTabRectangle_Document(index); } private Rectangle GetTabRectangle_ToolWindow(int index) { Rectangle rectTabStrip = TabStripRectangle; TabVS2012Light tab = (TabVS2012Light)(Tabs[index]); return new Rectangle(tab.TabX, rectTabStrip.Y, tab.TabWidth, rectTabStrip.Height); } private Rectangle GetTabRectangle_Document(int index) { Rectangle rectTabStrip = TabStripRectangle; var tab = (TabVS2012Light)Tabs[index]; Rectangle rect = new Rectangle(); rect.X = tab.TabX; rect.Width = tab.TabWidth; rect.Height = rectTabStrip.Height - DocumentTabGapTop; if (DockPane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom) rect.Y = rectTabStrip.Y + DocumentStripGapBottom; else rect.Y = rectTabStrip.Y + DocumentTabGapTop; return rect; } private void DrawTab(Graphics g, TabVS2012Light tab, Rectangle rect) { if (Appearance == DockPane.AppearanceStyle.ToolWindow) DrawTab_ToolWindow(g, tab, rect); else DrawTab_Document(g, tab, rect); } private GraphicsPath GetTabOutline(Tab tab, bool rtlTransform, bool toScreen) { if (Appearance == DockPane.AppearanceStyle.ToolWindow) return GetTabOutline_ToolWindow(tab, rtlTransform, toScreen); else return GetTabOutline_Document(tab, rtlTransform, toScreen, false); } private GraphicsPath GetTabOutline_ToolWindow(Tab tab, bool rtlTransform, bool toScreen) { Rectangle rect = GetTabRectangle(Tabs.IndexOf(tab)); if (rtlTransform) rect = DrawHelper.RtlTransform(this, rect); if (toScreen) rect = RectangleToScreen(rect); DrawHelper.GetRoundedCornerTab(GraphicsPath, rect, false); return GraphicsPath; } private GraphicsPath GetTabOutline_Document(Tab tab, bool rtlTransform, bool toScreen, bool full) { GraphicsPath.Reset(); Rectangle rect = GetTabRectangle(Tabs.IndexOf(tab)); // Shorten TabOutline so it doesn't get overdrawn by icons next to it rect.Intersect(TabsRectangle); rect.Width--; if (rtlTransform) rect = DrawHelper.RtlTransform(this, rect); if (toScreen) rect = RectangleToScreen(rect); GraphicsPath.AddRectangle(rect); return GraphicsPath; } private void DrawTab_ToolWindow(Graphics g, TabVS2012Light tab, Rectangle rect) { rect.Y += 1; Rectangle rectIcon = new Rectangle( rect.X + ToolWindowImageGapLeft, rect.Y - 1 + rect.Height - ToolWindowImageGapBottom - ToolWindowImageHeight, ToolWindowImageWidth, ToolWindowImageHeight); Rectangle rectText = rectIcon; rectText.X += rectIcon.Width + ToolWindowImageGapRight; rectText.Width = rect.Width - rectIcon.Width - ToolWindowImageGapLeft - ToolWindowImageGapRight - ToolWindowTextGapRight; Rectangle rectTab = DrawHelper.RtlTransform(this, rect); rectText = DrawHelper.RtlTransform(this, rectText); rectIcon = DrawHelper.RtlTransform(this, rectIcon); if (DockPane.ActiveContent == tab.Content && ((DockContent)tab.Content).IsActivated) { Color startColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.ActiveTabGradient.StartColor; Color endColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.ActiveTabGradient.EndColor; LinearGradientMode gradientMode = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.ActiveTabGradient.LinearGradientMode; g.FillRectangle(new LinearGradientBrush(rectTab, startColor, endColor, gradientMode), rect); Color textColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.ActiveTabGradient.TextColor; TextRenderer.DrawText(g, tab.Content.DockHandler.TabText, TextFont, rectText, textColor, ToolWindowTextFormat); } else { Color textColor; if (tab.Content == DockPane.MouseOverTab) textColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.ActiveTabGradient.TextColor; else textColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.InactiveTabGradient.TextColor; TextRenderer.DrawText(g, tab.Content.DockHandler.TabText, TextFont, rectText, textColor, ToolWindowTextFormat); } g.DrawLine(PenToolWindowTabBorder, rect.X + rect.Width - 1, rect.Y, rect.X + rect.Width - 1, rect.Height); if (rectTab.Contains(rectIcon)) g.DrawIcon(tab.Content.DockHandler.Icon, rectIcon); } private void DrawTab_Document(Graphics g, TabVS2012Light tab, Rectangle rect) { if (tab.TabWidth == 0) return; var rectCloseButton = GetCloseButtonRect(rect); Rectangle rectIcon = new Rectangle( rect.X + DocumentIconGapLeft, rect.Y + rect.Height - DocumentIconGapBottom - DocumentIconHeight, DocumentIconWidth, DocumentIconHeight); Rectangle rectText = rectIcon; if (DockPane.DockPanel.ShowDocumentIcon) { rectText.X += rectIcon.Width + DocumentIconGapRight; rectText.Y = rect.Y; rectText.Width = rect.Width - rectIcon.Width - DocumentIconGapLeft - DocumentIconGapRight - DocumentTextGapRight - rectCloseButton.Width; rectText.Height = rect.Height; } else rectText.Width = rect.Width - DocumentIconGapLeft - DocumentTextGapRight - rectCloseButton.Width; Rectangle rectTab = DrawHelper.RtlTransform(this, rect); Rectangle rectBack = DrawHelper.RtlTransform(this, rect); rectBack.Width += rect.X; rectBack.X = 0; rectText = DrawHelper.RtlTransform(this, rectText); rectIcon = DrawHelper.RtlTransform(this, rectIcon); Color activeColor = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.ActiveTabGradient.StartColor; Color lostFocusColor = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.ActiveTabGradient.EndColor; Color inactiveColor = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.InactiveTabGradient.StartColor; Color mouseHoverColor = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.InactiveTabGradient.EndColor; Color activeText = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.ActiveTabGradient.TextColor; Color inactiveText = DockPane.DockPanel.Skin.DockPaneStripSkin.DocumentGradient.InactiveTabGradient.TextColor; Color lostFocusText = SystemColors.GrayText; if (DockPane.ActiveContent == tab.Content) { if (DockPane.IsActiveDocumentPane) { g.FillRectangle(new SolidBrush(activeColor), rect); TextRenderer.DrawText(g, tab.Content.DockHandler.TabText, TextFont, rectText, activeText, DocumentTextFormat); g.DrawImage(rectCloseButton == ActiveClose ? Resources.ActiveTabHover_Close : Resources.ActiveTab_Close, rectCloseButton); } else { g.FillRectangle(new SolidBrush(lostFocusColor), rect); TextRenderer.DrawText(g, tab.Content.DockHandler.TabText, TextFont, rectText, lostFocusText, DocumentTextFormat); g.DrawImage(rectCloseButton == ActiveClose ? Resources.LostFocusTabHover_Close : Resources.LostFocusTab_Close, rectCloseButton); } } else { if (tab.Content == DockPane.MouseOverTab) { g.FillRectangle(new SolidBrush(mouseHoverColor), rect); TextRenderer.DrawText(g, tab.Content.DockHandler.TabText, TextFont, rectText, activeText, DocumentTextFormat); g.DrawImage(rectCloseButton == ActiveClose ? Resources.InactiveTabHover_Close : Resources.ActiveTabHover_Close, rectCloseButton); } else { g.FillRectangle(new SolidBrush(inactiveColor), rect); TextRenderer.DrawText(g, tab.Content.DockHandler.TabText, TextFont, rectText, inactiveText, DocumentTextFormat); } } if (rectTab.Contains(rectIcon) && DockPane.DockPanel.ShowDocumentIcon) g.DrawIcon(tab.Content.DockHandler.Icon, rectIcon); } protected override void OnMouseClick(MouseEventArgs e) { base.OnMouseClick(e); if (e.Button != MouseButtons.Left || Appearance != DockPane.AppearanceStyle.Document) return; var indexHit = HitTest(); if (indexHit > -1) TabCloseButtonHit(indexHit); } private void TabCloseButtonHit(int index) { var mousePos = PointToClient(MousePosition); var tabRect = GetTabRectangle(index); var closeButtonRect = GetCloseButtonRect(tabRect); var mouseRect = new Rectangle(mousePos, new Size(1, 1)); if (closeButtonRect.IntersectsWith(mouseRect)) DockPane.CloseActiveContent(); } private Rectangle GetCloseButtonRect(Rectangle rectTab) { if (Appearance != Docking.DockPane.AppearanceStyle.Document) { return Rectangle.Empty; } const int gap = 3; const int imageSize = 15; return new Rectangle(rectTab.X + rectTab.Width - imageSize - gap - 1, rectTab.Y + gap, imageSize, imageSize); } private void WindowList_Click(object sender, EventArgs e) { SelectMenu.Items.Clear(); foreach (TabVS2012Light tab in Tabs) { IDockContent content = tab.Content; ToolStripItem item = SelectMenu.Items.Add(content.DockHandler.TabText, content.DockHandler.Icon.ToBitmap()); item.Tag = tab.Content; item.Click += new EventHandler(ContextMenuItem_Click); } var workingArea = Screen.GetWorkingArea(ButtonWindowList.PointToScreen(new Point(ButtonWindowList.Width / 2, ButtonWindowList.Height / 2))); var menu = new Rectangle(ButtonWindowList.PointToScreen(new Point(0, ButtonWindowList.Location.Y + ButtonWindowList.Height)), SelectMenu.Size); var menuMargined = new Rectangle(menu.X - SelectMenuMargin, menu.Y - SelectMenuMargin, menu.Width + SelectMenuMargin, menu.Height + SelectMenuMargin); if (workingArea.Contains(menuMargined)) { SelectMenu.Show(menu.Location); } else { var newPoint = menu.Location; newPoint.X = DrawHelper.Balance(SelectMenu.Width, SelectMenuMargin, newPoint.X, workingArea.Left, workingArea.Right); newPoint.Y = DrawHelper.Balance(SelectMenu.Size.Height, SelectMenuMargin, newPoint.Y, workingArea.Top, workingArea.Bottom); var button = ButtonWindowList.PointToScreen(new Point(0, ButtonWindowList.Height)); if (newPoint.Y < button.Y) { // flip the menu up to be above the button. newPoint.Y = button.Y - ButtonWindowList.Height; SelectMenu.Show(newPoint, ToolStripDropDownDirection.AboveRight); } else { SelectMenu.Show(newPoint); } } } private void ContextMenuItem_Click(object sender, EventArgs e) { ToolStripMenuItem item = sender as ToolStripMenuItem; if (item != null) { IDockContent content = (IDockContent)item.Tag; DockPane.ActiveContent = content; } } private void SetInertButtons() { if (Appearance == DockPane.AppearanceStyle.ToolWindow) { if (m_buttonClose != null) m_buttonClose.Left = -m_buttonClose.Width; if (m_buttonWindowList != null) m_buttonWindowList.Left = -m_buttonWindowList.Width; } else { ButtonClose.Enabled = false; m_closeButtonVisible = false; ButtonClose.Visible = m_closeButtonVisible; ButtonClose.RefreshChanges(); ButtonWindowList.RefreshChanges(); } } protected override void OnLayout(LayoutEventArgs levent) { if (Appearance == DockPane.AppearanceStyle.Document) { LayoutButtons(); OnRefreshChanges(); } base.OnLayout(levent); } private void LayoutButtons() { Rectangle rectTabStrip = TabStripRectangle; // Set position and size of the buttons int buttonWidth = ButtonClose.Image.Width; int buttonHeight = ButtonClose.Image.Height; int height = rectTabStrip.Height - DocumentButtonGapTop - DocumentButtonGapBottom; if (buttonHeight < height) { buttonWidth = buttonWidth * (height / buttonHeight); buttonHeight = height; } Size buttonSize = new Size(buttonWidth, buttonHeight); int x = rectTabStrip.X + rectTabStrip.Width - DocumentTabGapLeft - DocumentButtonGapRight - buttonWidth; int y = rectTabStrip.Y + DocumentButtonGapTop; Point point = new Point(x, y); ButtonClose.Bounds = DrawHelper.RtlTransform(this, new Rectangle(point, buttonSize)); // If the close button is not visible draw the window list button overtop. // Otherwise it is drawn to the left of the close button. if (m_closeButtonVisible) point.Offset(-(DocumentButtonGapBetween + buttonWidth), 0); ButtonWindowList.Bounds = DrawHelper.RtlTransform(this, new Rectangle(point, buttonSize)); } private void Close_Click(object sender, EventArgs e) { DockPane.CloseActiveContent(); } protected override int HitTest(Point ptMouse) { if (!TabsRectangle.Contains(ptMouse)) return -1; foreach (Tab tab in Tabs) { GraphicsPath path = GetTabOutline(tab, true, false); if (path.IsVisible(ptMouse)) return Tabs.IndexOf(tab); } return -1; } protected override Rectangle GetTabBounds(Tab tab) { GraphicsPath path = GetTabOutline(tab, true, false); RectangleF rectangle = path.GetBounds(); return new Rectangle((int)rectangle.Left, (int)rectangle.Top, (int)rectangle.Width, (int)rectangle.Height); } private Rectangle ActiveClose { get { return _activeClose; } } private bool SetActiveClose(Rectangle rectangle) { if (_activeClose == rectangle) return false; _activeClose = rectangle; return true; } private bool SetMouseOverTab(IDockContent content) { if (DockPane.MouseOverTab == content) return false; DockPane.MouseOverTab = content; return true; } protected override void OnMouseHover(EventArgs e) { int index = HitTest(PointToClient(MousePosition)); string toolTip = string.Empty; base.OnMouseHover(e); bool tabUpdate = false; bool buttonUpdate = false; if (index != -1) { var tab = Tabs[index] as TabVS2012Light; if (Appearance == DockPane.AppearanceStyle.ToolWindow || Appearance == DockPane.AppearanceStyle.Document) { tabUpdate = SetMouseOverTab(tab.Content == DockPane.ActiveContent ? null : tab.Content); } if (!String.IsNullOrEmpty(tab.Content.DockHandler.ToolTipText)) toolTip = tab.Content.DockHandler.ToolTipText; else if (tab.MaxWidth > tab.TabWidth) toolTip = tab.Content.DockHandler.TabText; var mousePos = PointToClient(MousePosition); var tabRect = GetTabRectangle(index); var closeButtonRect = GetCloseButtonRect(tabRect); var mouseRect = new Rectangle(mousePos, new Size(1, 1)); buttonUpdate = SetActiveClose(closeButtonRect.IntersectsWith(mouseRect) ? closeButtonRect : Rectangle.Empty); } else { tabUpdate = SetMouseOverTab(null); buttonUpdate = SetActiveClose(Rectangle.Empty); } if (tabUpdate || buttonUpdate) Invalidate(); if (m_toolTip.GetToolTip(this) != toolTip) { m_toolTip.Active = false; m_toolTip.SetToolTip(this, toolTip); m_toolTip.Active = true; } // requires further tracking of mouse hover behavior, ResetMouseEventArgs(); } protected override void OnMouseLeave(EventArgs e) { var tabUpdate = SetMouseOverTab(null); var buttonUpdate = SetActiveClose(Rectangle.Empty); if (tabUpdate || buttonUpdate) Invalidate(); base.OnMouseLeave(e); } protected override void OnRightToLeftChanged(EventArgs e) { base.OnRightToLeftChanged(e); PerformLayout(); } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Apache.Ignite.Core.Impl { using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading.Tasks; using Apache.Ignite.Core.Binary; using Apache.Ignite.Core.Cache; using Apache.Ignite.Core.Cache.Configuration; using Apache.Ignite.Core.Cluster; using Apache.Ignite.Core.Common; using Apache.Ignite.Core.Compute; using Apache.Ignite.Core.Configuration; using Apache.Ignite.Core.Datastream; using Apache.Ignite.Core.DataStructures; using Apache.Ignite.Core.Events; using Apache.Ignite.Core.Impl.Binary; using Apache.Ignite.Core.Impl.Cache; using Apache.Ignite.Core.Impl.Cache.Platform; using Apache.Ignite.Core.Impl.Cluster; using Apache.Ignite.Core.Impl.Common; using Apache.Ignite.Core.Impl.Datastream; using Apache.Ignite.Core.Impl.DataStructures; using Apache.Ignite.Core.Impl.Handle; using Apache.Ignite.Core.Impl.Plugin; using Apache.Ignite.Core.Impl.Transactions; using Apache.Ignite.Core.Impl.Unmanaged; using Apache.Ignite.Core.Interop; using Apache.Ignite.Core.Lifecycle; using Apache.Ignite.Core.Log; using Apache.Ignite.Core.Messaging; using Apache.Ignite.Core.PersistentStore; using Apache.Ignite.Core.Services; using Apache.Ignite.Core.Transactions; using UU = Apache.Ignite.Core.Impl.Unmanaged.UnmanagedUtils; /// <summary> /// Native Ignite wrapper. /// </summary> internal sealed class Ignite : PlatformTargetAdapter, ICluster, IIgniteInternal, IIgnite { /// <summary> /// Operation codes for PlatformProcessorImpl calls. /// </summary> private enum Op { GetCache = 1, CreateCache = 2, GetOrCreateCache = 3, CreateCacheFromConfig = 4, GetOrCreateCacheFromConfig = 5, DestroyCache = 6, GetAffinity = 7, GetDataStreamer = 8, GetTransactions = 9, GetClusterGroup = 10, GetExtension = 11, GetAtomicLong = 12, GetAtomicReference = 13, GetAtomicSequence = 14, GetIgniteConfiguration = 15, GetCacheNames = 16, CreateNearCache = 17, GetOrCreateNearCache = 18, LoggerIsLevelEnabled = 19, LoggerLog = 20, GetBinaryProcessor = 21, ReleaseStart = 22, AddCacheConfiguration = 23, SetBaselineTopologyVersion = 24, SetBaselineTopologyNodes = 25, GetBaselineTopology = 26, DisableWal = 27, EnableWal = 28, IsWalEnabled = 29, SetTxTimeoutOnPartitionMapExchange = 30, GetNodeVersion = 31, IsBaselineAutoAdjustmentEnabled = 32, SetBaselineAutoAdjustmentEnabled = 33, GetBaselineAutoAdjustTimeout = 34, SetBaselineAutoAdjustTimeout = 35, GetCacheConfig = 36, GetThreadLocal = 37, GetOrCreateLock = 38 } /** */ private readonly IgniteConfiguration _cfg; /** Grid name. */ private readonly string _name; /** Unmanaged node. */ private readonly IPlatformTargetInternal _proc; /** Marshaller. */ private readonly Marshaller _marsh; /** Initial projection. */ private readonly ClusterGroupImpl _prj; /** Binary. */ private readonly Binary.Binary _binary; /** Binary processor. */ private readonly BinaryProcessor _binaryProc; /** Lifecycle handlers. */ private readonly IList<LifecycleHandlerHolder> _lifecycleHandlers; /** Local node. */ private IClusterNode _locNode; /** Callbacks */ private readonly UnmanagedCallbacks _cbs; /** Node info cache. */ private readonly ConcurrentDictionary<Guid, ClusterNodeImpl> _nodes = new ConcurrentDictionary<Guid, ClusterNodeImpl>(); /** Client reconnect task completion source. */ private volatile TaskCompletionSource<bool> _clientReconnectTaskCompletionSource = new TaskCompletionSource<bool>(); /** Plugin processor. */ private readonly PluginProcessor _pluginProcessor; /** Platform cache manager. */ private readonly PlatformCacheManager _platformCacheManager; /// <summary> /// Constructor. /// </summary> /// <param name="cfg">Configuration.</param> /// <param name="name">Grid name.</param> /// <param name="proc">Interop processor.</param> /// <param name="marsh">Marshaller.</param> /// <param name="lifecycleHandlers">Lifecycle beans.</param> /// <param name="cbs">Callbacks.</param> public Ignite(IgniteConfiguration cfg, string name, IPlatformTargetInternal proc, Marshaller marsh, IList<LifecycleHandlerHolder> lifecycleHandlers, UnmanagedCallbacks cbs) : base(proc) { Debug.Assert(cfg != null); Debug.Assert(proc != null); Debug.Assert(marsh != null); Debug.Assert(lifecycleHandlers != null); Debug.Assert(cbs != null); _cfg = cfg; _name = name; _proc = proc; _marsh = marsh; _lifecycleHandlers = lifecycleHandlers; _cbs = cbs; marsh.Ignite = this; _prj = new ClusterGroupImpl(Target.OutObjectInternal((int) Op.GetClusterGroup), null); _binary = new Binary.Binary(marsh); _binaryProc = new BinaryProcessor(DoOutOpObject((int) Op.GetBinaryProcessor)); cbs.Initialize(this); // Set reconnected task to completed state for convenience. _clientReconnectTaskCompletionSource.SetResult(false); SetCompactFooter(); _pluginProcessor = new PluginProcessor(this); _platformCacheManager = new PlatformCacheManager(this); } /// <summary> /// Sets the compact footer setting. /// </summary> private void SetCompactFooter() { if (!string.IsNullOrEmpty(_cfg.SpringConfigUrl)) { // If there is a Spring config, use setting from Spring, // since we ignore .NET config in legacy mode. var cfg0 = GetConfiguration().BinaryConfiguration; if (cfg0 != null) _marsh.CompactFooter = cfg0.CompactFooter; } } /// <summary> /// On-start routine. /// </summary> internal void OnStart() { PluginProcessor.OnIgniteStart(); foreach (var lifecycleBean in _lifecycleHandlers) lifecycleBean.OnStart(this); } /** <inheritdoc /> */ public string Name { get { return _name; } } /** <inheritdoc /> */ public ICluster GetCluster() { return this; } /** <inheritdoc /> */ IIgnite IClusterGroup.Ignite { get { return this; } } /** <inheritdoc /> */ public IClusterGroup ForLocal() { return _prj.ForNodes(GetLocalNode()); } /** <inheritdoc cref="IIgnite" /> */ public ICompute GetCompute() { return _prj.ForServers().GetCompute(); } /** <inheritdoc /> */ public IgniteProductVersion GetVersion() { return Target.OutStream((int) Op.GetNodeVersion, r => new IgniteProductVersion(r)); } /** <inheritdoc /> */ public IClusterGroup ForNodes(IEnumerable<IClusterNode> nodes) { return _prj.ForNodes(nodes); } /** <inheritdoc /> */ public IClusterGroup ForNodes(params IClusterNode[] nodes) { return _prj.ForNodes(nodes); } /** <inheritdoc /> */ public IClusterGroup ForNodeIds(IEnumerable<Guid> ids) { return _prj.ForNodeIds(ids); } /** <inheritdoc /> */ public IClusterGroup ForNodeIds(params Guid[] ids) { return _prj.ForNodeIds(ids); } /** <inheritdoc /> */ public IClusterGroup ForPredicate(Func<IClusterNode, bool> p) { IgniteArgumentCheck.NotNull(p, "p"); return _prj.ForPredicate(p); } /** <inheritdoc /> */ public IClusterGroup ForAttribute(string name, string val) { return _prj.ForAttribute(name, val); } /** <inheritdoc /> */ public IClusterGroup ForCacheNodes(string name) { return _prj.ForCacheNodes(name); } /** <inheritdoc /> */ public IClusterGroup ForDataNodes(string name) { return _prj.ForDataNodes(name); } /** <inheritdoc /> */ public IClusterGroup ForClientNodes(string name) { return _prj.ForClientNodes(name); } /** <inheritdoc /> */ public IClusterGroup ForRemotes() { return _prj.ForRemotes(); } /** <inheritdoc /> */ public IClusterGroup ForDaemons() { return _prj.ForDaemons(); } /** <inheritdoc /> */ public IClusterGroup ForHost(IClusterNode node) { IgniteArgumentCheck.NotNull(node, "node"); return _prj.ForHost(node); } /** <inheritdoc /> */ public IClusterGroup ForRandom() { return _prj.ForRandom(); } /** <inheritdoc /> */ public IClusterGroup ForOldest() { return _prj.ForOldest(); } /** <inheritdoc /> */ public IClusterGroup ForYoungest() { return _prj.ForYoungest(); } /** <inheritdoc /> */ public IClusterGroup ForDotNet() { return _prj.ForDotNet(); } /** <inheritdoc /> */ public IClusterGroup ForServers() { return _prj.ForServers(); } /** <inheritdoc /> */ public ICollection<IClusterNode> GetNodes() { return _prj.GetNodes(); } /** <inheritdoc /> */ public IClusterNode GetNode(Guid id) { return _prj.GetNode(id); } /** <inheritdoc /> */ public IClusterNode GetNode() { return _prj.GetNode(); } /** <inheritdoc /> */ public IClusterMetrics GetMetrics() { return _prj.GetMetrics(); } /** <inheritdoc /> */ [SuppressMessage("Microsoft.Usage", "CA1816:CallGCSuppressFinalizeCorrectly", Justification = "There is no finalizer.")] [SuppressMessage("Microsoft.Usage", "CA2213:DisposableFieldsShouldBeDisposed", MessageId = "_proxy", Justification = "Proxy does not need to be disposed.")] public void Dispose() { Ignition.Stop(Name, true); } /// <summary> /// Internal stop routine. /// </summary> /// <param name="cancel">Cancel flag.</param> internal void Stop(bool cancel) { var jniTarget = _proc as PlatformJniTarget; if (jniTarget == null) { throw new IgniteException("Ignition.Stop is not supported in thin client."); } UU.IgnitionStop(Name, cancel); _cbs.Cleanup(); } /// <summary> /// Called before node has stopped. /// </summary> internal void BeforeNodeStop() { var handler = Stopping; if (handler != null) handler.Invoke(this, EventArgs.Empty); } /// <summary> /// Called after node has stopped. /// </summary> internal void AfterNodeStop() { foreach (var bean in _lifecycleHandlers) bean.OnLifecycleEvent(LifecycleEventType.AfterNodeStop); var handler = Stopped; if (handler != null) handler.Invoke(this, EventArgs.Empty); } /** <inheritdoc /> */ public ICache<TK, TV> GetCache<TK, TV>(string name) { IgniteArgumentCheck.NotNull(name, "name"); return GetCache<TK, TV>(DoOutOpObject((int) Op.GetCache, w => w.WriteString(name))); } /** <inheritdoc /> */ public ICache<TK, TV> GetOrCreateCache<TK, TV>(string name) { IgniteArgumentCheck.NotNull(name, "name"); return GetCache<TK, TV>(DoOutOpObject((int) Op.GetOrCreateCache, w => w.WriteString(name))); } /** <inheritdoc /> */ public ICache<TK, TV> GetOrCreateCache<TK, TV>(CacheConfiguration configuration) { return GetOrCreateCache<TK, TV>(configuration, null); } /** <inheritdoc /> */ public ICache<TK, TV> GetOrCreateCache<TK, TV>(CacheConfiguration configuration, NearCacheConfiguration nearConfiguration) { return GetOrCreateCache<TK, TV>(configuration, nearConfiguration, null); } /** <inheritdoc /> */ public ICache<TK, TV> GetOrCreateCache<TK, TV>(CacheConfiguration configuration, NearCacheConfiguration nearConfiguration, PlatformCacheConfiguration platformCacheConfiguration) { return GetOrCreateCache<TK, TV>(configuration, nearConfiguration, platformCacheConfiguration, Op.GetOrCreateCacheFromConfig); } /** <inheritdoc /> */ public ICache<TK, TV> CreateCache<TK, TV>(string name) { IgniteArgumentCheck.NotNull(name, "name"); var cacheTarget = DoOutOpObject((int) Op.CreateCache, w => w.WriteString(name)); return GetCache<TK, TV>(cacheTarget); } /** <inheritdoc /> */ public ICache<TK, TV> CreateCache<TK, TV>(CacheConfiguration configuration) { return CreateCache<TK, TV>(configuration, null); } /** <inheritdoc /> */ public ICache<TK, TV> CreateCache<TK, TV>(CacheConfiguration configuration, NearCacheConfiguration nearConfiguration) { return CreateCache<TK, TV>(configuration, nearConfiguration, null); } /** <inheritdoc /> */ public ICache<TK, TV> CreateCache<TK, TV>(CacheConfiguration configuration, NearCacheConfiguration nearConfiguration, PlatformCacheConfiguration platformCacheConfiguration) { return GetOrCreateCache<TK, TV>(configuration, nearConfiguration, platformCacheConfiguration, Op.CreateCacheFromConfig); } /// <summary> /// Gets or creates the cache. /// </summary> private ICache<TK, TV> GetOrCreateCache<TK, TV>(CacheConfiguration configuration, NearCacheConfiguration nearConfiguration, PlatformCacheConfiguration platformCacheConfiguration, Op op) { IgniteArgumentCheck.NotNull(configuration, "configuration"); IgniteArgumentCheck.NotNull(configuration.Name, "CacheConfiguration.Name"); configuration.Validate(Logger); var cacheTarget = DoOutOpObject((int) op, s => { var w = BinaryUtils.Marshaller.StartMarshal(s); configuration.Write(w); if (nearConfiguration != null) { w.WriteBoolean(true); nearConfiguration.Write(w); } else { w.WriteBoolean(false); } if (platformCacheConfiguration != null) { w.WriteBoolean(true); platformCacheConfiguration.Write(w); } else { w.WriteBoolean(false); } }); return GetCache<TK, TV>(cacheTarget); } /** <inheritdoc /> */ public void DestroyCache(string name) { IgniteArgumentCheck.NotNull(name, "name"); DoOutOp((int) Op.DestroyCache, w => w.WriteString(name)); } /// <summary> /// Gets cache from specified native cache object. /// </summary> /// <param name="nativeCache">Native cache.</param> /// <param name="keepBinary">Keep binary flag.</param> /// <returns> /// New instance of cache wrapping specified native cache. /// </returns> public static ICache<TK, TV> GetCache<TK, TV>(IPlatformTargetInternal nativeCache, bool keepBinary = false) { return new CacheImpl<TK, TV>(nativeCache, false, keepBinary, false, false); } /** <inheritdoc /> */ public IClusterNode GetLocalNode() { return _locNode ?? (_locNode = GetNodes().FirstOrDefault(x => x.IsLocal) ?? ForDaemons().GetNodes().FirstOrDefault(x => x.IsLocal)); } /** <inheritdoc /> */ public bool PingNode(Guid nodeId) { return _prj.PingNode(nodeId); } /** <inheritdoc /> */ public long TopologyVersion { get { return _prj.TopologyVersion; } } /** <inheritdoc /> */ public ICollection<IClusterNode> GetTopology(long ver) { return _prj.Topology(ver); } /** <inheritdoc /> */ public void ResetMetrics() { _prj.ResetMetrics(); } /** <inheritdoc /> */ public Task<bool> ClientReconnectTask { get { return _clientReconnectTaskCompletionSource.Task; } } /** <inheritdoc /> */ public IDataStreamer<TK, TV> GetDataStreamer<TK, TV>(string cacheName) { IgniteArgumentCheck.NotNull(cacheName, "cacheName"); return GetDataStreamer<TK, TV>(cacheName, false); } /// <summary> /// Gets the data streamer. /// </summary> public IDataStreamer<TK, TV> GetDataStreamer<TK, TV>(string cacheName, bool keepBinary) { var streamerTarget = DoOutOpObject((int) Op.GetDataStreamer, w => { w.WriteString(cacheName); w.WriteBoolean(keepBinary); }); return new DataStreamerImpl<TK, TV>(streamerTarget, _marsh, cacheName, keepBinary); } /// <summary> /// Gets the public Ignite interface. /// </summary> public IIgnite GetIgnite() { return this; } /** <inheritdoc cref="IIgnite" /> */ public IBinary GetBinary() { return _binary; } /** <inheritdoc /> */ CacheAffinityImpl IIgniteInternal.GetAffinity(string cacheName) { IgniteArgumentCheck.NotNull(cacheName, "cacheName"); var aff = DoOutOpObject((int) Op.GetAffinity, w => w.WriteString(cacheName)); return new CacheAffinityImpl(aff, false); } /** <inheritdoc /> */ public ICacheAffinity GetAffinity(string cacheName) { return ((IIgniteInternal) this).GetAffinity(cacheName); } /** <inheritdoc /> */ public ITransactions GetTransactions() { return new TransactionsImpl(this, DoOutOpObject((int) Op.GetTransactions), GetLocalNode().Id); } /** <inheritdoc cref="IIgnite" /> */ public IMessaging GetMessaging() { return _prj.GetMessaging(); } /** <inheritdoc cref="IIgnite" /> */ public IEvents GetEvents() { return _prj.GetEvents(); } /** <inheritdoc cref="IIgnite" /> */ public IServices GetServices() { return _prj.ForServers().GetServices(); } /** <inheritdoc /> */ public void EnableStatistics(IEnumerable<string> cacheNames, bool enabled) { _prj.EnableStatistics(cacheNames, enabled); } /** <inheritdoc /> */ public void ClearStatistics(IEnumerable<string> caches) { _prj.ClearStatistics(caches); } /** <inheritdoc /> */ public IAtomicLong GetAtomicLong(string name, long initialValue, bool create) { IgniteArgumentCheck.NotNullOrEmpty(name, "name"); var nativeLong = DoOutOpObject((int) Op.GetAtomicLong, w => { w.WriteString(name); w.WriteLong(initialValue); w.WriteBoolean(create); }); if (nativeLong == null) return null; return new AtomicLong(nativeLong, name); } /** <inheritdoc /> */ public IAtomicSequence GetAtomicSequence(string name, long initialValue, bool create) { IgniteArgumentCheck.NotNullOrEmpty(name, "name"); var nativeSeq = DoOutOpObject((int) Op.GetAtomicSequence, w => { w.WriteString(name); w.WriteLong(initialValue); w.WriteBoolean(create); }); if (nativeSeq == null) return null; return new AtomicSequence(nativeSeq, name); } /** <inheritdoc /> */ public IAtomicReference<T> GetAtomicReference<T>(string name, T initialValue, bool create) { IgniteArgumentCheck.NotNullOrEmpty(name, "name"); var refTarget = DoOutOpObject((int) Op.GetAtomicReference, w => { w.WriteString(name); w.WriteObject(initialValue); w.WriteBoolean(create); }); return refTarget == null ? null : new AtomicReference<T>(refTarget, name); } /** <inheritdoc /> */ public IgniteConfiguration GetConfiguration() { return DoInOp((int) Op.GetIgniteConfiguration, s => new IgniteConfiguration(BinaryUtils.Marshaller.StartUnmarshal(s), _cfg)); } /** <inheritdoc /> */ public ICache<TK, TV> CreateNearCache<TK, TV>(string name, NearCacheConfiguration configuration) { return GetOrCreateNearCache0<TK, TV>(name, configuration, null, Op.CreateNearCache); } /** <inheritdoc /> */ public ICache<TK, TV> CreateNearCache<TK, TV>(string name, NearCacheConfiguration configuration, PlatformCacheConfiguration platformConfiguration) { return GetOrCreateNearCache0<TK, TV>(name, configuration, platformConfiguration, Op.CreateNearCache); } /** <inheritdoc /> */ public ICache<TK, TV> GetOrCreateNearCache<TK, TV>(string name, NearCacheConfiguration configuration) { return GetOrCreateNearCache0<TK, TV>(name, configuration, null, Op.GetOrCreateNearCache); } /** <inheritdoc /> */ public ICache<TK, TV> GetOrCreateNearCache<TK, TV>(string name, NearCacheConfiguration configuration, PlatformCacheConfiguration platformConfiguration) { return GetOrCreateNearCache0<TK, TV>(name, configuration, platformConfiguration, Op.GetOrCreateNearCache); } /** <inheritdoc /> */ public ICollection<string> GetCacheNames() { return Target.OutStream((int) Op.GetCacheNames, r => { var res = new string[r.ReadInt()]; for (var i = 0; i < res.Length; i++) res[i] = r.ReadString(); return (ICollection<string>) res; }); } /** <inheritdoc /> */ public CacheConfiguration GetCacheConfiguration(int cacheId) { return Target.InStreamOutStream((int) Op.GetCacheConfig, w => w.WriteInt(cacheId), s => new CacheConfiguration(BinaryUtils.Marshaller.StartUnmarshal(s))); } /** <inheritdoc /> */ public object GetJavaThreadLocal() { return Target.OutStream((int) Op.GetThreadLocal, r => r.ReadObject<object>()); } /** <inheritdoc /> */ public ILogger Logger { get { return _cbs.Log; } } /** <inheritdoc /> */ public event EventHandler Stopping; /** <inheritdoc /> */ public event EventHandler Stopped; /** <inheritdoc /> */ public event EventHandler ClientDisconnected; /** <inheritdoc /> */ public event EventHandler<ClientReconnectEventArgs> ClientReconnected; /** <inheritdoc /> */ public T GetPlugin<T>(string name) where T : class { IgniteArgumentCheck.NotNullOrEmpty(name, "name"); return PluginProcessor.GetProvider(name).GetPlugin<T>(); } /** <inheritdoc /> */ public void ResetLostPartitions(IEnumerable<string> cacheNames) { IgniteArgumentCheck.NotNull(cacheNames, "cacheNames"); _prj.ResetLostPartitions(cacheNames); } /** <inheritdoc /> */ public void ResetLostPartitions(params string[] cacheNames) { ResetLostPartitions((IEnumerable<string>) cacheNames); } /** <inheritdoc /> */ #pragma warning disable 618 public ICollection<IMemoryMetrics> GetMemoryMetrics() { return _prj.GetMemoryMetrics(); } /** <inheritdoc /> */ public IMemoryMetrics GetMemoryMetrics(string memoryPolicyName) { IgniteArgumentCheck.NotNullOrEmpty(memoryPolicyName, "memoryPolicyName"); return _prj.GetMemoryMetrics(memoryPolicyName); } #pragma warning restore 618 /** <inheritdoc cref="IIgnite" /> */ public void SetActive(bool isActive) { _prj.SetActive(isActive); } /** <inheritdoc cref="IIgnite" /> */ public bool IsActive() { return _prj.IsActive(); } /** <inheritdoc /> */ public void SetBaselineTopology(long topologyVersion) { DoOutInOp((int) Op.SetBaselineTopologyVersion, topologyVersion); } /** <inheritdoc /> */ public void SetBaselineTopology(IEnumerable<IBaselineNode> nodes) { IgniteArgumentCheck.NotNull(nodes, "nodes"); DoOutOp((int) Op.SetBaselineTopologyNodes, w => { var pos = w.Stream.Position; w.WriteInt(0); var cnt = 0; foreach (var node in nodes) { cnt++; BaselineNode.Write(w, node); } w.Stream.WriteInt(pos, cnt); }); } /** <inheritdoc /> */ public ICollection<IBaselineNode> GetBaselineTopology() { return DoInOp((int) Op.GetBaselineTopology, s => Marshaller.StartUnmarshal(s).ReadCollectionRaw(r => (IBaselineNode) new BaselineNode(r))); } /** <inheritdoc /> */ public void DisableWal(string cacheName) { IgniteArgumentCheck.NotNull(cacheName, "cacheName"); DoOutOp((int) Op.DisableWal, w => w.WriteString(cacheName)); } /** <inheritdoc /> */ public void EnableWal(string cacheName) { IgniteArgumentCheck.NotNull(cacheName, "cacheName"); DoOutOp((int) Op.EnableWal, w => w.WriteString(cacheName)); } /** <inheritdoc /> */ public bool IsWalEnabled(string cacheName) { IgniteArgumentCheck.NotNull(cacheName, "cacheName"); return DoOutOp((int) Op.IsWalEnabled, w => w.WriteString(cacheName)) == True; } /** <inheritdoc /> */ public void SetTxTimeoutOnPartitionMapExchange(TimeSpan timeout) { DoOutOp((int) Op.SetTxTimeoutOnPartitionMapExchange, (BinaryWriter w) => w.WriteLong((long) timeout.TotalMilliseconds)); } /** <inheritdoc /> */ public bool IsBaselineAutoAdjustEnabled() { return DoOutOp((int) Op.IsBaselineAutoAdjustmentEnabled, s => s.ReadBool()) == True; } /** <inheritdoc /> */ public void SetBaselineAutoAdjustEnabledFlag(bool isBaselineAutoAdjustEnabled) { DoOutOp((int) Op.SetBaselineAutoAdjustmentEnabled, w => w.WriteBoolean(isBaselineAutoAdjustEnabled)); } /** <inheritdoc /> */ public long GetBaselineAutoAdjustTimeout() { return DoOutOp((int) Op.GetBaselineAutoAdjustTimeout, s => s.ReadLong()); } /** <inheritdoc /> */ public void SetBaselineAutoAdjustTimeout(long baselineAutoAdjustTimeout) { DoOutInOp((int) Op.SetBaselineAutoAdjustTimeout, baselineAutoAdjustTimeout); } /** <inheritdoc /> */ #pragma warning disable 618 public IPersistentStoreMetrics GetPersistentStoreMetrics() { return _prj.GetPersistentStoreMetrics(); } #pragma warning restore 618 /** <inheritdoc /> */ public ICollection<IDataRegionMetrics> GetDataRegionMetrics() { return _prj.GetDataRegionMetrics(); } /** <inheritdoc /> */ public IDataRegionMetrics GetDataRegionMetrics(string memoryPolicyName) { return _prj.GetDataRegionMetrics(memoryPolicyName); } /** <inheritdoc /> */ public IDataStorageMetrics GetDataStorageMetrics() { return _prj.GetDataStorageMetrics(); } /** <inheritdoc /> */ public void AddCacheConfiguration(CacheConfiguration configuration) { IgniteArgumentCheck.NotNull(configuration, "configuration"); DoOutOp((int) Op.AddCacheConfiguration, s => configuration.Write(BinaryUtils.Marshaller.StartMarshal(s))); } /** <inheritdoc /> */ public IIgniteLock GetOrCreateLock(string name) { IgniteArgumentCheck.NotNullOrEmpty(name, "name"); var configuration = new LockConfiguration { Name = name }; return GetOrCreateLock(configuration, true); } /** <inheritdoc /> */ public IIgniteLock GetOrCreateLock(LockConfiguration configuration, bool create) { IgniteArgumentCheck.NotNull(configuration, "configuration"); IgniteArgumentCheck.NotNullOrEmpty(configuration.Name, "configuration.Name"); // Create a copy to ignore modifications from outside. var cfg = new LockConfiguration(configuration); var target = DoOutOpObject((int) Op.GetOrCreateLock, w => { w.WriteString(configuration.Name); w.WriteBoolean(configuration.IsFailoverSafe); w.WriteBoolean(configuration.IsFair); w.WriteBoolean(create); }); return target == null ? null : new IgniteLock(target, cfg); } /// <summary> /// Gets or creates near cache. /// </summary> private ICache<TK, TV> GetOrCreateNearCache0<TK, TV>(string name, NearCacheConfiguration configuration, PlatformCacheConfiguration platformConfiguration, Op op) { IgniteArgumentCheck.NotNull(configuration, "configuration"); var cacheTarget = DoOutOpObject((int) op, w => { w.WriteString(name); configuration.Write(w); if (platformConfiguration != null) { w.WriteBoolean(true); platformConfiguration.Write(w); } else { w.WriteBoolean(false); } }); return GetCache<TK, TV>(cacheTarget); } /// <summary> /// Gets internal projection. /// </summary> /// <returns>Projection.</returns> public ClusterGroupImpl ClusterGroup { get { return _prj; } } /// <summary> /// Gets the binary processor. /// </summary> public IBinaryProcessor BinaryProcessor { get { return _binaryProc; } } /// <summary> /// Configuration. /// </summary> public IgniteConfiguration Configuration { get { return _cfg; } } /// <summary> /// Handle registry. /// </summary> public HandleRegistry HandleRegistry { get { return _cbs.HandleRegistry; } } /// <summary> /// Gets the platform cache manager. /// </summary> public PlatformCacheManager PlatformCacheManager { get { return _platformCacheManager; } } /// <summary> /// Updates the node information from stream. /// </summary> /// <param name="memPtr">Stream ptr.</param> public void UpdateNodeInfo(long memPtr) { var stream = IgniteManager.Memory.Get(memPtr).GetStream(); IBinaryRawReader reader = Marshaller.StartUnmarshal(stream, false); var node = new ClusterNodeImpl(reader); node.Init(this); _nodes[node.Id] = node; } /// <summary> /// Returns instance of Ignite Transactions to mark a transaction with a special label. /// </summary> /// <param name="label"></param> /// <returns><see cref="ITransactions"/></returns> internal ITransactions GetTransactionsWithLabel(string label) { Debug.Assert(label != null); var platformTargetInternal = DoOutOpObject((int) Op.GetTransactions, s => { var w = BinaryUtils.Marshaller.StartMarshal(s); w.WriteString(label); }); return new TransactionsImpl(this, platformTargetInternal, GetLocalNode().Id, label); } /// <summary> /// Gets the node from cache. /// </summary> /// <param name="id">Node id.</param> /// <returns>Cached node.</returns> public ClusterNodeImpl GetNode(Guid? id) { return id == null ? null : _nodes[id.Value]; } /// <summary> /// Gets the interop processor. /// </summary> internal IPlatformTargetInternal InteropProcessor { get { return _proc; } } /// <summary> /// Called when local client node has been disconnected from the cluster. /// </summary> internal void OnClientDisconnected() { _clientReconnectTaskCompletionSource = new TaskCompletionSource<bool>(); var handler = ClientDisconnected; if (handler != null) handler.Invoke(this, EventArgs.Empty); } /// <summary> /// Called when local client node has been reconnected to the cluster. /// </summary> /// <param name="clusterRestarted">Cluster restarted flag.</param> internal void OnClientReconnected(bool clusterRestarted) { _marsh.OnClientReconnected(clusterRestarted); _clientReconnectTaskCompletionSource.TrySetResult(clusterRestarted); var handler = ClientReconnected; if (handler != null) handler.Invoke(this, new ClientReconnectEventArgs(clusterRestarted)); } /// <summary> /// Gets the plugin processor. /// </summary> public PluginProcessor PluginProcessor { get { return _pluginProcessor; } } /// <summary> /// Notify processor that it is safe to use. /// </summary> internal void ProcessorReleaseStart() { Target.InLongOutLong((int) Op.ReleaseStart, 0); } /// <summary> /// Checks whether log level is enabled in Java logger. /// </summary> internal bool LoggerIsLevelEnabled(LogLevel logLevel) { return Target.InLongOutLong((int) Op.LoggerIsLevelEnabled, (long) logLevel) == True; } /// <summary> /// Logs to the Java logger. /// </summary> internal void LoggerLog(LogLevel level, string msg, string category, string err) { Target.InStreamOutLong((int) Op.LoggerLog, w => { w.WriteInt((int) level); w.WriteString(msg); w.WriteString(category); w.WriteString(err); }); } /// <summary> /// Gets the platform plugin extension. /// </summary> internal IPlatformTarget GetExtension(int id) { return ((IPlatformTarget) Target).InStreamOutObject((int) Op.GetExtension, w => w.WriteInt(id)); } /** <inheritdoc /> */ public override string ToString() { return string.Format("Ignite [Name={0}]", _name); } } }
/* * Copyright (c) 2014 All Rights Reserved by the SDL Group. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.IO; using System.Collections.Generic; using System.Management.Automation; using Trisoft.ISHRemote.Exceptions; using Trisoft.ISHRemote.HelperClasses; namespace Trisoft.ISHRemote.Cmdlets.FileProcessor { /// <summary> /// <para type="synopsis">The New-IshObfuscatedFile cmdlet can be used to obfuscate the text in xml files or replace images with a generated image of the same format, width and height.</para> /// <para type="description"> /// The New-IshObfuscatedFile cmdlet can be used to: /// 1. For all files having a file extension that is present in XmlFileExtensions: /// All the words in the text of all xml files are replaced with hardcoded words of the same length. /// This includes the text in elements, the comments and the processing instructions. /// Optionally, you can specifiy the names of attributes in the XmlAttributesToObfuscate parameter for which the values need to be obfuscated as well. /// By default, attribute values are not obfuscated, as some attribute values are limited to a certain list of values defined in the DTD. /// Note that an obfuscated xml is not validated against it's DTD or schema. /// 2. For all files having a file extension that is present in ImageFileExtensions /// A new image is created with the same format, width and height as the original image. The new image will have a yellow background /// (and the filename in text in the image if it is wide enough to put it there). /// 3. For all files NOT having a file extension that is present in XmlImageExtensions or ImageFileExtensions /// A warning message is given on the console that the file could not be obfuscated /// /// It will do that for all files that are passed through the pipeline or via the -FilePath parameter. /// /// Only the successfully obfuscated files will be saved to the output folder with the same name, overwriting the file with the same name if that is already present /// When the obfuscation fails or if there is no obfuscator for the given file extension, a warning message is given on the console that the file could not be obfuscated /// /// You can specify which file extensions should be treated as xml, by specifying the XmlFileExtensions parameter. By default these are ".xml", ".dita", ".ditamap". /// You can specify which file extensions should be treated as image, by specifying the XmlFileExtensions parameter. By default these are ".png", ".gif", ".bmp", ".jpg", ".jpeg". /// </para> /// </summary> /// <example> /// <code> /// # This sample script will process all files in the input folder and save the obfuscated xml and image files in the output folder /// # Other type of files like .mpg, .mov, .swf etc. are not supported by the obfuscator, so will not be present in the output folder /// Note that the script deletes all the files in the output folder first /// /// # Input folder with the files to obfuscate /// $inputfolder = "Samples\Data-ObfuscateFiles\InputFiles" /// # Output folder with the obfuscated files. /// $outputfolder = "Samples\Data-ObfuscateFiles\OutputFiles" /// /// # Read all files to process from the inputfolder /// Get-ChildItem $inputfolder -File | /// New-IshObfuscatedFile -OutputFolder $outputfolder -XmlAttributesToObfuscate @("navtitle") /// </code> /// <para>Obfuscates all xml and image files in a certain directory</para> /// </example> /// <example> /// <code> /// $xhtmlFilePath = "C:\temp\test.html"; /// # Since we know that the .html file contains xhtml which can be loaded as xml, add it to the file extensions that should be treated as xml /// New-IshObfuscatedFile -OutputFolder "c:\out\" -FilePath $xhtmlFilePath -XmlFileExtensions @(".html") -XmlAttributesToObfuscate @() # @() = empty array /// </code> /// <para>Obfuscates one xhtml file</para> /// </example> [Cmdlet(VerbsCommon.New, "IshObfuscatedFile", SupportsShouldProcess = false)] [OutputType(typeof(FileInfo))] public sealed class NewIshObfuscatedFile : FileProcessorCmdlet { /// <summary> /// <para type="description">FilePath can be used to specify one or more input xml file location.</para> /// </summary> [Parameter(Mandatory = true, ValueFromPipeline = true)] [ValidateNotNullOrEmpty] public string[] FilePath { get; set; } /// <summary> /// <para type="description">Folder on the Windows filesystem where to store the new data files</para> /// </summary> [Parameter(Mandatory = true, ValueFromPipeline = false)] [ValidateNotNullOrEmpty] public string FolderPath { get; set; } /// <summary> /// <para type="description">The file extensions that should be treated as an xml.</para> /// </summary> [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = false)] [ValidateNotNullOrEmpty] public string[] XmlFileExtensions { get { return _xmlFileExtensions.ToArray(); } set { _xmlFileExtensions = new List<string>(value); } } /// <summary> /// <para type="description">The file extensions that should be treated as an image.</para> /// </summary> [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = false)] [ValidateNotNullOrEmpty] public string[] ImageFileExtensions { get { return _imageFileExtensions.ToArray(); } set { _imageFileExtensions = new List<string>(value); } } /// <summary> /// <para type="description">Array of attribute names for which the values need to be obfuscated as well.</para> /// </summary> [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = false)] [ValidateNotNull] public string[] XmlAttributesToObfuscate { get { return _xmlAttributesToObfuscate.ToArray(); } set { _xmlAttributesToObfuscate = new List<string>(value); } } #region Private fields /// <summary> /// Private field to store the file extensions that should be treated as an xml /// </summary> private List<string> _xmlFileExtensions = new List<string> { ".xml", ".dita", ".ditamap" }; /// <summary> /// Private field to store the file extensions that should be treated as an image /// </summary> private List<string> _imageFileExtensions = new List<string> { ".png", ".gif", ".bmp", ".jpg", ".jpeg" }; /// <summary> /// Private field to store the file extensions that should be treated as an image /// </summary> private List<string> _xmlAttributesToObfuscate = new List<string>(); /// <summary> /// Collection of the files to process /// </summary> private readonly List<FileInfo> _files = new List<FileInfo>(); #endregion protected override void BeginProcessing() { if (!Directory.Exists(FolderPath)) { WriteDebug("Creating FolderPath[${FolderPath}]"); string tempLocation = Directory.CreateDirectory(FolderPath).FullName; } base.BeginProcessing(); } /// <summary> /// Process the cmdlet. /// </summary> protected override void ProcessRecord() { try { foreach (string filePath in FilePath) { _files.Add(new FileInfo(filePath)); } } catch (TrisoftAutomationException trisoftAutomationException) { ThrowTerminatingError(new ErrorRecord(trisoftAutomationException, base.GetType().Name, ErrorCategory.InvalidOperation, null)); } catch (Exception exception) { ThrowTerminatingError(new ErrorRecord(exception, base.GetType().Name, ErrorCategory.NotSpecified, null)); } } /// <summary> /// Process the cmdlet. /// </summary> /// <exception cref="TrisoftAutomationException"></exception> /// <exception cref="Exception"></exception> /// <remarks>Writes <see cref="System.IO.FileInfo"/> to the pipeline.</remarks> protected override void EndProcessing() { try { int current = 0; WriteDebug("Obfuscating _files.Count["+_files.Count+"]"); foreach (FileInfo inputFile in _files) { string outputFilePath = Path.Combine(FolderPath, inputFile.Name); WriteDebug("Obfuscating inputFile[" + inputFile.FullName + "] to outputFile[" + outputFilePath + "]"); WriteParentProgress("Obfuscating inputFile[" + inputFile.FullName + "] to outputFile[" + outputFilePath + "]", ++current, _files.Count); try { if (_xmlFileExtensions.Contains(inputFile.Extension)) { IshObfuscator.ObfuscateXml(inputFile.FullName, outputFilePath, _xmlAttributesToObfuscate); WriteObject(new FileInfo(outputFilePath)); } else if (_imageFileExtensions.Contains(inputFile.Extension)) { IshObfuscator.ObfuscateImage(inputFile.FullName, outputFilePath); WriteObject(new FileInfo(outputFilePath)); } else { WriteVerbose("Obfuscating inputFile[" + inputFile.FullName + "] to outputFile[" + outputFilePath + "] failed: The file extension is not in the list of xml or image file extensions."); } } catch (Exception ex) { WriteWarning("Obfuscating inputFile[" + inputFile.FullName + "] to outputFile[" + outputFilePath + "] failed: " + ex.Message); } } } catch (TrisoftAutomationException trisoftAutomationException) { ThrowTerminatingError(new ErrorRecord(trisoftAutomationException, base.GetType().Name, ErrorCategory.InvalidOperation, null)); } catch (Exception exception) { ThrowTerminatingError(new ErrorRecord(exception, base.GetType().Name, ErrorCategory.NotSpecified, null)); } finally { base.EndProcessing(); } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Reflection; using System.Runtime.Serialization; using System.Web.Http; using System.Web.Http.Description; using System.Xml.Serialization; using Newtonsoft.Json; namespace OKTAIntegration.Areas.HelpPage.ModelDescriptions { /// <summary> /// Generates model descriptions for given types. /// </summary> public class ModelDescriptionGenerator { // Modify this to support more data annotation attributes. private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>> { { typeof(RequiredAttribute), a => "Required" }, { typeof(RangeAttribute), a => { RangeAttribute range = (RangeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum); } }, { typeof(MaxLengthAttribute), a => { MaxLengthAttribute maxLength = (MaxLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length); } }, { typeof(MinLengthAttribute), a => { MinLengthAttribute minLength = (MinLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length); } }, { typeof(StringLengthAttribute), a => { StringLengthAttribute strLength = (StringLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength); } }, { typeof(DataTypeAttribute), a => { DataTypeAttribute dataType = (DataTypeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString()); } }, { typeof(RegularExpressionAttribute), a => { RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern); } }, }; // Modify this to add more default documentations. private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string> { { typeof(Int16), "integer" }, { typeof(Int32), "integer" }, { typeof(Int64), "integer" }, { typeof(UInt16), "unsigned integer" }, { typeof(UInt32), "unsigned integer" }, { typeof(UInt64), "unsigned integer" }, { typeof(Byte), "byte" }, { typeof(Char), "character" }, { typeof(SByte), "signed byte" }, { typeof(Uri), "URI" }, { typeof(Single), "decimal number" }, { typeof(Double), "decimal number" }, { typeof(Decimal), "decimal number" }, { typeof(String), "string" }, { typeof(Guid), "globally unique identifier" }, { typeof(TimeSpan), "time interval" }, { typeof(DateTime), "date" }, { typeof(DateTimeOffset), "date" }, { typeof(Boolean), "boolean" }, }; private Lazy<IModelDocumentationProvider> _documentationProvider; public ModelDescriptionGenerator(HttpConfiguration config) { if (config == null) { throw new ArgumentNullException("config"); } _documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider); GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase); } public Dictionary<string, ModelDescription> GeneratedModels { get; private set; } private IModelDocumentationProvider DocumentationProvider { get { return _documentationProvider.Value; } } public ModelDescription GetOrCreateModelDescription(Type modelType) { if (modelType == null) { throw new ArgumentNullException("modelType"); } Type underlyingType = Nullable.GetUnderlyingType(modelType); if (underlyingType != null) { modelType = underlyingType; } ModelDescription modelDescription; string modelName = ModelNameHelper.GetModelName(modelType); if (GeneratedModels.TryGetValue(modelName, out modelDescription)) { if (modelType != modelDescription.ModelType) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " + "Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.", modelName, modelDescription.ModelType.FullName, modelType.FullName)); } return modelDescription; } if (DefaultTypeDocumentation.ContainsKey(modelType)) { return GenerateSimpleTypeModelDescription(modelType); } if (modelType.IsEnum) { return GenerateEnumTypeModelDescription(modelType); } if (modelType.IsGenericType) { Type[] genericArguments = modelType.GetGenericArguments(); if (genericArguments.Length == 1) { Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments); if (enumerableType.IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, genericArguments[0]); } } if (genericArguments.Length == 2) { Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments); if (dictionaryType.IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]); } Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments); if (keyValuePairType.IsAssignableFrom(modelType)) { return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]); } } } if (modelType.IsArray) { Type elementType = modelType.GetElementType(); return GenerateCollectionModelDescription(modelType, elementType); } if (modelType == typeof(NameValueCollection)) { return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string)); } if (typeof(IDictionary).IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object)); } if (typeof(IEnumerable).IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, typeof(object)); } return GenerateComplexTypeModelDescription(modelType); } // Change this to provide different name for the member. private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute) { JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>(); if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName)) { return jsonProperty.PropertyName; } if (hasDataContractAttribute) { DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>(); if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name)) { return dataMember.Name; } } return member.Name; } private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute) { JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>(); XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>(); IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>(); NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>(); ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>(); bool hasMemberAttribute = member.DeclaringType.IsEnum ? member.GetCustomAttribute<EnumMemberAttribute>() != null : member.GetCustomAttribute<DataMemberAttribute>() != null; // Display member only if all the followings are true: // no JsonIgnoreAttribute // no XmlIgnoreAttribute // no IgnoreDataMemberAttribute // no NonSerializedAttribute // no ApiExplorerSettingsAttribute with IgnoreApi set to true // no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute return jsonIgnore == null && xmlIgnore == null && ignoreDataMember == null && nonSerialized == null && (apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) && (!hasDataContractAttribute || hasMemberAttribute); } private string CreateDefaultDocumentation(Type type) { string documentation; if (DefaultTypeDocumentation.TryGetValue(type, out documentation)) { return documentation; } if (DocumentationProvider != null) { documentation = DocumentationProvider.GetDocumentation(type); } return documentation; } private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel) { List<ParameterAnnotation> annotations = new List<ParameterAnnotation>(); IEnumerable<Attribute> attributes = property.GetCustomAttributes(); foreach (Attribute attribute in attributes) { Func<object, string> textGenerator; if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator)) { annotations.Add( new ParameterAnnotation { AnnotationAttribute = attribute, Documentation = textGenerator(attribute) }); } } // Rearrange the annotations annotations.Sort((x, y) => { // Special-case RequiredAttribute so that it shows up on top if (x.AnnotationAttribute is RequiredAttribute) { return -1; } if (y.AnnotationAttribute is RequiredAttribute) { return 1; } // Sort the rest based on alphabetic order of the documentation return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase); }); foreach (ParameterAnnotation annotation in annotations) { propertyModel.Annotations.Add(annotation); } } private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType) { ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType); if (collectionModelDescription != null) { return new CollectionModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, ElementDescription = collectionModelDescription }; } return null; } private ModelDescription GenerateComplexTypeModelDescription(Type modelType) { ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(complexModelDescription.Name, complexModelDescription); bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo property in properties) { if (ShouldDisplayMember(property, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(property, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(property); } GenerateAnnotations(property, propertyModel); complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType); } } FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(field, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(field); } complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType); } } return complexModelDescription; } private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new DictionaryModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType) { EnumTypeModelDescription enumDescription = new EnumTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static)) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { EnumValueDescription enumValue = new EnumValueDescription { Name = field.Name, Value = field.GetRawConstantValue().ToString() }; if (DocumentationProvider != null) { enumValue.Documentation = DocumentationProvider.GetDocumentation(field); } enumDescription.Values.Add(enumValue); } } GeneratedModels.Add(enumDescription.Name, enumDescription); return enumDescription; } private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new KeyValuePairModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private ModelDescription GenerateSimpleTypeModelDescription(Type modelType) { SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription); return simpleModelDescription; } } }
using System; using System.IO; using System.Diagnostics; using System.Collections; using System.Collections.Generic; using Newtonsoft.Json; using SharpMake.Data; /* -----This application uses Json.Net which is under the MIT License----- The MIT License (MIT) 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. ----This application is under the MIT License---- MIT License Copyright (c) 2016 "Eclipsing Rainbows" Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ namespace SharpMake { public class SharpMakeVars { //Compiler Flags public static string COMPILER = "mcs"; public static readonly string COMPILER_OUT_FLAG = "-out:"; public static readonly string COMPILER_REFERENCE = "/reference:"; //Compile types. public static readonly string TYPE_EXE = "exe"; public static readonly string TYPE_LIB = "library"; //Compile Architectures public static readonly string ARCH_ANY = "anycpu"; public static readonly string ARCH_ANY32 = "anycpu32bitpreferred"; public static readonly string ARCH_ARM = "arm"; public static readonly string ARCH_X86 = "x86"; public static readonly string ARCH_X64 = "x64"; public static readonly string ARCH_ITA = "itanium"; } public class SharpMake { /* (makefile) | select Makefile by name, otherwise "Makefile" is selected (if found). -v/--verbose | verbose output -h/--help | Show help -o/--out (file name) | overwrite output file. --about | about information. --outputdir (dir) | overwrite output directory. --arch (architecture) | overwrite output target architecture. --binref (file) | Adds an binary reference to a file. --asmref (assembly) | Adds an reference to an .NET assembly --pkgref (package) | Adds an package reference.*/ private static bool IS_VERBOSE = false; private static string CMD_ARGS = ""; private static string CRT_MKFL = "Makefile"; private static int TARGET = 0; private static string TARGET_NAME = "default"; private static MakefileData CONFIG; private static bool COMMAND_ONLY = false; private static string forced_output = ""; private static List<string> forced_asm = new List<string>(); public static void Main(string[] args) { if (System.Environment.OSVersion.Platform == PlatformID.Win32NT || System.Environment.OSVersion.Platform == PlatformID.Win32S || System.Environment.OSVersion.Platform == PlatformID.Win32Windows) SharpMakeVars.COMPILER = "csc.exe"; if (args.Length > 0) { for (int i = 0; i < args.Length; i++) { string arg = args[i].ToLower(); if (arg == "--help" || arg == "-h") { Console.WriteLine(GetHelpStr()); Exit(); } else if (arg == "--about") { Console.WriteLine(GetAboutStr()); Exit(); } else if (arg == "--license") { Console.WriteLine(GetLicenseStr()); Exit(); } else if (arg == "--verbose" || arg == "-v") { IS_VERBOSE = true; } else if (arg == ("--makefile") || arg == "-m") { var mkfile = args[i+1]; if (File.Exists(mkfile)) CRT_MKFL = mkfile; i++; } else if (arg == "--out" || arg == "-o") { forced_output = args[i+1]; i++; } else if (arg == "--mono") { if (System.Environment.OSVersion.Platform == PlatformID.Win32NT || System.Environment.OSVersion.Platform == PlatformID.Win32S || System.Environment.OSVersion.Platform == PlatformID.Win32Windows) SharpMakeVars.COMPILER = "mcs"; else ErrorPrint("Your system uses Mono by default!", false); } else { TARGET_NAME = arg; } } } if (File.Exists(CRT_MKFL)) { var dat = File.ReadAllText(CRT_MKFL); try { Print("Loading Makefile..."); CONFIG = JsonConvert.DeserializeObject<MakefileData>(dat); } catch { ErrorPrint("Could not parse Makefile, try checking for syntax errors.", true); } if (CONFIG.target.Count < 1) { ErrorPrint("No targets in file!", true); } foreach(string arg in args) { if (arg == "--clean") { Print("Clearning " + CONFIG.target[TARGET].output_dir + "..."); foreach(string f in Directory.GetFiles(CONFIG.target[TARGET].output_dir)) { Print("Removing " + f + "..."); File.Delete(f); } Exit(); } } if (ContainsTargetName(TARGET_NAME) && TARGET_NAME.ToLower() != "default") { TARGET = GetTargetIdFromName(TARGET_NAME); } else { if (TARGET_NAME.ToLower() != "default") ErrorPrint(string.Format("Could not find target '{0}'.", TARGET_NAME), true); } BeginRecipePre(); if (!COMMAND_ONLY) BeginBuild(); else Print("Command-only recipe rules, skipping building steps."); BeginRecipePost(); } else ErrorPrint(string.Format("Could not find a Makefile with the name \"{0}\".", CRT_MKFL), true); } private static bool ContainsTargetName(string name) { foreach(Target t in CONFIG.target) { if (t.target_name == name) return true; } return false; } private static int GetTargetIdFromName(string name) { int index = 0; foreach(Target t in CONFIG.target) { if (t.target_name == name) return index; index++; } return -1; } private static bool ContainsRecipeWithName(string name, bool alert) { if (CONFIG.target[TARGET].recipes != null && CONFIG.target[TARGET].recipes.Count > 0) { foreach(Recipes r in CONFIG.target[TARGET].recipes) { if (r.recipe_name == name) { COMMAND_ONLY = r.command_only; return true; } } return false; } else { if (alert) Print("No Recipes found!"); } return false; } public enum RecipeTiming { Pre, Post } static List<string> GetFilesRecursivley(string dir) { List<string> files = new List<string>(); try { foreach (string f in Directory.GetFiles(dir)) { files.Add(f); } foreach (string d in Directory.GetDirectories(dir)) { foreach (string fi in GetFilesRecursivley(d)) { files.Add(fi); } } } catch (System.Exception excpt) { Console.WriteLine(excpt.Message); } return files; } private static List<RecipeData> GetRecipesFor(string name, RecipeTiming timing) { List<RecipeData> output = new List<RecipeData>(); foreach(Recipes r in CONFIG.target[TARGET].recipes) { if (r.recipe_name == name) { foreach(RecipeData dat in r.recipe_data) { if (dat.is_post && timing == RecipeTiming.Post) output.Add (dat); else if (!dat.is_post && timing == RecipeTiming.Pre) output.Add (dat); } } } return output; } private static System.Diagnostics.Stopwatch recipeWatch = null; private static void BeginRecipePre() { Print("Running pre-recipes for " + CONFIG.target[TARGET].target_name + "..."); if (ContainsRecipeWithName(CONFIG.target[TARGET].target_name, true)) { if (COMMAND_ONLY) { recipeWatch = System.Diagnostics.Stopwatch.StartNew(); } foreach(var data in GetRecipesFor(CONFIG.target[TARGET].target_name, RecipeTiming.Pre)) { foreach(var dat in data.commands) { string command = dat.Split(' ')[0]; string args = dat.Substring(command.Length); RunCommandIndep(command, args); } } } } private static void BeginRecipePost() { Print("Running post-recipes for " + CONFIG.target[TARGET].target_name + "..."); if (ContainsRecipeWithName(CONFIG.target[TARGET].target_name, false)) { foreach(var data in GetRecipesFor(CONFIG.target[TARGET].target_name, RecipeTiming.Post)) { foreach(var dat in data.commands) { string command = dat.Split(' ')[0]; string args = dat.Substring(command.Length); RunCommandIndep(command, args); } } } if (COMMAND_ONLY) { recipeWatch.Stop(); var elapsedMs = recipeWatch.ElapsedMilliseconds; Print(string.Format("Done! [Recipe Time {0}ms]", elapsedMs)); } } private static void BeginBuild() { if (!COMMAND_ONLY) { var watch = System.Diagnostics.Stopwatch.StartNew(); if (!string.IsNullOrEmpty(forced_output)) CONFIG.target[TARGET].output = forced_output; if (IS_VERBOSE) { Console.WriteLine("[VERBOSE ENABLED]\n"); Console.WriteLine(RunCommand("mcs", "--about")); } //VerbosePrint("InputJSON: \n" + File.ReadAllText(CRT_MKFL)); VerbosePrint("OutputFile: " + CONFIG.target[TARGET].output + " | OutputType: " + CONFIG.target[TARGET].output_type); Print("Preparing output directory..."); GetDir(CONFIG.target[TARGET].output_dir); Print("Adding files to build queue..."); foreach(string file in GetFilesRecursivley(CONFIG.target[TARGET].code_root)) { AddFile(file); } Print("Referencing Assemblies..."); foreach(string asm in Directory.GetFiles(CONFIG.target[TARGET].lib_dir)) { VerbosePrint("Checking out assembly: " + asm + "..."); if (CONFIG.target[TARGET].ref_asm.Contains(asm.Replace(CONFIG.target[TARGET].lib_dir, ""))) { ReferenceAssembly(asm); if (!File.Exists(CONFIG.target[TARGET].output_dir + asm.Replace(CONFIG.target[TARGET].lib_dir, ""))) File.Copy(asm, CONFIG.target[TARGET].output_dir + asm.Replace(CONFIG.target[TARGET].lib_dir, "")); } } Print("Referencing Packages..."); foreach(string pkg in CONFIG.target[TARGET].ref_pkgs) { AddPackage(pkg); } SetOutputFile(); if (!IS_VERBOSE) Print(string.Format("Compiling {0} to {1}...",CONFIG.target[TARGET].output + TranslateExtensionNoAction(CONFIG.target[TARGET].output_type), CONFIG.target[TARGET].output_dir)); VerbosePrint("Running Compiler... [mcs " + CMD_ARGS + "]"); if (!IS_VERBOSE) RunCommand("mcs", CMD_ARGS); else RunCommandIndep("mcs", CMD_ARGS); watch.Stop(); var elapsedMs = watch.ElapsedMilliseconds; Print(string.Format("Done! [Build Time {0}ms]", elapsedMs)); } } private static void AddPackage(string package) { VerbosePrint("Adding reference to package: " + package + "..."); CMD_ARGS += "-pkg:" + package + " "; } private static void AddFile(string file) { VerbosePrint("Adding file: " + file + " to build queue..."); if (!file.ToLower().EndsWith(".cs")) CMD_ARGS += "-resource:" + file + " "; else CMD_ARGS += file + " "; } private static void VerbosePrint(string message) { if (IS_VERBOSE) Console.WriteLine("[VERBOSE] " + message); } private static void Print(string message) { Console.WriteLine("[INFO] " + message); } private static void ErrorPrint(string message, bool fatal) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("[INFO] " + message); Console.ForegroundColor = ConsoleColor.Gray; if (fatal) Exit(); } private static void SetOutputFile() { CMD_ARGS += "-o " + CONFIG.target[TARGET].output_dir + CONFIG.target[TARGET].output + TranslateExtension(CONFIG.target[TARGET].output_type) + " "; } private static string TranslateExtension(string input) { if (input.ToLower() == "lib" || input.ToLower() == "library" || input.ToLower() == "dll" || input.ToLower() == "so") return ".dll -target:library"; else if (input.ToLower() == "exe" || input.ToLower() == "executable" || input.ToLower() == "app" || input.ToLower() == "application") return ".exe -target:exe"; return ".o -target:library"; } private static string TranslateExtensionNoAction(string input) { if (input.ToLower() == "lib" || input.ToLower() == "library" || input.ToLower() == "dll" || input.ToLower() == "so") return ".dll"; else if (input.ToLower() == "exe" || input.ToLower() == "executable" || input.ToLower() == "app" || input.ToLower() == "application") return ".exe"; return ".o"; } private static string TranslateOutputType(string input) { if (input == "lib") return SharpMakeVars.TYPE_LIB; else if (input == "exe") return SharpMakeVars.TYPE_EXE; throw new Exception("Unrecognized Output Type!"); } private static void ReferenceAssembly(string assembly) { CMD_ARGS += SharpMakeVars.COMPILER_REFERENCE + assembly + " "; VerbosePrint("Adding Reference: " + assembly + " to build queue..."); } private static void Exit() { Environment.Exit(0); } private static void RunCommandIndep(string command, string arguments) { Process proc = new Process(); proc.StartInfo.UseShellExecute = false; proc.StartInfo.RedirectStandardOutput = false; proc.StartInfo.RedirectStandardError = false; proc.StartInfo.FileName = command; proc.StartInfo.Arguments = arguments; proc.Start(); proc.WaitForExit (); } private static string RunCommand(string command, string arguments) { Process proc = new Process(); proc.StartInfo.UseShellExecute = false; proc.StartInfo.RedirectStandardOutput = true; proc.StartInfo.RedirectStandardError = true; proc.StartInfo.FileName = command; proc.StartInfo.Arguments = arguments; proc.Start(); string output = ""; string sec_output = ""; string lastline = ""; string lastErline = ""; sec_output = proc.StandardOutput.ReadToEnd(); sec_output += proc.StandardError.ReadToEnd(); while (!proc.StandardOutput.EndOfStream && !proc.StandardError.EndOfStream){ string currentLine = proc.StandardOutput.ReadLine (); if (currentLine != lastline) { Console.WriteLine (currentLine); output += currentLine + "\n"; } lastline = currentLine; string currentErLine = proc.StandardError.ReadLine (); if (currentErLine != lastErline) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine (currentErLine); Console.ForegroundColor = ConsoleColor.Gray; output += currentErLine + "\n"; } lastErline = currentErLine; } proc.WaitForExit (); if (output != "") return output; else return sec_output; } // Gets a directory, makes it if not found private static string GetDir(string dir) { try { string[] dirs = Directory.GetDirectories(dir); if (dirs.Length > 1) return dirs[0]; } catch { Directory.CreateDirectory(dir); } return dir; } private static string GetLicenseStr() { return @" -----This application uses Json.Net which is under the MIT License----- The MIT License (MIT) 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. ----This application is under the MIT License---- MIT License Copyright (c) 2016 'Eclipsing Rainbows' 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."; } private static string GetAboutStr() { return @"---About--- #Make ('smake') JSON based .NET application Makefile System by Eclipsing Rainbows [https://twitter.com/EclipsingR] This application is using Newtonsoft's JSON.Net library [https://github.com/JamesNK/Newtonsoft.Json] Run 'smake --license' to see license information, or consult the LICENSE file bundled with this application. "; } private static string GetHelpStr() { return @"How To: To run this application, just run 'smake' and the output file should be made. If the makefile is not called 'Makefile', please select the name of the makefile as an argument. Note for Makefile creators: Default makefile is the first makefile in the list! Example Usage: smake | Default run smake -m OtherMakefile build_and_clean | Select Makefile 'OtherMakeFile' and run 'build_and_clean' in it. smake --verbose --mono --arch x86 | Run verbose, force 32 bit and force to use mono. Arguments (Optional): [target] | Select target to be run. -m/--makefile <file> | Select Makefile by name, otherwise 'Makefile' is selected (if found). -v/verbose | Enable verbose logging output. -h/--help | Show help. -o/--out <file name> | Overwrite output file. --about | Shows about information. --license | Shows license information. --outputdir <dir> | Overrides output directory. --arch <architecture> | Overrides output target architecture. --binref <file> | Adds an binary reference to a file. --asmref <assembly> | Adds an reference to an .NET assembly --pkgref <package> | Adds an package reference. --mono | Force to use mcs. (Windows only) --clean | Cleans build output folder."; } } }
using System; using System.Data; using System.Data.OleDb; using PCSComUtils.DataAccess; using PCSComUtils.PCSExc; using PCSComUtils.Common; using PCSComUtils.Common.BO; using System.Text; using PCSComUtils.DataContext; namespace PCSComProduction.WorkOrder.DS { public class PRO_WorkOrderCompletionDS { const string PRO = " Product"; const string UM = "UnitOfMeasure"; const string CAPTION_UM = "UM"; const string WOD = " WODetail"; const string CQ = " Compqty"; const string SQ = " Scrapqty"; const string OPENQUANTITY = "OpenQuantity"; const string COMPQTY = "CompletedQuantity"; const string SCRAPQUANTITY = "ScrapQuantity"; const string WOC = " WOCompletion"; const string WOM = " WOMaster"; const string LOC = " Location"; const string BIN = " Bin"; private const string THIS = "PCSComProduction.WorkOrder.DS.PRO_WorkOrderCompletionDS"; public DataTable GetAvailableQtyByPostDate(DateTime pdtmPostDate) { const string SQL_DATETIME_FORMAT = "yyyy-MM-dd HH:mm"; const string BINAVAILABLE_FLD = "BinAvailable"; DataTable dtbResultTable = new DataTable(); OleDbConnection oconPCS = null; OleDbCommand ocmdPCS = null; if (pdtmPostDate == DateTime.MinValue) pdtmPostDate = (new UtilsBO()).GetDBDate(); string strSql = "SELECT DISTINCT"; strSql += " child.ProductID,"; strSql += " (ISNULL(SUM(ISNULL(bc.OHQuantity, 0) - ISNULL(bc.CommitQuantity, 0)), 0)"; strSql += " + ISNULL((SELECT SUM(CASE T.Type"; strSql += " WHEN 1 THEN -Quantity"; strSql += " WHEN 0 THEN Quantity"; strSql += " WHEN 2 THEN -Quantity"; strSql += " END) Quantity"; strSql += " FROM MST_TransactionHistory H JOIN MST_TranType T ON H.TranTypeID = T.TranTypeID"; strSql += " WHERE T.Type IN (0,1,2)"; strSql += " AND PostDate > '" + pdtmPostDate.ToString(SQL_DATETIME_FORMAT) + "'"; strSql += " AND LocationID = bc.LocationID"; strSql += " AND BinID = bc.BinID"; strSql += " AND ProductID = bc.ProductID),0)"; strSql += " ) as " + BINAVAILABLE_FLD; strSql += " , bc.ProductID"; strSql += " , bc.BinID"; strSql += " , bc.LocationID"; strSql += " ,PRO_ProductionLine.ProductionLineID"; strSql += " FROM PRO_WorkOrderDetail woi"; strSql += " INNER JOIN ITM_BOM bom ON woi.ProductID = bom.ProductID"; strSql += " INNER JOIN ITM_Product child ON bom.ComponentID = child.ProductID"; strSql += " INNER JOIN IV_BinCache bc ON bc.ProductID = child.ProductID"; strSql += " INNER JOIN MST_BIN ON MST_BIN.BinID = bc.BinID"; strSql += " INNER JOIN PRO_ProductionLine ON PRO_ProductionLine.LocationID = bc.LocationID"; strSql += " WHERE MST_BIN.BinTypeID = " + (int)BinTypeEnum.IN; //strSql += " AND PRO_ProductionLine.ProductionLineID = " + pintProductionLineID; //strSql += " AND woi.WorkOrderDetailID = " + pintWODetailId; strSql += " GROUP BY bc.ProductID, bc.BinID, bc.LocationID,"; strSql += " bc.CCNID, bc.MasterLocationID, child.ProductID,PRO_ProductionLine.ProductionLineID"; oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.CommandTimeout = 10000; ocmdPCS.Connection.Open(); OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS); odadPCS.Fill(dtbResultTable); return dtbResultTable; } public DataTable GetAvailableQuantityByProductionLinePostDate(DateTime pdtmPostDate, int pintProductionLineID, int pintWODetailId) { const string SQL_DATETIME_FORMAT = "yyyy-MM-dd HH:mm"; const string BINAVAILABLE_FLD = "BinAvailable"; DataTable dtbResultTable = new DataTable(); OleDbConnection oconPCS = null; OleDbCommand ocmdPCS = null; if (pdtmPostDate == DateTime.MinValue) pdtmPostDate = (new UtilsBO()).GetDBDate(); string strSql = "SELECT DISTINCT"; strSql += " child.ProductID,"; strSql += " (ISNULL(SUM(ISNULL(bc.OHQuantity, 0) - ISNULL(bc.CommitQuantity, 0)), 0)"; strSql += " + ISNULL((SELECT SUM(CASE T.Type"; strSql += " WHEN 1 THEN -Quantity"; strSql += " WHEN 0 THEN Quantity"; strSql += " WHEN 2 THEN -Quantity"; strSql += " END) Quantity"; strSql += " FROM MST_TransactionHistory H JOIN MST_TranType T ON H.TranTypeID = T.TranTypeID"; strSql += " WHERE T.Type IN (0,1,2)"; strSql += " AND PostDate > '" + pdtmPostDate.ToString(SQL_DATETIME_FORMAT) + "'"; strSql += " AND LocationID = bc.LocationID"; strSql += " AND BinID = bc.BinID"; strSql += " AND ProductID = bc.ProductID),0)"; strSql += " ) as " + BINAVAILABLE_FLD; strSql += " , bc.ProductID"; strSql += " , bc.BinID"; strSql += " , bc.LocationID"; strSql += " FROM PRO_WorkOrderDetail woi"; strSql += " INNER JOIN ITM_BOM bom ON woi.ProductID = bom.ProductID"; strSql += " INNER JOIN ITM_Product child ON bom.ComponentID = child.ProductID"; strSql += " INNER JOIN IV_BinCache bc ON bc.ProductID = child.ProductID"; strSql += " INNER JOIN MST_BIN ON MST_BIN.BinID = bc.BinID"; strSql += " INNER JOIN PRO_ProductionLine ON PRO_ProductionLine.LocationID = bc.LocationID"; strSql += " WHERE MST_BIN.BinTypeID = " + (int)BinTypeEnum.IN; strSql += " AND PRO_ProductionLine.ProductionLineID = " + pintProductionLineID; strSql += " AND woi.WorkOrderDetailID = " + pintWODetailId; strSql += " GROUP BY bc.ProductID, bc.BinID, bc.LocationID,"; strSql += " bc.CCNID, bc.MasterLocationID, child.ProductID"; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.CommandTimeout = 10000; ocmdPCS.Connection.Open(); OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS); odadPCS.Fill(dtbResultTable); return dtbResultTable; } public void Add(PRO_WorkOrderCompletion objObject) { const string METHOD_NAME = THIS + ".Add()"; OleDbConnection oconPCS = null; OleDbCommand ocmdPCS = null; try { string strSql = String.Empty; oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand("", oconPCS); strSql = "INSERT INTO PRO_WorkOrderCompletion(" + PRO_WorkOrderCompletionTable.POSTDATE_FLD + "," + PRO_WorkOrderCompletionTable.WOCOMPLETIONNO_FLD + "," + PRO_WorkOrderCompletionTable.COMPLETEDQUANTITY_FLD + "," + PRO_WorkOrderCompletionTable.LOT_FLD + "," + PRO_WorkOrderCompletionTable.SERIAL_FLD + "," + PRO_WorkOrderCompletionTable.LOCATIONID_FLD + "," + PRO_WorkOrderCompletionTable.BINID_FLD + "," + PRO_WorkOrderCompletionTable.CCNID_FLD + "," + PRO_WorkOrderCompletionTable.MASTERLOCATIONID_FLD + "," + PRO_WorkOrderCompletionTable.PRODUCTID_FLD + "," + PRO_WorkOrderCompletionTable.STOCKUMID_FLD + "," + PRO_WorkOrderCompletionTable.WORKORDERMASTERID_FLD + "," + PRO_WorkOrderCompletionTable.WORKORDERDETAILID_FLD + "," + PRO_WorkOrderCompletionTable.SHIFTID_FLD + "," + PRO_WorkOrderCompletionTable.ISSUEPURPOSEID_FLD + "," + PRO_WorkOrderCompletionTable.REMARK_FLD + "," + PRO_WorkOrderCompletionTable.QASTATUS_FLD + ")" + "VALUES(?, ?, ?, ?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; ocmdPCS.Parameters.Add(new OleDbParameter(PRO_WorkOrderCompletionTable.POSTDATE_FLD, OleDbType.Date)); ocmdPCS.Parameters[PRO_WorkOrderCompletionTable.POSTDATE_FLD].Value = objObject.PostDate; ocmdPCS.Parameters.Add(new OleDbParameter(PRO_WorkOrderCompletionTable.WOCOMPLETIONNO_FLD, OleDbType.VarWChar)); ocmdPCS.Parameters[PRO_WorkOrderCompletionTable.WOCOMPLETIONNO_FLD].Value = objObject.WOCompletionNo; ocmdPCS.Parameters.Add(new OleDbParameter(PRO_WorkOrderCompletionTable.COMPLETEDQUANTITY_FLD, OleDbType.Decimal)); ocmdPCS.Parameters[PRO_WorkOrderCompletionTable.COMPLETEDQUANTITY_FLD].Value = objObject.CompletedQuantity; ocmdPCS.Parameters.Add(new OleDbParameter(PRO_WorkOrderCompletionTable.LOT_FLD, OleDbType.VarWChar)); ocmdPCS.Parameters[PRO_WorkOrderCompletionTable.LOT_FLD].Value = objObject.Lot; ocmdPCS.Parameters.Add(new OleDbParameter(PRO_WorkOrderCompletionTable.SERIAL_FLD, OleDbType.VarWChar)); ocmdPCS.Parameters[PRO_WorkOrderCompletionTable.SERIAL_FLD].Value = objObject.Serial; ocmdPCS.Parameters.Add(new OleDbParameter(PRO_WorkOrderCompletionTable.LOCATIONID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[PRO_WorkOrderCompletionTable.LOCATIONID_FLD].Value = objObject.LocationID; ocmdPCS.Parameters.Add(new OleDbParameter(PRO_WorkOrderCompletionTable.BINID_FLD, OleDbType.Integer)); if (objObject.BinID != null) { ocmdPCS.Parameters[PRO_WorkOrderCompletionTable.BINID_FLD].Value = objObject.BinID; } else ocmdPCS.Parameters[PRO_WorkOrderCompletionTable.BINID_FLD].Value = DBNull.Value; ocmdPCS.Parameters.Add(new OleDbParameter(PRO_WorkOrderCompletionTable.CCNID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[PRO_WorkOrderCompletionTable.CCNID_FLD].Value = objObject.CCNID; ocmdPCS.Parameters.Add(new OleDbParameter(PRO_WorkOrderCompletionTable.MASTERLOCATIONID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[PRO_WorkOrderCompletionTable.MASTERLOCATIONID_FLD].Value = objObject.MasterLocationID; ocmdPCS.Parameters.Add(new OleDbParameter(PRO_WorkOrderCompletionTable.PRODUCTID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[PRO_WorkOrderCompletionTable.PRODUCTID_FLD].Value = objObject.ProductID; ocmdPCS.Parameters.Add(new OleDbParameter(PRO_WorkOrderCompletionTable.STOCKUMID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[PRO_WorkOrderCompletionTable.STOCKUMID_FLD].Value = objObject.StockUMID; ocmdPCS.Parameters.Add(new OleDbParameter(PRO_WorkOrderCompletionTable.WORKORDERMASTERID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[PRO_WorkOrderCompletionTable.WORKORDERMASTERID_FLD].Value = objObject.WorkOrderMasterID; ocmdPCS.Parameters.Add(new OleDbParameter(PRO_WorkOrderCompletionTable.WORKORDERDETAILID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[PRO_WorkOrderCompletionTable.WORKORDERDETAILID_FLD].Value = objObject.WorkOrderDetailID; //HACKED: Added by Tuan TQ. 09 Dec, 2005: Add more properties ocmdPCS.Parameters.Add(new OleDbParameter(PRO_WorkOrderCompletionTable.SHIFTID_FLD, OleDbType.Integer)); if (objObject.ShiftID != null & objObject.ShiftID > 0) { ocmdPCS.Parameters[PRO_WorkOrderCompletionTable.SHIFTID_FLD].Value = objObject.ShiftID; } else { ocmdPCS.Parameters[PRO_WorkOrderCompletionTable.SHIFTID_FLD].Value = DBNull.Value; } ocmdPCS.Parameters.Add(new OleDbParameter(PRO_WorkOrderCompletionTable.ISSUEPURPOSEID_FLD, OleDbType.Integer)); if (objObject.IssuePurposeID != null && objObject.IssuePurposeID > 0) { ocmdPCS.Parameters[PRO_WorkOrderCompletionTable.ISSUEPURPOSEID_FLD].Value = objObject.IssuePurposeID; } else { ocmdPCS.Parameters[PRO_WorkOrderCompletionTable.ISSUEPURPOSEID_FLD].Value = DBNull.Value; } ocmdPCS.Parameters.Add(new OleDbParameter(PRO_WorkOrderCompletionTable.REMARK_FLD, OleDbType.WChar)); ocmdPCS.Parameters[PRO_WorkOrderCompletionTable.REMARK_FLD].Value = objObject.Remark; //End Hacked ocmdPCS.Parameters.Add(new OleDbParameter(PRO_WorkOrderCompletionTable.QASTATUS_FLD, OleDbType.Integer)); ocmdPCS.Parameters[PRO_WorkOrderCompletionTable.QASTATUS_FLD].Value = objObject.QAStatus; ocmdPCS.CommandText = strSql; ocmdPCS.Connection.Open(); ocmdPCS.ExecuteNonQuery(); } catch (OleDbException ex) { if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE) { throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex); } else { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex); } } catch (InvalidOperationException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS != null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } /// <summary> /// AddAndReturnID /// </summary> /// <param name="pobjObjectVO"></param> /// <returns></returns> /// <author>Trada</author> /// <date>Friday, August 19 2005</date> public int AddAndReturnID(PRO_WorkOrderCompletion objObject) { const string METHOD_NAME = THIS + ".AddAndReturnID()"; OleDbConnection oconPCS = null; OleDbCommand ocmdPCS = null; try { oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(string.Empty, oconPCS); ocmdPCS.CommandTimeout = 10000; StringBuilder strSql = new StringBuilder("INSERT INTO PRO_WorkOrderCompletion("); strSql.Append(PRO_WorkOrderCompletionTable.POSTDATE_FLD + ","); strSql.Append(PRO_WorkOrderCompletionTable.WOCOMPLETIONDAT_FLD + ","); strSql.Append(PRO_WorkOrderCompletionTable.WOCOMPLETIONNO_FLD + ","); strSql.Append(PRO_WorkOrderCompletionTable.COMPLETEDQUANTITY_FLD + ","); strSql.Append(PRO_WorkOrderCompletionTable.LOT_FLD + ","); strSql.Append(PRO_WorkOrderCompletionTable.SERIAL_FLD + ","); strSql.Append(PRO_WorkOrderCompletionTable.LOCATIONID_FLD + ","); strSql.Append(PRO_WorkOrderCompletionTable.BINID_FLD + ","); strSql.Append(PRO_WorkOrderCompletionTable.CCNID_FLD + ","); strSql.Append(PRO_WorkOrderCompletionTable.MASTERLOCATIONID_FLD + ","); strSql.Append(PRO_WorkOrderCompletionTable.PRODUCTID_FLD + ","); strSql.Append(PRO_WorkOrderCompletionTable.STOCKUMID_FLD + ","); strSql.Append(PRO_WorkOrderCompletionTable.WORKORDERMASTERID_FLD + ","); strSql.Append(PRO_WorkOrderCompletionTable.WORKORDERDETAILID_FLD + ","); strSql.Append(PRO_WorkOrderCompletionTable.SHIFTID_FLD + ","); strSql.Append(PRO_WorkOrderCompletionTable.ISSUEPURPOSEID_FLD + ","); strSql.Append(PRO_WorkOrderCompletionTable.REMARK_FLD + ","); //strSql.Append("TransNo" + ","); strSql.Append(PRO_WorkOrderCompletionTable.QASTATUS_FLD + ")"); strSql.Append("VALUES(?, ?, ?, ?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) SELECT @@IDENTITY"); ocmdPCS.Parameters.Add(new OleDbParameter(PRO_WorkOrderCompletionTable.POSTDATE_FLD, OleDbType.Date)); ocmdPCS.Parameters[PRO_WorkOrderCompletionTable.POSTDATE_FLD].Value = objObject.PostDate; ocmdPCS.Parameters.Add(new OleDbParameter(PRO_WorkOrderCompletionTable.WOCOMPLETIONDAT_FLD, OleDbType.Date)); if (objObject.CompletedDate != null && objObject.CompletedDate != DateTime.MinValue) { ocmdPCS.Parameters[PRO_WorkOrderCompletionTable.WOCOMPLETIONDAT_FLD].Value = objObject.CompletedDate; } else ocmdPCS.Parameters[PRO_WorkOrderCompletionTable.WOCOMPLETIONDAT_FLD].Value = DBNull.Value; ocmdPCS.Parameters.Add(new OleDbParameter(PRO_WorkOrderCompletionTable.WOCOMPLETIONNO_FLD, OleDbType.VarWChar)); ocmdPCS.Parameters[PRO_WorkOrderCompletionTable.WOCOMPLETIONNO_FLD].Value = objObject.WOCompletionNo; ocmdPCS.Parameters.Add(new OleDbParameter(PRO_WorkOrderCompletionTable.COMPLETEDQUANTITY_FLD, OleDbType.Decimal)); ocmdPCS.Parameters[PRO_WorkOrderCompletionTable.COMPLETEDQUANTITY_FLD].Value = objObject.CompletedQuantity; ocmdPCS.Parameters.Add(new OleDbParameter(PRO_WorkOrderCompletionTable.LOT_FLD, OleDbType.VarWChar)); ocmdPCS.Parameters[PRO_WorkOrderCompletionTable.LOT_FLD].Value = objObject.Lot; ocmdPCS.Parameters.Add(new OleDbParameter(PRO_WorkOrderCompletionTable.SERIAL_FLD, OleDbType.VarWChar)); ocmdPCS.Parameters[PRO_WorkOrderCompletionTable.SERIAL_FLD].Value = objObject.Serial; ocmdPCS.Parameters.Add(new OleDbParameter(PRO_WorkOrderCompletionTable.LOCATIONID_FLD, OleDbType.Integer)); if (objObject.LocationID != null && objObject.LocationID > 0) ocmdPCS.Parameters[PRO_WorkOrderCompletionTable.LOCATIONID_FLD].Value = objObject.LocationID; else ocmdPCS.Parameters[PRO_WorkOrderCompletionTable.LOCATIONID_FLD].Value = DBNull.Value; ocmdPCS.Parameters.Add(new OleDbParameter(PRO_WorkOrderCompletionTable.BINID_FLD, OleDbType.Integer)); if (objObject.BinID != 0) { ocmdPCS.Parameters[PRO_WorkOrderCompletionTable.BINID_FLD].Value = objObject.BinID; } else ocmdPCS.Parameters[PRO_WorkOrderCompletionTable.BINID_FLD].Value = DBNull.Value; ocmdPCS.Parameters.Add(new OleDbParameter(PRO_WorkOrderCompletionTable.CCNID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[PRO_WorkOrderCompletionTable.CCNID_FLD].Value = objObject.CCNID; ocmdPCS.Parameters.Add(new OleDbParameter(PRO_WorkOrderCompletionTable.MASTERLOCATIONID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[PRO_WorkOrderCompletionTable.MASTERLOCATIONID_FLD].Value = objObject.MasterLocationID; ocmdPCS.Parameters.Add(new OleDbParameter(PRO_WorkOrderCompletionTable.PRODUCTID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[PRO_WorkOrderCompletionTable.PRODUCTID_FLD].Value = objObject.ProductID; ocmdPCS.Parameters.Add(new OleDbParameter(PRO_WorkOrderCompletionTable.STOCKUMID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[PRO_WorkOrderCompletionTable.STOCKUMID_FLD].Value = objObject.StockUMID; ocmdPCS.Parameters.Add(new OleDbParameter(PRO_WorkOrderCompletionTable.WORKORDERMASTERID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[PRO_WorkOrderCompletionTable.WORKORDERMASTERID_FLD].Value = objObject.WorkOrderMasterID; ocmdPCS.Parameters.Add(new OleDbParameter(PRO_WorkOrderCompletionTable.WORKORDERDETAILID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[PRO_WorkOrderCompletionTable.WORKORDERDETAILID_FLD].Value = objObject.WorkOrderDetailID; //HACKED: Added by Tuan TQ. 09 Dec, 2005: Add more properties ocmdPCS.Parameters.Add(new OleDbParameter(PRO_WorkOrderCompletionTable.SHIFTID_FLD, OleDbType.Integer)); if (objObject.ShiftID > 0) { ocmdPCS.Parameters[PRO_WorkOrderCompletionTable.SHIFTID_FLD].Value = objObject.ShiftID; } else { ocmdPCS.Parameters[PRO_WorkOrderCompletionTable.SHIFTID_FLD].Value = DBNull.Value; } ocmdPCS.Parameters.Add(new OleDbParameter(PRO_WorkOrderCompletionTable.ISSUEPURPOSEID_FLD, OleDbType.Integer)); if (objObject.IssuePurposeID > 0) { ocmdPCS.Parameters[PRO_WorkOrderCompletionTable.ISSUEPURPOSEID_FLD].Value = objObject.IssuePurposeID; } else { ocmdPCS.Parameters[PRO_WorkOrderCompletionTable.ISSUEPURPOSEID_FLD].Value = DBNull.Value; } ocmdPCS.Parameters.Add(new OleDbParameter(PRO_WorkOrderCompletionTable.REMARK_FLD, OleDbType.WChar)); ocmdPCS.Parameters[PRO_WorkOrderCompletionTable.REMARK_FLD].Value = objObject.Remark; //End Hacked //ocmdPCS.Parameters.Add(new OleDbParameter("TransNo", OleDbType.WChar)); //ocmdPCS.Parameters["TransNo"].Value = objObject.TransNo; ocmdPCS.Parameters.Add(new OleDbParameter(PRO_WorkOrderCompletionTable.QASTATUS_FLD, OleDbType.Integer)); ocmdPCS.Parameters[PRO_WorkOrderCompletionTable.QASTATUS_FLD].Value = objObject.QAStatus; ocmdPCS.CommandText = strSql.ToString(); ocmdPCS.Connection.Open(); object objResult = ocmdPCS.ExecuteScalar(); if ((objResult != null) && (objResult != DBNull.Value)) { return int.Parse(objResult.ToString()); } } catch (OleDbException ex) { if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE) { throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex); } else { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex); } } catch (InvalidOperationException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS != null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } return 0; } public void Delete(int pintID) { const string METHOD_NAME = THIS + ".Delete()"; string strSql = String.Empty; strSql = "DELETE " + PRO_WorkOrderCompletionTable.TABLE_NAME + " WHERE " + "WorkOrderCompletionID" + "=" + pintID.ToString(); OleDbConnection oconPCS = null; OleDbCommand ocmdPCS = null; try { oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); ocmdPCS.ExecuteNonQuery(); ocmdPCS = null; } catch (OleDbException ex) { if (ex.Errors[1].NativeError == ErrorCode.SQLCASCADE_PREVENT_KEYCODE) { throw new PCSDBException(ErrorCode.CASCADE_DELETE_PREVENT, METHOD_NAME, ex); } else { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex); } } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS != null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } public PRO_WorkOrderCompletion GetObjectVO(int pintID) { const string METHOD_NAME = THIS + ".GetObjectVO()"; DataSet dstPCS = new DataSet(); OleDbDataReader odrPCS = null; OleDbConnection oconPCS = null; OleDbCommand ocmdPCS = null; try { string strSql = String.Empty; strSql = "SELECT " + PRO_WorkOrderCompletionTable.WORKORDERCOMPLETIONID_FLD + "," + PRO_WorkOrderCompletionTable.POSTDATE_FLD + "," + PRO_WorkOrderCompletionTable.WOCOMPLETIONNO_FLD + "," + PRO_WorkOrderCompletionTable.COMPLETEDQUANTITY_FLD + "," + PRO_WorkOrderCompletionTable.LOT_FLD + "," + PRO_WorkOrderCompletionTable.SERIAL_FLD + "," + PRO_WorkOrderCompletionTable.LOCATIONID_FLD + "," + PRO_WorkOrderCompletionTable.BINID_FLD + "," + PRO_WorkOrderCompletionTable.CCNID_FLD + "," + PRO_WorkOrderCompletionTable.MASTERLOCATIONID_FLD + "," + PRO_WorkOrderCompletionTable.PRODUCTID_FLD + "," + PRO_WorkOrderCompletionTable.STOCKUMID_FLD + "," + PRO_WorkOrderCompletionTable.WORKORDERMASTERID_FLD + "," + PRO_WorkOrderCompletionTable.WORKORDERDETAILID_FLD + "," + PRO_WorkOrderCompletionTable.SHIFTID_FLD + "," + PRO_WorkOrderCompletionTable.ISSUEPURPOSEID_FLD + "," + PRO_WorkOrderCompletionTable.REMARK_FLD + "," + PRO_WorkOrderCompletionTable.QASTATUS_FLD + " FROM " + PRO_WorkOrderCompletionTable.TABLE_NAME + " WHERE " + PRO_WorkOrderCompletionTable.WORKORDERCOMPLETIONID_FLD + "=" + pintID; oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); odrPCS = ocmdPCS.ExecuteReader(); PRO_WorkOrderCompletion objObject = new PRO_WorkOrderCompletion(); while (odrPCS.Read()) { objObject.WorkOrderCompletionID = int.Parse(odrPCS[PRO_WorkOrderCompletionTable.WORKORDERCOMPLETIONID_FLD].ToString().Trim()); objObject.PostDate = DateTime.Parse(odrPCS[PRO_WorkOrderCompletionTable.POSTDATE_FLD].ToString().Trim()); objObject.WOCompletionNo = odrPCS[PRO_WorkOrderCompletionTable.WOCOMPLETIONNO_FLD].ToString().Trim(); objObject.CompletedQuantity = Decimal.Parse(odrPCS[PRO_WorkOrderCompletionTable.COMPLETEDQUANTITY_FLD].ToString().Trim()); objObject.Lot = odrPCS[PRO_WorkOrderCompletionTable.LOT_FLD].ToString().Trim(); objObject.Serial = odrPCS[PRO_WorkOrderCompletionTable.SERIAL_FLD].ToString().Trim(); objObject.LocationID = int.Parse(odrPCS[PRO_WorkOrderCompletionTable.LOCATIONID_FLD].ToString().Trim()); objObject.CCNID = int.Parse(odrPCS[PRO_WorkOrderCompletionTable.CCNID_FLD].ToString().Trim()); objObject.MasterLocationID = int.Parse(odrPCS[PRO_WorkOrderCompletionTable.MASTERLOCATIONID_FLD].ToString().Trim()); objObject.ProductID = int.Parse(odrPCS[PRO_WorkOrderCompletionTable.PRODUCTID_FLD].ToString().Trim()); objObject.StockUMID = int.Parse(odrPCS[PRO_WorkOrderCompletionTable.STOCKUMID_FLD].ToString().Trim()); objObject.WorkOrderMasterID = int.Parse(odrPCS[PRO_WorkOrderCompletionTable.WORKORDERMASTERID_FLD].ToString().Trim()); objObject.WorkOrderDetailID = int.Parse(odrPCS[PRO_WorkOrderCompletionTable.WORKORDERDETAILID_FLD].ToString().Trim()); //HACKED: edit by Tuan TQ, 09 Dec, 2005: Valid data before parse if (!odrPCS[PRO_WorkOrderCompletionTable.BINID_FLD].Equals(DBNull.Value)) { objObject.BinID = int.Parse(odrPCS[PRO_WorkOrderCompletionTable.BINID_FLD].ToString().Trim()); } if (!odrPCS[PRO_WorkOrderCompletionTable.QASTATUS_FLD].Equals(DBNull.Value)) { objObject.QAStatus = byte.Parse(odrPCS[PRO_WorkOrderCompletionTable.QASTATUS_FLD].ToString().Trim()); } //HACKED: Added by Tuan TQ. 09 Dec, 2005. Add more properties if (!odrPCS[PRO_WorkOrderCompletionTable.SHIFTID_FLD].Equals(DBNull.Value)) { objObject.ShiftID = int.Parse(odrPCS[PRO_WorkOrderCompletionTable.SHIFTID_FLD].ToString().Trim()); } if (!odrPCS[PRO_WorkOrderCompletionTable.ISSUEPURPOSEID_FLD].Equals(DBNull.Value)) { objObject.IssuePurposeID = int.Parse(odrPCS[PRO_WorkOrderCompletionTable.ISSUEPURPOSEID_FLD].ToString().Trim()); } objObject.Remark = odrPCS[PRO_WorkOrderCompletionTable.REMARK_FLD].ToString().Trim(); //End hacked } return objObject; } catch (OleDbException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS != null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } public void Update(object pobjObjecVO) { const string METHOD_NAME = THIS + ".Update()"; PRO_WorkOrderCompletionVO objObject = (PRO_WorkOrderCompletionVO)pobjObjecVO; //prepare value for parameters OleDbConnection oconPCS = null; OleDbCommand ocmdPCS = null; try { string strSql = String.Empty; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); strSql = "UPDATE PRO_WorkOrderCompletion SET " + PRO_WorkOrderCompletionTable.POSTDATE_FLD + "= ?" + "," + PRO_WorkOrderCompletionTable.WOCOMPLETIONNO_FLD + "= ?" + "," + PRO_WorkOrderCompletionTable.COMPLETEDQUANTITY_FLD + "= ?" + "," + PRO_WorkOrderCompletionTable.LOT_FLD + "= ?" + "," + PRO_WorkOrderCompletionTable.SERIAL_FLD + "= ?" + "," + PRO_WorkOrderCompletionTable.LOCATIONID_FLD + "= ?" + "," + PRO_WorkOrderCompletionTable.BINID_FLD + "= ?" + "," + PRO_WorkOrderCompletionTable.CCNID_FLD + "= ?" + "," + PRO_WorkOrderCompletionTable.MASTERLOCATIONID_FLD + "= ?" + "," + PRO_WorkOrderCompletionTable.PRODUCTID_FLD + "= ?" + "," + PRO_WorkOrderCompletionTable.STOCKUMID_FLD + "= ?" + "," + PRO_WorkOrderCompletionTable.WORKORDERMASTERID_FLD + "= ?" + "," + PRO_WorkOrderCompletionTable.WORKORDERDETAILID_FLD + "= ?" + "," + PRO_WorkOrderCompletionTable.SHIFTID_FLD + " = ?, " + PRO_WorkOrderCompletionTable.ISSUEPURPOSEID_FLD + " =?, " + PRO_WorkOrderCompletionTable.REMARK_FLD + " = ?, " + PRO_WorkOrderCompletionTable.QASTATUS_FLD + "= ?" + " WHERE " + PRO_WorkOrderCompletionTable.WORKORDERCOMPLETIONID_FLD + "= ?"; ocmdPCS.Parameters.Add(new OleDbParameter(PRO_WorkOrderCompletionTable.POSTDATE_FLD, OleDbType.Date)); ocmdPCS.Parameters[PRO_WorkOrderCompletionTable.POSTDATE_FLD].Value = objObject.PostDate; ocmdPCS.Parameters.Add(new OleDbParameter(PRO_WorkOrderCompletionTable.WOCOMPLETIONNO_FLD, OleDbType.VarWChar)); ocmdPCS.Parameters[PRO_WorkOrderCompletionTable.WOCOMPLETIONNO_FLD].Value = objObject.WOCompletionNo; ocmdPCS.Parameters.Add(new OleDbParameter(PRO_WorkOrderCompletionTable.COMPLETEDQUANTITY_FLD, OleDbType.Decimal)); ocmdPCS.Parameters[PRO_WorkOrderCompletionTable.COMPLETEDQUANTITY_FLD].Value = objObject.CompletedQuantity; ocmdPCS.Parameters.Add(new OleDbParameter(PRO_WorkOrderCompletionTable.LOT_FLD, OleDbType.VarWChar)); ocmdPCS.Parameters[PRO_WorkOrderCompletionTable.LOT_FLD].Value = objObject.Lot; ocmdPCS.Parameters.Add(new OleDbParameter(PRO_WorkOrderCompletionTable.SERIAL_FLD, OleDbType.VarWChar)); ocmdPCS.Parameters[PRO_WorkOrderCompletionTable.SERIAL_FLD].Value = objObject.Serial; ocmdPCS.Parameters.Add(new OleDbParameter(PRO_WorkOrderCompletionTable.LOCATIONID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[PRO_WorkOrderCompletionTable.LOCATIONID_FLD].Value = objObject.LocationID; ocmdPCS.Parameters.Add(new OleDbParameter(PRO_WorkOrderCompletionTable.BINID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[PRO_WorkOrderCompletionTable.BINID_FLD].Value = objObject.BinID; ocmdPCS.Parameters.Add(new OleDbParameter(PRO_WorkOrderCompletionTable.CCNID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[PRO_WorkOrderCompletionTable.CCNID_FLD].Value = objObject.CCNID; ocmdPCS.Parameters.Add(new OleDbParameter(PRO_WorkOrderCompletionTable.MASTERLOCATIONID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[PRO_WorkOrderCompletionTable.MASTERLOCATIONID_FLD].Value = objObject.MasterLocationID; ocmdPCS.Parameters.Add(new OleDbParameter(PRO_WorkOrderCompletionTable.PRODUCTID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[PRO_WorkOrderCompletionTable.PRODUCTID_FLD].Value = objObject.ProductID; ocmdPCS.Parameters.Add(new OleDbParameter(PRO_WorkOrderCompletionTable.STOCKUMID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[PRO_WorkOrderCompletionTable.STOCKUMID_FLD].Value = objObject.StockUMID; ocmdPCS.Parameters.Add(new OleDbParameter(PRO_WorkOrderCompletionTable.WORKORDERMASTERID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[PRO_WorkOrderCompletionTable.WORKORDERMASTERID_FLD].Value = objObject.WorkOrderMasterID; ocmdPCS.Parameters.Add(new OleDbParameter(PRO_WorkOrderCompletionTable.WORKORDERDETAILID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[PRO_WorkOrderCompletionTable.WORKORDERDETAILID_FLD].Value = objObject.WorkOrderDetailID; //HACKED: Added by Tuan TQ. 09 Dec, 2005: Add more properties ocmdPCS.Parameters.Add(new OleDbParameter(PRO_WorkOrderCompletionTable.SHIFTID_FLD, OleDbType.Integer)); if (objObject.ShiftID > 0) { ocmdPCS.Parameters[PRO_WorkOrderCompletionTable.SHIFTID_FLD].Value = objObject.ShiftID; } else { ocmdPCS.Parameters[PRO_WorkOrderCompletionTable.SHIFTID_FLD].Value = DBNull.Value; } ocmdPCS.Parameters.Add(new OleDbParameter(PRO_WorkOrderCompletionTable.ISSUEPURPOSEID_FLD, OleDbType.Integer)); if (objObject.IssuePurposeID > 0) { ocmdPCS.Parameters[PRO_WorkOrderCompletionTable.ISSUEPURPOSEID_FLD].Value = objObject.IssuePurposeID; } else { ocmdPCS.Parameters[PRO_WorkOrderCompletionTable.ISSUEPURPOSEID_FLD].Value = DBNull.Value; } ocmdPCS.Parameters.Add(new OleDbParameter(PRO_WorkOrderCompletionTable.REMARK_FLD, OleDbType.WChar)); ocmdPCS.Parameters[PRO_WorkOrderCompletionTable.REMARK_FLD].Value = objObject.Remark; //End Hacked ocmdPCS.Parameters.Add(new OleDbParameter(PRO_WorkOrderCompletionTable.QASTATUS_FLD, OleDbType.Integer)); ocmdPCS.Parameters[PRO_WorkOrderCompletionTable.QASTATUS_FLD].Value = objObject.QAStatus; ocmdPCS.Parameters.Add(new OleDbParameter(PRO_WorkOrderCompletionTable.WORKORDERCOMPLETIONID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[PRO_WorkOrderCompletionTable.WORKORDERCOMPLETIONID_FLD].Value = objObject.WorkOrderCompletionID; ocmdPCS.CommandText = strSql; ocmdPCS.Connection.Open(); ocmdPCS.ExecuteNonQuery(); } catch (OleDbException ex) { if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE) { throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex); } else { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex); } } catch (InvalidOperationException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS != null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } public DataSet List() { const string METHOD_NAME = THIS + ".List()"; DataSet dstPCS = new DataSet(); OleDbConnection oconPCS = null; OleDbCommand ocmdPCS = null; try { string strSql = String.Empty; strSql = "SELECT " + PRO_WorkOrderCompletionTable.WORKORDERCOMPLETIONID_FLD + "," + PRO_WorkOrderCompletionTable.POSTDATE_FLD + "," + PRO_WorkOrderCompletionTable.WOCOMPLETIONNO_FLD + "," + PRO_WorkOrderCompletionTable.COMPLETEDQUANTITY_FLD + "," + PRO_WorkOrderCompletionTable.LOT_FLD + "," + PRO_WorkOrderCompletionTable.SERIAL_FLD + "," + PRO_WorkOrderCompletionTable.LOCATIONID_FLD + "," + PRO_WorkOrderCompletionTable.BINID_FLD + "," + PRO_WorkOrderCompletionTable.CCNID_FLD + "," + PRO_WorkOrderCompletionTable.MASTERLOCATIONID_FLD + "," + PRO_WorkOrderCompletionTable.PRODUCTID_FLD + "," + PRO_WorkOrderCompletionTable.STOCKUMID_FLD + "," + PRO_WorkOrderCompletionTable.WORKORDERMASTERID_FLD + "," + PRO_WorkOrderCompletionTable.WORKORDERDETAILID_FLD + "," + PRO_WorkOrderCompletionTable.SHIFTID_FLD + "," + PRO_WorkOrderCompletionTable.ISSUEPURPOSEID_FLD + "," + PRO_WorkOrderCompletionTable.REMARK_FLD + "," + PRO_WorkOrderCompletionTable.QASTATUS_FLD + " FROM " + PRO_WorkOrderCompletionTable.TABLE_NAME; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS); odadPCS.Fill(dstPCS, PRO_WorkOrderCompletionTable.TABLE_NAME); return dstPCS; } catch (OleDbException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS != null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } public void UpdateDataSet(DataSet pData) { const string METHOD_NAME = THIS + ".UpdateDataSet()"; string strSql; OleDbConnection oconPCS = null; OleDbCommandBuilder odcbPCS; OleDbDataAdapter odadPCS = new OleDbDataAdapter(); try { strSql = "SELECT " + PRO_WorkOrderCompletionTable.WORKORDERCOMPLETIONID_FLD + "," + PRO_WorkOrderCompletionTable.POSTDATE_FLD + "," + PRO_WorkOrderCompletionTable.WOCOMPLETIONNO_FLD + "," + PRO_WorkOrderCompletionTable.COMPLETEDQUANTITY_FLD + "," + PRO_WorkOrderCompletionTable.LOT_FLD + "," + PRO_WorkOrderCompletionTable.SERIAL_FLD + "," + PRO_WorkOrderCompletionTable.LOCATIONID_FLD + "," + PRO_WorkOrderCompletionTable.BINID_FLD + "," + PRO_WorkOrderCompletionTable.CCNID_FLD + "," + PRO_WorkOrderCompletionTable.MASTERLOCATIONID_FLD + "," + PRO_WorkOrderCompletionTable.PRODUCTID_FLD + "," + PRO_WorkOrderCompletionTable.STOCKUMID_FLD + "," + PRO_WorkOrderCompletionTable.WORKORDERMASTERID_FLD + "," + PRO_WorkOrderCompletionTable.WORKORDERDETAILID_FLD + "," + PRO_WorkOrderCompletionTable.SHIFTID_FLD + "," + PRO_WorkOrderCompletionTable.ISSUEPURPOSEID_FLD + "," + PRO_WorkOrderCompletionTable.REMARK_FLD + "," + PRO_WorkOrderCompletionTable.QASTATUS_FLD + " FROM " + PRO_WorkOrderCompletionTable.TABLE_NAME; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); odadPCS.SelectCommand = new OleDbCommand(strSql, oconPCS); odcbPCS = new OleDbCommandBuilder(odadPCS); pData.EnforceConstraints = false; odadPCS.Update(pData, PRO_WorkOrderCompletionTable.TABLE_NAME); } catch (OleDbException ex) { if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE) { throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex); } else if (ex.Errors[1].NativeError == ErrorCode.SQLCASCADE_PREVENT_KEYCODE) { throw new PCSDBException(ErrorCode.CASCADE_DELETE_PREVENT, METHOD_NAME, ex); } else { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex); } } catch (InvalidOperationException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS != null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } /// <summary> /// get all completed quantity of a WorkOrderDetail = /// SELECT ISNULL(SUM(CompletedQuantity),0) /// FROM PRO_WorkOrderCompletion /// WHERE WorkOrderMasterID = pintWorkOrderMasterID /// AND WorkOrderDetailID = pintWorkOrderDetailID /// </summary> /// <returns>CompletedQuantity</returns> public decimal GetCompletedQuantity(int pintWorkOrderMasterID, int pintWorkOrderDetailID) { const string METHOD_NAME = THIS + ".GetCompletedQuantity()"; OleDbConnection oconPCS = null; OleDbCommand ocmdPCS = null; try { Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); string strSql = "SELECT ISNULL(SUM(" + PRO_WorkOrderCompletionTable.COMPLETEDQUANTITY_FLD + "), 0)"; strSql += " FROM " + PRO_WorkOrderCompletionTable.TABLE_NAME; strSql += " WHERE " + PRO_WorkOrderCompletionTable.WORKORDERMASTERID_FLD + "=" + pintWorkOrderMasterID; strSql += " AND " + PRO_WorkOrderCompletionTable.WORKORDERDETAILID_FLD + "=" + pintWorkOrderDetailID; ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); object objResult = ocmdPCS.ExecuteScalar(); if ((objResult != null) && (objResult != DBNull.Value)) { return decimal.Parse(objResult.ToString()); } return 0; } catch (OleDbException ex) { if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE) { throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex); } else { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex); } } catch (InvalidOperationException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS != null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } /// <summary> /// Get WO completion detail to load on form /// </summary> /// <param name="pintWOCompletionID"></param> /// <returns></returns> public DataRow GetWOCompletion(int pintWOCompletionID) { const string LOCATION_CODE = "LocationCode"; const string BIN_CODE = "BinCode"; const string METHOD_NAME = THIS + ".GetWOCompletion()"; DataSet dstPCS = new DataSet(); OleDbConnection oconPCS = null; OleDbCommand ocmdPCS = null; try { string strSql = String.Empty; strSql = "SELECT " + WOC + Constants.DOT + PRO_WorkOrderCompletionTable.WORKORDERCOMPLETIONID_FLD + "," + WOC + Constants.DOT + PRO_WorkOrderCompletionTable.POSTDATE_FLD + "," + WOC + Constants.DOT + PRO_WorkOrderCompletionTable.WOCOMPLETIONDAT_FLD + "," + WOC + Constants.DOT + PRO_WorkOrderCompletionTable.WOCOMPLETIONNO_FLD + "," + WOC + Constants.DOT + PRO_WorkOrderCompletionTable.COMPLETEDQUANTITY_FLD + "," + WOC + Constants.DOT + PRO_WorkOrderCompletionTable.LOT_FLD + "," + WOC + Constants.DOT + PRO_WorkOrderCompletionTable.SERIAL_FLD + "," + LOC + Constants.DOT + MST_LocationTable.CODE_FLD + Constants.WHITE_SPACE + LOCATION_CODE + "," + BIN + Constants.DOT + MST_BINTable.CODE_FLD + Constants.WHITE_SPACE + BIN_CODE + "," + WOC + Constants.DOT + PRO_WorkOrderCompletionTable.CCNID_FLD + "," + WOC + Constants.DOT + PRO_WorkOrderCompletionTable.MASTERLOCATIONID_FLD + "," + WOC + Constants.DOT + PRO_WorkOrderCompletionTable.PRODUCTID_FLD + "," + WOC + Constants.DOT + PRO_WorkOrderCompletionTable.STOCKUMID_FLD + "," + WOM + Constants.DOT + PRO_WorkOrderMasterTable.WORKORDERNO_FLD + "," + WOD + Constants.DOT + PRO_WorkOrderDetailTable.LINE_FLD + "," //Added by Tuan TQ. 29 Dec, 2005. Get WO Detail ID for printing BOM shortage + WOD + Constants.DOT + PRO_WorkOrderDetailTable.WORKORDERDETAILID_FLD + "," //End added //Added by Tuan TQ. 09 Dec, 2005. Add properties + WOC + Constants.DOT + PRO_WorkOrderCompletionTable.SHIFTID_FLD + "," + WOC + Constants.DOT + PRO_WorkOrderCompletionTable.ISSUEPURPOSEID_FLD + "," + WOC + Constants.DOT + PRO_WorkOrderCompletionTable.REMARK_FLD + "," + PRO_ShiftTable.TABLE_NAME + Constants.DOT + PRO_ShiftTable.SHIFTDESC_FLD + " as " + PRO_ShiftTable.TABLE_NAME + PRO_ShiftTable.SHIFTDESC_FLD + "," + PRO_IssuePurposeTable.TABLE_NAME + Constants.DOT + PRO_IssuePurposeTable.DESCRIPTION_FLD + " as " + PRO_IssuePurposeTable.TABLE_NAME + PRO_IssuePurposeTable.DESCRIPTION_FLD + "," //End added + WOC + Constants.DOT + PRO_WorkOrderCompletionTable.QASTATUS_FLD + " FROM " + PRO_WorkOrderCompletionTable.TABLE_NAME + WOC + " INNER JOIN " + PRO_WorkOrderMasterTable.TABLE_NAME + WOM + " ON " + WOC + Constants.DOT + PRO_WorkOrderCompletionTable.WORKORDERMASTERID_FLD + " = " + WOM + Constants.DOT + PRO_WorkOrderMasterTable.WORKORDERMASTERID_FLD + " INNER JOIN " + PRO_WorkOrderDetailTable.TABLE_NAME + WOD + " ON " + WOC + Constants.DOT + PRO_WorkOrderCompletionTable.WORKORDERDETAILID_FLD + " = " + WOD + Constants.DOT + PRO_WorkOrderDetailTable.WORKORDERDETAILID_FLD + " INNER JOIN " + MST_LocationTable.TABLE_NAME + LOC + " ON " + WOC + Constants.DOT + PRO_WorkOrderCompletionTable.LOCATIONID_FLD + " = " + LOC + Constants.DOT + MST_LocationTable.LOCATIONID_FLD + " LEFT JOIN " + MST_BINTable.TABLE_NAME + BIN + " ON " + WOC + Constants.DOT + PRO_WorkOrderCompletionTable.BINID_FLD + " = " + BIN + Constants.DOT + MST_BINTable.BINID_FLD //Added by Tuan TQ. 09 Dec, 2005 + " LEFT JOIN " + PRO_ShiftTable.TABLE_NAME + " ON " + PRO_ShiftTable.TABLE_NAME + Constants.DOT + PRO_ShiftTable.SHIFTID_FLD + "=" + WOC + Constants.DOT + PRO_WorkOrderCompletionTable.SHIFTID_FLD + " LEFT JOIN " + PRO_IssuePurposeTable.TABLE_NAME + " ON " + PRO_IssuePurposeTable.TABLE_NAME + Constants.DOT + PRO_IssuePurposeTable.ISSUEPURPOSEID_FLD + "=" + WOC + Constants.DOT + PRO_WorkOrderCompletionTable.ISSUEPURPOSEID_FLD //End added + " WHERE " + WOC + Constants.DOT + PRO_WorkOrderCompletionTable.WORKORDERCOMPLETIONID_FLD + " = " + pintWOCompletionID; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS); odadPCS.Fill(dstPCS, PRO_WorkOrderCompletionTable.TABLE_NAME); return dstPCS.Tables[0].Rows[0]; } catch (OleDbException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS != null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } /// <summary> /// GetWorkingTimeByProductionLineAndYearMonth /// </summary> /// <param name="pintProductionLineID"></param> /// <param name="pintYear"></param> /// <param name="pintMonth"></param> /// <returns></returns> /// <author>Trada</author> /// <date>Wednesday, July 19 2006</date> public DataSet GetWorkingTimeByProductionLineAndYearMonth(int pintProductionLineID, int pintYear, int pintMonth) { const string METHOD_NAME = THIS + ".GetWorkingTimeByProductionLineAndYearMonth()"; DataSet dstPCS = new DataSet(); OleDbConnection oconPCS = null; OleDbCommand ocmdPCS = null; try { string strSql = "SELECT " + PCSComUtils.Common.PRO_WorkingTime.WORKINGTIMEID_FLD + ", " + PCSComUtils.Common.PRO_WorkingTime.ENDTIME_FLD + ", " + PCSComUtils.Common.PRO_WorkingTime.STARTTIME_FLD + ", " + PCSComUtils.Common.PRO_WorkingTime.YEARSETUP_FLD + ", " + PCSComUtils.Common.PRO_WorkingTime.MONTHSETUP_FLD + ", " + PCSComUtils.Common.PRO_WorkingTime.PRODUCTIONLINEID_FLD + ", " + PCSComUtils.Common.PRO_WorkingTime.WORKINGHOURS_FLD + " FROM " + PCSComUtils.Common.PRO_WorkingTime.TABLE_NAME + " WHERE " + PCSComUtils.Common.PRO_WorkingTime.PRODUCTIONLINEID_FLD + " = " + pintProductionLineID.ToString() + " AND " + PCSComUtils.Common.PRO_WorkingTime.YEARSETUP_FLD + " = " + pintYear.ToString() + " AND " + PCSComUtils.Common.PRO_WorkingTime.MONTHSETUP_FLD + " = " + pintMonth.ToString(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS); odadPCS.Fill(dstPCS, PCSComUtils.Common.PRO_WorkingTime.TABLE_NAME); return dstPCS; } catch (OleDbException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS != null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } /// <summary> /// LoadDataForWOLine /// </summary> /// <param name="pintWODetailID"></param> /// <returns></returns> /// <author>Trada</author> /// <date>Wednesday, June 22 2005</date> public DataSet LoadDataForWOLine(int pintWODetailID) { const string METHOD_NAME = THIS + ".LoadDataForWOLine()"; DataSet dstPCS = new DataSet(); OleDbConnection oconPCS = null; OleDbCommand ocmdPCS = null; try { string strSql = "SELECT " + PRO + "." + ITM_ProductTable.PRODUCTID_FLD + ", " + PRO + "." + ITM_ProductTable.CODE_FLD + ", " + UM + "." + MST_UnitOfMeasureTable.CODE_FLD + Constants.WHITE_SPACE + CAPTION_UM + ", " + PRO + "." + ITM_ProductTable.DESCRIPTION_FLD + ", " + PRO + "." + ITM_ProductTable.REVISION_FLD + ", " + PRO + "." + ITM_ProductTable.QASTATUS_FLD + ", " + PRO + "." + ITM_ProductTable.LOTCONTROL_FLD + ", " + PRO + "." + ITM_ProductTable.LOTSIZE_FLD + ", " + WOD + "." + PRO_WorkOrderDetailTable.STOCKUMID_FLD + ", " + WOD + "." + PRO_WorkOrderDetailTable.WORKORDERDETAILID_FLD + ", " + " ISNULL(( " + WOD + "." + PRO_WorkOrderDetailTable.ORDERQUANTITY_FLD + " - " + CQ + "." + PRO_WorkOrderCompletionTable.COMPLETEDQUANTITY_FLD + " - " + SQ + "." + PRO_AOScrapDetailTable.SCRAPQUANTITY_FLD + "),0) " + OPENQUANTITY + " FROM " + PRO_WorkOrderDetailTable.TABLE_NAME + Constants.WHITE_SPACE + WOD + " INNER JOIN " + ITM_ProductTable.TABLE_NAME + Constants.WHITE_SPACE + PRO + " ON " + WOD + "." + PRO_WorkOrderDetailTable.PRODUCTID_FLD + " = " + PRO + "." + ITM_ProductTable.PRODUCTID_FLD + " INNER JOIN " + MST_UnitOfMeasureTable.TABLE_NAME + Constants.WHITE_SPACE + UM + " ON " + WOD + "." + PRO_WorkOrderDetailTable.STOCKUMID_FLD + " = " + UM + "." + MST_UnitOfMeasureTable.UNITOFMEASUREID_FLD + " LEFT JOIN (" + " SELECT " + PRO_WorkOrderCompletionTable.WORKORDERDETAILID_FLD + ", " + " SUM(" + PRO_WorkOrderCompletionTable.COMPLETEDQUANTITY_FLD + ") " + COMPQTY + " FROM " + PRO_WorkOrderCompletionTable.TABLE_NAME + " GROUP BY " + PRO_WorkOrderCompletionTable.WORKORDERDETAILID_FLD + " ) " + CQ + " ON " + WOD + "." + PRO_WorkOrderDetailTable.WORKORDERDETAILID_FLD + " = " + CQ + "." + PRO_WorkOrderCompletionTable.WORKORDERDETAILID_FLD + " LEFT JOIN ( " + " SELECT " + PRO_AOScrapDetailTable.WORKORDERDETAILID_FLD + ", " + " SUM(" + PRO_AOScrapDetailTable.SCRAPQUANTITY_FLD + ") " + SCRAPQUANTITY + " FROM " + PRO_AOScrapDetailTable.TABLE_NAME + " GROUP BY " + PRO_AOScrapDetailTable.WORKORDERDETAILID_FLD + " ) " + SQ + " ON " + WOD + "." + PRO_WorkOrderDetailTable.WORKORDERDETAILID_FLD + " = " + SQ + "." + PRO_AOScrapDetailTable.WORKORDERDETAILID_FLD + " WHERE " + WOD + "." + PRO_WorkOrderDetailTable.WORKORDERDETAILID_FLD + " = " + pintWODetailID; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS); odadPCS.Fill(dstPCS, PRO_WorkOrderCompletionTable.TABLE_NAME); return dstPCS; } catch (OleDbException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS != null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } /// <summary> /// Searches the work order line. /// </summary> /// <param name="fromDate">From date.</param> /// <param name="toDate">To date.</param> /// <param name="masterLocationId">The master location id.</param> /// <param name="workOrderMasterId">The work order master id.</param> /// <param name="productCondition"></param> /// <returns></returns> public DataTable SearchWorkOrderLine(DateTime fromDate, DateTime toDate, int masterLocationId, int workOrderMasterId, string productCondition) { const string METHOD_NAME = THIS + ".SearchWorkOrderLine()"; var dstPCS = new DataSet(); OleDbConnection oconPCS = null; OleDbCommand ocmdPCS; try { var commandText = new StringBuilder(); commandText.AppendLine(" SELECT TOP 20 0 'No', WOD.Line,"); commandText.AppendLine(" ITM_Category.Code AS ITM_CategoryCode, ITM_Product.Code, ITM_Product.Description, ITM_Product.Revision, UM.Code MST_UnitOfMeasureCode,"); commandText.AppendLine(" WOD.StartDate, WOD.DueDate, WOD.OrderQuantity - SUM(ISNULL(WOC.CompletedQuantity,0)) CompletedQuantity,"); commandText.AppendLine(" WOD.OrderQuantity, L.Code MST_LocationCode, B.Code MST_BINCode, '' WOCompletionNo, WOM.WorkOrderNo, '' Remark,"); commandText.AppendLine(" WOD.WorkOrderDetailID, WOD.WorkOrderMasterID, WOD.ProductID, WOD.StockUMID,"); commandText.AppendLine(" ITM_Product.MasterLocationID, PL.LocationID, B.BinID, ITM_Product.LotSize, ITM_Product.LotControl,"); commandText.AppendLine(" L.Bin, B.BinTypeID, ITM_Product.CategoryID, CAST(NULL AS DATETIME) CompletedDate, WOM.ProductionLineID"); commandText.AppendLine(" FROM PRO_WorkOrderDetail WOD JOIN PRO_WorkOrderMaster WOM ON WOD.WorkOrderMasterID = WOM.WorkOrderMasterID"); commandText.AppendLine(" INNER JOIN ITM_Product ON WOD.ProductID = ITM_Product.ProductID "); commandText.AppendLine(" INNER JOIN MST_UnitOfMeasure UM ON UM.UnitOfMeasureID = WOD.StockUMID "); commandText.AppendLine(" LEFT JOIN ITM_Category ON ITM_Product.CategoryID = ITM_Category.CategoryID"); commandText.AppendLine(" LEFT JOIN PRO_ProductionLine PL ON WOM.ProductionLineID = PL.ProductionLineID"); commandText.AppendLine(" LEFT JOIN MST_Location L ON L.LocationID = PL.LocationID "); commandText.AppendLine(" LEFT JOIN MST_BIN B ON B.LocationID = L.LocationID"); commandText.AppendLine(" AND B.BinTypeID = " + (int)BinTypeEnum.OK); commandText.AppendLine(" LEFT JOIN PRO_WorkOrderCompletion WOC ON WOD.WorkOrderDetailID = WOC.WorkOrderDetailID"); commandText.AppendLine(" WHERE WOD.Status = 2"); commandText.AppendLine(" AND DueDate >= ?"); commandText.AppendLine(" AND DueDate <= ?"); commandText.AppendLine(" AND WOM.MasterLocationID = " + masterLocationId); commandText.AppendLine(" AND WOD.WorkOrderMasterID = " + workOrderMasterId); if (!string.IsNullOrEmpty(productCondition)) { commandText.AppendLine(productCondition); } commandText.AppendLine(" GROUP BY WOD.WorkOrderMasterID, WOM.WorkOrderNo, WOD.WorkOrderDetailID, WOD.StartDate, WOD.DueDate,"); commandText.AppendLine(" WOD.ProductID, WOD.OrderQuantity, WOD.Line, WOD.Status, ITM_Category.Code,"); commandText.AppendLine(" WOD.StockUMID, UM.Code, L.Code, B.Code, ITM_Product.Code, ITM_Product.Description, WOM.ProductionLineID,"); commandText.AppendLine(" ITM_Product.Revision, ITM_Product.QAStatus, ITM_Product.MasterLocationID, PL.LocationID, B.BinID, ITM_Product.LotSize, ITM_Product.LotControl,"); commandText.AppendLine(" L.Bin, B.BinTypeID, ITM_Product.CategoryID"); commandText.AppendLine(" HAVING SUM(ISNULL(WOC.CompletedQuantity,0)) < WOD.OrderQuantity"); commandText.AppendLine(" ORDER BY WOD.DueDate"); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(commandText.ToString(), oconPCS); ocmdPCS.Parameters.Add(new OleDbParameter("@FromDate", OleDbType.Date)).Value = fromDate; ocmdPCS.Parameters.Add(new OleDbParameter("@ToDate", OleDbType.Date)).Value = toDate; ocmdPCS.Connection.Open(); var odadPCS = new OleDbDataAdapter(ocmdPCS); odadPCS.Fill(dstPCS, PRO_WorkOrderCompletionTable.TABLE_NAME); return dstPCS.Tables[0]; } catch (OleDbException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS != null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } /// <summary> /// Searches the work order line. /// </summary> /// <param name="multiTransNo">The multi trans no.</param> /// <returns></returns> public DataTable SearchWorkOrderLine(string multiTransNo) { const string METHOD_NAME = THIS + ".SearchWorkOrderLine()"; var dstPCS = new DataSet(); OleDbConnection oconPCS = null; OleDbCommand ocmdPCS; try { var commandText = new StringBuilder(); commandText.AppendLine(" SELECT TOP 20 0 AS 'No', WOD.Line,"); commandText.AppendLine(" ITM_Category.Code AS ITM_CategoryCode, P.Code, P.Description, P.Revision, UM.Code MST_UnitOfMeasureCode,"); commandText.AppendLine(" WOD.StartDate, WOD.DueDate, WOC.CompletedQuantity, WOD.OrderQuantity, L.Code MST_LocationCode, B.Code MST_BINCode,"); commandText.AppendLine(" WOC.WOCompletionNo, WOM.WorkOrderNo, WOC.Remark,"); commandText.AppendLine(" WOD.WorkOrderDetailID, WOD.WorkOrderMasterID, WOD.ProductID, WOD.StockUMID,"); commandText.AppendLine(" P.MasterLocationID, P.LocationID, P.BinID, P.LotSize, P.LotControl,"); commandText.AppendLine(" L.Bin, B.BinTypeID, P.CategoryID, CompletedDate, WOM.ProductionLineID"); commandText.AppendLine(" FROM PRO_WorkOrderDetail WOD JOIN PRO_WorkOrderMaster WOM ON WOD.WorkOrderMasterID = WOM.WorkOrderMasterID"); commandText.AppendLine(" JOIN ITM_Product P ON WOD.ProductID = P.ProductID "); commandText.AppendLine(" JOIN PRO_WorkOrderCompletion WOC ON WOD.WorkOrderDetailID = WOC.WorkOrderDetailID "); commandText.AppendLine(" JOIN MST_UnitOfMeasure UM ON UM.UnitOfMeasureID = WOD.StockUMID "); commandText.AppendLine(" LEFT JOIN ITM_Category ON P.CategoryID = ITM_Category.CategoryID"); commandText.AppendLine(" LEFT JOIN MST_Location L ON L.LocationID = P.LocationID "); commandText.AppendLine(" LEFT JOIN MST_BIN B ON B.BinID = P.BinID"); commandText.AppendLine(" WHERE WOC.MultiCompletionNo = ?"); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(commandText.ToString(), oconPCS); ocmdPCS.Parameters.Add(new OleDbParameter("@TransNo", OleDbType.VarWChar)).Value = multiTransNo; ocmdPCS.Connection.Open(); var odadPCS = new OleDbDataAdapter(ocmdPCS); odadPCS.Fill(dstPCS, PRO_WorkOrderCompletionTable.TABLE_NAME); return dstPCS.Tables[0]; } catch (OleDbException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS != null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } /// <summary> /// List all component of a product in work order detail /// </summary> /// <param name="pintWODetailID"></param> /// <returns></returns> public DataTable ListComponentByWODetail(int pintWODetailID) { const string METHOD_NAME = THIS + ".ListComponentByWODetail()"; const string UM_CODE = "UMCode"; DataSet dstPCS = new DataSet(); OleDbConnection oconPCS = null; OleDbCommand ocmdPCS = null; try { // 07-08-2006 dungla: join ITM_BOM instead of work order bom // 28-02-2007 CanhNv: add ,ITM_BOM.BomID, StringBuilder strSql = new StringBuilder(); strSql.Append("SELECT ITM_BOM.ComponentID, ITM_BOM.BomID,ITM_BOM.Quantity AS RequiredQuantity,"); strSql.Append(" ITM_Product.StockUMID, ITM_Product.Code, ITM_Product.Description, ITM_Product.Revision,"); strSql.Append(" MST_UnitOfMeasure.Code AS UMCode, ISNULL(ITM_Product.AllowNegativeQty,0) AllowNegativeQty,"); strSql.Append(" WOD.OrderQuantity * ITM_BOM.Quantity + WOD.OrderQuantity * ITM_BOM.Quantity* ISNULL(ITM_BOM.Shrink, 0)/100 "); strSql.Append(" - ISNULL((SELECT SUM(ISNULL(PRO_ComponentScrapDetail.ScrapQuantity, 0)) "); strSql.Append(" FROM PRO_ComponentScrapMaster Inner join PRO_ComponentScrapDetail "); strSql.Append(" on PRO_ComponentScrapMaster.ComponentScrapMasterID = PRO_ComponentScrapDetail.ComponentScrapMasterID "); strSql.Append(" Where PRO_ComponentScrapDetail.WorkOrderDetailID = WOD.WorkOrderDetailID "); strSql.Append(" and ITM_BOM.ComponentID = PRO_ComponentScrapDetail.ProductID), 0)"); strSql.Append(" -ISNULL((SELECT SUM(ISNULL(PRO_IssueMaterialDetail.CommitQuantity, 0)) "); strSql.Append(" FROM PRO_IssueMaterialMaster Inner join PRO_IssueMaterialDetail "); strSql.Append(" on PRO_IssueMaterialMaster.IssueMaterialMasterID = PRO_IssueMaterialDetail.IssueMaterialMasterID "); strSql.Append(" Where PRO_IssueMaterialDetail.WorkOrderDetailID = WOD.WorkOrderDetailID "); strSql.Append(" and ITM_BOM.ComponentID = PRO_IssueMaterialDetail.ProductID), 0) "); strSql.Append(" -ISNULL((SELECT SUM(ISNULL(PRO_WorkOrderCompletion.CompletedQuantity, 0)) "); strSql.Append(" FROM PRO_WorkOrderCompletion "); strSql.Append(" Where PRO_WorkOrderCompletion.WorkOrderDetailID = WOD.WorkOrderDetailID), 0)*ITM_BOM.Quantity as ShortageQuantity "); strSql.Append(" FROM PRO_WorkOrderDetail WOD inner join ITM_BOM"); strSql.Append(" on WOD.ProductID = ITM_BOM.ProductID "); strSql.Append(" INNER JOIN ITM_Product on ITM_BOM.ComponentID= ITM_Product.ProductID"); strSql.Append(" INNER JOIN MST_UnitOfMeasure ON ITM_Product.StockUMID = MST_UnitOfMeasure.UnitOfMeasureID"); strSql.Append(" WHERE WOD.WorkOrderDetailID = " + pintWODetailID); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql.ToString(), oconPCS); ocmdPCS.Connection.Open(); ocmdPCS.CommandTimeout = 10000; OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS); odadPCS.Fill(dstPCS, PRO_WOScheduleDetailTable.TABLE_NAME); return dstPCS.Tables[0]; } catch (OleDbException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS != null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.IO; namespace Apache.Geode.Client.UnitTests { using NUnit.Framework; using DUnitFramework; using Client; [TestFixture] [Category("group4")] [Category("unicast_only")] [Category("generics")] public class RegionFailingTests : ThinClientRegionSteps { #region Private members private UnitProcess _client1, _client2; #endregion protected override ClientBase[] GetClients() { _client1 = new UnitProcess(); _client2 = new UnitProcess(); return new ClientBase[] { _client1, _client2 }; } [TestFixtureTearDown] public override void EndTests() { CacheHelper.StopJavaServers(); base.EndTests(); } [TearDown] public override void EndTest() { try { _client1.Call(DestroyRegions); _client2.Call(DestroyRegions); CacheHelper.ClearEndpoints(); CacheHelper.ClearLocators(); } finally { CacheHelper.StopJavaServers(); CacheHelper.StopJavaLocators(); } base.EndTest(); } private void RunCheckPutGet() { CacheHelper.SetupJavaServers(true, "cacheServer_pdxreadserialized.xml"); CacheHelper.StartJavaLocator(1, "GFELOC"); Util.Log("Locator 1 started."); CacheHelper.StartJavaServerWithLocators(1, "GFECS1", 1); Util.Log("Cacheserver 1 started."); var putGetTest = new PutGetTests(); _client1.Call(CreateTCRegions_Pool, RegionNames, CacheHelper.Locators, "__TESTPOOL1_", false); Util.Log("Client 1 (pool locators) regions created"); _client2.Call(CreateTCRegions_Pool, RegionNames, CacheHelper.Locators, "__TESTPOOL1_", false); Util.Log("Client 2 (pool locators) regions created"); _client1.Call(putGetTest.SetRegion, RegionNames[0]); _client2.Call(putGetTest.SetRegion, RegionNames[0]); var dtTicks = DateTime.Now.Ticks; CacheableHelper.RegisterBuiltins(dtTicks); putGetTest.TestAllKeyValuePairs(_client1, _client2, RegionNames[0], true, dtTicks); _client1.Call(Close); Util.Log("Client 1 closed"); _client2.Call(Close); Util.Log("Client 2 closed"); CacheHelper.StopJavaServer(1); Util.Log("Cacheserver 1 stopped."); CacheHelper.StopJavaLocator(1); Util.Log("Locator 1 stopped."); CacheHelper.ClearEndpoints(); CacheHelper.ClearLocators(); } private void RunCheckPutGetWithAppDomain() { CacheHelper.SetupJavaServers(true, "cacheServer_pdxreadserialized.xml"); CacheHelper.StartJavaLocator(1, "GFELOC"); Util.Log("Locator 1 started."); CacheHelper.StartJavaServerWithLocators(1, "GFECS1", 1); Util.Log("Cacheserver 1 started."); var putGetTest = new PutGetTests(); _client1.Call(InitializeAppDomain); var dtTime = DateTime.Now.Ticks; _client1.Call(CreateTCRegions_Pool_AD, RegionNames, CacheHelper.Locators, "__TESTPOOL1_", false, false, dtTime); Util.Log("Client 1 (pool locators) regions created"); _client1.Call(SetRegionAD, RegionNames[0]); //m_client2.Call(putGetTest.SetRegion, RegionNames[0]); // CacheableHelper.RegisterBuiltins(); //putGetTest.TestAllKeyValuePairs(m_client1, m_client2, //RegionNames[0], true, pool); _client1.Call(TestAllKeyValuePairsAD, RegionNames[0], true, dtTime); //m_client1.Call(CloseCacheAD); Util.Log("Client 1 closed"); CacheHelper.CloseCache(); CacheHelper.StopJavaServer(1); Util.Log("Cacheserver 1 stopped."); CacheHelper.StopJavaLocator(1); Util.Log("Locator 1 stopped."); CacheHelper.ClearEndpoints(); CacheHelper.ClearLocators(); } private void RunPdxAppDomainTest(bool caching, bool readPdxSerialized) { CacheHelper.SetupJavaServers(true, "cacheServer_pdxreadserialized.xml"); CacheHelper.StartJavaLocator(1, "GFELOC"); Util.Log("Locator 1 started."); CacheHelper.StartJavaServerWithLocators(1, "GFECS1", 1); Util.Log("Cacheserver 1 started."); _client1.Call(InitializeAppDomain); _client1.Call(CreateTCRegions_Pool_AD2, RegionNames, CacheHelper.Locators, "__TESTPOOL1_", false, false, caching, readPdxSerialized); Util.Log("Client 1 (pool locators) regions created"); _client1.Call(SetRegionAD, RegionNames[0]); _client1.Call(pdxPutGetTest, caching, readPdxSerialized); _client1.Call(pdxGetPutTest, caching, readPdxSerialized); //m_client2.Call(putGetTest.SetRegion, RegionNames[0]); // CacheableHelper.RegisterBuiltins(); //putGetTest.TestAllKeyValuePairs(m_client1, m_client2, //RegionNames[0], true, pool); // m_client1.Call(TestAllKeyValuePairsAD, RegionNames[0], true, pool); _client1.Call(CloseCacheAD); Util.Log("Client 1 closed"); //CacheHelper.CloseCache(); CacheHelper.StopJavaServer(1); Util.Log("Cacheserver 1 stopped."); CacheHelper.StopJavaLocator(1); Util.Log("Locator 1 stopped."); CacheHelper.ClearEndpoints(); CacheHelper.ClearLocators(); } private void RunCheckPut() { CacheHelper.SetupJavaServers(true, "cacheserver_hashcode.xml"); CacheHelper.StartJavaLocator(1, "GFELOC"); Util.Log("Locator 1 started."); CacheHelper.StartJavaServerWithLocators(1, "GFECS1", 1); Util.Log("Cacheserver 1 started."); var putGetTest = new PutGetTests(); _client1.Call(CreateTCRegions_Pool, RegionNames, CacheHelper.Locators, "__TESTPOOL1_", false); Util.Log("Client 1 (pool locators) regions created"); _client2.Call(CreateTCRegions_Pool, RegionNames, CacheHelper.Locators, "__TESTPOOL1_", false); Util.Log("Client 2 (pool locators) regions created"); _client1.Call(putGetTest.SetRegion, RegionNames[0]); _client2.Call(putGetTest.SetRegion, RegionNames[0]); var dtTime = DateTime.Now.Ticks; CacheableHelper.RegisterBuiltinsJavaHashCode(dtTime); putGetTest.TestAllKeys(_client1, _client2, RegionNames[0], dtTime); _client1.Call(Close); Util.Log("Client 1 closed"); _client2.Call(Close); Util.Log("Client 2 closed"); CacheHelper.StopJavaServer(1); Util.Log("Cacheserver 1 stopped."); CacheHelper.StopJavaLocator(1); Util.Log("Locator 1 stopped."); CacheHelper.ClearEndpoints(); CacheHelper.ClearLocators(); } private void RunFixedPartitionResolver() { CacheHelper.SetupJavaServers(true, "cacheserver1_fpr.xml", "cacheserver2_fpr.xml", "cacheserver3_fpr.xml"); CacheHelper.StartJavaLocator(1, "GFELOC"); Util.Log("Locator 1 started."); CacheHelper.StartJavaServerWithLocators(1, "GFECS1", 1); Util.Log("Cacheserver 1 started."); CacheHelper.StartJavaServerWithLocators(2, "GFECS2", 1); Util.Log("Cacheserver 2 started."); CacheHelper.StartJavaServerWithLocators(3, "GFECS3", 1); Util.Log("Cacheserver 3 started."); var putGetTest = new PutGetTests(); _client1.Call(CreateTCRegions_Pool1, PartitionRegion1, CacheHelper.Locators, "__TESTPOOL1_", false); Util.Log("Client 1 (pool locators) PartitionRegion1 created"); _client1.Call(CreateTCRegions_Pool1, PartitionRegion2, CacheHelper.Locators, "__TESTPOOL1_", false); Util.Log("Client 1 (pool locators) PartitionRegion2 created"); _client1.Call(CreateTCRegions_Pool1, PartitionRegion3, CacheHelper.Locators, "__TESTPOOL1_", false); Util.Log("Client 1 (pool locators) PartitionRegion3 created"); _client1.Call(putGetTest.SetRegion, PartitionRegion1); putGetTest.DoPRSHFixedPartitionResolverTasks(_client1, PartitionRegion1); _client1.Call(putGetTest.SetRegion, PartitionRegion2); putGetTest.DoPRSHFixedPartitionResolverTasks(_client1, PartitionRegion2); _client1.Call(putGetTest.SetRegion, PartitionRegion3); putGetTest.DoPRSHFixedPartitionResolverTasks(_client1, PartitionRegion3); _client1.Call(Close); Util.Log("Client 1 closed"); _client2.Call(Close); Util.Log("Client 2 closed"); CacheHelper.StopJavaServer(1); Util.Log("Cacheserver 1 stopped."); CacheHelper.StopJavaServer(2); Util.Log("Cacheserver 2 stopped."); CacheHelper.StopJavaServer(3); Util.Log("Cacheserver 3 stopped."); CacheHelper.StopJavaLocator(1); Util.Log("Locator 1 stopped."); CacheHelper.ClearEndpoints(); CacheHelper.ClearLocators(); } private void RegisterOtherType() { try { CacheHelper.DCache.TypeRegistry.RegisterType(OtherType.CreateDeserializable, 0); } catch (IllegalStateException) { // ignored since we run multiple times for pool and non pool cases. } } private void DoPutsOtherTypeWithEx(OtherType.ExceptionType exType) { var region = CacheHelper.GetVerifyRegion<object, object>(m_regionNames[0]); for (var keyNum = 1; keyNum <= 10; ++keyNum) { try { region["key-" + keyNum] = new OtherType(keyNum, keyNum * keyNum, exType); if (exType != OtherType.ExceptionType.None) { Assert.Fail("Expected an exception in Put"); } } catch (GeodeIOException ex) { if (exType == OtherType.ExceptionType.Geode) { // Successfully changed exception back and forth Util.Log("Got expected exception in Put: " + ex); } else if (exType == OtherType.ExceptionType.GeodeGeode) { if (ex.InnerException is CacheServerException) { // Successfully changed exception back and forth Util.Log("Got expected exception in Put: " + ex); } else { throw; } } else { throw; } } catch (CacheServerException ex) { if (exType == OtherType.ExceptionType.GeodeSystem) { if (ex.InnerException is IOException) { // Successfully changed exception back and forth Util.Log("Got expected exception in Put: " + ex); } else { throw; } } else { throw; } } catch (IOException ex) { if (exType == OtherType.ExceptionType.System) { // Successfully changed exception back and forth Util.Log("Got expected system exception in Put: " + ex); } else { throw; } } catch (ApplicationException ex) { if (exType == OtherType.ExceptionType.SystemGeode) { if (ex.InnerException is CacheServerException) { // Successfully changed exception back and forth Util.Log("Got expected system exception in Put: " + ex); } else { throw; } } else if (exType == OtherType.ExceptionType.SystemSystem) { if (ex.InnerException is IOException) { // Successfully changed exception back and forth Util.Log("Got expected system exception in Put: " + ex); } else { throw; } } else { throw; } } } } private void RunCheckNativeException() { CacheHelper.SetupJavaServers(true, "cacheserver.xml"); CacheHelper.StartJavaLocator(1, "GFELOC"); Util.Log("Locator 1 started."); CacheHelper.StartJavaServerWithLocators(1, "GFECS1", 1); Util.Log("Cacheserver 1 started."); _client1.Call(RegisterOtherType); _client1.Call(CreateTCRegions_Pool, RegionNames, CacheHelper.Locators, "__TESTPOOL1_", false); Util.Log("StepOne (pool locators) complete."); _client1.Call(DoPutsOtherTypeWithEx, OtherType.ExceptionType.None); _client1.Call(DoPutsOtherTypeWithEx, OtherType.ExceptionType.Geode); _client1.Call(DoPutsOtherTypeWithEx, OtherType.ExceptionType.System); _client1.Call(DoPutsOtherTypeWithEx, OtherType.ExceptionType.GeodeGeode); _client1.Call(DoPutsOtherTypeWithEx, OtherType.ExceptionType.GeodeSystem); _client1.Call(DoPutsOtherTypeWithEx, OtherType.ExceptionType.SystemGeode); _client1.Call(DoPutsOtherTypeWithEx, OtherType.ExceptionType.SystemSystem); _client1.Call(Close); Util.Log("Client 1 closed"); CacheHelper.StopJavaServer(1); Util.Log("Cacheserver 1 stopped."); CacheHelper.StopJavaLocator(1); Util.Log("Locator 1 stopped."); CacheHelper.ClearEndpoints(); CacheHelper.ClearLocators(); } private void RunRemoveAllWithSingleHop() { CacheHelper.SetupJavaServers(true, "cacheserver1_pr.xml", "cacheserver2_pr.xml"); CacheHelper.StartJavaLocator(1, "GFELOC"); Util.Log("Locator 1 started."); CacheHelper.StartJavaServerWithLocators(1, "GFECS1", 1); Util.Log("Cacheserver 1 started."); CacheHelper.StartJavaServerWithLocators(2, "GFECS2", 1); Util.Log("Cacheserver 2 started."); _client1.Call(CreateTCRegions_Pool, RegionNames, CacheHelper.Locators, "__TESTPOOL1_", false); Util.Log("Client 1 (pool locators) regions created"); Util.Log("Region creation complete."); _client1.Call(RemoveAllSingleHopStep); Util.Log("RemoveAllSingleHopStep complete."); _client1.Call(Close); Util.Log("Client 1 closed"); CacheHelper.StopJavaServer(1); Util.Log("Cacheserver 1 stopped."); CacheHelper.StopJavaServer(2); Util.Log("Cacheserver 2 stopped."); CacheHelper.StopJavaLocator(1); Util.Log("Locator 1 stopped."); CacheHelper.ClearEndpoints(); CacheHelper.ClearLocators(); } protected virtual void RemoveAllSingleHopStep() { var region0 = CacheHelper.GetVerifyRegion<object, object>(m_regionNames[0]); ICollection<object> keys = new Collection<object>(); for (var y = 0; y < 1000; y++) { Util.Log("put:{0}", y); region0[y] = y; keys.Add(y); } region0.RemoveAll(keys); Assert.AreEqual(0, region0.Count); Util.Log("RemoveAllSingleHopStep completed"); } private void RunRemoveOps() { CacheHelper.SetupJavaServers(true, "cacheserver.xml"); CacheHelper.StartJavaLocator(1, "GFELOC"); Util.Log("Locator 1 started."); CacheHelper.StartJavaServerWithLocators(1, "GFECS1", 1); Util.Log("Cacheserver 1 started."); _client1.Call(CreateTCRegions_Pool, RegionNames, CacheHelper.Locators, "__TESTPOOL1_", false); Util.Log("StepOne (pool locators) complete."); _client2.Call(CreateTCRegions_Pool, RegionNames, CacheHelper.Locators, "__TESTPOOL1_", false); Util.Log("StepTwo (pool locators) complete."); _client1.Call(StepThree); Util.Log("StepThree complete."); _client1.Call(RemoveStepFive); Util.Log("RemoveStepFive complete."); _client2.Call(RemoveStepSix); Util.Log("RemoveStepSix complete."); _client1.Call(Close); Util.Log("Client 1 closed"); _client2.Call(Close); Util.Log("Client 2 closed"); CacheHelper.StopJavaServer(1); Util.Log("Cacheserver 1 stopped."); CacheHelper.StopJavaLocator(1); Util.Log("Locator 1 stopped."); CacheHelper.ClearEndpoints(); CacheHelper.ClearLocators(); } private void RegexInterestAllStep2() //client 2 //pxr2 { Util.Log("RegexInterestAllStep2 Enters."); var region0 = CacheHelper.GetVerifyRegion<object, object>(m_regionNames[0]); var region1 = CacheHelper.GetVerifyRegion<object, object>(m_regionNames[1]); //CreateEntry(m_regionNames[0], m_keys[1], m_vals[1]); //CreateEntry(m_regionNames[1], m_keys[1], m_vals[1]); region0.GetSubscriptionService().RegisterAllKeys(false, true); region1.GetSubscriptionService().RegisterAllKeys(false, true); if (region0.Count != 1 || region1.Count != 1) { Assert.Fail("Expected one entry in region"); } Util.Log("RegexInterestAllStep2 complete."); } private void RegexInterestAllStep3(string locators) { var region0 = CacheHelper.GetVerifyRegion<object, object>(m_regionNames[0]); var region1 = CacheHelper.GetVerifyRegion<object, object>(m_regionNames[1]); region0.GetSubscriptionService().UnregisterAllKeys(); region1.GetSubscriptionService().UnregisterAllKeys(); region0.GetLocalView().DestroyRegion(); region1.GetLocalView().DestroyRegion(); CreateTCRegions_Pool(RegionNames, locators, "__TESTPOOL1_", true); region0 = CacheHelper.GetVerifyRegion<object, object>(m_regionNames[0]); region1 = CacheHelper.GetVerifyRegion<object, object>(m_regionNames[1]); CreateEntry(m_regionNames[0], m_keys[0], m_nvals[0]); region0.GetSubscriptionService().RegisterRegex(".*", false, true); region1.GetSubscriptionService().RegisterRegex(".*", false, true); if (region0.Count != 1) { Assert.Fail("Expected one entry in region"); } if (region1.Count != 1) { Assert.Fail("Expected one entry in region"); } VerifyCreated(m_regionNames[0], m_keys[0]); VerifyCreated(m_regionNames[1], m_keys[2]); VerifyEntry(m_regionNames[0], m_keys[0], m_nvals[0]); VerifyEntry(m_regionNames[1], m_keys[2], m_vals[2]); Util.Log("RegexInterestAllStep3 complete."); } private void RegexInterestAllStep4() { var region0 = CacheHelper.GetVerifyRegion<object, object>(m_regionNames[0]); region0.GetSubscriptionService().RegisterAllKeys(false, false); if (region0.Count != 1) { Assert.Fail("Expected one entry in region"); } if (!region0.ContainsKey(m_keys[0])) { Assert.Fail("Expected region to contain the key"); } if (region0.ContainsValueForKey(m_keys[0])) { Assert.Fail("Expected region to not contain the value"); } var region1 = CacheHelper.GetVerifyRegion<object, object>(m_regionNames[1]); region1.GetSubscriptionService().RegisterRegex(".*", false, false); if (region1.Count != 1) { Assert.Fail("Expected one entry in region"); } if (!region1.ContainsKey(m_keys[2])) { Assert.Fail("Expected region to contain the key"); } if (region1.ContainsValueForKey(m_keys[2])) { Assert.Fail("Expected region to not contain the value"); } CreateEntry(m_regionNames[0], m_keys[1], m_vals[1]); UpdateEntry(m_regionNames[0], m_keys[0], m_vals[0], false); CreateEntry(m_regionNames[1], m_keys[3], m_vals[3]); } private void RegexInterestAllStep5() { var region0 = CacheHelper.GetVerifyRegion<object, object>(m_regionNames[0]); var region1 = CacheHelper.GetVerifyRegion<object, object>(m_regionNames[1]); if (region1.Count != 2 || region0.Count != 2) { Assert.Fail("Expected two entry in region"); } VerifyCreated(m_regionNames[0], m_keys[0]); VerifyCreated(m_regionNames[1], m_keys[2]); VerifyEntry(m_regionNames[0], m_keys[0], m_vals[0]); VerifyEntry(m_regionNames[0], m_keys[1], m_vals[1]); VerifyEntry(m_regionNames[1], m_keys[2], m_vals[2]); VerifyEntry(m_regionNames[1], m_keys[3], m_vals[3]); } private void RegexInterestAllStep6() { UpdateEntry(m_regionNames[0], m_keys[0], m_nvals[0], false); UpdateEntry(m_regionNames[1], m_keys[2], m_nvals[2], false); } private void RegexInterestAllStep7() //client 2 { VerifyEntry(m_regionNames[0], m_keys[0], m_nvals[0]); VerifyEntry(m_regionNames[0], m_keys[1], m_vals[1], false); VerifyEntry(m_regionNames[1], m_keys[2], m_nvals[2]); VerifyEntry(m_regionNames[1], m_keys[3], m_vals[3], false); } private void RegexInterestAllStep8() { var region0 = CacheHelper.GetVerifyRegion<object, object>(m_regionNames[0]); var region1 = CacheHelper.GetVerifyRegion<object, object>(m_regionNames[1]); region0.GetSubscriptionService().UnregisterAllKeys(); region1.GetSubscriptionService().UnregisterAllKeys(); } private void RegexInterestAllStep9() { UpdateEntry(m_regionNames[0], m_keys[0], m_vals[0], false); VerifyEntry(m_regionNames[0], m_keys[1], m_vals[1], false); UpdateEntry(m_regionNames[1], m_keys[2], m_vals[2], false); VerifyEntry(m_regionNames[1], m_keys[3], m_vals[3], false); } private void RegexInterestAllStep10() { VerifyEntry(m_regionNames[0], m_keys[0], m_nvals[0]); VerifyEntry(m_regionNames[0], m_keys[1], m_vals[1]); VerifyEntry(m_regionNames[1], m_keys[2], m_nvals[2]); VerifyEntry(m_regionNames[1], m_keys[3], m_vals[3]); } private void RunFailoverInterestAll(bool ssl) { CacheHelper.SetupJavaServers(true, "cacheserver_notify_subscription.xml", "cacheserver_notify_subscription2.xml"); CacheHelper.StartJavaLocator(1, "GFELOC", null, ssl); Util.Log("Locator 1 started."); CacheHelper.StartJavaServerWithLocators(1, "GFECS1", 1, ssl); Util.Log("Cacheserver 1 started."); _client1.Call(CreateTCRegions_Pool, RegionNames, CacheHelper.Locators, "__TESTPOOL1_", true, ssl); _client1.Call(StepThree); Util.Log("StepThree complete."); _client2.Call(CreateTCRegions_Pool, RegionNames, CacheHelper.Locators, "__TESTPOOL1_", true, ssl); Util.Log("CreateTCRegions complete."); _client2.Call(RegexInterestAllStep2); Util.Log("RegexInterestAllStep2 complete."); _client2.Call(RegexInterestAllStep3, CacheHelper.Locators); Util.Log("RegexInterestAllStep3 complete."); _client1.Call(RegexInterestAllStep4); Util.Log("RegexInterestAllStep4 complete."); _client2.Call(RegexInterestAllStep5); Util.Log("RegexInterestAllStep5 complete."); CacheHelper.StartJavaServerWithLocators(2, "GFECS2", 1, ssl); CacheHelper.StopJavaServer(1); //failover happens Util.Log("Cacheserver 2 started and failover forced"); _client1.Call(RegexInterestAllStep6); Util.Log("RegexInterestAllStep6 complete."); System.Threading.Thread.Sleep(5000); // sleep to let updates arrive _client2.Call(RegexInterestAllStep7); Util.Log("RegexInterestAllStep7 complete."); _client2.Call(RegexInterestAllStep8); Util.Log("RegexInterestAllStep8 complete."); _client1.Call(RegexInterestAllStep9); Util.Log("RegexInterestAllStep9 complete."); _client2.Call(RegexInterestAllStep10); Util.Log("RegexInterestAllStep10 complete."); _client1.Call(Close); Util.Log("Client 1 closed"); _client2.Call(Close); Util.Log("Client 2 closed"); CacheHelper.StopJavaServer(2); Util.Log("Cacheserver 2 stopped."); CacheHelper.StopJavaLocator(1, true, ssl); Util.Log("Locator 1 stopped."); CacheHelper.ClearEndpoints(); CacheHelper.ClearLocators(); } private void RunIdictionaryOps() { CacheHelper.SetupJavaServers(true, "cacheserver.xml"); CacheHelper.StartJavaLocator(1, "GFELOC"); Util.Log("Locator 1 started."); CacheHelper.StartJavaServerWithLocators(1, "GFECS1", 1); Util.Log("Cacheserver 1 started."); _client1.Call(CreateTCRegions_Pool, RegionNames2, CacheHelper.Locators, "__TESTPOOL1_", false); Util.Log("StepOne (pool locators) complete."); _client1.Call(IdictionaryRegionOperations, "DistRegionAck"); Util.Log("IdictionaryRegionOperations complete."); _client1.Call(IdictionaryRegionNullKeyOperations, "DistRegionAck"); Util.Log("IdictionaryRegionNullKeyOperations complete."); _client1.Call(IdictionaryRegionArrayOperations, "DistRegionAck"); Util.Log("IdictionaryRegionArrayOperations complete."); _client1.Call(Close); Util.Log("Client 1 closed"); CacheHelper.StopJavaServer(1); Util.Log("Cacheserver 1 stopped."); CacheHelper.StopJavaLocator(1); Util.Log("Locator 1 stopped."); CacheHelper.ClearEndpoints(); CacheHelper.ClearLocators(); } #region Tests [Test] public void CheckPutGet() { RunCheckPutGet(); } [Test] public void CheckPutGetWithAppDomain() { RunCheckPutGetWithAppDomain(); } [Test] public void PdxAppDomainTest() { RunPdxAppDomainTest(false, true); // pool with locators RunPdxAppDomainTest(true, true); // pool with locators RunPdxAppDomainTest(false, false); // pool with locators RunPdxAppDomainTest(true, false); // pool with locators } [Test] public void JavaHashCode() { RunCheckPut(); } [Test] public void CheckFixedPartitionResolver() { RunFixedPartitionResolver(); } [Test] public void CheckNativeException() { RunCheckNativeException(); } [Test] public void RemoveAllWithSingleHop() { RunRemoveAllWithSingleHop(); } [Test] public void RemoveOps() { RunRemoveOps(); } [Test] public void FailOverInterestAllWithSsl() { RunFailoverInterestAll(true); } [Test] public void IdictionaryOps() { RunIdictionaryOps(); } #endregion } }
namespace IDT4.Engine.CM { internal partial class CollisionModelManager { /* =============================================================================== Visualisation code =============================================================================== */ const char *cm_contentsNameByIndex[] = { "none", // 0 "solid", // 1 "opaque", // 2 "water", // 3 "playerclip", // 4 "monsterclip", // 5 "moveableclip", // 6 "ikclip", // 7 "blood", // 8 "body", // 9 "corpse", // 10 "trigger", // 11 "aas_solid", // 12 "aas_obstacle", // 13 "flashlight_trigger", // 14 NULL }; int cm_contentsFlagByIndex[] = { -1, // 0 CONTENTS_SOLID, // 1 CONTENTS_OPAQUE, // 2 CONTENTS_WATER, // 3 CONTENTS_PLAYERCLIP, // 4 CONTENTS_MONSTERCLIP, // 5 CONTENTS_MOVEABLECLIP, // 6 CONTENTS_IKCLIP, // 7 CONTENTS_BLOOD, // 8 CONTENTS_BODY, // 9 CONTENTS_CORPSE, // 10 CONTENTS_TRIGGER, // 11 CONTENTS_AAS_SOLID, // 12 CONTENTS_AAS_OBSTACLE, // 13 CONTENTS_FLASHLIGHT_TRIGGER, // 14 0 }; idCVar cm_drawMask( "cm_drawMask", "none", CVAR_GAME, "collision mask", cm_contentsNameByIndex, idCmdSystem::ArgCompletion_String<cm_contentsNameByIndex> ); idCVar cm_drawColor( "cm_drawColor", "1 0 0 .5", CVAR_GAME, "color used to draw the collision models" ); idCVar cm_drawFilled( "cm_drawFilled", "0", CVAR_GAME | CVAR_BOOL, "draw filled polygons" ); idCVar cm_drawInternal( "cm_drawInternal", "1", CVAR_GAME | CVAR_BOOL, "draw internal edges green" ); idCVar cm_drawNormals( "cm_drawNormals", "0", CVAR_GAME | CVAR_BOOL, "draw polygon and edge normals" ); idCVar cm_backFaceCull( "cm_backFaceCull", "0", CVAR_GAME | CVAR_BOOL, "cull back facing polygons" ); idCVar cm_debugCollision( "cm_debugCollision", "0", CVAR_GAME | CVAR_BOOL, "debug the collision detection" ); static idVec4 cm_color; /* ================ idCollisionModelManagerLocal::ContentsFromString ================ */ int idCollisionModelManagerLocal::ContentsFromString( const char *string ) const { int i, contents = 0; idLexer src( string, idStr::Length( string ), "ContentsFromString" ); idToken token; while( src.ReadToken( &token ) ) { if ( token == "," ) { continue; } for ( i = 1; cm_contentsNameByIndex[i] != NULL; i++ ) { if ( token.Icmp( cm_contentsNameByIndex[i] ) == 0 ) { contents |= cm_contentsFlagByIndex[i]; break; } } } return contents; } /* ================ idCollisionModelManagerLocal::StringFromContents ================ */ const char *idCollisionModelManagerLocal::StringFromContents( const int contents ) const { int i, length = 0; static char contentsString[MAX_STRING_CHARS]; contentsString[0] = '\0'; for ( i = 1; cm_contentsFlagByIndex[i] != 0; i++ ) { if ( contents & cm_contentsFlagByIndex[i] ) { if ( length != 0 ) { length += idStr::snPrintf( contentsString + length, sizeof( contentsString ) - length, "," ); } length += idStr::snPrintf( contentsString + length, sizeof( contentsString ) - length, cm_contentsNameByIndex[i] ); } } return contentsString; } /* ================ idCollisionModelManagerLocal::DrawEdge ================ */ void idCollisionModelManagerLocal::DrawEdge( cm_model_t *model, int edgeNum, const idVec3 &origin, const idMat3 &axis ) { int side; cm_edge_t *edge; idVec3 start, end, mid; bool isRotated; isRotated = axis.IsRotated(); edge = model->edges + abs(edgeNum); side = edgeNum < 0; start = model->vertices[edge->vertexNum[side]].p; end = model->vertices[edge->vertexNum[!side]].p; if ( isRotated ) { start *= axis; end *= axis; } start += origin; end += origin; if ( edge->internal ) { if ( cm_drawInternal.GetBool() ) { session->rw->DebugArrow( colorGreen, start, end, 1 ); } } else { if ( edge->numUsers > 2 ) { session->rw->DebugArrow( colorBlue, start, end, 1 ); } else { session->rw->DebugArrow( cm_color, start, end, 1 ); } } if ( cm_drawNormals.GetBool() ) { mid = (start + end) * 0.5f; if ( isRotated ) { end = mid + 5 * (axis * edge->normal); } else { end = mid + 5 * edge->normal; } session->rw->DebugArrow( colorCyan, mid, end, 1 ); } } /* ================ idCollisionModelManagerLocal::DrawPolygon ================ */ void idCollisionModelManagerLocal::DrawPolygon( cm_model_t *model, cm_polygon_t *p, const idVec3 &origin, const idMat3 &axis, const idVec3 &viewOrigin ) { int i, edgeNum; cm_edge_t *edge; idVec3 center, end, dir; if ( cm_backFaceCull.GetBool() ) { edgeNum = p->edges[0]; edge = model->edges + abs(edgeNum); dir = model->vertices[edge->vertexNum[0]].p - viewOrigin; if ( dir * p->plane.Normal() > 0.0f ) { return; } } if ( cm_drawNormals.GetBool() ) { center = vec3_origin; for ( i = 0; i < p->numEdges; i++ ) { edgeNum = p->edges[i]; edge = model->edges + abs(edgeNum); center += model->vertices[edge->vertexNum[edgeNum < 0]].p; } center *= (1.0f / p->numEdges); if ( axis.IsRotated() ) { center = center * axis + origin; end = center + 5 * (axis * p->plane.Normal()); } else { center += origin; end = center + 5 * p->plane.Normal(); } session->rw->DebugArrow( colorMagenta, center, end, 1 ); } if ( cm_drawFilled.GetBool() ) { idFixedWinding winding; for ( i = p->numEdges - 1; i >= 0; i-- ) { edgeNum = p->edges[i]; edge = model->edges + abs(edgeNum); winding += origin + model->vertices[edge->vertexNum[INTSIGNBITSET(edgeNum)]].p * axis; } session->rw->DebugPolygon( cm_color, winding ); } else { for ( i = 0; i < p->numEdges; i++ ) { edgeNum = p->edges[i]; edge = model->edges + abs(edgeNum); if ( edge->checkcount == checkCount ) { continue; } edge->checkcount = checkCount; DrawEdge( model, edgeNum, origin, axis ); } } } /* ================ idCollisionModelManagerLocal::DrawNodePolygons ================ */ void idCollisionModelManagerLocal::DrawNodePolygons( cm_model_t *model, cm_node_t *node, const idVec3 &origin, const idMat3 &axis, const idVec3 &viewOrigin, const float radius ) { int i; cm_polygon_t *p; cm_polygonRef_t *pref; while (1) { for ( pref = node->polygons; pref; pref = pref->next ) { p = pref->p; if ( radius ) { // polygon bounds should overlap with trace bounds for ( i = 0; i < 3; i++ ) { if ( p->bounds[0][i] > viewOrigin[i] + radius ) { break; } if ( p->bounds[1][i] < viewOrigin[i] - radius ) { break; } } if ( i < 3 ) { continue; } } if ( p->checkcount == checkCount ) { continue; } if ( !( p->contents & cm_contentsFlagByIndex[cm_drawMask.GetInteger()] ) ) { continue; } DrawPolygon( model, p, origin, axis, viewOrigin ); p->checkcount = checkCount; } if ( node->planeType == -1 ) { break; } if ( radius && viewOrigin[node->planeType] > node->planeDist + radius ) { node = node->children[0]; } else if ( radius && viewOrigin[node->planeType] < node->planeDist - radius ) { node = node->children[1]; } else { DrawNodePolygons( model, node->children[1], origin, axis, viewOrigin, radius ); node = node->children[0]; } } } /* ================ idCollisionModelManagerLocal::DrawModel ================ */ void idCollisionModelManagerLocal::DrawModel( CmHandle handle, const idVec3 &modelOrigin, const idMat3 &modelAxis, const idVec3 &viewOrigin, const float radius ) { cm_model_t *model; idVec3 viewPos; if ( handle < 0 && handle >= numModels ) { return; } if ( cm_drawColor.IsModified() ) { sscanf( cm_drawColor.GetString(), "%f %f %f %f", &cm_color.x, &cm_color.y, &cm_color.z, &cm_color.w ); cm_drawColor.ClearModified(); } model = models[ handle ]; viewPos = (viewOrigin - modelOrigin) * modelAxis.Transpose(); checkCount++; DrawNodePolygons( model, model->node, modelOrigin, modelAxis, viewPos, radius ); } /* =============================================================================== Speed test code =============================================================================== */ static idCVar cm_testCollision( "cm_testCollision", "0", CVAR_GAME | CVAR_BOOL, "" ); static idCVar cm_testRotation( "cm_testRotation", "1", CVAR_GAME | CVAR_BOOL, "" ); static idCVar cm_testModel( "cm_testModel", "0", CVAR_GAME | CVAR_INTEGER, "" ); static idCVar cm_testTimes( "cm_testTimes", "1000", CVAR_GAME | CVAR_INTEGER, "" ); static idCVar cm_testRandomMany( "cm_testRandomMany", "0", CVAR_GAME | CVAR_BOOL, "" ); static idCVar cm_testOrigin( "cm_testOrigin", "0 0 0", CVAR_GAME, "" ); static idCVar cm_testReset( "cm_testReset", "0", CVAR_GAME | CVAR_BOOL, "" ); static idCVar cm_testBox( "cm_testBox", "-16 -16 0 16 16 64", CVAR_GAME, "" ); static idCVar cm_testBoxRotation( "cm_testBoxRotation", "0 0 0", CVAR_GAME, "" ); static idCVar cm_testWalk( "cm_testWalk", "1", CVAR_GAME | CVAR_BOOL, "" ); static idCVar cm_testLength( "cm_testLength", "1024", CVAR_GAME | CVAR_FLOAT, "" ); static idCVar cm_testRadius( "cm_testRadius", "64", CVAR_GAME | CVAR_FLOAT, "" ); static idCVar cm_testAngle( "cm_testAngle", "60", CVAR_GAME | CVAR_FLOAT, "" ); static int total_translation; static int min_translation = 999999; static int max_translation = -999999; static int num_translation = 0; static int total_rotation; static int min_rotation = 999999; static int max_rotation = -999999; static int num_rotation = 0; static idVec3 start; static idVec3 *testend; #include "../sys/sys_public.h" void idCollisionModelManagerLocal::DebugOutput( const idVec3 &origin ) { int i, k, t; char buf[128]; idVec3 end; idAngles boxAngles; idMat3 modelAxis, boxAxis; idBounds bounds; trace_t trace; if ( !cm_testCollision.GetBool() ) { return; } testend = (idVec3 *) Mem_Alloc( cm_testTimes.GetInteger() * sizeof(idVec3) ); if ( cm_testReset.GetBool() || ( cm_testWalk.GetBool() && !start.Compare( start ) ) ) { total_translation = total_rotation = 0; min_translation = min_rotation = 999999; max_translation = max_rotation = -999999; num_translation = num_rotation = 0; cm_testReset.SetBool( false ); } if ( cm_testWalk.GetBool() ) { start = origin; cm_testOrigin.SetString( va( "%1.2f %1.2f %1.2f", start[0], start[1], start[2] ) ); } else { sscanf( cm_testOrigin.GetString(), "%f %f %f", &start[0], &start[1], &start[2] ); } sscanf( cm_testBox.GetString(), "%f %f %f %f %f %f", &bounds[0][0], &bounds[0][1], &bounds[0][2], &bounds[1][0], &bounds[1][1], &bounds[1][2] ); sscanf( cm_testBoxRotation.GetString(), "%f %f %f", &boxAngles[0], &boxAngles[1], &boxAngles[2] ); boxAxis = boxAngles.ToMat3(); modelAxis.Identity(); idTraceModel itm( bounds ); idRandom random( 0 ); idTimer timer; if ( cm_testRandomMany.GetBool() ) { // if many traces in one random direction for ( i = 0; i < 3; i++ ) { testend[0][i] = start[i] + random.CRandomFloat() * cm_testLength.GetFloat(); } for ( k = 1; k < cm_testTimes.GetInteger(); k++ ) { testend[k] = testend[0]; } } else { // many traces each in a different random direction for ( k = 0; k < cm_testTimes.GetInteger(); k++ ) { for ( i = 0; i < 3; i++ ) { testend[k][i] = start[i] + random.CRandomFloat() * cm_testLength.GetFloat(); } } } // translational collision detection timer.Clear(); timer.Start(); for ( i = 0; i < cm_testTimes.GetInteger(); i++ ) { Translation( &trace, start, testend[i], &itm, boxAxis, CONTENTS_SOLID|CONTENTS_PLAYERCLIP, cm_testModel.GetInteger(), vec3_origin, modelAxis ); } timer.Stop(); t = timer.Milliseconds(); if ( t < min_translation ) min_translation = t; if ( t > max_translation ) max_translation = t; num_translation++; total_translation += t; if ( cm_testTimes.GetInteger() > 9999 ) { sprintf( buf, "%3dK", (int ) ( cm_testTimes.GetInteger() / 1000 ) ); } else { sprintf( buf, "%4d", cm_testTimes.GetInteger() ); } common->Printf("%s translations: %4d milliseconds, (min = %d, max = %d, av = %1.1f)\n", buf, t, min_translation, max_translation, (float) total_translation / num_translation ); if ( cm_testRandomMany.GetBool() ) { // if many traces in one random direction for ( i = 0; i < 3; i++ ) { testend[0][i] = start[i] + random.CRandomFloat() * cm_testRadius.GetFloat(); } for ( k = 1; k < cm_testTimes.GetInteger(); k++ ) { testend[k] = testend[0]; } } else { // many traces each in a different random direction for ( k = 0; k < cm_testTimes.GetInteger(); k++ ) { for ( i = 0; i < 3; i++ ) { testend[k][i] = start[i] + random.CRandomFloat() * cm_testRadius.GetFloat(); } } } if ( cm_testRotation.GetBool() ) { // rotational collision detection idVec3 vec( random.CRandomFloat(), random.CRandomFloat(), random.RandomFloat() ); vec.Normalize(); idRotation rotation( vec3_origin, vec, cm_testAngle.GetFloat() ); timer.Clear(); timer.Start(); for ( i = 0; i < cm_testTimes.GetInteger(); i++ ) { rotation.SetOrigin( testend[i] ); Rotation( &trace, start, rotation, &itm, boxAxis, CONTENTS_SOLID|CONTENTS_PLAYERCLIP, cm_testModel.GetInteger(), vec3_origin, modelAxis ); } timer.Stop(); t = timer.Milliseconds(); if ( t < min_rotation ) min_rotation = t; if ( t > max_rotation ) max_rotation = t; num_rotation++; total_rotation += t; if ( cm_testTimes.GetInteger() > 9999 ) { sprintf( buf, "%3dK", (int ) ( cm_testTimes.GetInteger() / 1000 ) ); } else { sprintf( buf, "%4d", cm_testTimes.GetInteger() ); } common->Printf("%s rotation: %4d milliseconds, (min = %d, max = %d, av = %1.1f)\n", buf, t, min_rotation, max_rotation, (float) total_rotation / num_rotation ); } Mem_Free( testend ); testend = NULL; } } }
using UnityEngine; using UnityEditor; using System; using System.Linq; using System.IO; using System.Collections.Generic; using Model=UnityEngine.AssetBundles.GraphTool.DataModel.Version2; namespace UnityEngine.AssetBundles.GraphTool { public class FileUtility { public static void RemakeDirectory (string localFolderPath) { if (Directory.Exists(localFolderPath)) { FileUtility.DeleteDirectory(localFolderPath, true); } Directory.CreateDirectory(localFolderPath); } public static void CopyFile (string sourceFilePath, string targetFilePath) { var parentDirectoryPath = Path.GetDirectoryName(targetFilePath); Directory.CreateDirectory(parentDirectoryPath); File.Copy(sourceFilePath, targetFilePath, true); } public static void CopyTemplateFile (string sourceFilePath, string targetFilePath, string srcName, string dstName) { var parentDirectoryPath = Path.GetDirectoryName(targetFilePath); Directory.CreateDirectory(parentDirectoryPath); StreamReader r = File.OpenText(sourceFilePath); string contents = r.ReadToEnd(); contents = contents.Replace(srcName, dstName); File.WriteAllText(targetFilePath, contents); } public static void DeleteFileThenDeleteFolderIfEmpty (string localTargetFilePath) { File.Delete(localTargetFilePath); File.Delete(localTargetFilePath + Model.Settings.UNITY_METAFILE_EXTENSION); var directoryPath = Directory.GetParent(localTargetFilePath).FullName; var restFiles = GetFilePathsInFolder(directoryPath); if (!restFiles.Any()) { FileUtility.DeleteDirectory(directoryPath, true); File.Delete(directoryPath + Model.Settings.UNITY_METAFILE_EXTENSION); } } // Get all files under given path, including files in child folders public static List<string> GetAllFilePathsInFolder (string localFolderPath, bool includeHidden=false, bool includeMeta=!Model.Settings.IGNORE_META) { var filePaths = new List<string>(); if (string.IsNullOrEmpty(localFolderPath)) { return filePaths; } if (!Directory.Exists(localFolderPath)) { return filePaths; } GetFilePathsRecursively(localFolderPath, filePaths, includeHidden, includeMeta); return filePaths; } // Get files under given path public static List<string> GetFilePathsInFolder (string folderPath, bool includeHidden=false, bool includeMeta=!Model.Settings.IGNORE_META) { var filePaths = Directory.GetFiles(folderPath).Select(p=>p); if(!includeHidden) { filePaths = filePaths.Where(path => !(Path.GetFileName(path).StartsWith(Model.Settings.DOTSTART_HIDDEN_FILE_HEADSTRING))); } if (!includeMeta) { filePaths = filePaths.Where(path => !FileUtility.IsMetaFile(path)); } // Directory.GetFiles() returns platform dependent delimiter, so make sure replace with "/" if( Path.DirectorySeparatorChar != Model.Settings.UNITY_FOLDER_SEPARATOR ) { filePaths = filePaths.Select(filePath => filePath.Replace(Path.DirectorySeparatorChar.ToString(), Model.Settings.UNITY_FOLDER_SEPARATOR.ToString())); } return filePaths.ToList(); } private static void GetFilePathsRecursively (string localFolderPath, List<string> filePaths, bool includeHidden=false, bool includeMeta=!Model.Settings.IGNORE_META) { var folders = Directory.GetDirectories(localFolderPath); foreach (var folder in folders) { GetFilePathsRecursively(folder, filePaths, includeHidden, includeMeta); } var files = GetFilePathsInFolder(localFolderPath, includeHidden, includeMeta); filePaths.AddRange(files); } /** create combination of path. delimiter is always '/'. */ public static string PathCombine (params string[] paths) { if (paths.Length < 2) { throw new ArgumentException("Argument must contain at least 2 strings to combine."); } var combinedPath = _PathCombine(paths[0], paths[1]); var restPaths = new string[paths.Length-2]; Array.Copy(paths, 2, restPaths, 0, restPaths.Length); foreach (var path in restPaths) combinedPath = _PathCombine(combinedPath, path); return combinedPath; } private static string _PathCombine (string head, string tail) { if (!head.EndsWith(Model.Settings.UNITY_FOLDER_SEPARATOR.ToString())) { head = head + Model.Settings.UNITY_FOLDER_SEPARATOR; } if (string.IsNullOrEmpty(tail)) { return head; } if (tail.StartsWith(Model.Settings.UNITY_FOLDER_SEPARATOR.ToString())) { tail = tail.Substring(1); } return Path.Combine(head, tail); } public static string GetPathWithProjectPath (string pathUnderProjectFolder) { var assetPath = Application.dataPath; var projectPath = Directory.GetParent(assetPath).ToString(); return FileUtility.PathCombine(projectPath, pathUnderProjectFolder); } public static string GetPathWithAssetsPath (string pathUnderAssetsFolder) { var assetPath = Application.dataPath; return FileUtility.PathCombine(assetPath, pathUnderAssetsFolder); } public static string ProjectPathWithSlash () { var assetPath = Application.dataPath; return Directory.GetParent(assetPath).ToString() + Model.Settings.UNITY_FOLDER_SEPARATOR; } public static bool IsMetaFile (string filePath) { if (filePath.EndsWith(Model.Settings.UNITY_METAFILE_EXTENSION)) return true; return false; } public static bool ContainsHiddenFiles (string filePath) { var pathComponents = filePath.Split(Model.Settings.UNITY_FOLDER_SEPARATOR); foreach (var path in pathComponents) { if (path.StartsWith(Model.Settings.DOTSTART_HIDDEN_FILE_HEADSTRING)) return true; } return false; } public static string EnsurePrefabBuilderCacheDirExists(BuildTarget t, Model.NodeData node) { var cacheDir = FileUtility.PathCombine(Model.Settings.Path.PrefabBuilderCachePath, node.Id, SystemDataUtility.GetPathSafeTargetName(t)); if (!Directory.Exists(cacheDir)) { Directory.CreateDirectory(cacheDir); } if (!cacheDir.EndsWith(Model.Settings.UNITY_FOLDER_SEPARATOR.ToString())) { cacheDir = cacheDir + Model.Settings.UNITY_FOLDER_SEPARATOR.ToString(); } return cacheDir; } public static string EnsureAssetGeneratorCacheDirExists(BuildTarget t, Model.NodeData node) { var cacheDir = FileUtility.PathCombine(Model.Settings.Path.AssetGeneratorCachePath, node.Id, SystemDataUtility.GetPathSafeTargetName(t)); if (!Directory.Exists(cacheDir)) { Directory.CreateDirectory(cacheDir); } if (!cacheDir.EndsWith(Model.Settings.UNITY_FOLDER_SEPARATOR.ToString())) { cacheDir = cacheDir + Model.Settings.UNITY_FOLDER_SEPARATOR.ToString(); } return cacheDir; } public static string EnsureAssetBundleCacheDirExists(BuildTarget t, Model.NodeData node, bool remake = false) { var cacheDir = FileUtility.PathCombine(Model.Settings.Path.BundleBuilderCachePath, node.Id, BuildTargetUtility.TargetToAssetBundlePlatformName(t)); if (!Directory.Exists(cacheDir)) { Directory.CreateDirectory(cacheDir); } else { if(remake) { RemakeDirectory(cacheDir); } } return cacheDir; } public static string GetImportSettingTemplateFilePath(string name) { if(name == Model.Settings.GUI_TEXT_SETTINGTEMPLATE_MODEL) { return Model.Settings.Path.SettingTemplateModel; } if(name == Model.Settings.GUI_TEXT_SETTINGTEMPLATE_AUDIO) { return Model.Settings.Path.SettingTemplateAudio; } if(name == Model.Settings.GUI_TEXT_SETTINGTEMPLATE_TEXTURE) { return Model.Settings.Path.SettingTemplateTexture; } #if UNITY_5_6 || UNITY_5_6_OR_NEWER if(name == Model.Settings.GUI_TEXT_SETTINGTEMPLATE_VIDEO) { return Model.Settings.Path.SettingTemplateVideo; } #endif return null; } public static string GetImportSettingTemplateFilePath(AssetReference a) { if(a.filterType == typeof(ModelImporter)) { return Model.Settings.Path.SettingTemplateModel; } if(a.filterType == typeof(AudioImporter)) { return Model.Settings.Path.SettingTemplateAudio; } if(a.filterType == typeof(TextureImporter)) { return Model.Settings.Path.SettingTemplateTexture; } #if UNITY_5_6 || UNITY_5_6_OR_NEWER if(a.filterType == typeof(VideoClipImporter)) { return Model.Settings.Path.SettingTemplateVideo; } #endif return null; } public static void DeleteDirectory(string varDirePath,bool varRecursive) { string[] tempDirs = Directory.GetDirectories(varDirePath); string[] tempFiles = Directory.GetFiles(varDirePath); foreach (var tempDir in tempDirs) { File.SetAttributes(tempDir, FileAttributes.Normal); } foreach (var tempFile in tempFiles) { File.SetAttributes(tempFile, FileAttributes.Normal); File.Delete(tempFile); } File.SetAttributes(varDirePath, FileAttributes.Normal); Directory.Delete(varDirePath, varRecursive); } } }
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. namespace System.Data.Entity.Migrations.History { using System.Collections.Generic; using System.Data.Common; using System.Data.Entity.Core; using System.Data.Entity.Core.Common; using System.Data.Entity.Core.Common.CommandTrees; using System.Data.Entity.Core.Common.CommandTrees.ExpressionBuilder; using System.Data.Entity.Core.EntityClient; using System.Data.Entity.Core.Metadata.Edm; using System.Data.Entity.Infrastructure; using System.Data.Entity.Infrastructure.Interception; using System.Data.Entity.Internal; using System.Data.Entity.Migrations.Edm; using System.Data.Entity.Migrations.Infrastructure; using System.Data.Entity.Migrations.Model; using System.Data.Entity.ModelConfiguration.Edm; using System.Data.Entity.Resources; using System.Data.Entity.Utilities; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Transactions; using System.Xml.Linq; internal class HistoryRepository : RepositoryBase { private static readonly string _productVersion = typeof(HistoryRepository).Assembly().GetInformationalVersion(); public static readonly PropertyInfo MigrationIdProperty = typeof(HistoryRow).GetDeclaredProperty("MigrationId"); public static readonly PropertyInfo ContextKeyProperty = typeof(HistoryRow).GetDeclaredProperty("ContextKey"); private readonly string _contextKey; private readonly int? _commandTimeout; private readonly IEnumerable<string> _schemas; private readonly Func<DbConnection, string, HistoryContext> _historyContextFactory; private readonly DbContext _contextForInterception; private readonly int _contextKeyMaxLength; private readonly int _migrationIdMaxLength; private readonly DatabaseExistenceState _initialExistence; private readonly DbTransaction _existingTransaction; private string _currentSchema; private bool? _exists; private bool _contextKeyColumnExists; public HistoryRepository( InternalContext usersContext, string connectionString, DbProviderFactory providerFactory, string contextKey, int? commandTimeout, Func<DbConnection, string, HistoryContext> historyContextFactory, IEnumerable<string> schemas = null, DbContext contextForInterception = null, DatabaseExistenceState initialExistence = DatabaseExistenceState.Unknown) : base(usersContext, connectionString, providerFactory) { DebugCheck.NotEmpty(contextKey); DebugCheck.NotNull(historyContextFactory); _initialExistence = initialExistence; _commandTimeout = commandTimeout; _existingTransaction = usersContext.TryGetCurrentStoreTransaction(); _schemas = new[] { EdmModelExtensions.DefaultSchema } .Concat(schemas ?? Enumerable.Empty<string>()) .Distinct(); _contextForInterception = contextForInterception; _historyContextFactory = historyContextFactory; DbConnection connection = null; try { connection = CreateConnection(); using (var context = CreateContext(connection)) { var historyRowEntity = ((IObjectContextAdapter)context).ObjectContext .MetadataWorkspace .GetItems<EntityType>(DataSpace.CSpace) .Single(et => et.GetClrType() == typeof(HistoryRow)); var maxLength = historyRowEntity .Properties .Single(p => p.GetClrPropertyInfo().IsSameAs(MigrationIdProperty)) .MaxLength; _migrationIdMaxLength = maxLength.HasValue ? maxLength.Value : HistoryContext.MigrationIdMaxLength; maxLength = historyRowEntity .Properties .Single(p => p.GetClrPropertyInfo().IsSameAs(ContextKeyProperty)) .MaxLength; _contextKeyMaxLength = maxLength.HasValue ? maxLength.Value : HistoryContext.ContextKeyMaxLength; } } finally { DisposeConnection(connection); } _contextKey = contextKey.RestrictTo(_contextKeyMaxLength); } public virtual MigrationOperation CreateInsertOperation(string migrationId, XDocument model) { DebugCheck.NotEmpty(migrationId); DebugCheck.NotNull(model); DbConnection connection = null; try { connection = CreateConnection(); using (var context = CreateContext(connection)) { context.History.Add( new HistoryRow { MigrationId = migrationId.RestrictTo(_migrationIdMaxLength), ContextKey = _contextKey, Model = new ModelCompressor().Compress(model), ProductVersion = _productVersion }); using (var commandTracer = new CommandTracer(context)) { context.SaveChanges(); return new HistoryOperation( commandTracer.CommandTrees.OfType<DbModificationCommandTree>().ToList()); } } } finally { DisposeConnection(connection); } } public int ContextKeyMaxLength { get { return _contextKeyMaxLength; } } public int MigrationIdMaxLength { get { return _migrationIdMaxLength; } } public string CurrentSchema { get { return _currentSchema; } set { DebugCheck.NotEmpty(value); _currentSchema = value; } } public virtual XDocument GetLastModel(out string migrationId, out string productVersion, string contextKey = null) { using (var context = CreateContext(connection)) { context.Database.ExecuteSqlCommand( ((IObjectContextAdapter)context).ObjectContext.CreateDatabaseScript()); context.History.Add( new HistoryRow { MigrationId = MigrationAssembly .CreateMigrationId(Strings.InitialCreate) .RestrictTo(_migrationIdMaxLength), ContextKey = _contextKey, Model = new ModelCompressor().Compress(model), ProductVersion = _productVersion }); context.SaveChanges(); } migrationId = null; productVersion = null; if (!Exists(contextKey)) { return null; } DbConnection connection = null; try { connection = CreateConnection(); using (var context = CreateContext(connection)) { using (new TransactionScope(TransactionScopeOption.Suppress)) { var baseQuery = CreateHistoryQuery(context, contextKey) .OrderByDescending(h => h.MigrationId); var lastModel = baseQuery .Select( s => new { s.MigrationId, s.Model, s.ProductVersion }) .FirstOrDefault(); if (lastModel == null) { return null; } migrationId = lastModel.MigrationId; productVersion = lastModel.ProductVersion; return new ModelCompressor().Decompress(lastModel.Model); } } } finally { DisposeConnection(connection); } } public virtual XDocument GetModel(string migrationId, out string productVersion) { DebugCheck.NotEmpty(migrationId); productVersion = null; if (!Exists()) { return null; } migrationId = migrationId.RestrictTo(_migrationIdMaxLength); DbConnection connection = null; try { connection = CreateConnection(); using (var context = CreateContext(connection)) { var baseQuery = CreateHistoryQuery(context) .Where(h => h.MigrationId == migrationId); var model = baseQuery .Select( h => new { h.Model, h.ProductVersion }) .SingleOrDefault(); if (model == null) { return null; } productVersion = model.ProductVersion; return new ModelCompressor().Decompress(model.Model); } } finally { DisposeConnection(connection); } } public virtual IEnumerable<string> GetPendingMigrations(IEnumerable<string> localMigrations) { DebugCheck.NotNull(localMigrations); if (!Exists()) { return localMigrations; } DbConnection connection = null; try { connection = CreateConnection(); using (var context = CreateContext(connection)) { List<string> databaseMigrations; using (new TransactionScope(TransactionScopeOption.Suppress)) { databaseMigrations = CreateHistoryQuery(context) .Select(h => h.MigrationId) .ToList(); } localMigrations = localMigrations .Select(m => m.RestrictTo(_migrationIdMaxLength)) .ToArray(); var pendingMigrations = localMigrations.Except(databaseMigrations); var firstDatabaseMigration = databaseMigrations.FirstOrDefault(); var firstLocalMigration = localMigrations.FirstOrDefault(); // If the first database migration and the first local migration don't match, // but both are named InitialCreate then treat it as already applied. This can // happen when trying to migrate a database that was created using initializers if (firstDatabaseMigration != firstLocalMigration && firstDatabaseMigration != null && firstDatabaseMigration.MigrationName() == Strings.InitialCreate && firstLocalMigration != null && firstLocalMigration.MigrationName() == Strings.InitialCreate) { Debug.Assert(pendingMigrations.First() == firstLocalMigration); pendingMigrations = pendingMigrations.Skip(1); } return pendingMigrations.ToList(); } } finally { DisposeConnection(connection); } } public virtual IEnumerable<string> GetMigrationsSince(string migrationId) { DebugCheck.NotEmpty(migrationId); var exists = Exists(); DbConnection connection = null; try { connection = CreateConnection(); using (var context = CreateContext(connection)) { var query = CreateHistoryQuery(context); migrationId = migrationId.RestrictTo(_migrationIdMaxLength); if (migrationId != DbMigrator.InitialDatabase) { if (!exists || !query.Any(h => h.MigrationId == migrationId)) { throw Error.MigrationNotFound(migrationId); } query = query.Where(h => string.Compare(h.MigrationId, migrationId, StringComparison.Ordinal) > 0); } else if (!exists) { return Enumerable.Empty<string>(); } return query .OrderByDescending(h => h.MigrationId) .Select(h => h.MigrationId) .ToList(); } } finally { DisposeConnection(connection); } } public virtual string GetMigrationId(string migrationName) { DebugCheck.NotEmpty(migrationName); if (!Exists()) { return null; } DbConnection connection = null; try { connection = CreateConnection(); using (var context = CreateContext(connection)) { var migrationIds = CreateHistoryQuery(context) .Select(h => h.MigrationId) .Where(m => m.Substring(16) == migrationName) .ToList(); if (!migrationIds.Any()) { return null; } if (migrationIds.Count() == 1) { return migrationIds.Single(); } throw Error.AmbiguousMigrationName(migrationName); } } finally { DisposeConnection(connection); } } private IQueryable<HistoryRow> CreateHistoryQuery(HistoryContext context, string contextKey = null) { IQueryable<HistoryRow> q = context.History; contextKey = !string.IsNullOrWhiteSpace(contextKey) ? contextKey.RestrictTo(_contextKeyMaxLength) : _contextKey; if (_contextKeyColumnExists) { q = q.Where(h => h.ContextKey == contextKey); } return q; } public virtual bool IsShared() { if (!Exists() || !_contextKeyColumnExists) { return false; } DbConnection connection = null; try { connection = CreateConnection(); using (var context = CreateContext(connection)) { return context.History.Any(hr => hr.ContextKey != _contextKey); } } finally { DisposeConnection(connection); } } public virtual bool HasMigrations() { if (!Exists()) { return false; } if (!_contextKeyColumnExists) { return true; } DbConnection connection = null; try { connection = CreateConnection(); using (var context = CreateContext(connection)) { return context.History.Count(hr => hr.ContextKey == _contextKey) > 0; } } finally { DisposeConnection(connection); } } public virtual bool Exists(string contextKey = null) { if (_exists == null) { _exists = QueryExists(contextKey ?? _contextKey); } return _exists.Value; } private bool QueryExists(string contextKey) { DebugCheck.NotNull(contextKey); if (_initialExistence == DatabaseExistenceState.DoesNotExist) { return false; } DbConnection connection = null; try { connection = CreateConnection(); if (_initialExistence == DatabaseExistenceState.Unknown) { using (var context = CreateContext(connection)) { if (!context.Database.Exists()) { return false; } } } foreach (var schema in _schemas.Reverse()) { using (var context = CreateContext(connection, schema)) { _currentSchema = schema; _contextKeyColumnExists = true; // Do the context-key specific query first, since if it succeeds we can avoid // doing the more general query. try { using (new TransactionScope(TransactionScopeOption.Suppress)) { contextKey = contextKey.RestrictTo(_contextKeyMaxLength); if (context.History.Count(hr => hr.ContextKey == contextKey) > 0) { return true; } } } catch (EntityException) { _contextKeyColumnExists = false; } // If the context-key specific query failed, then try the general query to see // if there is a history table in this schema at all if (!_contextKeyColumnExists) { try { using (new TransactionScope(TransactionScopeOption.Suppress)) { context.History.Count(); } } catch (EntityException) { _currentSchema = null; } } } } } finally { DisposeConnection(connection); } return !string.IsNullOrWhiteSpace(_currentSchema); } public virtual void ResetExists() { _exists = null; } public virtual IEnumerable<MigrationOperation> GetUpgradeOperations() { if (!Exists()) { yield break; } DbConnection connection = null; try { connection = CreateConnection(); var tableName = "dbo." + HistoryContext.DefaultTableName; DbProviderManifest providerManifest; if (connection.GetProviderInfo(out providerManifest).IsSqlCe()) { tableName = HistoryContext.DefaultTableName; } using (var context = new LegacyHistoryContext(connection)) { var createdOnExists = false; try { InjectInterceptionContext(context); using (new TransactionScope(TransactionScopeOption.Suppress)) { context.History .Select(h => h.CreatedOn) .FirstOrDefault(); } createdOnExists = true; } catch (EntityException) { } if (createdOnExists) { yield return new DropColumnOperation(tableName, "CreatedOn"); } } using (var context = CreateContext(connection)) { if (!_contextKeyColumnExists) { if (_historyContextFactory != HistoryContext.DefaultFactory) { throw Error.UnableToUpgradeHistoryWhenCustomFactory(); } yield return new AddColumnOperation( tableName, new ColumnModel(PrimitiveTypeKind.String) { MaxLength = _contextKeyMaxLength, Name = "ContextKey", IsNullable = false, DefaultValue = _contextKey }); var emptyModel = new DbModelBuilder().Build(connection).GetModel(); var createTableOperation = (CreateTableOperation) new EdmModelDiffer().Diff(emptyModel, context.GetModel()).Single(); var dropPrimaryKeyOperation = new DropPrimaryKeyOperation { Table = tableName, CreateTableOperation = createTableOperation }; dropPrimaryKeyOperation.Columns.Add("MigrationId"); yield return dropPrimaryKeyOperation; yield return new AlterColumnOperation( tableName, new ColumnModel(PrimitiveTypeKind.String) { MaxLength = _migrationIdMaxLength, Name = "MigrationId", IsNullable = false }, isDestructiveChange: false); var addPrimaryKeyOperation = new AddPrimaryKeyOperation { Table = tableName }; addPrimaryKeyOperation.Columns.Add("MigrationId"); addPrimaryKeyOperation.Columns.Add("ContextKey"); yield return addPrimaryKeyOperation; } } } finally { DisposeConnection(connection); } } public virtual MigrationOperation CreateDeleteOperation(string migrationId) { DebugCheck.NotEmpty(migrationId); DbConnection connection = null; try { connection = CreateConnection(); using (var context = CreateContext(connection)) { var historyRow = new HistoryRow { MigrationId = migrationId.RestrictTo(_migrationIdMaxLength), ContextKey = _contextKey }; context.History.Attach(historyRow); context.History.Remove(historyRow); using (var commandTracer = new CommandTracer(context)) { context.SaveChanges(); return new HistoryOperation( commandTracer.CommandTrees.OfType<DbModificationCommandTree>().ToList()); } } } finally { DisposeConnection(connection); } } public virtual IEnumerable<DbQueryCommandTree> CreateDiscoveryQueryTrees() { DbConnection connection = null; try { connection = CreateConnection(); foreach (var schema in _schemas) { using (var context = CreateContext(connection, schema)) { var query = context.History .Where(h => h.ContextKey == _contextKey) .Select(s => s.MigrationId) .OrderByDescending(s => s); var dbQuery = query as DbQuery<string>; if (dbQuery != null) { dbQuery.InternalQuery.ObjectQuery.EnablePlanCaching = false; } using (var commandTracer = new CommandTracer(context)) { query.First(); var queryTree = commandTracer .CommandTrees .OfType<DbQueryCommandTree>() .Single(t => t.DataSpace == DataSpace.SSpace); yield return new DbQueryCommandTree( queryTree.MetadataWorkspace, queryTree.DataSpace, queryTree.Query.Accept( new ParameterInliner( commandTracer.DbCommands.Single().Parameters))); } } } } finally { DisposeConnection(connection); } } private class ParameterInliner : DefaultExpressionVisitor { private readonly DbParameterCollection _parameters; public ParameterInliner(DbParameterCollection parameters) { DebugCheck.NotNull(parameters); _parameters = parameters; } public override DbExpression Visit(DbParameterReferenceExpression expression) { // Inline parameters return DbExpressionBuilder.Constant(_parameters[expression.ParameterName].Value); } // Removes null parameter checks public override DbExpression Visit(DbOrExpression expression) { return expression.Left.Accept(this); } public override DbExpression Visit(DbAndExpression expression) { if (expression.Right is DbNotExpression) { return expression.Left.Accept(this); } return base.Visit(expression); } } public virtual void BootstrapUsingEFProviderDdl(XDocument model) { DebugCheck.NotNull(model); DbConnection connection = null; try { connection = CreateConnection(); using (var context = CreateContext(connection)) { context.Database.ExecuteSqlCommand( ((IObjectContextAdapter)context).ObjectContext.CreateDatabaseScript()); context.History.Add( new HistoryRow { MigrationId = MigrationAssembly .CreateMigrationId(Strings.InitialCreate) .RestrictTo(_migrationIdMaxLength), ContextKey = _contextKey, Model = new ModelCompressor().Compress(model), ProductVersion = _productVersion }); context.SaveChanges(); } } finally { DisposeConnection(connection); } } public HistoryContext CreateContext(DbConnection connection, string schema = null) { DebugCheck.NotNull(connection); var context = _historyContextFactory(connection, schema ?? CurrentSchema); context.Database.CommandTimeout = _commandTimeout; if (_existingTransaction != null) { Debug.Assert(_existingTransaction.Connection == connection); if (_existingTransaction.Connection == connection) { context.Database.UseTransaction(_existingTransaction); } } InjectInterceptionContext(context); return context; } private void InjectInterceptionContext(DbContext context) { if (_contextForInterception != null) { var objectContext = context.InternalContext.ObjectContext; objectContext.InterceptionContext = objectContext.InterceptionContext.WithDbContext(_contextForInterception); } } } }
using System; using System.Collections; using Org.BouncyCastle.Crypto.Parameters; using Org.BouncyCastle.Math; using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Crypto.Engines { /** * NaccacheStern Engine. For details on this cipher, please see * http://www.gemplus.com/smart/rd/publications/pdf/NS98pkcs.pdf */ public class NaccacheSternEngine : IAsymmetricBlockCipher { private bool forEncryption; private NaccacheSternKeyParameters key; private IList[] lookup = null; private bool debug = false; public string AlgorithmName { get { return "NaccacheStern"; } } /** * Initializes this algorithm. Must be called before all other Functions. * * @see org.bouncycastle.crypto.AsymmetricBlockCipher#init(bool, * org.bouncycastle.crypto.CipherParameters) */ public void Init( bool forEncryption, ICipherParameters parameters) { this.forEncryption = forEncryption; if (parameters is ParametersWithRandom) { parameters = ((ParametersWithRandom)parameters).Parameters; } key = (NaccacheSternKeyParameters)parameters; // construct lookup table for faster decryption if necessary if (!this.forEncryption) { #if !NETFX_CORE if (debug) { Console.WriteLine("Constructing lookup Array"); } #endif NaccacheSternPrivateKeyParameters priv = (NaccacheSternPrivateKeyParameters)key; IList primes = priv.SmallPrimesList; lookup = new IList[primes.Count]; for (int i = 0; i < primes.Count; i++) { IBigInteger actualPrime = (BigInteger)primes[i]; int actualPrimeValue = actualPrime.IntValue; lookup[i] = Platform.CreateArrayList(actualPrimeValue); lookup[i].Add(BigInteger.One); #if !NETFX_CORE if (debug) { Console.WriteLine("Constructing lookup ArrayList for " + actualPrimeValue); } #endif IBigInteger accJ = BigInteger.Zero; for (int j = 1; j < actualPrimeValue; j++) { // IBigInteger bigJ = BigInteger.ValueOf(j); // accJ = priv.PhiN.Multiply(bigJ); accJ = accJ.Add(priv.PhiN); IBigInteger comp = accJ.Divide(actualPrime); lookup[i].Add(priv.G.ModPow(comp, priv.Modulus)); } } } } public bool Debug { set { this.debug = value; } } /** * Returns the input block size of this algorithm. * * @see org.bouncycastle.crypto.AsymmetricBlockCipher#GetInputBlockSize() */ public int GetInputBlockSize() { if (forEncryption) { // We can only encrypt values up to lowerSigmaBound return (key.LowerSigmaBound + 7) / 8 - 1; } else { // We pad to modulus-size bytes for easier decryption. // return key.Modulus.ToByteArray().Length; return key.Modulus.BitLength / 8 + 1; } } /** * Returns the output block size of this algorithm. * * @see org.bouncycastle.crypto.AsymmetricBlockCipher#GetOutputBlockSize() */ public int GetOutputBlockSize() { if (forEncryption) { // encrypted Data is always padded up to modulus size // return key.Modulus.ToByteArray().Length; return key.Modulus.BitLength / 8 + 1; } else { // decrypted Data has upper limit lowerSigmaBound return (key.LowerSigmaBound + 7) / 8 - 1; } } /** * Process a single Block using the Naccache-Stern algorithm. * * @see org.bouncycastle.crypto.AsymmetricBlockCipher#ProcessBlock(byte[], * int, int) */ public byte[] ProcessBlock( byte[] inBytes, int inOff, int length) { if (key == null) throw new InvalidOperationException("NaccacheStern engine not initialised"); if (length > (GetInputBlockSize() + 1)) throw new DataLengthException("input too large for Naccache-Stern cipher.\n"); if (!forEncryption) { // At decryption make sure that we receive padded data blocks if (length < GetInputBlockSize()) { throw new InvalidCipherTextException("BlockLength does not match modulus for Naccache-Stern cipher.\n"); } } // transform input into BigInteger IBigInteger input = new BigInteger(1, inBytes, inOff, length); #if !NETFX_CORE if (debug) { Console.WriteLine("input as BigInteger: " + input); } #endif byte[] output; if (forEncryption) { output = Encrypt(input); } else { IList plain = Platform.CreateArrayList(); NaccacheSternPrivateKeyParameters priv = (NaccacheSternPrivateKeyParameters)key; IList primes = priv.SmallPrimesList; // Get Chinese Remainders of CipherText for (int i = 0; i < primes.Count; i++) { IBigInteger exp = input.ModPow(priv.PhiN.Divide((BigInteger)primes[i]), priv.Modulus); IList al = lookup[i]; if (lookup[i].Count != ((BigInteger)primes[i]).IntValue) { #if !NETFX_CORE if (debug) { Console.WriteLine("Prime is " + primes[i] + ", lookup table has size " + al.Count); } #endif throw new InvalidCipherTextException("Error in lookup Array for " + ((BigInteger)primes[i]).IntValue + ": Size mismatch. Expected ArrayList with length " + ((BigInteger)primes[i]).IntValue + " but found ArrayList of length " + lookup[i].Count); } int lookedup = al.IndexOf(exp); if (lookedup == -1) { #if !NETFX_CORE if (debug) { Console.WriteLine("Actual prime is " + primes[i]); Console.WriteLine("Decrypted value is " + exp); Console.WriteLine("LookupList for " + primes[i] + " with size " + lookup[i].Count + " is: "); for (int j = 0; j < lookup[i].Count; j++) { Console.WriteLine(lookup[i][j]); } } #endif throw new InvalidCipherTextException("Lookup failed"); } plain.Add(BigInteger.ValueOf(lookedup)); } IBigInteger test = chineseRemainder(plain, primes); // Should not be used as an oracle, so reencrypt output to see // if it corresponds to input // this breaks probabilisic encryption, so disable it. Anyway, we do // use the first n primes for key generation, so it is pretty easy // to guess them. But as stated in the paper, this is not a security // breach. So we can just work with the correct sigma. // if (debug) { // Console.WriteLine("Decryption is " + test); // } // if ((key.G.ModPow(test, key.Modulus)).Equals(input)) { // output = test.ToByteArray(); // } else { // if(debug){ // Console.WriteLine("Engine seems to be used as an oracle, // returning null"); // } // output = null; // } output = test.ToByteArray(); } return output; } /** * Encrypts a IBigInteger aka Plaintext with the public key. * * @param plain * The IBigInteger to encrypt * @return The byte[] representation of the encrypted IBigInteger (i.e. * crypted.toByteArray()) */ public byte[] Encrypt( IBigInteger plain) { // Always return modulus size values 0-padded at the beginning // 0-padding at the beginning is correctly parsed by IBigInteger :) // byte[] output = key.Modulus.ToByteArray(); // Array.Clear(output, 0, output.Length); byte[] output = new byte[key.Modulus.BitLength / 8 + 1]; byte[] tmp = key.G.ModPow(plain, key.Modulus).ToByteArray(); Array.Copy(tmp, 0, output, output.Length - tmp.Length, tmp.Length); #if !NETFX_CORE if (debug) { Console.WriteLine("Encrypted value is: " + new BigInteger(output)); } #endif return output; } /** * Adds the contents of two encrypted blocks mod sigma * * @param block1 * the first encrypted block * @param block2 * the second encrypted block * @return encrypt((block1 + block2) mod sigma) * @throws InvalidCipherTextException */ public byte[] AddCryptedBlocks( byte[] block1, byte[] block2) { // check for correct blocksize if (forEncryption) { if ((block1.Length > GetOutputBlockSize()) || (block2.Length > GetOutputBlockSize())) { throw new InvalidCipherTextException( "BlockLength too large for simple addition.\n"); } } else { if ((block1.Length > GetInputBlockSize()) || (block2.Length > GetInputBlockSize())) { throw new InvalidCipherTextException( "BlockLength too large for simple addition.\n"); } } // calculate resulting block IBigInteger m1Crypt = new BigInteger(1, block1); IBigInteger m2Crypt = new BigInteger(1, block2); IBigInteger m1m2Crypt = m1Crypt.Multiply(m2Crypt); m1m2Crypt = m1m2Crypt.Mod(key.Modulus); #if !NETFX_CORE if (debug) { Console.WriteLine("c(m1) as BigInteger:....... " + m1Crypt); Console.WriteLine("c(m2) as BigInteger:....... " + m2Crypt); Console.WriteLine("c(m1)*c(m2)%n = c(m1+m2)%n: " + m1m2Crypt); } #endif //byte[] output = key.Modulus.ToByteArray(); //Array.Clear(output, 0, output.Length); byte[] output = new byte[key.Modulus.BitLength / 8 + 1]; byte[] m1m2CryptBytes = m1m2Crypt.ToByteArray(); Array.Copy(m1m2CryptBytes, 0, output, output.Length - m1m2CryptBytes.Length, m1m2CryptBytes.Length); return output; } /** * Convenience Method for data exchange with the cipher. * * Determines blocksize and splits data to blocksize. * * @param data the data to be processed * @return the data after it went through the NaccacheSternEngine. * @throws InvalidCipherTextException */ public byte[] ProcessData( byte[] data) { #if !NETFX_CORE if (debug) { Console.WriteLine(); } #endif if (data.Length > GetInputBlockSize()) { int inBlocksize = GetInputBlockSize(); int outBlocksize = GetOutputBlockSize(); #if !NETFX_CORE if (debug) { Console.WriteLine("Input blocksize is: " + inBlocksize + " bytes"); Console.WriteLine("Output blocksize is: " + outBlocksize + " bytes"); Console.WriteLine("Data has length:.... " + data.Length + " bytes"); } #endif int datapos = 0; int retpos = 0; byte[] retval = new byte[(data.Length / inBlocksize + 1) * outBlocksize]; while (datapos < data.Length) { byte[] tmp; if (datapos + inBlocksize < data.Length) { tmp = ProcessBlock(data, datapos, inBlocksize); datapos += inBlocksize; } else { tmp = ProcessBlock(data, datapos, data.Length - datapos); datapos += data.Length - datapos; } #if !NETFX_CORE if (debug) { Console.WriteLine("new datapos is " + datapos); } #endif if (tmp != null) { tmp.CopyTo(retval, retpos); retpos += tmp.Length; } else { #if !NETFX_CORE if (debug) { Console.WriteLine("cipher returned null"); } #endif throw new InvalidCipherTextException("cipher returned null"); } } byte[] ret = new byte[retpos]; Array.Copy(retval, 0, ret, 0, retpos); #if !NETFX_CORE if (debug) { Console.WriteLine("returning " + ret.Length + " bytes"); } #endif return ret; } else { #if !NETFX_CORE if (debug) { Console.WriteLine("data size is less then input block size, processing directly"); } #endif return ProcessBlock(data, 0, data.Length); } } /** * Computes the integer x that is expressed through the given primes and the * congruences with the chinese remainder theorem (CRT). * * @param congruences * the congruences c_i * @param primes * the primes p_i * @return an integer x for that x % p_i == c_i */ private static IBigInteger chineseRemainder(IList congruences, IList primes) { IBigInteger retval = BigInteger.Zero; IBigInteger all = BigInteger.One; for (int i = 0; i < primes.Count; i++) { all = all.Multiply((BigInteger)primes[i]); } for (int i = 0; i < primes.Count; i++) { IBigInteger a = (BigInteger)primes[i]; IBigInteger b = all.Divide(a); IBigInteger b2 = b.ModInverse(a); IBigInteger tmp = b.Multiply(b2); tmp = tmp.Multiply((BigInteger)congruences[i]); retval = retval.Add(tmp); } return retval.Mod(all); } } }
//------------------------------------------------------------------------------ // <copyright file="MachineKey.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ /* * MachineKey * * Copyright (c) 2009 Microsoft Corporation */ namespace System.Web.Security { using System; using System.Linq; using System.Web.Configuration; using System.Web.Security.Cryptography; using System.Web.Util; ///////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////// public enum MachineKeyProtection { All, Encryption, Validation } ///////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////// public static class MachineKey { ///////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////// [Obsolete("This method is obsolete and is only provided for compatibility with existing code. It is recommended that new code use the Protect and Unprotect methods instead.")] public static string Encode(byte[] data, MachineKeyProtection protectionOption) { if (data == null) throw new ArgumentNullException("data"); ////////////////////////////////////////////////////////////////////// // Step 1: Get the MAC and add to the blob if (protectionOption == MachineKeyProtection.All || protectionOption == MachineKeyProtection.Validation) { byte[] bHash = MachineKeySection.HashData(data, null, 0, data.Length); byte[] bAll = new byte[bHash.Length + data.Length]; Buffer.BlockCopy(data, 0, bAll, 0, data.Length); Buffer.BlockCopy(bHash, 0, bAll, data.Length, bHash.Length); data = bAll; } if (protectionOption == MachineKeyProtection.All || protectionOption == MachineKeyProtection.Encryption) { ////////////////////////////////////////////////////////////////////// // Step 2: Encryption data = MachineKeySection.EncryptOrDecryptData(true, data, null, 0, data.Length, false, false, IVType.Random, !AppSettings.UseLegacyMachineKeyEncryption); } ////////////////////////////////////////////////////////////////////// // Step 3: Covert the buffer to HEX string and return it return CryptoUtil.BinaryToHex(data); } ///////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////// [Obsolete("This method is obsolete and is only provided for compatibility with existing code. It is recommended that new code use the Protect and Unprotect methods instead.")] public static byte[] Decode(string encodedData, MachineKeyProtection protectionOption) { if (encodedData == null) throw new ArgumentNullException("encodedData"); if ((encodedData.Length % 2) != 0) throw new ArgumentException(null, "encodedData"); byte[] data = null; try { ////////////////////////////////////////////////////////////////////// // Step 1: Covert the HEX string to byte array data = CryptoUtil.HexToBinary(encodedData); } catch { throw new ArgumentException(null, "encodedData"); } if (data == null || data.Length < 1) throw new ArgumentException(null, "encodedData"); if (protectionOption == MachineKeyProtection.All || protectionOption == MachineKeyProtection.Encryption) { ////////////////////////////////////////////////////////////////// // Step 2: Decrypt the data data = MachineKeySection.EncryptOrDecryptData(false, data, null, 0, data.Length, false, false, IVType.Random, !AppSettings.UseLegacyMachineKeyEncryption); if (data == null) return null; } if (protectionOption == MachineKeyProtection.All || protectionOption == MachineKeyProtection.Validation) { ////////////////////////////////////////////////////////////////// // Step 3a: Remove the hash from the end of the data if (data.Length < MachineKeySection.HashSize) return null; byte[] originalData = data; data = new byte[originalData.Length - MachineKeySection.HashSize]; Buffer.BlockCopy(originalData, 0, data, 0, data.Length); ////////////////////////////////////////////////////////////////// // Step 3b: Calculate the hash and make sure it matches byte[] bHash = MachineKeySection.HashData(data, null, 0, data.Length); if (bHash == null || bHash.Length != MachineKeySection.HashSize) return null; // Sizes don't match for (int iter = 0; iter < bHash.Length; iter++) { if (bHash[iter] != originalData[data.Length + iter]) return null; // Mis-match found } } return data; } /// <summary> /// Cryptographically protects and tamper-proofs the specified data. /// </summary> /// <param name="userData">The plaintext data that needs to be protected.</param> /// <param name="purposes">(optional) A list of purposes that describe what the data is meant for. /// If this value is specified, the same list must be passed to the Unprotect method in order /// to decipher the returned ciphertext.</param> /// <returns>The ciphertext data. To decipher the data, call the Unprotect method, passing this /// value as the 'protectedData' parameter.</returns> /// <remarks> /// This method supercedes the Encode method, which required the caller to know whether he wanted /// the plaintext data to be encrypted, signed, or both. In contrast, the Protect method just /// does the right thing and securely protects the data. Ciphertext data produced by this method /// can only be deciphered by the Unprotect method. /// /// The 'purposes' parameter is an optional list of reason strings that can lock the ciphertext /// to a specific purpose. The intent of this parameter is that different subsystems within /// an application may depend on cryptographic operations, and a malicious client should not be /// able to get the result of one subsystem's Protect method and feed it as input to another /// subsystem's Unprotect method, which could have undesirable or insecure behavior. In essence, /// the 'purposes' parameter helps ensure that some protected data can be consumed only by the /// component that originally generated it. Applications should take care to ensure that each /// subsystem uses a unique 'purposes' list. /// /// For example, to protect or unprotect an authentication token, the application could call: /// MachineKey.Protect(..., "Authentication token"); /// MachineKey.Unprotect(..., "Authentication token"); /// /// Applications may dynamically generate the 'purposes' parameter if desired. If an application /// does this, user-supplied values like usernames should never directly be passed for the 'purposes' /// parameter. They should instead be prefixed with something (like "Username: " + username) to /// minimize the risk of a malicious client crafting input that collides with a token in use by some /// other part of the system. Any dynamically-generated tokens should come after non-dynamically /// generated tokens. /// /// For example, to protect or unprotect a private message that is tied to a specific user, the /// application could call: /// MachineKey.Protect(..., "Private message", "Recipient: " + username); /// MachineKey.Unprotect(..., "Private message", "Recipient: " + username); /// /// In both of the above examples, is it important that the caller of the Unprotect method be able to /// resurrect the original 'purposes' list. Otherwise the operation will fail with a CryptographicException. /// </remarks> public static byte[] Protect(byte[] userData, params string[] purposes) { if (userData == null) { throw new ArgumentNullException("userData"); } // Technically we don't care if the purposes array contains whitespace-only entries, // but the DataProtector class does, so we'll just block them right here. if (purposes != null && purposes.Any(String.IsNullOrWhiteSpace)) { throw new ArgumentException(SR.GetString(SR.MachineKey_InvalidPurpose), "purposes"); } return Protect(AspNetCryptoServiceProvider.Instance, userData, purposes); } // Internal method for unit testing. internal static byte[] Protect(ICryptoServiceProvider cryptoServiceProvider, byte[] userData, string[] purposes) { // If the user is calling this method, we want to use the ICryptoServiceProvider // regardless of whether or not it's the default provider. Purpose derivedPurpose = Purpose.User_MachineKey_Protect.AppendSpecificPurposes(purposes); ICryptoService cryptoService = cryptoServiceProvider.GetCryptoService(derivedPurpose); return cryptoService.Protect(userData); } /// <summary> /// Verifies the integrity of and deciphers the given ciphertext. /// </summary> /// <param name="protectedData">Ciphertext data that was produced by the Protect method.</param> /// <param name="purposes">(optional) A list of purposes that describe what the data is meant for.</param> /// <returns>The plaintext data.</returns> /// <exception>Throws a CryptographicException if decryption fails. This can occur if the 'protectedData' has /// been tampered with, if an incorrect 'purposes' parameter is specified, or if an application is deployed /// to more than one server (as in a farm scenario) but is using auto-generated encryption keys.</exception> /// <remarks>See documentation on the Protect method for more information.</remarks> public static byte[] Unprotect(byte[] protectedData, params string[] purposes) { if (protectedData == null) { throw new ArgumentNullException("protectedData"); } // Technically we don't care if the purposes array contains whitespace-only entries, // but the DataProtector class does, so we'll just block them right here. if (purposes != null && purposes.Any(String.IsNullOrWhiteSpace)) { throw new ArgumentException(SR.GetString(SR.MachineKey_InvalidPurpose), "purposes"); } return Unprotect(AspNetCryptoServiceProvider.Instance, protectedData, purposes); } // Internal method for unit testing. internal static byte[] Unprotect(ICryptoServiceProvider cryptoServiceProvider, byte[] protectedData, string[] purposes) { // If the user is calling this method, we want to use the ICryptoServiceProvider // regardless of whether or not it's the default provider. Purpose derivedPurpose = Purpose.User_MachineKey_Protect.AppendSpecificPurposes(purposes); ICryptoService cryptoService = cryptoServiceProvider.GetCryptoService(derivedPurpose); return cryptoService.Unprotect(protectedData); } } }
/****************************************************************************** * The MIT License * Copyright (c) 2003 Novell Inc. www.novell.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the Software), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. *******************************************************************************/ // // Novell.Directory.Ldap.LdapAttributeSet.cs // // Author: // Sunil Kumar (Sunilk@novell.com) // // (C) 2003 Novell, Inc (http://www.novell.com) // using System; namespace Novell.Directory.LDAP.VQ { /// <summary> /// A set of {@link LdapAttribute} objects. /// /// An <code>LdapAttributeSet</code> is a collection of <code>LdapAttribute</code> /// classes as returned from an <code>LdapEntry</code> on a search or read /// operation. <code>LdapAttributeSet</code> may be also used to contruct an entry /// to be added to a directory. If the <code>add()</code> or <code>addAll()</code> /// methods are called and one or more of the objects to be added is not /// an <code>LdapAttribute, ClassCastException</code> is thrown (as discussed in the /// documentation for <code>java.util.Collection</code>). /// /// /// </summary> /// <seealso cref="LdapAttribute"> /// </seealso> /// <seealso cref="LdapEntry"> /// </seealso> public class LdapAttributeSet : SupportClass.AbstractSetSupport//, SupportClass.SetSupport { /// <summary> Returns the number of attributes in this set. /// /// </summary> /// <returns> number of attributes in this set. /// </returns> public override int Count { get { return map.Count; } } /// <summary> This is the underlying data structure for this set. /// HashSet is similar to the functionality of this set. The difference /// is we use the name of an attribute as keys in the Map and LdapAttributes /// as the values. We also do not declare the map as transient, making the /// map serializable. /// </summary> private System.Collections.Hashtable map; /// <summary> Constructs an empty set of attributes.</summary> public LdapAttributeSet() : base() { map = new System.Collections.Hashtable(); } // --- methods not defined in Set --- /// <summary> Returns a deep copy of this attribute set. /// /// </summary> /// <returns> A deep copy of this attribute set. /// </returns> public override object Clone() { try { object newObj = MemberwiseClone(); System.Collections.IEnumerator i = GetEnumerator(); while (i.MoveNext()) { ((LdapAttributeSet)newObj).Add(((LdapAttribute)i.Current).Clone()); } return newObj; } catch (Exception ce) { throw new Exception("Internal error, cannot create clone"); } } /// <summary> Returns the attribute matching the specified attrName. /// /// For example: /// <ul> /// <li><code>getAttribute("cn")</code> returns only the "cn" attribute</li> /// <li><code>getAttribute("cn;lang-en")</code> returns only the "cn;lang-en" /// attribute.</li> /// </ul> /// In both cases, <code>null</code> is returned if there is no exact match to /// the specified attrName. /// /// Note: Novell eDirectory does not currently support language subtypes. /// It does support the "binary" subtype. /// /// </summary> /// <param name="attrName"> The name of an attribute to retrieve, with or without /// subtype specifications. For example, "cn", "cn;phonetic", and /// "cn;binary" are valid attribute names. /// /// </param> /// <returns> The attribute matching the specified attrName, or <code>null</code> /// if there is no exact match. /// </returns> public virtual LdapAttribute getAttribute(string attrName) { return (LdapAttribute)map[attrName.ToUpper()]; } /// <summary> Returns a single best-match attribute, or <code>null</code> if no match is /// available in the entry. /// /// Ldap version 3 allows adding a subtype specification to an attribute /// name. For example, "cn;lang-ja" indicates a Japanese language /// subtype of the "cn" attribute and "cn;lang-ja-JP-kanji" may be a subtype /// of "cn;lang-ja". This feature may be used to provide multiple /// localizations in the same directory. For attributes which do not vary /// among localizations, only the base attribute may be stored, whereas /// for others there may be varying degrees of specialization. /// /// For example, <code>getAttribute(attrName,lang)</code> returns the /// <code>LdapAttribute</code> that exactly matches attrName and that /// best matches lang. /// /// If there are subtypes other than "lang" subtypes included /// in attrName, for example, "cn;binary", only attributes with all of /// those subtypes are returned. If lang is <code>null</code> or empty, the /// method behaves as getAttribute(attrName). If there are no matching /// attributes, <code>null</code> is returned. /// /// /// Assume the entry contains only the following attributes: /// /// <ul> /// <li>cn;lang-en</li> /// <li>cn;lang-ja-JP-kanji</li> /// <li>sn</li> /// </ul> /// /// Examples: /// <ul> /// <li><code>getAttribute( "cn" )</code> returns <code>null</code>.</li> /// <li><code>getAttribute( "sn" )</code> returns the "sn" attribute.</li> /// <li><code>getAttribute( "cn", "lang-en-us" )</code> /// returns the "cn;lang-en" attribute.</li> /// <li><code>getAttribute( "cn", "lang-en" )</code> /// returns the "cn;lang-en" attribute.</li> /// <li><code>getAttribute( "cn", "lang-ja" )</code> /// returns <code>null</code>.</li> /// <li><code>getAttribute( "sn", "lang-en" )</code> /// returns the "sn" attribute.</li> /// </ul> /// /// Note: Novell eDirectory does not currently support language subtypes. /// It does support the "binary" subtype. /// /// </summary> /// <param name="attrName"> The name of an attribute to retrieve, with or without /// subtype specifications. For example, "cn", "cn;phonetic", and /// cn;binary" are valid attribute names. /// /// </param> /// <param name="lang"> A language specification with optional subtypes /// appended using "-" as separator. For example, "lang-en", "lang-en-us", /// "lang-ja", and "lang-ja-JP-kanji" are valid language specification. /// /// </param> /// <returns> A single best-match <code>LdapAttribute</code>, or <code>null</code> /// if no match is found in the entry. /// /// </returns> public virtual LdapAttribute getAttribute(string attrName, string lang) { string key = attrName + ";" + lang; return (LdapAttribute)map[key.ToUpper()]; } /// <summary> Creates a new attribute set containing only the attributes that have /// the specified subtypes. /// /// For example, suppose an attribute set contains the following /// attributes: /// /// <ul> /// <li> cn</li> /// <li> cn;lang-ja</li> /// <li> sn;phonetic;lang-ja</li> /// <li> sn;lang-us</li> /// </ul> /// /// Calling the <code>getSubset</code> method and passing lang-ja as the /// argument, the method returns an attribute set containing the following /// attributes: /// /// <ul> /// <li>cn;lang-ja</li> /// <li>sn;phonetic;lang-ja</li> /// </ul> /// /// </summary> /// <param name="subtype"> Semi-colon delimited list of subtypes to include. For /// example: /// <ul> /// <li> "lang-ja" specifies only Japanese language subtypes</li> /// <li> "binary" specifies only binary subtypes</li> /// <li> "binary;lang-ja" specifies only Japanese language subtypes /// which also are binary</li> /// </ul> /// /// Note: Novell eDirectory does not currently support language subtypes. /// It does support the "binary" subtype. /// /// </param> /// <returns> An attribute set containing the attributes that match the /// specified subtype. /// </returns> public virtual LdapAttributeSet getSubset(string subtype) { // Create a new tempAttributeSet LdapAttributeSet tempAttributeSet = new LdapAttributeSet(); System.Collections.IEnumerator i = GetEnumerator(); // Cycle throught this.attributeSet while (i.MoveNext()) { LdapAttribute attr = (LdapAttribute)i.Current; // Does this attribute have the subtype we are looking for. If // yes then add it to our AttributeSet, else next attribute if (attr.hasSubtype(subtype)) tempAttributeSet.Add(attr.Clone()); } return tempAttributeSet; } // --- methods defined in set --- /// <summary> Returns an iterator over the attributes in this set. The attributes /// returned from this iterator are not in any particular order. /// /// </summary> /// <returns> iterator over the attributes in this set /// </returns> public override System.Collections.IEnumerator GetEnumerator() { return map.Values.GetEnumerator(); } /// <summary> Returns <code>true</code> if this set contains no elements /// /// </summary> /// <returns> <code>true</code> if this set contains no elements /// </returns> public override bool IsEmpty() { return (map.Count == 0); } /// <summary> Returns <code>true</code> if this set contains an attribute of the same name /// as the specified attribute. /// /// </summary> /// <param name="attr"> Object of type <code>LdapAttribute</code> /// /// </param> /// <returns> true if this set contains the specified attribute /// /// @throws ClassCastException occurs the specified Object /// is not of type LdapAttribute. /// </returns> public override bool Contains(object attr) { LdapAttribute attribute = (LdapAttribute)attr; return map.ContainsKey(attribute.Name.ToUpper()); } /// <summary> Adds the specified attribute to this set if it is not already present. /// If an attribute with the same name already exists in the set then the /// specified attribute will not be added. /// /// </summary> /// <param name="attr"> Object of type <code>LdapAttribute</code> /// /// </param> /// <returns> true if the attribute was added. /// /// @throws ClassCastException occurs the specified Object /// is not of type <code>LdapAttribute</code>. /// </returns> public override bool Add(object attr) { //We must enforce that attr is an LdapAttribute LdapAttribute attribute = (LdapAttribute)attr; string name = attribute.Name.ToUpper(); if (map.ContainsKey(name)) return false; SupportClass.PutElement(map, name, attribute); return true; } /// <summary> Removes the specified object from this set if it is present. /// /// If the specified object is of type <code>LdapAttribute</code>, the /// specified attribute will be removed. If the specified object is of type /// <code>String</code>, the attribute with a name that matches the string will /// be removed. /// /// </summary> /// <param name="object">LdapAttribute to be removed or <code>String</code> naming /// the attribute to be removed. /// /// </param> /// <returns> true if the object was removed. /// /// @throws ClassCastException occurs the specified Object /// is not of type <code>LdapAttribute</code> or of type <code>String</code>. /// </returns> public override bool Remove(object object_Renamed) { string attributeName; //the name is the key to object in the HashMap if (object_Renamed is string) { attributeName = ((string)object_Renamed); } else { attributeName = ((LdapAttribute)object_Renamed).Name; } if ((object)attributeName == null) { return false; } return (SupportClass.HashtableRemove(map, attributeName.ToUpper()) != null); } /// <summary> Removes all of the elements from this set.</summary> public override void Clear() { map.Clear(); } /// <summary> Adds all <code>LdapAttribute</code> objects in the specified collection to /// this collection. /// /// </summary> /// <param name="c"> Collection of <code>LdapAttribute</code> objects. /// /// @throws ClassCastException occurs when an element in the /// collection is not of type <code>LdapAttribute</code>. /// /// </param> /// <returns> true if this set changed as a result of the call. /// </returns> public override bool AddAll(System.Collections.ICollection c) { bool setChanged = false; System.Collections.IEnumerator i = c.GetEnumerator(); while (i.MoveNext()) { // we must enforce that everything in c is an LdapAttribute // add will return true if the attribute was added if (Add(i.Current)) { setChanged = true; } } return setChanged; } /// <summary> Returns a string representation of this LdapAttributeSet /// /// </summary> /// <returns> a string representation of this LdapAttributeSet /// </returns> public override string ToString() { System.Text.StringBuilder retValue = new System.Text.StringBuilder("LdapAttributeSet: "); System.Collections.IEnumerator attrs = GetEnumerator(); bool first = true; while (attrs.MoveNext()) { if (!first) { retValue.Append(" "); } first = false; LdapAttribute attr = (LdapAttribute)attrs.Current; retValue.Append(attr.ToString()); } return retValue.ToString(); } } }
using UnityEngine; using UnityEngine.Serialization; using UnityWeld.Binding.Internal; namespace UnityWeld.Binding { /// <summary> /// Bind a property in the view model to one the UI, subscribing to OnPropertyChanged /// and updating the UI accordingly. Also bind to a UnityEvent in the UI and update the /// view model when the event is triggered. /// </summary> [AddComponentMenu("Unity Weld/TwoWay Property Binding")] [HelpURL("https://github.com/Real-Serious-Games/Unity-Weld")] public class TwoWayPropertyBinding : AbstractMemberBinding { /// <summary> /// Name of the property in the view model to bind. /// </summary> public string ViewModelPropertyName { get { return viewModelPropertyName; } set { viewModelPropertyName = value; } } [SerializeField] private string viewModelPropertyName; /// <summary> /// Event in the view to bind to. /// </summary> public string ViewEventName { get { return viewEventName; } set { viewEventName = value; } } [SerializeField, FormerlySerializedAs("uiEventName")] private string viewEventName; /// <summary> /// Property on the view to update when value changes. /// </summary> public string ViewPropertName { get { return viewPropertyName; } set { viewPropertyName = value; } } [SerializeField, FormerlySerializedAs("uiPropertyName")] private string viewPropertyName; /// <summary> /// Name of the type of the adapter we're using to convert values from the /// view model to the view. Can be empty for no adapter. /// </summary> public string ViewAdapterTypeName { get { return viewAdapterTypeName; } set { viewAdapterTypeName = value; } } [SerializeField] private string viewAdapterTypeName; /// <summary> /// Options for the adapter from the view model to the view. /// </summary> public AdapterOptions ViewAdapterOptions { get { return viewAdapterOptions; } set { viewAdapterOptions = value; } } [SerializeField] private AdapterOptions viewAdapterOptions; /// <summary> /// Name of the type of the adapter we're using to conver values from the /// view back to the view model. Can be empty for no adapter. /// </summary> public string ViewModelAdapterTypeName { get { return viewModelAdapterTypeName; } set { viewModelAdapterTypeName = value; } } [SerializeField] private string viewModelAdapterTypeName; /// <summary> /// Options for the adapter from the view to the view model. /// </summary> public AdapterOptions ViewModelAdapterOptions { get { return viewModelAdapterOptions; } set { viewModelAdapterOptions = value; } } [SerializeField] private AdapterOptions viewModelAdapterOptions; /// <summary> /// The name of the property to assign an exception to when adapter/validation fails. /// </summary> public string ExceptionPropertyName { get { return exceptionPropertyName; } set { exceptionPropertyName = value; } } [SerializeField] private string exceptionPropertyName; /// <summary> /// Adapter to apply to any adapter/validation exception that is assigned to the view model. /// </summary> public string ExceptionAdapterTypeName { get { return exceptionAdapterTypeName; } set { exceptionAdapterTypeName = value; } } [SerializeField] private string exceptionAdapterTypeName; /// <summary> /// Adapter options for an exception. /// </summary> public AdapterOptions ExceptionAdapterOptions { get { return exceptionAdapterOptions; } set { exceptionAdapterOptions = value; } } [SerializeField] private AdapterOptions exceptionAdapterOptions; /// <summary> /// Watches the view-model for changes that must be propagated to the view. /// </summary> private PropertyWatcher viewModelWatcher; /// <summary> /// Watches the view for changes that must be propagated to the view-model. /// </summary> private UnityEventWatcher unityEventWatcher; public override void Connect() { string propertyName; Component view; ParseViewEndPointReference(viewPropertyName, out propertyName, out view); var viewModelEndPoint = MakeViewModelEndPoint( viewModelPropertyName, viewModelAdapterTypeName, viewModelAdapterOptions ); var propertySync = new PropertySync( // Source viewModelEndPoint, // Dest new PropertyEndPoint( view, propertyName, CreateAdapter(viewAdapterTypeName), viewAdapterOptions, "view", this ), // Errors, exceptions and validation. !string.IsNullOrEmpty(exceptionPropertyName) ? MakeViewModelEndPoint( exceptionPropertyName, exceptionAdapterTypeName, exceptionAdapterOptions ) : null , this ); viewModelWatcher = viewModelEndPoint.Watch( () => propertySync.SyncFromSource() ); string eventName; string eventComponentType; ParseEndPointReference(viewEventName, out eventName, out eventComponentType); var eventView = GetComponent(eventComponentType); unityEventWatcher = new UnityEventWatcher( eventView, eventName, () => propertySync.SyncFromDest() ); // Copy the initial value over from the view-model. propertySync.SyncFromSource(); } public override void Disconnect() { if (viewModelWatcher != null) { viewModelWatcher.Dispose(); viewModelWatcher = null; } if (unityEventWatcher != null) { unityEventWatcher.Dispose(); unityEventWatcher = null; } } } }
using System; using System.Collections.Generic; using Android.Runtime; namespace Com.Tencent.Mapsdk.Raster.Model { // Metadata.xml XPath class reference: path="/api/package[@name='com.tencent.mapsdk.raster.model']/class[@name='GroundOverlay']" [global::Android.Runtime.Register ("com/tencent/mapsdk/raster/model/GroundOverlay", DoNotGenerateAcw=true)] public sealed partial class GroundOverlay : global::Java.Lang.Object { internal static IntPtr java_class_handle; internal static IntPtr class_ref { get { return JNIEnv.FindClass ("com/tencent/mapsdk/raster/model/GroundOverlay", ref java_class_handle); } } protected override IntPtr ThresholdClass { get { return class_ref; } } protected override global::System.Type ThresholdType { get { return typeof (GroundOverlay); } } internal GroundOverlay (IntPtr javaReference, JniHandleOwnership transfer) : base (javaReference, transfer) {} static IntPtr id_getBearing; static IntPtr id_setBearing_F; public float Bearing { // Metadata.xml XPath method reference: path="/api/package[@name='com.tencent.mapsdk.raster.model']/class[@name='GroundOverlay']/method[@name='getBearing' and count(parameter)=0]" [Register ("getBearing", "()F", "GetGetBearingHandler")] get { if (id_getBearing == IntPtr.Zero) id_getBearing = JNIEnv.GetMethodID (class_ref, "getBearing", "()F"); return JNIEnv.CallFloatMethod (Handle, id_getBearing); } // Metadata.xml XPath method reference: path="/api/package[@name='com.tencent.mapsdk.raster.model']/class[@name='GroundOverlay']/method[@name='setBearing' and count(parameter)=1 and parameter[1][@type='float']]" [Register ("setBearing", "(F)V", "GetSetBearing_FHandler")] set { if (id_setBearing_F == IntPtr.Zero) id_setBearing_F = JNIEnv.GetMethodID (class_ref, "setBearing", "(F)V"); JNIEnv.CallVoidMethod (Handle, id_setBearing_F, new JValue (value)); } } static IntPtr id_getBounds; protected global::Com.Tencent.Mapsdk.Raster.Model.LatLngBounds Bounds { // Metadata.xml XPath method reference: path="/api/package[@name='com.tencent.mapsdk.raster.model']/class[@name='GroundOverlay']/method[@name='getBounds' and count(parameter)=0]" [Register ("getBounds", "()Lcom/tencent/mapsdk/raster/model/LatLngBounds;", "GetGetBoundsHandler")] get { if (id_getBounds == IntPtr.Zero) id_getBounds = JNIEnv.GetMethodID (class_ref, "getBounds", "()Lcom/tencent/mapsdk/raster/model/LatLngBounds;"); return global::Java.Lang.Object.GetObject<global::Com.Tencent.Mapsdk.Raster.Model.LatLngBounds> (JNIEnv.CallObjectMethod (Handle, id_getBounds), JniHandleOwnership.TransferLocalRef); } } static IntPtr id_getHeight; protected float Height { // Metadata.xml XPath method reference: path="/api/package[@name='com.tencent.mapsdk.raster.model']/class[@name='GroundOverlay']/method[@name='getHeight' and count(parameter)=0]" [Register ("getHeight", "()F", "GetGetHeightHandler")] get { if (id_getHeight == IntPtr.Zero) id_getHeight = JNIEnv.GetMethodID (class_ref, "getHeight", "()F"); return JNIEnv.CallFloatMethod (Handle, id_getHeight); } } static IntPtr id_getId; protected string Id { // Metadata.xml XPath method reference: path="/api/package[@name='com.tencent.mapsdk.raster.model']/class[@name='GroundOverlay']/method[@name='getId' and count(parameter)=0]" [Register ("getId", "()Ljava/lang/String;", "GetGetIdHandler")] get { if (id_getId == IntPtr.Zero) id_getId = JNIEnv.GetMethodID (class_ref, "getId", "()Ljava/lang/String;"); return JNIEnv.GetString (JNIEnv.CallObjectMethod (Handle, id_getId), JniHandleOwnership.TransferLocalRef); } } static IntPtr id_getPosition; static IntPtr id_setPosition_Lcom_tencent_mapsdk_raster_model_LatLng_; protected global::Com.Tencent.Mapsdk.Raster.Model.LatLng Position { // Metadata.xml XPath method reference: path="/api/package[@name='com.tencent.mapsdk.raster.model']/class[@name='GroundOverlay']/method[@name='getPosition' and count(parameter)=0]" [Register ("getPosition", "()Lcom/tencent/mapsdk/raster/model/LatLng;", "GetGetPositionHandler")] get { if (id_getPosition == IntPtr.Zero) id_getPosition = JNIEnv.GetMethodID (class_ref, "getPosition", "()Lcom/tencent/mapsdk/raster/model/LatLng;"); return global::Java.Lang.Object.GetObject<global::Com.Tencent.Mapsdk.Raster.Model.LatLng> (JNIEnv.CallObjectMethod (Handle, id_getPosition), JniHandleOwnership.TransferLocalRef); } // Metadata.xml XPath method reference: path="/api/package[@name='com.tencent.mapsdk.raster.model']/class[@name='GroundOverlay']/method[@name='setPosition' and count(parameter)=1 and parameter[1][@type='com.tencent.mapsdk.raster.model.LatLng']]" [Register ("setPosition", "(Lcom/tencent/mapsdk/raster/model/LatLng;)V", "GetSetPosition_Lcom_tencent_mapsdk_raster_model_LatLng_Handler")] set { if (id_setPosition_Lcom_tencent_mapsdk_raster_model_LatLng_ == IntPtr.Zero) id_setPosition_Lcom_tencent_mapsdk_raster_model_LatLng_ = JNIEnv.GetMethodID (class_ref, "setPosition", "(Lcom/tencent/mapsdk/raster/model/LatLng;)V"); JNIEnv.CallVoidMethod (Handle, id_setPosition_Lcom_tencent_mapsdk_raster_model_LatLng_, new JValue (value)); } } static IntPtr id_getTransparency; static IntPtr id_setTransparency_F; protected float Transparency { // Metadata.xml XPath method reference: path="/api/package[@name='com.tencent.mapsdk.raster.model']/class[@name='GroundOverlay']/method[@name='getTransparency' and count(parameter)=0]" [Register ("getTransparency", "()F", "GetGetTransparencyHandler")] get { if (id_getTransparency == IntPtr.Zero) id_getTransparency = JNIEnv.GetMethodID (class_ref, "getTransparency", "()F"); return JNIEnv.CallFloatMethod (Handle, id_getTransparency); } // Metadata.xml XPath method reference: path="/api/package[@name='com.tencent.mapsdk.raster.model']/class[@name='GroundOverlay']/method[@name='setTransparency' and count(parameter)=1 and parameter[1][@type='float']]" [Register ("setTransparency", "(F)V", "GetSetTransparency_FHandler")] set { if (id_setTransparency_F == IntPtr.Zero) id_setTransparency_F = JNIEnv.GetMethodID (class_ref, "setTransparency", "(F)V"); JNIEnv.CallVoidMethod (Handle, id_setTransparency_F, new JValue (value)); } } static IntPtr id_isVisible; static IntPtr id_setVisible_Z; protected bool Visible { // Metadata.xml XPath method reference: path="/api/package[@name='com.tencent.mapsdk.raster.model']/class[@name='GroundOverlay']/method[@name='isVisible' and count(parameter)=0]" [Register ("isVisible", "()Z", "GetIsVisibleHandler")] get { if (id_isVisible == IntPtr.Zero) id_isVisible = JNIEnv.GetMethodID (class_ref, "isVisible", "()Z"); return JNIEnv.CallBooleanMethod (Handle, id_isVisible); } // Metadata.xml XPath method reference: path="/api/package[@name='com.tencent.mapsdk.raster.model']/class[@name='GroundOverlay']/method[@name='setVisible' and count(parameter)=1 and parameter[1][@type='boolean']]" [Register ("setVisible", "(Z)V", "GetSetVisible_ZHandler")] set { if (id_setVisible_Z == IntPtr.Zero) id_setVisible_Z = JNIEnv.GetMethodID (class_ref, "setVisible", "(Z)V"); JNIEnv.CallVoidMethod (Handle, id_setVisible_Z, new JValue (value)); } } static IntPtr id_getWidth; protected float Width { // Metadata.xml XPath method reference: path="/api/package[@name='com.tencent.mapsdk.raster.model']/class[@name='GroundOverlay']/method[@name='getWidth' and count(parameter)=0]" [Register ("getWidth", "()F", "GetGetWidthHandler")] get { if (id_getWidth == IntPtr.Zero) id_getWidth = JNIEnv.GetMethodID (class_ref, "getWidth", "()F"); return JNIEnv.CallFloatMethod (Handle, id_getWidth); } } static IntPtr id_getZIndex; static IntPtr id_setZIndex_F; public float ZIndex { // Metadata.xml XPath method reference: path="/api/package[@name='com.tencent.mapsdk.raster.model']/class[@name='GroundOverlay']/method[@name='getZIndex' and count(parameter)=0]" [Register ("getZIndex", "()F", "GetGetZIndexHandler")] get { if (id_getZIndex == IntPtr.Zero) id_getZIndex = JNIEnv.GetMethodID (class_ref, "getZIndex", "()F"); return JNIEnv.CallFloatMethod (Handle, id_getZIndex); } // Metadata.xml XPath method reference: path="/api/package[@name='com.tencent.mapsdk.raster.model']/class[@name='GroundOverlay']/method[@name='setZIndex' and count(parameter)=1 and parameter[1][@type='float']]" [Register ("setZIndex", "(F)V", "GetSetZIndex_FHandler")] set { if (id_setZIndex_F == IntPtr.Zero) id_setZIndex_F = JNIEnv.GetMethodID (class_ref, "setZIndex", "(F)V"); JNIEnv.CallVoidMethod (Handle, id_setZIndex_F, new JValue (value)); } } static IntPtr id_equals_Ljava_lang_Object_; // Metadata.xml XPath method reference: path="/api/package[@name='com.tencent.mapsdk.raster.model']/class[@name='GroundOverlay']/method[@name='equals' and count(parameter)=1 and parameter[1][@type='java.lang.Object']]" [Register ("equals", "(Ljava/lang/Object;)Z", "")] public override sealed bool Equals (global::Java.Lang.Object p0) { if (id_equals_Ljava_lang_Object_ == IntPtr.Zero) id_equals_Ljava_lang_Object_ = JNIEnv.GetMethodID (class_ref, "equals", "(Ljava/lang/Object;)Z"); bool __ret = JNIEnv.CallBooleanMethod (Handle, id_equals_Ljava_lang_Object_, new JValue (p0)); return __ret; } static IntPtr id_hashCode; // Metadata.xml XPath method reference: path="/api/package[@name='com.tencent.mapsdk.raster.model']/class[@name='GroundOverlay']/method[@name='hashCode' and count(parameter)=0]" [Register ("hashCode", "()I", "")] public override sealed int GetHashCode () { if (id_hashCode == IntPtr.Zero) id_hashCode = JNIEnv.GetMethodID (class_ref, "hashCode", "()I"); return JNIEnv.CallIntMethod (Handle, id_hashCode); } static IntPtr id_remove; // Metadata.xml XPath method reference: path="/api/package[@name='com.tencent.mapsdk.raster.model']/class[@name='GroundOverlay']/method[@name='remove' and count(parameter)=0]" [Register ("remove", "()V", "")] public void Remove () { if (id_remove == IntPtr.Zero) id_remove = JNIEnv.GetMethodID (class_ref, "remove", "()V"); JNIEnv.CallVoidMethod (Handle, id_remove); } static IntPtr id_setAnchor_FF; // Metadata.xml XPath method reference: path="/api/package[@name='com.tencent.mapsdk.raster.model']/class[@name='GroundOverlay']/method[@name='setAnchor' and count(parameter)=2 and parameter[1][@type='float'] and parameter[2][@type='float']]" [Register ("setAnchor", "(FF)V", "")] public void SetAnchor (float p0, float p1) { if (id_setAnchor_FF == IntPtr.Zero) id_setAnchor_FF = JNIEnv.GetMethodID (class_ref, "setAnchor", "(FF)V"); JNIEnv.CallVoidMethod (Handle, id_setAnchor_FF, new JValue (p0), new JValue (p1)); } static IntPtr id_setDimensions_F; // Metadata.xml XPath method reference: path="/api/package[@name='com.tencent.mapsdk.raster.model']/class[@name='GroundOverlay']/method[@name='setDimensions' and count(parameter)=1 and parameter[1][@type='float']]" [Register ("setDimensions", "(F)V", "")] protected void SetDimensions (float p0) { if (id_setDimensions_F == IntPtr.Zero) id_setDimensions_F = JNIEnv.GetMethodID (class_ref, "setDimensions", "(F)V"); JNIEnv.CallVoidMethod (Handle, id_setDimensions_F, new JValue (p0)); } static IntPtr id_setDimensions_FF; // Metadata.xml XPath method reference: path="/api/package[@name='com.tencent.mapsdk.raster.model']/class[@name='GroundOverlay']/method[@name='setDimensions' and count(parameter)=2 and parameter[1][@type='float'] and parameter[2][@type='float']]" [Register ("setDimensions", "(FF)V", "")] protected void SetDimensions (float p0, float p1) { if (id_setDimensions_FF == IntPtr.Zero) id_setDimensions_FF = JNIEnv.GetMethodID (class_ref, "setDimensions", "(FF)V"); JNIEnv.CallVoidMethod (Handle, id_setDimensions_FF, new JValue (p0), new JValue (p1)); } static IntPtr id_setImage_Lcom_tencent_mapsdk_raster_model_BitmapDescriptor_; // Metadata.xml XPath method reference: path="/api/package[@name='com.tencent.mapsdk.raster.model']/class[@name='GroundOverlay']/method[@name='setImage' and count(parameter)=1 and parameter[1][@type='com.tencent.mapsdk.raster.model.BitmapDescriptor']]" [Register ("setImage", "(Lcom/tencent/mapsdk/raster/model/BitmapDescriptor;)V", "")] protected void SetImage (global::Com.Tencent.Mapsdk.Raster.Model.BitmapDescriptor p0) { if (id_setImage_Lcom_tencent_mapsdk_raster_model_BitmapDescriptor_ == IntPtr.Zero) id_setImage_Lcom_tencent_mapsdk_raster_model_BitmapDescriptor_ = JNIEnv.GetMethodID (class_ref, "setImage", "(Lcom/tencent/mapsdk/raster/model/BitmapDescriptor;)V"); JNIEnv.CallVoidMethod (Handle, id_setImage_Lcom_tencent_mapsdk_raster_model_BitmapDescriptor_, new JValue (p0)); } static IntPtr id_setPositionFromBounds_Lcom_tencent_mapsdk_raster_model_LatLngBounds_; // Metadata.xml XPath method reference: path="/api/package[@name='com.tencent.mapsdk.raster.model']/class[@name='GroundOverlay']/method[@name='setPositionFromBounds' and count(parameter)=1 and parameter[1][@type='com.tencent.mapsdk.raster.model.LatLngBounds']]" [Register ("setPositionFromBounds", "(Lcom/tencent/mapsdk/raster/model/LatLngBounds;)V", "")] protected void SetPositionFromBounds (global::Com.Tencent.Mapsdk.Raster.Model.LatLngBounds p0) { if (id_setPositionFromBounds_Lcom_tencent_mapsdk_raster_model_LatLngBounds_ == IntPtr.Zero) id_setPositionFromBounds_Lcom_tencent_mapsdk_raster_model_LatLngBounds_ = JNIEnv.GetMethodID (class_ref, "setPositionFromBounds", "(Lcom/tencent/mapsdk/raster/model/LatLngBounds;)V"); JNIEnv.CallVoidMethod (Handle, id_setPositionFromBounds_Lcom_tencent_mapsdk_raster_model_LatLngBounds_, new JValue (p0)); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.Build.Utilities; using System; using System.Collections.Generic; using Xunit; namespace Microsoft.Build.UnitTests.Evaluation { public class SimpleVersion_Tests { [Fact] public void Ctor_Default() { VerifyVersion(new SimpleVersion(), 0, 0, 0, 0); } [Theory] [InlineData(0)] [InlineData(2)] [InlineData(int.MaxValue)] public static void Ctor_Int(int major) { VerifyVersion(new SimpleVersion(major), major, 0, 0, 0); } [Theory] [InlineData(0, 0)] [InlineData(2, 3)] [InlineData(int.MaxValue, int.MaxValue)] public static void Ctor_Int_Int(int major, int minor) { VerifyVersion(new SimpleVersion(major, minor), major, minor, 0, 0); } [Theory] [InlineData(0, 0, 0)] [InlineData(2, 3, 4)] [InlineData(int.MaxValue, int.MaxValue, int.MaxValue)] public static void Ctor_Int_Int_Int(int major, int minor, int build) { VerifyVersion(new SimpleVersion(major, minor, build), major, minor, build, 0); } [Theory] [InlineData(0, 0, 0, 0)] [InlineData(2, 3, 4, 7)] [InlineData(2, 3, 4, 32767)] [InlineData(2, 3, 4, 32768)] [InlineData(2, 3, 4, 65535)] [InlineData(2, 3, 4, 65536)] [InlineData(2, 3, 4, 2147483647)] [InlineData(2, 3, 4, 2147450879)] [InlineData(2, 3, 4, 2147418112)] [InlineData(int.MaxValue, int.MaxValue, int.MaxValue, int.MaxValue)] public static void Ctor_Int_Int_Int_Int(int major, int minor, int build, int revision) { VerifyVersion(new SimpleVersion(major, minor, build, revision), major, minor, build, revision); } [Fact] public void Ctor_NegativeMajor_ThrowsArgumentOutOfRangeException() { Assert.Throws<ArgumentOutOfRangeException>("major", () => new SimpleVersion(-1, 0)); Assert.Throws<ArgumentOutOfRangeException>("major", () => new SimpleVersion(-1, 0, 0)); Assert.Throws<ArgumentOutOfRangeException>("major", () => new SimpleVersion(-1, 0, 0, 0)); } [Fact] public void Ctor_NegativeMinor_ThrowsArgumentOutOfRangeException() { Assert.Throws<ArgumentOutOfRangeException>("minor", () => new SimpleVersion(0, -1)); Assert.Throws<ArgumentOutOfRangeException>("minor", () => new SimpleVersion(0, -1, 0)); Assert.Throws<ArgumentOutOfRangeException>("minor", () => new SimpleVersion(0, -1, 0, 0)); } [Fact] public void Ctor_NegativeBuild_ThrowsArgumentOutOfRangeException() { Assert.Throws<ArgumentOutOfRangeException>("build", () => new SimpleVersion(0, 0, -1)); Assert.Throws<ArgumentOutOfRangeException>("build", () => new SimpleVersion(0, 0, -1, 0)); } [Fact] public void Ctor_NegativeRevision_ThrowsArgumentOutOfRangeException() { Assert.Throws<ArgumentOutOfRangeException>("revision", () => new SimpleVersion(0, 0, 0, -1)); } public static IEnumerable<object[]> Comparison_TestData() { foreach (var input in new (SimpleVersion v1, SimpleVersion v2, int expectedSign)[] { (new SimpleVersion(1, 2), new SimpleVersion(1, 2), 0), (new SimpleVersion(1, 2), new SimpleVersion(1, 3), -1), (new SimpleVersion(1, 2), new SimpleVersion(1, 1), 1), (new SimpleVersion(1, 2), new SimpleVersion(2, 0), -1), (new SimpleVersion(1, 2), new SimpleVersion(1, 2, 1), -1), (new SimpleVersion(1, 2), new SimpleVersion(1, 2, 0, 1), -1), (new SimpleVersion(1, 2), new SimpleVersion(1, 0), 1), (new SimpleVersion(1, 2), new SimpleVersion(1, 0, 1), 1), (new SimpleVersion(1, 2), new SimpleVersion(1, 0, 0, 1), 1), (new SimpleVersion(3, 2, 1), new SimpleVersion(2, 2, 1), 1), (new SimpleVersion(3, 2, 1), new SimpleVersion(3, 1, 1), 1), (new SimpleVersion(3, 2, 1), new SimpleVersion(3, 2, 0), 1), (new SimpleVersion(1, 2, 3, 4), new SimpleVersion(1, 2, 3, 4), 0), (new SimpleVersion(1, 2, 3, 4), new SimpleVersion(1, 2, 3, 5), -1), (new SimpleVersion(1, 2, 3, 4), new SimpleVersion(1, 2, 3, 3), 1) }) { yield return new object[] { input.v1, input.v2, input.expectedSign }; yield return new object[] { input.v2, input.v1, input.expectedSign * -1 }; } } [Theory] [MemberData(nameof(Comparison_TestData))] public void CompareTo_ReturnsExpected(object version1Object, object version2Object, int expectedSign) { var version1 = (SimpleVersion)version1Object; var version2 = (SimpleVersion)version2Object; Assert.Equal(expectedSign, Comparer<SimpleVersion>.Default.Compare(version1, version2)); Assert.Equal(expectedSign, Math.Sign(version1.CompareTo(version2))); } [Theory] [MemberData(nameof(Comparison_TestData))] public void ComparisonOperators_ReturnExpected(object version1Object, object version2Object, int expectedSign) { var version1 = (SimpleVersion)version1Object; var version2 = (SimpleVersion)version2Object; if (expectedSign < 0) { Assert.True(version1 < version2); Assert.True(version1 <= version2); Assert.False(version1 == version2); Assert.False(version1 >= version2); Assert.False(version1 > version2); Assert.True(version1 != version2); } else if (expectedSign == 0) { Assert.False(version1 < version2); Assert.True(version1 <= version2); Assert.True(version1 == version2); Assert.True(version1 >= version2); Assert.False(version1 > version2); Assert.False(version1 != version2); } else { Assert.False(version1 < version2); Assert.False(version1 <= version2); Assert.False(version1 == version2); Assert.True(version1 >= version2); Assert.True(version1 > version2); Assert.True(version1 != version2); } } public static IEnumerable<object[]> Equals_TestData() { yield return new object[] { new SimpleVersion(2, 3), new SimpleVersion(2, 3), true }; yield return new object[] { new SimpleVersion(2, 3), new SimpleVersion(2, 4), false }; yield return new object[] { new SimpleVersion(2, 3), new SimpleVersion(3, 3), false }; yield return new object[] { new SimpleVersion(2, 3, 4), new SimpleVersion(2, 3, 4), true }; yield return new object[] { new SimpleVersion(2, 3, 4), new SimpleVersion(2, 3, 5), false }; yield return new object[] { new SimpleVersion(2, 3, 4), new SimpleVersion(2, 3), false }; yield return new object[] { new SimpleVersion(2, 3, 4, 5), new SimpleVersion(2, 3, 4, 5), true }; yield return new object[] { new SimpleVersion(2, 3, 4, 5), new SimpleVersion(2, 3, 4, 6), false }; yield return new object[] { new SimpleVersion(2, 3, 4, 5), new SimpleVersion(2, 3), false }; yield return new object[] { new SimpleVersion(2, 3, 4, 5), new SimpleVersion(2, 3, 4), false }; yield return new object[] { new SimpleVersion(2, 3, 0), new SimpleVersion(2, 3), true }; yield return new object[] { new SimpleVersion(2, 3, 4, 0), new SimpleVersion(2, 3, 4), true }; yield return new object[] { new SimpleVersion(2, 3, 4, 5), new TimeSpan(), false }; yield return new object[] { new SimpleVersion(2, 3, 4, 5), null, false }; } [Theory] [MemberData(nameof(Equals_TestData))] public static void Equals_Other_ReturnsExpected(object version1Object, object version2Object, bool expected) { var version1 = (SimpleVersion)version1Object; if (version2Object is SimpleVersion version2) { Assert.Equal(expected, version1.Equals(version2)); Assert.Equal(expected, version1 == version2); Assert.Equal(!expected, version1 != version2); } Assert.Equal(expected, version1.Equals(version2Object)); if (version2Object != null) { Assert.Equal(expected, version1Object.GetHashCode() == version2Object.GetHashCode()); } } public static IEnumerable<object[]> Parse_Valid_TestData() { foreach (var prefix in new[] { "", "v", "V"}) { foreach (var suffix in new[] { "", "-pre", "-pre+metadata", "+metadata"}) { yield return new object[] { $"{prefix}1{suffix}", new SimpleVersion(1) }; yield return new object[] { $"{prefix}1.2{suffix}", new SimpleVersion(1, 2) }; yield return new object[] { $"{prefix}1.2.3{suffix}", new SimpleVersion(1, 2, 3) }; yield return new object[] { $"{prefix}1.2.3.4{suffix}", new SimpleVersion(1, 2, 3, 4) }; yield return new object[] { $"{prefix}2147483647.2147483647.2147483647.2147483647{suffix}", new SimpleVersion(int.MaxValue, int.MaxValue, int.MaxValue, int.MaxValue) }; } } } [Theory] [MemberData(nameof(Parse_Valid_TestData))] public static void Parse_ValidInput_ReturnsExpected(string input, object expected) { Assert.Equal(expected, SimpleVersion.Parse(input)); } public static IEnumerable<object[]> Parse_Invalid_TestData() { yield return new object[] { null, typeof(ArgumentNullException) }; // Input is null yield return new object[] { "", typeof(FormatException) }; // Input is empty yield return new object[] { "1,2,3,4", typeof(FormatException) }; // Input contains invalid separator yield return new object[] { "1.2.3.4.5", typeof(FormatException) }; // Input has more than 4 version components yield return new object[] { "1." , typeof(FormatException) }; // Input contains empty component yield return new object[] { "1.2,", typeof(FormatException) }; // Input contains empty component yield return new object[] { "1.2.3.", typeof(FormatException) }; // Input contains empty component yield return new object[] { "1.2.3.4.", typeof(FormatException) }; // Input contains empty component yield return new object[] { "NotAVersion", typeof(FormatException) }; // Input contains non-numeric value yield return new object[] { "b.2.3.4", typeof(FormatException) }; // Input contains non-numeric value yield return new object[] { "1.b.3.4", typeof(FormatException) }; // Input contains non-numeric value yield return new object[] { "1.2.b.4", typeof(FormatException) }; // Input contains non-numeric value yield return new object[] { "1.2.3.b", typeof(FormatException) }; // Input contains non-numeric value yield return new object[] { "2147483648.2.3.4", typeof(FormatException) }; // Input contains a value > int.MaxValue yield return new object[] { "1.2147483648.3.4", typeof(FormatException) }; // Input contains a value > int.MaxValue yield return new object[] { "1.2.2147483648.4", typeof(FormatException) }; // Input contains a value > int.MaxValue yield return new object[] { "1.2.3.2147483648", typeof(FormatException) }; // Input contains a value > int.MaxValue // System.Version allows whitespace around components, but we don't yield return new object[] { "2 .3. 4. \t\r\n15 ", typeof(FormatException) }; yield return new object[] { " 2 .3. 4. \t\r\n15 ", typeof(FormatException) }; // System.Version rejects these because they have negative values, but SimpleVersion strips interprest as semver prerelease to strip // They are still invalid because the stripping leaves a empty components behind which are also not allowed as above. yield return new object[] { "-1.2.3.4", typeof(FormatException) }; yield return new object[] { "1.-2.3.4", typeof(FormatException) }; yield return new object[] { "1.2.-3.4", typeof(FormatException) }; yield return new object[] { "1.2.3.-4", typeof(FormatException) }; // System.Version treats this as 1.2.3.4, but SimpleVersion interprets as semver metadata to ignore yielding invalid empty string // System.Version parses allowing leading sign, but we treat both sign indicators as beginning of semver part to strip. yield return new object[] { "+1.+2.+3.+4", typeof(FormatException) }; // Only one 'v' allowed as prefix yield return new object[] { "vv1.2.3.4", typeof(FormatException) }; } [Theory] [MemberData(nameof(Parse_Invalid_TestData))] public static void Parse_InvalidInput_ThrowsException(string input, Type exceptionType) { Assert.Throws(exceptionType, () => SimpleVersion.Parse(input)); } public static IEnumerable<object[]> ToString_TestData() { yield return new object[] { new SimpleVersion(1), "1.0.0.0"}; yield return new object[] { new SimpleVersion(1, 2), "1.2.0.0" }; yield return new object[] { new SimpleVersion(1, 2, 3), "1.2.3.0" }; yield return new object[] { new SimpleVersion(1, 2, 3, 4), "1.2.3.4" }; } [Theory] [MemberData(nameof(ToString_TestData))] public static void ToString_Invoke_ReturnsExpected(object versionObject, string expected) { var version = (SimpleVersion)versionObject; Assert.Equal(expected, version.ToString()); } private static void VerifyVersion(SimpleVersion version, int major, int minor, int build, int revision) { Assert.Equal(major, version.Major); Assert.Equal(minor, version.Minor); Assert.Equal(build, version.Build); Assert.Equal(revision, version.Revision); } } }
// 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.DirectoryServices; using System.Collections.Generic; using System.Collections; using System.Diagnostics; using System.Security.Principal; namespace System.DirectoryServices.AccountManagement { internal class ADDNLinkedAttrSet : BookmarkableResultSet { // This class can be used to either enumerate the members of a group, or the groups // to which a principal belongs. If being used to enumerate the members of a group: // * groupDN --- the DN of the group we're enumerating // * members --- array of enumerators containing the DNs of the members of the group we're enumerating (the "member" attribute) // * primaryGroupDN --- should be null // * recursive --- whether or not to recursively enumerate group membership // // If being used to enumerate the groups to which a principal belongs: // * groupDN --- the DN of the principal (i.e., the user) // * members --- the DNs of the groups to which that principal belongs (e.g, the "memberOf" attribute) // * primaryGroupDN --- the DN of the principal's primary group (constructed from the "primaryGroupID" attribute) // * recursive --- should be false // // Note that the variables in this class are generally named in accord with the "enumerating the members // of a group" case. // // It is assumed that recursive enumeration will only be performed for the "enumerating the members of a group" // case, not the "groups to which a principal belongs" case, thus, this.recursive == true implies the former // (but this.recursive == false could imply either case). internal ADDNLinkedAttrSet( string groupDN, IEnumerable[] members, string primaryGroupDN, DirectorySearcher primaryGroupMembersSearcher, bool recursive, ADStoreCtx storeCtx) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "ADDNLinkedAttrSet: groupDN={0}, primaryGroupDN={1}, recursive={2}, PG queryFilter={3}, PG queryBase={4}", groupDN, (primaryGroupDN != null ? primaryGroupDN : "NULL"), recursive, (primaryGroupMembersSearcher != null ? primaryGroupMembersSearcher.Filter : "NULL"), (primaryGroupMembersSearcher != null ? primaryGroupMembersSearcher.SearchRoot.Path : "NULL")); _groupsVisited.Add(groupDN); // so we don't revisit it _recursive = recursive; _storeCtx = storeCtx; _originalStoreCtx = storeCtx; if (null != members) { foreach (IEnumerable enumerator in members) { _membersQueue.Enqueue(enumerator); _originalMembers.Enqueue(enumerator); } } _members = null; _currentMembersSearcher = null; _primaryGroupDN = primaryGroupDN; if (primaryGroupDN == null) _returnedPrimaryGroup = true; // so we don't bother trying to return the primary group _primaryGroupMembersSearcher = primaryGroupMembersSearcher; _expansionMode = ExpansionMode.Enum; _originalExpansionMode = _expansionMode; } internal ADDNLinkedAttrSet( string groupDN, DirectorySearcher[] membersSearcher, string primaryGroupDN, DirectorySearcher primaryGroupMembersSearcher, bool recursive, ADStoreCtx storeCtx) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "ADDNLinkedAttrSet: groupDN={0}, primaryGroupDN={1}, recursive={2}, M queryFilter={3}, M queryBase={4}, PG queryFilter={5}, PG queryBase={6}", groupDN, (primaryGroupDN != null ? primaryGroupDN : "NULL"), recursive, (membersSearcher != null ? membersSearcher[0].Filter : "NULL"), (membersSearcher != null ? membersSearcher[0].SearchRoot.Path : "NULL"), (primaryGroupMembersSearcher != null ? primaryGroupMembersSearcher.Filter : "NULL"), (primaryGroupMembersSearcher != null ? primaryGroupMembersSearcher.SearchRoot.Path : "NULL")); _groupsVisited.Add(groupDN); // so we don't revisit it _recursive = recursive; _storeCtx = storeCtx; _originalStoreCtx = storeCtx; _members = null; _originalMembers = null; _membersEnum = null; _primaryGroupDN = primaryGroupDN; if (primaryGroupDN == null) _returnedPrimaryGroup = true; // so we don't bother trying to return the primary group if (null != membersSearcher) { foreach (DirectorySearcher ds in membersSearcher) { _memberSearchersQueue.Enqueue(ds); _memberSearchersQueueOriginal.Enqueue(ds); } } _currentMembersSearcher = null; _primaryGroupMembersSearcher = primaryGroupMembersSearcher; _expansionMode = ExpansionMode.ASQ; _originalExpansionMode = _expansionMode; } // Return the principal we're positioned at as a Principal object. // Need to use our StoreCtx's GetAsPrincipal to convert the native object to a Principal override internal object CurrentAsPrincipal { get { if (this.current != null) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "CurrentAsPrincipal: using current"); if (this.current is DirectoryEntry) return ADUtils.DirectoryEntryAsPrincipal((DirectoryEntry)this.current, _storeCtx); else { return ADUtils.SearchResultAsPrincipal((SearchResult)this.current, _storeCtx, null); } } else { GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "CurrentAsPrincipal: using currentForeignPrincipal"); Debug.Assert(_currentForeignPrincipal != null); return _currentForeignPrincipal; } } } // Advance the enumerator to the next principal in the result set, pulling in additional pages // of results (or ranges of attribute values) as needed. // Returns true if successful, false if no more results to return. override internal bool MoveNext() { GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "Entering MoveNext"); _atBeginning = false; bool needToRetry; bool f = false; do { needToRetry = false; // reset our found state. If we are restarting the loop we don't have a current principal yet. f = false; if (!_returnedPrimaryGroup) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "MoveNext: trying PrimaryGroup DN"); f = MoveNextPrimaryGroupDN(); } if (!f) { if (_expansionMode == ExpansionMode.ASQ) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "MoveNext: trying member searcher"); f = MoveNextMemberSearcher(); } else { GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "MoveNext: trying member enum"); f = MoveNextMemberEnum(); } } if (!f) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "MoveNext: trying foreign"); f = MoveNextForeign(ref needToRetry); } if (!f) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "MoveNext: trying primary group search"); f = MoveNextQueryPrimaryGroupMember(); } } while (needToRetry); return f; } private bool MoveNextPrimaryGroupDN() { // Do the special primary group ID processing if we haven't yet returned the primary group. Debug.Assert(_primaryGroupDN != null); this.current = SDSUtils.BuildDirectoryEntry( BuildPathFromDN(_primaryGroupDN), _storeCtx.Credentials, _storeCtx.AuthTypes); _storeCtx.InitializeNewDirectoryOptions((DirectoryEntry)this.current); GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "MoveNextMemberSearcher: returning primary group {0}", ((DirectoryEntry)this.current).Path); _currentForeignDE = null; _currentForeignPrincipal = null; _returnedPrimaryGroup = true; return true; } private bool GetNextSearchResult() { bool memberFound = false; do { if (_currentMembersSearcher == null) { Debug.Assert(_memberSearchersQueue != null); if (_memberSearchersQueue.Count == 0) { // We are out of searchers in the queue. return false; } else { // Remove the next searcher from the queue and place it in the current search variable. _currentMembersSearcher = _memberSearchersQueue.Dequeue(); _memberSearchResults = _currentMembersSearcher.FindAll(); Debug.Assert(_memberSearchResults != null); _memberSearchResultsEnumerator = _memberSearchResults.GetEnumerator(); } } GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "MoveNextQueryMember: have a searcher"); memberFound = _memberSearchResultsEnumerator.MoveNext(); // The search is complete. // Dipose the searcher and search results. if (!memberFound) { _currentMembersSearcher.Dispose(); _currentMembersSearcher = null; _memberSearchResults.Dispose(); _memberSearchResults = null; } } while (!memberFound); return memberFound; } private bool MoveNextMemberSearcher() { GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "Entering MoveNextMemberSearcher"); bool needToRetry = false; bool f = false; do { f = GetNextSearchResult(); needToRetry = false; if (f) { SearchResult currentSR = (SearchResult)_memberSearchResultsEnumerator.Current; // Got a member from this group (or, got a group of which we're a member). // Create a DirectoryEntry for it. string memberDN = (string)currentSR.Properties["distinguishedName"][0]; GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "MoveNextMemberSearcher: got a value from the enumerator: {0}", memberDN); // Make sure the member is a principal if ((!ADUtils.IsOfObjectClass(currentSR, "group")) && (!ADUtils.IsOfObjectClass(currentSR, "user")) && // includes computer as well (!ADUtils.IsOfObjectClass(currentSR, "foreignSecurityPrincipal"))) { // We found a member, but it's not a principal type. Skip it. GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "MoveNextMemberSearcher: not a principal, skipping"); needToRetry = true; } // If we're processing recursively, and the member is a group, we DON'T return it, // but rather treat it as something to recursively visit later // (unless we've already visited the group previously) else if (_recursive && ADUtils.IsOfObjectClass(currentSR, "group")) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "MoveNextMemberSearcher: adding to groupsToVisit"); if (!_groupsVisited.Contains(memberDN) && !_groupsToVisit.Contains(memberDN)) _groupsToVisit.Add(memberDN); // and go on to the next member.... needToRetry = true; } else if (_recursive && ADUtils.IsOfObjectClass(currentSR, "foreignSecurityPrincipal")) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "MoveNextMemberSearcher: foreign principal, adding to foreignMembers"); // If we haven't seen this FPO yet then add it to the seen user database. if (!_usersVisited.ContainsKey(currentSR.Properties["distinguishedName"][0].ToString())) { // The FPO might represent a group, in which case we should recursively enumerate its // membership. So save it off for later processing. _foreignMembersCurrentGroup.Add(currentSR.GetDirectoryEntry()); _usersVisited.Add(currentSR.Properties["distinguishedName"][0].ToString(), true); } // and go on to the next member.... needToRetry = true; } else { GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "MoveNextMemberSearcher: using as current"); // Check to see if we have already seen this user during the enumeration // If so then move on to the next user. If not then return it as current. if (!_usersVisited.ContainsKey(currentSR.Properties["distinguishedName"][0].ToString())) { this.current = currentSR; _currentForeignDE = null; _currentForeignPrincipal = null; _usersVisited.Add(currentSR.Properties["distinguishedName"][0].ToString(), true); } else { needToRetry = true; } } } else { // We reached the end of this group's membership. If we're not processing recursively, // we're done. Otherwise, go on to the next group to visit. // First create a DE that points to the group we want to expand, Using that as a search root run // an ASQ search against member and start enumerting those results. if (_recursive) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "MoveNextMemberSearcher: recursive processing, groupsToVisit={0}", _groupsToVisit.Count); if (_groupsToVisit.Count > 0) { // Pull off the next group to visit string groupDN = _groupsToVisit[0]; _groupsToVisit.RemoveAt(0); _groupsVisited.Add(groupDN); GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "MoveNextMemberSearcher: recursively processing {0}", groupDN); // get the membership of this new group DirectoryEntry groupDE = SDSUtils.BuildDirectoryEntry(BuildPathFromDN(groupDN), _storeCtx.Credentials, _storeCtx.AuthTypes); _storeCtx.InitializeNewDirectoryOptions(groupDE); // Queue up a searcher for the new group expansion. DirectorySearcher ds = SDSUtils.ConstructSearcher(groupDE); ds.Filter = "(objectClass=*)"; ds.SearchScope = SearchScope.Base; ds.AttributeScopeQuery = "member"; ds.CacheResults = false; _memberSearchersQueue.Enqueue(ds); // and go on to the first member of this new group. needToRetry = true; } } } } while (needToRetry); return f; } private bool GetNextEnum() { bool memberFound = false; do { if (null == _members) { if (_membersQueue.Count == 0) { return false; } _members = _membersQueue.Dequeue(); _membersEnum = _members.GetEnumerator(); } memberFound = _membersEnum.MoveNext(); if (!memberFound) { IDisposable disposableMembers = _members as IDisposable; if (disposableMembers != null) { disposableMembers.Dispose(); } IDisposable disposableMembersEnum = _membersEnum as IDisposable; if (disposableMembersEnum != null) { disposableMembersEnum.Dispose(); } _members = null; _membersEnum = null; } } while (!memberFound); return memberFound; } private bool MoveNextMemberEnum() { GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "Entering MoveNextMemberEnum"); bool needToRetry = false; bool disposeMemberDE = false; bool f; do { f = GetNextEnum(); needToRetry = false; disposeMemberDE = false; if (f) { DirectoryEntry memberDE = null; try { // Got a member from this group (or, got a group of which we're a member). // Create a DirectoryEntry for it. string memberDN = (string)_membersEnum.Current; GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "MoveNextMemberEnum: got a value from the enumerator: {0}", memberDN); memberDE = SDSUtils.BuildDirectoryEntry( BuildPathFromDN(memberDN), _storeCtx.Credentials, _storeCtx.AuthTypes); _storeCtx.InitializeNewDirectoryOptions(memberDE); _storeCtx.LoadDirectoryEntryAttributes(memberDE); // Make sure the member is a principal if ((!ADUtils.IsOfObjectClass(memberDE, "group")) && (!ADUtils.IsOfObjectClass(memberDE, "user")) && // includes computer as well (!ADUtils.IsOfObjectClass(memberDE, "foreignSecurityPrincipal"))) { // We found a member, but it's not a principal type. Skip it. GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "MoveNextMemberEnum: not a principal, skipping"); needToRetry = true; disposeMemberDE = true; //Since member is not principal we don't return it. So mark it for dispose. } // If we're processing recursively, and the member is a group, we DON'T return it, // but rather treat it as something to recursively visit later // (unless we've already visited the group previously) else if (_recursive && ADUtils.IsOfObjectClass(memberDE, "group")) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "MoveNextMemberEnum: adding to groupsToVisit"); if (!_groupsVisited.Contains(memberDN) && !_groupsToVisit.Contains(memberDN)) _groupsToVisit.Add(memberDN); // and go on to the next member.... needToRetry = true; disposeMemberDE = true; //Since recursive is set to true, we do not return groups. So mark it for dispose. } else if (_recursive && ADUtils.IsOfObjectClass(memberDE, "foreignSecurityPrincipal")) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "MoveNextMemberEnum: foreign principal, adding to foreignMembers"); // If we haven't seen this FPO yet then add it to the seen user database. if (!_usersVisited.ContainsKey(memberDE.Properties["distinguishedName"][0].ToString())) { // The FPO might represent a group, in which case we should recursively enumerate its // membership. So save it off for later processing. _foreignMembersCurrentGroup.Add(memberDE); _usersVisited.Add(memberDE.Properties["distinguishedName"][0].ToString(), true); disposeMemberDE = false; //We store the FPO DirectoryEntry objects for further processing. So do NOT dispose it. } // and go on to the next member.... needToRetry = true; } else { GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "MoveNextMemberEnum: using as current"); // Check to see if we have already seen this user during the enumeration // If so then move on to the next user. If not then return it as current. if (!_usersVisited.ContainsKey(memberDE.Properties["distinguishedName"][0].ToString())) { this.current = memberDE; _currentForeignDE = null; _currentForeignPrincipal = null; _usersVisited.Add(memberDE.Properties["distinguishedName"][0].ToString(), true); disposeMemberDE = false; //memberDE will be set in the Principal object we return. So do NOT dispose it. } else { needToRetry = true; } } } finally { if (disposeMemberDE && memberDE != null) { //This means the constructed member is not used in the new principal memberDE.Dispose(); } } } else { // We reached the end of this group's membership. If we're not processing recursively, // we're done. Otherwise, go on to the next group to visit. if (_recursive) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "MoveNextLocal: recursive processing, groupsToVisit={0}", _groupsToVisit.Count); if (_groupsToVisit.Count > 0) { // Pull off the next group to visit string groupDN = _groupsToVisit[0]; _groupsToVisit.RemoveAt(0); _groupsVisited.Add(groupDN); GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "MoveNextMemberEnum: recursively processing {0}", groupDN); // get the membership of this new group DirectoryEntry groupDE = SDSUtils.BuildDirectoryEntry( BuildPathFromDN(groupDN), _storeCtx.Credentials, _storeCtx.AuthTypes); _storeCtx.InitializeNewDirectoryOptions(groupDE); // set up for the next round of enumeration //Here a new DirectoryEntry object is created and passed //to RangeRetriever object. Hence, configure //RangeRetriever to dispose the DirEntry on its dispose. _membersQueue.Enqueue(new RangeRetriever(groupDE, "member", true)); // and go on to the first member of this new group.... needToRetry = true; } } } } while (needToRetry); return f; } private void TranslateForeignMembers() { GlobalDebug.WriteLineIf(GlobalDebug.Warn, "ADDNLinkedAttrSet", "TranslateForeignMembers: Translating foreign members"); List<byte[]> sidList = new List<byte[]>(_foreignMembersCurrentGroup.Count); // Foreach foreign principal retrive the sid. // If the SID is for a fake object we have to track it separately. If we were attempt to translate it // it would fail and not be returned and we would lose it. // Once we have a list of sids then translate them against the target store in one call. foreach (DirectoryEntry de in _foreignMembersCurrentGroup) { // Get the SID of the foreign principal if (de.Properties["objectSid"].Count == 0) { throw new PrincipalOperationException(SR.ADStoreCtxCantRetrieveObjectSidForCrossStore); } byte[] sid = (byte[])de.Properties["objectSid"].Value; // What type of SID is it? SidType sidType = Utils.ClassifySID(sid); if (sidType == SidType.FakeObject) { //Add the foreign member DirectoryEntry to fakePrincipalMembers list for further translation //This de will be disposed after completing the translation by another code block. _fakePrincipalMembers.Add(de); // It's a FPO for something like NT AUTHORITY\NETWORK SERVICE. // There's no real store object corresponding to this FPO, so // fake a Principal. GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "TranslateForeignMembers: fake principal, SID={0}", Utils.ByteArrayToString(sid)); } else { GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "TranslateForeignMembers: standard principal, SID={0}", Utils.ByteArrayToString(sid)); sidList.Add(sid); //We do NOT need the Foreign member DirectoryEntry object once it has been translated and added to sidList. //So disposing it off now de.Dispose(); } } // This call will perform a bulk sid translate to the name + issuer domain. _foreignMembersToReturn = new SidList(sidList, _storeCtx.DnsHostName, _storeCtx.Credentials); // We have translated the sids so clear the group now. _foreignMembersCurrentGroup.Clear(); } private bool MoveNextForeign(ref bool outerNeedToRetry) { outerNeedToRetry = false; bool needToRetry; Principal foreignPrincipal; GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "Entering MoveNextForeign"); do { needToRetry = false; if (_foreignMembersCurrentGroup.Count > 0) { TranslateForeignMembers(); } if (_fakePrincipalMembers.Count > 0) { foreignPrincipal = _storeCtx.ConstructFakePrincipalFromSID((byte[])_fakePrincipalMembers[0].Properties["objectSid"].Value); _fakePrincipalMembers[0].Dispose(); _fakePrincipalMembers.RemoveAt(0); } else if ((_foreignMembersToReturn != null) && (_foreignMembersToReturn.Length > 0)) { StoreCtx foreignStoreCtx; SidListEntry foreignSid = _foreignMembersToReturn[0]; // sidIssuerName is null only if SID was not resolved // return a unknown principal back if (null == foreignSid.sidIssuerName) { // create and return the unknown principal if it is not yet present in usersVisited if (!_usersVisited.ContainsKey(foreignSid.name)) { byte[] sid = Utils.ConvertNativeSidToByteArray(foreignSid.pSid); UnknownPrincipal unknownPrincipal = UnknownPrincipal.CreateUnknownPrincipal(_storeCtx.OwningContext, sid, foreignSid.name); _usersVisited.Add(foreignSid.name, true); this.current = null; _currentForeignDE = null; _currentForeignPrincipal = unknownPrincipal; // remove the current member _foreignMembersToReturn.RemoveAt(0); return true; } // remove the current member _foreignMembersToReturn.RemoveAt(0); needToRetry = true; continue; } SidType sidType = Utils.ClassifySID(foreignSid.pSid); if (sidType == SidType.RealObjectFakeDomain) { // This is a BUILTIN object. It's a real object on the store we're connected to, but LookupSid // will tell us it's a member of the BUILTIN domain. Resolve it as a principal on our store. GlobalDebug.WriteLineIf(GlobalDebug.Warn, "ADDNLinkedAttrSet", "MoveNextForeign: builtin principal"); foreignStoreCtx = _storeCtx; } else { ContextOptions remoteOptions = DefaultContextOptions.ADDefaultContextOption; #if USE_CTX_CACHE PrincipalContext remoteCtx = SDSCache.Domain.GetContext(foreignSid.sidIssuerName, _storeCtx.Credentials, remoteOptions); #else PrincipalContext remoteCtx = new PrincipalContext( ContextType.Domain, foreignSid.sidIssuerName, null, (this.storeCtx.Credentials != null ? this.storeCtx.Credentials.UserName : null), (this.storeCtx.Credentials != null ? storeCtx.storeCtx.Credentials.Password : null), remoteOptions); #endif foreignStoreCtx = remoteCtx.QueryCtx; } foreignPrincipal = foreignStoreCtx.FindPrincipalByIdentRef( typeof(Principal), UrnScheme.SidScheme, (new SecurityIdentifier(Utils.ConvertNativeSidToByteArray(_foreignMembersToReturn[0].pSid), 0)).ToString(), DateTime.UtcNow); if (null == foreignPrincipal) { GlobalDebug.WriteLineIf(GlobalDebug.Warn, "ADDNLinkedAttrSet", "MoveNextForeign: no matching principal"); throw new PrincipalOperationException(SR.ADStoreCtxFailedFindCrossStoreTarget); } _foreignMembersToReturn.RemoveAt(0); } else { // We don't have any more foreign principals to return so start with the foreign groups if (_foreignGroups.Count > 0) { outerNeedToRetry = true; // Determine the domainFunctionalityMode of the foreign domain. If they are W2k or not a global group then we can't use ASQ. if (_foreignGroups[0].Context.ServerInformation.OsVersion == DomainControllerMode.Win2k || _foreignGroups[0].GroupScope != GroupScope.Global) { _expansionMode = ExpansionMode.Enum; return ExpandForeignGroupEnumerator(); } else { _expansionMode = ExpansionMode.ASQ; return ExpandForeignGroupSearcher(); } } else { // We are done with foreign principals and groups.. return false; } } if (foreignPrincipal is GroupPrincipal) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "MoveNextForeign: foreign member is a group"); // A group, need to recursively expand it (unless it's a fake group, // in which case it is by definition empty and so contains nothing to expand, or unless // we've already or will visit it). // Postpone to later. if (!foreignPrincipal.fakePrincipal) { string groupDN = (string)((DirectoryEntry)foreignPrincipal.UnderlyingObject).Properties["distinguishedName"].Value; GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "MoveNextForeign: not a fake group, adding {0} to foreignGroups", groupDN); if (!_groupsVisited.Contains(groupDN) && !_groupsToVisit.Contains(groupDN)) { _foreignGroups.Add((GroupPrincipal)foreignPrincipal); } else { foreignPrincipal.Dispose(); } } needToRetry = true; continue; } else { // Not a group, nothing to recursively expand, so just return it. GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "MoveNextForeign: using as currentForeignDE/currentForeignPrincipal"); DirectoryEntry foreignDE = (DirectoryEntry)foreignPrincipal.GetUnderlyingObject(); _storeCtx.LoadDirectoryEntryAttributes(foreignDE); if (!_usersVisited.ContainsKey(foreignDE.Properties["distinguishedName"][0].ToString())) { _usersVisited.Add(foreignDE.Properties["distinguishedName"][0].ToString(), true); this.current = null; _currentForeignDE = null; _currentForeignPrincipal = foreignPrincipal; return true; } else { foreignPrincipal.Dispose(); } needToRetry = true; continue; } } while (needToRetry); return false; } private bool ExpandForeignGroupEnumerator() { Debug.Assert(_recursive == true); GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "ExpandForeignGroupEnumerator: there are {0} foreignGroups", _foreignGroups.Count); GroupPrincipal foreignGroup = _foreignGroups[0]; _foreignGroups.RemoveAt(0); // Since members of AD groups must be AD objects Debug.Assert(foreignGroup.Context.QueryCtx is ADStoreCtx); Debug.Assert(foreignGroup.UnderlyingObject is DirectoryEntry); Debug.Assert(((DirectoryEntry)foreignGroup.UnderlyingObject).Path.StartsWith("LDAP:", StringComparison.Ordinal)); _storeCtx = (ADStoreCtx)foreignGroup.Context.QueryCtx; //Here the foreignGroup object is removed from the foreignGroups collection. //and not used anymore. Hence, configure RangeRetriever to dispose the DirEntry on its dispose. _membersQueue.Enqueue(new RangeRetriever((DirectoryEntry)foreignGroup.UnderlyingObject, "member", true)); string groupDN = (string)((DirectoryEntry)foreignGroup.UnderlyingObject).Properties["distinguishedName"].Value; _groupsVisited.Add(groupDN); GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "ExpandForeignGroupEnumerator: recursively processing {0}", groupDN); return true; } private bool ExpandForeignGroupSearcher() { Debug.Assert(_recursive == true); GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "ExpandForeignGroupSearcher: there are {0} foreignGroups", _foreignGroups.Count); GroupPrincipal foreignGroup = _foreignGroups[0]; _foreignGroups.RemoveAt(0); // Since members of AD groups must be AD objects Debug.Assert(foreignGroup.Context.QueryCtx is ADStoreCtx); Debug.Assert(foreignGroup.UnderlyingObject is DirectoryEntry); Debug.Assert(((DirectoryEntry)foreignGroup.UnderlyingObject).Path.StartsWith("LDAP:", StringComparison.Ordinal)); _storeCtx = (ADStoreCtx)foreignGroup.Context.QueryCtx; // Queue up a searcher for the new group expansion. DirectorySearcher ds = SDSUtils.ConstructSearcher((DirectoryEntry)foreignGroup.UnderlyingObject); ds.Filter = "(objectClass=*)"; ds.SearchScope = SearchScope.Base; ds.AttributeScopeQuery = "member"; ds.CacheResults = false; _memberSearchersQueue.Enqueue(ds); string groupDN = (string)((DirectoryEntry)foreignGroup.UnderlyingObject).Properties["distinguishedName"].Value; _groupsVisited.Add(groupDN); GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "ExpandForeignGroupSearcher: recursively processing {0}", groupDN); return true; } private bool MoveNextQueryPrimaryGroupMember() { bool f = false; if (_primaryGroupMembersSearcher != null) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "MoveNextQueryMember: have a searcher"); if (_queryMembersResults == null) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "MoveNextQueryMember: issuing query"); _queryMembersResults = _primaryGroupMembersSearcher.FindAll(); Debug.Assert(_queryMembersResults != null); _queryMembersResultEnumerator = _queryMembersResults.GetEnumerator(); } f = _queryMembersResultEnumerator.MoveNext(); if (f) { this.current = (SearchResult)_queryMembersResultEnumerator.Current; Debug.Assert(this.current != null); _currentForeignDE = null; _currentForeignPrincipal = null; GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "MoveNextQueryMember: got a result, using as current {0}", ((SearchResult)this.current).Path); } } return f; } // Resets the enumerator to before the first result in the set. This potentially can be an expensive // operation, e.g., if doing a paged search, may need to re-retrieve the first page of results. // As a special case, if the ResultSet is already at the very beginning, this is guaranteed to be // a no-op. override internal void Reset() { GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "Reset"); if (!_atBeginning) { _usersVisited.Clear(); _groupsToVisit.Clear(); string originalGroupDN = _groupsVisited[0]; _groupsVisited.Clear(); _groupsVisited.Add(originalGroupDN); // clear the current enumerator _members = null; _membersEnum = null; // replace all items in the queue with the originals and reset them. if (null != _originalMembers) { _membersQueue.Clear(); foreach (IEnumerable ie in _originalMembers) { _membersQueue.Enqueue(ie); IEnumerator enumerator = ie.GetEnumerator(); enumerator.Reset(); } } _expansionMode = _originalExpansionMode; _storeCtx = _originalStoreCtx; this.current = null; if (_primaryGroupDN != null) _returnedPrimaryGroup = false; _foreignMembersCurrentGroup.Clear(); _fakePrincipalMembers.Clear(); if (null != _foreignMembersToReturn) _foreignMembersToReturn.Clear(); _currentForeignPrincipal = null; _currentForeignDE = null; _foreignGroups.Clear(); _queryMembersResultEnumerator = null; if (_queryMembersResults != null) { _queryMembersResults.Dispose(); _queryMembersResults = null; } if (null != _currentMembersSearcher) { _currentMembersSearcher.Dispose(); _currentMembersSearcher = null; } _memberSearchResultsEnumerator = null; if (_memberSearchResults != null) { _memberSearchResults.Dispose(); _memberSearchResults = null; } if (null != _memberSearchersQueue) { foreach (DirectorySearcher ds in _memberSearchersQueue) { ds.Dispose(); } _memberSearchersQueue.Clear(); if (null != _memberSearchersQueueOriginal) { foreach (DirectorySearcher ds in _memberSearchersQueueOriginal) { _memberSearchersQueue.Enqueue(ds); } } } _atBeginning = true; } } override internal ResultSetBookmark BookmarkAndReset() { GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "Bookmarking"); ADDNLinkedAttrSetBookmark bookmark = new ADDNLinkedAttrSetBookmark(); bookmark.usersVisited = _usersVisited; _usersVisited = new Dictionary<string, bool>(); bookmark.groupsToVisit = _groupsToVisit; _groupsToVisit = new List<string>(); string originalGroupDN = _groupsVisited[0]; bookmark.groupsVisited = _groupsVisited; _groupsVisited = new List<string>(); _groupsVisited.Add(originalGroupDN); bookmark.expansionMode = _expansionMode; // bookmark the current enumerators bookmark.members = _members; bookmark.membersEnum = _membersEnum; // Clear the current enumerators for reset _members = null; _membersEnum = null; // Copy all enumerators in the queue over to the bookmark queue. if (null != _membersQueue) { bookmark.membersQueue = new Queue<IEnumerable>(_membersQueue.Count); foreach (IEnumerable ie in _membersQueue) { bookmark.membersQueue.Enqueue(ie); } } // Refill the original queue with the original enumerators and reset them if (null != _membersQueue) { _membersQueue.Clear(); if (_originalMembers != null) { foreach (IEnumerable ie in _originalMembers) { _membersQueue.Enqueue(ie); IEnumerator enumerator = ie.GetEnumerator(); enumerator.Reset(); } } } bookmark.storeCtx = _storeCtx; _expansionMode = _originalExpansionMode; if (null != _currentMembersSearcher) { _currentMembersSearcher.Dispose(); _currentMembersSearcher = null; } _storeCtx = _originalStoreCtx; bookmark.current = this.current; bookmark.returnedPrimaryGroup = _returnedPrimaryGroup; this.current = null; if (_primaryGroupDN != null) _returnedPrimaryGroup = false; bookmark.foreignMembersCurrentGroup = _foreignMembersCurrentGroup; bookmark.fakePrincipalMembers = _fakePrincipalMembers; bookmark.foreignMembersToReturn = _foreignMembersToReturn; bookmark.currentForeignPrincipal = _currentForeignPrincipal; bookmark.currentForeignDE = _currentForeignDE; _foreignMembersCurrentGroup = new List<DirectoryEntry>(); _fakePrincipalMembers = new List<DirectoryEntry>(); _currentForeignDE = null; bookmark.foreignGroups = _foreignGroups; _foreignGroups = new List<GroupPrincipal>(); bookmark.queryMembersResults = _queryMembersResults; bookmark.queryMembersResultEnumerator = _queryMembersResultEnumerator; _queryMembersResults = null; _queryMembersResultEnumerator = null; bookmark.memberSearchResults = _memberSearchResults; bookmark.memberSearchResultsEnumerator = _memberSearchResultsEnumerator; _memberSearchResults = null; _memberSearchResultsEnumerator = null; if (null != _memberSearchersQueue) { bookmark.memberSearcherQueue = new Queue<DirectorySearcher>(_memberSearchersQueue.Count); foreach (DirectorySearcher ds in _memberSearchersQueue) { bookmark.memberSearcherQueue.Enqueue(ds); } } if (null != _memberSearchersQueueOriginal) { _memberSearchersQueue.Clear(); foreach (DirectorySearcher ds in _memberSearchersQueueOriginal) { _memberSearchersQueue.Enqueue(ds); } } bookmark.atBeginning = _atBeginning; _atBeginning = true; return bookmark; } override internal void RestoreBookmark(ResultSetBookmark bookmark) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "Restoring from bookmark"); Debug.Assert(bookmark is ADDNLinkedAttrSetBookmark); ADDNLinkedAttrSetBookmark adBookmark = (ADDNLinkedAttrSetBookmark)bookmark; _usersVisited = adBookmark.usersVisited; _groupsToVisit = adBookmark.groupsToVisit; _groupsVisited = adBookmark.groupsVisited; _storeCtx = adBookmark.storeCtx; this.current = adBookmark.current; _returnedPrimaryGroup = adBookmark.returnedPrimaryGroup; _foreignMembersCurrentGroup = adBookmark.foreignMembersCurrentGroup; _fakePrincipalMembers = adBookmark.fakePrincipalMembers; _foreignMembersToReturn = adBookmark.foreignMembersToReturn; _currentForeignPrincipal = adBookmark.currentForeignPrincipal; _currentForeignDE = adBookmark.currentForeignDE; _foreignGroups = adBookmark.foreignGroups; if (_queryMembersResults != null) _queryMembersResults.Dispose(); _queryMembersResults = adBookmark.queryMembersResults; _queryMembersResultEnumerator = adBookmark.queryMembersResultEnumerator; _memberSearchResults = adBookmark.memberSearchResults; _memberSearchResultsEnumerator = adBookmark.memberSearchResultsEnumerator; _atBeginning = adBookmark.atBeginning; _expansionMode = adBookmark.expansionMode; // Replace enumerators _members = adBookmark.members; _membersEnum = adBookmark.membersEnum; // Replace the enumerator queue elements if (null != _membersQueue) { _membersQueue.Clear(); if (null != adBookmark.membersQueue) { foreach (IEnumerable ie in adBookmark.membersQueue) { _membersQueue.Enqueue(ie); } } } if (null != _memberSearchersQueue) { foreach (DirectorySearcher ds in _memberSearchersQueue) { ds.Dispose(); } _memberSearchersQueue.Clear(); if (null != adBookmark.memberSearcherQueue) { foreach (DirectorySearcher ds in adBookmark.memberSearcherQueue) { _memberSearchersQueue.Enqueue(ds); } } } } // IDisposable implementation public override void Dispose() { try { if (!_disposed) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "Dispose: disposing"); if (_primaryGroupMembersSearcher != null) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "Dispose: disposing primaryGroupMembersSearcher"); _primaryGroupMembersSearcher.Dispose(); } if (_queryMembersResults != null) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "Dispose: disposing queryMembersResults"); _queryMembersResults.Dispose(); } if (_currentMembersSearcher != null) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "Dispose: disposing membersSearcher"); _currentMembersSearcher.Dispose(); } if (_memberSearchResults != null) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "Dispose: disposing memberSearchResults"); _memberSearchResults.Dispose(); } if (_memberSearchersQueue != null) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "Dispose: disposing memberSearchersQueue"); foreach (DirectorySearcher ds in _memberSearchersQueue) { ds.Dispose(); } _memberSearchersQueue.Clear(); } IDisposable disposableMembers = _members as IDisposable; if (disposableMembers != null) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "Dispose: disposing members Enumerable"); disposableMembers.Dispose(); } IDisposable disposableMembersEnum = _membersEnum as IDisposable; if (disposableMembersEnum != null) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "Dispose: disposing membersEnum Enumerator"); disposableMembersEnum.Dispose(); } if (_membersQueue != null) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "ADDNLinkedAttrSet", "Dispose: disposing membersQueue"); foreach (IEnumerable enumerable in _membersQueue) { IDisposable disposableEnum = enumerable as IDisposable; if (disposableEnum != null) { disposableEnum.Dispose(); } } } if (_foreignGroups != null) { foreach (GroupPrincipal gp in _foreignGroups) { gp.Dispose(); } } _disposed = true; } } finally { base.Dispose(); } } // // // private UnsafeNativeMethods.IADsPathname _pathCracker = null; private object _pathLock = new object(); private Dictionary<string, bool> _usersVisited = new Dictionary<string, bool>(); // The 0th entry in this list is always the DN of the original group/user whose membership we're querying private List<string> _groupsVisited = new List<string>(); private List<string> _groupsToVisit = new List<string>(); protected object current = null; // current member of the group (or current group of the user) private bool _returnedPrimaryGroup = false; private string _primaryGroupDN; // the DN of the user's PrimaryGroup (not included in this.members/originalMembers) private bool _recursive; private Queue<IEnumerable> _membersQueue = new Queue<IEnumerable>(); private IEnumerable _members; // the membership we're currently enumerating over private Queue<IEnumerable> _originalMembers = new Queue<IEnumerable>(); // the membership we started off with (before recursing) private IEnumerator _membersEnum = null; private ADStoreCtx _storeCtx; private ADStoreCtx _originalStoreCtx; private bool _atBeginning = true; private bool _disposed = false; // foreign // This contains a list of employees built while enumerating the current group. These are FSP objects in the current domain and need to // be translated to find out the domain that holds the actual object. private List<DirectoryEntry> _foreignMembersCurrentGroup = new List<DirectoryEntry>(); // List of objects from the group tha are actual fake group objects. private List<DirectoryEntry> _fakePrincipalMembers = new List<DirectoryEntry>(); // list of SIDs + store that have been translated. These could be any principal object private SidList _foreignMembersToReturn = null; private Principal _currentForeignPrincipal = null; private DirectoryEntry _currentForeignDE = null; private List<GroupPrincipal> _foreignGroups = new List<GroupPrincipal>(); // members based on a query (used for users who are group members by virtue of their primaryGroupId pointing to the group) private DirectorySearcher _primaryGroupMembersSearcher; private SearchResultCollection _queryMembersResults = null; private IEnumerator _queryMembersResultEnumerator = null; private DirectorySearcher _currentMembersSearcher = null; private Queue<DirectorySearcher> _memberSearchersQueue = new Queue<DirectorySearcher>(); private Queue<DirectorySearcher> _memberSearchersQueueOriginal = new Queue<DirectorySearcher>(); private SearchResultCollection _memberSearchResults = null; private IEnumerator _memberSearchResultsEnumerator = null; private ExpansionMode _expansionMode; private ExpansionMode _originalExpansionMode; private string BuildPathFromDN(string dn) { string userSuppliedServername = _storeCtx.UserSuppliedServerName; if (null == _pathCracker) { lock (_pathLock) { if (null == _pathCracker) { UnsafeNativeMethods.Pathname pathNameObj = new UnsafeNativeMethods.Pathname(); _pathCracker = (UnsafeNativeMethods.IADsPathname)pathNameObj; _pathCracker.EscapedMode = 2 /* ADS_ESCAPEDMODE_ON */; } } } _pathCracker.Set(dn, 4 /* ADS_SETTYPE_DN */); string escapedDn = _pathCracker.Retrieve(7 /* ADS_FORMAT_X500_DN */); if (userSuppliedServername.Length > 0) return "LDAP://" + _storeCtx.UserSuppliedServerName + "/" + escapedDn; else return "LDAP://" + escapedDn; } } internal enum ExpansionMode { Enum = 0, ASQ = 1, } internal class ADDNLinkedAttrSetBookmark : ResultSetBookmark { public Dictionary<string, bool> usersVisited; public List<string> groupsToVisit; public List<string> groupsVisited; public IEnumerable members; public IEnumerator membersEnum = null; public Queue<IEnumerable> membersQueue; public ADStoreCtx storeCtx; public object current; public bool returnedPrimaryGroup; public List<DirectoryEntry> foreignMembersCurrentGroup; public List<DirectoryEntry> fakePrincipalMembers; public SidList foreignMembersToReturn; public Principal currentForeignPrincipal; public DirectoryEntry currentForeignDE; public List<GroupPrincipal> foreignGroups; public SearchResultCollection queryMembersResults; public IEnumerator queryMembersResultEnumerator; public SearchResultCollection memberSearchResults; public IEnumerator memberSearchResultsEnumerator; public bool atBeginning; public ExpansionMode expansionMode; public Queue<DirectorySearcher> memberSearcherQueue; } } // #endif
// // Mono.WebServer.MonoWorkerRequest // // Authors: // Daniel Lopez Ridruejo // Gonzalo Paniagua Javier // // Documentation: // Brian Nickel // // Copyright (c) 2002 Daniel Lopez Ridruejo. // (c) 2002,2003 Ximian, Inc. // All rights reserved. // (C) Copyright 2004-2010 Novell, Inc. (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Collections.Specialized; using System.Configuration; using System.IO; using System.Linq; using System.Security.Cryptography.X509Certificates; using System.Text; using System.Web; using System.Web.Hosting; using Mono.WebServer.Log; namespace Mono.WebServer { public abstract class MonoWorkerRequest : SimpleWorkerRequest { const string DEFAULT_EXCEPTION_HTML = "<html><head><title>Runtime Error</title></head><body>An exception ocurred:<pre>{0}</pre></body></html>"; static readonly char[] mapPathTrimStartChars = { '/' }; static bool checkFileAccess = true; readonly static bool needToReplacePathSeparator; readonly static char pathSeparatorChar; readonly IApplicationHost appHostBase; Encoding encoding; Encoding headerEncoding; byte [] queryStringBytes; string hostVPath; string hostPath; string hostPhysicalRoot; EndOfSendNotification end_send; object end_send_data; X509Certificate client_cert; NameValueCollection server_variables; bool inUnhandledException; // as we must have the client certificate (if provided) then we're able to avoid // pre-calculating some items (and cache them if we have to calculate) string cert_cookie; string cert_issuer; string cert_serial; string cert_subject; protected byte[] server_raw; protected byte[] client_raw; public event MapPathEventHandler MapPathEvent; public event EndOfRequestHandler EndOfRequestEvent; public abstract int RequestId { get; } protected static bool RunningOnWindows { get; private set; } public static bool CheckFileAccess { get { return checkFileAccess; } set { checkFileAccess = value; } } // Gets the physical path of the application host of the // current instance. string HostPath { get { if (hostPath == null) hostPath = appHostBase.Path; return hostPath; } } // Gets the virtual path of the application host of the // current instance. string HostVPath { get { if (hostVPath == null) hostVPath = appHostBase.VPath; return hostVPath; } } string HostPhysicalRoot { get { if (hostPhysicalRoot == null) hostPhysicalRoot = appHostBase.Server.PhysicalRoot; return hostPhysicalRoot; } } protected virtual Encoding Encoding { get { if (encoding == null) encoding = Encoding.GetEncoding (28591); return encoding; } set { encoding = value; } } protected virtual Encoding HeaderEncoding { get { if (headerEncoding == null) { HttpContext ctx = HttpContext.Current; HttpResponse response = ctx != null ? ctx.Response : null; Encoding enc = inUnhandledException ? null : response != null ? response.HeaderEncoding : null; headerEncoding = enc ?? Encoding; } return headerEncoding; } } static MonoWorkerRequest () { PlatformID pid = Environment.OSVersion.Platform; RunningOnWindows = ((int) pid != 128 && pid != PlatformID.Unix && pid != PlatformID.MacOSX); if (Path.DirectorySeparatorChar != '/') { needToReplacePathSeparator = true; pathSeparatorChar = Path.DirectorySeparatorChar; } try { string v = ConfigurationManager.AppSettings ["MonoServerCheckHiddenFiles"]; if (!String.IsNullOrEmpty (v)) { if (!Boolean.TryParse (v, out checkFileAccess)) checkFileAccess = true; } } catch (Exception) { // ignore checkFileAccess = true; } } protected MonoWorkerRequest (IApplicationHost appHost) : base (String.Empty, String.Empty, null) { if (appHost == null) throw new ArgumentNullException ("appHost"); appHostBase = appHost; } public override string GetAppPath () { return HostVPath; } public override string GetAppPathTranslated () { return HostPath; } public override string GetFilePathTranslated () { return MapPath (GetFilePath ()); } public override string GetLocalAddress () { return "localhost"; } public override string GetServerName () { string hostHeader = GetKnownRequestHeader(HeaderHost); if (String.IsNullOrEmpty (hostHeader)) { hostHeader = GetLocalAddress (); } else { int colonIndex = hostHeader.IndexOf (':'); if (colonIndex > 0) { hostHeader = hostHeader.Substring (0, colonIndex); } else if (colonIndex == 0) { hostHeader = GetLocalAddress (); } } return hostHeader; } public override int GetLocalPort () { return 0; } public override byte [] GetPreloadedEntityBody () { return null; } public override byte [] GetQueryStringRawBytes () { if (queryStringBytes == null) { string queryString = GetQueryString (); if (queryString != null) queryStringBytes = Encoding.GetBytes (queryString); } return queryStringBytes; } // Invokes the registered delegates one by one until the path is mapped. // // Parameters: // path = virutal path of the request. // // Returns a string containing the mapped physical path of the request, or null if // the path was not successfully mapped. // string DoMapPathEvent (string path) { if (MapPathEvent != null) { var args = new MapPathEventArgs (path); foreach (MapPathEventHandler evt in MapPathEvent.GetInvocationList ()) { evt (this, args); if (args.IsMapped) return args.MappedPath; } } return null; } // The logic here is as follows: // // If path is equal to the host's virtual path (including trailing slash), // return the host virtual path. // // If path is absolute (starts with '/') then check if it's under our host vpath. If // it is, base the mapping under the virtual application's physical path. If it // isn't use the physical root of the application server to return the mapped // path. If you have just one application configured, then the values computed in // both of the above cases will be the same. If you have several applications // configured for this xsp/mod-mono-server instance, then virtual paths outside our // application virtual path will return physical paths relative to the server's // physical root, not application's. This is consistent with the way IIS worker // request works. See bug #575600 // public override string MapPath (string path) { string eventResult = DoMapPathEvent (path); if (eventResult != null) return eventResult; string hostVPath = HostVPath; int hostVPathLen = HostVPath.Length; int pathLen = path != null ? path.Length : 0; #if NET_2_0 bool inThisApp = path.StartsWith (hostVPath, StringComparison.Ordinal); #else bool inThisApp = path.StartsWith (hostVPath); #endif if (pathLen == 0 || (inThisApp && (pathLen == hostVPathLen || (pathLen == hostVPathLen + 1 && path [pathLen - 1] == '/')))) { if (needToReplacePathSeparator) return HostPath.Replace ('/', pathSeparatorChar); return HostPath; } string basePath = null; switch (path [0]) { case '~': if (path.Length >= 2 && path [1] == '/') path = path.Substring (1); break; case '/': if (!inThisApp) basePath = HostPhysicalRoot; break; } if (basePath == null) basePath = HostPath; if (inThisApp && (path.Length == hostVPathLen || path [hostVPathLen] == '/')) path = path.Substring (hostVPathLen + 1); path = path.TrimStart (mapPathTrimStartChars); if (needToReplacePathSeparator) path = path.Replace ('/', pathSeparatorChar); return Path.Combine (basePath, path); } protected abstract bool GetRequestData (); public bool ReadRequestData () { return GetRequestData (); } static void LocationAccessible (string localPath) { bool doThrow = false; if (RunningOnWindows) { try { var fi = new FileInfo (localPath); FileAttributes attr = fi.Attributes; if ((attr & FileAttributes.Hidden) != 0 || (attr & FileAttributes.System) != 0) doThrow = true; } catch (Exception) { // ignore, will be handled in system.web return; } } else { // throw only if the file exists, let system.web handle the request // otherwise if (File.Exists (localPath) || Directory.Exists (localPath)) if (Path.GetFileName (localPath) [0] == '.') doThrow = true; } if (doThrow) throw new HttpException (403, "Forbidden."); } void AssertFileAccessible () { if (!checkFileAccess) return; string localPath = GetFilePathTranslated (); if (String.IsNullOrEmpty (localPath)) return; char dirsep = Path.DirectorySeparatorChar; string appPath = GetAppPathTranslated (); string[] segments = localPath.Substring (appPath.Length).Split (dirsep); var sb = new StringBuilder (appPath); foreach (string s in segments) { if (s.Length == 0) continue; if (s [0] != '.') { sb.Append (s); sb.Append (dirsep); continue; } sb.Append (s); LocationAccessible (sb.ToString ()); } } public void ProcessRequest () { string error = null; inUnhandledException = false; try { AssertFileAccessible (); HttpRuntime.ProcessRequest (this); } catch (HttpException ex) { inUnhandledException = true; error = ex.GetHtmlErrorMessage (); } catch (Exception ex) { inUnhandledException = true; var hex = new HttpException (400, "Bad request", ex); error = hex.GetHtmlErrorMessage (); } if (!inUnhandledException) return; if (error.Length == 0) error = String.Format (DEFAULT_EXCEPTION_HTML, "Unknown error"); try { SendStatus (400, "Bad request"); SendUnknownResponseHeader ("Connection", "close"); SendUnknownResponseHeader ("Date", DateTime.Now.ToUniversalTime ().ToString ("r")); Encoding enc = Encoding.UTF8; byte[] bytes = enc.GetBytes (error); SendUnknownResponseHeader ("Content-Type", "text/html; charset=" + enc.WebName); SendUnknownResponseHeader ("Content-Length", bytes.Length.ToString ()); SendResponseFromMemory (bytes, bytes.Length); FlushResponse (true); } catch (Exception ex) { // should "never" happen Logger.Write (LogLevel.Error, "Error while processing a request: "); Logger.Write (ex); throw; } } public override void EndOfRequest () { if (EndOfRequestEvent != null) EndOfRequestEvent (this); if (end_send != null) end_send (this, end_send_data); } public override void SetEndOfSendNotification (EndOfSendNotification callback, object extraData) { end_send = callback; end_send_data = extraData; } public override void SendCalculatedContentLength (int contentLength) { //FIXME: Should we ignore this for apache2? SendUnknownResponseHeader ("Content-Length", contentLength.ToString ()); } public override void SendKnownResponseHeader (int index, string value) { if (HeadersSent ()) return; string headerName = GetKnownResponseHeaderName (index); SendUnknownResponseHeader (headerName, value); } protected void SendFromStream (Stream stream, long offset, long length) { if (offset < 0 || length <= 0) return; long stLength = stream.Length; if (offset + length > stLength) length = stLength - offset; if (offset > 0) stream.Seek (offset, SeekOrigin.Begin); var fileContent = new byte [8192]; int count = fileContent.Length; while (length > 0 && (count = stream.Read (fileContent, 0, count)) != 0) { SendResponseFromMemory (fileContent, count); length -= count; // Keep the System. prefix count = (int) System.Math.Min (length, fileContent.Length); } } public override void SendResponseFromFile (string filename, long offset, long length) { FileStream file = null; try { file = File.OpenRead (filename); SendFromStream (file, offset, length); } finally { if (file != null) file.Close (); } } public override void SendResponseFromFile (IntPtr handle, long offset, long length) { Stream file = null; try { file = new FileStream (handle, FileAccess.Read); SendFromStream (file, offset, length); } finally { if (file != null) file.Close (); } } public override string GetServerVariable (string name) { if (server_variables == null) return String.Empty; if (IsSecure ()) { X509Certificate client = ClientCertificate; switch (name) { case "CERT_COOKIE": if (cert_cookie == null) { if (client == null) cert_cookie = String.Empty; else cert_cookie = client.GetCertHashString (); } return cert_cookie; case "CERT_ISSUER": if (cert_issuer == null) { if (client == null) cert_issuer = String.Empty; else cert_issuer = client.Issuer; } return cert_issuer; case "CERT_SERIALNUMBER": if (cert_serial == null) { if (client == null) cert_serial = String.Empty; else cert_serial = client.GetSerialNumberString (); } return cert_serial; case "CERT_SUBJECT": if (cert_subject == null) { if (client == null) cert_subject = String.Empty; else cert_subject = client.Subject; } return cert_subject; } } string s = server_variables [name]; return s ?? String.Empty; } public void AddServerVariable (string name, string value) { if (server_variables == null) server_variables = new NameValueCollection (); server_variables.Add (name, value); } #region Client Certificate Support public X509Certificate ClientCertificate { get { if ((client_cert == null) && (client_raw != null)) client_cert = new X509Certificate (client_raw); return client_cert; } } public void SetClientCertificate (byte[] rawcert) { client_raw = rawcert; } public override byte[] GetClientCertificate () { return client_raw; } public override byte[] GetClientCertificateBinaryIssuer () { if (ClientCertificate == null) return base.GetClientCertificateBinaryIssuer (); // TODO: not 100% sure of the content return new byte [0]; } public override int GetClientCertificateEncoding () { if (ClientCertificate == null) return base.GetClientCertificateEncoding (); return 0; } public override byte[] GetClientCertificatePublicKey () { if (ClientCertificate == null) return base.GetClientCertificatePublicKey (); return ClientCertificate.GetPublicKey (); } public override DateTime GetClientCertificateValidFrom () { if (ClientCertificate == null) return base.GetClientCertificateValidFrom (); return DateTime.Parse (ClientCertificate.GetEffectiveDateString ()); } public override DateTime GetClientCertificateValidUntil () { if (ClientCertificate == null) return base.GetClientCertificateValidUntil (); return DateTime.Parse (ClientCertificate.GetExpirationDateString ()); } #endregion protected static string[] SplitAndTrim (string list) { if (String.IsNullOrEmpty (list)) return new string[0]; return (from f in list.Split (',') let trimmed = f.Trim () where trimmed.Length != 0 select trimmed).ToArray (); } } }
using System; using System.Linq; using System.Reflection; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Hosting; using OrchardCore.Environment.Extensions; using OrchardCore.Environment.Extensions.Features; using OrchardCore.Environment.Shell.Builders.Models; using OrchardCore.Modules; namespace OrchardCore.Environment.Shell.Builders { public class ShellContainerFactory : IShellContainerFactory { private IFeatureInfo _applicationFeature; private readonly IHostEnvironment _hostingEnvironment; private readonly IExtensionManager _extensionManager; private readonly IServiceProvider _serviceProvider; private readonly IServiceCollection _applicationServices; public ShellContainerFactory( IHostEnvironment hostingEnvironment, IExtensionManager extensionManager, IServiceProvider serviceProvider, IServiceCollection applicationServices) { _hostingEnvironment = hostingEnvironment; _extensionManager = extensionManager; _applicationServices = applicationServices; _serviceProvider = serviceProvider; } public IServiceProvider CreateContainer(ShellSettings settings, ShellBlueprint blueprint) { var tenantServiceCollection = _serviceProvider.CreateChildContainer(_applicationServices); tenantServiceCollection.AddSingleton(settings); tenantServiceCollection.AddSingleton(sp => { // Resolve it lazily as it's constructed lazily var shellSettings = sp.GetRequiredService<ShellSettings>(); return shellSettings.ShellConfiguration; }); tenantServiceCollection.AddSingleton(blueprint.Descriptor); tenantServiceCollection.AddSingleton(blueprint); // Execute IStartup registrations var moduleServiceCollection = _serviceProvider.CreateChildContainer(_applicationServices); foreach (var dependency in blueprint.Dependencies.Where(t => typeof(IStartup).IsAssignableFrom(t.Key))) { moduleServiceCollection.TryAddEnumerable(ServiceDescriptor.Singleton(typeof(IStartup), dependency.Key)); tenantServiceCollection.TryAddEnumerable(ServiceDescriptor.Singleton(typeof(IStartup), dependency.Key)); } // To not trigger features loading before it is normally done by 'ShellHost', // init here the application feature in place of doing it in the constructor. EnsureApplicationFeature(); foreach (var rawStartup in blueprint.Dependencies.Keys.Where(t => t.Name == "Startup")) { // Startup classes inheriting from IStartup are already treated if (typeof(IStartup).IsAssignableFrom(rawStartup)) { continue; } // Ignore Startup class from main application if (blueprint.Dependencies.TryGetValue(rawStartup, out var startupFeature) && startupFeature.FeatureInfo.Id == _applicationFeature.Id) { continue; } // Create a wrapper around this method var configureServicesMethod = rawStartup.GetMethod( nameof(IStartup.ConfigureServices), BindingFlags.Public | BindingFlags.Instance, null, CallingConventions.Any, new Type[] { typeof(IServiceCollection) }, null); var configureMethod = rawStartup.GetMethod( nameof(IStartup.Configure), BindingFlags.Public | BindingFlags.Instance); var orderProperty = rawStartup.GetProperty( nameof(IStartup.Order), BindingFlags.Public | BindingFlags.Instance); var configureOrderProperty = rawStartup.GetProperty( nameof(IStartup.ConfigureOrder), BindingFlags.Public | BindingFlags.Instance); // Add the startup class to the DI so we can instantiate it with // valid ctor arguments moduleServiceCollection.AddSingleton(rawStartup); tenantServiceCollection.AddSingleton(rawStartup); moduleServiceCollection.AddSingleton<IStartup>(sp => { var startupInstance = sp.GetService(rawStartup); return new StartupBaseMock(startupInstance, configureServicesMethod, configureMethod, orderProperty, configureOrderProperty); }); tenantServiceCollection.AddSingleton<IStartup>(sp => { var startupInstance = sp.GetService(rawStartup); return new StartupBaseMock(startupInstance, configureServicesMethod, configureMethod, orderProperty, configureOrderProperty); }); } // Make shell settings available to the modules moduleServiceCollection.AddSingleton(settings); moduleServiceCollection.AddSingleton(sp => { // Resolve it lazily as it's constructed lazily var shellSettings = sp.GetRequiredService<ShellSettings>(); return shellSettings.ShellConfiguration; }); var moduleServiceProvider = moduleServiceCollection.BuildServiceProvider(true); // Index all service descriptors by their feature id var featureAwareServiceCollection = new FeatureAwareServiceCollection(tenantServiceCollection); var startups = moduleServiceProvider.GetServices<IStartup>(); // IStartup instances are ordered by module dependency with an Order of 0 by default. // OrderBy performs a stable sort so order is preserved among equal Order values. startups = startups.OrderBy(s => s.Order); // Let any module add custom service descriptors to the tenant foreach (var startup in startups) { var feature = blueprint.Dependencies.FirstOrDefault(x => x.Key == startup.GetType()).Value?.FeatureInfo; // If the startup is not coming from an extension, associate it to the application feature. // For instance when Startup classes are registered with Configure<Startup>() from the application. featureAwareServiceCollection.SetCurrentFeature(feature ?? _applicationFeature); startup.ConfigureServices(featureAwareServiceCollection); } (moduleServiceProvider as IDisposable).Dispose(); var shellServiceProvider = tenantServiceCollection.BuildServiceProvider(true); // Register all DIed types in ITypeFeatureProvider var typeFeatureProvider = shellServiceProvider.GetRequiredService<ITypeFeatureProvider>(); foreach (var featureServiceCollection in featureAwareServiceCollection.FeatureCollections) { foreach (var serviceDescriptor in featureServiceCollection.Value) { var type = serviceDescriptor.GetImplementationType(); if (type != null) { var feature = featureServiceCollection.Key; if (feature == _applicationFeature) { var attribute = type.GetCustomAttributes<FeatureAttribute>(false).FirstOrDefault(); if (attribute != null) { feature = featureServiceCollection.Key.Extension.Features .FirstOrDefault(f => f.Id == attribute.FeatureName) ?? feature; } } typeFeatureProvider.TryAdd(type, feature); } } } return shellServiceProvider; } private void EnsureApplicationFeature() { if (_applicationFeature == null) { lock (this) { if (_applicationFeature == null) { _applicationFeature = _extensionManager.GetFeatures() .FirstOrDefault(f => f.Id == _hostingEnvironment.ApplicationName); } } } } } }
// 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 ShiftRightLogical128BitLaneUInt321() { var test = new ImmUnaryOpTest__ShiftRightLogical128BitLaneUInt321(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); // Validates passing an instance member of a class works test.RunClassFldScenario(); // Validates passing the field of a local struct works test.RunStructLclFldScenario(); // Validates passing an instance member of a struct works test.RunStructFldScenario(); } 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 ImmUnaryOpTest__ShiftRightLogical128BitLaneUInt321 { private struct TestStruct { public Vector128<UInt32> _fld; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (uint)8; } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref testStruct._fld), ref Unsafe.As<UInt32, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); return testStruct; } public void RunStructFldScenario(ImmUnaryOpTest__ShiftRightLogical128BitLaneUInt321 testClass) { var result = Sse2.ShiftRightLogical128BitLane(_fld, 1); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld, testClass._dataTable.outArrayPtr); } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<UInt32>>() / sizeof(UInt32); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<UInt32>>() / sizeof(UInt32); private static UInt32[] _data = new UInt32[Op1ElementCount]; private static Vector128<UInt32> _clsVar; private Vector128<UInt32> _fld; private SimpleUnaryOpTest__DataTable<UInt32, UInt32> _dataTable; static ImmUnaryOpTest__ShiftRightLogical128BitLaneUInt321() { for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (uint)8; } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _clsVar), ref Unsafe.As<UInt32, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); } public ImmUnaryOpTest__ShiftRightLogical128BitLaneUInt321() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (uint)8; } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _fld), ref Unsafe.As<UInt32, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (uint)8; } _dataTable = new SimpleUnaryOpTest__DataTable<UInt32, UInt32>(_data, new UInt32[RetElementCount], LargestVectorSize); } public bool IsSupported => Sse2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Sse2.ShiftRightLogical128BitLane( Unsafe.Read<Vector128<UInt32>>(_dataTable.inArrayPtr), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Sse2.ShiftRightLogical128BitLane( Sse2.LoadVector128((UInt32*)(_dataTable.inArrayPtr)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Sse2.ShiftRightLogical128BitLane( Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArrayPtr)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Sse2).GetMethod(nameof(Sse2.ShiftRightLogical128BitLane), new Type[] { typeof(Vector128<UInt32>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<UInt32>>(_dataTable.inArrayPtr), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt32>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Sse2).GetMethod(nameof(Sse2.ShiftRightLogical128BitLane), new Type[] { typeof(Vector128<UInt32>), typeof(byte) }) .Invoke(null, new object[] { Sse2.LoadVector128((UInt32*)(_dataTable.inArrayPtr)), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt32>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Sse2).GetMethod(nameof(Sse2.ShiftRightLogical128BitLane), new Type[] { typeof(Vector128<UInt32>), typeof(byte) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArrayPtr)), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt32>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Sse2.ShiftRightLogical128BitLane( _clsVar, 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var firstOp = Unsafe.Read<Vector128<UInt32>>(_dataTable.inArrayPtr); var result = Sse2.ShiftRightLogical128BitLane(firstOp, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var firstOp = Sse2.LoadVector128((UInt32*)(_dataTable.inArrayPtr)); var result = Sse2.ShiftRightLogical128BitLane(firstOp, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var firstOp = Sse2.LoadAlignedVector128((UInt32*)(_dataTable.inArrayPtr)); var result = Sse2.ShiftRightLogical128BitLane(firstOp, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new ImmUnaryOpTest__ShiftRightLogical128BitLaneUInt321(); var result = Sse2.ShiftRightLogical128BitLane(test._fld, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Sse2.ShiftRightLogical128BitLane(_fld, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld, _dataTable.outArrayPtr); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Sse2.ShiftRightLogical128BitLane(test._fld, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<UInt32> firstOp, void* result, [CallerMemberName] string method = "") { UInt32[] inArray = new UInt32[Op1ElementCount]; UInt32[] outArray = new UInt32[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray[0]), firstOp); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); ValidateResult(inArray, outArray, method); } private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "") { UInt32[] inArray = new UInt32[Op1ElementCount]; UInt32[] outArray = new UInt32[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); ValidateResult(inArray, outArray, method); } private void ValidateResult(UInt32[] firstOp, UInt32[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (result[0] != 134217728) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if ((i == 3 ? result[i] != 0 : result[i] != 134217728)) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Sse2)}.{nameof(Sse2.ShiftRightLogical128BitLane)}<UInt32>(Vector128<UInt32><9>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
/* **************************************************************************** * * Copyright (c) Microsoft Corporation. * * This source code is subject to terms and conditions of the Apache License, Version 2.0. A * copy of the license can be found in the License.html file at the root of this distribution. If * you cannot locate the Apache License, Version 2.0, please send an email to * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound * by the terms of the Apache License, Version 2.0. * * You must not remove this notice, or any other, from this software. * * * ***************************************************************************/ #if !CLR2 #else using Microsoft.Scripting.Ast; #endif using System.Collections.Generic; using System.Diagnostics; using System.Management.Automation.Language; using System.Reflection; using System.Runtime.CompilerServices; namespace System.Management.Automation.Interpreter { internal sealed class InterpretedFrame { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] public static readonly ThreadLocal<InterpretedFrame> CurrentFrame = new ThreadLocal<InterpretedFrame>(); internal readonly Interpreter Interpreter; internal InterpretedFrame _parent; [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2105:ArrayFieldsShouldNotBeReadOnly")] private int[] _continuations; private int _continuationIndex; private int _pendingContinuation; private object _pendingValue; [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2105:ArrayFieldsShouldNotBeReadOnly")] public readonly object[] Data; [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2105:ArrayFieldsShouldNotBeReadOnly")] public readonly StrongBox<object>[] Closure; public int StackIndex; public int InstructionIndex; // When a ThreadAbortException is raised from interpreted code this is the first frame that caught it. // No handlers within this handler re-abort the current thread when left. public ExceptionHandler CurrentAbortHandler; internal InterpretedFrame(Interpreter interpreter, StrongBox<object>[] closure) { Interpreter = interpreter; StackIndex = interpreter.LocalCount; Data = new object[StackIndex + interpreter.Instructions.MaxStackDepth]; int c = interpreter.Instructions.MaxContinuationDepth; if (c > 0) { _continuations = new int[c]; } Closure = closure; _pendingContinuation = -1; _pendingValue = Interpreter.NoValue; } public DebugInfo GetDebugInfo(int instructionIndex) { return DebugInfo.GetMatchingDebugInfo(Interpreter._debugInfos, instructionIndex); } public string Name { get { return Interpreter._name; } } #region Data Stack Operations public void Push(object value) { Data[StackIndex++] = value; } public void Push(bool value) { Data[StackIndex++] = value ? ScriptingRuntimeHelpers.True : ScriptingRuntimeHelpers.False; } public void Push(int value) { Data[StackIndex++] = ScriptingRuntimeHelpers.Int32ToObject(value); } public object Pop() { return Data[--StackIndex]; } internal void SetStackDepth(int depth) { StackIndex = Interpreter.LocalCount + depth; } public object Peek() { return Data[StackIndex - 1]; } public void Dup() { int i = StackIndex; Data[i] = Data[i - 1]; StackIndex = i + 1; } public ExecutionContext ExecutionContext { get { return (ExecutionContext)Data[1]; } } public FunctionContext FunctionContext { get { return (FunctionContext)Data[0]; } } #endregion #region Stack Trace public InterpretedFrame Parent { get { return _parent; } } public static bool IsInterpretedFrame(MethodBase method) { //ContractUtils.RequiresNotNull(method, "method"); return method.DeclaringType == typeof(Interpreter) && method.Name == "Run"; } /// <summary> /// A single interpreted frame might be represented by multiple subsequent Interpreter.Run CLR frames. /// This method filters out the duplicate CLR frames. /// </summary> public static IEnumerable<StackFrame> GroupStackFrames(IEnumerable<StackFrame> stackTrace) { bool inInterpretedFrame = false; foreach (StackFrame frame in stackTrace) { if (InterpretedFrame.IsInterpretedFrame(frame.GetMethod())) { if (inInterpretedFrame) { continue; } inInterpretedFrame = true; } else { inInterpretedFrame = false; } yield return frame; } } public IEnumerable<InterpretedFrameInfo> GetStackTraceDebugInfo() { var frame = this; do { yield return new InterpretedFrameInfo(frame.Name, frame.GetDebugInfo(frame.InstructionIndex)); frame = frame.Parent; } while (frame != null); } internal void SaveTraceToException(Exception exception) { if (exception.Data[typeof(InterpretedFrameInfo)] == null) { exception.Data[typeof(InterpretedFrameInfo)] = new List<InterpretedFrameInfo>(GetStackTraceDebugInfo()).ToArray(); } } public static InterpretedFrameInfo[] GetExceptionStackTrace(Exception exception) { return exception.Data[typeof(InterpretedFrameInfo)] as InterpretedFrameInfo[]; } #if DEBUG internal string[] Trace { get { var trace = new List<string>(); var frame = this; do { trace.Add(frame.Name); frame = frame.Parent; } while (frame != null); return trace.ToArray(); } } #endif internal ThreadLocal<InterpretedFrame>.StorageInfo Enter() { var currentFrame = InterpretedFrame.CurrentFrame.GetStorageInfo(); _parent = currentFrame.Value; currentFrame.Value = this; return currentFrame; } internal void Leave(ThreadLocal<InterpretedFrame>.StorageInfo currentFrame) { currentFrame.Value = _parent; } #endregion #region Continuations internal bool IsJumpHappened() { return _pendingContinuation >= 0; } public void RemoveContinuation() { _continuationIndex--; } public void PushContinuation(int continuation) { _continuations[_continuationIndex++] = continuation; } public int YieldToCurrentContinuation() { var target = Interpreter._labels[_continuations[_continuationIndex - 1]]; SetStackDepth(target.StackDepth); return target.Index - InstructionIndex; } /// <summary> /// Get called from the LeaveFinallyInstruction /// </summary> public int YieldToPendingContinuation() { Debug.Assert(_pendingContinuation >= 0); RuntimeLabel pendingTarget = Interpreter._labels[_pendingContinuation]; // the current continuation might have higher priority (continuationIndex is the depth of the current continuation): if (pendingTarget.ContinuationStackDepth < _continuationIndex) { RuntimeLabel currentTarget = Interpreter._labels[_continuations[_continuationIndex - 1]]; SetStackDepth(currentTarget.StackDepth); return currentTarget.Index - InstructionIndex; } SetStackDepth(pendingTarget.StackDepth); if (_pendingValue != Interpreter.NoValue) { Data[StackIndex - 1] = _pendingValue; } // Set the _pendingContinuation and _pendingValue to the default values if we finally gets to the Goto target _pendingContinuation = -1; _pendingValue = Interpreter.NoValue; return pendingTarget.Index - InstructionIndex; } internal void PushPendingContinuation() { Push(_pendingContinuation); Push(_pendingValue); _pendingContinuation = -1; _pendingValue = Interpreter.NoValue; } internal void PopPendingContinuation() { _pendingValue = Pop(); _pendingContinuation = (int)Pop(); } private static MethodInfo s_goto; private static MethodInfo s_voidGoto; internal static MethodInfo GotoMethod { get { return s_goto ?? (s_goto = typeof(InterpretedFrame).GetMethod("Goto")); } } internal static MethodInfo VoidGotoMethod { get { return s_voidGoto ?? (s_voidGoto = typeof(InterpretedFrame).GetMethod("VoidGoto")); } } public int VoidGoto(int labelIndex) { return Goto(labelIndex, Interpreter.NoValue, gotoExceptionHandler: false); } public int Goto(int labelIndex, object value, bool gotoExceptionHandler) { // TODO: we know this at compile time (except for compiled loop): RuntimeLabel target = Interpreter._labels[labelIndex]; Debug.Assert(!gotoExceptionHandler || (gotoExceptionHandler && _continuationIndex == target.ContinuationStackDepth), "When it's time to jump to the exception handler, all previous finally blocks should already be processed"); if (_continuationIndex == target.ContinuationStackDepth) { SetStackDepth(target.StackDepth); if (value != Interpreter.NoValue) { Data[StackIndex - 1] = value; } return target.Index - InstructionIndex; } // if we are in the middle of executing jump we forget the previous target and replace it by a new one: _pendingContinuation = labelIndex; _pendingValue = value; return YieldToCurrentContinuation(); } #endregion } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; namespace biz.dfch.CS.Examples.Odata.Tests.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create /// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
using System; using System.IO; using System.Threading; using System.Reflection; using System.Collections.Generic; using System.Linq; namespace Python.Runtime { /// <summary> /// This class provides the public interface of the Python runtime. /// </summary> public class PythonEngine : IDisposable { private static DelegateManager delegateManager; private static bool initialized; public PythonEngine() { Initialize(); } public PythonEngine(params string[] args) { Initialize(args); } public PythonEngine(IEnumerable<string> args) { Initialize(args); } public void Dispose() { Shutdown(); } public static bool IsInitialized { get { return initialized; } } internal static DelegateManager DelegateManager { get { if (delegateManager == null) { throw new InvalidOperationException( "DelegateManager has not yet been initialized using Python.Runtime.PythonEngine.Initialize()."); } return delegateManager; } } public static string ProgramName { get { string result = Runtime.Py_GetProgramName(); if (result == null) { return ""; } return result; } set { Runtime.Py_SetProgramName(value); } } public static string PythonHome { get { string result = Runtime.Py_GetPythonHome(); if (result == null) { return ""; } return result; } set { Runtime.Py_SetPythonHome(value); } } public static string PythonPath { get { string result = Runtime.Py_GetPath(); if (result == null) { return ""; } return result; } set { Runtime.Py_SetPath(value); } } public static string Version { get { return Runtime.Py_GetVersion(); } } public static string BuildInfo { get { return Runtime.Py_GetBuildInfo(); } } public static string Platform { get { return Runtime.Py_GetPlatform(); } } public static string Copyright { get { return Runtime.Py_GetCopyright(); } } public static int RunSimpleString(string code) { return Runtime.PyRun_SimpleString(code); } public static void Initialize() { Initialize(Enumerable.Empty<string>()); } /// <summary> /// Initialize Method /// </summary> /// <remarks> /// Initialize the Python runtime. It is safe to call this method /// more than once, though initialization will only happen on the /// first call. It is *not* necessary to hold the Python global /// interpreter lock (GIL) to call this method. /// </remarks> public static void Initialize(IEnumerable<string> args) { if (!initialized) { // Creating the delegateManager MUST happen before Runtime.Initialize // is called. If it happens afterwards, DelegateManager's CodeGenerator // throws an exception in its ctor. This exception is eaten somehow // during an initial "import clr", and the world ends shortly thereafter. // This is probably masking some bad mojo happening somewhere in Runtime.Initialize(). delegateManager = new DelegateManager(); Runtime.Initialize(); initialized = true; Exceptions.Clear(); Py.SetArgv(args); // register the atexit callback (this doesn't use Py_AtExit as the C atexit // callbacks are called after python is fully finalized but the python ones // are called while the python engine is still running). string code = "import atexit, clr\n" + "atexit.register(clr._AtExit)\n"; PyObject r = PythonEngine.RunString(code); if (r != null) { r.Dispose(); } // Load the clr.py resource into the clr module IntPtr clr = Python.Runtime.ImportHook.GetCLRModule(); IntPtr clr_dict = Runtime.PyModule_GetDict(clr); var locals = new PyDict(); try { IntPtr module = Runtime.PyImport_AddModule("clr._extras"); IntPtr module_globals = Runtime.PyModule_GetDict(module); IntPtr builtins = Runtime.PyEval_GetBuiltins(); Runtime.PyDict_SetItemString(module_globals, "__builtins__", builtins); Assembly assembly = Assembly.GetExecutingAssembly(); using (Stream stream = assembly.GetManifestResourceStream("clr.py")) using (var reader = new StreamReader(stream)) { // add the contents of clr.py to the module string clr_py = reader.ReadToEnd(); PyObject result = RunString(clr_py, module_globals, locals.Handle); if (null == result) { throw new PythonException(); } result.Dispose(); } // add the imported module to the clr module, and copy the API functions // and decorators into the main clr module. Runtime.PyDict_SetItemString(clr_dict, "_extras", module); foreach (PyObject key in locals.Keys()) { if (!key.ToString().StartsWith("_") || key.ToString().Equals("__version__")) { PyObject value = locals[key]; Runtime.PyDict_SetItem(clr_dict, key.Handle, value.Handle); value.Dispose(); } key.Dispose(); } } finally { locals.Dispose(); } } } /// <summary> /// A helper to perform initialization from the context of an active /// CPython interpreter process - this bootstraps the managed runtime /// when it is imported by the CLR extension module. /// </summary> #if PYTHON3 public static IntPtr InitExt() #elif PYTHON2 public static void InitExt() #endif { try { Initialize(); // Trickery - when the import hook is installed into an already // running Python, the standard import machinery is still in // control for the duration of the import that caused bootstrap. // // That is problematic because the std machinery tries to get // sub-names directly from the module __dict__ rather than going // through our module object's getattr hook. This workaround is // evil ;) We essentially climb up the stack looking for the // import that caused the bootstrap to happen, then re-execute // the import explicitly after our hook has been installed. By // doing this, the original outer import should work correctly. // // Note that this is only needed during the execution of the // first import that installs the CLR import hook. This hack // still doesn't work if you use the interactive interpreter, // since there is no line info to get the import line ;( string code = "import traceback\n" + "for item in traceback.extract_stack():\n" + " line = item[3]\n" + " if line is not None:\n" + " if line.startswith('import CLR') or \\\n" + " line.startswith('import clr') or \\\n" + " line.startswith('from clr') or \\\n" + " line.startswith('from CLR'):\n" + " exec(line)\n" + " break\n"; PyObject r = PythonEngine.RunString(code); if (r != null) { r.Dispose(); } } catch (PythonException e) { e.Restore(); #if PYTHON3 return IntPtr.Zero; #endif } #if PYTHON3 return Python.Runtime.ImportHook.GetCLRModule(); #endif } /// <summary> /// Shutdown Method /// </summary> /// <remarks> /// Shutdown and release resources held by the Python runtime. The /// Python runtime can no longer be used in the current process /// after calling the Shutdown method. /// </remarks> public static void Shutdown() { if (initialized) { Runtime.Shutdown(); initialized = false; } } /// <summary> /// AcquireLock Method /// </summary> /// <remarks> /// Acquire the Python global interpreter lock (GIL). Managed code /// *must* call this method before using any objects or calling any /// methods on objects in the Python.Runtime namespace. The only /// exception is PythonEngine.Initialize, which may be called without /// first calling AcquireLock. /// Each call to AcquireLock must be matched by a corresponding call /// to ReleaseLock, passing the token obtained from AcquireLock. /// For more information, see the "Extending and Embedding" section /// of the Python documentation on www.python.org. /// </remarks> public static IntPtr AcquireLock() { return Runtime.PyGILState_Ensure(); } /// <summary> /// ReleaseLock Method /// </summary> /// <remarks> /// Release the Python global interpreter lock using a token obtained /// from a previous call to AcquireLock. /// For more information, see the "Extending and Embedding" section /// of the Python documentation on www.python.org. /// </remarks> public static void ReleaseLock(IntPtr gs) { Runtime.PyGILState_Release(gs); } /// <summary> /// BeginAllowThreads Method /// </summary> /// <remarks> /// Release the Python global interpreter lock to allow other threads /// to run. This is equivalent to the Py_BEGIN_ALLOW_THREADS macro /// provided by the C Python API. /// For more information, see the "Extending and Embedding" section /// of the Python documentation on www.python.org. /// </remarks> public static IntPtr BeginAllowThreads() { return Runtime.PyEval_SaveThread(); } /// <summary> /// EndAllowThreads Method /// </summary> /// <remarks> /// Re-aquire the Python global interpreter lock for the current /// thread. This is equivalent to the Py_END_ALLOW_THREADS macro /// provided by the C Python API. /// For more information, see the "Extending and Embedding" section /// of the Python documentation on www.python.org. /// </remarks> public static void EndAllowThreads(IntPtr ts) { Runtime.PyEval_RestoreThread(ts); } /// <summary> /// ImportModule Method /// </summary> /// <remarks> /// Given a fully-qualified module or package name, import the /// module and return the resulting module object as a PyObject /// or null if an exception is raised. /// </remarks> public static PyObject ImportModule(string name) { IntPtr op = Runtime.PyImport_ImportModule(name); Py.Throw(); return new PyObject(op); } /// <summary> /// ReloadModule Method /// </summary> /// <remarks> /// Given a PyObject representing a previously loaded module, reload /// the module. /// </remarks> public static PyObject ReloadModule(PyObject module) { IntPtr op = Runtime.PyImport_ReloadModule(module.Handle); Py.Throw(); return new PyObject(op); } /// <summary> /// ModuleFromString Method /// </summary> /// <remarks> /// Given a string module name and a string containing Python code, /// execute the code in and return a module of the given name. /// </remarks> public static PyObject ModuleFromString(string name, string code) { IntPtr c = Runtime.Py_CompileString(code, "none", (IntPtr)257); Py.Throw(); IntPtr m = Runtime.PyImport_ExecCodeModule(name, c); Py.Throw(); return new PyObject(m); } /// <summary> /// RunString Method /// </summary> /// <remarks> /// Run a string containing Python code. Returns the result of /// executing the code string as a PyObject instance, or null if /// an exception was raised. /// </remarks> public static PyObject RunString( string code, IntPtr? globals = null, IntPtr? locals = null ) { var borrowedGlobals = true; if (globals == null) { globals = Runtime.PyEval_GetGlobals(); if (globals == IntPtr.Zero) { globals = Runtime.PyDict_New(); Runtime.PyDict_SetItemString( globals.Value, "__builtins__", Runtime.PyEval_GetBuiltins() ); borrowedGlobals = false; } } var borrowedLocals = true; if (locals == null) { locals = Runtime.PyDict_New(); borrowedLocals = false; } var flag = (IntPtr)257; /* Py_file_input */ try { IntPtr result = Runtime.PyRun_String( code, flag, globals.Value, locals.Value ); Py.Throw(); return new PyObject(result); } finally { if (!borrowedLocals) { Runtime.XDecref(locals.Value); } if (!borrowedGlobals) { Runtime.XDecref(globals.Value); } } } } public static class Py { public static GILState GIL() { if (!PythonEngine.IsInitialized) { PythonEngine.Initialize(); } return new GILState(); } public class GILState : IDisposable { private IntPtr state; internal GILState() { state = PythonEngine.AcquireLock(); } public void Dispose() { PythonEngine.ReleaseLock(state); GC.SuppressFinalize(this); } ~GILState() { Dispose(); } } public class KeywordArguments : PyDict { } public static KeywordArguments kw(params object[] kv) { var dict = new KeywordArguments(); if (kv.Length % 2 != 0) { throw new ArgumentException("Must have an equal number of keys and values"); } for (var i = 0; i < kv.Length; i += 2) { IntPtr value; if (kv[i + 1] is PyObject) { value = ((PyObject)kv[i + 1]).Handle; } else { value = Converter.ToPython(kv[i + 1], kv[i + 1]?.GetType()); } if (Runtime.PyDict_SetItemString(dict.Handle, (string)kv[i], value) != 0) { throw new ArgumentException(string.Format("Cannot add key '{0}' to dictionary.", (string)kv[i])); } if (!(kv[i + 1] is PyObject)) { Runtime.XDecref(value); } } return dict; } public static PyObject Import(string name) { return PythonEngine.ImportModule(name); } public static void SetArgv() { IEnumerable<string> args; try { args = Environment.GetCommandLineArgs(); } catch (NotSupportedException) { args = Enumerable.Empty<string>(); } SetArgv( new[] { "" }.Concat( Environment.GetCommandLineArgs().Skip(1) ) ); } public static void SetArgv(params string[] argv) { SetArgv(argv as IEnumerable<string>); } public static void SetArgv(IEnumerable<string> argv) { using (GIL()) { string[] arr = argv.ToArray(); Runtime.PySys_SetArgvEx(arr.Length, arr, 0); Py.Throw(); } } internal static void Throw() { using (GIL()) { if (Runtime.PyErr_Occurred() != 0) { throw new PythonException(); } } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // ExceptQueryOperator.cs // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System.Collections.Generic; using System.Diagnostics; using System.Threading; namespace System.Linq.Parallel { /// <summary> /// Operator that yields the elements from the first data source that aren't in the second. /// This is known as the set relative complement, i.e. left - right. /// </summary> /// <typeparam name="TInputOutput"></typeparam> internal sealed class ExceptQueryOperator<TInputOutput> : BinaryQueryOperator<TInputOutput, TInputOutput, TInputOutput> { private readonly IEqualityComparer<TInputOutput> _comparer; // An equality comparer. //--------------------------------------------------------------------------------------- // Constructs a new set except operator. // internal ExceptQueryOperator(ParallelQuery<TInputOutput> left, ParallelQuery<TInputOutput> right, IEqualityComparer<TInputOutput> comparer) : base(left, right) { Debug.Assert(left != null && right != null, "child data sources cannot be null"); _comparer = comparer; _outputOrdered = LeftChild.OutputOrdered; SetOrdinalIndex(OrdinalIndexState.Shuffled); } internal override QueryResults<TInputOutput> Open( QuerySettings settings, bool preferStriping) { // We just open our child operators, left and then right. Do not propagate the preferStriping value, but // instead explicitly set it to false. Regardless of whether the parent prefers striping or range // partitioning, the output will be hash-partitioned. QueryResults<TInputOutput> leftChildResults = LeftChild.Open(settings, false); QueryResults<TInputOutput> rightChildResults = RightChild.Open(settings, false); return new BinaryQueryOperatorResults(leftChildResults, rightChildResults, this, settings, false); } public override void WrapPartitionedStream<TLeftKey, TRightKey>( PartitionedStream<TInputOutput, TLeftKey> leftStream, PartitionedStream<TInputOutput, TRightKey> rightStream, IPartitionedStreamRecipient<TInputOutput> outputRecipient, bool preferStriping, QuerySettings settings) { Debug.Assert(leftStream.PartitionCount == rightStream.PartitionCount); if (OutputOrdered) { WrapPartitionedStreamHelper<TLeftKey, TRightKey>( ExchangeUtilities.HashRepartitionOrdered<TInputOutput, NoKeyMemoizationRequired, TLeftKey>( leftStream, null, null, _comparer, settings.CancellationState.MergedCancellationToken), rightStream, outputRecipient, settings.CancellationState.MergedCancellationToken); } else { WrapPartitionedStreamHelper<int, TRightKey>( ExchangeUtilities.HashRepartition<TInputOutput, NoKeyMemoizationRequired, TLeftKey>( leftStream, null, null, _comparer, settings.CancellationState.MergedCancellationToken), rightStream, outputRecipient, settings.CancellationState.MergedCancellationToken); } } //--------------------------------------------------------------------------------------- // This is a helper method. WrapPartitionedStream decides what type TLeftKey is going // to be, and then call this method with that key as a generic parameter. // private void WrapPartitionedStreamHelper<TLeftKey, TRightKey>( PartitionedStream<Pair, TLeftKey> leftHashStream, PartitionedStream<TInputOutput, TRightKey> rightPartitionedStream, IPartitionedStreamRecipient<TInputOutput> outputRecipient, CancellationToken cancellationToken) { int partitionCount = leftHashStream.PartitionCount; PartitionedStream<Pair, int> rightHashStream = ExchangeUtilities.HashRepartition<TInputOutput, NoKeyMemoizationRequired, TRightKey>( rightPartitionedStream, null, null, _comparer, cancellationToken); PartitionedStream<TInputOutput, TLeftKey> outputStream = new PartitionedStream<TInputOutput, TLeftKey>(partitionCount, leftHashStream.KeyComparer, OrdinalIndexState.Shuffled); for (int i = 0; i < partitionCount; i++) { if (OutputOrdered) { outputStream[i] = new OrderedExceptQueryOperatorEnumerator<TLeftKey>( leftHashStream[i], rightHashStream[i], _comparer, leftHashStream.KeyComparer, cancellationToken); } else { outputStream[i] = (QueryOperatorEnumerator<TInputOutput, TLeftKey>)(object) new ExceptQueryOperatorEnumerator<TLeftKey>(leftHashStream[i], rightHashStream[i], _comparer, cancellationToken); } } outputRecipient.Receive(outputStream); } //--------------------------------------------------------------------------------------- // Returns an enumerable that represents the query executing sequentially. // internal override IEnumerable<TInputOutput> AsSequentialQuery(CancellationToken token) { IEnumerable<TInputOutput> wrappedLeftChild = CancellableEnumerable.Wrap(LeftChild.AsSequentialQuery(token), token); IEnumerable<TInputOutput> wrappedRightChild = CancellableEnumerable.Wrap(RightChild.AsSequentialQuery(token), token); return wrappedLeftChild.Except(wrappedRightChild, _comparer); } //--------------------------------------------------------------------------------------- // Whether this operator performs a premature merge that would not be performed in // a similar sequential operation (i.e., in LINQ to Objects). // internal override bool LimitsParallelism { get { return false; } } //--------------------------------------------------------------------------------------- // This enumerator calculates the distinct set incrementally. It does this by maintaining // a history -- in the form of a set -- of all data already seen. It then only returns // elements that have not yet been seen. // class ExceptQueryOperatorEnumerator<TLeftKey> : QueryOperatorEnumerator<TInputOutput, int> { private QueryOperatorEnumerator<Pair, TLeftKey> _leftSource; // Left data source. private QueryOperatorEnumerator<Pair, int> _rightSource; // Right data source. private IEqualityComparer<TInputOutput> _comparer; // A comparer used for equality checks/hash-coding. private Set<TInputOutput> _hashLookup; // The hash lookup, used to produce the distinct set. private CancellationToken _cancellationToken; private Shared<int> _outputLoopCount; //--------------------------------------------------------------------------------------- // Instantiates a new except query operator enumerator. // internal ExceptQueryOperatorEnumerator( QueryOperatorEnumerator<Pair, TLeftKey> leftSource, QueryOperatorEnumerator<Pair, int> rightSource, IEqualityComparer<TInputOutput> comparer, CancellationToken cancellationToken) { Debug.Assert(leftSource != null); Debug.Assert(rightSource != null); _leftSource = leftSource; _rightSource = rightSource; _comparer = comparer; _cancellationToken = cancellationToken; } //--------------------------------------------------------------------------------------- // Walks the two data sources, left and then right, to produce the distinct set // internal override bool MoveNext(ref TInputOutput currentElement, ref int currentKey) { Debug.Assert(_leftSource != null); Debug.Assert(_rightSource != null); // Build the set out of the left data source, if we haven't already. if (_hashLookup == null) { _outputLoopCount = new Shared<int>(0); _hashLookup = new Set<TInputOutput>(_comparer); Pair rightElement = new Pair(default(TInputOutput), default(NoKeyMemoizationRequired)); int rightKeyUnused = default(int); int i = 0; while (_rightSource.MoveNext(ref rightElement, ref rightKeyUnused)) { if ((i++ & CancellationState.POLL_INTERVAL) == 0) CancellationState.ThrowIfCanceled(_cancellationToken); _hashLookup.Add((TInputOutput)rightElement.First); } } // Now iterate over the right data source, looking for matches. Pair leftElement = new Pair(default(TInputOutput), default(NoKeyMemoizationRequired)); TLeftKey leftKeyUnused = default(TLeftKey); while (_leftSource.MoveNext(ref leftElement, ref leftKeyUnused)) { if ((_outputLoopCount.Value++ & CancellationState.POLL_INTERVAL) == 0) CancellationState.ThrowIfCanceled(_cancellationToken); if (_hashLookup.Add((TInputOutput)leftElement.First)) { // This element has never been seen. Return it. currentElement = (TInputOutput)leftElement.First; #if DEBUG currentKey = unchecked((int)0xdeadbeef); #endif return true; } } return false; } protected override void Dispose(bool disposing) { Debug.Assert(_leftSource != null && _rightSource != null); _leftSource.Dispose(); _rightSource.Dispose(); } } class OrderedExceptQueryOperatorEnumerator<TLeftKey> : QueryOperatorEnumerator<TInputOutput, TLeftKey> { private QueryOperatorEnumerator<Pair, TLeftKey> _leftSource; // Left data source. private QueryOperatorEnumerator<Pair, int> _rightSource; // Right data source. private IEqualityComparer<TInputOutput> _comparer; // A comparer used for equality checks/hash-coding. private IComparer<TLeftKey> _leftKeyComparer; // A comparer for order keys. private IEnumerator<KeyValuePair<Wrapper<TInputOutput>, Pair>> _outputEnumerator; // The enumerator output elements + order keys. private CancellationToken _cancellationToken; //--------------------------------------------------------------------------------------- // Instantiates a new except query operator enumerator. // internal OrderedExceptQueryOperatorEnumerator( QueryOperatorEnumerator<Pair, TLeftKey> leftSource, QueryOperatorEnumerator<Pair, int> rightSource, IEqualityComparer<TInputOutput> comparer, IComparer<TLeftKey> leftKeyComparer, CancellationToken cancellationToken) { Debug.Assert(leftSource != null); Debug.Assert(rightSource != null); _leftSource = leftSource; _rightSource = rightSource; _comparer = comparer; _leftKeyComparer = leftKeyComparer; _cancellationToken = cancellationToken; } //--------------------------------------------------------------------------------------- // Walks the two data sources, left and then right, to produce the distinct set // internal override bool MoveNext(ref TInputOutput currentElement, ref TLeftKey currentKey) { Debug.Assert(_leftSource != null); Debug.Assert(_rightSource != null); // Build the set out of the left data source, if we haven't already. if (_outputEnumerator == null) { Set<TInputOutput> rightLookup = new Set<TInputOutput>(_comparer); Pair rightElement = new Pair(default(TInputOutput), default(NoKeyMemoizationRequired)); int rightKeyUnused = default(int); int i = 0; while (_rightSource.MoveNext(ref rightElement, ref rightKeyUnused)) { if ((i++ & CancellationState.POLL_INTERVAL) == 0) CancellationState.ThrowIfCanceled(_cancellationToken); rightLookup.Add((TInputOutput)rightElement.First); } var leftLookup = new Dictionary<Wrapper<TInputOutput>, Pair>( new WrapperEqualityComparer<TInputOutput>(_comparer)); Pair leftElement = new Pair(default(TInputOutput), default(NoKeyMemoizationRequired)); TLeftKey leftKey = default(TLeftKey); while (_leftSource.MoveNext(ref leftElement, ref leftKey)) { if ((i++ & CancellationState.POLL_INTERVAL) == 0) CancellationState.ThrowIfCanceled(_cancellationToken); if (rightLookup.Contains((TInputOutput)leftElement.First)) { continue; } Pair oldEntry; Wrapper<TInputOutput> wrappedLeftElement = new Wrapper<TInputOutput>((TInputOutput)leftElement.First); if (!leftLookup.TryGetValue(wrappedLeftElement, out oldEntry) || _leftKeyComparer.Compare(leftKey, (TLeftKey)oldEntry.Second) < 0) { // For each "elem" value, we store the smallest key, and the element value that had that key. // Note that even though two element values are "equal" according to the EqualityComparer, // we still cannot choose arbitrarily which of the two to yield. leftLookup[wrappedLeftElement] = new Pair(leftElement.First, leftKey); } } _outputEnumerator = leftLookup.GetEnumerator(); } if (_outputEnumerator.MoveNext()) { Pair currentPair = _outputEnumerator.Current.Value; currentElement = (TInputOutput)currentPair.First; currentKey = (TLeftKey)currentPair.Second; return true; } return false; } protected override void Dispose(bool disposing) { Debug.Assert(_leftSource != null && _rightSource != null); _leftSource.Dispose(); _rightSource.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.Linq; using System.Numerics; using Xunit; namespace System.Security.Cryptography.Rsa.Tests { public partial class ImportExport { [Fact] public static void ExportAutoKey() { RSAParameters privateParams; RSAParameters publicParams; int keySize; using (RSA rsa = RSAFactory.Create()) { keySize = rsa.KeySize; // We've not done anything with this instance yet, but it should automatically // create the key, because we'll now asked about it. privateParams = rsa.ExportParameters(true); publicParams = rsa.ExportParameters(false); // It shouldn't be changing things when it generated the key. Assert.Equal(keySize, rsa.KeySize); } Assert.Null(publicParams.D); Assert.NotNull(privateParams.D); ValidateParameters(ref publicParams); ValidateParameters(ref privateParams); Assert.Equal(privateParams.Modulus, publicParams.Modulus); Assert.Equal(privateParams.Exponent, publicParams.Exponent); } [Fact] public static void PaddedExport() { // OpenSSL's numeric type for the storage of RSA key parts disregards zero-valued // prefix bytes. // // The .NET 4.5 RSACryptoServiceProvider type verifies that all of the D breakdown // values (P, DP, Q, DQ, InverseQ) are exactly half the size of D (which is itself // the same size as Modulus). // // These two things, in combination, suggest that we ensure that all .NET // implementations of RSA export their keys to the fixed array size suggested by their // KeySize property. RSAParameters diminishedDPParameters = TestData.DiminishedDPParameters; RSAParameters exported; using (RSA rsa = RSAFactory.Create()) { rsa.ImportParameters(diminishedDPParameters); exported = rsa.ExportParameters(true); } // DP is the most likely to fail, the rest just otherwise ensure that Export // isn't losing data. AssertKeyEquals(ref diminishedDPParameters, ref exported); } [Fact] public static void LargeKeyImportExport() { RSAParameters imported = TestData.RSA16384Params; using (RSA rsa = RSAFactory.Create()) { try { rsa.ImportParameters(imported); } catch (CryptographicException) { // The key is pretty big, perhaps it was refused. return; } RSAParameters exported = rsa.ExportParameters(false); Assert.Equal(exported.Modulus, imported.Modulus); Assert.Equal(exported.Exponent, imported.Exponent); Assert.Null(exported.D); exported = rsa.ExportParameters(true); AssertKeyEquals(ref imported, ref exported); } } [Fact] public static void UnusualExponentImportExport() { // Most choices for the Exponent value in an RSA key use a Fermat prime. // Since a Fermat prime is 2^(2^m) + 1, it always only has two bits set, and // frequently has the form { 0x01, [some number of 0x00s], 0x01 }, which has the same // representation in both big- and little-endian. // // The only real requirement for an Exponent value is that it be coprime to (p-1)(q-1). // So here we'll use the (non-Fermat) prime value 433 (0x01B1) to ensure big-endian export. RSAParameters unusualExponentParameters = TestData.UnusualExponentParameters; RSAParameters exported; using (RSA rsa = RSAFactory.Create()) { rsa.ImportParameters(unusualExponentParameters); exported = rsa.ExportParameters(true); } // Exponent is the most likely to fail, the rest just otherwise ensure that Export // isn't losing data. AssertKeyEquals(ref unusualExponentParameters, ref exported); } [Fact] public static void ImportExport1032() { RSAParameters imported = TestData.RSA1032Parameters; RSAParameters exported; RSAParameters exportedPublic; using (RSA rsa = RSAFactory.Create()) { rsa.ImportParameters(imported); exported = rsa.ExportParameters(true); exportedPublic = rsa.ExportParameters(false); } AssertKeyEquals(ref imported, ref exported); Assert.Equal(exportedPublic.Modulus, imported.Modulus); Assert.Equal(exportedPublic.Exponent, imported.Exponent); Assert.Null(exportedPublic.D); } [Fact] public static void ImportReset() { using (RSA rsa = RSAFactory.Create()) { RSAParameters exported = rsa.ExportParameters(true); RSAParameters imported; // Ensure that we cause the KeySize value to change. if (rsa.KeySize == 1024) { imported = TestData.RSA2048Params; } else { imported = TestData.RSA1024Params; } Assert.NotEqual(imported.Modulus.Length * 8, rsa.KeySize); Assert.NotEqual(imported.Modulus, exported.Modulus); rsa.ImportParameters(imported); Assert.Equal(imported.Modulus.Length * 8, rsa.KeySize); exported = rsa.ExportParameters(true); AssertKeyEquals(ref imported, ref exported); } } [Fact] public static void ImportPrivateExportPublic() { RSAParameters imported = TestData.RSA1024Params; using (RSA rsa = RSAFactory.Create()) { rsa.ImportParameters(imported); RSAParameters exportedPublic = rsa.ExportParameters(false); Assert.Equal(imported.Modulus, exportedPublic.Modulus); Assert.Equal(imported.Exponent, exportedPublic.Exponent); Assert.Null(exportedPublic.D); ValidateParameters(ref exportedPublic); } } [Fact] public static void MultiExport() { RSAParameters imported = TestData.RSA1024Params; using (RSA rsa = RSAFactory.Create()) { rsa.ImportParameters(imported); RSAParameters exportedPrivate = rsa.ExportParameters(true); RSAParameters exportedPrivate2 = rsa.ExportParameters(true); RSAParameters exportedPublic = rsa.ExportParameters(false); RSAParameters exportedPublic2 = rsa.ExportParameters(false); RSAParameters exportedPrivate3 = rsa.ExportParameters(true); RSAParameters exportedPublic3 = rsa.ExportParameters(false); AssertKeyEquals(ref imported, ref exportedPrivate); Assert.Equal(imported.Modulus, exportedPublic.Modulus); Assert.Equal(imported.Exponent, exportedPublic.Exponent); Assert.Null(exportedPublic.D); ValidateParameters(ref exportedPublic); AssertKeyEquals(ref exportedPrivate, ref exportedPrivate2); AssertKeyEquals(ref exportedPrivate, ref exportedPrivate3); AssertKeyEquals(ref exportedPublic, ref exportedPublic2); AssertKeyEquals(ref exportedPublic, ref exportedPublic3); } } [Fact] public static void PublicOnlyPrivateExport() { RSAParameters imported = new RSAParameters { Modulus = TestData.RSA1024Params.Modulus, Exponent = TestData.RSA1024Params.Exponent, }; using (RSA rsa = RSAFactory.Create()) { rsa.ImportParameters(imported); Assert.ThrowsAny<CryptographicException>(() => rsa.ExportParameters(true)); } } [Fact] public static void ImportNoExponent() { RSAParameters imported = new RSAParameters { Modulus = TestData.RSA1024Params.Modulus, }; using (RSA rsa = RSAFactory.Create()) { Assert.ThrowsAny<CryptographicException>(() => rsa.ImportParameters(imported)); } } [Fact] public static void ImportNoModulus() { RSAParameters imported = new RSAParameters { Exponent = TestData.RSA1024Params.Exponent, }; using (RSA rsa = RSAFactory.Create()) { Assert.ThrowsAny<CryptographicException>(() => rsa.ImportParameters(imported)); } } [Fact] public static void ImportNoDP() { // Because RSAParameters is a struct, this is a copy, // so assigning DP is not destructive to other tests. RSAParameters imported = TestData.RSA1024Params; imported.DP = null; using (RSA rsa = RSAFactory.Create()) { Assert.ThrowsAny<CryptographicException>(() => rsa.ImportParameters(imported)); } } internal static void AssertKeyEquals(ref RSAParameters expected, ref RSAParameters actual) { Assert.Equal(expected.Modulus, actual.Modulus); Assert.Equal(expected.Exponent, actual.Exponent); Assert.Equal(expected.P, actual.P); Assert.Equal(expected.DP, actual.DP); Assert.Equal(expected.Q, actual.Q); Assert.Equal(expected.DQ, actual.DQ); Assert.Equal(expected.InverseQ, actual.InverseQ); if (expected.D == null) { Assert.Null(actual.D); } else { Assert.NotNull(actual.D); // If the value matched expected, take that as valid and shortcut the math. // If it didn't, we'll test that the value is at least legal. if (!expected.D.SequenceEqual(actual.D)) { VerifyDValue(ref actual); } } } internal static void ValidateParameters(ref RSAParameters rsaParams) { Assert.NotNull(rsaParams.Modulus); Assert.NotNull(rsaParams.Exponent); // Key compatibility: RSA as an algorithm is achievable using just N (Modulus), // E (public Exponent) and D (private exponent). Having all of the breakdowns // of D make the algorithm faster, and shipped versions of RSACryptoServiceProvider // have thrown if D is provided and the rest of the private key values are not. // So, here we're going to assert that none of them were null for private keys. if (rsaParams.D == null) { Assert.Null(rsaParams.P); Assert.Null(rsaParams.DP); Assert.Null(rsaParams.Q); Assert.Null(rsaParams.DQ); Assert.Null(rsaParams.InverseQ); } else { Assert.NotNull(rsaParams.P); Assert.NotNull(rsaParams.DP); Assert.NotNull(rsaParams.Q); Assert.NotNull(rsaParams.DQ); Assert.NotNull(rsaParams.InverseQ); } } private static void VerifyDValue(ref RSAParameters rsaParams) { if (rsaParams.P == null) { return; } // Verify that the formula (D * E) % LCM(p - 1, q - 1) == 1 // is true. // // This is NOT the same as saying D = ModInv(E, LCM(p - 1, q - 1)), // because D = ModInv(E, (p - 1) * (q - 1)) is a valid choice, but will // still work through this formula. BigInteger p = PositiveBigInteger(rsaParams.P); BigInteger q = PositiveBigInteger(rsaParams.Q); BigInteger e = PositiveBigInteger(rsaParams.Exponent); BigInteger d = PositiveBigInteger(rsaParams.D); BigInteger lambda = LeastCommonMultiple(p - 1, q - 1); BigInteger modProduct = (d * e) % lambda; Assert.Equal(BigInteger.One, modProduct); } private static BigInteger LeastCommonMultiple(BigInteger a, BigInteger b) { BigInteger gcd = BigInteger.GreatestCommonDivisor(a, b); return BigInteger.Abs(a) / gcd * BigInteger.Abs(b); } private static BigInteger PositiveBigInteger(byte[] bigEndianBytes) { byte[] littleEndianBytes; if (bigEndianBytes[0] >= 0x80) { // Insert a padding 00 byte so the number is treated as positive. littleEndianBytes = new byte[bigEndianBytes.Length + 1]; Buffer.BlockCopy(bigEndianBytes, 0, littleEndianBytes, 1, bigEndianBytes.Length); } else { littleEndianBytes = (byte[])bigEndianBytes.Clone(); } Array.Reverse(littleEndianBytes); return new BigInteger(littleEndianBytes); } } }
// // Options.cs // // Authors: // Jonathan Pryor <jpryor@novell.com> // // Copyright (C) 2008 Novell (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // // Compile With: // gmcs -debug+ -r:System.Core Options.cs -o:NDesk.Options.dll // gmcs -debug+ -d:LINQ -r:System.Core Options.cs -o:NDesk.Options.dll // // The LINQ version just changes the implementation of // OptionSet.Parse(IEnumerable<string>), and confers no semantic changes. // // A Getopt::Long-inspired option parsing library for C#. // // NDesk.Options.OptionSet is built upon a key/value table, where the // key is a option format string and the value is a delegate that is // invoked when the format string is matched. // // Option format strings: // Regex-like BNF Grammar: // name: .+ // type: [=:] // sep: ( [^{}]+ | '{' .+ '}' )? // aliases: ( name type sep ) ( '|' name type sep )* // // Each '|'-delimited name is an alias for the associated action. If the // format string ends in a '=', it has a required value. If the format // string ends in a ':', it has an optional value. If neither '=' or ':' // is present, no value is supported. `=' or `:' need only be defined on one // alias, but if they are provided on more than one they must be consistent. // // Each alias portion may also end with a "key/value separator", which is used // to split option values if the option accepts > 1 value. If not specified, // it defaults to '=' and ':'. If specified, it can be any character except // '{' and '}' OR the *string* between '{' and '}'. If no separator should be // used (i.e. the separate values should be distinct arguments), then "{}" // should be used as the separator. // // Options are extracted either from the current option by looking for // the option name followed by an '=' or ':', or is taken from the // following option IFF: // - The current option does not contain a '=' or a ':' // - The current option requires a value (i.e. not a Option type of ':') // // The `name' used in the option format string does NOT include any leading // option indicator, such as '-', '--', or '/'. All three of these are // permitted/required on any named option. // // Option bundling is permitted so long as: // - '-' is used to start the option group // - all of the bundled options are a single character // - at most one of the bundled options accepts a value, and the value // provided starts from the next character to the end of the string. // // This allows specifying '-a -b -c' as '-abc', and specifying '-D name=value' // as '-Dname=value'. // // Option processing is disabled by specifying "--". All options after "--" // are returned by OptionSet.Parse() unchanged and unprocessed. // // Unprocessed options are returned from OptionSet.Parse(). // // Examples: // int verbose = 0; // OptionSet p = new OptionSet () // .Add ("v", v => ++verbose) // .Add ("name=|value=", v => Console.WriteLine (v)); // p.Parse (new string[]{"-v", "--v", "/v", "-name=A", "/name", "B", "extra"}); // // The above would parse the argument string array, and would invoke the // lambda expression three times, setting `verbose' to 3 when complete. // It would also print out "A" and "B" to standard output. // The returned array would contain the string "extra". // // C# 3.0 collection initializers are supported and encouraged: // var p = new OptionSet () { // { "h|?|help", v => ShowHelp () }, // }; // // System.ComponentModel.TypeConverter is also supported, allowing the use of // custom data types in the callback type; TypeConverter.ConvertFromString() // is used to convert the value option to an instance of the specified // type: // // var p = new OptionSet () { // { "foo=", (Foo f) => Console.WriteLine (f.ToString ()) }, // }; // // Random other tidbits: // - Boolean options (those w/o '=' or ':' in the option format string) // are explicitly enabled if they are followed with '+', and explicitly // disabled if they are followed with '-': // string a = null; // var p = new OptionSet () { // { "a", s => a = s }, // }; // p.Parse (new string[]{"-a"}); // sets v != null // p.Parse (new string[]{"-a+"}); // sets v != null // p.Parse (new string[]{"-a-"}); // sets v == null // using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.IO; using System.Runtime.Serialization; using System.Security.Permissions; using System.Text; using System.Text.RegularExpressions; #if LINQ using System.Linq; #endif #if TEST using NDesk.Options; #endif namespace checksum.infrastructure.commandline { public class OptionValueCollection : IList, IList<string> { private readonly OptionContext c; private readonly List<string> values = new List<string>(); internal OptionValueCollection(OptionContext c) { this.c = c; } #region ICollection void ICollection.CopyTo(Array array, int index) { (values as ICollection).CopyTo(array, index); } bool ICollection.IsSynchronized { get { return (values as ICollection).IsSynchronized; } } object ICollection.SyncRoot { get { return (values as ICollection).SyncRoot; } } #endregion #region ICollection<T> public void Clear() { values.Clear(); } public int Count { get { return values.Count; } } public bool IsReadOnly { get { return false; } } public void Add(string item) { values.Add(item); } public bool Contains(string item) { return values.Contains(item); } public void CopyTo(string[] array, int arrayIndex) { values.CopyTo(array, arrayIndex); } public bool Remove(string item) { return values.Remove(item); } #endregion #region IEnumerable IEnumerator IEnumerable.GetEnumerator() { return values.GetEnumerator(); } #endregion #region IEnumerable<T> public IEnumerator<string> GetEnumerator() { return values.GetEnumerator(); } #endregion #region IList int IList.Add(object value) { return (values as IList).Add(value); } bool IList.Contains(object value) { return (values as IList).Contains(value); } int IList.IndexOf(object value) { return (values as IList).IndexOf(value); } void IList.Insert(int index, object value) { (values as IList).Insert(index, value); } void IList.Remove(object value) { (values as IList).Remove(value); } void IList.RemoveAt(int index) { (values as IList).RemoveAt(index); } bool IList.IsFixedSize { get { return false; } } object IList.this[int index] { get { return this[index]; } set { (values as IList)[index] = value; } } #endregion #region IList<T> public int IndexOf(string item) { return values.IndexOf(item); } public void Insert(int index, string item) { values.Insert(index, item); } public void RemoveAt(int index) { values.RemoveAt(index); } public string this[int index] { get { AssertValid(index); return index >= values.Count ? null : values[index]; } set { values[index] = value; } } private void AssertValid(int index) { if (c.Option == null) throw new InvalidOperationException("OptionContext.Option is null."); if (index >= c.Option.MaxValueCount) throw new ArgumentOutOfRangeException("index"); if (c.Option.OptionValueType == OptionValueType.Required && index >= values.Count) throw new OptionException(string.Format( c.OptionSet.MessageLocalizer("Missing required value for option '{0}'."), c.OptionName), c.OptionName); } #endregion public List<string> ToList() { return new List<string>(values); } public string[] ToArray() { return values.ToArray(); } public override string ToString() { return string.Join(", ", values.ToArray()); } } public class OptionContext { private readonly OptionValueCollection c; private readonly OptionSet set; public OptionContext(OptionSet set) { this.set = set; c = new OptionValueCollection(this); } public Option Option { get; set; } public string OptionName { get; set; } public int OptionIndex { get; set; } public OptionSet OptionSet { get { return set; } } public OptionValueCollection OptionValues { get { return c; } } } public enum OptionValueType { None, Optional, Required, } public abstract class Option { private static readonly char[] NameTerminator = new[] {'=', ':'}; private readonly int count; private readonly string description; private readonly string[] names; private readonly string prototype; private readonly OptionValueType type; private string[] separators; protected Option(string prototype, string description) : this(prototype, description, 1) { } protected Option(string prototype, string description, int maxValueCount) { if (prototype == null) throw new ArgumentNullException("prototype"); if (prototype.Length == 0) throw new ArgumentException("Cannot be the empty string.", "prototype"); if (maxValueCount < 0) throw new ArgumentOutOfRangeException("maxValueCount"); this.prototype = prototype; names = prototype.Split('|'); this.description = description; count = maxValueCount; type = ParsePrototype(); if (count == 0 && type != OptionValueType.None) throw new ArgumentException( "Cannot provide maxValueCount of 0 for OptionValueType.Required or " + "OptionValueType.Optional.", "maxValueCount"); if (type == OptionValueType.None && maxValueCount > 1) throw new ArgumentException( string.Format("Cannot provide maxValueCount of {0} for OptionValueType.None.", maxValueCount), "maxValueCount"); if (Array.IndexOf(names, "<>") >= 0 && ((names.Length == 1 && type != OptionValueType.None) || (names.Length > 1 && MaxValueCount > 1))) throw new ArgumentException( "The default option handler '<>' cannot require values.", "prototype"); } public string Prototype { get { return prototype; } } public string Description { get { return description; } } public OptionValueType OptionValueType { get { return type; } } public int MaxValueCount { get { return count; } } internal string[] Names { get { return names; } } internal string[] ValueSeparators { get { return separators; } } public string[] GetNames() { return (string[]) names.Clone(); } public string[] GetValueSeparators() { if (separators == null) return new string[0]; return (string[]) separators.Clone(); } protected static T Parse<T>(string value, OptionContext c) { TypeConverter conv = TypeDescriptor.GetConverter(typeof (T)); T t = default (T); try { if (value != null) t = (T) conv.ConvertFromString(value); } catch (Exception e) { throw new OptionException( string.Format( c.OptionSet.MessageLocalizer("Could not convert string `{0}' to type {1} for option `{2}'."), value, typeof (T).Name, c.OptionName), c.OptionName, e); } return t; } private OptionValueType ParsePrototype() { char type = '\0'; var seps = new List<string>(); for (int i = 0; i < names.Length; ++i) { string name = names[i]; if (name.Length == 0) throw new ArgumentException("Empty option names are not supported.", "prototype"); int end = name.IndexOfAny(NameTerminator); if (end == -1) continue; names[i] = name.Substring(0, end); if (type == '\0' || type == name[end]) type = name[end]; else throw new ArgumentException( string.Format("Conflicting option types: '{0}' vs. '{1}'.", type, name[end]), "prototype"); AddSeparators(name, end, seps); } if (type == '\0') return OptionValueType.None; if (count <= 1 && seps.Count != 0) throw new ArgumentException( string.Format("Cannot provide key/value separators for Options taking {0} value(s).", count), "prototype"); if (count > 1) { if (seps.Count == 0) separators = new[] {":", "="}; else if (seps.Count == 1 && seps[0].Length == 0) separators = null; else separators = seps.ToArray(); } return type == '=' ? OptionValueType.Required : OptionValueType.Optional; } private static void AddSeparators(string name, int end, ICollection<string> seps) { int start = -1; for (int i = end + 1; i < name.Length; ++i) { switch (name[i]) { case '{': if (start != -1) throw new ArgumentException( string.Format("Ill-formed name/value separator found in \"{0}\".", name), "prototype"); start = i + 1; break; case '}': if (start == -1) throw new ArgumentException( string.Format("Ill-formed name/value separator found in \"{0}\".", name), "prototype"); seps.Add(name.Substring(start, i - start)); start = -1; break; default: if (start == -1) seps.Add(name[i].ToString()); break; } } if (start != -1) throw new ArgumentException( string.Format("Ill-formed name/value separator found in \"{0}\".", name), "prototype"); } public void Invoke(OptionContext c) { OnParseComplete(c); c.OptionName = null; c.Option = null; c.OptionValues.Clear(); } protected abstract void OnParseComplete(OptionContext c); public override string ToString() { return Prototype; } } [Serializable] public class OptionException : Exception { private readonly string option; public OptionException() { } public OptionException(string message, string optionName) : base(message) { option = optionName; } public OptionException(string message, string optionName, Exception innerException) : base(message, innerException) { option = optionName; } protected OptionException(SerializationInfo info, StreamingContext context) : base(info, context) { option = info.GetString("OptionName"); } public string OptionName { get { return option; } } [SecurityPermission(SecurityAction.LinkDemand, SerializationFormatter = true)] public override void GetObjectData(SerializationInfo info, StreamingContext context) { base.GetObjectData(info, context); info.AddValue("OptionName", option); } } public delegate void OptionAction<TKey, TValue>(TKey key, TValue value); public class OptionSet : KeyedCollection<string, Option> { public OptionSet() : this(delegate(string f) { return f; }) { } public OptionSet(Converter<string, string> localizer) { this.localizer = localizer; } private readonly Converter<string, string> localizer; public Converter<string, string> MessageLocalizer { get { return localizer; } } protected override string GetKeyForItem(Option item) { if (item == null) throw new ArgumentNullException("option"); if (item.Names != null && item.Names.Length > 0) return item.Names[0]; // This should never happen, as it's invalid for Option to be // constructed w/o any names. throw new InvalidOperationException("Option has no names!"); } [Obsolete("Use KeyedCollection.this[string]")] protected Option GetOptionForName(string option) { if (option == null) throw new ArgumentNullException("option"); try { return base[option]; } catch (KeyNotFoundException) { return null; } } protected override void InsertItem(int index, Option item) { base.InsertItem(index, item); AddImpl(item); } protected override void RemoveItem(int index) { base.RemoveItem(index); Option p = Items[index]; // KeyedCollection.RemoveItem() handles the 0th item for (int i = 1; i < p.Names.Length; ++i) { Dictionary.Remove(p.Names[i]); } } protected override void SetItem(int index, Option item) { base.SetItem(index, item); RemoveItem(index); AddImpl(item); } private void AddImpl(Option option) { if (option == null) throw new ArgumentNullException("option"); var added = new List<string>(option.Names.Length); try { // KeyedCollection.InsertItem/SetItem handle the 0th name. for (int i = 1; i < option.Names.Length; ++i) { Dictionary.Add(option.Names[i], option); added.Add(option.Names[i]); } } catch (Exception) { foreach (string name in added) Dictionary.Remove(name); throw; } } public new OptionSet Add(Option option) { base.Add(option); return this; } private sealed class ActionOption : Option { private readonly Action<OptionValueCollection> action; public ActionOption(string prototype, string description, int count, Action<OptionValueCollection> action) : base(prototype, description, count) { if (action == null) throw new ArgumentNullException("action"); this.action = action; } protected override void OnParseComplete(OptionContext c) { action(c.OptionValues); } } public OptionSet Add(string prototype, Action<string> action) { return Add(prototype, null, action); } public OptionSet Add(string prototype, string description, Action<string> action) { if (action == null) throw new ArgumentNullException("action"); Option p = new ActionOption(prototype, description, 1, delegate(OptionValueCollection v) { action(v[0]); }); base.Add(p); return this; } public OptionSet Add(string prototype, OptionAction<string, string> action) { return Add(prototype, null, action); } public OptionSet Add(string prototype, string description, OptionAction<string, string> action) { if (action == null) throw new ArgumentNullException("action"); Option p = new ActionOption(prototype, description, 2, delegate(OptionValueCollection v) { action(v[0], v[1]); }); base.Add(p); return this; } private sealed class ActionOption<T> : Option { private readonly Action<T> action; public ActionOption(string prototype, string description, Action<T> action) : base(prototype, description, 1) { if (action == null) throw new ArgumentNullException("action"); this.action = action; } protected override void OnParseComplete(OptionContext c) { action(Parse<T>(c.OptionValues[0], c)); } } private sealed class ActionOption<TKey, TValue> : Option { private readonly OptionAction<TKey, TValue> action; public ActionOption(string prototype, string description, OptionAction<TKey, TValue> action) : base(prototype, description, 2) { if (action == null) throw new ArgumentNullException("action"); this.action = action; } protected override void OnParseComplete(OptionContext c) { action( Parse<TKey>(c.OptionValues[0], c), Parse<TValue>(c.OptionValues[1], c)); } } public OptionSet Add<T>(string prototype, Action<T> action) { return Add(prototype, null, action); } public OptionSet Add<T>(string prototype, string description, Action<T> action) { return Add(new ActionOption<T>(prototype, description, action)); } public OptionSet Add<TKey, TValue>(string prototype, OptionAction<TKey, TValue> action) { return Add(prototype, null, action); } public OptionSet Add<TKey, TValue>(string prototype, string description, OptionAction<TKey, TValue> action) { return Add(new ActionOption<TKey, TValue>(prototype, description, action)); } protected virtual OptionContext CreateOptionContext() { return new OptionContext(this); } #if LINQ public List<string> Parse (IEnumerable<string> arguments) { bool process = true; OptionContext c = CreateOptionContext (); c.OptionIndex = -1; var def = GetOptionForName ("<>"); var unprocessed = from argument in arguments where ++c.OptionIndex >= 0 && (process || def != null) ? process ? argument == "--" ? (process = false) : !Parse (argument, c) ? def != null ? Unprocessed (null, def, c, argument) : true : false : def != null ? Unprocessed (null, def, c, argument) : true : true select argument; List<string> r = unprocessed.ToList (); if (c.Option != null) c.Option.Invoke (c); return r; } #else public List<string> Parse(IEnumerable<string> arguments) { OptionContext c = CreateOptionContext(); c.OptionIndex = -1; bool process = true; var unprocessed = new List<string>(); Option def = Contains("<>") ? this["<>"] : null; foreach (string argument in arguments) { ++c.OptionIndex; if (argument == "--") { process = false; continue; } if (!process) { Unprocessed(unprocessed, def, c, argument); continue; } if (!Parse(argument, c)) Unprocessed(unprocessed, def, c, argument); } if (c.Option != null) c.Option.Invoke(c); return unprocessed; } #endif private static bool Unprocessed(ICollection<string> extra, Option def, OptionContext c, string argument) { if (def == null) { extra.Add(argument); return false; } c.OptionValues.Add(argument); c.Option = def; c.Option.Invoke(c); return false; } private readonly Regex ValueOption = new Regex( @"^(?<flag>--|-|/)(?<name>[^:=]+)((?<sep>[:=])(?<value>.*))?$"); protected bool GetOptionParts(string argument, out string flag, out string name, out string sep, out string value) { if (argument == null) throw new ArgumentNullException("argument"); flag = name = sep = value = null; Match m = ValueOption.Match(argument); if (!m.Success) { return false; } flag = m.Groups["flag"].Value; name = m.Groups["name"].Value; if (m.Groups["sep"].Success && m.Groups["value"].Success) { sep = m.Groups["sep"].Value; value = m.Groups["value"].Value; } return true; } protected virtual bool Parse(string argument, OptionContext c) { if (c.Option != null) { ParseValue(argument, c); return true; } string f, n, s, v; if (!GetOptionParts(argument, out f, out n, out s, out v)) return false; Option p; if (Contains(n)) { p = this[n]; c.OptionName = f + n; c.Option = p; switch (p.OptionValueType) { case OptionValueType.None: c.OptionValues.Add(n); c.Option.Invoke(c); break; case OptionValueType.Optional: case OptionValueType.Required: ParseValue(v, c); break; } return true; } // no match; is it a bool option? if (ParseBool(argument, n, c)) return true; // is it a bundled option? if (ParseBundledValue(f, string.Concat(n + s + v), c)) return true; return false; } private void ParseValue(string option, OptionContext c) { if (option != null) foreach (string o in c.Option.ValueSeparators != null ? option.Split(c.Option.ValueSeparators, StringSplitOptions.None) : new[] {option}) { c.OptionValues.Add(o); } if (c.OptionValues.Count == c.Option.MaxValueCount || c.Option.OptionValueType == OptionValueType.Optional) c.Option.Invoke(c); else if (c.OptionValues.Count > c.Option.MaxValueCount) { throw new OptionException(localizer(string.Format( "Error: Found {0} option values when expecting {1}.", c.OptionValues.Count, c.Option.MaxValueCount)), c.OptionName); } } private bool ParseBool(string option, string n, OptionContext c) { Option p; string rn; if (n.Length >= 1 && (n[n.Length - 1] == '+' || n[n.Length - 1] == '-') && Contains((rn = n.Substring(0, n.Length - 1)))) { p = this[rn]; string v = n[n.Length - 1] == '+' ? option : null; c.OptionName = option; c.Option = p; c.OptionValues.Add(v); p.Invoke(c); return true; } return false; } private bool ParseBundledValue(string f, string n, OptionContext c) { if (f != "-") return false; for (int i = 0; i < n.Length; ++i) { Option p; string opt = f + n[i].ToString(); string rn = n[i].ToString(); if (!Contains(rn)) { if (i == 0) return false; throw new OptionException(string.Format(localizer( "Cannot bundle unregistered option '{0}'."), opt), opt); } p = this[rn]; switch (p.OptionValueType) { case OptionValueType.None: Invoke(c, opt, n, p); break; case OptionValueType.Optional: case OptionValueType.Required: { string v = n.Substring(i + 1); c.Option = p; c.OptionName = opt; ParseValue(v.Length != 0 ? v : null, c); return true; } default: throw new InvalidOperationException("Unknown OptionValueType: " + p.OptionValueType); } } return true; } private static void Invoke(OptionContext c, string name, string value, Option option) { c.OptionName = name; c.Option = option; c.OptionValues.Add(value); option.Invoke(c); } private const int OptionWidth = 29; public void WriteOptionDescriptions(TextWriter o) { foreach (Option p in this) { int written = 0; if (!WriteOptionPrototype(o, p, ref written)) continue; if (written < OptionWidth) o.Write(new string(' ', OptionWidth - written)); else { o.WriteLine(); o.Write(new string(' ', OptionWidth)); } List<string> lines = GetLines(localizer(GetDescription(p.Description))); o.WriteLine(lines[0]); var prefix = new string(' ', OptionWidth + 2); for (int i = 1; i < lines.Count; ++i) { o.Write(prefix); o.WriteLine(lines[i]); } } } private bool WriteOptionPrototype(TextWriter o, Option p, ref int written) { string[] names = p.Names; int i = GetNextOptionIndex(names, 0); if (i == names.Length) return false; if (names[i].Length == 1) { Write(o, ref written, " -"); Write(o, ref written, names[0]); } else { Write(o, ref written, " --"); Write(o, ref written, names[0]); } for (i = GetNextOptionIndex(names, i + 1); i < names.Length; i = GetNextOptionIndex(names, i + 1)) { Write(o, ref written, ", "); Write(o, ref written, names[i].Length == 1 ? "-" : "--"); Write(o, ref written, names[i]); } if (p.OptionValueType == OptionValueType.Optional || p.OptionValueType == OptionValueType.Required) { if (p.OptionValueType == OptionValueType.Optional) { Write(o, ref written, localizer("[")); } Write(o, ref written, localizer("=" + GetArgumentName(0, p.MaxValueCount, p.Description))); string sep = p.ValueSeparators != null && p.ValueSeparators.Length > 0 ? p.ValueSeparators[0] : " "; for (int c = 1; c < p.MaxValueCount; ++c) { Write(o, ref written, localizer(sep + GetArgumentName(c, p.MaxValueCount, p.Description))); } if (p.OptionValueType == OptionValueType.Optional) { Write(o, ref written, localizer("]")); } } return true; } private static int GetNextOptionIndex(string[] names, int i) { while (i < names.Length && names[i] == "<>") { ++i; } return i; } private static void Write(TextWriter o, ref int n, string s) { n += s.Length; o.Write(s); } private static string GetArgumentName(int index, int maxIndex, string description) { if (description == null) return maxIndex == 1 ? "VALUE" : "VALUE" + (index + 1); string[] nameStart; if (maxIndex == 1) nameStart = new[] {"{0:", "{"}; else nameStart = new[] {"{" + index + ":"}; for (int i = 0; i < nameStart.Length; ++i) { int start, j = 0; do { start = description.IndexOf(nameStart[i], j); } while (start >= 0 && j != 0 ? description[j++ - 1] == '{' : false); if (start == -1) continue; int end = description.IndexOf("}", start); if (end == -1) continue; return description.Substring(start + nameStart[i].Length, end - start - nameStart[i].Length); } return maxIndex == 1 ? "VALUE" : "VALUE" + (index + 1); } private static string GetDescription(string description) { if (description == null) return string.Empty; var sb = new StringBuilder(description.Length); int start = -1; for (int i = 0; i < description.Length; ++i) { switch (description[i]) { case '{': if (i == start) { sb.Append('{'); start = -1; } else if (start < 0) start = i + 1; break; case '}': if (start < 0) { if ((i + 1) == description.Length || description[i + 1] != '}') throw new InvalidOperationException("Invalid option description: " + description); ++i; sb.Append("}"); } else { sb.Append(description.Substring(start, i - start)); start = -1; } break; case ':': if (start < 0) goto default; start = i + 1; break; default: if (start < 0) sb.Append(description[i]); break; } } return sb.ToString(); } private static List<string> GetLines(string description) { var lines = new List<string>(); if (string.IsNullOrEmpty(description)) { lines.Add(string.Empty); return lines; } int length = 80 - OptionWidth - 2; int start = 0, end; do { end = GetLineEnd(start, length, description); bool cont = false; if (end < description.Length) { char c = description[end]; if (c == '-' || (char.IsWhiteSpace(c) && c != '\n')) ++end; else if (c != '\n') { cont = true; --end; } } lines.Add(description.Substring(start, end - start)); if (cont) { lines[lines.Count - 1] += "-"; } start = end; if (start < description.Length && description[start] == '\n') ++start; } while (end < description.Length); return lines; } private static int GetLineEnd(int start, int length, string description) { int end = Math.Min(start + length, description.Length); int sep = -1; for (int i = start; i < end; ++i) { switch (description[i]) { case ' ': case '\t': case '\v': case '-': case ',': case '.': case ';': sep = i; break; case '\n': return i; } } if (sep == -1 || end == description.Length) return end; return sep; } } }
//---------------------------------------------------------------------------- // 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 //---------------------------------------------------------------------------- #if true using MatterHackers.Agg.Image; using System; namespace MatterHackers.Agg { /* //========================================================line_image_scale public class line_image_scale { IImage m_source; double m_height; double m_scale; public line_image_scale(IImage src, double height) { m_source = (src); m_height = (height); m_scale = (src.height() / height); } public double width() { return m_source.width(); } public double height() { return m_height; } public RGBA_Bytes pixel(int x, int y) { double src_y = (y + 0.5) * m_scale - 0.5; int h = m_source.height() - 1; int y1 = ufloor(src_y); int y2 = y1 + 1; RGBA_Bytes pix1 = (y1 < 0) ? new no_color() : m_source.pixel(x, y1); RGBA_Bytes pix2 = (y2 > h) ? no_color() : m_source.pixel(x, y2); return pix1.gradient(pix2, src_y - y1); } }; */ //======================================================line_image_pattern public class line_image_pattern : ImageBuffer { private IPatternFilter m_filter; private int m_dilation; private int m_dilation_hr; private ImageBuffer m_buf = new ImageBuffer(); private byte[] m_data = null; private int m_DataSizeInBytes = 0; private int m_width; private int m_height; private int m_width_hr; private int m_half_height_hr; private int m_offset_y_hr; //-------------------------------------------------------------------- public line_image_pattern(IPatternFilter filter) { m_filter = filter; m_dilation = (filter.dilation() + 1); m_dilation_hr = (m_dilation << LineAABasics.line_subpixel_shift); m_width = (0); m_height = (0); m_width_hr = (0); m_half_height_hr = (0); m_offset_y_hr = (0); } ~line_image_pattern() { if (m_DataSizeInBytes > 0) { m_data = null; } } // Create //-------------------------------------------------------------------- public line_image_pattern(IPatternFilter filter, line_image_pattern src) { m_filter = (filter); m_dilation = (filter.dilation() + 1); m_dilation_hr = (m_dilation << LineAABasics.line_subpixel_shift); m_width = 0; m_height = 0; m_width_hr = 0; m_half_height_hr = 0; m_offset_y_hr = (0); create(src); } // Create //-------------------------------------------------------------------- public void create(IImageByte src) { // we are going to create a dialated image for filtering // we add m_dilation pixels to every side of the image and then copy the image in the x // dirrection into each end so that we can sample into this image to get filtering on x repeating // if the original image look like this // // 123456 // // the new image would look like this // // 0000000000 // 0000000000 // 5612345612 // 0000000000 // 0000000000 m_height = (int)agg_basics.uceil(src.Height); m_width = (int)agg_basics.uceil(src.Width); m_width_hr = (int)agg_basics.uround(src.Width * LineAABasics.line_subpixel_scale); m_half_height_hr = (int)agg_basics.uround(src.Height * LineAABasics.line_subpixel_scale / 2); m_offset_y_hr = m_dilation_hr + m_half_height_hr - LineAABasics.line_subpixel_scale / 2; m_half_height_hr += LineAABasics.line_subpixel_scale / 2; int bufferWidth = m_width + m_dilation * 2; int bufferHeight = m_height + m_dilation * 2; int bytesPerPixel = src.BitDepth / 8; int NewSizeInBytes = bufferWidth * bufferHeight * bytesPerPixel; if (m_DataSizeInBytes < NewSizeInBytes) { m_DataSizeInBytes = NewSizeInBytes; m_data = new byte[m_DataSizeInBytes]; } m_buf.AttachBuffer(m_data, 0, bufferWidth, bufferHeight, bufferWidth * bytesPerPixel, src.BitDepth, bytesPerPixel); byte[] destBuffer = m_buf.GetBuffer(); byte[] sourceBuffer = src.GetBuffer(); // copy the image into the middle of the dest for (int y = 0; y < m_height; y++) { for (int x = 0; x < m_width; x++) { int sourceOffset = src.GetBufferOffsetXY(x, y); int destOffset = m_buf.GetBufferOffsetXY(m_dilation, y + m_dilation); for (int channel = 0; channel < bytesPerPixel; channel++) { destBuffer[destOffset++] = sourceBuffer[sourceOffset++]; } } } // copy the first two pixels form the end into the begining and from the begining into the end for (int y = 0; y < m_height; y++) { int s1Offset = src.GetBufferOffsetXY(0, y); int d1Offset = m_buf.GetBufferOffsetXY(m_dilation + m_width, y); int s2Offset = src.GetBufferOffsetXY(m_width - m_dilation, y); int d2Offset = m_buf.GetBufferOffsetXY(0, y); for (int x = 0; x < m_dilation; x++) { for (int channel = 0; channel < bytesPerPixel; channel++) { destBuffer[d1Offset++] = sourceBuffer[s1Offset++]; destBuffer[d2Offset++] = sourceBuffer[s2Offset++]; } } } } //-------------------------------------------------------------------- public int pattern_width() { return m_width_hr; } public int line_width() { return m_half_height_hr; } public double width() { return m_height; } //-------------------------------------------------------------------- public void pixel(RGBA_Bytes[] destBuffer, int destBufferOffset, int x, int y) { m_filter.pixel_high_res(m_buf, destBuffer, destBufferOffset, x % m_width_hr + m_dilation_hr, y + m_offset_y_hr); } //-------------------------------------------------------------------- public IPatternFilter filter() { return m_filter; } }; /* //=================================================line_image_pattern_pow2 public class line_image_pattern_pow2 : line_image_pattern<IPatternFilter> { uint m_mask; //-------------------------------------------------------------------- public line_image_pattern_pow2(IPatternFilter filter) : line_image_pattern<IPatternFilter>(filter), m_mask(line_subpixel_mask) {} //-------------------------------------------------------------------- public line_image_pattern_pow2(IPatternFilter filter, ImageBuffer src) : line_image_pattern<IPatternFilter>(filter), m_mask(line_subpixel_mask) { create(src); } //-------------------------------------------------------------------- public void create(ImageBuffer src) { line_image_pattern<IPatternFilter>::create(src); m_mask = 1; while(m_mask < base_type::m_width) { m_mask <<= 1; m_mask |= 1; } m_mask <<= line_subpixel_shift - 1; m_mask |= line_subpixel_mask; base_type::m_width_hr = m_mask + 1; } //-------------------------------------------------------------------- public void pixel(RGBA_Bytes* p, int x, int y) { base_type::m_filter->pixel_high_res( base_type::m_buf.rows(), p, (x & m_mask) + base_type::m_dilation_hr, y + base_type::m_offset_y_hr); } }; */ //===================================================distance_interpolator4 public class distance_interpolator4 { private int m_dx; private int m_dy; private int m_dx_start; private int m_dy_start; private int m_dx_pict; private int m_dy_pict; private int m_dx_end; private int m_dy_end; private int m_dist; private int m_dist_start; private int m_dist_pict; private int m_dist_end; private int m_len; //--------------------------------------------------------------------- public distance_interpolator4() { } public distance_interpolator4(int x1, int y1, int x2, int y2, int sx, int sy, int ex, int ey, int len, double scale, int x, int y) { m_dx = (x2 - x1); m_dy = (y2 - y1); m_dx_start = (LineAABasics.line_mr(sx) - LineAABasics.line_mr(x1)); m_dy_start = (LineAABasics.line_mr(sy) - LineAABasics.line_mr(y1)); m_dx_end = (LineAABasics.line_mr(ex) - LineAABasics.line_mr(x2)); m_dy_end = (LineAABasics.line_mr(ey) - LineAABasics.line_mr(y2)); m_dist = (agg_basics.iround((double)(x + LineAABasics.line_subpixel_scale / 2 - x2) * (double)(m_dy) - (double)(y + LineAABasics.line_subpixel_scale / 2 - y2) * (double)(m_dx))); m_dist_start = ((LineAABasics.line_mr(x + LineAABasics.line_subpixel_scale / 2) - LineAABasics.line_mr(sx)) * m_dy_start - (LineAABasics.line_mr(y + LineAABasics.line_subpixel_scale / 2) - LineAABasics.line_mr(sy)) * m_dx_start); m_dist_end = ((LineAABasics.line_mr(x + LineAABasics.line_subpixel_scale / 2) - LineAABasics.line_mr(ex)) * m_dy_end - (LineAABasics.line_mr(y + LineAABasics.line_subpixel_scale / 2) - LineAABasics.line_mr(ey)) * m_dx_end); m_len = (int)(agg_basics.uround(len / scale)); double d = len * scale; int dx = agg_basics.iround(((x2 - x1) << LineAABasics.line_subpixel_shift) / d); int dy = agg_basics.iround(((y2 - y1) << LineAABasics.line_subpixel_shift) / d); m_dx_pict = -dy; m_dy_pict = dx; m_dist_pict = ((x + LineAABasics.line_subpixel_scale / 2 - (x1 - dy)) * m_dy_pict - (y + LineAABasics.line_subpixel_scale / 2 - (y1 + dx)) * m_dx_pict) >> LineAABasics.line_subpixel_shift; m_dx <<= LineAABasics.line_subpixel_shift; m_dy <<= LineAABasics.line_subpixel_shift; m_dx_start <<= LineAABasics.line_mr_subpixel_shift; m_dy_start <<= LineAABasics.line_mr_subpixel_shift; m_dx_end <<= LineAABasics.line_mr_subpixel_shift; m_dy_end <<= LineAABasics.line_mr_subpixel_shift; } //--------------------------------------------------------------------- public void inc_x() { m_dist += m_dy; m_dist_start += m_dy_start; m_dist_pict += m_dy_pict; m_dist_end += m_dy_end; } //--------------------------------------------------------------------- public void dec_x() { m_dist -= m_dy; m_dist_start -= m_dy_start; m_dist_pict -= m_dy_pict; m_dist_end -= m_dy_end; } //--------------------------------------------------------------------- public void inc_y() { m_dist -= m_dx; m_dist_start -= m_dx_start; m_dist_pict -= m_dx_pict; m_dist_end -= m_dx_end; } //--------------------------------------------------------------------- public void dec_y() { m_dist += m_dx; m_dist_start += m_dx_start; m_dist_pict += m_dx_pict; m_dist_end += m_dx_end; } //--------------------------------------------------------------------- public void inc_x(int dy) { m_dist += m_dy; m_dist_start += m_dy_start; m_dist_pict += m_dy_pict; m_dist_end += m_dy_end; if (dy > 0) { m_dist -= m_dx; m_dist_start -= m_dx_start; m_dist_pict -= m_dx_pict; m_dist_end -= m_dx_end; } if (dy < 0) { m_dist += m_dx; m_dist_start += m_dx_start; m_dist_pict += m_dx_pict; m_dist_end += m_dx_end; } } //--------------------------------------------------------------------- public void dec_x(int dy) { m_dist -= m_dy; m_dist_start -= m_dy_start; m_dist_pict -= m_dy_pict; m_dist_end -= m_dy_end; if (dy > 0) { m_dist -= m_dx; m_dist_start -= m_dx_start; m_dist_pict -= m_dx_pict; m_dist_end -= m_dx_end; } if (dy < 0) { m_dist += m_dx; m_dist_start += m_dx_start; m_dist_pict += m_dx_pict; m_dist_end += m_dx_end; } } //--------------------------------------------------------------------- public void inc_y(int dx) { m_dist -= m_dx; m_dist_start -= m_dx_start; m_dist_pict -= m_dx_pict; m_dist_end -= m_dx_end; if (dx > 0) { m_dist += m_dy; m_dist_start += m_dy_start; m_dist_pict += m_dy_pict; m_dist_end += m_dy_end; } if (dx < 0) { m_dist -= m_dy; m_dist_start -= m_dy_start; m_dist_pict -= m_dy_pict; m_dist_end -= m_dy_end; } } //--------------------------------------------------------------------- public void dec_y(int dx) { m_dist += m_dx; m_dist_start += m_dx_start; m_dist_pict += m_dx_pict; m_dist_end += m_dx_end; if (dx > 0) { m_dist += m_dy; m_dist_start += m_dy_start; m_dist_pict += m_dy_pict; m_dist_end += m_dy_end; } if (dx < 0) { m_dist -= m_dy; m_dist_start -= m_dy_start; m_dist_pict -= m_dy_pict; m_dist_end -= m_dy_end; } } //--------------------------------------------------------------------- public int dist() { return m_dist; } public int dist_start() { return m_dist_start; } public int dist_pict() { return m_dist_pict; } public int dist_end() { return m_dist_end; } //--------------------------------------------------------------------- public int dx() { return m_dx; } public int dy() { return m_dy; } public int dx_start() { return m_dx_start; } public int dy_start() { return m_dy_start; } public int dx_pict() { return m_dx_pict; } public int dy_pict() { return m_dy_pict; } public int dx_end() { return m_dx_end; } public int dy_end() { return m_dy_end; } public int len() { return m_len; } }; #if true #if false //==================================================line_interpolator_image public class line_interpolator_image { line_parameters m_lp; dda2_line_interpolator m_li; distance_interpolator4 m_di; IImageByte m_ren; int m_plen; int m_x; int m_y; int m_old_x; int m_old_y; int m_width; int m_max_extent; int m_start; int m_step; int[] m_dist_pos = new int[max_half_width + 1]; RGBA_Bytes[] m_colors = new RGBA_Bytes[max_half_width * 2 + 4]; //--------------------------------------------------------------------- public const int max_half_width = 64; //--------------------------------------------------------------------- public line_interpolator_image(renderer_outline_aa ren, line_parameters lp, int sx, int sy, int ex, int ey, int pattern_start, double scale_x) { throw new NotImplementedException(); /* m_lp=(lp); m_li = new dda2_line_interpolator(lp.vertical ? LineAABasics.line_dbl_hr(lp.x2 - lp.x1) : LineAABasics.line_dbl_hr(lp.y2 - lp.y1), lp.vertical ? Math.Abs(lp.y2 - lp.y1) : Math.Abs(lp.x2 - lp.x1) + 1); m_di = new distance_interpolator4(lp.x1, lp.y1, lp.x2, lp.y2, sx, sy, ex, ey, lp.len, scale_x, lp.x1 & ~LineAABasics.line_subpixel_mask, lp.y1 & ~LineAABasics.line_subpixel_mask); m_ren=ren; m_x = (lp.x1 >> LineAABasics.line_subpixel_shift); m_y = (lp.y1 >> LineAABasics.line_subpixel_shift); m_old_x=(m_x); m_old_y=(m_y); m_count = ((lp.vertical ? Math.Abs((lp.y2 >> LineAABasics.line_subpixel_shift) - m_y) : Math.Abs((lp.x2 >> LineAABasics.line_subpixel_shift) - m_x))); m_width=(ren.subpixel_width()); //m_max_extent(m_width >> (LineAABasics.line_subpixel_shift - 2)); m_max_extent = ((m_width + LineAABasics.line_subpixel_scale) >> LineAABasics.line_subpixel_shift); m_start=(pattern_start + (m_max_extent + 2) * ren.pattern_width()); m_step=(0); dda2_line_interpolator li = new dda2_line_interpolator(0, lp.vertical ? (lp.dy << LineAABasics.line_subpixel_shift) : (lp.dx << LineAABasics.line_subpixel_shift), lp.len); uint i; int stop = m_width + LineAABasics.line_subpixel_scale * 2; for(i = 0; i < max_half_width; ++i) { m_dist_pos[i] = li.y(); if(m_dist_pos[i] >= stop) break; ++li; } m_dist_pos[i] = 0x7FFF0000; int dist1_start; int dist2_start; int npix = 1; if(lp.vertical) { do { --m_li; m_y -= lp.inc; m_x = (m_lp.x1 + m_li.y()) >> LineAABasics.line_subpixel_shift; if(lp.inc > 0) m_di.dec_y(m_x - m_old_x); else m_di.inc_y(m_x - m_old_x); m_old_x = m_x; dist1_start = dist2_start = m_di.dist_start(); int dx = 0; if(dist1_start < 0) ++npix; do { dist1_start += m_di.dy_start(); dist2_start -= m_di.dy_start(); if(dist1_start < 0) ++npix; if(dist2_start < 0) ++npix; ++dx; } while(m_dist_pos[dx] <= m_width); if(npix == 0) break; npix = 0; } while(--m_step >= -m_max_extent); } else { do { --m_li; m_x -= lp.inc; m_y = (m_lp.y1 + m_li.y()) >> LineAABasics.line_subpixel_shift; if(lp.inc > 0) m_di.dec_x(m_y - m_old_y); else m_di.inc_x(m_y - m_old_y); m_old_y = m_y; dist1_start = dist2_start = m_di.dist_start(); int dy = 0; if(dist1_start < 0) ++npix; do { dist1_start -= m_di.dx_start(); dist2_start += m_di.dx_start(); if(dist1_start < 0) ++npix; if(dist2_start < 0) ++npix; ++dy; } while(m_dist_pos[dy] <= m_width); if(npix == 0) break; npix = 0; } while(--m_step >= -m_max_extent); } m_li.adjust_forward(); m_step -= m_max_extent; */ } //--------------------------------------------------------------------- public bool step_hor() { throw new NotImplementedException(); /* ++m_li; m_x += m_lp.inc; m_y = (m_lp.y1 + m_li.y()) >> LineAABasics.line_subpixel_shift; if(m_lp.inc > 0) m_di.inc_x(m_y - m_old_y); else m_di.dec_x(m_y - m_old_y); m_old_y = m_y; int s1 = m_di.dist() / m_lp.len; int s2 = -s1; if(m_lp.inc < 0) s1 = -s1; int dist_start; int dist_pict; int dist_end; int dy; int dist; dist_start = m_di.dist_start(); dist_pict = m_di.dist_pict() + m_start; dist_end = m_di.dist_end(); RGBA_Bytes* p0 = m_colors + max_half_width + 2; RGBA_Bytes* p1 = p0; int npix = 0; p1->clear(); if(dist_end > 0) { if(dist_start <= 0) { m_ren.pixel(p1, dist_pict, s2); } ++npix; } ++p1; dy = 1; while((dist = m_dist_pos[dy]) - s1 <= m_width) { dist_start -= m_di.dx_start(); dist_pict -= m_di.dx_pict(); dist_end -= m_di.dx_end(); p1->clear(); if(dist_end > 0 && dist_start <= 0) { if(m_lp.inc > 0) dist = -dist; m_ren.pixel(p1, dist_pict, s2 - dist); ++npix; } ++p1; ++dy; } dy = 1; dist_start = m_di.dist_start(); dist_pict = m_di.dist_pict() + m_start; dist_end = m_di.dist_end(); while((dist = m_dist_pos[dy]) + s1 <= m_width) { dist_start += m_di.dx_start(); dist_pict += m_di.dx_pict(); dist_end += m_di.dx_end(); --p0; p0->clear(); if(dist_end > 0 && dist_start <= 0) { if(m_lp.inc > 0) dist = -dist; m_ren.pixel(p0, dist_pict, s2 + dist); ++npix; } ++dy; } m_ren.blend_color_vspan(m_x, m_y - dy + 1, (uint)(p1 - p0), p0); return npix && ++m_step < m_count; */ } //--------------------------------------------------------------------- public bool step_ver() { throw new NotImplementedException(); /* ++m_li; m_y += m_lp.inc; m_x = (m_lp.x1 + m_li.y()) >> LineAABasics.line_subpixel_shift; if(m_lp.inc > 0) m_di.inc_y(m_x - m_old_x); else m_di.dec_y(m_x - m_old_x); m_old_x = m_x; int s1 = m_di.dist() / m_lp.len; int s2 = -s1; if(m_lp.inc > 0) s1 = -s1; int dist_start; int dist_pict; int dist_end; int dist; int dx; dist_start = m_di.dist_start(); dist_pict = m_di.dist_pict() + m_start; dist_end = m_di.dist_end(); RGBA_Bytes* p0 = m_colors + max_half_width + 2; RGBA_Bytes* p1 = p0; int npix = 0; p1->clear(); if(dist_end > 0) { if(dist_start <= 0) { m_ren.pixel(p1, dist_pict, s2); } ++npix; } ++p1; dx = 1; while((dist = m_dist_pos[dx]) - s1 <= m_width) { dist_start += m_di.dy_start(); dist_pict += m_di.dy_pict(); dist_end += m_di.dy_end(); p1->clear(); if(dist_end > 0 && dist_start <= 0) { if(m_lp.inc > 0) dist = -dist; m_ren.pixel(p1, dist_pict, s2 + dist); ++npix; } ++p1; ++dx; } dx = 1; dist_start = m_di.dist_start(); dist_pict = m_di.dist_pict() + m_start; dist_end = m_di.dist_end(); while((dist = m_dist_pos[dx]) + s1 <= m_width) { dist_start -= m_di.dy_start(); dist_pict -= m_di.dy_pict(); dist_end -= m_di.dy_end(); --p0; p0->clear(); if(dist_end > 0 && dist_start <= 0) { if(m_lp.inc > 0) dist = -dist; m_ren.pixel(p0, dist_pict, s2 - dist); ++npix; } ++dx; } m_ren.blend_color_hspan(m_x - dx + 1, m_y, (uint)(p1 - p0), p0); return npix && ++m_step < m_count; */ } //--------------------------------------------------------------------- public int pattern_end() { return m_start + m_di.len(); } //--------------------------------------------------------------------- public bool vertical() { return m_lp.vertical; } public int width() { return m_width; } } #endif //===================================================renderer_outline_image //template<class BaseRenderer, class ImagePattern> public class ImageLineRenderer : LineRenderer { private IImageByte m_ren; private line_image_pattern m_pattern; private int m_start; private double m_scale_x; private RectangleInt m_clip_box; private bool m_clipping; //--------------------------------------------------------------------- //typedef renderer_outline_image<BaseRenderer, ImagePattern> self_type; //--------------------------------------------------------------------- public ImageLineRenderer(IImageByte ren, line_image_pattern patt) { m_ren = ren; m_pattern = patt; m_start = (0); m_scale_x = (1.0); m_clip_box = new RectangleInt(0, 0, 0, 0); m_clipping = (false); } public void attach(IImageByte ren) { m_ren = ren; } //--------------------------------------------------------------------- public void pattern(line_image_pattern p) { m_pattern = p; } public line_image_pattern pattern() { return m_pattern; } //--------------------------------------------------------------------- public void reset_clipping() { m_clipping = false; } public void clip_box(double x1, double y1, double x2, double y2) { m_clip_box.Left = line_coord_sat.conv(x1); m_clip_box.Bottom = line_coord_sat.conv(y1); m_clip_box.Right = line_coord_sat.conv(x2); m_clip_box.Top = line_coord_sat.conv(y2); m_clipping = true; } //--------------------------------------------------------------------- public void scale_x(double s) { m_scale_x = s; } public double scale_x() { return m_scale_x; } //--------------------------------------------------------------------- public void start_x(double s) { m_start = agg_basics.iround(s * LineAABasics.line_subpixel_scale); } public double start_x() { return (double)(m_start) / LineAABasics.line_subpixel_scale; } //--------------------------------------------------------------------- public int subpixel_width() { return m_pattern.line_width(); } public int pattern_width() { return m_pattern.pattern_width(); } public double width() { return (double)(subpixel_width()) / LineAABasics.line_subpixel_scale; } public void pixel(RGBA_Bytes[] p, int offset, int x, int y) { throw new NotImplementedException(); //m_pattern.pixel(p, x, y); } public void blend_color_hspan(int x, int y, uint len, RGBA_Bytes[] colors, int colorsOffset) { throw new NotImplementedException(); // m_ren.blend_color_hspan(x, y, len, colors, null, 0); } public void blend_color_vspan(int x, int y, uint len, RGBA_Bytes[] colors, int colorsOffset) { throw new NotImplementedException(); // m_ren.blend_color_vspan(x, y, len, colors, null, 0); } public static bool accurate_join_only() { return true; } public override void semidot(CompareFunction cmp, int xc1, int yc1, int xc2, int yc2) { } public override void semidot_hline(CompareFunction cmp, int xc1, int yc1, int xc2, int yc2, int x1, int y1, int x2) { } public override void pie(int xc, int yc, int x1, int y1, int x2, int y2) { } public override void line0(line_parameters lp) { } public override void line1(line_parameters lp, int sx, int sy) { } public override void line2(line_parameters lp, int ex, int ey) { } public void line3_no_clip(line_parameters lp, int sx, int sy, int ex, int ey) { throw new NotImplementedException(); /* if(lp.len > LineAABasics.line_max_length) { line_parameters lp1, lp2; lp.divide(lp1, lp2); int mx = lp1.x2 + (lp1.y2 - lp1.y1); int my = lp1.y2 - (lp1.x2 - lp1.x1); line3_no_clip(lp1, (lp.x1 + sx) >> 1, (lp.y1 + sy) >> 1, mx, my); line3_no_clip(lp2, mx, my, (lp.x2 + ex) >> 1, (lp.y2 + ey) >> 1); return; } LineAABasics.fix_degenerate_bisectrix_start(lp, ref sx, ref sy); LineAABasics.fix_degenerate_bisectrix_end(lp, ref ex, ref ey); line_interpolator_image li = new line_interpolator_image(this, lp, sx, sy, ex, ey, m_start, m_scale_x); if(li.vertical()) { while(li.step_ver()); } else { while(li.step_hor()); } m_start += uround(lp.len / m_scale_x); */ } public override void line3(line_parameters lp, int sx, int sy, int ex, int ey) { throw new NotImplementedException(); /* if(m_clipping) { int x1 = lp.x1; int y1 = lp.y1; int x2 = lp.x2; int y2 = lp.y2; uint flags = clip_line_segment(&x1, &y1, &x2, &y2, m_clip_box); int start = m_start; if((flags & 4) == 0) { if(flags) { line_parameters lp2(x1, y1, x2, y2, uround(calc_distance(x1, y1, x2, y2))); if(flags & 1) { m_start += uround(calc_distance(lp.x1, lp.y1, x1, y1) / m_scale_x); sx = x1 + (y2 - y1); sy = y1 - (x2 - x1); } else { while(Math.Abs(sx - lp.x1) + Math.Abs(sy - lp.y1) > lp2.len) { sx = (lp.x1 + sx) >> 1; sy = (lp.y1 + sy) >> 1; } } if(flags & 2) { ex = x2 + (y2 - y1); ey = y2 - (x2 - x1); } else { while(Math.Abs(ex - lp.x2) + Math.Abs(ey - lp.y2) > lp2.len) { ex = (lp.x2 + ex) >> 1; ey = (lp.y2 + ey) >> 1; } } line3_no_clip(lp2, sx, sy, ex, ey); } else { line3_no_clip(lp, sx, sy, ex, ey); } } m_start = start + uround(lp.len / m_scale_x); } else { line3_no_clip(lp, sx, sy, ex, ey); } */ } }; #endif } #endif
/* * Copyright 2008 ZXing 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. */ using System; using System.Collections.Generic; using System.Text; using ZXing.Common; using ZXing.Common.ReedSolomon; namespace ZXing.QrCode.Internal { /// <summary> /// </summary> /// <author>satorux@google.com (Satoru Takabayashi) - creator</author> /// <author>dswitkin@google.com (Daniel Switkin) - ported from C++</author> public static class Encoder { // The original table is defined in the table 5 of JISX0510:2004 (p.19). private static readonly int[] ALPHANUMERIC_TABLE = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 0x00-0x0f -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 0x10-0x1f 36, -1, -1, -1, 37, 38, -1, -1, -1, -1, 39, 40, -1, 41, 42, 43, // 0x20-0x2f 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 44, -1, -1, -1, -1, -1, // 0x30-0x3f -1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, // 0x40-0x4f 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, -1, -1, -1, -1, -1, // 0x50-0x5f }; internal static String DEFAULT_BYTE_MODE_ENCODING = "ISO-8859-1"; // The mask penalty calculation is complicated. See Table 21 of JISX0510:2004 (p.45) for details. // Basically it applies four rules and summate all penalties. private static int calculateMaskPenalty(ByteMatrix matrix) { return MaskUtil.applyMaskPenaltyRule1(matrix) + MaskUtil.applyMaskPenaltyRule2(matrix) + MaskUtil.applyMaskPenaltyRule3(matrix) + MaskUtil.applyMaskPenaltyRule4(matrix); } /// <summary> /// Encode "bytes" with the error correction level "ecLevel". The encoding mode will be chosen /// internally by chooseMode(). On success, store the result in "qrCode". /// We recommend you to use QRCode.EC_LEVEL_L (the lowest level) for /// "getECLevel" since our primary use is to show QR code on desktop screens. We don't need very /// strong error correction for this purpose. /// Note that there is no way to encode bytes in MODE_KANJI. We might want to add EncodeWithMode() /// with which clients can specify the encoding mode. For now, we don't need the functionality. /// </summary> /// <param name="content">text to encode</param> /// <param name="ecLevel">error correction level to use</param> /// <returns><see cref="QRCode"/> representing the encoded QR code</returns> public static QRCode encode(String content, ErrorCorrectionLevel ecLevel) { return encode(content, ecLevel, null); } /// <summary> /// Encodes the specified content. /// </summary> /// <param name="content">The content.</param> /// <param name="ecLevel">The ec level.</param> /// <param name="hints">The hints.</param> /// <returns></returns> public static QRCode encode(String content, ErrorCorrectionLevel ecLevel, IDictionary<EncodeHintType, object> hints) { // Determine what character encoding has been specified by the caller, if any #if !SILVERLIGHT || WINDOWS_PHONE String encoding = hints == null || !hints.ContainsKey(EncodeHintType.CHARACTER_SET) ? null : (String)hints[EncodeHintType.CHARACTER_SET]; if (encoding == null) { encoding = DEFAULT_BYTE_MODE_ENCODING; } bool generateECI = !DEFAULT_BYTE_MODE_ENCODING.Equals(encoding); #else // Silverlight supports only UTF-8 and UTF-16 out-of-the-box const string encoding = "UTF-8"; // caller of the method can only control if the ECI segment should be written // character set is fixed to UTF-8; but some scanners doesn't like the ECI segment bool generateECI = (hints != null && hints.ContainsKey(EncodeHintType.CHARACTER_SET)); #endif // Pick an encoding mode appropriate for the content. Note that this will not attempt to use // multiple modes / segments even if that were more efficient. Twould be nice. Mode mode = chooseMode(content, encoding); // This will store the header information, like mode and // length, as well as "header" segments like an ECI segment. BitArray headerBits = new BitArray(); // Append ECI segment if applicable if (mode == Mode.BYTE && generateECI) { CharacterSetECI eci = CharacterSetECI.getCharacterSetECIByName(encoding); if (eci != null) { var eciIsExplicitDisabled = (hints != null && hints.ContainsKey(EncodeHintType.DISABLE_ECI) ? (bool)hints[EncodeHintType.DISABLE_ECI] : false); if (!eciIsExplicitDisabled) { appendECI(eci, headerBits); } } } // (With ECI in place,) Write the mode marker appendModeInfo(mode, headerBits); // Collect data within the main segment, separately, to count its size if needed. Don't add it to // main payload yet. BitArray dataBits = new BitArray(); appendBytes(content, mode, dataBits, encoding); // Hard part: need to know version to know how many bits length takes. But need to know how many // bits it takes to know version. First we take a guess at version by assuming version will be // the minimum, 1: int provisionalBitsNeeded = headerBits.Size + mode.getCharacterCountBits(Version.getVersionForNumber(1)) + dataBits.Size; Version provisionalVersion = chooseVersion(provisionalBitsNeeded, ecLevel); // Use that guess to calculate the right version. I am still not sure this works in 100% of cases. int bitsNeeded = headerBits.Size + mode.getCharacterCountBits(provisionalVersion) + dataBits.Size; Version version = chooseVersion(bitsNeeded, ecLevel); BitArray headerAndDataBits = new BitArray(); headerAndDataBits.appendBitArray(headerBits); // Find "length" of main segment and write it int numLetters = mode == Mode.BYTE ? dataBits.SizeInBytes : content.Length; appendLengthInfo(numLetters, version, mode, headerAndDataBits); // Put data together into the overall payload headerAndDataBits.appendBitArray(dataBits); Version.ECBlocks ecBlocks = version.getECBlocksForLevel(ecLevel); int numDataBytes = version.TotalCodewords - ecBlocks.TotalECCodewords; // Terminate the bits properly. terminateBits(numDataBytes, headerAndDataBits); // Interleave data bits with error correction code. BitArray finalBits = interleaveWithECBytes(headerAndDataBits, version.TotalCodewords, numDataBytes, ecBlocks.NumBlocks); QRCode qrCode = new QRCode { ECLevel = ecLevel, Mode = mode, Version = version }; // Choose the mask pattern and set to "qrCode". int dimension = version.DimensionForVersion; ByteMatrix matrix = new ByteMatrix(dimension, dimension); int maskPattern = chooseMaskPattern(finalBits, ecLevel, version, matrix); qrCode.MaskPattern = maskPattern; // Build the matrix and set it to "qrCode". MatrixUtil.buildMatrix(finalBits, ecLevel, version, maskPattern, matrix); qrCode.Matrix = matrix; return qrCode; } /// <summary> /// Gets the alphanumeric code. /// </summary> /// <param name="code">The code.</param> /// <returns>the code point of the table used in alphanumeric mode or /// -1 if there is no corresponding code in the table.</returns> internal static int getAlphanumericCode(int code) { if (code < ALPHANUMERIC_TABLE.Length) { return ALPHANUMERIC_TABLE[code]; } return -1; } /// <summary> /// Chooses the mode. /// </summary> /// <param name="content">The content.</param> /// <returns></returns> public static Mode chooseMode(String content) { return chooseMode(content, null); } /// <summary> /// Choose the best mode by examining the content. Note that 'encoding' is used as a hint; /// if it is Shift_JIS, and the input is only double-byte Kanji, then we return {@link Mode#KANJI}. /// </summary> /// <param name="content">The content.</param> /// <param name="encoding">The encoding.</param> /// <returns></returns> private static Mode chooseMode(String content, String encoding) { if ("Shift_JIS".Equals(encoding)) { // Choose Kanji mode if all input are double-byte characters return isOnlyDoubleByteKanji(content) ? Mode.KANJI : Mode.BYTE; } bool hasNumeric = false; bool hasAlphanumeric = false; for (int i = 0; i < content.Length; ++i) { char c = content[i]; if (c >= '0' && c <= '9') { hasNumeric = true; } else if (getAlphanumericCode(c) != -1) { hasAlphanumeric = true; } else { return Mode.BYTE; } } if (hasAlphanumeric) { return Mode.ALPHANUMERIC; } if (hasNumeric) { return Mode.NUMERIC; } return Mode.BYTE; } private static bool isOnlyDoubleByteKanji(String content) { byte[] bytes; try { bytes = Encoding.GetEncoding("Shift_JIS").GetBytes(content); } catch (Exception ) { return false; } int length = bytes.Length; if (length % 2 != 0) { return false; } for (int i = 0; i < length; i += 2) { int byte1 = bytes[i] & 0xFF; if ((byte1 < 0x81 || byte1 > 0x9F) && (byte1 < 0xE0 || byte1 > 0xEB)) { return false; } } return true; } private static int chooseMaskPattern(BitArray bits, ErrorCorrectionLevel ecLevel, Version version, ByteMatrix matrix) { int minPenalty = Int32.MaxValue; // Lower penalty is better. int bestMaskPattern = -1; // We try all mask patterns to choose the best one. for (int maskPattern = 0; maskPattern < QRCode.NUM_MASK_PATTERNS; maskPattern++) { MatrixUtil.buildMatrix(bits, ecLevel, version, maskPattern, matrix); int penalty = calculateMaskPenalty(matrix); if (penalty < minPenalty) { minPenalty = penalty; bestMaskPattern = maskPattern; } } return bestMaskPattern; } private static Version chooseVersion(int numInputBits, ErrorCorrectionLevel ecLevel) { // In the following comments, we use numbers of Version 7-H. for (int versionNum = 1; versionNum <= 40; versionNum++) { Version version = Version.getVersionForNumber(versionNum); // numBytes = 196 int numBytes = version.TotalCodewords; // getNumECBytes = 130 Version.ECBlocks ecBlocks = version.getECBlocksForLevel(ecLevel); int numEcBytes = ecBlocks.TotalECCodewords; // getNumDataBytes = 196 - 130 = 66 int numDataBytes = numBytes - numEcBytes; int totalInputBytes = (numInputBits + 7) / 8; if (numDataBytes >= totalInputBytes) { return version; } } throw new WriterException("Data too big"); } /// <summary> /// Terminate bits as described in 8.4.8 and 8.4.9 of JISX0510:2004 (p.24). /// </summary> /// <param name="numDataBytes">The num data bytes.</param> /// <param name="bits">The bits.</param> internal static void terminateBits(int numDataBytes, BitArray bits) { int capacity = numDataBytes << 3; if (bits.Size > capacity) { throw new WriterException("data bits cannot fit in the QR Code" + bits.Size + " > " + capacity); } for (int i = 0; i < 4 && bits.Size < capacity; ++i) { bits.appendBit(false); } // Append termination bits. See 8.4.8 of JISX0510:2004 (p.24) for details. // If the last byte isn't 8-bit aligned, we'll add padding bits. int numBitsInLastByte = bits.Size & 0x07; if (numBitsInLastByte > 0) { for (int i = numBitsInLastByte; i < 8; i++) { bits.appendBit(false); } } // If we have more space, we'll fill the space with padding patterns defined in 8.4.9 (p.24). int numPaddingBytes = numDataBytes - bits.SizeInBytes; for (int i = 0; i < numPaddingBytes; ++i) { bits.appendBits((i & 0x01) == 0 ? 0xEC : 0x11, 8); } if (bits.Size != capacity) { throw new WriterException("Bits size does not equal capacity"); } } /// <summary> /// Get number of data bytes and number of error correction bytes for block id "blockID". Store /// the result in "numDataBytesInBlock", and "numECBytesInBlock". See table 12 in 8.5.1 of /// JISX0510:2004 (p.30) /// </summary> /// <param name="numTotalBytes">The num total bytes.</param> /// <param name="numDataBytes">The num data bytes.</param> /// <param name="numRSBlocks">The num RS blocks.</param> /// <param name="blockID">The block ID.</param> /// <param name="numDataBytesInBlock">The num data bytes in block.</param> /// <param name="numECBytesInBlock">The num EC bytes in block.</param> internal static void getNumDataBytesAndNumECBytesForBlockID(int numTotalBytes, int numDataBytes, int numRSBlocks, int blockID, int[] numDataBytesInBlock, int[] numECBytesInBlock) { if (blockID >= numRSBlocks) { throw new WriterException("Block ID too large"); } // numRsBlocksInGroup2 = 196 % 5 = 1 int numRsBlocksInGroup2 = numTotalBytes % numRSBlocks; // numRsBlocksInGroup1 = 5 - 1 = 4 int numRsBlocksInGroup1 = numRSBlocks - numRsBlocksInGroup2; // numTotalBytesInGroup1 = 196 / 5 = 39 int numTotalBytesInGroup1 = numTotalBytes / numRSBlocks; // numTotalBytesInGroup2 = 39 + 1 = 40 int numTotalBytesInGroup2 = numTotalBytesInGroup1 + 1; // numDataBytesInGroup1 = 66 / 5 = 13 int numDataBytesInGroup1 = numDataBytes / numRSBlocks; // numDataBytesInGroup2 = 13 + 1 = 14 int numDataBytesInGroup2 = numDataBytesInGroup1 + 1; // numEcBytesInGroup1 = 39 - 13 = 26 int numEcBytesInGroup1 = numTotalBytesInGroup1 - numDataBytesInGroup1; // numEcBytesInGroup2 = 40 - 14 = 26 int numEcBytesInGroup2 = numTotalBytesInGroup2 - numDataBytesInGroup2; // Sanity checks. // 26 = 26 if (numEcBytesInGroup1 != numEcBytesInGroup2) { throw new WriterException("EC bytes mismatch"); } // 5 = 4 + 1. if (numRSBlocks != numRsBlocksInGroup1 + numRsBlocksInGroup2) { throw new WriterException("RS blocks mismatch"); } // 196 = (13 + 26) * 4 + (14 + 26) * 1 if (numTotalBytes != ((numDataBytesInGroup1 + numEcBytesInGroup1) * numRsBlocksInGroup1) + ((numDataBytesInGroup2 + numEcBytesInGroup2) * numRsBlocksInGroup2)) { throw new WriterException("Total bytes mismatch"); } if (blockID < numRsBlocksInGroup1) { numDataBytesInBlock[0] = numDataBytesInGroup1; numECBytesInBlock[0] = numEcBytesInGroup1; } else { numDataBytesInBlock[0] = numDataBytesInGroup2; numECBytesInBlock[0] = numEcBytesInGroup2; } } /// <summary> /// Interleave "bits" with corresponding error correction bytes. On success, store the result in /// "result". The interleave rule is complicated. See 8.6 of JISX0510:2004 (p.37) for details. /// </summary> /// <param name="bits">The bits.</param> /// <param name="numTotalBytes">The num total bytes.</param> /// <param name="numDataBytes">The num data bytes.</param> /// <param name="numRSBlocks">The num RS blocks.</param> /// <returns></returns> internal static BitArray interleaveWithECBytes(BitArray bits, int numTotalBytes, int numDataBytes, int numRSBlocks) { // "bits" must have "getNumDataBytes" bytes of data. if (bits.SizeInBytes != numDataBytes) { throw new WriterException("Number of bits and data bytes does not match"); } // Step 1. Divide data bytes into blocks and generate error correction bytes for them. We'll // store the divided data bytes blocks and error correction bytes blocks into "blocks". int dataBytesOffset = 0; int maxNumDataBytes = 0; int maxNumEcBytes = 0; // Since, we know the number of reedsolmon blocks, we can initialize the vector with the number. var blocks = new List<BlockPair>(numRSBlocks); for (int i = 0; i < numRSBlocks; ++i) { int[] numDataBytesInBlock = new int[1]; int[] numEcBytesInBlock = new int[1]; getNumDataBytesAndNumECBytesForBlockID( numTotalBytes, numDataBytes, numRSBlocks, i, numDataBytesInBlock, numEcBytesInBlock); int size = numDataBytesInBlock[0]; byte[] dataBytes = new byte[size]; bits.toBytes(8 * dataBytesOffset, dataBytes, 0, size); byte[] ecBytes = generateECBytes(dataBytes, numEcBytesInBlock[0]); blocks.Add(new BlockPair(dataBytes, ecBytes)); maxNumDataBytes = Math.Max(maxNumDataBytes, size); maxNumEcBytes = Math.Max(maxNumEcBytes, ecBytes.Length); dataBytesOffset += numDataBytesInBlock[0]; } if (numDataBytes != dataBytesOffset) { throw new WriterException("Data bytes does not match offset"); } BitArray result = new BitArray(); // First, place data blocks. for (int i = 0; i < maxNumDataBytes; ++i) { foreach (BlockPair block in blocks) { byte[] dataBytes = block.DataBytes; if (i < dataBytes.Length) { result.appendBits(dataBytes[i], 8); } } } // Then, place error correction blocks. for (int i = 0; i < maxNumEcBytes; ++i) { foreach (BlockPair block in blocks) { byte[] ecBytes = block.ErrorCorrectionBytes; if (i < ecBytes.Length) { result.appendBits(ecBytes[i], 8); } } } if (numTotalBytes != result.SizeInBytes) { // Should be same. throw new WriterException("Interleaving error: " + numTotalBytes + " and " + result.SizeInBytes + " differ."); } return result; } internal static byte[] generateECBytes(byte[] dataBytes, int numEcBytesInBlock) { int numDataBytes = dataBytes.Length; int[] toEncode = new int[numDataBytes + numEcBytesInBlock]; for (int i = 0; i < numDataBytes; i++) { toEncode[i] = dataBytes[i] & 0xFF; } new ReedSolomonEncoder(GenericGF.QR_CODE_FIELD_256).encode(toEncode, numEcBytesInBlock); byte[] ecBytes = new byte[numEcBytesInBlock]; for (int i = 0; i < numEcBytesInBlock; i++) { ecBytes[i] = (byte)toEncode[numDataBytes + i]; } return ecBytes; } /// <summary> /// Append mode info. On success, store the result in "bits". /// </summary> /// <param name="mode">The mode.</param> /// <param name="bits">The bits.</param> internal static void appendModeInfo(Mode mode, BitArray bits) { bits.appendBits(mode.Bits, 4); } /// <summary> /// Append length info. On success, store the result in "bits". /// </summary> /// <param name="numLetters">The num letters.</param> /// <param name="version">The version.</param> /// <param name="mode">The mode.</param> /// <param name="bits">The bits.</param> internal static void appendLengthInfo(int numLetters, Version version, Mode mode, BitArray bits) { int numBits = mode.getCharacterCountBits(version); if (numLetters >= (1 << numBits)) { throw new WriterException(numLetters + " is bigger than " + ((1 << numBits) - 1)); } bits.appendBits(numLetters, numBits); } /// <summary> /// Append "bytes" in "mode" mode (encoding) into "bits". On success, store the result in "bits". /// </summary> /// <param name="content">The content.</param> /// <param name="mode">The mode.</param> /// <param name="bits">The bits.</param> /// <param name="encoding">The encoding.</param> internal static void appendBytes(String content, Mode mode, BitArray bits, String encoding) { if (mode.Equals(Mode.NUMERIC)) appendNumericBytes(content, bits); else if (mode.Equals(Mode.ALPHANUMERIC)) appendAlphanumericBytes(content, bits); else if (mode.Equals(Mode.BYTE)) append8BitBytes(content, bits, encoding); else if (mode.Equals(Mode.KANJI)) appendKanjiBytes(content, bits); else throw new WriterException("Invalid mode: " + mode); } internal static void appendNumericBytes(String content, BitArray bits) { int length = content.Length; int i = 0; while (i < length) { int num1 = content[i] - '0'; if (i + 2 < length) { // Encode three numeric letters in ten bits. int num2 = content[i + 1] - '0'; int num3 = content[i + 2] - '0'; bits.appendBits(num1 * 100 + num2 * 10 + num3, 10); i += 3; } else if (i + 1 < length) { // Encode two numeric letters in seven bits. int num2 = content[i + 1] - '0'; bits.appendBits(num1 * 10 + num2, 7); i += 2; } else { // Encode one numeric letter in four bits. bits.appendBits(num1, 4); i++; } } } internal static void appendAlphanumericBytes(String content, BitArray bits) { int length = content.Length; int i = 0; while (i < length) { int code1 = getAlphanumericCode(content[i]); if (code1 == -1) { throw new WriterException(); } if (i + 1 < length) { int code2 = getAlphanumericCode(content[i + 1]); if (code2 == -1) { throw new WriterException(); } // Encode two alphanumeric letters in 11 bits. bits.appendBits(code1 * 45 + code2, 11); i += 2; } else { // Encode one alphanumeric letter in six bits. bits.appendBits(code1, 6); i++; } } } internal static void append8BitBytes(String content, BitArray bits, String encoding) { byte[] bytes; try { bytes = Encoding.GetEncoding(encoding).GetBytes(content); } #if WindowsCE catch (PlatformNotSupportedException) { try { // WindowsCE doesn't support all encodings. But it is device depended. // So we try here the some different ones if (encoding == "ISO-8859-1") { bytes = Encoding.GetEncoding(1252).GetBytes(content); } else { bytes = Encoding.GetEncoding("UTF-8").GetBytes(content); } } catch (Exception uee) { throw new WriterException(uee.Message, uee); } } #endif catch (Exception uee) { throw new WriterException(uee.Message, uee); } foreach (byte b in bytes) { bits.appendBits(b, 8); } } internal static void appendKanjiBytes(String content, BitArray bits) { byte[] bytes; try { bytes = Encoding.GetEncoding("Shift_JIS").GetBytes(content); } catch (Exception uee) { throw new WriterException(uee.Message, uee); } int length = bytes.Length; for (int i = 0; i < length; i += 2) { int byte1 = bytes[i] & 0xFF; int byte2 = bytes[i + 1] & 0xFF; int code = (byte1 << 8) | byte2; int subtracted = -1; if (code >= 0x8140 && code <= 0x9ffc) { subtracted = code - 0x8140; } else if (code >= 0xe040 && code <= 0xebbf) { subtracted = code - 0xc140; } if (subtracted == -1) { throw new WriterException("Invalid byte sequence"); } int encoded = ((subtracted >> 8) * 0xc0) + (subtracted & 0xff); bits.appendBits(encoded, 13); } } private static void appendECI(CharacterSetECI eci, BitArray bits) { bits.appendBits(Mode.ECI.Bits, 4); // This is correct for values up to 127, which is all we need now. bits.appendBits(eci.Value, 8); } } }
// // 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; using Microsoft.WindowsAzure; namespace Microsoft.Azure.Management.Resources { public static partial class ResourceOperationsExtensions { /// <summary> /// Checks whether resource exists. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Resources.IResourceOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. The name is case /// insensitive. /// </param> /// <param name='identity'> /// Required. Resource identity. /// </param> /// <returns> /// Resource group information. /// </returns> public static ResourceExistsResult CheckExistence(this IResourceOperations operations, string resourceGroupName, ResourceIdentity identity) { return Task.Factory.StartNew((object s) => { return ((IResourceOperations)s).CheckExistenceAsync(resourceGroupName, identity); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Checks whether resource exists. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Resources.IResourceOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. The name is case /// insensitive. /// </param> /// <param name='identity'> /// Required. Resource identity. /// </param> /// <returns> /// Resource group information. /// </returns> public static Task<ResourceExistsResult> CheckExistenceAsync(this IResourceOperations operations, string resourceGroupName, ResourceIdentity identity) { return operations.CheckExistenceAsync(resourceGroupName, identity, CancellationToken.None); } /// <summary> /// Create a resource. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Resources.IResourceOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. The name is case /// insensitive. /// </param> /// <param name='identity'> /// Required. Resource identity. /// </param> /// <param name='parameters'> /// Required. Create or update resource parameters. /// </param> /// <returns> /// Resource information. /// </returns> public static ResourceCreateOrUpdateResult CreateOrUpdate(this IResourceOperations operations, string resourceGroupName, ResourceIdentity identity, BasicResource parameters) { return Task.Factory.StartNew((object s) => { return ((IResourceOperations)s).CreateOrUpdateAsync(resourceGroupName, identity, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Create a resource. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Resources.IResourceOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. The name is case /// insensitive. /// </param> /// <param name='identity'> /// Required. Resource identity. /// </param> /// <param name='parameters'> /// Required. Create or update resource parameters. /// </param> /// <returns> /// Resource information. /// </returns> public static Task<ResourceCreateOrUpdateResult> CreateOrUpdateAsync(this IResourceOperations operations, string resourceGroupName, ResourceIdentity identity, BasicResource parameters) { return operations.CreateOrUpdateAsync(resourceGroupName, identity, parameters, CancellationToken.None); } /// <summary> /// Delete resource and all of its resources. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Resources.IResourceOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. The name is case /// insensitive. /// </param> /// <param name='identity'> /// Required. Resource identity. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static OperationResponse Delete(this IResourceOperations operations, string resourceGroupName, ResourceIdentity identity) { return Task.Factory.StartNew((object s) => { return ((IResourceOperations)s).DeleteAsync(resourceGroupName, identity); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Delete resource and all of its resources. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Resources.IResourceOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. The name is case /// insensitive. /// </param> /// <param name='identity'> /// Required. Resource identity. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static Task<OperationResponse> DeleteAsync(this IResourceOperations operations, string resourceGroupName, ResourceIdentity identity) { return operations.DeleteAsync(resourceGroupName, identity, CancellationToken.None); } /// <summary> /// Returns a resource belonging to a resource group. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Resources.IResourceOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. The name is case /// insensitive. /// </param> /// <param name='identity'> /// Required. Resource identity. /// </param> /// <returns> /// Resource information. /// </returns> public static ResourceGetResult Get(this IResourceOperations operations, string resourceGroupName, ResourceIdentity identity) { return Task.Factory.StartNew((object s) => { return ((IResourceOperations)s).GetAsync(resourceGroupName, identity); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Returns a resource belonging to a resource group. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Resources.IResourceOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group. The name is case /// insensitive. /// </param> /// <param name='identity'> /// Required. Resource identity. /// </param> /// <returns> /// Resource information. /// </returns> public static Task<ResourceGetResult> GetAsync(this IResourceOperations operations, string resourceGroupName, ResourceIdentity identity) { return operations.GetAsync(resourceGroupName, identity, CancellationToken.None); } /// <summary> /// Get all of the resources under a subscription. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Resources.IResourceOperations. /// </param> /// <param name='parameters'> /// Optional. Query parameters. If null is passed returns all resource /// groups. /// </param> /// <returns> /// List of resource groups. /// </returns> public static ResourceListResult List(this IResourceOperations operations, ResourceListParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IResourceOperations)s).ListAsync(parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get all of the resources under a subscription. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Resources.IResourceOperations. /// </param> /// <param name='parameters'> /// Optional. Query parameters. If null is passed returns all resource /// groups. /// </param> /// <returns> /// List of resource groups. /// </returns> public static Task<ResourceListResult> ListAsync(this IResourceOperations operations, ResourceListParameters parameters) { return operations.ListAsync(parameters, CancellationToken.None); } /// <summary> /// Get a list of deployments. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Resources.IResourceOperations. /// </param> /// <param name='nextLink'> /// Required. NextLink from the previous successful call to List /// operation. /// </param> /// <returns> /// List of resource groups. /// </returns> public static ResourceListResult ListNext(this IResourceOperations operations, string nextLink) { return Task.Factory.StartNew((object s) => { return ((IResourceOperations)s).ListNextAsync(nextLink); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get a list of deployments. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Resources.IResourceOperations. /// </param> /// <param name='nextLink'> /// Required. NextLink from the previous successful call to List /// operation. /// </param> /// <returns> /// List of resource groups. /// </returns> public static Task<ResourceListResult> ListNextAsync(this IResourceOperations operations, string nextLink) { return operations.ListNextAsync(nextLink, CancellationToken.None); } } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. // See THIRD-PARTY-NOTICES.TXT in the project root for license information. using System.Collections.Generic; using System.Diagnostics; namespace System.Net.Http.HPack { internal class HPackEncoder { private IEnumerator<KeyValuePair<string, string>> _enumerator; public bool BeginEncode(IEnumerable<KeyValuePair<string, string>> headers, Span<byte> buffer, out int length) { _enumerator = headers.GetEnumerator(); _enumerator.MoveNext(); return Encode(buffer, out length); } public bool BeginEncode(int statusCode, IEnumerable<KeyValuePair<string, string>> headers, Span<byte> buffer, out int length) { _enumerator = headers.GetEnumerator(); _enumerator.MoveNext(); int statusCodeLength = EncodeStatusCode(statusCode, buffer); bool done = Encode(buffer.Slice(statusCodeLength), throwIfNoneEncoded: false, out int headersLength); length = statusCodeLength + headersLength; return done; } public bool Encode(Span<byte> buffer, out int length) { return Encode(buffer, throwIfNoneEncoded: true, out length); } private bool Encode(Span<byte> buffer, bool throwIfNoneEncoded, out int length) { int currentLength = 0; do { if (!EncodeHeader(_enumerator.Current.Key, _enumerator.Current.Value, buffer.Slice(currentLength), out int headerLength)) { if (currentLength == 0 && throwIfNoneEncoded) { throw new HPackEncodingException(); } length = currentLength; return false; } currentLength += headerLength; } while (_enumerator.MoveNext()); length = currentLength; return true; } private int EncodeStatusCode(int statusCode, Span<byte> buffer) { switch (statusCode) { // Status codes which exist in the HTTP/2 StaticTable. case 200: case 204: case 206: case 304: case 400: case 404: case 500: buffer[0] = (byte)(0x80 | StaticTable.StatusIndex[statusCode]); return 1; default: // Send as Literal Header Field Without Indexing - Indexed Name buffer[0] = 0x08; ReadOnlySpan<byte> statusBytes = StatusCodes.ToStatusBytes(statusCode); buffer[1] = (byte)statusBytes.Length; statusBytes.CopyTo(buffer.Slice(2)); return 2 + statusBytes.Length; } } private bool EncodeHeader(string name, string value, Span<byte> buffer, out int length) { int i = 0; length = 0; if (buffer.Length == 0) { return false; } buffer[i++] = 0; if (i == buffer.Length) { return false; } if (!EncodeString(name, buffer.Slice(i), out int nameLength, lowercase: true)) { return false; } i += nameLength; if (i >= buffer.Length) { return false; } if (!EncodeString(value, buffer.Slice(i), out int valueLength, lowercase: false)) { return false; } i += valueLength; length = i; return true; } private bool EncodeString(string value, Span<byte> destination, out int bytesWritten, bool lowercase) { // From https://tools.ietf.org/html/rfc7541#section-5.2 // ------------------------------------------------------ // 0 1 2 3 4 5 6 7 // +---+---+---+---+---+---+---+---+ // | H | String Length (7+) | // +---+---------------------------+ // | String Data (Length octets) | // +-------------------------------+ if (destination.Length != 0) { destination[0] = 0; // TODO: Use Huffman encoding if (IntegerEncoder.Encode(value.Length, 7, destination, out int integerLength)) { Debug.Assert(integerLength >= 1); destination = destination.Slice(integerLength); if (value.Length <= destination.Length) { for (int i = 0; i < value.Length; i++) { char c = value[i]; destination[i] = (byte)((uint)(c - 'A') <= ('Z' - 'A') ? c | 0x20 : c); } bytesWritten = integerLength + value.Length; return true; } } } bytesWritten = 0; return false; } // Things we should add: // * Huffman encoding // // Things we should consider adding: // * Dynamic table encoding: // This would make the encoder stateful, which complicates things significantly. // Additionally, it's not clear exactly what strings we would add to the dynamic table // without some additional guidance from the user about this. // So for now, don't do dynamic encoding. /// <summary>Encodes an "Indexed Header Field".</summary> public static bool EncodeIndexedHeaderField(int index, Span<byte> destination, out int bytesWritten) { // From https://tools.ietf.org/html/rfc7541#section-6.1 // ---------------------------------------------------- // 0 1 2 3 4 5 6 7 // +---+---+---+---+---+---+---+---+ // | 1 | Index (7+) | // +---+---------------------------+ if (destination.Length != 0) { destination[0] = 0x80; return IntegerEncoder.Encode(index, 7, destination, out bytesWritten); } bytesWritten = 0; return false; } /// <summary>Encodes a "Literal Header Field without Indexing".</summary> public static bool EncodeLiteralHeaderFieldWithoutIndexing(int index, string value, Span<byte> destination, out int bytesWritten) { // From https://tools.ietf.org/html/rfc7541#section-6.2.2 // ------------------------------------------------------ // 0 1 2 3 4 5 6 7 // +---+---+---+---+---+---+---+---+ // | 0 | 0 | 0 | 0 | Index (4+) | // +---+---+-----------------------+ // | H | Value Length (7+) | // +---+---------------------------+ // | Value String (Length octets) | // +-------------------------------+ if ((uint)destination.Length >= 2) { destination[0] = 0; if (IntegerEncoder.Encode(index, 4, destination, out int indexLength)) { Debug.Assert(indexLength >= 1); if (EncodeStringLiteral(value, destination.Slice(indexLength), out int nameLength)) { bytesWritten = indexLength + nameLength; return true; } } } bytesWritten = 0; return false; } /// <summary> /// Encodes a "Literal Header Field without Indexing", but only the index portion; /// a subsequent call to <see cref="EncodeStringLiteral"/> must be used to encode the associated value. /// </summary> public static bool EncodeLiteralHeaderFieldWithoutIndexing(int index, Span<byte> destination, out int bytesWritten) { // From https://tools.ietf.org/html/rfc7541#section-6.2.2 // ------------------------------------------------------ // 0 1 2 3 4 5 6 7 // +---+---+---+---+---+---+---+---+ // | 0 | 0 | 0 | 0 | Index (4+) | // +---+---+-----------------------+ // // ... expected after this: // // | H | Value Length (7+) | // +---+---------------------------+ // | Value String (Length octets) | // +-------------------------------+ if ((uint)destination.Length != 0) { destination[0] = 0; if (IntegerEncoder.Encode(index, 4, destination, out int indexLength)) { Debug.Assert(indexLength >= 1); bytesWritten = indexLength; return true; } } bytesWritten = 0; return false; } /// <summary>Encodes a "Literal Header Field without Indexing - New Name".</summary> public static bool EncodeLiteralHeaderFieldWithoutIndexingNewName(string name, ReadOnlySpan<string> values, string separator, Span<byte> destination, out int bytesWritten) { // From https://tools.ietf.org/html/rfc7541#section-6.2.2 // ------------------------------------------------------ // 0 1 2 3 4 5 6 7 // +---+---+---+---+---+---+---+---+ // | 0 | 0 | 0 | 0 | 0 | // +---+---+-----------------------+ // | H | Name Length (7+) | // +---+---------------------------+ // | Name String (Length octets) | // +---+---------------------------+ // | H | Value Length (7+) | // +---+---------------------------+ // | Value String (Length octets) | // +-------------------------------+ if ((uint)destination.Length >= 3) { destination[0] = 0; if (EncodeLiteralHeaderName(name, destination.Slice(1), out int nameLength) && EncodeStringLiterals(values, separator, destination.Slice(1 + nameLength), out int valueLength)) { bytesWritten = 1 + nameLength + valueLength; return true; } } bytesWritten = 0; return false; } /// <summary> /// Encodes a "Literal Header Field without Indexing - New Name", but only the name portion; /// a subsequent call to <see cref="EncodeStringLiteral"/> must be used to encode the associated value. /// </summary> public static bool EncodeLiteralHeaderFieldWithoutIndexingNewName(string name, Span<byte> destination, out int bytesWritten) { // From https://tools.ietf.org/html/rfc7541#section-6.2.2 // ------------------------------------------------------ // 0 1 2 3 4 5 6 7 // +---+---+---+---+---+---+---+---+ // | 0 | 0 | 0 | 0 | 0 | // +---+---+-----------------------+ // | H | Name Length (7+) | // +---+---------------------------+ // | Name String (Length octets) | // +---+---------------------------+ // // ... expected after this: // // | H | Value Length (7+) | // +---+---------------------------+ // | Value String (Length octets) | // +-------------------------------+ if ((uint)destination.Length >= 2) { destination[0] = 0; if (EncodeLiteralHeaderName(name, destination.Slice(1), out int nameLength)) { bytesWritten = 1 + nameLength; return true; } } bytesWritten = 0; return false; } private static bool EncodeLiteralHeaderName(string value, Span<byte> destination, out int bytesWritten) { // From https://tools.ietf.org/html/rfc7541#section-5.2 // ------------------------------------------------------ // 0 1 2 3 4 5 6 7 // +---+---+---+---+---+---+---+---+ // | H | String Length (7+) | // +---+---------------------------+ // | String Data (Length octets) | // +-------------------------------+ if (destination.Length != 0) { destination[0] = 0; // TODO: Use Huffman encoding if (IntegerEncoder.Encode(value.Length, 7, destination, out int integerLength)) { Debug.Assert(integerLength >= 1); destination = destination.Slice(integerLength); if (value.Length <= destination.Length) { for (int i = 0; i < value.Length; i++) { char c = value[i]; destination[i] = (byte)((uint)(c - 'A') <= ('Z' - 'A') ? c | 0x20 : c); } bytesWritten = integerLength + value.Length; return true; } } } bytesWritten = 0; return false; } private static bool EncodeStringLiteralValue(string value, Span<byte> destination, out int bytesWritten) { if (value.Length <= destination.Length) { for (int i = 0; i < value.Length; i++) { char c = value[i]; if ((c & 0xFF80) != 0) { throw new HttpRequestException(SR.net_http_request_invalid_char_encoding); } destination[i] = (byte)c; } bytesWritten = value.Length; return true; } bytesWritten = 0; return false; } public static bool EncodeStringLiteral(string value, Span<byte> destination, out int bytesWritten) { // From https://tools.ietf.org/html/rfc7541#section-5.2 // ------------------------------------------------------ // 0 1 2 3 4 5 6 7 // +---+---+---+---+---+---+---+---+ // | H | String Length (7+) | // +---+---------------------------+ // | String Data (Length octets) | // +-------------------------------+ if (destination.Length != 0) { destination[0] = 0; // TODO: Use Huffman encoding if (IntegerEncoder.Encode(value.Length, 7, destination, out int integerLength)) { Debug.Assert(integerLength >= 1); if (EncodeStringLiteralValue(value, destination.Slice(integerLength), out int valueLength)) { bytesWritten = integerLength + valueLength; return true; } } } bytesWritten = 0; return false; } public static bool EncodeStringLiterals(ReadOnlySpan<string> values, string separator, Span<byte> destination, out int bytesWritten) { bytesWritten = 0; if (values.Length == 0) { return EncodeStringLiteral("", destination, out bytesWritten); } else if (values.Length == 1) { return EncodeStringLiteral(values[0], destination, out bytesWritten); } if (destination.Length != 0) { int valueLength = 0; // Calculate length of all parts and separators. foreach (string part in values) { valueLength = checked((int)(valueLength + part.Length)); } valueLength = checked((int)(valueLength + (values.Length - 1) * separator.Length)); destination[0] = 0; if (IntegerEncoder.Encode(valueLength, 7, destination, out int integerLength)) { Debug.Assert(integerLength >= 1); int encodedLength = 0; for (int j = 0; j < values.Length; j++) { if (j != 0 && !EncodeStringLiteralValue(separator, destination.Slice(integerLength), out encodedLength)) { return false; } integerLength += encodedLength; if (!EncodeStringLiteralValue(values[j], destination.Slice(integerLength), out encodedLength)) { return false; } integerLength += encodedLength; } bytesWritten = integerLength; return true; } } return false; } /// <summary> /// Encodes a "Literal Header Field without Indexing" to a new array, but only the index portion; /// a subsequent call to <see cref="EncodeStringLiteral"/> must be used to encode the associated value. /// </summary> public static byte[] EncodeLiteralHeaderFieldWithoutIndexingToAllocatedArray(int index) { Span<byte> span = stackalloc byte[256]; bool success = EncodeLiteralHeaderFieldWithoutIndexing(index, span, out int length); Debug.Assert(success, $"Stack-allocated space was too small for index '{index}'."); return span.Slice(0, length).ToArray(); } /// <summary> /// Encodes a "Literal Header Field without Indexing - New Name" to a new array, but only the name portion; /// a subsequent call to <see cref="EncodeStringLiteral"/> must be used to encode the associated value. /// </summary> public static byte[] EncodeLiteralHeaderFieldWithoutIndexingNewNameToAllocatedArray(string name) { Span<byte> span = stackalloc byte[256]; bool success = EncodeLiteralHeaderFieldWithoutIndexingNewName(name, span, out int length); Debug.Assert(success, $"Stack-allocated space was too small for \"{name}\"."); return span.Slice(0, length).ToArray(); } /// <summary>Encodes a "Literal Header Field without Indexing" to a new array.</summary> public static byte[] EncodeLiteralHeaderFieldWithoutIndexingToAllocatedArray(int index, string value) { Span<byte> span = #if DEBUG stackalloc byte[4]; // to validate growth algorithm #else stackalloc byte[512]; #endif while (true) { if (EncodeLiteralHeaderFieldWithoutIndexing(index, value, span, out int length)) { return span.Slice(0, length).ToArray(); } // This is a rare path, only used once per HTTP/2 connection and only // for very long host names. Just allocate rather than complicate // the code with ArrayPool usage. In practice we should never hit this, // as hostnames should be <= 255 characters. span = new byte[span.Length * 2]; } } } }
using System; using System.Collections.Generic; using System.Text; using ForieroEngine.MIDIUnified.Utils; namespace ForieroEngine.MIDIUnified.Midi { /// <summary> /// A helper class to manage collection of MIDI events /// It has the ability to organise them in tracks /// </summary> public class MidiEventCollection : IEnumerable<IList<MidiEvent>> { int midiFileType; List<IList<MidiEvent>> trackEvents; int deltaTicksPerQuarterNote; long startAbsoluteTime; /// <summary> /// Creates a new Midi Event collection /// </summary> /// <param name="midiFileType">Initial file type</param> /// <param name="deltaTicksPerQuarterNote">Delta Ticks Per Quarter Note</param> public MidiEventCollection(int midiFileType, int deltaTicksPerQuarterNote) { this.midiFileType = midiFileType; this.deltaTicksPerQuarterNote = deltaTicksPerQuarterNote; this.startAbsoluteTime = 0; trackEvents = new List<IList<MidiEvent>>(); } /// <summary> /// The number of tracks /// </summary> public int Tracks { get { return trackEvents.Count; } } /// <summary> /// The absolute time that should be considered as time zero /// Not directly used here, but useful for timeshifting applications /// </summary> public long StartAbsoluteTime { get { return startAbsoluteTime; } set { startAbsoluteTime = value; } } /// <summary> /// The number of ticks per quarter note /// </summary> public int DeltaTicksPerQuarterNote { get { return deltaTicksPerQuarterNote; } } /// <summary> /// Gets events on a specified track /// </summary> /// <param name="trackNumber">Track number</param> /// <returns>The list of events</returns> public IList<MidiEvent> GetTrackEvents(int trackNumber) { return trackEvents[trackNumber]; } /// <summary> /// Gets events on a specific track /// </summary> /// <param name="trackNumber">Track number</param> /// <returns>The list of events</returns> public IList<MidiEvent> this[int trackNumber] { get { return trackEvents[trackNumber]; } } /// <summary> /// Adds a new track /// </summary> /// <returns>The new track event list</returns> public IList<MidiEvent> AddTrack() { return AddTrack(null); } /// <summary> /// Adds a new track /// </summary> /// <param name="initialEvents">Initial events to add to the new track</param> /// <returns>The new track event list</returns> public IList<MidiEvent> AddTrack(IList<MidiEvent> initialEvents) { List<MidiEvent> events = new List<MidiEvent>(); if (initialEvents != null) { events.AddRange(initialEvents); } trackEvents.Add(events); return events; } /// <summary> /// Removes a track /// </summary> /// <param name="track">Track number to remove</param> public void RemoveTrack(int track) { trackEvents.RemoveAt(track); } /// <summary> /// Clears all events /// </summary> public void Clear() { trackEvents.Clear(); } /// <summary> /// The MIDI file type /// </summary> public int MidiFileType { get { return midiFileType; } set { if (midiFileType != value) { // set MIDI file type before calling flatten or explode functions midiFileType = value; if (value == 0) { FlattenToOneTrack(); } else { ExplodeToManyTracks(); } } } } /// <summary> /// Adds an event to the appropriate track depending on file type /// </summary> /// <param name="midiEvent">The event to be added</param> /// <param name="originalTrack">The original (or desired) track number</param> /// <remarks>When adding events in type 0 mode, the originalTrack parameter /// is ignored. If in type 1 mode, it will use the original track number to /// store the new events. If the original track was 0 and this is a channel based /// event, it will create new tracks if necessary and put it on the track corresponding /// to its channel number</remarks> public void AddEvent(MidiEvent midiEvent, int originalTrack) { if (midiFileType == 0) { EnsureTracks(1); trackEvents[0].Add(midiEvent); } else { if(originalTrack == 0) { // if its a channel based event, lets move it off to // a channel track of its own switch (midiEvent.CommandCode) { case MidiCommandCode.NoteOff: case MidiCommandCode.NoteOn: case MidiCommandCode.KeyAfterTouch: case MidiCommandCode.ControlChange: case MidiCommandCode.PatchChange: case MidiCommandCode.ChannelAfterTouch: case MidiCommandCode.PitchWheelChange: EnsureTracks(midiEvent.Channel + 1); trackEvents[midiEvent.Channel].Add(midiEvent); break; default: EnsureTracks(1); trackEvents[0].Add(midiEvent); break; } } else { // put it on the track it was originally on EnsureTracks(originalTrack + 1); trackEvents[originalTrack].Add(midiEvent); } } } private void EnsureTracks(int count) { for (int n = trackEvents.Count; n < count; n++) { trackEvents.Add(new List<MidiEvent>()); } } private void ExplodeToManyTracks() { IList<MidiEvent> originalList = trackEvents[0]; Clear(); foreach (MidiEvent midiEvent in originalList) { AddEvent(midiEvent, 0); } PrepareForExport(); } private void FlattenToOneTrack() { bool eventsAdded = false; for (int track = 1; track < trackEvents.Count; track++) { foreach (MidiEvent midiEvent in trackEvents[track]) { if (!MidiEvent.IsEndTrack(midiEvent)) { trackEvents[0].Add(midiEvent); eventsAdded = true; } } } for (int track = trackEvents.Count - 1; track > 0; track--) { RemoveTrack(track); } if (eventsAdded) { PrepareForExport(); } } /// <summary> /// Sorts, removes empty tracks and adds end track markers /// </summary> public void PrepareForExport() { var comparer = new MidiEventComparer(); // 1. sort each track foreach (List<MidiEvent> list in trackEvents) { MergeSort.Sort(list, comparer); // 2. remove all End track events except one at the very end int index = 0; while (index < list.Count - 1) { if(MidiEvent.IsEndTrack(list[index])) { list.RemoveAt(index); } else { index++; } } } int track = 0; // 3. remove empty tracks and add missing while (track < trackEvents.Count) { IList<MidiEvent> list = trackEvents[track]; if (list.Count == 0) { RemoveTrack(track); } else { if(list.Count == 1 && MidiEvent.IsEndTrack(list[0])) { RemoveTrack(track); } else { if(!MidiEvent.IsEndTrack(list[list.Count-1])) { list.Add(new MetaEvent(MetaEventType.EndTrack, 0, list[list.Count - 1].AbsoluteTime)); } track++; } } } } /// <summary> /// Gets an enumerator for the lists of track events /// </summary> public IEnumerator<IList<MidiEvent>> GetEnumerator() { return trackEvents.GetEnumerator(); } /// <summary> /// Gets an enumerator for the lists of track events /// </summary> System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return trackEvents.GetEnumerator(); } } }
namespace Microsoft.ApplicationInsights.DependencyCollector.Implementation { using System; using System.Collections.Generic; using System.Diagnostics; using Microsoft.ApplicationInsights.Common; using Microsoft.ApplicationInsights.DataContracts; using Microsoft.ApplicationInsights.Extensibility; using Microsoft.ApplicationInsights.Extensibility.Implementation; internal class TelemetryDiagnosticSourceListener : DiagnosticSourceListenerBase<HashSet<string>>, IDiagnosticEventHandler { internal const string ActivityStartNameSuffix = ".Start"; internal const string ActivityStopNameSuffix = ".Stop"; private readonly HashSet<string> includedDiagnosticSources = new HashSet<string>(StringComparer.OrdinalIgnoreCase); private readonly Dictionary<string, HashSet<string>> includedDiagnosticSourceActivities = new Dictionary<string, HashSet<string>>(StringComparer.OrdinalIgnoreCase); private readonly Dictionary<string, IDiagnosticEventHandler> customEventHandlers = new Dictionary<string, IDiagnosticEventHandler>(StringComparer.OrdinalIgnoreCase); public TelemetryDiagnosticSourceListener(TelemetryConfiguration configuration, ICollection<string> includeDiagnosticSourceActivities) : base(configuration) { this.Client.Context.GetInternalContext().SdkVersion = SdkVersionUtils.GetSdkVersion("rdd" + RddSource.DiagnosticSourceListener + ":"); this.PrepareInclusionLists(includeDiagnosticSourceActivities); } public bool IsEventEnabled(string evnt, object input1, object input2) { return !evnt.EndsWith(ActivityStartNameSuffix, StringComparison.Ordinal); } public void OnEvent(KeyValuePair<string, object> evnt, DiagnosticListener diagnosticListener) { if (!evnt.Key.EndsWith(ActivityStopNameSuffix, StringComparison.Ordinal)) { return; } Activity currentActivity = Activity.Current; // extensibility point - can chain more telemetry extraction methods here var telemetry = ExtractDependencyTelemetry(diagnosticListener, currentActivity); if (telemetry == null) { return; } // properly fill dependency telemetry operation context if (currentActivity.IdFormat == ActivityIdFormat.W3C) { telemetry.Context.Operation.Id = currentActivity.TraceId.ToHexString(); if (currentActivity.ParentSpanId != default) { telemetry.Context.Operation.ParentId = currentActivity.ParentSpanId.ToHexString(); } telemetry.Id = currentActivity.SpanId.ToHexString(); } else { telemetry.Id = currentActivity.Id; telemetry.Context.Operation.Id = currentActivity.RootId; telemetry.Context.Operation.ParentId = currentActivity.ParentId; } telemetry.Timestamp = currentActivity.StartTimeUtc; telemetry.Properties["DiagnosticSource"] = diagnosticListener.Name; telemetry.Properties["Activity"] = currentActivity.OperationName; this.Client.TrackDependency(telemetry); } internal static DependencyTelemetry ExtractDependencyTelemetry(DiagnosticListener diagnosticListener, Activity currentActivity) { DependencyTelemetry telemetry = new DependencyTelemetry { Id = currentActivity.Id, Duration = currentActivity.Duration, Name = currentActivity.OperationName, }; Uri requestUri = null; string component = null; string queryStatement = null; string httpUrl = null; string peerAddress = null; string peerService = null; foreach (KeyValuePair<string, string> tag in currentActivity.Tags) { // interpret Tags as defined by OpenTracing conventions // https://github.com/opentracing/specification/blob/master/semantic_conventions.md switch (tag.Key) { case "component": { component = tag.Value; break; } case "db.statement": { queryStatement = tag.Value; break; } case "error": { if (bool.TryParse(tag.Value, out var failed)) { telemetry.Success = !failed; continue; // skip Properties } break; } case "http.status_code": { telemetry.ResultCode = tag.Value; continue; // skip Properties } case "http.method": { continue; // skip Properties } case "http.url": { httpUrl = tag.Value; if (Uri.TryCreate(tag.Value, UriKind.RelativeOrAbsolute, out requestUri)) { continue; // skip Properties } break; } case "peer.address": { peerAddress = tag.Value; break; } case "peer.hostname": { telemetry.Target = tag.Value; continue; // skip Properties } case "peer.service": { peerService = tag.Value; break; } } // if more than one tag with the same name is specified, the first one wins // TODO verify if still needed once https://github.com/Microsoft/ApplicationInsights-dotnet/issues/562 is resolved if (!telemetry.Properties.ContainsKey(tag.Key)) { telemetry.Properties.Add(tag); } } if (string.IsNullOrEmpty(telemetry.Type)) { telemetry.Type = peerService ?? component ?? diagnosticListener.Name; } if (string.IsNullOrEmpty(telemetry.Target)) { // 'peer.address' can be not user-friendly, thus use only if nothing else specified telemetry.Target = requestUri?.Host ?? peerAddress; } if (string.IsNullOrEmpty(telemetry.Name)) { telemetry.Name = currentActivity.OperationName; } if (string.IsNullOrEmpty(telemetry.Data)) { telemetry.Data = queryStatement ?? requestUri?.OriginalString ?? httpUrl; } return telemetry; } internal void RegisterHandler(string diagnosticSourceName, IDiagnosticEventHandler eventHandler) { this.customEventHandlers[diagnosticSourceName] = eventHandler; } internal override bool IsSourceEnabled(DiagnosticListener value) { return this.includedDiagnosticSources.Contains(value.Name); } internal override bool IsActivityEnabled(string activityName, HashSet<string> includedActivities) { // if no list of included activities then all are included return includedActivities == null || includedActivities.Contains(activityName); } protected override HashSet<string> GetListenerContext(DiagnosticListener diagnosticListener) { if (!this.includedDiagnosticSourceActivities.TryGetValue(diagnosticListener.Name, out var includedActivities)) { return null; } return includedActivities; } protected override IDiagnosticEventHandler GetEventHandler(string diagnosticListenerName) { if (this.customEventHandlers.TryGetValue(diagnosticListenerName, out var eventHandler)) { return eventHandler; } return this; } private void PrepareInclusionLists(ICollection<string> includeDiagnosticSourceActivities) { if (includeDiagnosticSourceActivities == null) { return; } foreach (string inclusion in includeDiagnosticSourceActivities) { if (string.IsNullOrWhiteSpace(inclusion)) { continue; } // each individual inclusion can specify // 1) the name of Diagnostic Source // - in that case the whole source is included // - e.g. "System.Net.Http" // 2) the names of Diagnostic Source and Activity separated by ':' // - in that case only the activity is enabled from given source // - e.g. "" string[] tokens = inclusion.Split(':'); // the Diagnostic Source is included (even if only certain activities are enabled) this.includedDiagnosticSources.Add(tokens[0]); if (tokens.Length > 1) { // only certain Activity from the Diagnostic Source is included if (!this.includedDiagnosticSourceActivities.TryGetValue(tokens[0], out var includedActivities)) { includedActivities = new HashSet<string>(StringComparer.OrdinalIgnoreCase); this.includedDiagnosticSourceActivities[tokens[0]] = includedActivities; } // include activity and activity Stop events includedActivities.Add(tokens[1]); includedActivities.Add(tokens[1] + ActivityStopNameSuffix); } } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; using System.Linq; using Validation; namespace System.Collections.Immutable { /// <summary> /// An immutable unordered hash set implementation. /// </summary> /// <typeparam name="T">The type of elements in the set.</typeparam> [DebuggerDisplay("Count = {Count}")] [DebuggerTypeProxy(typeof(ImmutableHashSet<>.DebuggerProxy))] public sealed partial class ImmutableHashSet<T> : IImmutableSet<T>, IHashKeyCollection<T>, IReadOnlyCollection<T>, ICollection<T>, ISet<T>, ICollection { /// <summary> /// An empty immutable hash set with the default comparer for <typeparamref name="T"/>. /// </summary> [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] public static readonly ImmutableHashSet<T> Empty = new ImmutableHashSet<T>(ImmutableSortedDictionary<int, HashBucket>.Node.EmptyNode, EqualityComparer<T>.Default, 0); /// <summary> /// The singleton delegate that freezes the contents of hash buckets when the root of the data structure is frozen. /// </summary> private static readonly Action<KeyValuePair<int, HashBucket>> FreezeBucketAction = (kv) => kv.Value.Freeze(); /// <summary> /// The equality comparer used to hash the elements in the collection. /// </summary> private readonly IEqualityComparer<T> equalityComparer; /// <summary> /// The number of elements in this collection. /// </summary> private readonly int count; /// <summary> /// The sorted dictionary that this hash set wraps. The key is the hash code and the value is the bucket of all items that hashed to it. /// </summary> private readonly ImmutableSortedDictionary<int, HashBucket>.Node root; /// <summary> /// Initializes a new instance of the <see cref="ImmutableHashSet&lt;T&gt;"/> class. /// </summary> /// <param name="equalityComparer">The equality comparer.</param> internal ImmutableHashSet(IEqualityComparer<T> equalityComparer) : this(ImmutableSortedDictionary<int, HashBucket>.Node.EmptyNode, equalityComparer, 0) { } /// <summary> /// Initializes a new instance of the <see cref="ImmutableHashSet&lt;T&gt;"/> class. /// </summary> /// <param name="root">The sorted set that this set wraps.</param> /// <param name="equalityComparer">The equality comparer used by this instance.</param> /// <param name="count">The number of elements in this collection.</param> private ImmutableHashSet(ImmutableSortedDictionary<int, HashBucket>.Node root, IEqualityComparer<T> equalityComparer, int count) { Requires.NotNull(root, "root"); Requires.NotNull(equalityComparer, "equalityComparer"); root.Freeze(FreezeBucketAction); this.root = root; this.count = count; this.equalityComparer = equalityComparer; } /// <summary> /// See the <see cref="IImmutableSet&lt;T&gt;"/> interface. /// </summary> public ImmutableHashSet<T> Clear() { Contract.Ensures(Contract.Result<ImmutableHashSet<T>>() != null); Contract.Ensures(Contract.Result<ImmutableHashSet<T>>().IsEmpty); return this.IsEmpty ? this : ImmutableHashSet<T>.Empty.WithComparer(this.equalityComparer); } /// <summary> /// See the <see cref="IImmutableSet&lt;T&gt;"/> interface. /// </summary> public int Count { get { return this.count; } } /// <summary> /// See the <see cref="IImmutableSet&lt;T&gt;"/> interface. /// </summary> public bool IsEmpty { get { return this.Count == 0; } } #region IHashKeyCollection<T> Properties /// <summary> /// See the <see cref="IImmutableSet&lt;T&gt;"/> interface. /// </summary> public IEqualityComparer<T> KeyComparer { get { return this.equalityComparer; } } #endregion #region IImmutableSet<T> Properties /// <summary> /// See the <see cref="IImmutableSet&lt;T&gt;"/> interface. /// </summary> [ExcludeFromCodeCoverage] IImmutableSet<T> IImmutableSet<T>.Clear() { return this.Clear(); } #endregion #region ICollection Properties /// <summary> /// See ICollection. /// </summary> [DebuggerBrowsable(DebuggerBrowsableState.Never)] object ICollection.SyncRoot { get { return this; } } /// <summary> /// See the ICollection interface. /// </summary> [DebuggerBrowsable(DebuggerBrowsableState.Never)] bool ICollection.IsSynchronized { get { // This is immutable, so it is always thread-safe. return true; } } #endregion /// <summary> /// Gets a data structure that captures the current state of this map, as an input into a query or mutating function. /// </summary> private MutationInput Origin { get { return new MutationInput(this); } } #region Public methods /// <summary> /// Creates a collection with the same contents as this collection that /// can be efficiently mutated across multiple operations using standard /// mutable interfaces. /// </summary> /// <remarks> /// This is an O(1) operation and results in only a single (small) memory allocation. /// The mutable collection that is returned is *not* thread-safe. /// </remarks> [Pure] public Builder ToBuilder() { // We must not cache the instance created here and return it to various callers. // Those who request a mutable collection must get references to the collection // that version independently of each other. return new Builder(this); } /// <summary> /// See the <see cref="IImmutableSet&lt;T&gt;"/> interface. /// </summary> [Pure] public ImmutableHashSet<T> Add(T item) { Requires.NotNullAllowStructs(item, "item"); Contract.Ensures(Contract.Result<ImmutableHashSet<T>>() != null); var result = Add(item, this.Origin); return result.Finalize(this); } /// <summary> /// See the <see cref="IImmutableSet&lt;T&gt;"/> interface. /// </summary> public ImmutableHashSet<T> Remove(T item) { Requires.NotNullAllowStructs(item, "item"); Contract.Ensures(Contract.Result<ImmutableHashSet<T>>() != null); var result = Remove(item, this.Origin); return result.Finalize(this); } /// <summary> /// Searches the set for a given value and returns the equal value it finds, if any. /// </summary> /// <param name="equalValue">The value to search for.</param> /// <param name="actualValue">The value from the set that the search found, or the original value if the search yielded no match.</param> /// <returns>A value indicating whether the search was successful.</returns> /// <remarks> /// This can be useful when you want to reuse a previously stored reference instead of /// a newly constructed one (so that more sharing of references can occur) or to look up /// a value that has more complete data than the value you currently have, although their /// comparer functions indicate they are equal. /// </remarks> [Pure] public bool TryGetValue(T equalValue, out T actualValue) { Requires.NotNullAllowStructs(equalValue, "value"); int hashCode = this.equalityComparer.GetHashCode(equalValue); HashBucket bucket; if (this.root.TryGetValue(hashCode, Comparer<int>.Default, out bucket)) { return bucket.TryExchange(equalValue, this.equalityComparer, out actualValue); } actualValue = equalValue; return false; } /// <summary> /// See the <see cref="IImmutableSet&lt;T&gt;"/> interface. /// </summary> [Pure] public ImmutableHashSet<T> Union(IEnumerable<T> other) { Requires.NotNull(other, "other"); Contract.Ensures(Contract.Result<ImmutableHashSet<T>>() != null); return this.Union(other, avoidWithComparer: false); } /// <summary> /// See the <see cref="IImmutableSet&lt;T&gt;"/> interface. /// </summary> [Pure] public ImmutableHashSet<T> Intersect(IEnumerable<T> other) { Requires.NotNull(other, "other"); Contract.Ensures(Contract.Result<ImmutableHashSet<T>>() != null); var result = Intersect(other, this.Origin); return result.Finalize(this); } /// <summary> /// See the <see cref="IImmutableSet&lt;T&gt;"/> interface. /// </summary> public ImmutableHashSet<T> Except(IEnumerable<T> other) { Requires.NotNull(other, "other"); var result = Except(other, this.equalityComparer, this.root); return result.Finalize(this); } /// <summary> /// Produces a set that contains elements either in this set or a given sequence, but not both. /// </summary> /// <param name="other">The other sequence of items.</param> /// <returns>The new set.</returns> [Pure] public ImmutableHashSet<T> SymmetricExcept(IEnumerable<T> other) { Requires.NotNull(other, "other"); Contract.Ensures(Contract.Result<IImmutableSet<T>>() != null); var result = SymmetricExcept(other, this.Origin); return result.Finalize(this); } /// <summary> /// Checks whether a given sequence of items entirely describe the contents of this set. /// </summary> /// <param name="other">The sequence of items to check against this set.</param> /// <returns>A value indicating whether the sets are equal.</returns> [Pure] public bool SetEquals(IEnumerable<T> other) { Requires.NotNull(other, "other"); return SetEquals(other, this.Origin); } /// <summary> /// Determines whether the current set is a property (strict) subset of a specified collection. /// </summary> /// <param name="other">The collection to compare to the current set.</param> /// <returns>true if the current set is a correct subset of other; otherwise, false.</returns> [Pure] public bool IsProperSubsetOf(IEnumerable<T> other) { Requires.NotNull(other, "other"); return IsProperSubsetOf(other, this.Origin); } /// <summary> /// Determines whether the current set is a correct superset of a specified collection. /// </summary> /// <param name="other">The collection to compare to the current set.</param> /// <returns>true if the current set is a correct superset of other; otherwise, false.</returns> [Pure] public bool IsProperSupersetOf(IEnumerable<T> other) { Requires.NotNull(other, "other"); return IsProperSupersetOf(other, this.Origin); } /// <summary> /// Determines whether a set is a subset of a specified collection. /// </summary> /// <param name="other">The collection to compare to the current set.</param> /// <returns>true if the current set is a subset of other; otherwise, false.</returns> [Pure] public bool IsSubsetOf(IEnumerable<T> other) { Requires.NotNull(other, "other"); return IsSubsetOf(other, this.Origin); } /// <summary> /// Determines whether the current set is a superset of a specified collection. /// </summary> /// <param name="other">The collection to compare to the current set.</param> /// <returns>true if the current set is a superset of other; otherwise, false.</returns> [Pure] public bool IsSupersetOf(IEnumerable<T> other) { Requires.NotNull(other, "other"); return IsSupersetOf(other, this.Origin); } /// <summary> /// Determines whether the current set overlaps with the specified collection. /// </summary> /// <param name="other">The collection to compare to the current set.</param> /// <returns>true if the current set and other share at least one common element; otherwise, false.</returns> [Pure] public bool Overlaps(IEnumerable<T> other) { Requires.NotNull(other, "other"); return Overlaps(other, this.Origin); } #endregion #region IImmutableSet<T> Methods /// <summary> /// See the <see cref="IImmutableSet&lt;T&gt;"/> interface. /// </summary> [ExcludeFromCodeCoverage] IImmutableSet<T> IImmutableSet<T>.Add(T item) { return this.Add(item); } /// <summary> /// See the <see cref="IImmutableSet&lt;T&gt;"/> interface. /// </summary> [ExcludeFromCodeCoverage] IImmutableSet<T> IImmutableSet<T>.Remove(T item) { return this.Remove(item); } /// <summary> /// See the <see cref="IImmutableSet&lt;T&gt;"/> interface. /// </summary> [ExcludeFromCodeCoverage] IImmutableSet<T> IImmutableSet<T>.Union(IEnumerable<T> other) { return this.Union(other); } /// <summary> /// See the <see cref="IImmutableSet&lt;T&gt;"/> interface. /// </summary> [ExcludeFromCodeCoverage] IImmutableSet<T> IImmutableSet<T>.Intersect(IEnumerable<T> other) { return this.Intersect(other); } /// <summary> /// See the <see cref="IImmutableSet&lt;T&gt;"/> interface. /// </summary> [ExcludeFromCodeCoverage] IImmutableSet<T> IImmutableSet<T>.Except(IEnumerable<T> other) { return this.Except(other); } /// <summary> /// Produces a set that contains elements either in this set or a given sequence, but not both. /// </summary> /// <param name="other">The other sequence of items.</param> /// <returns>The new set.</returns> [ExcludeFromCodeCoverage] IImmutableSet<T> IImmutableSet<T>.SymmetricExcept(IEnumerable<T> other) { return this.SymmetricExcept(other); } /// <summary> /// See the <see cref="IImmutableSet&lt;T&gt;"/> interface. /// </summary> public bool Contains(T item) { Requires.NotNullAllowStructs(item, "item"); return Contains(item, this.Origin); } /// <summary> /// See the <see cref="IImmutableSet&lt;T&gt;"/> interface. /// </summary> [Pure] public ImmutableHashSet<T> WithComparer(IEqualityComparer<T> equalityComparer) { Contract.Ensures(Contract.Result<ImmutableHashSet<T>>() != null); if (equalityComparer == null) { equalityComparer = EqualityComparer<T>.Default; } if (equalityComparer == this.equalityComparer) { return this; } else { var result = new ImmutableHashSet<T>(equalityComparer); result = result.Union(this, avoidWithComparer: true); return result; } } #endregion #region ISet<T> Members /// <summary> /// See <see cref="ISet{T}"/> /// </summary> bool ISet<T>.Add(T item) { throw new NotSupportedException(); } /// <summary> /// See <see cref="ISet{T}"/> /// </summary> void ISet<T>.ExceptWith(IEnumerable<T> other) { throw new NotSupportedException(); } /// <summary> /// See <see cref="ISet{T}"/> /// </summary> void ISet<T>.IntersectWith(IEnumerable<T> other) { throw new NotSupportedException(); } /// <summary> /// See <see cref="ISet{T}"/> /// </summary> void ISet<T>.SymmetricExceptWith(IEnumerable<T> other) { throw new NotSupportedException(); } /// <summary> /// See <see cref="ISet{T}"/> /// </summary> void ISet<T>.UnionWith(IEnumerable<T> other) { throw new NotSupportedException(); } #endregion #region ICollection<T> members /// <summary> /// See the <see cref="ICollection{T}"/> interface. /// </summary> bool ICollection<T>.IsReadOnly { get { return true; } } /// <summary> /// See the <see cref="ICollection{T}"/> interface. /// </summary> void ICollection<T>.CopyTo(T[] array, int arrayIndex) { Requires.NotNull(array, "array"); Requires.Range(arrayIndex >= 0, "arrayIndex"); Requires.Range(array.Length >= arrayIndex + this.Count, "arrayIndex"); foreach (T item in this) { array[arrayIndex++] = item; } } /// <summary> /// See the <see cref="IList{T}"/> interface. /// </summary> void ICollection<T>.Add(T item) { throw new NotSupportedException(); } /// <summary> /// See the <see cref="ICollection{T}"/> interface. /// </summary> void ICollection<T>.Clear() { throw new NotSupportedException(); } /// <summary> /// See the <see cref="IList{T}"/> interface. /// </summary> bool ICollection<T>.Remove(T item) { throw new NotSupportedException(); } #endregion #region ICollection Methods /// <summary> /// Copies the elements of the <see cref="T:System.Collections.ICollection" /> to an <see cref="T:System.Array" />, starting at a particular <see cref="T:System.Array" /> index. /// </summary> /// <param name="array">The one-dimensional <see cref="T:System.Array" /> that is the destination of the elements copied from <see cref="T:System.Collections.ICollection" />. The <see cref="T:System.Array" /> must have zero-based indexing.</param> /// <param name="arrayIndex">The zero-based index in <paramref name="array" /> at which copying begins.</param> void ICollection.CopyTo(Array array, int arrayIndex) { Requires.NotNull(array, "array"); Requires.Range(arrayIndex >= 0, "arrayIndex"); Requires.Range(array.Length >= arrayIndex + this.Count, "arrayIndex"); if (this.count == 0) { return; } int[] indices = new int[1]; // SetValue takes a params array; lifting out the implicit allocation from the loop foreach (T item in this) { indices[0] = arrayIndex++; array.SetValue(item, indices); } } #endregion #region IEnumerable<T> Members /// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> /// <returns> /// A <see cref="T:System.Collections.Generic.IEnumerator`1"/> that can be used to iterate through the collection. /// </returns> public Enumerator GetEnumerator() { return new Enumerator(this.root); } /// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> IEnumerator<T> IEnumerable<T>.GetEnumerator() { return this.GetEnumerator(); } #endregion #region IEnumerable Members /// <summary> /// Returns an enumerator that iterates through a collection. /// </summary> /// <returns> /// An <see cref="T:System.Collections.IEnumerator"/> object that can be used to iterate through the collection. /// </returns> IEnumerator IEnumerable.GetEnumerator() { return this.GetEnumerator(); } #endregion #region Static query and manipulator methods /// <summary> /// Performs the set operation on a given data structure. /// </summary> private static bool IsSupersetOf(IEnumerable<T> other, MutationInput origin) { Requires.NotNull(other, "other"); foreach (T item in other) { if (!Contains(item, origin)) { return false; } } return true; } /// <summary> /// Performs the set operation on a given data structure. /// </summary> private static MutationResult Add(T item, MutationInput origin) { Requires.NotNullAllowStructs(item, "item"); OperationResult result; int hashCode = origin.EqualityComparer.GetHashCode(item); HashBucket bucket = origin.Root.GetValueOrDefault(hashCode, Comparer<int>.Default); var newBucket = bucket.Add(item, origin.EqualityComparer, out result); if (result == OperationResult.NoChangeRequired) { return new MutationResult(origin.Root, 0); } var newRoot = UpdateRoot(origin.Root, hashCode, newBucket); Debug.Assert(result == OperationResult.SizeChanged); return new MutationResult(newRoot, 1 /*result == OperationResult.SizeChanged ? 1 : 0*/); } /// <summary> /// Performs the set operation on a given data structure. /// </summary> private static MutationResult Remove(T item, MutationInput origin) { Requires.NotNullAllowStructs(item, "item"); var result = OperationResult.NoChangeRequired; int hashCode = origin.EqualityComparer.GetHashCode(item); HashBucket bucket; var newRoot = origin.Root; if (origin.Root.TryGetValue(hashCode, Comparer<int>.Default, out bucket)) { var newBucket = bucket.Remove(item, origin.EqualityComparer, out result); if (result == OperationResult.NoChangeRequired) { return new MutationResult(origin.Root, 0); } newRoot = UpdateRoot(origin.Root, hashCode, newBucket); } return new MutationResult(newRoot, result == OperationResult.SizeChanged ? -1 : 0); } /// <summary> /// Performs the set operation on a given data structure. /// </summary> private static bool Contains(T item, MutationInput origin) { int hashCode = origin.EqualityComparer.GetHashCode(item); HashBucket bucket; if (origin.Root.TryGetValue(hashCode, Comparer<int>.Default, out bucket)) { return bucket.Contains(item, origin.EqualityComparer); } return false; } /// <summary> /// Performs the set operation on a given data structure. /// </summary> private static MutationResult Union(IEnumerable<T> other, MutationInput origin) { Requires.NotNull(other, "other"); int count = 0; var newRoot = origin.Root; foreach (var item in other) { int hashCode = origin.EqualityComparer.GetHashCode(item); HashBucket bucket = newRoot.GetValueOrDefault(hashCode, Comparer<int>.Default); OperationResult result; var newBucket = bucket.Add(item, origin.EqualityComparer, out result); if (result == OperationResult.SizeChanged) { newRoot = UpdateRoot(newRoot, hashCode, newBucket); count++; } } return new MutationResult(newRoot, count); } /// <summary> /// Performs the set operation on a given data structure. /// </summary> private static bool Overlaps(IEnumerable<T> other, MutationInput origin) { Requires.NotNull(other, "other"); if (origin.Root.IsEmpty) { return false; } foreach (T item in other) { if (Contains(item, origin)) { return true; } } return false; } /// <summary> /// Performs the set operation on a given data structure. /// </summary> private static bool SetEquals(IEnumerable<T> other, MutationInput origin) { Requires.NotNull(other, "other"); var otherSet = new HashSet<T>(other, origin.EqualityComparer); if (origin.Count != otherSet.Count) { return false; } int matches = 0; foreach (T item in otherSet) { if (!Contains(item, origin)) { return false; } matches++; } return matches == origin.Count; } /// <summary> /// Performs the set operation on a given data structure. /// </summary> private static ImmutableSortedDictionary<int, HashBucket>.Node UpdateRoot(ImmutableSortedDictionary<int, HashBucket>.Node root, int hashCode, HashBucket newBucket) { bool mutated; if (newBucket.IsEmpty) { return root.Remove(hashCode, Comparer<int>.Default, out mutated); } else { bool replacedExistingValue; return root.SetItem(hashCode, newBucket, Comparer<int>.Default, EqualityComparer<HashBucket>.Default, out replacedExistingValue, out mutated); } } /// <summary> /// Performs the set operation on a given data structure. /// </summary> private static MutationResult Intersect(IEnumerable<T> other, MutationInput origin) { Requires.NotNull(other, "other"); var newSet = ImmutableSortedDictionary<int, HashBucket>.Node.EmptyNode; int count = 0; foreach (var item in other) { if (Contains(item, origin)) { var result = Add(item, new MutationInput(newSet, origin.EqualityComparer, count)); newSet = result.Root; count += result.Count; } } return new MutationResult(newSet, count, CountType.FinalValue); } /// <summary> /// Performs the set operation on a given data structure. /// </summary> private static MutationResult Except(IEnumerable<T> other, IEqualityComparer<T> equalityComparer, ImmutableSortedDictionary<int, HashBucket>.Node root) { Requires.NotNull(other, "other"); Requires.NotNull(equalityComparer, "equalityComparer"); Requires.NotNull(root, "root"); int count = 0; var newRoot = root; foreach (var item in other) { int hashCode = equalityComparer.GetHashCode(item); HashBucket bucket; if (newRoot.TryGetValue(hashCode, Comparer<int>.Default, out bucket)) { OperationResult result; HashBucket newBucket = bucket.Remove(item, equalityComparer, out result); if (result == OperationResult.SizeChanged) { count--; newRoot = UpdateRoot(newRoot, hashCode, newBucket); } } } return new MutationResult(newRoot, count); } /// <summary> /// Performs the set operation on a given data structure. /// </summary> [Pure] private static MutationResult SymmetricExcept(IEnumerable<T> other, MutationInput origin) { Requires.NotNull(other, "other"); var otherAsSet = Empty.Union(other); int count = 0; var result = ImmutableSortedDictionary<int, HashBucket>.Node.EmptyNode; foreach (T item in new NodeEnumerable(origin.Root)) { if (!otherAsSet.Contains(item)) { var mutationResult = Add(item, new MutationInput(result, origin.EqualityComparer, count)); result = mutationResult.Root; count += mutationResult.Count; } } foreach (T item in otherAsSet) { if (!Contains(item, origin)) { var mutationResult = Add(item, new MutationInput(result, origin.EqualityComparer, count)); result = mutationResult.Root; count += mutationResult.Count; } } return new MutationResult(result, count, CountType.FinalValue); } /// <summary> /// Performs the set operation on a given data structure. /// </summary> private static bool IsProperSubsetOf(IEnumerable<T> other, MutationInput origin) { Requires.NotNull(other, "other"); if (origin.Root.IsEmpty) { return other.Any(); } // To determine whether everything we have is also in another sequence, // we enumerate the sequence and "tag" whether it's in this collection, // then consider whether every element in this collection was tagged. // Since this collection is immutable we cannot directly tag. So instead // we simply count how many "hits" we have and ensure it's equal to the // size of this collection. Of course for this to work we need to ensure // the uniqueness of items in the given sequence, so we create a set based // on the sequence first. var otherSet = new HashSet<T>(other, origin.EqualityComparer); if (origin.Count >= otherSet.Count) { return false; } int matches = 0; bool extraFound = false; foreach (T item in otherSet) { if (Contains(item, origin)) { matches++; } else { extraFound = true; } if (matches == origin.Count && extraFound) { return true; } } return false; } /// <summary> /// Performs the set operation on a given data structure. /// </summary> private static bool IsProperSupersetOf(IEnumerable<T> other, MutationInput origin) { Requires.NotNull(other, "other"); if (origin.Root.IsEmpty) { return false; } int matchCount = 0; foreach (T item in other) { matchCount++; if (!Contains(item, origin)) { return false; } } return origin.Count > matchCount; } /// <summary> /// Performs the set operation on a given data structure. /// </summary> private static bool IsSubsetOf(IEnumerable<T> other, MutationInput origin) { Requires.NotNull(other, "other"); if (origin.Root.IsEmpty) { return true; } // To determine whether everything we have is also in another sequence, // we enumerate the sequence and "tag" whether it's in this collection, // then consider whether every element in this collection was tagged. // Since this collection is immutable we cannot directly tag. So instead // we simply count how many "hits" we have and ensure it's equal to the // size of this collection. Of course for this to work we need to ensure // the uniqueness of items in the given sequence, so we create a set based // on the sequence first. var otherSet = new HashSet<T>(other, origin.EqualityComparer); int matches = 0; foreach (T item in otherSet) { if (Contains(item, origin)) { matches++; } } return matches == origin.Count; } #endregion /// <summary> /// Wraps the specified data structure with an immutable collection wrapper. /// </summary> /// <param name="root">The root of the data structure.</param> /// <param name="equalityComparer">The equality comparer.</param> /// <param name="count">The number of elements in the data structure.</param> /// <returns>The immutable collection.</returns> private static ImmutableHashSet<T> Wrap(ImmutableSortedDictionary<int, HashBucket>.Node root, IEqualityComparer<T> equalityComparer, int count) { Requires.NotNull(root, "root"); Requires.NotNull(equalityComparer, "equalityComparer"); Requires.Range(count >= 0, "count"); return new ImmutableHashSet<T>(root, equalityComparer, count); } /// <summary> /// Wraps the specified data structure with an immutable collection wrapper. /// </summary> /// <param name="root">The root of the data structure.</param> /// <param name="adjustedCountIfDifferentRoot">The adjusted count if the root has changed.</param> /// <returns>The immutable collection.</returns> private ImmutableHashSet<T> Wrap(ImmutableSortedDictionary<int, HashBucket>.Node root, int adjustedCountIfDifferentRoot) { return (root != this.root) ? new ImmutableHashSet<T>(root, this.equalityComparer, adjustedCountIfDifferentRoot) : this; } /// <summary> /// Bulk adds entries to the set. /// </summary> /// <param name="items">The entries to add.</param> /// <param name="avoidWithComparer"><c>true</c> when being called from ToHashSet to avoid StackOverflow.</param> [Pure] private ImmutableHashSet<T> Union(IEnumerable<T> items, bool avoidWithComparer) { Requires.NotNull(items, "items"); Contract.Ensures(Contract.Result<ImmutableHashSet<T>>() != null); // Some optimizations may apply if we're an empty set. if (this.IsEmpty && !avoidWithComparer) { // If the items being added actually come from an ImmutableHashSet<T>, // reuse that instance if possible. var other = items as ImmutableHashSet<T>; if (other != null) { return other.WithComparer(this.KeyComparer); } } var result = Union(items, this.Origin); return result.Finalize(this); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /*============================================================ ** ** ** ** ** ** Purpose: Abstract base class for all Streams. Provides ** default implementations of asynchronous reads & writes, in ** terms of the synchronous reads & writes (and vice versa). ** ** ===========================================================*/ using System; using System.Buffers; using System.Threading; using System.Threading.Tasks; using System.Runtime; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Runtime.ExceptionServices; using System.Security; using System.Diagnostics; using System.Reflection; namespace System.IO { public abstract class Stream : MarshalByRefObject, IDisposable { public static readonly Stream Null = new NullStream(); //We pick a value that is the largest multiple of 4096 that is still smaller than the large object heap threshold (85K). // The CopyTo/CopyToAsync buffer is short-lived and is likely to be collected at Gen0, and it offers a significant // improvement in Copy performance. private const int _DefaultCopyBufferSize = 81920; // To implement Async IO operations on streams that don't support async IO private ReadWriteTask _activeReadWriteTask; private SemaphoreSlim _asyncActiveSemaphore; internal SemaphoreSlim EnsureAsyncActiveSemaphoreInitialized() { // Lazily-initialize _asyncActiveSemaphore. As we're never accessing the SemaphoreSlim's // WaitHandle, we don't need to worry about Disposing it. return LazyInitializer.EnsureInitialized(ref _asyncActiveSemaphore, () => new SemaphoreSlim(1, 1)); } public abstract bool CanRead { get; } // If CanSeek is false, Position, Seek, Length, and SetLength should throw. public abstract bool CanSeek { get; } public virtual bool CanTimeout { get { return false; } } public abstract bool CanWrite { get; } public abstract long Length { get; } public abstract long Position { get; set; } public virtual int ReadTimeout { get { throw new InvalidOperationException(SR.InvalidOperation_TimeoutsNotSupported); } set { throw new InvalidOperationException(SR.InvalidOperation_TimeoutsNotSupported); } } public virtual int WriteTimeout { get { throw new InvalidOperationException(SR.InvalidOperation_TimeoutsNotSupported); } set { throw new InvalidOperationException(SR.InvalidOperation_TimeoutsNotSupported); } } public Task CopyToAsync(Stream destination) { int bufferSize = GetCopyBufferSize(); return CopyToAsync(destination, bufferSize); } public Task CopyToAsync(Stream destination, Int32 bufferSize) { return CopyToAsync(destination, bufferSize, CancellationToken.None); } public Task CopyToAsync(Stream destination, CancellationToken cancellationToken) { int bufferSize = GetCopyBufferSize(); return CopyToAsync(destination, bufferSize, cancellationToken); } public virtual Task CopyToAsync(Stream destination, Int32 bufferSize, CancellationToken cancellationToken) { StreamHelpers.ValidateCopyToArgs(this, destination, bufferSize); return CopyToAsyncInternal(destination, bufferSize, cancellationToken); } private async Task CopyToAsyncInternal(Stream destination, Int32 bufferSize, CancellationToken cancellationToken) { Debug.Assert(destination != null); Debug.Assert(bufferSize > 0); Debug.Assert(CanRead); Debug.Assert(destination.CanWrite); byte[] buffer = ArrayPool<byte>.Shared.Rent(bufferSize); bufferSize = 0; // reuse same field for high water mark to avoid needing another field in the state machine try { while (true) { int bytesRead = await ReadAsync(buffer, 0, buffer.Length, cancellationToken).ConfigureAwait(false); if (bytesRead == 0) break; if (bytesRead > bufferSize) bufferSize = bytesRead; await destination.WriteAsync(buffer, 0, bytesRead, cancellationToken).ConfigureAwait(false); } } finally { Array.Clear(buffer, 0, bufferSize); // clear only the most we used ArrayPool<byte>.Shared.Return(buffer, clearArray: false); } } // Reads the bytes from the current stream and writes the bytes to // the destination stream until all bytes are read, starting at // the current position. public void CopyTo(Stream destination) { int bufferSize = GetCopyBufferSize(); CopyTo(destination, bufferSize); } public virtual void CopyTo(Stream destination, int bufferSize) { StreamHelpers.ValidateCopyToArgs(this, destination, bufferSize); byte[] buffer = ArrayPool<byte>.Shared.Rent(bufferSize); int highwaterMark = 0; try { int read; while ((read = Read(buffer, 0, buffer.Length)) != 0) { if (read > highwaterMark) highwaterMark = read; destination.Write(buffer, 0, read); } } finally { Array.Clear(buffer, 0, highwaterMark); // clear only the most we used ArrayPool<byte>.Shared.Return(buffer, clearArray: false); } } private int GetCopyBufferSize() { int bufferSize = _DefaultCopyBufferSize; if (CanSeek) { long length = Length; long position = Position; if (length <= position) // Handles negative overflows { // There are no bytes left in the stream to copy. // However, because CopyTo{Async} is virtual, we need to // ensure that any override is still invoked to provide its // own validation, so we use the smallest legal buffer size here. bufferSize = 1; } else { long remaining = length - position; if (remaining > 0) { // In the case of a positive overflow, stick to the default size bufferSize = (int)Math.Min(bufferSize, remaining); } } } return bufferSize; } // Stream used to require that all cleanup logic went into Close(), // which was thought up before we invented IDisposable. However, we // need to follow the IDisposable pattern so that users can write // sensible subclasses without needing to inspect all their base // classes, and without worrying about version brittleness, from a // base class switching to the Dispose pattern. We're moving // Stream to the Dispose(bool) pattern - that's where all subclasses // should put their cleanup starting in V2. public virtual void Close() { // Ideally we would assert CanRead == CanWrite == CanSeek = false, // but we'd have to fix PipeStream & NetworkStream very carefully. Dispose(true); GC.SuppressFinalize(this); } public void Dispose() { // Ideally we would assert CanRead == CanWrite == CanSeek = false, // but we'd have to fix PipeStream & NetworkStream very carefully. Close(); } protected virtual void Dispose(bool disposing) { // Note: Never change this to call other virtual methods on Stream // like Write, since the state on subclasses has already been // torn down. This is the last code to run on cleanup for a stream. } public abstract void Flush(); public Task FlushAsync() { return FlushAsync(CancellationToken.None); } public virtual Task FlushAsync(CancellationToken cancellationToken) { return Task.Factory.StartNew(state => ((Stream)state).Flush(), this, cancellationToken, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); } [Obsolete("CreateWaitHandle will be removed eventually. Please use \"new ManualResetEvent(false)\" instead.")] protected virtual WaitHandle CreateWaitHandle() { return new ManualResetEvent(false); } public virtual IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, Object state) { return BeginReadInternal(buffer, offset, count, callback, state, serializeAsynchronously: false, apm: true); } internal IAsyncResult BeginReadInternal( byte[] buffer, int offset, int count, AsyncCallback callback, Object state, bool serializeAsynchronously, bool apm) { if (!CanRead) throw Error.GetReadNotSupported(); // To avoid a race with a stream's position pointer & generating race conditions // with internal buffer indexes in our own streams that // don't natively support async IO operations when there are multiple // async requests outstanding, we will block the application's main // thread if it does a second IO request until the first one completes. var semaphore = EnsureAsyncActiveSemaphoreInitialized(); Task semaphoreTask = null; if (serializeAsynchronously) { semaphoreTask = semaphore.WaitAsync(); } else { semaphore.Wait(); } // Create the task to asynchronously do a Read. This task serves both // as the asynchronous work item and as the IAsyncResult returned to the user. var asyncResult = new ReadWriteTask(true /*isRead*/, apm, delegate { // The ReadWriteTask stores all of the parameters to pass to Read. // As we're currently inside of it, we can get the current task // and grab the parameters from it. var thisTask = Task.InternalCurrent as ReadWriteTask; Debug.Assert(thisTask != null, "Inside ReadWriteTask, InternalCurrent should be the ReadWriteTask"); try { // Do the Read and return the number of bytes read return thisTask._stream.Read(thisTask._buffer, thisTask._offset, thisTask._count); } finally { // If this implementation is part of Begin/EndXx, then the EndXx method will handle // finishing the async operation. However, if this is part of XxAsync, then there won't // be an end method, and this task is responsible for cleaning up. if (!thisTask._apm) { thisTask._stream.FinishTrackingAsyncOperation(); } thisTask.ClearBeginState(); // just to help alleviate some memory pressure } }, state, this, buffer, offset, count, callback); // Schedule it if (semaphoreTask != null) RunReadWriteTaskWhenReady(semaphoreTask, asyncResult); else RunReadWriteTask(asyncResult); return asyncResult; // return it } public virtual int EndRead(IAsyncResult asyncResult) { if (asyncResult == null) throw new ArgumentNullException(nameof(asyncResult)); var readTask = _activeReadWriteTask; if (readTask == null) { throw new ArgumentException(SR.InvalidOperation_WrongAsyncResultOrEndReadCalledMultiple); } else if (readTask != asyncResult) { throw new InvalidOperationException(SR.InvalidOperation_WrongAsyncResultOrEndReadCalledMultiple); } else if (!readTask._isRead) { throw new ArgumentException(SR.InvalidOperation_WrongAsyncResultOrEndReadCalledMultiple); } try { return readTask.GetAwaiter().GetResult(); // block until completion, then get result / propagate any exception } finally { FinishTrackingAsyncOperation(); } } public Task<int> ReadAsync(Byte[] buffer, int offset, int count) { return ReadAsync(buffer, offset, count, CancellationToken.None); } public virtual Task<int> ReadAsync(Byte[] buffer, int offset, int count, CancellationToken cancellationToken) { // If cancellation was requested, bail early with an already completed task. // Otherwise, return a task that represents the Begin/End methods. return cancellationToken.IsCancellationRequested ? Task.FromCanceled<int>(cancellationToken) : BeginEndReadAsync(buffer, offset, count); } public virtual ValueTask<int> ReadAsync(Memory<byte> destination, CancellationToken cancellationToken = default(CancellationToken)) { if (destination.TryGetArray(out ArraySegment<byte> array)) { return new ValueTask<int>(ReadAsync(array.Array, array.Offset, array.Count, cancellationToken)); } else { byte[] buffer = ArrayPool<byte>.Shared.Rent(destination.Length); return FinishReadAsync(ReadAsync(buffer, 0, destination.Length, cancellationToken), buffer, destination); async ValueTask<int> FinishReadAsync(Task<int> readTask, byte[] localBuffer, Memory<byte> localDestination) { try { int result = await readTask.ConfigureAwait(false); new Span<byte>(localBuffer, 0, result).CopyTo(localDestination.Span); return result; } finally { ArrayPool<byte>.Shared.Return(localBuffer); } } } } [MethodImplAttribute(MethodImplOptions.InternalCall)] private extern bool HasOverriddenBeginEndRead(); private Task<Int32> BeginEndReadAsync(Byte[] buffer, Int32 offset, Int32 count) { if (!HasOverriddenBeginEndRead()) { // If the Stream does not override Begin/EndRead, then we can take an optimized path // that skips an extra layer of tasks / IAsyncResults. return (Task<Int32>)BeginReadInternal(buffer, offset, count, null, null, serializeAsynchronously: true, apm: false); } // Otherwise, we need to wrap calls to Begin/EndWrite to ensure we use the derived type's functionality. return TaskFactory<Int32>.FromAsyncTrim( this, new ReadWriteParameters { Buffer = buffer, Offset = offset, Count = count }, (stream, args, callback, state) => stream.BeginRead(args.Buffer, args.Offset, args.Count, callback, state), // cached by compiler (stream, asyncResult) => stream.EndRead(asyncResult)); // cached by compiler } private struct ReadWriteParameters // struct for arguments to Read and Write calls { internal byte[] Buffer; internal int Offset; internal int Count; } public virtual IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, Object state) { return BeginWriteInternal(buffer, offset, count, callback, state, serializeAsynchronously: false, apm: true); } internal IAsyncResult BeginWriteInternal( byte[] buffer, int offset, int count, AsyncCallback callback, Object state, bool serializeAsynchronously, bool apm) { if (!CanWrite) throw Error.GetWriteNotSupported(); // To avoid a race condition with a stream's position pointer & generating conditions // with internal buffer indexes in our own streams that // don't natively support async IO operations when there are multiple // async requests outstanding, we will block the application's main // thread if it does a second IO request until the first one completes. var semaphore = EnsureAsyncActiveSemaphoreInitialized(); Task semaphoreTask = null; if (serializeAsynchronously) { semaphoreTask = semaphore.WaitAsync(); // kick off the asynchronous wait, but don't block } else { semaphore.Wait(); // synchronously wait here } // Create the task to asynchronously do a Write. This task serves both // as the asynchronous work item and as the IAsyncResult returned to the user. var asyncResult = new ReadWriteTask(false /*isRead*/, apm, delegate { // The ReadWriteTask stores all of the parameters to pass to Write. // As we're currently inside of it, we can get the current task // and grab the parameters from it. var thisTask = Task.InternalCurrent as ReadWriteTask; Debug.Assert(thisTask != null, "Inside ReadWriteTask, InternalCurrent should be the ReadWriteTask"); try { // Do the Write thisTask._stream.Write(thisTask._buffer, thisTask._offset, thisTask._count); return 0; // not used, but signature requires a value be returned } finally { // If this implementation is part of Begin/EndXx, then the EndXx method will handle // finishing the async operation. However, if this is part of XxAsync, then there won't // be an end method, and this task is responsible for cleaning up. if (!thisTask._apm) { thisTask._stream.FinishTrackingAsyncOperation(); } thisTask.ClearBeginState(); // just to help alleviate some memory pressure } }, state, this, buffer, offset, count, callback); // Schedule it if (semaphoreTask != null) RunReadWriteTaskWhenReady(semaphoreTask, asyncResult); else RunReadWriteTask(asyncResult); return asyncResult; // return it } private void RunReadWriteTaskWhenReady(Task asyncWaiter, ReadWriteTask readWriteTask) { Debug.Assert(readWriteTask != null); Debug.Assert(asyncWaiter != null); // If the wait has already completed, run the task. if (asyncWaiter.IsCompleted) { Debug.Assert(asyncWaiter.IsCompletedSuccessfully, "The semaphore wait should always complete successfully."); RunReadWriteTask(readWriteTask); } else // Otherwise, wait for our turn, and then run the task. { asyncWaiter.ContinueWith((t, state) => { Debug.Assert(t.IsCompletedSuccessfully, "The semaphore wait should always complete successfully."); var rwt = (ReadWriteTask)state; rwt._stream.RunReadWriteTask(rwt); // RunReadWriteTask(readWriteTask); }, readWriteTask, default(CancellationToken), TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); } } private void RunReadWriteTask(ReadWriteTask readWriteTask) { Debug.Assert(readWriteTask != null); Debug.Assert(_activeReadWriteTask == null, "Expected no other readers or writers"); // Schedule the task. ScheduleAndStart must happen after the write to _activeReadWriteTask to avoid a race. // Internally, we're able to directly call ScheduleAndStart rather than Start, avoiding // two interlocked operations. However, if ReadWriteTask is ever changed to use // a cancellation token, this should be changed to use Start. _activeReadWriteTask = readWriteTask; // store the task so that EndXx can validate it's given the right one readWriteTask.m_taskScheduler = TaskScheduler.Default; readWriteTask.ScheduleAndStart(needsProtection: false); } private void FinishTrackingAsyncOperation() { _activeReadWriteTask = null; Debug.Assert(_asyncActiveSemaphore != null, "Must have been initialized in order to get here."); _asyncActiveSemaphore.Release(); } public virtual void EndWrite(IAsyncResult asyncResult) { if (asyncResult == null) throw new ArgumentNullException(nameof(asyncResult)); var writeTask = _activeReadWriteTask; if (writeTask == null) { throw new ArgumentException(SR.InvalidOperation_WrongAsyncResultOrEndWriteCalledMultiple); } else if (writeTask != asyncResult) { throw new InvalidOperationException(SR.InvalidOperation_WrongAsyncResultOrEndWriteCalledMultiple); } else if (writeTask._isRead) { throw new ArgumentException(SR.InvalidOperation_WrongAsyncResultOrEndWriteCalledMultiple); } try { writeTask.GetAwaiter().GetResult(); // block until completion, then propagate any exceptions Debug.Assert(writeTask.Status == TaskStatus.RanToCompletion); } finally { FinishTrackingAsyncOperation(); } } // Task used by BeginRead / BeginWrite to do Read / Write asynchronously. // A single instance of this task serves four purposes: // 1. The work item scheduled to run the Read / Write operation // 2. The state holding the arguments to be passed to Read / Write // 3. The IAsyncResult returned from BeginRead / BeginWrite // 4. The completion action that runs to invoke the user-provided callback. // This last item is a bit tricky. Before the AsyncCallback is invoked, the // IAsyncResult must have completed, so we can't just invoke the handler // from within the task, since it is the IAsyncResult, and thus it's not // yet completed. Instead, we use AddCompletionAction to install this // task as its own completion handler. That saves the need to allocate // a separate completion handler, it guarantees that the task will // have completed by the time the handler is invoked, and it allows // the handler to be invoked synchronously upon the completion of the // task. This all enables BeginRead / BeginWrite to be implemented // with a single allocation. private sealed class ReadWriteTask : Task<int>, ITaskCompletionAction { internal readonly bool _isRead; internal readonly bool _apm; // true if this is from Begin/EndXx; false if it's from XxAsync internal Stream _stream; internal byte[] _buffer; internal readonly int _offset; internal readonly int _count; private AsyncCallback _callback; private ExecutionContext _context; internal void ClearBeginState() // Used to allow the args to Read/Write to be made available for GC { _stream = null; _buffer = null; } public ReadWriteTask( bool isRead, bool apm, Func<object, int> function, object state, Stream stream, byte[] buffer, int offset, int count, AsyncCallback callback) : base(function, state, CancellationToken.None, TaskCreationOptions.DenyChildAttach) { Debug.Assert(function != null); Debug.Assert(stream != null); Debug.Assert(buffer != null); // Store the arguments _isRead = isRead; _apm = apm; _stream = stream; _buffer = buffer; _offset = offset; _count = count; // If a callback was provided, we need to: // - Store the user-provided handler // - Capture an ExecutionContext under which to invoke the handler // - Add this task as its own completion handler so that the Invoke method // will run the callback when this task completes. if (callback != null) { _callback = callback; _context = ExecutionContext.Capture(); base.AddCompletionAction(this); } } private static void InvokeAsyncCallback(object completedTask) { var rwc = (ReadWriteTask)completedTask; var callback = rwc._callback; rwc._callback = null; callback(rwc); } private static ContextCallback s_invokeAsyncCallback; void ITaskCompletionAction.Invoke(Task completingTask) { // Get the ExecutionContext. If there is none, just run the callback // directly, passing in the completed task as the IAsyncResult. // If there is one, process it with ExecutionContext.Run. var context = _context; if (context == null) { var callback = _callback; _callback = null; callback(completingTask); } else { _context = null; var invokeAsyncCallback = s_invokeAsyncCallback; if (invokeAsyncCallback == null) s_invokeAsyncCallback = invokeAsyncCallback = InvokeAsyncCallback; // benign race condition ExecutionContext.Run(context, invokeAsyncCallback, this); } } bool ITaskCompletionAction.InvokeMayRunArbitraryCode { get { return true; } } } public Task WriteAsync(Byte[] buffer, int offset, int count) { return WriteAsync(buffer, offset, count, CancellationToken.None); } public virtual Task WriteAsync(Byte[] buffer, int offset, int count, CancellationToken cancellationToken) { // If cancellation was requested, bail early with an already completed task. // Otherwise, return a task that represents the Begin/End methods. return cancellationToken.IsCancellationRequested ? Task.FromCanceled(cancellationToken) : BeginEndWriteAsync(buffer, offset, count); } public virtual Task WriteAsync(ReadOnlyMemory<byte> source, CancellationToken cancellationToken = default(CancellationToken)) { if (MemoryMarshal.TryGetArray(source, out ArraySegment<byte> array)) { return WriteAsync(array.Array, array.Offset, array.Count, cancellationToken); } else { byte[] buffer = ArrayPool<byte>.Shared.Rent(source.Length); source.Span.CopyTo(buffer); return FinishWriteAsync(WriteAsync(buffer, 0, source.Length, cancellationToken), buffer); async Task FinishWriteAsync(Task writeTask, byte[] localBuffer) { try { await writeTask.ConfigureAwait(false); } finally { ArrayPool<byte>.Shared.Return(localBuffer); } } } } [MethodImplAttribute(MethodImplOptions.InternalCall)] private extern bool HasOverriddenBeginEndWrite(); private Task BeginEndWriteAsync(Byte[] buffer, Int32 offset, Int32 count) { if (!HasOverriddenBeginEndWrite()) { // If the Stream does not override Begin/EndWrite, then we can take an optimized path // that skips an extra layer of tasks / IAsyncResults. return (Task)BeginWriteInternal(buffer, offset, count, null, null, serializeAsynchronously: true, apm: false); } // Otherwise, we need to wrap calls to Begin/EndWrite to ensure we use the derived type's functionality. return TaskFactory<VoidTaskResult>.FromAsyncTrim( this, new ReadWriteParameters { Buffer = buffer, Offset = offset, Count = count }, (stream, args, callback, state) => stream.BeginWrite(args.Buffer, args.Offset, args.Count, callback, state), // cached by compiler (stream, asyncResult) => // cached by compiler { stream.EndWrite(asyncResult); return default(VoidTaskResult); }); } public abstract long Seek(long offset, SeekOrigin origin); public abstract void SetLength(long value); public abstract int Read(byte[] buffer, int offset, int count); public virtual int Read(Span<byte> destination) { byte[] buffer = ArrayPool<byte>.Shared.Rent(destination.Length); try { int numRead = Read(buffer, 0, destination.Length); if ((uint)numRead > destination.Length) { throw new IOException(SR.IO_StreamTooLong); } new Span<byte>(buffer, 0, numRead).CopyTo(destination); return numRead; } finally { ArrayPool<byte>.Shared.Return(buffer); } } // Reads one byte from the stream by calling Read(byte[], int, int). // Will return an unsigned byte cast to an int or -1 on end of stream. // This implementation does not perform well because it allocates a new // byte[] each time you call it, and should be overridden by any // subclass that maintains an internal buffer. Then, it can help perf // significantly for people who are reading one byte at a time. public virtual int ReadByte() { byte[] oneByteArray = new byte[1]; int r = Read(oneByteArray, 0, 1); if (r == 0) return -1; return oneByteArray[0]; } public abstract void Write(byte[] buffer, int offset, int count); public virtual void Write(ReadOnlySpan<byte> source) { byte[] buffer = ArrayPool<byte>.Shared.Rent(source.Length); try { source.CopyTo(buffer); Write(buffer, 0, source.Length); } finally { ArrayPool<byte>.Shared.Return(buffer); } } // Writes one byte from the stream by calling Write(byte[], int, int). // This implementation does not perform well because it allocates a new // byte[] each time you call it, and should be overridden by any // subclass that maintains an internal buffer. Then, it can help perf // significantly for people who are writing one byte at a time. public virtual void WriteByte(byte value) { byte[] oneByteArray = new byte[1]; oneByteArray[0] = value; Write(oneByteArray, 0, 1); } public static Stream Synchronized(Stream stream) { if (stream == null) throw new ArgumentNullException(nameof(stream)); if (stream is SyncStream) return stream; return new SyncStream(stream); } [Obsolete("Do not call or override this method.")] protected virtual void ObjectInvariant() { } internal IAsyncResult BlockingBeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, Object state) { // To avoid a race with a stream's position pointer & generating conditions // with internal buffer indexes in our own streams that // don't natively support async IO operations when there are multiple // async requests outstanding, we will block the application's main // thread and do the IO synchronously. // This can't perform well - use a different approach. SynchronousAsyncResult asyncResult; try { int numRead = Read(buffer, offset, count); asyncResult = new SynchronousAsyncResult(numRead, state); } catch (IOException ex) { asyncResult = new SynchronousAsyncResult(ex, state, isWrite: false); } if (callback != null) { callback(asyncResult); } return asyncResult; } internal static int BlockingEndRead(IAsyncResult asyncResult) { return SynchronousAsyncResult.EndRead(asyncResult); } internal IAsyncResult BlockingBeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, Object state) { // To avoid a race condition with a stream's position pointer & generating conditions // with internal buffer indexes in our own streams that // don't natively support async IO operations when there are multiple // async requests outstanding, we will block the application's main // thread and do the IO synchronously. // This can't perform well - use a different approach. SynchronousAsyncResult asyncResult; try { Write(buffer, offset, count); asyncResult = new SynchronousAsyncResult(state); } catch (IOException ex) { asyncResult = new SynchronousAsyncResult(ex, state, isWrite: true); } if (callback != null) { callback(asyncResult); } return asyncResult; } internal static void BlockingEndWrite(IAsyncResult asyncResult) { SynchronousAsyncResult.EndWrite(asyncResult); } private sealed class NullStream : Stream { internal NullStream() { } public override bool CanRead { get { return true; } } public override bool CanWrite { get { return true; } } public override bool CanSeek { get { return true; } } public override long Length { get { return 0; } } public override long Position { get { return 0; } set { } } public override void CopyTo(Stream destination, int bufferSize) { StreamHelpers.ValidateCopyToArgs(this, destination, bufferSize); // After we validate arguments this is a nop. } public override Task CopyToAsync(Stream destination, int bufferSize, CancellationToken cancellationToken) { // Validate arguments here for compat, since previously this method // was inherited from Stream (which did check its arguments). StreamHelpers.ValidateCopyToArgs(this, destination, bufferSize); return cancellationToken.IsCancellationRequested ? Task.FromCanceled(cancellationToken) : Task.CompletedTask; } protected override void Dispose(bool disposing) { // Do nothing - we don't want NullStream singleton (static) to be closable } public override void Flush() { } public override Task FlushAsync(CancellationToken cancellationToken) { return cancellationToken.IsCancellationRequested ? Task.FromCanceled(cancellationToken) : Task.CompletedTask; } public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, Object state) { if (!CanRead) throw Error.GetReadNotSupported(); return BlockingBeginRead(buffer, offset, count, callback, state); } public override int EndRead(IAsyncResult asyncResult) { if (asyncResult == null) throw new ArgumentNullException(nameof(asyncResult)); return BlockingEndRead(asyncResult); } public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, Object state) { if (!CanWrite) throw Error.GetWriteNotSupported(); return BlockingBeginWrite(buffer, offset, count, callback, state); } public override void EndWrite(IAsyncResult asyncResult) { if (asyncResult == null) throw new ArgumentNullException(nameof(asyncResult)); BlockingEndWrite(asyncResult); } public override int Read(byte[] buffer, int offset, int count) { return 0; } public override int Read(Span<byte> destination) { return 0; } public override Task<int> ReadAsync(Byte[] buffer, int offset, int count, CancellationToken cancellationToken) { return AsyncTaskMethodBuilder<int>.s_defaultResultTask; } public override ValueTask<int> ReadAsync(Memory<byte> destination, CancellationToken cancellationToken = default(CancellationToken)) { return new ValueTask<int>(0); } public override int ReadByte() { return -1; } public override void Write(byte[] buffer, int offset, int count) { } public override void Write(ReadOnlySpan<byte> source) { } public override Task WriteAsync(Byte[] buffer, int offset, int count, CancellationToken cancellationToken) { return cancellationToken.IsCancellationRequested ? Task.FromCanceled(cancellationToken) : Task.CompletedTask; } public override Task WriteAsync(ReadOnlyMemory<byte> source, CancellationToken cancellationToken = default(CancellationToken)) { return cancellationToken.IsCancellationRequested ? Task.FromCanceled(cancellationToken) : Task.CompletedTask; } public override void WriteByte(byte value) { } public override long Seek(long offset, SeekOrigin origin) { return 0; } public override void SetLength(long length) { } } /// <summary>Used as the IAsyncResult object when using asynchronous IO methods on the base Stream class.</summary> internal sealed class SynchronousAsyncResult : IAsyncResult { private readonly Object _stateObject; private readonly bool _isWrite; private ManualResetEvent _waitHandle; private ExceptionDispatchInfo _exceptionInfo; private bool _endXxxCalled; private Int32 _bytesRead; internal SynchronousAsyncResult(Int32 bytesRead, Object asyncStateObject) { _bytesRead = bytesRead; _stateObject = asyncStateObject; //_isWrite = false; } internal SynchronousAsyncResult(Object asyncStateObject) { _stateObject = asyncStateObject; _isWrite = true; } internal SynchronousAsyncResult(Exception ex, Object asyncStateObject, bool isWrite) { _exceptionInfo = ExceptionDispatchInfo.Capture(ex); _stateObject = asyncStateObject; _isWrite = isWrite; } public bool IsCompleted { // We never hand out objects of this type to the user before the synchronous IO completed: get { return true; } } public WaitHandle AsyncWaitHandle { get { return LazyInitializer.EnsureInitialized(ref _waitHandle, () => new ManualResetEvent(true)); } } public Object AsyncState { get { return _stateObject; } } public bool CompletedSynchronously { get { return true; } } internal void ThrowIfError() { if (_exceptionInfo != null) _exceptionInfo.Throw(); } internal static Int32 EndRead(IAsyncResult asyncResult) { SynchronousAsyncResult ar = asyncResult as SynchronousAsyncResult; if (ar == null || ar._isWrite) throw new ArgumentException(SR.Arg_WrongAsyncResult); if (ar._endXxxCalled) throw new ArgumentException(SR.InvalidOperation_EndReadCalledMultiple); ar._endXxxCalled = true; ar.ThrowIfError(); return ar._bytesRead; } internal static void EndWrite(IAsyncResult asyncResult) { SynchronousAsyncResult ar = asyncResult as SynchronousAsyncResult; if (ar == null || !ar._isWrite) throw new ArgumentException(SR.Arg_WrongAsyncResult); if (ar._endXxxCalled) throw new ArgumentException(SR.InvalidOperation_EndWriteCalledMultiple); ar._endXxxCalled = true; ar.ThrowIfError(); } } // class SynchronousAsyncResult // SyncStream is a wrapper around a stream that takes // a lock for every operation making it thread safe. internal sealed class SyncStream : Stream, IDisposable { private Stream _stream; internal SyncStream(Stream stream) { if (stream == null) throw new ArgumentNullException(nameof(stream)); _stream = stream; } public override bool CanRead { get { return _stream.CanRead; } } public override bool CanWrite { get { return _stream.CanWrite; } } public override bool CanSeek { get { return _stream.CanSeek; } } public override bool CanTimeout { get { return _stream.CanTimeout; } } public override long Length { get { lock (_stream) { return _stream.Length; } } } public override long Position { get { lock (_stream) { return _stream.Position; } } set { lock (_stream) { _stream.Position = value; } } } public override int ReadTimeout { get { return _stream.ReadTimeout; } set { _stream.ReadTimeout = value; } } public override int WriteTimeout { get { return _stream.WriteTimeout; } set { _stream.WriteTimeout = value; } } // In the off chance that some wrapped stream has different // semantics for Close vs. Dispose, let's preserve that. public override void Close() { lock (_stream) { try { _stream.Close(); } finally { base.Dispose(true); } } } protected override void Dispose(bool disposing) { lock (_stream) { try { // Explicitly pick up a potentially methodimpl'ed Dispose if (disposing) ((IDisposable)_stream).Dispose(); } finally { base.Dispose(disposing); } } } public override void Flush() { lock (_stream) _stream.Flush(); } public override int Read(byte[] bytes, int offset, int count) { lock (_stream) return _stream.Read(bytes, offset, count); } public override int Read(Span<byte> destination) { lock (_stream) return _stream.Read(destination); } public override int ReadByte() { lock (_stream) return _stream.ReadByte(); } public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, Object state) { bool overridesBeginRead = _stream.HasOverriddenBeginEndRead(); lock (_stream) { // If the Stream does have its own BeginRead implementation, then we must use that override. // If it doesn't, then we'll use the base implementation, but we'll make sure that the logic // which ensures only one asynchronous operation does so with an asynchronous wait rather // than a synchronous wait. A synchronous wait will result in a deadlock condition, because // the EndXx method for the outstanding async operation won't be able to acquire the lock on // _stream due to this call blocked while holding the lock. return overridesBeginRead ? _stream.BeginRead(buffer, offset, count, callback, state) : _stream.BeginReadInternal(buffer, offset, count, callback, state, serializeAsynchronously: true, apm: true); } } public override int EndRead(IAsyncResult asyncResult) { if (asyncResult == null) throw new ArgumentNullException(nameof(asyncResult)); lock (_stream) return _stream.EndRead(asyncResult); } public override long Seek(long offset, SeekOrigin origin) { lock (_stream) return _stream.Seek(offset, origin); } public override void SetLength(long length) { lock (_stream) _stream.SetLength(length); } public override void Write(byte[] bytes, int offset, int count) { lock (_stream) _stream.Write(bytes, offset, count); } public override void Write(ReadOnlySpan<byte> source) { lock (_stream) _stream.Write(source); } public override void WriteByte(byte b) { lock (_stream) _stream.WriteByte(b); } public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, Object state) { bool overridesBeginWrite = _stream.HasOverriddenBeginEndWrite(); lock (_stream) { // If the Stream does have its own BeginWrite implementation, then we must use that override. // If it doesn't, then we'll use the base implementation, but we'll make sure that the logic // which ensures only one asynchronous operation does so with an asynchronous wait rather // than a synchronous wait. A synchronous wait will result in a deadlock condition, because // the EndXx method for the outstanding async operation won't be able to acquire the lock on // _stream due to this call blocked while holding the lock. return overridesBeginWrite ? _stream.BeginWrite(buffer, offset, count, callback, state) : _stream.BeginWriteInternal(buffer, offset, count, callback, state, serializeAsynchronously: true, apm: true); } } public override void EndWrite(IAsyncResult asyncResult) { if (asyncResult == null) throw new ArgumentNullException(nameof(asyncResult)); lock (_stream) _stream.EndWrite(asyncResult); } } } }
using UnityEngine; using System.Collections; using System.Collections.Generic; public class VHWayPointNavigator : MonoBehaviour { #region Constants public enum PathLoopType { // when you reach the end of a path... Loop, // return to the path start point and do it again PingPong, // go back the way you came Stop, // just stop } public enum PathFollowingType { // how you move along the path Lerp, } public delegate void OnPathCompleted(List<Vector3> pathFollowed); public delegate void OnWayPointReached(VHWayPointNavigator navaigator, Vector3 wp, int wpId, int totalNumWPs); #endregion #region Variables public float m_Speed = 10; public float m_AngularVelocity = 90; public bool m_TurnTowardsTargetPosition = true; public bool m_IgnoreHeight = false; public bool m_ImmediatelyStartPathing = true; public PathLoopType m_LoopType = PathLoopType.Stop; public PathFollowingType m_FollowingType = PathFollowingType.Lerp; public GameObject m_Pather; public GameObject[] WayPoints; List<Vector3> m_WayPoints = new List<Vector3>(); int m_nPrevWP = -1; // the waypoint that you're coming from int m_nNextWP = 0; // the waypoint that you are moving towards float m_fTimeToReachTarget; float m_fCurrentTime = 0; bool m_bInReverse = false; bool m_bIsPathing = false; //Vector3 m_PathDirection = new Vector3(); protected OnPathCompleted m_PathCompletedCallback; protected OnWayPointReached m_WayPointReachedCallback; #endregion #region Properties public Vector3 PreviousPosition { get { return m_WayPoints[m_nPrevWP]; } } public Vector3 TargetPosition { get { return m_WayPoints[m_nNextWP]; } } public int PrevWP { get { return m_nPrevWP; } } public int NextWP { get { return m_nNextWP; } } public bool IsPathing { get { return m_bIsPathing; } } public int NumWayPoints { get { return m_WayPoints.Count; } } public Vector3 TurnTarget { get { return m_IgnoreHeight ? new Vector3(TargetPosition.x, m_Pather.transform.position.y, TargetPosition.z) : TargetPosition; } } #endregion #region Functions public void SetIsPathing(bool isPathing) { if (isPathing && m_LoopType == PathLoopType.Stop && (m_nPrevWP >= m_WayPoints.Count || m_nNextWP >= m_WayPoints.Count)) { // they've already completed their path, so there's nowhere to path to Debug.Log("Can't start moving again. You've completed your path and your loop type is \'Stop\'"); return; } m_bIsPathing = isPathing; } //public override void VHStart() public void Start() { if (m_Pather == null) { m_Pather = gameObject; } if (m_ImmediatelyStartPathing) { NavigatePath(true); } } List<Vector3> ConvertWayPointGOsToPositions(GameObject[] waypoints) { List<Vector3> waypointPositions = new List<Vector3>(); for (int i = 0; i < waypoints.Length; i++) { waypointPositions.Add(waypoints[i].transform.position); } return waypointPositions; } public void resetPathNavigator() { m_nPrevWP = -1; m_nNextWP = 0; m_WayPoints.Clear(); } public void NavigatePath(bool forcePositionToFirstPoint) { NavigatePath(ConvertWayPointGOsToPositions(WayPoints), forcePositionToFirstPoint); } /// <summary> /// Start navigating the given waypoints /// </summary> /// <param name="wayPoints"></param> public void NavigatePath(List<Vector3> wayPoints, bool forcePositionToFirstPoint) { if (wayPoints == null || wayPoints.Count < 2) { Debug.LogError("Bad path passed into NavigatePath"); return; } if (forcePositionToFirstPoint) { m_Pather.transform.position = wayPoints[0]; m_Pather.transform.forward = (wayPoints[1] - wayPoints[0]).normalized; } SetPath(wayPoints, true); m_nPrevWP = -1; m_nNextWP = 0; SetIsPathing(true); MoveToNextWayPoint(); VHMath.TurnTowardsTarget(this, m_Pather, TargetPosition, 360); } /// <summary> /// This doesn't reset the current and next wp indices /// </summary> /// <param name="wayPoints"></param> public void SetPath(List<Vector3> wayPoints, bool bContinuePath) { m_WayPoints.Clear(); m_WayPoints.AddRange(wayPoints); if (m_nPrevWP > wayPoints.Count - 1) { Debug.LogError("you're new path is shorter than what you have already traversed"); } SetIsPathing(true); if(!bContinuePath) MoveToNextWayPoint(); } //public override void VHUpdate() public void Update() { if (!IsPathing) { return; } //m_PathDirection = MovementDirection(); m_Pather.transform.position = Vector3.Lerp(PreviousPosition, TargetPosition, m_fCurrentTime / m_fTimeToReachTarget); if (m_fCurrentTime >= m_fTimeToReachTarget) { // they reached the next point, clamp their position to what their target was MoveToNextWayPoint(); } m_fCurrentTime += Time.deltaTime; } void MoveToNextWayPoint() { // clamp their position to where they were going m_Pather.transform.position = m_IgnoreHeight ? new Vector3(TargetPosition.x, m_Pather.transform.position.y, TargetPosition.z) : TargetPosition; m_fCurrentTime = 0; bool bPathComplete = false; switch (m_LoopType) { case PathLoopType.Loop: if (++m_nPrevWP >= m_WayPoints.Count) { m_nPrevWP = 0; } if (++m_nNextWP >= m_WayPoints.Count) { m_nNextWP = 0; bPathComplete = true; } break; case PathLoopType.PingPong: if (m_bInReverse) { if (--m_nPrevWP < 0) m_nPrevWP = 0; if (--m_nNextWP < 0) { m_nNextWP = 1; m_bInReverse = false; bPathComplete = true; } } else { if (++m_nPrevWP >= m_WayPoints.Count) m_nPrevWP = m_WayPoints.Count - 1; if (++m_nNextWP >= m_WayPoints.Count) { m_nNextWP = m_WayPoints.Count - 2; m_bInReverse = true; bPathComplete = true; } } //m_fTimeToReachTarget = Utils.GetTimeToReachPosition(PreviousPosition, TargetPosition, m_Speed); break; case PathLoopType.Stop: ++m_nPrevWP; ++m_nNextWP; if (m_nPrevWP >= m_WayPoints.Count || m_nNextWP >= m_WayPoints.Count) { // they reached the end of the path SetIsPathing(false); bPathComplete = true; } break; } if (IsPathing) { // calculate time to reach next wp m_fTimeToReachTarget = VHMath.GetTimeToReachPosition(PreviousPosition, TargetPosition, m_Speed); //m_PathDirection = MovementDirection(); //m_TurnTowardsTargetPosition = true; if (m_TurnTowardsTargetPosition) { StopCoroutine("Internal_TurnTowardsTarget"); VHMath.TurnTowardsTarget(this, m_Pather, TurnTarget, m_AngularVelocity); } } if (m_WayPointReachedCallback != null) { m_WayPointReachedCallback(this, PreviousPosition, PrevWP, m_WayPoints.Count); } if (bPathComplete && m_PathCompletedCallback != null) { m_PathCompletedCallback(m_WayPoints); } } /// <summary> /// Setups a callback that will be called when the path has been completely traversed /// </summary> /// <param name="cb"></param> public void AddPathCompletedCallback(OnPathCompleted cb) { m_PathCompletedCallback += cb; } public void AddWayPointReachedCallback(OnWayPointReached cb) { m_WayPointReachedCallback += cb; } /// <summary> /// Set how fast you move along your path /// </summary> /// <param name="speed"></param> public void SetSpeed(float speed) { if (Mathf.Abs(m_Speed - speed) <= Mathf.Epsilon) return; m_Speed = speed; SetIsPathing(speed != 0); } public Vector3 MovementDirection() { Vector3 direction = (TargetPosition - m_Pather.transform.position); if (m_IgnoreHeight) { direction.y = 0; } direction.Normalize(); return direction; } public float GetTotalPathLength() { if (m_WayPoints.Count == 0) { m_WayPoints = ConvertWayPointGOsToPositions(WayPoints); } float totalPathLength = 0; for (int i = 1; i < m_WayPoints.Count; i++) { totalPathLength += Vector3.Distance(m_WayPoints[i], m_WayPoints[i - 1]); } return totalPathLength; } #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.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Linq; namespace System.ComponentModel.DataAnnotations { /// <summary> /// Attribute to provide a hint to the presentation layer about what control it should use /// </summary> [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = true)] public class UIHintAttribute : Attribute { private readonly UIHintImplementation _implementation; /// <summary> /// Constructor that accepts the name of the control, without specifying which presentation layer to use /// </summary> /// <param name="uiHint">The name of the UI control.</param> public UIHintAttribute(string uiHint) : this(uiHint, null, Array.Empty<object>()) { } /// <summary> /// Constructor that accepts both the name of the control as well as the presentation layer /// </summary> /// <param name="uiHint">The name of the control to use</param> /// <param name="presentationLayer">The name of the presentation layer that supports this control</param> public UIHintAttribute(string uiHint, string presentationLayer) : this(uiHint, presentationLayer, Array.Empty<object>()) { } /// <summary> /// Full constructor that accepts the name of the control, presentation layer, and optional parameters /// to use when constructing the control /// </summary> /// <param name="uiHint">The name of the control</param> /// <param name="presentationLayer">The presentation layer</param> /// <param name="controlParameters">The list of parameters for the control</param> public UIHintAttribute(string uiHint, string presentationLayer, params object[] controlParameters) { _implementation = new UIHintImplementation(uiHint, presentationLayer, controlParameters); } /// <summary> /// Gets the name of the control that is most appropriate for this associated property or field /// </summary> public string UIHint => _implementation.UIHint; /// <summary> /// Gets the name of the presentation layer that supports the control type in <see cref="UIHint" /> /// </summary> public string PresentationLayer => _implementation.PresentationLayer; /// <summary> /// Gets the name-value pairs used as parameters to the control's constructor /// </summary> /// <exception cref="InvalidOperationException"> is thrown if the current attribute is ill-formed.</exception> public IDictionary<string, object> ControlParameters => _implementation.ControlParameters; public override int GetHashCode() => _implementation.GetHashCode(); public override bool Equals(object obj) { var otherAttribute = obj as UIHintAttribute; if (otherAttribute == null) { return false; } return _implementation.Equals(otherAttribute._implementation); } internal class UIHintImplementation { private readonly object[] _inputControlParameters; private IDictionary<string, object> _controlParameters; public UIHintImplementation(string uiHint, string presentationLayer, params object[] controlParameters) { UIHint = uiHint; PresentationLayer = presentationLayer; if (controlParameters != null) { _inputControlParameters = new object[controlParameters.Length]; Array.Copy(controlParameters, 0, _inputControlParameters, 0, controlParameters.Length); } } /// <summary> /// Gets the name of the control that is most appropriate for this associated property or field /// </summary> public string UIHint { get; } /// <summary> /// Gets the name of the presentation layer that supports the control type in <see cref="UIHint" /> /// </summary> public string PresentationLayer { get; } public IDictionary<string, object> ControlParameters { get { if (_controlParameters == null) { // Lazy load the dictionary. It's fine if this method executes multiple times in stress scenarios. // If the method throws (indicating that the input params are invalid) this property will throw // every time it's accessed. _controlParameters = BuildControlParametersDictionary(); } return _controlParameters; } } /// <summary> /// Returns the hash code for this UIHintAttribute. /// </summary> /// <returns>A 32-bit signed integer hash code.</returns> public override int GetHashCode() { var a = UIHint ?? string.Empty; var b = PresentationLayer ?? string.Empty; return a.GetHashCode() ^ b.GetHashCode(); } /// <summary> /// Determines whether this instance of UIHintAttribute and a specified object, /// which must also be a UIHintAttribute object, have the same value. /// </summary> /// <param name="obj">An System.Object.</param> /// <returns>true if obj is a UIHintAttribute and its value is the same as this instance; otherwise, false.</returns> public override bool Equals(object obj) { // don't need to perform a type check on obj since this is an internal class var otherImplementation = (UIHintImplementation)obj; if (UIHint != otherImplementation.UIHint || PresentationLayer != otherImplementation.PresentationLayer) { return false; } IDictionary<string, object> leftParams; IDictionary<string, object> rightParams; try { leftParams = ControlParameters; rightParams = otherImplementation.ControlParameters; } catch (InvalidOperationException) { return false; } Debug.Assert(leftParams != null, "leftParams shouldn't be null"); Debug.Assert(rightParams != null, "rightParams shouldn't be null"); if (leftParams.Count != rightParams.Count) { return false; } return leftParams.OrderBy(p => p.Key).SequenceEqual(rightParams.OrderBy(p => p.Key)); } /// <summary> /// Validates the input control parameters and throws InvalidOperationException if they are not correct. /// </summary> /// <returns> /// Dictionary of control parameters. /// </returns> private IDictionary<string, object> BuildControlParametersDictionary() { IDictionary<string, object> controlParameters = new Dictionary<string, object>(); object[] inputControlParameters = _inputControlParameters; if (inputControlParameters == null || inputControlParameters.Length == 0) { return controlParameters; } if (inputControlParameters.Length % 2 != 0) { throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, SR.UIHintImplementation_NeedEvenNumberOfControlParameters)); } for (int i = 0; i < inputControlParameters.Length; i += 2) { object key = inputControlParameters[i]; object value = inputControlParameters[i + 1]; if (key == null) { throw new InvalidOperationException( string.Format( CultureInfo.CurrentCulture, SR.UIHintImplementation_ControlParameterKeyIsNull, i)); } var keyString = key as string; if (keyString == null) { throw new InvalidOperationException( string.Format( CultureInfo.CurrentCulture, SR.UIHintImplementation_ControlParameterKeyIsNotAString, i, inputControlParameters[i].ToString())); } if (controlParameters.ContainsKey(keyString)) { throw new InvalidOperationException( string.Format( CultureInfo.CurrentCulture, SR.UIHintImplementation_ControlParameterKeyOccursMoreThanOnce, i, keyString)); } controlParameters[keyString] = value; } return controlParameters; } } } }
namespace XenAdmin.TabPages { partial class HistoryPage { /// <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) { ConnectionsManager.History.CollectionChanged -= History_CollectionChanged; XenAdmin.Actions.ActionBase.NewAction -= Action_NewAction; if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(HistoryPage)); System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle1 = new System.Windows.Forms.DataGridViewCellStyle(); System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle2 = new System.Windows.Forms.DataGridViewCellStyle(); System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle3 = new System.Windows.Forms.DataGridViewCellStyle(); System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle4 = new System.Windows.Forms.DataGridViewCellStyle(); System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle5 = new System.Windows.Forms.DataGridViewCellStyle(); this.toolStripTop = new System.Windows.Forms.ToolStrip(); this.toolStripDdbFilterStatus = new XenAdmin.Controls.FilterStatusToolStripDropDownButton(); this.toolStripDdbFilterLocation = new XenAdmin.Controls.FilterLocationToolStripDropDownButton(); this.toolStripDdbFilterDates = new XenAdmin.Controls.FilterDatesToolStripDropDownButton(); this.toolStripSplitButtonDismiss = new System.Windows.Forms.ToolStripSplitButton(); this.tsmiDismissAll = new System.Windows.Forms.ToolStripMenuItem(); this.tsmiDismissSelected = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripLabelFiltersOnOff = new System.Windows.Forms.ToolStripLabel(); this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel(); this.dataGridView = new XenAdmin.Controls.DataGridViewEx.DataGridViewEx(); this.columnExpander = new System.Windows.Forms.DataGridViewImageColumn(); this.columnStatus = new System.Windows.Forms.DataGridViewImageColumn(); this.columnMessage = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.columnLocation = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.columnDate = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.columnActions = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.tableLayoutPanel2 = new System.Windows.Forms.TableLayoutPanel(); this.toolStripTop.SuspendLayout(); this.tableLayoutPanel1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.dataGridView)).BeginInit(); this.tableLayoutPanel2.SuspendLayout(); this.SuspendLayout(); // // toolStripTop // resources.ApplyResources(this.toolStripTop, "toolStripTop"); this.toolStripTop.BackColor = System.Drawing.Color.WhiteSmoke; this.toolStripTop.GripStyle = System.Windows.Forms.ToolStripGripStyle.Hidden; this.toolStripTop.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.toolStripDdbFilterStatus, this.toolStripDdbFilterLocation, this.toolStripDdbFilterDates, this.toolStripSplitButtonDismiss, this.toolStripLabelFiltersOnOff}); this.toolStripTop.Name = "toolStripTop"; // // toolStripDdbFilterStatus // this.toolStripDdbFilterStatus.AutoToolTip = false; this.toolStripDdbFilterStatus.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text; resources.ApplyResources(this.toolStripDdbFilterStatus, "toolStripDdbFilterStatus"); this.toolStripDdbFilterStatus.Name = "toolStripDdbFilterStatus"; this.toolStripDdbFilterStatus.FilterChanged += new System.Action(this.toolStripDdbFilterStatus_FilterChanged); // // toolStripDdbFilterLocation // this.toolStripDdbFilterLocation.AutoToolTip = false; this.toolStripDdbFilterLocation.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text; resources.ApplyResources(this.toolStripDdbFilterLocation, "toolStripDdbFilterLocation"); this.toolStripDdbFilterLocation.Name = "toolStripDdbFilterLocation"; this.toolStripDdbFilterLocation.FilterChanged += new System.Action(this.toolStripDdbFilterLocation_FilterChanged); // // toolStripDdbFilterDates // this.toolStripDdbFilterDates.AutoToolTip = false; this.toolStripDdbFilterDates.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text; resources.ApplyResources(this.toolStripDdbFilterDates, "toolStripDdbFilterDates"); this.toolStripDdbFilterDates.Name = "toolStripDdbFilterDates"; this.toolStripDdbFilterDates.FilterChanged += new System.Action(this.toolStripDdbFilterDates_FilterChanged); // // toolStripSplitButtonDismiss // this.toolStripSplitButtonDismiss.AutoToolTip = false; this.toolStripSplitButtonDismiss.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text; this.toolStripSplitButtonDismiss.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.tsmiDismissAll, this.tsmiDismissSelected}); resources.ApplyResources(this.toolStripSplitButtonDismiss, "toolStripSplitButtonDismiss"); this.toolStripSplitButtonDismiss.Name = "toolStripSplitButtonDismiss"; this.toolStripSplitButtonDismiss.DropDownItemClicked += new System.Windows.Forms.ToolStripItemClickedEventHandler(this.toolStripSplitButtonDismiss_DropDownItemClicked); // // tsmiDismissAll // this.tsmiDismissAll.Name = "tsmiDismissAll"; resources.ApplyResources(this.tsmiDismissAll, "tsmiDismissAll"); this.tsmiDismissAll.Click += new System.EventHandler(this.tsmiDismissAll_Click); // // tsmiDismissSelected // this.tsmiDismissSelected.Name = "tsmiDismissSelected"; resources.ApplyResources(this.tsmiDismissSelected, "tsmiDismissSelected"); this.tsmiDismissSelected.Click += new System.EventHandler(this.tsmiDismissSelected_Click); // // toolStripLabelFiltersOnOff // this.toolStripLabelFiltersOnOff.Alignment = System.Windows.Forms.ToolStripItemAlignment.Right; resources.ApplyResources(this.toolStripLabelFiltersOnOff, "toolStripLabelFiltersOnOff"); this.toolStripLabelFiltersOnOff.Name = "toolStripLabelFiltersOnOff"; // // tableLayoutPanel1 // resources.ApplyResources(this.tableLayoutPanel1, "tableLayoutPanel1"); this.tableLayoutPanel1.BackColor = System.Drawing.Color.Gainsboro; this.tableLayoutPanel1.Controls.Add(this.dataGridView, 0, 0); this.tableLayoutPanel1.Name = "tableLayoutPanel1"; // // dataGridView // this.dataGridView.AutoSizeRowsMode = System.Windows.Forms.DataGridViewAutoSizeRowsMode.AllCells; this.dataGridView.BackgroundColor = System.Drawing.SystemColors.Window; this.dataGridView.BorderStyle = System.Windows.Forms.BorderStyle.None; this.dataGridView.CellBorderStyle = System.Windows.Forms.DataGridViewCellBorderStyle.None; this.dataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.DisableResizing; this.dataGridView.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] { this.columnExpander, this.columnStatus, this.columnMessage, this.columnLocation, this.columnDate, this.columnActions}); resources.ApplyResources(this.dataGridView, "dataGridView"); this.dataGridView.GridColor = System.Drawing.SystemColors.Control; this.dataGridView.MultiSelect = true; this.dataGridView.Name = "dataGridView"; this.dataGridView.CellClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.dataGridView_CellClick); this.dataGridView.ColumnHeaderMouseClick += new System.Windows.Forms.DataGridViewCellMouseEventHandler(this.dataGridView_ColumnHeaderMouseClick); this.dataGridView.SelectionChanged += new System.EventHandler(this.dataGridView_SelectionChanged); // // columnExpander // this.columnExpander.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.None; dataGridViewCellStyle1.Alignment = System.Windows.Forms.DataGridViewContentAlignment.TopCenter; dataGridViewCellStyle1.NullValue = ((object)(resources.GetObject("dataGridViewCellStyle1.NullValue"))); dataGridViewCellStyle1.Padding = new System.Windows.Forms.Padding(0, 5, 0, 0); this.columnExpander.DefaultCellStyle = dataGridViewCellStyle1; resources.ApplyResources(this.columnExpander, "columnExpander"); this.columnExpander.Name = "columnExpander"; // // columnStatus // this.columnStatus.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.AllCells; dataGridViewCellStyle2.Alignment = System.Windows.Forms.DataGridViewContentAlignment.TopLeft; dataGridViewCellStyle2.NullValue = ((object)(resources.GetObject("dataGridViewCellStyle2.NullValue"))); dataGridViewCellStyle2.Padding = new System.Windows.Forms.Padding(0, 2, 0, 0); this.columnStatus.DefaultCellStyle = dataGridViewCellStyle2; resources.ApplyResources(this.columnStatus, "columnStatus"); this.columnStatus.Name = "columnStatus"; this.columnStatus.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.Automatic; // // columnMessage // dataGridViewCellStyle3.Alignment = System.Windows.Forms.DataGridViewContentAlignment.TopLeft; dataGridViewCellStyle3.WrapMode = System.Windows.Forms.DataGridViewTriState.True; this.columnMessage.DefaultCellStyle = dataGridViewCellStyle3; resources.ApplyResources(this.columnMessage, "columnMessage"); this.columnMessage.Name = "columnMessage"; // // columnLocation // dataGridViewCellStyle4.Alignment = System.Windows.Forms.DataGridViewContentAlignment.TopLeft; this.columnLocation.DefaultCellStyle = dataGridViewCellStyle4; resources.ApplyResources(this.columnLocation, "columnLocation"); this.columnLocation.Name = "columnLocation"; // // columnDate // dataGridViewCellStyle5.Alignment = System.Windows.Forms.DataGridViewContentAlignment.TopLeft; this.columnDate.DefaultCellStyle = dataGridViewCellStyle5; resources.ApplyResources(this.columnDate, "columnDate"); this.columnDate.Name = "columnDate"; // // columnActions // this.columnActions.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.AllCells; resources.ApplyResources(this.columnActions, "columnActions"); this.columnActions.Name = "columnActions"; this.columnActions.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.NotSortable; // // tableLayoutPanel2 // resources.ApplyResources(this.tableLayoutPanel2, "tableLayoutPanel2"); this.tableLayoutPanel2.BackColor = System.Drawing.Color.Gainsboro; this.tableLayoutPanel2.Controls.Add(this.toolStripTop, 0, 0); this.tableLayoutPanel2.Name = "tableLayoutPanel2"; // // HistoryPage // resources.ApplyResources(this, "$this"); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi; this.BackColor = System.Drawing.SystemColors.Window; this.Controls.Add(this.tableLayoutPanel2); this.Controls.Add(this.tableLayoutPanel1); this.DoubleBuffered = true; this.Name = "HistoryPage"; this.toolStripTop.ResumeLayout(false); this.toolStripTop.PerformLayout(); this.tableLayoutPanel1.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.dataGridView)).EndInit(); this.tableLayoutPanel2.ResumeLayout(false); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.ToolStrip toolStripTop; private System.Windows.Forms.ToolStripSplitButton toolStripSplitButtonDismiss; private System.Windows.Forms.ToolStripMenuItem tsmiDismissAll; private System.Windows.Forms.ToolStripMenuItem tsmiDismissSelected; private XenAdmin.Controls.DataGridViewEx.DataGridViewEx dataGridView; private XenAdmin.Controls.FilterStatusToolStripDropDownButton toolStripDdbFilterStatus; private XenAdmin.Controls.FilterLocationToolStripDropDownButton toolStripDdbFilterLocation; private XenAdmin.Controls.FilterDatesToolStripDropDownButton toolStripDdbFilterDates; private System.Windows.Forms.ToolStripLabel toolStripLabelFiltersOnOff; private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1; private System.Windows.Forms.TableLayoutPanel tableLayoutPanel2; private System.Windows.Forms.DataGridViewImageColumn columnExpander; private System.Windows.Forms.DataGridViewImageColumn columnStatus; private System.Windows.Forms.DataGridViewTextBoxColumn columnMessage; private System.Windows.Forms.DataGridViewTextBoxColumn columnLocation; private System.Windows.Forms.DataGridViewTextBoxColumn columnDate; private System.Windows.Forms.DataGridViewTextBoxColumn columnActions; } }
using MediaBrowser.Model.ApiClient; using MediaBrowser.Model.Dlna; using MediaBrowser.Model.Dto; using MediaBrowser.Model.Sync; using MediaBrowser.Model.Users; using System.Collections.Generic; using System.IO; using System.Threading.Tasks; namespace Emby.ApiInteraction.Data { public interface ILocalAssetManager { /// <summary> /// Records the user action. /// </summary> /// <param name="action">The action.</param> /// <returns>Task.</returns> Task RecordUserAction(UserAction action); /// <summary> /// Deletes the specified action. /// </summary> /// <param name="action">The action.</param> /// <returns>Task.</returns> Task Delete(UserAction action); /// <summary> /// Deletes the specified item. /// </summary> /// <param name="item">The item.</param> /// <returns>Task.</returns> Task Delete(LocalItem item); /// <summary> /// Gets all user actions by serverId /// </summary> /// <param name="serverId"></param> /// <returns></returns> Task<IEnumerable<UserAction>> GetUserActions(string serverId); /// <summary> /// Adds the or update. /// </summary> /// <param name="item">The item.</param> /// <returns>Task.</returns> Task AddOrUpdate(LocalItem item); /// <summary> /// Gets the files. /// </summary> /// <param name="item">The item.</param> /// <returns>Task&lt;List&lt;ItemFileInfo&gt;&gt;.</returns> Task<List<ItemFileInfo>> GetFiles(LocalItem item); /// <summary> /// Deletes the specified file. /// </summary> /// <param name="path">The path.</param> /// <returns>Task.</returns> Task DeleteFile(string path); /// <summary> /// Saves the subtitles. /// </summary> /// <param name="stream">The stream.</param> /// <param name="format">The format.</param> /// <param name="item">The item.</param> /// <param name="language">The language.</param> /// <param name="isForced">if set to <c>true</c> [is forced].</param> /// <returns>Task&lt;System.String&gt;.</returns> Task<string> SaveSubtitles(Stream stream, string format, LocalItem item, string language, bool isForced); /// <summary> /// Saves the media. /// </summary> /// <param name="stream">The stream.</param> /// <param name="localItem">The local item.</param> /// <param name="server">The server.</param> /// <returns>Task.</returns> Task SaveMedia(Stream stream, LocalItem localItem, ServerInfo server); #if WINDOWS_UWP /// <summary> /// Saves the media. /// </summary> /// <param name="file">The file.</param> /// <param name="localItem">The local item.</param> /// <param name="server">The server.</param> /// <returns>Task.</returns> Task SaveMedia(Windows.Storage.IStorageFile file, LocalItem localItem, ServerInfo server); #endif /// <summary> /// Creates the local item. /// </summary> /// <param name="libraryItem">The library item.</param> /// <param name="server">The server.</param> /// <param name="syncJobItemId">The synchronize job item identifier.</param> /// <param name="originalFileName">Name of the original file.</param> /// <returns>LocalItem.</returns> LocalItem CreateLocalItem(BaseItemDto libraryItem, ServerInfo server, string syncJobItemId, string originalFileName); /// <summary> /// Gets the local item. /// </summary> /// <param name="localId">The local identifier.</param> /// <returns>Task&lt;LocalItem&gt;.</returns> Task<LocalItem> GetLocalItem(string localId); /// <summary> /// Gets the local item. /// </summary> /// <param name="serverId">The server identifier.</param> /// <param name="itemId">The item identifier.</param> /// <returns>Task&lt;LocalItem&gt;.</returns> Task<LocalItem> GetLocalItem(string serverId, string itemId); /// <summary> /// Files the exists. /// </summary> /// <param name="path">The path.</param> /// <returns>Task&lt;System.Boolean&gt;.</returns> Task<bool> FileExists(string path); /// <summary> /// Gets the server item ids. /// </summary> /// <param name="serverId">The server identifier.</param> /// <returns>Task&lt;List&lt;System.String&gt;&gt;.</returns> Task<List<string>> GetServerItemIds(string serverId); /// <summary> /// Gets the file stream. /// </summary> /// <param name="info">The information.</param> /// <returns>Task&lt;Stream&gt;.</returns> Task<Stream> GetFileStream(StreamInfo info); /// <summary> /// Gets the file stream. /// </summary> /// <param name="path">The path.</param> /// <returns>Task&lt;Stream&gt;.</returns> Task<Stream> GetFileStream(string path); /// <summary> /// Saves the offline user. /// </summary> /// <param name="user">The user.</param> /// <returns>Task.</returns> Task SaveOfflineUser(UserDto user); /// <summary> /// Deletes the offline user. /// </summary> /// <param name="id">The identifier.</param> /// <returns>Task.</returns> Task DeleteOfflineUser(string id); /// <summary> /// Saves the user image. /// </summary> /// <param name="user">The user.</param> /// <param name="stream">The stream.</param> /// <returns>Task.</returns> Task SaveImage(UserDto user, Stream stream); /// <summary> /// Gets the user image. /// </summary> /// <param name="user">The user.</param> /// <returns>Task&lt;Stream&gt;.</returns> Task<Stream> GetImage(UserDto user); /// <summary> /// Deletes the user image. /// </summary> /// <param name="user">The user.</param> /// <returns>Task.</returns> Task DeleteImage(UserDto user); /// <summary> /// Determines whether the specified user has image. /// </summary> /// <param name="user">The user.</param> Task<bool> HasImage(UserDto user); /// <summary> /// Saves the item image. /// </summary> /// <param name="serverId">The server identifier.</param> /// <param name="itemId">The item identifier.</param> /// <param name="imageId">The image identifier.</param> /// <param name="stream">The stream.</param> /// <returns>Task.</returns> Task SaveImage(string serverId, string itemId, string imageId, Stream stream); Task SaveImage(string itemId, string imageId, Stream stream); /// <summary> /// Determines whether the specified server identifier has image. /// </summary> /// <param name="serverId">The server identifier.</param> /// <param name="itemId">The item identifier.</param> /// <param name="imageId">The image identifier.</param> Task<bool> HasImage(string serverId, string itemId, string imageId); Task<bool> HasImage(string itemId, string imageId); /// <summary> /// Gets the image. /// </summary> /// <param name="serverId">The server identifier.</param> /// <param name="itemId">The item identifier.</param> /// <param name="imageId">The image identifier.</param> /// <returns>Task&lt;Stream&gt;.</returns> Task<Stream> GetImage(string serverId, string itemId, string imageId); Task<Stream> GetImage(string itemId, string imageId); /// <summary> /// Determines whether the specified item has image. /// </summary> /// <param name="item">The item.</param> /// <param name="imageId">The image identifier.</param> Task<bool> HasImage(BaseItemDto item, string imageId); /// <summary> /// Gets the image. /// </summary> /// <param name="item">The item.</param> /// <param name="imageId">The image identifier.</param> /// <returns>Task&lt;Stream&gt;.</returns> Task<Stream> GetImage(BaseItemDto item, string imageId); /// <summary> /// Gets the views. /// </summary> /// <param name="serverId">The server identifier.</param> /// <param name="userId">The user identifier.</param> /// <returns>Task&lt;List&lt;BaseItemDto&gt;&gt;.</returns> Task<List<BaseItemDto>> GetViews(string serverId, string userId); /// <summary> /// Gets the items. /// </summary> /// <param name="user">The user.</param> /// <param name="parentItem">The parent item.</param> /// <returns>Task&lt;List&lt;BaseItemDto&gt;&gt;.</returns> Task<List<BaseItemDto>> GetItems(UserDto user, BaseItemDto parentItem); /// <summary> /// Gets the user. /// </summary> /// <param name="id">The identifier.</param> /// <returns>Task&lt;UserDto&gt;.</returns> Task<UserDto> GetUser(string id); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using swc = System.Windows.Controls; using swn = System.Windows.Navigation; using sw = System.Windows; using swf = System.Windows.Forms; using swi = System.Windows.Input; using Eto.Forms; using System.Runtime.InteropServices; using Eto.CustomControls; using Eto.Drawing; namespace Eto.Wpf.Forms.Controls { public class SwfWebViewHandler : WpfFrameworkElement<swf.Integration.WindowsFormsHost, WebView, WebView.ICallback>, WebView.IHandler { public swf.WebBrowser Browser { get; private set; } [ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] [Guid("6d5140c1-7436-11ce-8034-00aa006009fa")] internal interface IServiceProvider { [return: MarshalAs(UnmanagedType.IUnknown)] object QueryService(ref Guid guidService, ref Guid riid); } HashSet<string> delayedEvents = new HashSet<string>(); SHDocVw.WebBrowser_V1 WebBrowserV1 { get { return (SHDocVw.WebBrowser_V1)Browser.ActiveXInstance; } } public override sw.Size GetPreferredSize(sw.Size constraint) { var size = base.GetPreferredSize(constraint); return new sw.Size(Math.Min(size.Width, 100), Math.Min(size.Height, 100)); } public void AttachEvent(SHDocVw.WebBrowser_V1 control, string handler) { switch (handler) { case WebView.OpenNewWindowEvent: control.NewWindow += WebBrowserV1_NewWindow; break; } } static readonly string[] ValidInputTags = { "input", "textarea" }; public SwfWebViewHandler() { Browser = new swf.WebBrowser { IsWebBrowserContextMenuEnabled = false, WebBrowserShortcutsEnabled = false, AllowWebBrowserDrop = false, ScriptErrorsSuppressed = true }; Browser.HandleCreated += (sender, e) => HookDocumentEvents(); Control = new swf.Integration.WindowsFormsHost { Child = Browser }; Browser.PreviewKeyDown += (sender, e) => { switch (e.KeyCode) { case swf.Keys.Down: case swf.Keys.Up: case swf.Keys.Left: case swf.Keys.Right: case swf.Keys.PageDown: case swf.Keys.PageUp: // enable scrolling via keyboard e.IsInputKey = true; return; } var doc = Browser.Document; if (!Browser.WebBrowserShortcutsEnabled && doc != null) { // implement shortcut keys for copy/paste switch (e.KeyData) { case (swf.Keys.C | swf.Keys.Control): doc.ExecCommand("Copy", false, null); break; case (swf.Keys.V | swf.Keys.Control): if (doc.ActiveElement != null && ValidInputTags.Contains(doc.ActiveElement.TagName.ToLowerInvariant())) doc.ExecCommand("Paste", false, null); break; case (swf.Keys.X | swf.Keys.Control): if (doc.ActiveElement != null && ValidInputTags.Contains(doc.ActiveElement.TagName.ToLowerInvariant())) doc.ExecCommand("Cut", false, null); break; case (swf.Keys.A | swf.Keys.Control): doc.ExecCommand("SelectAll", false, null); break; } } }; } void WebBrowserV1_NewWindow(string URL, int Flags, string TargetFrameName, ref object PostData, string Headers, ref bool Processed) { var e = new WebViewNewWindowEventArgs(new Uri(URL), TargetFrameName); Callback.OnOpenNewWindow(Widget, e); Processed = e.Cancel; } public override void AttachEvent(string handler) { switch (handler) { case WebView.NavigatedEvent: this.Browser.Navigated += (sender, e) => { Callback.OnNavigated(Widget, new WebViewLoadedEventArgs(e.Url)); }; break; case WebView.DocumentLoadedEvent: this.Browser.DocumentCompleted += (sender, e) => { Callback.OnDocumentLoaded(Widget, new WebViewLoadedEventArgs(e.Url)); }; break; case WebView.DocumentLoadingEvent: this.Browser.Navigating += (sender, e) => { var args = new WebViewLoadingEventArgs(e.Url, false); Callback.OnDocumentLoading(Widget, args); e.Cancel = args.Cancel; }; break; case WebView.OpenNewWindowEvent: HookDocumentEvents(handler); break; case WebView.DocumentTitleChangedEvent: this.Browser.DocumentTitleChanged += delegate { Callback.OnDocumentTitleChanged(Widget, new WebViewTitleEventArgs(Browser.DocumentTitle)); }; break; default: base.AttachEvent(handler); break; } } void HookDocumentEvents(string newEvent = null) { if (newEvent != null) delayedEvents.Add(newEvent); if (Browser.ActiveXInstance != null) { foreach (var handler in delayedEvents) AttachEvent(WebBrowserV1, handler); delayedEvents.Clear(); } } public Uri Url { get { return this.Browser.Url; } set { this.Browser.Url = value; } } public string DocumentTitle { get { return this.Browser.DocumentTitle; } } public string ExecuteScript(string script) { var fullScript = string.Format("var fn = function() {{ {0} }}; fn();", script); return Convert.ToString(Browser.Document.InvokeScript("eval", new object[] { fullScript })); } public void Stop() { this.Browser.Stop(); } public void Reload() { this.Browser.Refresh(); } public void GoBack() { this.Browser.GoBack(); } public bool CanGoBack { get { return this.Browser.CanGoBack; } } public void GoForward() { this.Browser.GoForward(); } public bool CanGoForward { get { return this.Browser.CanGoForward; } } HttpServer server; public void LoadHtml(string html, Uri baseUri) { if (baseUri != null) { if (server == null) server = new HttpServer(); server.SetHtml(html, baseUri != null ? baseUri.LocalPath : null); Browser.Navigate(server.Url); } else this.Browser.DocumentText = html; } public void ShowPrintDialog() { this.Browser.ShowPrintDialog(); } public bool BrowserContextMenuEnabled { get { return Browser.IsWebBrowserContextMenuEnabled; } set { Browser.IsWebBrowserContextMenuEnabled = value; } } public override Eto.Drawing.Color BackgroundColor { get { return Eto.Drawing.Colors.Transparent; } set { } } } }
// // Copyright (C) 2010 Jackson Harper (jackson@manosdemono.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.Collections.Generic; using System.IO; using System.Text; using Manos.IO; namespace Manos.Http { public class HttpResponse : HttpEntity, IHttpResponse { private Dictionary<string, HttpCookie> cookies; private StreamWriter writer; public HttpResponse(Context context, IHttpRequest request, ITcpSocket socket) : base(context) { Request = request; Socket = socket; StatusCode = 200; WriteHeaders = true; Stream = new HttpStream(this, socket.GetSocketStream()); Stream.Chunked = (request.MajorVersion > 0 && request.MinorVersion > 0); } public IHttpRequest Request { get; private set; } public Dictionary<string, HttpCookie> Cookies { get { if (cookies == null) cookies = new Dictionary<string, HttpCookie>(); return cookies; } } #region IHttpResponse Members public StreamWriter Writer { get { if (writer == null) writer = new StreamWriter(new HttpStreamWriterWrapper(Stream)); return writer; } } public int StatusCode { get; set; } public bool WriteHeaders { get; set; } public void Redirect(string url) { StatusCode = 302; Headers.SetNormalizedHeader("Location", url); // WriteMetadata (); End(); } public override void WriteMetadata(StringBuilder builder) { WriteStatusLine(builder); if (WriteHeaders) { Headers.Write(builder, cookies == null ? null : Cookies.Values, Encoding.ASCII); } } public void SetHeader(string name, string value) { Headers.SetHeader(name, value); } public void SetCookie(string name, HttpCookie cookie) { Cookies[name] = cookie; } public HttpCookie SetCookie(string name, string value) { if (name == null) throw new ArgumentNullException("name"); if (value == null) throw new ArgumentNullException("value"); var cookie = new HttpCookie(name, value); SetCookie(name, cookie); return cookie; } public HttpCookie SetCookie(string name, string value, string domain) { if (name == null) throw new ArgumentNullException("name"); if (value == null) throw new ArgumentNullException("value"); var cookie = new HttpCookie(name, value); cookie.Domain = domain; SetCookie(name, cookie); return cookie; } public HttpCookie SetCookie(string name, string value, DateTime expires) { return SetCookie(name, value, null, expires); } public HttpCookie SetCookie(string name, string value, string domain, DateTime expires) { if (name == null) throw new ArgumentNullException("name"); if (value == null) throw new ArgumentNullException("value"); var cookie = new HttpCookie(name, value); cookie.Domain = domain; cookie.Expires = expires; SetCookie(name, cookie); return cookie; } public HttpCookie SetCookie(string name, string value, TimeSpan max_age) { return SetCookie(name, value, DateTime.Now + max_age); } public HttpCookie SetCookie(string name, string value, string domain, TimeSpan max_age) { return SetCookie(name, value, domain, DateTime.Now + max_age); } public void RemoveCookie(string name) { var cookie = new HttpCookie(name, ""); cookie.Expires = DateTime.Now.AddYears(-1); SetCookie(name, cookie); } #endregion public override void Reset() { cookies = null; base.Reset(); } public override ParserSettings CreateParserSettings() { var settings = new ParserSettings(); settings.OnBody = OnBody; return settings; } protected override int OnHeadersComplete(HttpParser parser) { base.OnHeadersComplete(parser); StatusCode = parser.StatusCode; if (Request.Method == HttpMethod.HTTP_HEAD) return 1; return 0; } private void WriteStatusLine(StringBuilder builder) { builder.Append("HTTP/"); builder.Append(Request.MajorVersion); builder.Append("."); builder.Append(Request.MinorVersion); builder.Append(" "); builder.Append(StatusCode); builder.Append(" "); builder.Append(GetStatusDescription(StatusCode)); builder.Append("\r\n"); } private static string GetStatusDescription(int code) { switch (code) { case 100: return "Continue"; case 101: return "Switching Protocols"; case 102: return "Processing"; case 200: return "OK"; case 201: return "Created"; case 202: return "Accepted"; case 203: return "Non-Authoritative Information"; case 204: return "No Content"; case 205: return "Reset Content"; case 206: return "Partial Content"; case 207: return "Multi-Status"; case 300: return "Multiple Choices"; case 301: return "Moved Permanently"; case 302: return "Found"; case 303: return "See Other"; case 304: return "Not Modified"; case 305: return "Use Proxy"; case 307: return "Temporary Redirect"; case 400: return "Bad Request"; case 401: return "Unauthorized"; case 402: return "Payment Required"; case 403: return "Forbidden"; case 404: return "Not Found"; case 405: return "Method Not Allowed"; case 406: return "Not Acceptable"; case 407: return "Proxy Authentication Required"; case 408: return "Request Timeout"; case 409: return "Conflict"; case 410: return "Gone"; case 411: return "Length Required"; case 412: return "Precondition Failed"; case 413: return "Request Entity Too Large"; case 414: return "Request-Uri Too Long"; case 415: return "Unsupported Media Type"; case 416: return "Requested Range Not Satisfiable"; case 417: return "Expectation Failed"; case 422: return "Unprocessable Entity"; case 423: return "Locked"; case 424: return "Failed Dependency"; case 500: return "Internal Server Error"; case 501: return "Not Implemented"; case 502: return "Bad Gateway"; case 503: return "Service Unavailable"; case 504: return "Gateway Timeout"; case 505: return "Http Version Not Supported"; case 507: return "Insufficient Storage"; } return ""; } } }
using System; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using System.IO; using System.Linq; using Semmle.Extraction.CSharp.Populators; using System.Collections.Generic; using System.Threading.Tasks; using System.Diagnostics; using Semmle.Util.Logging; namespace Semmle.Extraction.CSharp { /// <summary> /// Encapsulates a C# analysis task. /// </summary> public class Analyser : IDisposable { protected Extraction.Extractor? extractor; protected CSharpCompilation? compilation; protected Layout? layout; protected CommonOptions? options; private readonly object progressMutex = new object(); // The bulk of the extraction work, potentially executed in parallel. protected readonly List<Action> extractionTasks = new List<Action>(); private int taskCount = 0; private readonly Stopwatch stopWatch = new Stopwatch(); private readonly IProgressMonitor progressMonitor; public ILogger Logger { get; } protected readonly bool addAssemblyTrapPrefix; public PathTransformer PathTransformer { get; } protected Analyser(IProgressMonitor pm, ILogger logger, bool addAssemblyTrapPrefix, PathTransformer pathTransformer) { Logger = logger; this.addAssemblyTrapPrefix = addAssemblyTrapPrefix; Logger.Log(Severity.Info, "EXTRACTION STARTING at {0}", DateTime.Now); stopWatch.Start(); progressMonitor = pm; PathTransformer = pathTransformer; } /// <summary> /// Perform an analysis on a source file/syntax tree. /// </summary> /// <param name="tree">Syntax tree to analyse.</param> public void AnalyseTree(SyntaxTree tree) { extractionTasks.Add(() => DoExtractTree(tree)); } #nullable disable warnings /// <summary> /// Enqueue all reference analysis tasks. /// </summary> public void AnalyseReferences() { foreach (var assembly in compilation.References.OfType<PortableExecutableReference>()) { // CIL first - it takes longer. if (options.CIL) extractionTasks.Add(() => DoExtractCIL(assembly)); extractionTasks.Add(() => DoAnalyseReferenceAssembly(assembly)); } } /// <summary> /// Constructs the map from assembly string to its filename. /// /// Roslyn doesn't record the relationship between a filename and its assembly /// information, so we need to retrieve this information manually. /// </summary> protected void SetReferencePaths() { foreach (var reference in compilation.References.OfType<PortableExecutableReference>()) { try { var refPath = reference.FilePath!; /* This method is significantly faster and more lightweight than using * System.Reflection.Assembly.ReflectionOnlyLoadFrom. It is also allows * loading the same assembly from different locations. */ using var pereader = new System.Reflection.PortableExecutable.PEReader(new FileStream(refPath, FileMode.Open, FileAccess.Read, FileShare.Read)); var metadata = pereader.GetMetadata(); string assemblyIdentity; unsafe { var reader = new System.Reflection.Metadata.MetadataReader(metadata.Pointer, metadata.Length); var def = reader.GetAssemblyDefinition(); assemblyIdentity = reader.GetString(def.Name) + " " + def.Version; } extractor.SetAssemblyFile(assemblyIdentity, refPath); } catch (Exception ex) // lgtm[cs/catch-of-all-exceptions] { extractor.Message(new Message("Exception reading reference file", reference.FilePath, null, ex.StackTrace)); } } } /// <summary> /// Extract an assembly to a new trap file. /// If the trap file exists, skip extraction to avoid duplicating /// extraction within the snapshot. /// </summary> /// <param name="r">The assembly to extract.</param> private void DoAnalyseReferenceAssembly(PortableExecutableReference r) { try { var stopwatch = new Stopwatch(); stopwatch.Start(); var assemblyPath = r.FilePath!; var transformedAssemblyPath = PathTransformer.Transform(assemblyPath); var projectLayout = layout.LookupProjectOrDefault(transformedAssemblyPath); using var trapWriter = projectLayout.CreateTrapWriter(Logger, transformedAssemblyPath, options.TrapCompression, discardDuplicates: true); var skipExtraction = options.Cache && File.Exists(trapWriter.TrapFile); if (!skipExtraction) { /* Note on parallel builds: * * The trap writer and source archiver both perform atomic moves * of the file to the final destination. * * If the same source file or trap file are generated concurrently * (by different parallel invocations of the extractor), then * last one wins. * * Specifically, if two assemblies are analysed concurrently in a build, * then there is a small amount of duplicated work but the output should * still be correct. */ // compilation.Clone() reduces memory footprint by allowing the symbols // in c to be garbage collected. Compilation c = compilation.Clone(); if (c.GetAssemblyOrModuleSymbol(r) is IAssemblySymbol assembly) { var cx = new Context(extractor, c, trapWriter, new AssemblyScope(assembly, assemblyPath), addAssemblyTrapPrefix); foreach (var module in assembly.Modules) { AnalyseNamespace(cx, module.GlobalNamespace); } Entities.Attribute.ExtractAttributes(cx, assembly, Entities.Assembly.Create(cx, assembly.GetSymbolLocation())); cx.PopulateAll(); } } ReportProgress(assemblyPath, trapWriter.TrapFile, stopwatch.Elapsed, skipExtraction ? AnalysisAction.UpToDate : AnalysisAction.Extracted); } catch (Exception ex) // lgtm[cs/catch-of-all-exceptions] { Logger.Log(Severity.Error, " Unhandled exception analyzing {0}: {1}", r.FilePath, ex); } } private void DoExtractCIL(PortableExecutableReference r) { var stopwatch = new Stopwatch(); stopwatch.Start(); CIL.Analyser.ExtractCIL(layout, r.FilePath!, Logger, options, out var trapFile, out var extracted); stopwatch.Stop(); ReportProgress(r.FilePath, trapFile, stopwatch.Elapsed, extracted ? AnalysisAction.Extracted : AnalysisAction.UpToDate); } private void DoExtractTree(SyntaxTree tree) { try { var stopwatch = new Stopwatch(); stopwatch.Start(); var sourcePath = tree.FilePath; var transformedSourcePath = PathTransformer.Transform(sourcePath); var projectLayout = layout.LookupProjectOrNull(transformedSourcePath); var excluded = projectLayout is null; var trapPath = excluded ? "" : projectLayout!.GetTrapPath(Logger, transformedSourcePath, options.TrapCompression); var upToDate = false; if (!excluded) { // compilation.Clone() is used to allow symbols to be garbage collected. using var trapWriter = projectLayout!.CreateTrapWriter(Logger, transformedSourcePath, options.TrapCompression, discardDuplicates: false); upToDate = options.Fast && FileIsUpToDate(sourcePath, trapWriter.TrapFile); if (!upToDate) { var cx = new Context(extractor, compilation.Clone(), trapWriter, new SourceScope(tree), addAssemblyTrapPrefix); // Ensure that the file itself is populated in case the source file is totally empty var root = tree.GetRoot(); Entities.File.Create(cx, root.SyntaxTree.FilePath); var csNode = (CSharpSyntaxNode)root; var directiveVisitor = new DirectiveVisitor(cx); csNode.Accept(directiveVisitor); foreach (var branch in directiveVisitor.BranchesTaken) { cx.TrapStackSuffix.Add(branch); } csNode.Accept(new CompilationUnitVisitor(cx)); cx.PopulateAll(); CommentPopulator.ExtractCommentBlocks(cx, cx.CommentGenerator); cx.PopulateAll(); } } ReportProgress(sourcePath, trapPath, stopwatch.Elapsed, excluded ? AnalysisAction.Excluded : upToDate ? AnalysisAction.UpToDate : AnalysisAction.Extracted); } catch (Exception ex) // lgtm[cs/catch-of-all-exceptions] { extractor.Message(new Message($"Unhandled exception processing syntax tree. {ex.Message}", tree.FilePath, null, ex.StackTrace)); } } #nullable restore warnings private static bool FileIsUpToDate(string src, string dest) { return File.Exists(dest) && File.GetLastWriteTime(dest) >= File.GetLastWriteTime(src); } private void AnalyseNamespace(Context cx, INamespaceSymbol ns) { foreach (var memberNamespace in ns.GetNamespaceMembers()) { AnalyseNamespace(cx, memberNamespace); } foreach (var memberType in ns.GetTypeMembers()) { Entities.Type.Create(cx, memberType).ExtractRecursive(); } } private void ReportProgress(string src, string output, TimeSpan time, AnalysisAction action) { lock (progressMutex) progressMonitor.Analysed(++taskCount, extractionTasks.Count, src, output, time, action); } /// <summary> /// Run all extraction tasks. /// </summary> /// <param name="numberOfThreads">The number of threads to use.</param> public void PerformExtraction(int numberOfThreads) { Parallel.Invoke( new ParallelOptions { MaxDegreeOfParallelism = numberOfThreads }, extractionTasks.ToArray()); } public virtual void Dispose() { stopWatch.Stop(); Logger.Log(Severity.Info, " Peak working set = {0} MB", Process.GetCurrentProcess().PeakWorkingSet64 / (1024 * 1024)); if (TotalErrors > 0) Logger.Log(Severity.Info, "EXTRACTION FAILED with {0} error{1} in {2}", TotalErrors, TotalErrors == 1 ? "" : "s", stopWatch.Elapsed); else Logger.Log(Severity.Info, "EXTRACTION SUCCEEDED in {0}", stopWatch.Elapsed); Logger.Dispose(); } /// <summary> /// Number of errors encountered during extraction. /// </summary> private int ExtractorErrors => extractor?.Errors ?? 0; /// <summary> /// Number of errors encountered by the compiler. /// </summary> public int CompilationErrors { get; set; } /// <summary> /// Total number of errors reported. /// </summary> public int TotalErrors => CompilationErrors + ExtractorErrors; /// <summary> /// Logs information about the extractor. /// </summary> public void LogExtractorInfo(string extractorVersion) { Logger.Log(Severity.Info, " Extractor: {0}", Environment.GetCommandLineArgs().First()); Logger.Log(Severity.Info, " Extractor version: {0}", extractorVersion); Logger.Log(Severity.Info, " Current working directory: {0}", Directory.GetCurrentDirectory()); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using System.Text.RegularExpressions; namespace PopX { public class Json { public const string NamePattern = "([\"]{1}[A-Za-z0-9]+[\"]{1})"; public const string SemiColonPattern = "([\\s]*):([\\s]*)"; // https://stackoverflow.com/a/32155765/355753 public const string ValueStringPattern = "([\\s]*)\"([^\\\\\"]*)\"([\\s]*)"; public const string ValueBoolPattern = "([\\s]*)(true|false){1}([\\s]*)"; public const string WhiteSpaceCharacters = " \n\r\t\b\f"; public const string ValidAsciiCharacters = "\"\\/"; public static string GetNamePattern(string Name) { return "([\"]{1}" + Name + "[\"]{1})"; } public static bool IsValidJsonAscii(char Char) { // https://www.json.org/ // gr: this tests unicode, which is supposed to be valid, but for binary-testing purposes it's letting through 0xff and stuff. no good //if (System.Char.IsLetter(Char)) // return true; if (IsWhiteSpace(Char)) return true; if (Char >= 'A' && Char <= 'Z') return true; if (Char >= 'a' && Char <= 'z') return true; if (Char >= '0' && Char <= '9') return true; var MatchIndex = ValidAsciiCharacters.IndexOf(Char); if (MatchIndex != -1) return true; //Debug.Log("Non json char: " + Char); return false; } public static bool IsWhiteSpace(char Char) { var MatchIndex = WhiteSpaceCharacters.IndexOf(Char); return MatchIndex != -1; } // works on byte[] and string, but can't do a generics with that in c#, so accessor for now. // Which is probably ultra slow static public int GetJsonLength(System.Func<int, char> GetChar) { var Index = 0; while (IsJsonWhitespace (GetChar (Index))) { Index++; } // pull json off the front if (GetChar(Index) != '{') throw new System.Exception("Data is not json. Starts["+Index+"] with " + (char)GetChar(Index)); Index++; var OpeningBrace = '{'; var ClosingBrace = '}'; int BraceCount = 1; while (BraceCount > 0) { try { var Char = GetChar(Index); if (Char == OpeningBrace) BraceCount++; if (Char == ClosingBrace) BraceCount--; Index++; } catch // OOB { throw new System.Exception("Json braces not balanced"); } } return Index; } static public int GetJsonLength(string Data,int StartPos=0) { return GetJsonLength((i) => { return Data[i+StartPos]; }); } static public int GetJsonLength(byte[] Data,int StartPos=0) { return GetJsonLength((i) => { return (char)Data[i+StartPos]; }); } static void EscapeChar(ref char[] CharPair) { switch(CharPair[0]) { case '\n': CharPair[0] = '\\'; CharPair[1] = 'n'; break; case '\t': CharPair[0] = '\\'; CharPair[1] = 't'; break; case '\r': CharPair[0] = '\\'; CharPair[1] = 'r'; break; case '\\': CharPair[0] = '\\'; CharPair[1] = '\\'; break; } } static public string EscapeValue(string Unescaped,bool WrapInQuotes=true) { var Escaped = WrapInQuotes ? "\"" : ""; var CharPair = new char[2]; var NullChar = '\0'; foreach (var Char in Unescaped) { CharPair [0] = Char; CharPair [1] = NullChar; EscapeChar (ref CharPair); Escaped += CharPair [0]; if (CharPair [1] != NullChar) Escaped += CharPair [1]; } if (WrapInQuotes) Escaped += "\""; return Escaped; } static public string EscapeValue(bool Value) { return Value ? "true" : "false"; } static public void Replace(ref string Json,string Key,string Value) { var StringElementPattern = GetNamePattern (Key) + PopX.Json.SemiColonPattern + ValueStringPattern; var RegExpression = new Regex (StringElementPattern); // todo: json escaping! var Replacement = '"' + Key + '"' + ':' + EscapeValue(Value); // harder to debug, but simpler implementation Json = RegExpression.Replace (Json, Replacement); } static public void Replace(ref string Json, string Key,bool Value) { var StringElementPattern = GetNamePattern(Key) + PopX.Json.SemiColonPattern + ValueBoolPattern; var RegExpression = new Regex(StringElementPattern); // todo: json escaping! var Replacement = '"' + Key + '"' + ':' + EscapeValue(Value); // harder to debug, but simpler implementation Json = RegExpression.Replace(Json, Replacement); } static bool IsJsonWhitespace(char Char) { switch(Char) { case '\n': case ' ': case '\r': case '\t': return true; default: return false; } } static public void Append(ref string Json,string Key,string Value) { // construct what we're injecting var NewContent = '"' + Key + '"' + ':' + EscapeValue(Value); // find end brace var LastBrace = Json.LastIndexOf('}'); if (LastBrace < 0) throw new System.Exception ("Missing end brace of json"); // look for any json content between end of start brace // need to cope with comments var HasJsonContent = false; for (int i = LastBrace - 1; i >= 0; i--) { var Char = Json [i]; if (IsJsonWhitespace (Char)) continue; if (Char == '{') break; HasJsonContent = true; } if (HasJsonContent) NewContent = ",\n" + NewContent; NewContent += '\n'; Json = Json.Insert (LastBrace, NewContent); } } }