context
stringlengths
2.52k
185k
gt
stringclasses
1 value
using System; using System.Collections.Generic; using QuickGraph; using System.Linq; namespace SIP { using Graph = UndirectedGraph<Vertex, Edge>; using WeightedGraph = UndirectedGraph<WeightedVertex, WeightedEdge>; using Label = String; using TVFT = Dictionary<String, int>; using TEFT = Dictionary<Tuple<String, String>, int>; public class SEQ { SEQ() {} public static List<Item> BuildSEQ(Graph q, Graph g) { // Base data structures HashSet<int> vt = new HashSet<int>(); // verticies in seq (or in minimun spanning tree) List<Item> seq = new List<Item>(); // Initialize tabels TVFT vft = mkVFT (q, g); // vertex frequency table TEFT eft = mkEFT (q, g); // edge frequency table WeightedGraph qw = weightGraph (vft, eft, q); // First step: find first candidates var vCount = q.VertexCount; var p = lightestEdges (qw); var e = selectFirstEdge (p.ToList (), qw); // Add first edge int srcID = e.Source.ID; int tgtID = e.Target.ID; vt.Add (srcID); vt.Add (tgtID); seq.Add (new Item(-1, srcID, e.Source.Label, degree(q, srcID), new List<int>())); seq.Add (new Item(srcID, tgtID, e.Target.Label, degree(q, tgtID), new List<int>())); qw.RemoveEdge (e); // Loop while building whole SEQ while (vt.Count() < vCount) { p = front (qw, vt); // Select next suitable set of verticies e = selectSpanningEdge (p, qw, vt); // Next best edge // Add currently chosen vertex to SEQ var outerVert = outerVertex (vt, e); var innerVert = (e.Source != outerVert) ? e.Source : e.Target; vt.Add (outerVert.ID); qw.RemoveEdge (e); // Other edges not included to tree but fully contained by its verticies var absorbed = from ee in qw.Edges where (ee.Target.ID == outerVert.ID || ee.Source.ID == outerVert.ID) && vt.Contains (ee.Source.ID) && vt.Contains (ee.Target.ID) orderby ee.Weight select ee; var extras = new List<int> (); foreach (var ee in absorbed) { extras.Add ((ee.Source.ID != outerVert.ID) ? ee.Source.ID : ee.Target.ID); qw.RemoveEdge (ee); } seq.Add(new Item(innerVert.ID, outerVert.ID, outerVert.Label, degree(q, outerVert.ID), extras)); } return seq; } static Dictionary<Label, int> mkVFT(Graph q, Graph g) { var ft = new Dictionary<Label, int> (); foreach (var v in q.Vertices) { if (!ft.ContainsKey (v.Label)) { ft [v.Label] = g.Vertices.Count (v2 => v2.Label.Equals (v.Label)); } } return ft; } static Dictionary<Tuple<Label, Label>, int> mkEFT(Graph q, Graph g) { var ft = new Dictionary<Tuple<Label, Label>, int> (); foreach (var e in q.Edges) { var key = Tuple.Create (e.Source.Label, e.Target.Label); var key2 = Tuple.Create (e.Target.Label, e.Source.Label); if (!(ft.ContainsKey (key) || ft.ContainsKey (key2))) { ft [key] = g.Edges.Count (e2 => Edge.UndirectedEquals (e, e2)); ft [key2] = ft [key]; } } return ft; } static WeightedGraph weightGraph(TVFT vft, TEFT eft, Graph q) { var qq = new WeightedGraph (false); qq.AddVerticesAndEdgeRange ( from e in q.Edges select weightEdge(vft, eft, e) ); return qq; } static WeightedEdge weightEdge(TVFT vft, TEFT eft, IEdge<Vertex> e) { var src = new WeightedVertex (e.Source.ID, e.Source.Label, vft [e.Source.Label]); var tgt = new WeightedVertex (e.Target.ID, e.Target.Label, vft [e.Target.Label]); var w = eft [Tuple.Create (src.Label, tgt.Label)]; return new WeightedEdge(src, tgt, w); } static IEnumerable<WeightedEdge> lightestEdges(WeightedGraph q) { var minWeight = q.Edges.Min(e => e.Weight); return q.Edges.Where (e => e.Weight == minWeight); } static WeightedEdge selectFirstEdge(IEnumerable<WeightedEdge> p, WeightedGraph q) { if (p.Count() > 1) { Func<WeightedVertex, int> degree = v => q.AdjacentEdges(v).Count(); Func<WeightedEdge, int> edgeDegree = e => degree (e.Source) + degree (e.Target); var minEdgeDegree = q.Edges.Min (edgeDegree); p = p.Where (e => edgeDegree (e) == minEdgeDegree); } return p.First (); } static int indGCount(WeightedGraph q, HashSet<int> vs) { return q.Edges.Count ( e => vs.Contains (e.Source.ID) && vs.Contains (e.Target.ID) ); } static WeightedVertex outerVertex(HashSet<int> vs, WeightedEdge e) { return (vs.Contains (e.Source.ID)) ? e.Target : e.Source; } static WeightedEdge selectSpanningEdge(IEnumerable<WeightedEdge> p, WeightedGraph q, HashSet<int> vs) { if (p.Count () > 1) { Func<WeightedEdge, int> ind = e => { var o = outerVertex (vs, e); vs.Add (o.ID); var indg = indGCount (q, vs); vs.Remove (o.ID); return indg; }; var maxIndG = q.Edges.Max (ind); p = p.Where (e => ind (e) == maxIndG); } if (p.Count () > 1) { Func<WeightedEdge, int> outerDegree = e => q.AdjacentEdges(outerVertex (vs, e)).Count(); var minDegree = q.Edges.Min (outerDegree); p = p.Where (e => outerDegree (e) == minDegree); } return p.First (); } static int degree(Graph q, int vID) { var vert = (from v in q.Vertices where v.ID == vID select v).First(); return q.AdjacentEdges (vert).Count (); } static IEnumerable<WeightedEdge> front(WeightedGraph q, HashSet<int> vs) { List<WeightedEdge> es = new List<WeightedEdge> (); foreach (var e in q.Edges) { var src = e.Source; var tgt = e.Target; var srcin = vs.Contains (src.ID); var tgtin = vs.Contains (tgt.ID); if (srcin ^ tgtin) { es.Add (e); } } return es; } public class Item { public Item(int parent, int vertex, Label label, int degree, List<int> extraEdges) { this.Parent = parent; this.Vertex = vertex; this.Label = label; this.Degree = degree; this.ExtraEdges = extraEdges; } public int Parent { get; private set; } public int Vertex { get; private set; } public String Label { get; private set; } public int Degree { get; private set; } public List<int> ExtraEdges { get; private set; } public override string ToString () { return string.Format ("[{0} -> {1}({2}); d({3})]", Parent, Vertex, Label, Degree); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System.Drawing.Imaging { /* * EmfPlusRecordType constants */ /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType"]/*' /> /// <devdoc> /// <para> /// Specifies the methods available in a metafile to read and write graphic /// commands. /// </para> /// </devdoc> public enum EmfPlusRecordType { /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.WmfRecordBase"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> WmfRecordBase = 0x00010000, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.WmfSetBkColor"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> WmfSetBkColor = WmfRecordBase | 0x201, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.WmfSetBkMode"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> WmfSetBkMode = WmfRecordBase | 0x102, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.WmfSetMapMode"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> WmfSetMapMode = WmfRecordBase | 0x103, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.WmfSetROP2"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> WmfSetROP2 = WmfRecordBase | 0x104, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.WmfSetRelAbs"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> WmfSetRelAbs = WmfRecordBase | 0x105, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.WmfSetPolyFillMode"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> WmfSetPolyFillMode = WmfRecordBase | 0x106, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.WmfSetStretchBltMode"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> WmfSetStretchBltMode = WmfRecordBase | 0x107, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.WmfSetTextCharExtra"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> WmfSetTextCharExtra = WmfRecordBase | 0x108, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.WmfSetTextColor"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> WmfSetTextColor = WmfRecordBase | 0x209, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.WmfSetTextJustification"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> WmfSetTextJustification = WmfRecordBase | 0x20A, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.WmfSetWindowOrg"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> WmfSetWindowOrg = WmfRecordBase | 0x20B, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.WmfSetWindowExt"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> WmfSetWindowExt = WmfRecordBase | 0x20C, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.WmfSetViewportOrg"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> WmfSetViewportOrg = WmfRecordBase | 0x20D, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.WmfSetViewportExt"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> WmfSetViewportExt = WmfRecordBase | 0x20E, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.WmfOffsetWindowOrg"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> WmfOffsetWindowOrg = WmfRecordBase | 0x20F, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.WmfScaleWindowExt"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> WmfScaleWindowExt = WmfRecordBase | 0x410, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.WmfOffsetViewportOrg"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> WmfOffsetViewportOrg = WmfRecordBase | 0x211, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.WmfScaleViewportExt"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> WmfScaleViewportExt = WmfRecordBase | 0x412, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.WmfLineTo"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> WmfLineTo = WmfRecordBase | 0x213, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.WmfMoveTo"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> WmfMoveTo = WmfRecordBase | 0x214, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.WmfExcludeClipRect"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> WmfExcludeClipRect = WmfRecordBase | 0x415, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.WmfIntersectClipRect"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> WmfIntersectClipRect = WmfRecordBase | 0x416, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.WmfArc"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> WmfArc = WmfRecordBase | 0x817, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.WmfEllipse"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> WmfEllipse = WmfRecordBase | 0x418, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.WmfFloodFill"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> WmfFloodFill = WmfRecordBase | 0x419, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.WmfPie"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> WmfPie = WmfRecordBase | 0x81A, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.WmfRectangle"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> WmfRectangle = WmfRecordBase | 0x41B, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.WmfRoundRect"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> WmfRoundRect = WmfRecordBase | 0x61C, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.WmfPatBlt"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> WmfPatBlt = WmfRecordBase | 0x61D, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.WmfSaveDC"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> WmfSaveDC = WmfRecordBase | 0x01E, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.WmfSetPixel"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> WmfSetPixel = WmfRecordBase | 0x41F, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.WmfOffsetCilpRgn"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> WmfOffsetCilpRgn = WmfRecordBase | 0x220, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.WmfTextOut"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> WmfTextOut = WmfRecordBase | 0x521, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.WmfBitBlt"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> WmfBitBlt = WmfRecordBase | 0x922, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.WmfStretchBlt"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> WmfStretchBlt = WmfRecordBase | 0xB23, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.WmfPolygon"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> WmfPolygon = WmfRecordBase | 0x324, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.WmfPolyline"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> WmfPolyline = WmfRecordBase | 0x325, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.WmfEscape"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> WmfEscape = WmfRecordBase | 0x626, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.WmfRestoreDC"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> WmfRestoreDC = WmfRecordBase | 0x127, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.WmfFillRegion"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> WmfFillRegion = WmfRecordBase | 0x228, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.WmfFrameRegion"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> WmfFrameRegion = WmfRecordBase | 0x429, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.WmfInvertRegion"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> WmfInvertRegion = WmfRecordBase | 0x12A, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.WmfPaintRegion"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> WmfPaintRegion = WmfRecordBase | 0x12B, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.WmfSelectClipRegion"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> WmfSelectClipRegion = WmfRecordBase | 0x12C, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.WmfSelectObject"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> WmfSelectObject = WmfRecordBase | 0x12D, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.WmfSetTextAlign"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> WmfSetTextAlign = WmfRecordBase | 0x12E, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.WmfChord"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> WmfChord = WmfRecordBase | 0x830, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.WmfSetMapperFlags"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> WmfSetMapperFlags = WmfRecordBase | 0x231, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.WmfExtTextOut"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> WmfExtTextOut = WmfRecordBase | 0xA32, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.WmfSetDibToDev"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> WmfSetDibToDev = WmfRecordBase | 0xD33, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.WmfSelectPalette"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> WmfSelectPalette = WmfRecordBase | 0x234, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.WmfRealizePalette"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> WmfRealizePalette = WmfRecordBase | 0x035, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.WmfAnimatePalette"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> WmfAnimatePalette = WmfRecordBase | 0x436, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.WmfSetPalEntries"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> WmfSetPalEntries = WmfRecordBase | 0x037, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.WmfPolyPolygon"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> WmfPolyPolygon = WmfRecordBase | 0x538, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.WmfResizePalette"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> WmfResizePalette = WmfRecordBase | 0x139, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.WmfDibBitBlt"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> WmfDibBitBlt = WmfRecordBase | 0x940, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.WmfDibStretchBlt"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> WmfDibStretchBlt = WmfRecordBase | 0xb41, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.WmfDibCreatePatternBrush"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> WmfDibCreatePatternBrush = WmfRecordBase | 0x142, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.WmfStretchDib"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> WmfStretchDib = WmfRecordBase | 0xf43, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.WmfExtFloodFill"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> WmfExtFloodFill = WmfRecordBase | 0x548, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.WmfSetLayout"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> WmfSetLayout = WmfRecordBase | 0x149, // META_SETLAYOUT /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.WmfDeleteObject"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> WmfDeleteObject = WmfRecordBase | 0x1f0, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.WmfCreatePalette"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> WmfCreatePalette = WmfRecordBase | 0x0f7, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.WmfCreatePatternBrush"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> WmfCreatePatternBrush = WmfRecordBase | 0x1f9, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.WmfCreatePenIndirect"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> WmfCreatePenIndirect = WmfRecordBase | 0x2fa, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.WmfCreateFontIndirect"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> WmfCreateFontIndirect = WmfRecordBase | 0x2fb, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.WmfCreateBrushIndirect"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> WmfCreateBrushIndirect = WmfRecordBase | 0x2fc, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.WmfCreateRegion"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> WmfCreateRegion = WmfRecordBase | 0x6ff, // Since we have to enumerate GDI records right along with GDI+ records, // we list all the GDI records here so that they can be part of the // same enumeration type which is used in the enumeration callback. /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.EmfHeader"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> EmfHeader = 1, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.EmfPolyBezier"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> EmfPolyBezier = 2, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.EmfPolygon"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> EmfPolygon = 3, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.EmfPolyline"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> EmfPolyline = 4, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.EmfPolyBezierTo"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> EmfPolyBezierTo = 5, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.EmfPolyLineTo"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> EmfPolyLineTo = 6, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.EmfPolyPolyline"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> EmfPolyPolyline = 7, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.EmfPolyPolygon"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> EmfPolyPolygon = 8, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.EmfSetWindowExtEx"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> EmfSetWindowExtEx = 9, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.EmfSetWindowOrgEx"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> EmfSetWindowOrgEx = 10, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.EmfSetViewportExtEx"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> EmfSetViewportExtEx = 11, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.EmfSetViewportOrgEx"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> EmfSetViewportOrgEx = 12, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.EmfSetBrushOrgEx"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> EmfSetBrushOrgEx = 13, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.EmfEof"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> EmfEof = 14, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.EmfSetPixelV"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> EmfSetPixelV = 15, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.EmfSetMapperFlags"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> EmfSetMapperFlags = 16, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.EmfSetMapMode"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> EmfSetMapMode = 17, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.EmfSetBkMode"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> EmfSetBkMode = 18, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.EmfSetPolyFillMode"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> EmfSetPolyFillMode = 19, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.EmfSetROP2"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> EmfSetROP2 = 20, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.EmfSetStretchBltMode"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> EmfSetStretchBltMode = 21, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.EmfSetTextAlign"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> EmfSetTextAlign = 22, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.EmfSetColorAdjustment"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> EmfSetColorAdjustment = 23, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.EmfSetTextColor"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> EmfSetTextColor = 24, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.EmfSetBkColor"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> EmfSetBkColor = 25, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.EmfOffsetClipRgn"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> EmfOffsetClipRgn = 26, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.EmfMoveToEx"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> EmfMoveToEx = 27, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.EmfSetMetaRgn"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> EmfSetMetaRgn = 28, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.EmfExcludeClipRect"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> EmfExcludeClipRect = 29, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.EmfIntersectClipRect"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> EmfIntersectClipRect = 30, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.EmfScaleViewportExtEx"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> EmfScaleViewportExtEx = 31, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.EmfScaleWindowExtEx"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> EmfScaleWindowExtEx = 32, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.EmfSaveDC"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> EmfSaveDC = 33, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.EmfRestoreDC"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> EmfRestoreDC = 34, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.EmfSetWorldTransform"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> EmfSetWorldTransform = 35, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.EmfModifyWorldTransform"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> EmfModifyWorldTransform = 36, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.EmfSelectObject"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> EmfSelectObject = 37, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.EmfCreatePen"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> EmfCreatePen = 38, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.EmfCreateBrushIndirect"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> EmfCreateBrushIndirect = 39, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.EmfDeleteObject"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> EmfDeleteObject = 40, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.EmfAngleArc"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> EmfAngleArc = 41, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.EmfEllipse"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> EmfEllipse = 42, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.EmfRectangle"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> EmfRectangle = 43, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.EmfRoundRect"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> EmfRoundRect = 44, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.EmfRoundArc"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> EmfRoundArc = 45, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.EmfChord"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> EmfChord = 46, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.EmfPie"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> EmfPie = 47, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.EmfSelectPalette"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> EmfSelectPalette = 48, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.EmfCreatePalette"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> EmfCreatePalette = 49, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.EmfSetPaletteEntries"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> EmfSetPaletteEntries = 50, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.EmfResizePalette"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> EmfResizePalette = 51, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.EmfRealizePalette"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> EmfRealizePalette = 52, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.EmfExtFloodFill"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> EmfExtFloodFill = 53, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.EmfLineTo"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> EmfLineTo = 54, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.EmfArcTo"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> EmfArcTo = 55, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.EmfPolyDraw"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> EmfPolyDraw = 56, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.EmfSetArcDirection"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> EmfSetArcDirection = 57, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.EmfSetMiterLimit"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> EmfSetMiterLimit = 58, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.EmfBeginPath"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> EmfBeginPath = 59, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.EmfEndPath"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> EmfEndPath = 60, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.EmfCloseFigure"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> EmfCloseFigure = 61, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.EmfFillPath"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> EmfFillPath = 62, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.EmfStrokeAndFillPath"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> EmfStrokeAndFillPath = 63, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.EmfStrokePath"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> EmfStrokePath = 64, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.EmfFlattenPath"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> EmfFlattenPath = 65, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.EmfWidenPath"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> EmfWidenPath = 66, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.EmfSelectClipPath"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> EmfSelectClipPath = 67, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.EmfAbortPath"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> EmfAbortPath = 68, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.EmfReserved069"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> EmfReserved069 = 69, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.EmfGdiComment"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> EmfGdiComment = 70, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.EmfFillRgn"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> EmfFillRgn = 71, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.EmfFrameRgn"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> EmfFrameRgn = 72, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.EmfInvertRgn"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> EmfInvertRgn = 73, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.EmfPaintRgn"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> EmfPaintRgn = 74, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.EmfExtSelectClipRgn"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> EmfExtSelectClipRgn = 75, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.EmfBitBlt"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> EmfBitBlt = 76, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.EmfStretchBlt"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> EmfStretchBlt = 77, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.EmfMaskBlt"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> EmfMaskBlt = 78, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.EmfPlgBlt"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> EmfPlgBlt = 79, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.EmfSetDIBitsToDevice"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> EmfSetDIBitsToDevice = 80, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.EmfStretchDIBits"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> EmfStretchDIBits = 81, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.EmfExtCreateFontIndirect"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> EmfExtCreateFontIndirect = 82, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.EmfExtTextOutA"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> EmfExtTextOutA = 83, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.EmfExtTextOutW"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> EmfExtTextOutW = 84, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.EmfPolyBezier16"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> EmfPolyBezier16 = 85, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.EmfPolygon16"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> EmfPolygon16 = 86, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.EmfPolyline16"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> EmfPolyline16 = 87, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.EmfPolyBezierTo16"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> EmfPolyBezierTo16 = 88, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.EmfPolylineTo16"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> EmfPolylineTo16 = 89, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.EmfPolyPolyline16"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> EmfPolyPolyline16 = 90, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.EmfPolyPolygon16"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> EmfPolyPolygon16 = 91, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.EmfPolyDraw16"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> EmfPolyDraw16 = 92, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.EmfCreateMonoBrush"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> EmfCreateMonoBrush = 93, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.EmfCreateDibPatternBrushPt"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> EmfCreateDibPatternBrushPt = 94, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.EmfExtCreatePen"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> EmfExtCreatePen = 95, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.EmfPolyTextOutA"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> EmfPolyTextOutA = 96, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.EmfPolyTextOutW"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> EmfPolyTextOutW = 97, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.EmfSetIcmMode"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> EmfSetIcmMode = 98, // EMR_SETICMMODE, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.EmfCreateColorSpace"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> EmfCreateColorSpace = 99, // EMR_CREATECOLORSPACE, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.EmfSetColorSpace"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> EmfSetColorSpace = 100, // EMR_SETCOLORSPACE, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.EmfDeleteColorSpace"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> EmfDeleteColorSpace = 101, // EMR_DELETECOLORSPACE, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.EmfGlsRecord"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> EmfGlsRecord = 102, // EMR_GLSRECORD, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.EmfGlsBoundedRecord"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> EmfGlsBoundedRecord = 103, // EMR_GLSBOUNDEDRECORD, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.EmfPixelFormat"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> EmfPixelFormat = 104, // EMR_PIXELFORMAT, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.EmfDrawEscape"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> EmfDrawEscape = 105, // EMR_RESERVED_105, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.EmfExtEscape"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> EmfExtEscape = 106, // EMR_RESERVED_106, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.EmfStartDoc"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> EmfStartDoc = 107, // EMR_RESERVED_107, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.EmfSmallTextOut"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> EmfSmallTextOut = 108, // EMR_RESERVED_108, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.EmfForceUfiMapping"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> EmfForceUfiMapping = 109, // EMR_RESERVED_109, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.EmfNamedEscpae"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> EmfNamedEscpae = 110, // EMR_RESERVED_110, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.EmfColorCorrectPalette"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> EmfColorCorrectPalette = 111, // EMR_COLORCORRECTPALETTE, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.EmfSetIcmProfileA"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> EmfSetIcmProfileA = 112, // EMR_SETICMPROFILEA, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.EmfSetIcmProfileW"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> EmfSetIcmProfileW = 113, // EMR_SETICMPROFILEW, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.EmfAlphaBlend"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> EmfAlphaBlend = 114, // EMR_ALPHABLEND, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.EmfSetLayout"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> EmfSetLayout = 115, // EMR_SETLAYOUT, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.EmfTransparentBlt"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> EmfTransparentBlt = 116, // EMR_TRANSPARENTBLT, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.EmfReserved117"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> EmfReserved117 = 117, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.EmfGradientFill"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> EmfGradientFill = 118, // EMR_GRADIENTFILL, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.EmfSetLinkedUfis"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> EmfSetLinkedUfis = 119, // EMR_RESERVED_119, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.EmfSetTextJustification"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> EmfSetTextJustification = 120, // EMR_RESERVED_120, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.EmfColorMatchToTargetW"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> EmfColorMatchToTargetW = 121, // EMR_COLORMATCHTOTARGETW, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.EmfCreateColorSpaceW"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> EmfCreateColorSpaceW = 122, // EMR_CREATECOLORSPACEW, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.EmfMax"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> EmfMax = 122, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.EmfMin"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> EmfMin = 1, // That is the END of the GDI EMF records. // Now we start the list of EMF+ records. We leave quite // a bit of room here for the addition of any new GDI // records that may be added later. /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.EmfPlusRecordBase"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> EmfPlusRecordBase = 0x00004000, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.Invalid"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> Invalid = EmfPlusRecordBase, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.Header"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> Header, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.EndOfFile"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> EndOfFile, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.Comment"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> Comment, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.GetDC"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> GetDC, // the application grabbed the metafile dc /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.MultiFormatStart"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> MultiFormatStart, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.MultiFormatSection"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> MultiFormatSection, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.MultiFormatEnd"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> MultiFormatEnd, // For all Persistent Objects /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.Object"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> Object, // Drawing Records /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.Clear"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> Clear, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.FillRects"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> FillRects, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.DrawRects"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> DrawRects, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.FillPolygon"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> FillPolygon, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.DrawLines"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> DrawLines, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.FillEllipse"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> FillEllipse, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.DrawEllipse"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> DrawEllipse, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.FillPie"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> FillPie, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.DrawPie"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> DrawPie, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.DrawArc"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> DrawArc, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.FillRegion"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> FillRegion, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.FillPath"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> FillPath, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.DrawPath"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> DrawPath, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.FillClosedCurve"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> FillClosedCurve, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.DrawClosedCurve"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> DrawClosedCurve, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.DrawCurve"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> DrawCurve, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.DrawBeziers"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> DrawBeziers, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.DrawImage"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> DrawImage, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.DrawImagePoints"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> DrawImagePoints, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.DrawString"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> DrawString, // Graphics State Records /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.SetRenderingOrigin"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> SetRenderingOrigin, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.SetAntiAliasMode"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> SetAntiAliasMode, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.SetTextRenderingHint"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> SetTextRenderingHint, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.SetTextContrast"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> SetTextContrast, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.SetInterpolationMode"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> SetInterpolationMode, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.SetPixelOffsetMode"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> SetPixelOffsetMode, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.SetCompositingMode"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> SetCompositingMode, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.SetCompositingQuality"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> SetCompositingQuality, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.Save"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> Save, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.Restore"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> Restore, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.BeginContainer"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> BeginContainer, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.BeginContainerNoParams"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] BeginContainerNoParams, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.EndContainer"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> EndContainer, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.SetWorldTransform"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> SetWorldTransform, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.ResetWorldTransform"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> ResetWorldTransform, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.MultiplyWorldTransform"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> MultiplyWorldTransform, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.TranslateWorldTransform"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> TranslateWorldTransform, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.ScaleWorldTransform"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> ScaleWorldTransform, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.RotateWorldTransform"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> RotateWorldTransform, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.SetPageTransform"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> SetPageTransform, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.ResetClip"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> ResetClip, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.SetClipRect"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> SetClipRect, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.SetClipPath"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> SetClipPath, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.SetClipRegion"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> SetClipRegion, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.OffsetClip"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> OffsetClip, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.DrawDriverString"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> DrawDriverString, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.Total"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> Total, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.Max"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> Max = Total - 1, /// <include file='doc\EmfPlusRecordType.uex' path='docs/doc[@for="EmfPlusRecordType.Min"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> Min = Header } }
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System; using System.Collections.Generic; using System.Linq; using OpenTK; using OpenTK.Graphics; using osu.Framework.Allocation; using osu.Framework.Extensions.Color4Extensions; using osu.Framework.Graphics; using osu.Framework.Graphics.Colour; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Sprites; using osu.Framework.Graphics.Textures; using osu.Framework.Localisation; using osu.Game.Beatmaps; using osu.Game.Graphics; using osu.Game.Graphics.Sprites; using osu.Game.Graphics.UserInterface; using osu.Game.Rulesets.Scoring; using osu.Game.Screens.Play; using osu.Game.Screens.Select.Leaderboards; using osu.Game.Users; using osu.Framework.Graphics.Shapes; namespace osu.Game.Screens.Ranking { internal class ResultsPageScore : ResultsPage { private ScoreCounter scoreCounter; public ResultsPageScore(Score score, WorkingBeatmap beatmap) : base(score, beatmap) { } private FillFlowContainer<DrawableScoreStatistic> statisticsContainer; [BackgroundDependencyLoader] private void load(OsuColour colours) { const float user_header_height = 120; Children = new Drawable[] { new Container { RelativeSizeAxes = Axes.Both, Padding = new MarginPadding { Top = user_header_height }, Children = new Drawable[] { new Box { RelativeSizeAxes = Axes.Both, Colour = Color4.White, }, } }, new FillFlowContainer { RelativeSizeAxes = Axes.X, AutoSizeAxes = Axes.Y, Direction = FillDirection.Vertical, Children = new Drawable[] { new UserHeader(Score.User) { Anchor = Anchor.TopCentre, Origin = Anchor.TopCentre, RelativeSizeAxes = Axes.X, Height = user_header_height, }, new DrawableRank(Score.Rank) { Anchor = Anchor.TopCentre, Origin = Anchor.TopCentre, Size = new Vector2(150, 60), Margin = new MarginPadding(20), }, new Container { Anchor = Anchor.TopCentre, Origin = Anchor.TopCentre, RelativeSizeAxes = Axes.X, Height = 60, Children = new Drawable[] { new SongProgressGraph { RelativeSizeAxes = Axes.Both, Alpha = 0.5f, Objects = Beatmap.Beatmap.HitObjects, }, scoreCounter = new SlowScoreCounter(6) { Anchor = Anchor.TopCentre, Origin = Anchor.TopCentre, Colour = colours.PinkDarker, Y = 10, TextSize = 56, }, } }, new OsuSpriteText { Anchor = Anchor.TopCentre, Origin = Anchor.TopCentre, Colour = colours.PinkDarker, Shadow = false, Font = @"Exo2.0-Bold", TextSize = 16, Text = "total score", Margin = new MarginPadding { Bottom = 15 }, }, new BeatmapDetails(Beatmap.BeatmapInfo) { Anchor = Anchor.TopCentre, Origin = Anchor.TopCentre, Margin = new MarginPadding { Bottom = 10 }, }, new DateTimeDisplay(Score.Date.LocalDateTime) { Anchor = Anchor.TopCentre, Origin = Anchor.TopCentre, }, new Container { RelativeSizeAxes = Axes.X, Size = new Vector2(0.75f, 1), Anchor = Anchor.TopCentre, Origin = Anchor.TopCentre, Margin = new MarginPadding { Top = 10, Bottom = 10 }, Children = new Drawable[] { new Box { Colour = ColourInfo.GradientHorizontal( colours.GrayC.Opacity(0), colours.GrayC.Opacity(0.9f)), RelativeSizeAxes = Axes.Both, Size = new Vector2(0.5f, 1), }, new Box { Anchor = Anchor.TopRight, Origin = Anchor.TopRight, Colour = ColourInfo.GradientHorizontal( colours.GrayC.Opacity(0.9f), colours.GrayC.Opacity(0)), RelativeSizeAxes = Axes.Both, Size = new Vector2(0.5f, 1), }, } }, statisticsContainer = new FillFlowContainer<DrawableScoreStatistic> { AutoSizeAxes = Axes.Both, Anchor = Anchor.TopCentre, Origin = Anchor.TopCentre, Direction = FillDirection.Horizontal, LayoutDuration = 200, LayoutEasing = Easing.OutQuint } } } }; statisticsContainer.ChildrenEnumerable = Score.Statistics.Select(s => new DrawableScoreStatistic(s)); } protected override void LoadComplete() { base.LoadComplete(); Schedule(() => { scoreCounter.Increment(Score.TotalScore); int delay = 0; foreach (var s in statisticsContainer.Children) { s.FadeOut() .Then(delay += 200) .FadeIn(300 + delay, Easing.Out); } }); } private class DrawableScoreStatistic : Container { private readonly KeyValuePair<string, dynamic> statistic; public DrawableScoreStatistic(KeyValuePair<string, dynamic> statistic) { this.statistic = statistic; AutoSizeAxes = Axes.Both; Margin = new MarginPadding { Left = 5, Right = 5 }; } [BackgroundDependencyLoader] private void load(OsuColour colours) { Children = new Drawable[] { new SpriteText { Text = statistic.Value.ToString().PadLeft(4, '0'), Colour = colours.Gray7, TextSize = 30, Anchor = Anchor.TopCentre, Origin = Anchor.TopCentre, }, new SpriteText { Text = statistic.Key, Colour = colours.Gray7, Font = @"Exo2.0-Bold", Y = 26, Anchor = Anchor.TopCentre, Origin = Anchor.TopCentre, }, }; } } private class DateTimeDisplay : Container { private DateTime datetime; public DateTimeDisplay(DateTime datetime) { this.datetime = datetime; AutoSizeAxes = Axes.Y; Width = 140; Masking = true; CornerRadius = 5; } [BackgroundDependencyLoader] private void load(OsuColour colours) { Children = new Drawable[] { new Box { RelativeSizeAxes = Axes.Both, Colour = colours.Gray6, }, new OsuSpriteText { Origin = Anchor.CentreLeft, Anchor = Anchor.CentreLeft, Text = datetime.ToString("HH:mm"), Padding = new MarginPadding { Left = 10, Right = 10, Top = 5, Bottom = 5 }, Colour = Color4.White, }, new OsuSpriteText { Origin = Anchor.CentreRight, Anchor = Anchor.CentreRight, Text = datetime.ToString("yyyy/MM/dd"), Padding = new MarginPadding { Left = 10, Right = 10, Top = 5, Bottom = 5 }, Colour = Color4.White, } }; } } private class BeatmapDetails : Container { private readonly BeatmapInfo beatmap; private readonly OsuSpriteText title; private readonly OsuSpriteText artist; private readonly OsuSpriteText versionMapper; public BeatmapDetails(BeatmapInfo beatmap) { this.beatmap = beatmap; AutoSizeAxes = Axes.Both; Children = new Drawable[] { new FillFlowContainer { Direction = FillDirection.Vertical, RelativeSizeAxes = Axes.X, AutoSizeAxes = Axes.Y, Children = new Drawable[] { title = new OsuSpriteText { Anchor = Anchor.TopCentre, Origin = Anchor.TopCentre, Shadow = false, TextSize = 24, Font = @"Exo2.0-BoldItalic", }, artist = new OsuSpriteText { Anchor = Anchor.TopCentre, Origin = Anchor.TopCentre, Shadow = false, TextSize = 20, Font = @"Exo2.0-BoldItalic", }, versionMapper = new OsuSpriteText { Anchor = Anchor.TopCentre, Origin = Anchor.TopCentre, Shadow = false, TextSize = 16, Font = @"Exo2.0-Bold", }, } } }; } [BackgroundDependencyLoader] private void load(OsuColour colours, LocalisationEngine localisation) { title.Colour = artist.Colour = colours.BlueDarker; versionMapper.Colour = colours.Gray8; versionMapper.Text = $"{beatmap.Version} - mapped by {beatmap.Metadata.Author}"; title.Current = localisation.GetUnicodePreference(beatmap.Metadata.TitleUnicode, beatmap.Metadata.Title); artist.Current = localisation.GetUnicodePreference(beatmap.Metadata.ArtistUnicode, beatmap.Metadata.Artist); } } private class UserHeader : Container { private readonly User user; private readonly Sprite cover; public UserHeader(User user) { this.user = user; Children = new Drawable[] { cover = new Sprite { RelativeSizeAxes = Axes.Both, FillMode = FillMode.Fill, Anchor = Anchor.Centre, Origin = Anchor.Centre, }, new OsuSpriteText { Font = @"Exo2.0-RegularItalic", Text = user.Username, Anchor = Anchor.BottomCentre, Origin = Anchor.BottomCentre, TextSize = 30, Padding = new MarginPadding { Bottom = 10 }, } }; } [BackgroundDependencyLoader] private void load(TextureStore textures) { if (!string.IsNullOrEmpty(user.CoverUrl)) cover.Texture = textures.Get(user.CoverUrl); } } private class SlowScoreCounter : ScoreCounter { protected override double RollingDuration => 3000; protected override Easing RollingEasing => Easing.OutPow10; public SlowScoreCounter(uint leading = 0) : base(leading) { DisplayedCountSpriteText.Shadow = false; DisplayedCountSpriteText.Font = @"Venera-Light"; UseCommaSeparator = true; } } } }
//////////////////////////////////////////////////////////////////////////////// //Main.cs //Created on: 2015-8-20, 19:35 // //Project VoxelEngine //Copyright C bajsko 2015. All rights Reserved. //////////////////////////////////////////////////////////////////////////////// using System; using System.Collections.Generic; using System.Linq; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.GamerServices; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Media; using VoxelEngine.Basic; using VoxelEngine.GameConsole; using VoxelEngine.Game; using VoxelEngine.Utility; namespace VoxelEngine { /// <summary> /// This is the main type for your game /// </summary> public class Main : Microsoft.Xna.Framework.Game { private const string RENDERING_SETTINGS = "render_settings.vxl"; public static Main Instance { get; private set; } public static bool WindowIsActive {get { return Instance.IsActive; }} public static GameTime GameTime { get; private set; } public static Vector2 ScreenSize { get; private set; } public static FreeCamera Camera { get; set; } //in god we trust public static bool ShowAxisHelper { get; set; } public static bool ShowFPS { get; set; } public static int ChunkRenderCount { get; set; } public static int TrianleRenderCount { get; set; } public static int VertexRenderCount { get; set; } public static int VisibleChunks { get; set; } public static World World { get { return Instance.world; } } public static bool HaltChunkManager {get; set;} public Settings RenderingSettings { get; private set; } private World world; private WorldRenderer worldRenderer; private AxisHelper axisHelper; private GraphicsDeviceManager graphics; private SpriteBatch spriteBatch; private Keys ConsoleKey { get { return Keys.Tab; } } public Main() : base() { Instance = this; graphics = new GraphicsDeviceManager(this); Content.RootDirectory = "Content"; RenderingSettings = SettingsParser.Parse(Environment.CurrentDirectory + "\\" + RENDERING_SETTINGS); ShowAxisHelper = true; ShowFPS = true; IsFixedTimeStep = true; } /// <summary> /// Allows the game to perform any initialization it needs to before starting to run. /// This is where it can query for any required services and load any non-graphic /// related content. Calling base.Initialize will enumerate through any components /// and initialize them as well. /// </summary> protected override void Initialize() { graphics.PreferredBackBufferWidth = RenderingSettings.WindowWidth; graphics.PreferredBackBufferHeight = RenderingSettings.WindowHeight; graphics.ApplyChanges(); ScreenSize = new Vector2(RenderingSettings.WindowWidth, RenderingSettings.WindowHeight); base.Initialize(); } /// <summary> /// LoadContent will be called once per game and is the place to load /// all of your content. /// </summary> protected override void LoadContent() { // Create a new SpriteBatch, which can be used to draw textures. spriteBatch = new SpriteBatch(GraphicsDevice); Resources.Initialize(Content); GUI.Initialize(spriteBatch); SystemConsole.InitConsole(ConsoleKey); LogRenderSettings(); Camera = new FreeCamera(); world = new World(); worldRenderer = new WorldRenderer(world); axisHelper = new AxisHelper(new Vector2(0, 0), Camera.Projection, Camera.View); // TODO: use this.Content to load your game content here base.LoadContent(); } /// <summary> /// UnloadContent will be called once per game and is the place to unload /// all content. /// </summary> protected override void UnloadContent() { // TODO: Unload any non ContentManager content here } /// <summary> /// Allows the game to run logic such as updating the world, /// checking for collisions, gathering input, and playing audio. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Update(GameTime gameTime) { GameTime = gameTime; float dt = (float)gameTime.ElapsedGameTime.TotalSeconds; InputManager.Update(); SystemConsole.Update(); Camera.Update(dt); world.Update(dt); axisHelper.Update(); base.Update(gameTime); } /// <summary> /// This is called when the game should draw itself. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Draw(GameTime gameTime) { Vector4 color255 = new Vector4(0.31f, 0.43f, 0.7f, 1f) * 255; GraphicsDevice.Clear(new Color(color255/255)); GraphicsDevice.DepthStencilState = DepthStencilState.Default; FPSLogger.Update(); worldRenderer.Render(); if(ShowAxisHelper) axisHelper.Draw(); SystemConsole.Render(); //Also draw our FPS in top right corner if(ShowFPS) GUI.DrawString(Resources.SystemConsoleFont, "FPS: " + FPSLogger.FPS, new Vector2(Main.ScreenSize.X - 70, 10), Color.Green); GUI.DrawString(Resources.SystemConsoleFont, "Chunks rendererd: " + Main.ChunkRenderCount, new Vector2(Main.ScreenSize.X - 250, 30), Color.Black); GUI.DrawString(Resources.SystemConsoleFont, "Triangles rendererd: " + Main.TrianleRenderCount, new Vector2(Main.ScreenSize.X - 250, 50), Color.Black); GUI.DrawString(Resources.SystemConsoleFont, "Vertices rendererd: " + Main.VertexRenderCount, new Vector2(Main.ScreenSize.X - 250, 70), Color.Black); GUI.DrawString(Resources.SystemConsoleFont, "Cam pos: " + Main.Camera.Position / Chunk.CHUNK_SIZE, new Vector2(Main.ScreenSize.X - 400, 120), Color.Black); base.Draw(gameTime); } public static void SetDebugCamSpeed(float m) { Camera.SetMoveSpeed(m); } /// <summary> /// Logs render settings. /// </summary> public static void LogRenderSettings() { SystemConsole.Log(LogType.SettingsInfo, "Resouloution: " + Instance.RenderingSettings.WindowWidth + "x" + Instance.RenderingSettings.WindowHeight); SystemConsole.Log(LogType.SettingsInfo, "UseFrustum: " + Instance.RenderingSettings.UseFrustum); SystemConsole.Log(LogType.SettingsInfo, "UseSmoothLighting: " + Instance.RenderingSettings.UseSmoothLighting); SystemConsole.Log(LogType.SettingsInfo, "UseDynamicShadows: " + Instance.RenderingSettings.UseDynamicShadows); } /// <summary> /// Sets the world rendering mode /// </summary> /// <param name="mode">RenderMode to apply</param> public static void SetRenderMode(RenderMode mode) { Instance.worldRenderer.SetRenderMode(mode); } /// <summary> /// Sets the graphics device rasterizer /// </summary> /// <param name="state">Rasterizer to apply</param> public static void SetRasterizer(RasterizerState state) { Instance.GraphicsDevice.RasterizerState = state; } public static void EnableFog() { Instance.worldRenderer.EnableFog(); } public static void DisableFog() { Instance.worldRenderer.DisableFog(); } public static void EnableAO() { Instance.worldRenderer.EnableAO(); } public static void DisableAO() { Instance.worldRenderer.DisableAO(); } /// <summary> /// Shows cursor /// </summary> public static void ShowCursor() { Instance.IsMouseVisible = true; } /// <summary> /// Hide cursor /// </summary> public static void HideCursor() { Instance.IsMouseVisible = false; } /// <summary> /// Terminate application. /// </summary> public static void Quit() { Instance.Exit(); } } }
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("System.Net.Security")] namespace System.Net.Sockets { using System.Collections; using System.Diagnostics; using System.Globalization; using System.IO; using System.Net; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Threading; using Microsoft.SPOT; using Microsoft.SPOT.Net; using Microsoft.SPOT.Hardware; using NativeSocket = Microsoft.SPOT.Net.SocketNative; public class Socket : IDisposable { /* WARNING!!!! * The m_Handle field MUST be the first field in the Socket class; it is expected by * the SPOT.NET.SocketNative class. */ [FieldNoReflection] internal int m_Handle = -1; private bool m_fBlocking = true; private EndPoint m_localEndPoint = null; // timeout values are stored in uSecs since the Poll method requires it. private int m_recvTimeout = System.Threading.Timeout.Infinite; private int m_sendTimeout = System.Threading.Timeout.Infinite; public Socket(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType) { m_Handle = NativeSocket.socket((int)addressFamily, (int)socketType, (int)protocolType); } private Socket(int handle) { m_Handle = handle; } public int Available { get { if (m_Handle == -1) { throw new ObjectDisposedException(); } uint cBytes = 0; NativeSocket.ioctl(m_Handle, NativeSocket.FIONREAD, ref cBytes); return (int)cBytes; } } private EndPoint GetEndPoint(bool fLocal) { if (m_Handle == -1) { throw new ObjectDisposedException(); } EndPoint ep = null; if (m_localEndPoint == null) { m_localEndPoint = new IPEndPoint(IPAddress.Any, 0); } byte[] address = null; if (fLocal) { NativeSocket.getsockname(m_Handle, out address); } else { NativeSocket.getpeername(m_Handle, out address); } SocketAddress socketAddress = new SocketAddress(address); ep = m_localEndPoint.Create(socketAddress); if (fLocal) { m_localEndPoint = ep; } return ep; } public EndPoint LocalEndPoint { get { return GetEndPoint(true); } } public EndPoint RemoteEndPoint { get { return GetEndPoint(false); } } public int ReceiveTimeout { get { return m_recvTimeout; } set { SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, value); } } public int SendTimeout { get { return m_sendTimeout; } set { SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, value); } } public void Bind(EndPoint localEP) { if (m_Handle == -1) { throw new ObjectDisposedException(); } NativeSocket.bind(m_Handle, localEP.Serialize().m_Buffer); m_localEndPoint = localEP; } public void Connect(EndPoint remoteEP) { if (m_Handle == -1) { throw new ObjectDisposedException(); } NativeSocket.connect(m_Handle, remoteEP.Serialize().m_Buffer, !m_fBlocking); if (m_fBlocking) { Poll(-1, SelectMode.SelectWrite); } } public void Close() { ((IDisposable)this).Dispose(); } public void Listen(int backlog) { if (m_Handle == -1) { throw new ObjectDisposedException(); } NativeSocket.listen(m_Handle, backlog); } public Socket Accept() { if (m_Handle == -1) { throw new ObjectDisposedException(); } int socketHandle; if (m_fBlocking) { Poll(-1, SelectMode.SelectRead); } socketHandle = NativeSocket.accept(m_Handle); Socket socket = new Socket(socketHandle); socket.m_localEndPoint = this.m_localEndPoint; return socket; } public int Send(byte[] buffer, int size, SocketFlags socketFlags) { return Send(buffer, 0, size, socketFlags); } public int Send(byte[] buffer, SocketFlags socketFlags) { return Send(buffer, 0, buffer != null ? buffer.Length : 0, socketFlags); } public int Send(byte[] buffer) { return Send(buffer, 0, buffer != null ? buffer.Length : 0, SocketFlags.None); } public int Send(byte[] buffer, int offset, int size, SocketFlags socketFlags) { if (m_Handle == -1) { throw new ObjectDisposedException(); } return NativeSocket.send(m_Handle, buffer, offset, size, (int)socketFlags, m_sendTimeout); } public int SendTo(byte[] buffer, int offset, int size, SocketFlags socketFlags, EndPoint remoteEP) { if (m_Handle == -1) { throw new ObjectDisposedException(); } byte[] address = remoteEP.Serialize().m_Buffer; return NativeSocket.sendto(m_Handle, buffer, offset, size, (int)socketFlags, m_sendTimeout, address); } public int SendTo(byte[] buffer, int size, SocketFlags socketFlags, EndPoint remoteEP) { return SendTo(buffer, 0, size, socketFlags, remoteEP); } public int SendTo(byte[] buffer, SocketFlags socketFlags, EndPoint remoteEP) { return SendTo(buffer, 0, buffer != null ? buffer.Length : 0, socketFlags, remoteEP); } public int SendTo(byte[] buffer, EndPoint remoteEP) { return SendTo(buffer, 0, buffer != null ? buffer.Length : 0, SocketFlags.None, remoteEP); } public int Receive(byte[] buffer, int size, SocketFlags socketFlags) { return Receive(buffer, 0, size, socketFlags); } public int Receive(byte[] buffer, SocketFlags socketFlags) { return Receive(buffer, 0, buffer != null ? buffer.Length : 0, socketFlags); } public int Receive(byte[] buffer) { return Receive(buffer, 0, buffer != null ? buffer.Length : 0, SocketFlags.None); } public int Receive(byte[] buffer, int offset, int size, SocketFlags socketFlags) { if (m_Handle == -1) { throw new ObjectDisposedException(); } return NativeSocket.recv(m_Handle, buffer, offset, size, (int)socketFlags, m_recvTimeout); } public int ReceiveFrom(byte[] buffer, int offset, int size, SocketFlags socketFlags, ref EndPoint remoteEP) { if (m_Handle == -1) { throw new ObjectDisposedException(); } byte[] address = remoteEP.Serialize().m_Buffer; int len = 0; len = NativeSocket.recvfrom(m_Handle, buffer, offset, size, (int)socketFlags, m_recvTimeout, ref address); SocketAddress socketAddress = new SocketAddress(address); remoteEP = remoteEP.Create(socketAddress); return len; } public int ReceiveFrom(byte[] buffer, int size, SocketFlags socketFlags, ref EndPoint remoteEP) { return ReceiveFrom(buffer, 0, size, socketFlags, ref remoteEP); } public int ReceiveFrom(byte[] buffer, SocketFlags socketFlags, ref EndPoint remoteEP) { return ReceiveFrom(buffer, 0, buffer != null ? buffer.Length : 0, socketFlags, ref remoteEP); } public int ReceiveFrom(byte[] buffer, ref EndPoint remoteEP) { return ReceiveFrom(buffer, 0, buffer != null ? buffer.Length : 0, SocketFlags.None, ref remoteEP); } public void SetSocketOption(SocketOptionLevel optionLevel, SocketOptionName optionName, int optionValue) { if (m_Handle == -1) { throw new ObjectDisposedException(); } //BitConverter.GetBytes(int). Or else deal with endianness here? byte[] val; if(SystemInfo.IsBigEndian) val = new byte[4] { (byte)(optionValue >> 24), (byte)(optionValue >> 16), (byte)(optionValue >> 8), (byte)(optionValue >> 0) }; else val = new byte[4] { (byte)(optionValue >> 0), (byte)(optionValue >> 8), (byte)(optionValue >> 16), (byte)(optionValue >> 24) }; switch (optionName) { case SocketOptionName.SendTimeout: m_sendTimeout = optionValue; break; case SocketOptionName.ReceiveTimeout: m_recvTimeout = optionValue; break; } NativeSocket.setsockopt(m_Handle, (int)optionLevel, (int)optionName, val); } public void SetSocketOption(SocketOptionLevel optionLevel, SocketOptionName optionName, bool optionValue) { SetSocketOption(optionLevel, optionName, (optionValue ? 1 : 0)); } public void SetSocketOption(SocketOptionLevel optionLevel, SocketOptionName optionName, byte[] optionValue) { if (m_Handle == -1) { throw new ObjectDisposedException(); } NativeSocket.setsockopt(m_Handle, (int)optionLevel, (int)optionName, optionValue); } public object GetSocketOption(SocketOptionLevel optionLevel, SocketOptionName optionName) { if (optionName == SocketOptionName.DontLinger || optionName == SocketOptionName.AddMembership || optionName == SocketOptionName.DropMembership) { //special case linger? throw new NotSupportedException(); } byte[] val = new byte[4]; GetSocketOption(optionLevel, optionName, val); //Use BitConverter.ToInt32 //endianness? int iVal; if(SystemInfo.IsBigEndian) iVal = (val[3] << 0 | val[2] << 8 | val[1] << 16 | val[0] << 24); else iVal = (val[0] << 0 | val[1] << 8 | val[2] << 16 | val[3] << 24); return (object)iVal; } public void GetSocketOption(SocketOptionLevel optionLevel, SocketOptionName optionName, byte[] val) { if (m_Handle == -1) { throw new ObjectDisposedException(); } NativeSocket.getsockopt(m_Handle, (int)optionLevel, (int)optionName, val); } public bool Poll(int microSeconds, SelectMode mode) { if (m_Handle == -1) { throw new ObjectDisposedException(); } return NativeSocket.poll(m_Handle, (int)mode, microSeconds); } [MethodImplAttribute(MethodImplOptions.Synchronized)] protected virtual void Dispose(bool disposing) { if (m_Handle != -1) { NativeSocket.close(m_Handle); m_Handle = -1; } } void IDisposable.Dispose() { Dispose(true); GC.SuppressFinalize(this); } ~Socket() { Dispose(false); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * 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 TestZByte() { var test = new BooleanBinaryOpTest__TestZByte(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local works test.RunLclFldScenario(); // Validates passing an instance member works test.RunFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class BooleanBinaryOpTest__TestZByte { private const int VectorSize = 32; private const int Op1ElementCount = VectorSize / sizeof(Byte); private const int Op2ElementCount = VectorSize / sizeof(Byte); private static Byte[] _data1 = new Byte[Op1ElementCount]; private static Byte[] _data2 = new Byte[Op2ElementCount]; private static Vector256<Byte> _clsVar1; private static Vector256<Byte> _clsVar2; private Vector256<Byte> _fld1; private Vector256<Byte> _fld2; private BooleanBinaryOpTest__DataTable<Byte, Byte> _dataTable; static BooleanBinaryOpTest__TestZByte() { var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (byte)(random.Next(0, byte.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Byte>, byte>(ref _clsVar1), ref Unsafe.As<Byte, byte>(ref _data1[0]), VectorSize); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (byte)(random.Next(0, byte.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Byte>, byte>(ref _clsVar2), ref Unsafe.As<Byte, byte>(ref _data2[0]), VectorSize); } public BooleanBinaryOpTest__TestZByte() { Succeeded = true; var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (byte)(random.Next(0, byte.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Byte>, byte>(ref _fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), VectorSize); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (byte)(random.Next(0, byte.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Byte>, byte>(ref _fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), VectorSize); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (byte)(random.Next(0, byte.MaxValue)); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (byte)(random.Next(0, byte.MaxValue)); } _dataTable = new BooleanBinaryOpTest__DataTable<Byte, Byte>(_data1, _data2, VectorSize); } public bool IsSupported => Avx.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { var result = Avx.TestZ( Unsafe.Read<Vector256<Byte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Byte>>(_dataTable.inArray2Ptr) ); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result); } public void RunBasicScenario_Load() { var result = Avx.TestZ( Avx.LoadVector256((Byte*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Byte*)(_dataTable.inArray2Ptr)) ); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result); } public void RunBasicScenario_LoadAligned() { var result = Avx.TestZ( Avx.LoadAlignedVector256((Byte*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((Byte*)(_dataTable.inArray2Ptr)) ); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result); } public void RunReflectionScenario_UnsafeRead() { var method = typeof(Avx).GetMethod(nameof(Avx.TestZ), new Type[] { typeof(Vector256<Byte>), typeof(Vector256<Byte>) }); if (method != null) { var result = method.Invoke(null, new object[] { Unsafe.Read<Vector256<Byte>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Byte>>(_dataTable.inArray2Ptr) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result)); } } public void RunReflectionScenario_Load() { var method = typeof(Avx).GetMethod(nameof(Avx.TestZ), new Type[] { typeof(Vector256<Byte>), typeof(Vector256<Byte>) }); if (method != null) { var result = method.Invoke(null, new object[] { Avx.LoadVector256((Byte*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Byte*)(_dataTable.inArray2Ptr)) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result)); } } public void RunReflectionScenario_LoadAligned() { var method = typeof(Avx).GetMethod(nameof(Avx.TestZ), new Type[] { typeof(Vector256<Byte>), typeof(Vector256<Byte>) }); if (method != null) { var result = method.Invoke(null, new object[] { Avx.LoadAlignedVector256((Byte*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((Byte*)(_dataTable.inArray2Ptr)) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result)); } } public void RunClsVarScenario() { var result = Avx.TestZ( _clsVar1, _clsVar2 ); ValidateResult(_clsVar1, _clsVar2, result); } public void RunLclVarScenario_UnsafeRead() { var left = Unsafe.Read<Vector256<Byte>>(_dataTable.inArray1Ptr); var right = Unsafe.Read<Vector256<Byte>>(_dataTable.inArray2Ptr); var result = Avx.TestZ(left, right); ValidateResult(left, right, result); } public void RunLclVarScenario_Load() { var left = Avx.LoadVector256((Byte*)(_dataTable.inArray1Ptr)); var right = Avx.LoadVector256((Byte*)(_dataTable.inArray2Ptr)); var result = Avx.TestZ(left, right); ValidateResult(left, right, result); } public void RunLclVarScenario_LoadAligned() { var left = Avx.LoadAlignedVector256((Byte*)(_dataTable.inArray1Ptr)); var right = Avx.LoadAlignedVector256((Byte*)(_dataTable.inArray2Ptr)); var result = Avx.TestZ(left, right); ValidateResult(left, right, result); } public void RunLclFldScenario() { var test = new BooleanBinaryOpTest__TestZByte(); var result = Avx.TestZ(test._fld1, test._fld2); ValidateResult(test._fld1, test._fld2, result); } public void RunFldScenario() { var result = Avx.TestZ(_fld1, _fld2); ValidateResult(_fld1, _fld2, result); } public void RunUnsupportedScenario() { Succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector256<Byte> left, Vector256<Byte> right, bool result, [CallerMemberName] string method = "") { Byte[] inArray1 = new Byte[Op1ElementCount]; Byte[] inArray2 = new Byte[Op2ElementCount]; Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left); Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right); ValidateResult(inArray1, inArray2, result, method); } private void ValidateResult(void* left, void* right, bool result, [CallerMemberName] string method = "") { Byte[] inArray1 = new Byte[Op1ElementCount]; Byte[] inArray2 = new Byte[Op2ElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize); ValidateResult(inArray1, inArray2, result, method); } private void ValidateResult(Byte[] left, Byte[] right, bool result, [CallerMemberName] string method = "") { var expectedResult = true; for (var i = 0; i < Op1ElementCount; i++) { expectedResult &= ((left[i] & right[i]) == 0); } if (expectedResult != result) { Succeeded = false; Console.WriteLine($"{nameof(Avx)}.{nameof(Avx.TestZ)}<Byte>(Vector256<Byte>, Vector256<Byte>): {method} failed:"); Console.WriteLine($" left: ({string.Join(", ", left)})"); Console.WriteLine($" right: ({string.Join(", ", right)})"); Console.WriteLine($" result: ({string.Join(", ", result)})"); Console.WriteLine(); } } } }
using System; using System.Data; using Csla; using Csla.Data; using SelfLoad.DataAccess; using SelfLoad.DataAccess.ERCLevel; namespace SelfLoad.Business.ERCLevel { /// <summary> /// D08_Region (editable child object).<br/> /// This is a generated base class of <see cref="D08_Region"/> business object. /// </summary> /// <remarks> /// This class contains one child collection:<br/> /// - <see cref="D09_CityObjects"/> of type <see cref="D09_CityColl"/> (1:M relation to <see cref="D10_City"/>)<br/> /// This class is an item of <see cref="D07_RegionColl"/> collection. /// </remarks> [Serializable] public partial class D08_Region : BusinessBase<D08_Region> { #region Static Fields private static int _lastID; #endregion #region Business Properties /// <summary> /// Maintains metadata about <see cref="Region_ID"/> property. /// </summary> public static readonly PropertyInfo<int> Region_IDProperty = RegisterProperty<int>(p => p.Region_ID, "Regions ID"); /// <summary> /// Gets the Regions ID. /// </summary> /// <value>The Regions ID.</value> public int Region_ID { get { return GetProperty(Region_IDProperty); } } /// <summary> /// Maintains metadata about <see cref="Region_Name"/> property. /// </summary> public static readonly PropertyInfo<string> Region_NameProperty = RegisterProperty<string>(p => p.Region_Name, "Regions Name"); /// <summary> /// Gets or sets the Regions Name. /// </summary> /// <value>The Regions Name.</value> public string Region_Name { get { return GetProperty(Region_NameProperty); } set { SetProperty(Region_NameProperty, value); } } /// <summary> /// Maintains metadata about child <see cref="D09_Region_SingleObject"/> property. /// </summary> public static readonly PropertyInfo<D09_Region_Child> D09_Region_SingleObjectProperty = RegisterProperty<D09_Region_Child>(p => p.D09_Region_SingleObject, "D09 Region Single Object", RelationshipTypes.Child); /// <summary> /// Gets the D09 Region Single Object ("self load" child property). /// </summary> /// <value>The D09 Region Single Object.</value> public D09_Region_Child D09_Region_SingleObject { get { return GetProperty(D09_Region_SingleObjectProperty); } private set { LoadProperty(D09_Region_SingleObjectProperty, value); } } /// <summary> /// Maintains metadata about child <see cref="D09_Region_ASingleObject"/> property. /// </summary> public static readonly PropertyInfo<D09_Region_ReChild> D09_Region_ASingleObjectProperty = RegisterProperty<D09_Region_ReChild>(p => p.D09_Region_ASingleObject, "D09 Region ASingle Object", RelationshipTypes.Child); /// <summary> /// Gets the D09 Region ASingle Object ("self load" child property). /// </summary> /// <value>The D09 Region ASingle Object.</value> public D09_Region_ReChild D09_Region_ASingleObject { get { return GetProperty(D09_Region_ASingleObjectProperty); } private set { LoadProperty(D09_Region_ASingleObjectProperty, value); } } /// <summary> /// Maintains metadata about child <see cref="D09_CityObjects"/> property. /// </summary> public static readonly PropertyInfo<D09_CityColl> D09_CityObjectsProperty = RegisterProperty<D09_CityColl>(p => p.D09_CityObjects, "D09 City Objects", RelationshipTypes.Child); /// <summary> /// Gets the D09 City Objects ("self load" child property). /// </summary> /// <value>The D09 City Objects.</value> public D09_CityColl D09_CityObjects { get { return GetProperty(D09_CityObjectsProperty); } private set { LoadProperty(D09_CityObjectsProperty, value); } } #endregion #region Factory Methods /// <summary> /// Factory method. Creates a new <see cref="D08_Region"/> object. /// </summary> /// <returns>A reference to the created <see cref="D08_Region"/> object.</returns> internal static D08_Region NewD08_Region() { return DataPortal.CreateChild<D08_Region>(); } /// <summary> /// Factory method. Loads a <see cref="D08_Region"/> object from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> /// <returns>A reference to the fetched <see cref="D08_Region"/> object.</returns> internal static D08_Region GetD08_Region(SafeDataReader dr) { D08_Region obj = new D08_Region(); // show the framework that this is a child object obj.MarkAsChild(); obj.Fetch(dr); obj.MarkOld(); return obj; } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="D08_Region"/> class. /// </summary> /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public D08_Region() { // Use factory methods and do not use direct creation. // show the framework that this is a child object MarkAsChild(); } #endregion #region Data Access /// <summary> /// Loads default values for the <see cref="D08_Region"/> object properties. /// </summary> [Csla.RunLocal] protected override void Child_Create() { LoadProperty(Region_IDProperty, System.Threading.Interlocked.Decrement(ref _lastID)); LoadProperty(D09_Region_SingleObjectProperty, DataPortal.CreateChild<D09_Region_Child>()); LoadProperty(D09_Region_ASingleObjectProperty, DataPortal.CreateChild<D09_Region_ReChild>()); LoadProperty(D09_CityObjectsProperty, DataPortal.CreateChild<D09_CityColl>()); var args = new DataPortalHookArgs(); OnCreate(args); base.Child_Create(); } /// <summary> /// Loads a <see cref="D08_Region"/> object from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> private void Fetch(SafeDataReader dr) { // Value properties LoadProperty(Region_IDProperty, dr.GetInt32("Region_ID")); LoadProperty(Region_NameProperty, dr.GetString("Region_Name")); var args = new DataPortalHookArgs(dr); OnFetchRead(args); } /// <summary> /// Loads child objects. /// </summary> internal void FetchChildren() { LoadProperty(D09_Region_SingleObjectProperty, D09_Region_Child.GetD09_Region_Child(Region_ID)); LoadProperty(D09_Region_ASingleObjectProperty, D09_Region_ReChild.GetD09_Region_ReChild(Region_ID)); LoadProperty(D09_CityObjectsProperty, D09_CityColl.GetD09_CityColl(Region_ID)); } /// <summary> /// Inserts a new <see cref="D08_Region"/> object in the database. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Insert(D06_Country parent) { using (var dalManager = DalFactorySelfLoad.GetManager()) { var args = new DataPortalHookArgs(); OnInsertPre(args); var dal = dalManager.GetProvider<ID08_RegionDal>(); using (BypassPropertyChecks) { int region_ID = -1; dal.Insert( parent.Country_ID, out region_ID, Region_Name ); LoadProperty(Region_IDProperty, region_ID); } OnInsertPost(args); // flushes all pending data operations FieldManager.UpdateChildren(this); } } /// <summary> /// Updates in the database all changes made to the <see cref="D08_Region"/> object. /// </summary> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Update() { if (!IsDirty) return; using (var dalManager = DalFactorySelfLoad.GetManager()) { var args = new DataPortalHookArgs(); OnUpdatePre(args); var dal = dalManager.GetProvider<ID08_RegionDal>(); using (BypassPropertyChecks) { dal.Update( Region_ID, Region_Name ); } OnUpdatePost(args); // flushes all pending data operations FieldManager.UpdateChildren(this); } } /// <summary> /// Self deletes the <see cref="D08_Region"/> object from database. /// </summary> [Transactional(TransactionalTypes.TransactionScope)] private void Child_DeleteSelf() { using (var dalManager = DalFactorySelfLoad.GetManager()) { var args = new DataPortalHookArgs(); // flushes all pending data operations FieldManager.UpdateChildren(this); OnDeletePre(args); var dal = dalManager.GetProvider<ID08_RegionDal>(); using (BypassPropertyChecks) { dal.Delete(ReadProperty(Region_IDProperty)); } OnDeletePost(args); } } #endregion #region DataPortal Hooks /// <summary> /// Occurs after setting all defaults for object creation. /// </summary> partial void OnCreate(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation. /// </summary> partial void OnDeletePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after the delete operation, before Commit(). /// </summary> partial void OnDeletePost(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the fetch operation. /// </summary> partial void OnFetchPre(DataPortalHookArgs args); /// <summary> /// Occurs after the fetch operation (object or collection is fully loaded and set up). /// </summary> partial void OnFetchPost(DataPortalHookArgs args); /// <summary> /// Occurs after the low level fetch operation, before the data reader is destroyed. /// </summary> partial void OnFetchRead(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the update operation. /// </summary> partial void OnUpdatePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit(). /// </summary> partial void OnUpdatePost(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation. /// </summary> partial void OnInsertPre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit(). /// </summary> partial void OnInsertPost(DataPortalHookArgs args); #endregion } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // File System.Web.UI.WebControls.ListControl.cs // Automatically generated contract file. using System.Collections.Generic; using System.IO; using System.Text; using System.Diagnostics.Contracts; using System; // Disable the "this variable is not used" warning as every field would imply it. #pragma warning disable 0414 // Disable the "this variable is never assigned to". #pragma warning disable 0067 // Disable the "this event is never assigned to". #pragma warning disable 0649 // Disable the "this variable is never used". #pragma warning disable 0169 // Disable the "new keyword not required" warning. #pragma warning disable 0109 // Disable the "extern without DllImport" warning. #pragma warning disable 0626 // Disable the "could hide other member" warning, can happen on certain properties. #pragma warning disable 0108 namespace System.Web.UI.WebControls { abstract public partial class ListControl : DataBoundControl, System.Web.UI.IEditableTextControl, System.Web.UI.ITextControl { #region Methods and constructors protected override void AddAttributesToRender(System.Web.UI.HtmlTextWriter writer) { } public virtual new void ClearSelection() { } public ListControl() { } protected override void LoadViewState(Object savedState) { } protected override void OnDataBinding(EventArgs e) { } protected internal override void OnPreRender(EventArgs e) { } protected virtual new void OnSelectedIndexChanged(EventArgs e) { } protected virtual new void OnTextChanged(EventArgs e) { } protected internal override void PerformDataBinding(System.Collections.IEnumerable dataSource) { } protected override void PerformSelect() { } protected internal override void RenderContents(System.Web.UI.HtmlTextWriter writer) { } protected override Object SaveViewState() { return default(Object); } protected void SetPostDataSelection(int selectedIndex) { } protected override void TrackViewState() { } protected internal virtual new void VerifyMultiSelect() { } #endregion #region Properties and indexers public virtual new bool AppendDataBoundItems { get { return default(bool); } set { } } public virtual new bool AutoPostBack { get { return default(bool); } set { } } public virtual new bool CausesValidation { get { return default(bool); } set { } } public virtual new string DataTextField { get { return default(string); } set { } } public virtual new string DataTextFormatString { get { return default(string); } set { } } public virtual new string DataValueField { get { return default(string); } set { } } public virtual new ListItemCollection Items { get { return default(ListItemCollection); } } public virtual new int SelectedIndex { get { return default(int); } set { } } public virtual new ListItem SelectedItem { get { return default(ListItem); } } public virtual new string SelectedValue { get { return default(string); } set { } } protected override System.Web.UI.HtmlTextWriterTag TagKey { get { return default(System.Web.UI.HtmlTextWriterTag); } } public virtual new string Text { get { return default(string); } set { } } public virtual new string ValidationGroup { get { return default(string); } set { } } #endregion #region Events public event EventHandler SelectedIndexChanged { add { } remove { } } public event EventHandler TextChanged { add { } remove { } } #endregion } }
namespace Microsoft.Azure.Management.Scheduler { using System; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; /// <summary> /// Extension methods for JobCollectionsOperations. /// </summary> public static partial class JobCollectionsOperationsExtensions { /// <summary> /// Gets all job collections under specified subscription. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static IPage<JobCollectionDefinition> ListBySubscription(this IJobCollectionsOperations operations) { return Task.Factory.StartNew(s => ((IJobCollectionsOperations)s).ListBySubscriptionAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets all job collections under specified subscription. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<JobCollectionDefinition>> ListBySubscriptionAsync(this IJobCollectionsOperations operations, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListBySubscriptionWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets all job collections under specified resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The resource group name. /// </param> public static IPage<JobCollectionDefinition> ListByResourceGroup(this IJobCollectionsOperations operations, string resourceGroupName) { return Task.Factory.StartNew(s => ((IJobCollectionsOperations)s).ListByResourceGroupAsync(resourceGroupName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets all job collections under specified resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<JobCollectionDefinition>> ListByResourceGroupAsync(this IJobCollectionsOperations operations, string resourceGroupName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListByResourceGroupWithHttpMessagesAsync(resourceGroupName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets a job collection. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='jobCollectionName'> /// The job collection name. /// </param> public static JobCollectionDefinition Get(this IJobCollectionsOperations operations, string resourceGroupName, string jobCollectionName) { return Task.Factory.StartNew(s => ((IJobCollectionsOperations)s).GetAsync(resourceGroupName, jobCollectionName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets a job collection. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='jobCollectionName'> /// The job collection name. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<JobCollectionDefinition> GetAsync(this IJobCollectionsOperations operations, string resourceGroupName, string jobCollectionName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, jobCollectionName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Provisions a new job collection or updates an existing job collection. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='jobCollectionName'> /// The job collection name. /// </param> /// <param name='jobCollection'> /// The job collection definition. /// </param> public static JobCollectionDefinition CreateOrUpdate(this IJobCollectionsOperations operations, string resourceGroupName, string jobCollectionName, JobCollectionDefinition jobCollection) { return Task.Factory.StartNew(s => ((IJobCollectionsOperations)s).CreateOrUpdateAsync(resourceGroupName, jobCollectionName, jobCollection), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Provisions a new job collection or updates an existing job collection. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='jobCollectionName'> /// The job collection name. /// </param> /// <param name='jobCollection'> /// The job collection definition. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<JobCollectionDefinition> CreateOrUpdateAsync(this IJobCollectionsOperations operations, string resourceGroupName, string jobCollectionName, JobCollectionDefinition jobCollection, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, jobCollectionName, jobCollection, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Patches an existing job collection. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='jobCollectionName'> /// The job collection name. /// </param> /// <param name='jobCollection'> /// The job collection definition. /// </param> public static JobCollectionDefinition Patch(this IJobCollectionsOperations operations, string resourceGroupName, string jobCollectionName, JobCollectionDefinition jobCollection) { return Task.Factory.StartNew(s => ((IJobCollectionsOperations)s).PatchAsync(resourceGroupName, jobCollectionName, jobCollection), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Patches an existing job collection. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='jobCollectionName'> /// The job collection name. /// </param> /// <param name='jobCollection'> /// The job collection definition. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<JobCollectionDefinition> PatchAsync(this IJobCollectionsOperations operations, string resourceGroupName, string jobCollectionName, JobCollectionDefinition jobCollection, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.PatchWithHttpMessagesAsync(resourceGroupName, jobCollectionName, jobCollection, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Deletes a job collection. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='jobCollectionName'> /// The job collection name. /// </param> public static void Delete(this IJobCollectionsOperations operations, string resourceGroupName, string jobCollectionName) { Task.Factory.StartNew(s => ((IJobCollectionsOperations)s).DeleteAsync(resourceGroupName, jobCollectionName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Deletes a job collection. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='jobCollectionName'> /// The job collection name. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task DeleteAsync(this IJobCollectionsOperations operations, string resourceGroupName, string jobCollectionName, CancellationToken cancellationToken = default(CancellationToken)) { await operations.DeleteWithHttpMessagesAsync(resourceGroupName, jobCollectionName, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Deletes a job collection. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='jobCollectionName'> /// The job collection name. /// </param> public static void BeginDelete(this IJobCollectionsOperations operations, string resourceGroupName, string jobCollectionName) { Task.Factory.StartNew(s => ((IJobCollectionsOperations)s).BeginDeleteAsync(resourceGroupName, jobCollectionName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Deletes a job collection. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='jobCollectionName'> /// The job collection name. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task BeginDeleteAsync(this IJobCollectionsOperations operations, string resourceGroupName, string jobCollectionName, CancellationToken cancellationToken = default(CancellationToken)) { await operations.BeginDeleteWithHttpMessagesAsync(resourceGroupName, jobCollectionName, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Enables all of the jobs in the job collection. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='jobCollectionName'> /// The job collection name. /// </param> public static void Enable(this IJobCollectionsOperations operations, string resourceGroupName, string jobCollectionName) { Task.Factory.StartNew(s => ((IJobCollectionsOperations)s).EnableAsync(resourceGroupName, jobCollectionName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Enables all of the jobs in the job collection. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='jobCollectionName'> /// The job collection name. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task EnableAsync(this IJobCollectionsOperations operations, string resourceGroupName, string jobCollectionName, CancellationToken cancellationToken = default(CancellationToken)) { await operations.EnableWithHttpMessagesAsync(resourceGroupName, jobCollectionName, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Enables all of the jobs in the job collection. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='jobCollectionName'> /// The job collection name. /// </param> public static void BeginEnable(this IJobCollectionsOperations operations, string resourceGroupName, string jobCollectionName) { Task.Factory.StartNew(s => ((IJobCollectionsOperations)s).BeginEnableAsync(resourceGroupName, jobCollectionName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Enables all of the jobs in the job collection. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='jobCollectionName'> /// The job collection name. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task BeginEnableAsync(this IJobCollectionsOperations operations, string resourceGroupName, string jobCollectionName, CancellationToken cancellationToken = default(CancellationToken)) { await operations.BeginEnableWithHttpMessagesAsync(resourceGroupName, jobCollectionName, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Disables all of the jobs in the job collection. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='jobCollectionName'> /// The job collection name. /// </param> public static void Disable(this IJobCollectionsOperations operations, string resourceGroupName, string jobCollectionName) { Task.Factory.StartNew(s => ((IJobCollectionsOperations)s).DisableAsync(resourceGroupName, jobCollectionName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Disables all of the jobs in the job collection. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='jobCollectionName'> /// The job collection name. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task DisableAsync(this IJobCollectionsOperations operations, string resourceGroupName, string jobCollectionName, CancellationToken cancellationToken = default(CancellationToken)) { await operations.DisableWithHttpMessagesAsync(resourceGroupName, jobCollectionName, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Disables all of the jobs in the job collection. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='jobCollectionName'> /// The job collection name. /// </param> public static void BeginDisable(this IJobCollectionsOperations operations, string resourceGroupName, string jobCollectionName) { Task.Factory.StartNew(s => ((IJobCollectionsOperations)s).BeginDisableAsync(resourceGroupName, jobCollectionName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Disables all of the jobs in the job collection. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='jobCollectionName'> /// The job collection name. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task BeginDisableAsync(this IJobCollectionsOperations operations, string resourceGroupName, string jobCollectionName, CancellationToken cancellationToken = default(CancellationToken)) { await operations.BeginDisableWithHttpMessagesAsync(resourceGroupName, jobCollectionName, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets all job collections under specified subscription. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> public static IPage<JobCollectionDefinition> ListBySubscriptionNext(this IJobCollectionsOperations operations, string nextPageLink) { return Task.Factory.StartNew(s => ((IJobCollectionsOperations)s).ListBySubscriptionNextAsync(nextPageLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets all job collections under specified subscription. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<JobCollectionDefinition>> ListBySubscriptionNextAsync(this IJobCollectionsOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListBySubscriptionNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets all job collections under specified resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> public static IPage<JobCollectionDefinition> ListByResourceGroupNext(this IJobCollectionsOperations operations, string nextPageLink) { return Task.Factory.StartNew(s => ((IJobCollectionsOperations)s).ListByResourceGroupNextAsync(nextPageLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets all job collections under specified resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<JobCollectionDefinition>> ListByResourceGroupNextAsync(this IJobCollectionsOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListByResourceGroupNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } }
/* * * (c) Copyright Ascensio System Limited 2010-2021 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Collections.Generic; using System.Linq; using ASC.Api.Attributes; using ASC.Api.Wiki.Wrappers; using ASC.Core; using ASC.Core.Tenants; using ASC.Web.Community.Product; using ASC.Web.Community.Wiki.Common; using ASC.Web.Core.Users; using ASC.Web.Studio.UserControls.Common.Comments; using ASC.Web.Studio.Utility; using ASC.Web.Studio.Utility.HtmlUtility; using ASC.Web.UserControls.Wiki; using ASC.Web.UserControls.Wiki.Data; using File = ASC.Web.UserControls.Wiki.Data.File; namespace ASC.Api.Community { public partial class CommunityApi { private readonly WikiEngine _engine = new WikiEngine(); /// <summary> /// Creates a new wiki page with the page name and content specified in the request /// </summary> /// <short>Create page</short> /// <param name="name">Page name</param> /// <param name="body">Page content</param> /// <returns>page info</returns> /// <category>Wiki</category> [Create("wiki")] public PageWrapper CreatePage(string name, string body) { return new PageWrapper(_engine.CreatePage(new Page { PageName = name, Body = body })); } /// <summary> /// Returns the list of all pages in wiki or pages in wiki category specified in the request /// </summary> /// <short>Pages</short> /// <section>Pages</section> /// <param name="category">Category name</param> /// <returns></returns> /// <category>Wiki</category> [Read("wiki")] public IEnumerable<PageWrapper> GetPages(string category) { return category == null ? _engine.GetPages().ConvertAll(x => new PageWrapper(x)) : _engine.GetPages(category).ConvertAll(x => new PageWrapper(x)); } /// <summary> /// Return the detailed information about the wiki page with the name and version specified in the request /// </summary> /// <short>Page</short> /// <section>Pages</section> /// <param name="name">Page name</param> /// <param name="version">Page version</param> /// <returns>Page info</returns> /// <category>Wiki</category> [Read("wiki/{name}")] public PageWrapper GetPage(string name, int? version) { if (string.IsNullOrEmpty(name)) throw new ArgumentException(); var page = version != null ? _engine.GetPage(name, (int)version) : _engine.GetPage(name); if (page == null) throw new Exception("wiki page not found"); return new PageWrapper(page); } /// <summary> /// Returns the list of history changes for the wiki page with the name specified in the request /// </summary> /// <short>History</short> /// <section>Pages</section> /// <param name="page">Page name</param> /// <returns>List of pages</returns> /// <category>Wiki</category> [Read("wiki/{page}/story")] public IEnumerable<PageWrapper> GetHistory(string page) { return _engine.GetPageHistory(page).ConvertAll(x => new PageWrapper(x)); } /// <summary> /// Returns the list of wiki pages with the name matching the search query specified in the request /// </summary> /// <short>Search</short> /// <section>Pages</section> /// <param name="name">Part of the page name</param> /// <returns>List of pages</returns> /// <category>Wiki</category> [Read("wiki/search/byname/{name}")] public IEnumerable<PageWrapper> SearchPages(string name) { return _engine.SearchPagesByName(name).ConvertAll(x => new PageWrapper(x)); } /// <summary> /// Returns the list of wiki pages with the content matching the search query specified in the request /// </summary> /// <short>Search</short> /// <section>Pages</section> /// <param name="content">Part of the page content</param> /// <returns>List of pages</returns> /// <category>Wiki</category> [Read("wiki/search/bycontent/{content}")] public IEnumerable<PageWrapper> SearchPagesByContent(string content) { return _engine.SearchPagesByContent(content).ConvertAll(x => new PageWrapper(x)); } /// <summary> /// Updates the wiki page with the name and content specified in the request /// </summary> /// <short>Update page</short> /// <section>Pages</section> /// <param name="name">Page name</param> /// <param name="body">Page content</param> /// <returns>Page info</returns> /// <category>Wiki</category> [Update("wiki/{name}")] public PageWrapper UpdatePage(string name, string body) { return new PageWrapper(_engine.UpdatePage(new Page { PageName = name, Body = body })); } /// <summary> /// Deletes the wiki page with the name specified in the request /// </summary> /// <short>Delete page</short> /// <section>Pages</section> /// <param name="name">Page name</param> /// <category>Wiki</category> [Delete("wiki/{name}")] public void DeletePage(string name) { _engine.RemovePage(name); } /// <summary> /// Creates the comment to the selected wiki page with the content specified in the request /// </summary> /// <short>Create comment</short> /// <section>Comments</section> /// <param name="page">Page name</param> /// <param name="content">Comment content</param> /// <param name="parentId">Comment parent id</param> /// <returns>Comment info</returns> /// <category>Wiki</category> [Create("wiki/{page}/comment")] public CommentWrapper CreateComment(string page, string content, string parentId) { var parentIdGuid = String.IsNullOrEmpty(parentId) ? Guid.Empty : new Guid(parentId); return new CommentWrapper(_engine.CreateComment(new Comment { PageName = page, Body = content, ParentId = parentIdGuid })); } /// <summary> /// Returns the list of all comments to the wiki page with the name specified in the request /// </summary> /// <short>All comments</short> /// <section>Comments</section> /// <param name="page">Page name</param> /// <returns>List of comments</returns> /// <category>Wiki</category> [Read("wiki/{page}/comment")] public List<CommentWrapper> GetComments(string page) { return _engine.GetComments(page).ConvertAll(x => new CommentWrapper(x)); } /// <summary> /// Uploads the selected files to the wiki 'Files' section /// </summary> /// <short>Upload files</short> /// <param name="files">List of files to upload</param> /// <returns>List of files</returns> /// <category>Wiki</category> [Create("wiki/file")] public IEnumerable<FileWrapper> UploadFiles(IEnumerable<System.Web.HttpPostedFileBase> files) { if (files == null || !files.Any()) throw new ArgumentNullException("files"); return files.Select(file => new FileWrapper(_engine.CreateOrUpdateFile(new File { FileName = file.FileName, FileSize = file.ContentLength, UploadFileName = file.FileName }, file.InputStream))); } /// <summary> /// Returns the detailed file info about the file with the specified name in the wiki 'Files' section /// </summary> /// <short>File</short> /// <section>Files</section> /// <param name="name">File name</param> /// <returns>File info</returns> /// <category>Wiki</category> [Read("wiki/file/{name}")] public FileWrapper GetFile(string name) { return new FileWrapper(_engine.GetFile(name)); } /// <summary> /// Deletes the files with the specified name from the wiki 'Files' section /// </summary> /// <short>Delete file</short> /// <param name="name">File name</param> /// <category>Wiki</category> [Delete("wiki/file/{name}")] public void DeleteFile(string name) { _engine.RemoveFile(name); } /// <summary> /// Get comment preview with the content specified in the request /// </summary> /// <short>Get comment preview</short> /// <section>Comments</section> /// <param name="commentid">Comment ID</param> /// <param name="htmltext">Comment content</param> /// <returns>Comment info</returns> /// <category>Wiki</category> [Create("wiki/comment/preview")] public CommentInfo GetWikiCommentPreview(string commentid, string htmltext) { var comment = !string.IsNullOrEmpty(commentid) ? _engine.GetComment(new Guid(commentid)) : new Comment(); comment.Date = TenantUtil.DateTimeNow(); comment.UserId = SecurityContext.CurrentAccount.ID; comment.Body = htmltext; var info = GetCommentInfo(comment); info.IsEditPermissions = false; info.IsResponsePermissions = false; return info; } /// <summary> ///Remove comment with the id specified in the request /// </summary> /// <short>Remove comment</short> /// <section>Comments</section> /// <param name="commentid">Comment ID</param> /// <returns>Comment info</returns> /// <category>Wiki</category> [Delete("wiki/comment/{commentid}")] public string RemoveWikiComment(string commentid) { _engine.DeleteComment(new Guid(commentid)); return commentid; } /// <category>Wiki</category> [Create("wiki/comment")] public CommentInfo AddWikiComment(string parentcommentid, string entityid, string content) { CommunitySecurity.DemandPermissions(ASC.Web.Community.Wiki.Common.Constants.Action_AddComment); var parentIdGuid = String.IsNullOrEmpty(parentcommentid) ? Guid.Empty : new Guid(parentcommentid); var newComment = _engine.CreateComment(new Comment { Body = content, PageName = entityid, ParentId = parentIdGuid }); return GetCommentInfo(newComment); } /// <summary> /// Updates the comment to the selected wiki page with the comment content specified in the request /// </summary> /// <short>Update comment</short> /// <section>Comments</section> /// <param name="commentid">Comment ID</param> /// <param name="content">Comment content</param> /// <returns></returns> /// <category>Wiki</category> [Update("wiki/comment/{commentid}")] public string UpdateWikiComment(string commentid, string content) { if (string.IsNullOrEmpty(content)) throw new ArgumentException(); _engine.UpdateComment(new Comment { Id = new Guid(commentid), Body = content }); return HtmlUtility.GetFull(content); } private static CommentInfo GetCommentInfo(Comment comment) { var info = new CommentInfo { CommentID = comment.Id.ToString(), UserID = comment.UserId, TimeStamp = comment.Date, TimeStampStr = comment.Date.Ago(), IsRead = true, Inactive = comment.Inactive, CommentBody = HtmlUtility.GetFull(comment.Body), UserFullName = DisplayUserSettings.GetFullUserName(comment.UserId), UserProfileLink = CommonLinkUtility.GetUserProfile(comment.UserId), UserAvatarPath = UserPhotoManager.GetBigPhotoURL(comment.UserId), IsEditPermissions = CommunitySecurity.CheckPermissions(new WikiObjectsSecurityObject(comment), ASC.Web.Community.Wiki.Common.Constants.Action_EditRemoveComment), IsResponsePermissions = CommunitySecurity.CheckPermissions(ASC.Web.Community.Wiki.Common.Constants.Action_AddComment), UserPost = CoreContext.UserManager.GetUsers(comment.UserId).Title }; return info; } } }
// 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; using Xunit.Abstractions; using System.IO; using System.Xml.XPath; using System.Xml.Xsl; using XmlCoreTest.Common; namespace System.Xml.Tests { public class SameInstanceXslTransformTestCase : XsltApiTestCaseBase2 { // Variables from init string protected string _strPath; // Path of the data files // Other global variables public XslCompiledTransform xsltSameInstance; // Used for same instance testing of XsltArgumentList private ITestOutputHelper _output; public SameInstanceXslTransformTestCase(ITestOutputHelper output) : base(output) { _output = output; Init(null); } public new void Init(object objParam) { xsltSameInstance = new XslCompiledTransform(); _strPath = Path.Combine("TestFiles", FilePathUtil.GetTestDataPath(), "XsltApiV2"); return; } } //[TestCase(Name = "Same instance testing: Transform() - READER")] public class SameInstanceXslTransformReader : SameInstanceXslTransformTestCase { private XPathDocument _xd; // Loads XML file private XmlReader _xrData; // Loads XML File private ITestOutputHelper _output; public SameInstanceXslTransformReader(ITestOutputHelper output) : base(output) { _output = output; } private void Load(string _strXslFile, string _strXmlFile) { _xrData = XmlReader.Create(Path.Combine(_strPath, _strXmlFile)); _xd = new XPathDocument(_xrData, XmlSpace.Preserve); _xrData.Dispose(); XmlReaderSettings xrs = new XmlReaderSettings(); #pragma warning disable 0618 xrs.ProhibitDtd = false; #pragma warning restore 0618 XmlReader xrTemp = XmlReader.Create(Path.Combine(_strPath, _strXslFile), xrs); xsltSameInstance.Load(xrTemp); } //////////////////////////////////////////////////////////////// // Same instance testing: // Multiple Transform() over same XslCompiledTransform object //////////////////////////////////////////////////////////////// public int Transform(object args) { for (int i = 1; i <= 100; i++) { StringWriter sw = new StringWriter(); xsltSameInstance.Transform(_xrData, null, sw); _output.WriteLine("Transform: Thread " + args + "\tIteration " + i + "\tDone with READER transform..."); } return 1; } //[Variation("Multiple Transform(): Reader - Basic Test")] [InlineData()] [Theory] public void proc1() { Load("xslt_multithreading_test.xsl", "foo.xml"); CThreads rThreads = new CThreads(_output); rThreads.Add(new ThreadFunc(Transform), "1"); rThreads.Add(new ThreadFunc(Transform), "2"); rThreads.Add(new ThreadFunc(Transform), "3"); rThreads.Add(new ThreadFunc(Transform), "4"); rThreads.Add(new ThreadFunc(Transform), "5"); //Wait until they are complete rThreads.Start(); rThreads.Wait(); return; } //[Variation("Multiple Transform(): Reader - QFE 505 Repro")] [InlineData()] [Theory] public void proc2() { AppContext.SetSwitch("Switch.System.Xml.AllowDefaultResolver", true); Load("QFE505_multith_customer_repro_with_or_expr.xsl", "QFE505_multith_customer_repro_with_or_expr.xml"); CThreads rThreads = new CThreads(_output); rThreads.Add(new ThreadFunc(Transform), "1"); rThreads.Add(new ThreadFunc(Transform), "2"); rThreads.Add(new ThreadFunc(Transform), "3"); rThreads.Add(new ThreadFunc(Transform), "4"); rThreads.Add(new ThreadFunc(Transform), "5"); //Wait until they are complete rThreads.Start(); rThreads.Wait(); return; } //[Variation("Multiple Transform(): Reader - AVTs")] [InlineData()] [Theory] public void proc3() { Load("xslt_multith_AVTs.xsl", "xslt_multith_AVTs.xml"); CThreads rThreads = new CThreads(_output); rThreads.Add(new ThreadFunc(Transform), "1"); rThreads.Add(new ThreadFunc(Transform), "2"); rThreads.Add(new ThreadFunc(Transform), "3"); rThreads.Add(new ThreadFunc(Transform), "4"); rThreads.Add(new ThreadFunc(Transform), "5"); //Wait until they are complete rThreads.Start(); rThreads.Wait(); return; } //[Variation("Multiple Transform(): Reader - xsl:key")] [InlineData()] [Theory] public void proc4() { Load("xslt_multith_keytest.xsl", "xslt_multith_keytest.xml"); CThreads rThreads = new CThreads(_output); rThreads.Add(new ThreadFunc(Transform), "1"); rThreads.Add(new ThreadFunc(Transform), "2"); rThreads.Add(new ThreadFunc(Transform), "3"); rThreads.Add(new ThreadFunc(Transform), "4"); rThreads.Add(new ThreadFunc(Transform), "5"); //Wait until they are complete rThreads.Start(); rThreads.Wait(); return; } //[Variation("Multiple Transform(): Reader - xsl:sort")] [InlineData()] [Theory] public void proc5() { Load("xslt_multith_sorting.xsl", "xslt_multith_sorting.xml"); CThreads rThreads = new CThreads(_output); rThreads.Add(new ThreadFunc(Transform), "1"); rThreads.Add(new ThreadFunc(Transform), "2"); rThreads.Add(new ThreadFunc(Transform), "3"); rThreads.Add(new ThreadFunc(Transform), "4"); rThreads.Add(new ThreadFunc(Transform), "5"); //Wait until they are complete rThreads.Start(); rThreads.Wait(); return; } //[Variation("Multiple Transform(): Reader - Attribute Sets")] [InlineData()] [Theory] public void proc6() { Load("xslt_mutith_attribute_sets.xsl", "xslt_mutith_attribute_sets.xml"); CThreads rThreads = new CThreads(_output); rThreads.Add(new ThreadFunc(Transform), "1"); rThreads.Add(new ThreadFunc(Transform), "2"); rThreads.Add(new ThreadFunc(Transform), "3"); rThreads.Add(new ThreadFunc(Transform), "4"); rThreads.Add(new ThreadFunc(Transform), "5"); //Wait until they are complete rThreads.Start(); rThreads.Wait(); return; } //[Variation("Multiple Transform(): Reader - Boolean Expression AND")] [InlineData()] [Theory] public void proc7() { Load("xslt_mutith_boolean_expr_and.xsl", "xslt_mutith_boolean_expr_and.xml"); CThreads rThreads = new CThreads(_output); rThreads.Add(new ThreadFunc(Transform), "1"); rThreads.Add(new ThreadFunc(Transform), "2"); rThreads.Add(new ThreadFunc(Transform), "3"); rThreads.Add(new ThreadFunc(Transform), "4"); rThreads.Add(new ThreadFunc(Transform), "5"); //Wait until they are complete rThreads.Start(); rThreads.Wait(); return; } //[Variation("Multiple Transform(): Reader - Boolean Expression OR")] [InlineData()] [Theory] public void proc8() { Load("xslt_mutith_boolean_expr_or.xsl", "xslt_mutith_boolean_expr_or.xml"); CThreads rThreads = new CThreads(_output); rThreads.Add(new ThreadFunc(Transform), "1"); rThreads.Add(new ThreadFunc(Transform), "2"); rThreads.Add(new ThreadFunc(Transform), "3"); rThreads.Add(new ThreadFunc(Transform), "4"); rThreads.Add(new ThreadFunc(Transform), "5"); //Wait until they are complete rThreads.Start(); rThreads.Wait(); return; } //[Variation("Multiple Transform(): Reader - FormatNubmer function")] [InlineData()] [Theory] public void proc9() { Load("xslt_mutith_format_number.xsl", "xslt_mutith_format_number.xml"); CThreads rThreads = new CThreads(_output); rThreads.Add(new ThreadFunc(Transform), "1"); rThreads.Add(new ThreadFunc(Transform), "2"); rThreads.Add(new ThreadFunc(Transform), "3"); rThreads.Add(new ThreadFunc(Transform), "4"); rThreads.Add(new ThreadFunc(Transform), "5"); //Wait until they are complete rThreads.Start(); rThreads.Wait(); return; } //[Variation("Multiple Transform(): Reader - Position() function")] [InlineData()] [Theory] public void proc10() { Load("xslt_mutith_position_func.xsl", "xslt_mutith_position_func.xml"); CThreads rThreads = new CThreads(_output); rThreads.Add(new ThreadFunc(Transform), "1"); rThreads.Add(new ThreadFunc(Transform), "2"); rThreads.Add(new ThreadFunc(Transform), "3"); rThreads.Add(new ThreadFunc(Transform), "4"); rThreads.Add(new ThreadFunc(Transform), "5"); //Wait until they are complete rThreads.Start(); rThreads.Wait(); return; } //[Variation("Multiple Transform(): Reader - preserve space")] [InlineData()] [Theory] public void proc11() { Load("xslt_mutith_preserve_space.xsl", "xslt_mutith_preserve_space.xml"); CThreads rThreads = new CThreads(_output); rThreads.Add(new ThreadFunc(Transform), "1"); rThreads.Add(new ThreadFunc(Transform), "2"); rThreads.Add(new ThreadFunc(Transform), "3"); rThreads.Add(new ThreadFunc(Transform), "4"); rThreads.Add(new ThreadFunc(Transform), "5"); //Wait until they are complete rThreads.Start(); rThreads.Wait(); return; } //[Variation("Multiple Transform(): Reader - Variable nodeset")] [InlineData()] [Theory] public void proc12() { Load("xslt_mutith_variable_nodeset.xsl", "xslt_mutith_variable_nodeset.xml"); CThreads rThreads = new CThreads(_output); rThreads.Add(new ThreadFunc(Transform), "1"); rThreads.Add(new ThreadFunc(Transform), "2"); rThreads.Add(new ThreadFunc(Transform), "3"); rThreads.Add(new ThreadFunc(Transform), "4"); rThreads.Add(new ThreadFunc(Transform), "5"); //Wait until they are complete rThreads.Start(); rThreads.Wait(); return; } } //[TestCase(Name = "Same instance testing: Transform() - TEXTWRITER")] public class SameInstanceXslTransformWriter : SameInstanceXslTransformTestCase { private XPathDocument _xd; // Loads XML file private XmlReader _xrData; // Loads XML file private ITestOutputHelper _output; public SameInstanceXslTransformWriter(ITestOutputHelper output) : base(output) { _output = output; } //////////////////////////////////////////////////////////////// // Same instance testing: // Multiple Transform() over same XslCompiledTransform object //////////////////////////////////////////////////////////////// public int Transform(object args) { for (int i = 1; i <= 100; i++) { using (XmlTextWriter tw = new XmlTextWriter(System.IO.TextWriter.Null)) { xsltSameInstance.Transform(_xrData, null, tw); } } //_output.WriteLine("Transform: Thread " + args + "\tDone with WRITER transform..."); return 1; } private void Load(string _strXslFile, string _strXmlFile) { _xrData = XmlReader.Create(Path.Combine(_strPath, _strXmlFile)); _xd = new XPathDocument(_xrData, XmlSpace.Preserve); _xrData.Dispose(); XmlReaderSettings xrs = new XmlReaderSettings(); #pragma warning disable 0618 xrs.ProhibitDtd = false; #pragma warning restore 0618 XmlReader xrTemp = XmlReader.Create(Path.Combine(_strPath, _strXslFile), xrs); xsltSameInstance.Load(xrTemp); } //[Variation("Multiple Transform(): TextWriter - Basic Test")] [InlineData()] [Theory] public void proc1() { Load("xslt_multithreading_test.xsl", "foo.xml"); CThreads rThreads = new CThreads(_output); rThreads.Add(new ThreadFunc(Transform), "1"); rThreads.Add(new ThreadFunc(Transform), "2"); rThreads.Add(new ThreadFunc(Transform), "3"); rThreads.Add(new ThreadFunc(Transform), "4"); rThreads.Add(new ThreadFunc(Transform), "5"); //Wait until they are complete rThreads.Start(); rThreads.Wait(); return; } //[Variation("Multiple Transform(): TextWriter - QFE 505 Repro")] [InlineData()] [Theory] public void proc2() { AppContext.SetSwitch("Switch.System.Xml.AllowDefaultResolver", true); Load("QFE505_multith_customer_repro_with_or_expr.xsl", "QFE505_multith_customer_repro_with_or_expr.xml"); CThreads rThreads = new CThreads(_output); rThreads.Add(new ThreadFunc(Transform), "1"); rThreads.Add(new ThreadFunc(Transform), "2"); rThreads.Add(new ThreadFunc(Transform), "3"); rThreads.Add(new ThreadFunc(Transform), "4"); rThreads.Add(new ThreadFunc(Transform), "5"); //Wait until they are complete rThreads.Start(); rThreads.Wait(); return; } //[Variation("Multiple Transform(): TextWriter - AVTs")] [InlineData()] [Theory] public void proc3() { Load("xslt_multith_AVTs.xsl", "xslt_multith_AVTs.xml"); CThreads rThreads = new CThreads(_output); rThreads.Add(new ThreadFunc(Transform), "1"); rThreads.Add(new ThreadFunc(Transform), "2"); rThreads.Add(new ThreadFunc(Transform), "3"); rThreads.Add(new ThreadFunc(Transform), "4"); rThreads.Add(new ThreadFunc(Transform), "5"); //Wait until they are complete rThreads.Start(); rThreads.Wait(); return; } //[Variation("Multiple Transform(): TextWriter - xsl:key")] [InlineData()] [Theory] public void proc4() { Load("xslt_multith_keytest.xsl", "xslt_multith_keytest.xml"); CThreads rThreads = new CThreads(_output); rThreads.Add(new ThreadFunc(Transform), "1"); rThreads.Add(new ThreadFunc(Transform), "2"); rThreads.Add(new ThreadFunc(Transform), "3"); rThreads.Add(new ThreadFunc(Transform), "4"); rThreads.Add(new ThreadFunc(Transform), "5"); //Wait until they are complete rThreads.Start(); rThreads.Wait(); return; } //[Variation("Multiple Transform(): TextWriter - xsl:sort")] [InlineData()] [Theory] public void proc5() { Load("xslt_multith_sorting.xsl", "xslt_multith_sorting.xml"); CThreads rThreads = new CThreads(_output); rThreads.Add(new ThreadFunc(Transform), "1"); rThreads.Add(new ThreadFunc(Transform), "2"); rThreads.Add(new ThreadFunc(Transform), "3"); rThreads.Add(new ThreadFunc(Transform), "4"); rThreads.Add(new ThreadFunc(Transform), "5"); //Wait until they are complete rThreads.Start(); rThreads.Wait(); return; } //[Variation("Multiple Transform(): TextWriter - Attribute Sets")] [InlineData()] [Theory] public void proc6() { Load("xslt_mutith_attribute_sets.xsl", "xslt_mutith_attribute_sets.xml"); CThreads rThreads = new CThreads(_output); rThreads.Add(new ThreadFunc(Transform), "1"); rThreads.Add(new ThreadFunc(Transform), "2"); rThreads.Add(new ThreadFunc(Transform), "3"); rThreads.Add(new ThreadFunc(Transform), "4"); rThreads.Add(new ThreadFunc(Transform), "5"); //Wait until they are complete rThreads.Start(); rThreads.Wait(); return; } //[Variation("Multiple Transform(): TextWriter - Boolean Expression AND")] [InlineData()] [Theory] public void proc7() { Load("xslt_mutith_boolean_expr_and.xsl", "xslt_mutith_boolean_expr_and.xml"); CThreads rThreads = new CThreads(_output); rThreads.Add(new ThreadFunc(Transform), "1"); rThreads.Add(new ThreadFunc(Transform), "2"); rThreads.Add(new ThreadFunc(Transform), "3"); rThreads.Add(new ThreadFunc(Transform), "4"); rThreads.Add(new ThreadFunc(Transform), "5"); //Wait until they are complete rThreads.Start(); rThreads.Wait(); return; } //[Variation("Multiple Transform(): TextWriter - Boolean Expression OR")] [InlineData()] [Theory] public void proc8() { Load("xslt_mutith_boolean_expr_or.xsl", "xslt_mutith_boolean_expr_or.xml"); CThreads rThreads = new CThreads(_output); rThreads.Add(new ThreadFunc(Transform), "1"); rThreads.Add(new ThreadFunc(Transform), "2"); rThreads.Add(new ThreadFunc(Transform), "3"); rThreads.Add(new ThreadFunc(Transform), "4"); rThreads.Add(new ThreadFunc(Transform), "5"); //Wait until they are complete rThreads.Start(); rThreads.Wait(); return; } //[Variation("Multiple Transform(): TextWriter - FormatNubmer function")] [InlineData()] [Theory] public void proc9() { Load("xslt_mutith_format_number.xsl", "xslt_mutith_format_number.xml"); CThreads rThreads = new CThreads(_output); rThreads.Add(new ThreadFunc(Transform), "1"); rThreads.Add(new ThreadFunc(Transform), "2"); rThreads.Add(new ThreadFunc(Transform), "3"); rThreads.Add(new ThreadFunc(Transform), "4"); rThreads.Add(new ThreadFunc(Transform), "5"); //Wait until they are complete rThreads.Start(); rThreads.Wait(); return; } //[Variation("Multiple Transform(): TextWriter - Position() function")] [InlineData()] [Theory] public void proc10() { Load("xslt_mutith_position_func.xsl", "xslt_mutith_position_func.xml"); CThreads rThreads = new CThreads(_output); rThreads.Add(new ThreadFunc(Transform), "1"); rThreads.Add(new ThreadFunc(Transform), "2"); rThreads.Add(new ThreadFunc(Transform), "3"); rThreads.Add(new ThreadFunc(Transform), "4"); rThreads.Add(new ThreadFunc(Transform), "5"); //Wait until they are complete rThreads.Start(); rThreads.Wait(); return; } //[Variation("Multiple Transform(): TextWriter - preserve space")] [InlineData()] [Theory] public void proc11() { Load("xslt_mutith_preserve_space.xsl", "xslt_mutith_preserve_space.xml"); CThreads rThreads = new CThreads(_output); rThreads.Add(new ThreadFunc(Transform), "1"); rThreads.Add(new ThreadFunc(Transform), "2"); rThreads.Add(new ThreadFunc(Transform), "3"); rThreads.Add(new ThreadFunc(Transform), "4"); rThreads.Add(new ThreadFunc(Transform), "5"); //Wait until they are complete rThreads.Start(); rThreads.Wait(); return; } //[Variation("Multiple Transform(): TextWriter - Variable nodeset")] [InlineData()] [Theory] public void proc12() { Load("xslt_mutith_variable_nodeset.xsl", "xslt_mutith_variable_nodeset.xml"); CThreads rThreads = new CThreads(_output); rThreads.Add(new ThreadFunc(Transform), "1"); rThreads.Add(new ThreadFunc(Transform), "2"); rThreads.Add(new ThreadFunc(Transform), "3"); rThreads.Add(new ThreadFunc(Transform), "4"); rThreads.Add(new ThreadFunc(Transform), "5"); //Wait until they are complete rThreads.Start(); rThreads.Wait(); return; } } }
//----------------------------------------------------------------------------- // Torque // Copyright GarageGames, LLC 2011 //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- function TerrainMaterialDlg::show( %this, %matIndex, %terrMat, %onApplyCallback ) { Canvas.pushDialog( %this ); %this.matIndex = %matIndex; %this.onApplyCallback = %onApplyCallback; %matLibTree = %this-->matLibTree; %item = %matLibTree.findItemByObjectId( %terrMat ); if ( %item != -1 ) { %matLibTree.selectItem( %item ); %matLibTree.scrollVisible( %item ); } else { for( %i = 1; %i < %matLibTree.getItemCount(); %i++ ) { %terrMat = TerrainMaterialDlg-->matLibTree.getItemValue(%i); if( %terrMat.getClassName() $= "TerrainMaterial" ) { %matLibTree.selectItem( %i, true ); %matLibTree.scrollVisible( %i ); break; } } } } //----------------------------------------------------------------------------- function TerrainMaterialDlg::showByObjectId( %this, %matObjectId, %onApplyCallback ) { Canvas.pushDialog( %this ); %this.matIndex = -1; %this.onApplyCallback = %onApplyCallback; %matLibTree = %this-->matLibTree; %matLibTree.clearSelection(); %item = %matLibTree.findItemByObjectId( %matObjectId ); if ( %item != -1 ) { %matLibTree.selectItem( %item ); %matLibTree.scrollVisible( %item ); } } //----------------------------------------------------------------------------- function TerrainMaterialDlg::onWake( %this ) { if( !isObject( ETerrainMaterialPersistMan ) ) new PersistenceManager( ETerrainMaterialPersistMan ); if( !isObject( TerrainMaterialDlgNewGroup ) ) new SimGroup( TerrainMaterialDlgNewGroup ); if( !isObject( TerrainMaterialDlgDeleteGroup ) ) new SimGroup( TerrainMaterialDlgDeleteGroup ); // Snapshot the materials. %this.snapshotMaterials(); // Refresh the material list. %matLibTree = %this-->matLibTree; %matLibTree.clear(); %matLibTree.open( TerrainMaterialSet, false ); %matLibTree.buildVisibleTree( true ); %item = %matLibTree.getFirstRootItem(); %matLibTree.expandItem( %item ); %this.activateMaterialCtrls( true ); } //----------------------------------------------------------------------------- function TerrainMaterialDlg::onSleep( %this ) { if( isObject( TerrainMaterialDlgSnapshot ) ) TerrainMaterialDlgSnapshot.delete(); %this-->matLibTree.clear(); } //----------------------------------------------------------------------------- function TerrainMaterialDlg::dialogApply( %this ) { // Move all new materials we have created to the root group. %newCount = TerrainMaterialDlgNewGroup.getCount(); for( %i = 0; %i < %newCount; %i ++ ) RootGroup.add( TerrainMaterialDlgNewGroup.getObject( %i ) ); // Finalize deletion of all removed materials. %deletedCount = TerrainMaterialDlgDeleteGroup.getCount(); for( %i = 0; %i < %deletedCount; %i ++ ) { %mat = TerrainMaterialDlgDeleteGroup.getObject( %i ); ETerrainMaterialPersistMan.removeObjectFromFile( %mat ); %matIndex = ETerrainEditor.getMaterialIndex( %mat.internalName ); if( %matIndex != -1 ) { ETerrainEditor.removeMaterial( %matIndex ); EPainter.updateLayers(); } %mat.delete(); } // Make sure we save any changes to the current selection. %this.saveDirtyMaterial( %this.activeMat ); // Save all changes. ETerrainMaterialPersistMan.saveDirty(); // Delete the snapshot. TerrainMaterialDlgSnapshot.delete(); // Remove ourselves from the canvas. Canvas.popDialog( TerrainMaterialDlg ); call( %this.onApplyCallback, %this.activeMat, %this.matIndex ); } //----------------------------------------------------------------------------- function TerrainMaterialDlg::dialogCancel( %this ) { // Restore material properties we have changed. %this.restoreMaterials(); // Clear the persistence manager state. ETerrainMaterialPersistMan.clearAll(); // Delete all new object we have created. TerrainMaterialDlgNewGroup.clear(); // Restore materials we have marked for deletion. %deletedCount = TerrainMaterialDlgDeleteGroup.getCount(); for( %i = 0; %i < %deletedCount; %i ++ ) { %mat = TerrainMaterialDlgDeleteGroup.getObject( %i ); %mat.parentGroup = RootGroup; TerrainMaterialSet.add( %mat ); } Canvas.popDialog( TerrainMaterialDlg ); } //----------------------------------------------------------------------------- function TerrainMaterialDlg::setMaterialName( %this, %newName ) { %mat = %this.activeMat; if( %mat.internalName !$= %newName ) { %existingMat = TerrainMaterialSet.findObjectByInternalName( %newName ); if( isObject( %existingMat ) ) { MessageBoxOK( "Error", "There already is a terrain material called '" @ %newName @ "'.", "", "" ); } else { %mat.setInternalName( %newName ); %this-->matLibTree.buildVisibleTree( false ); } } } //----------------------------------------------------------------------------- function TerrainMaterialDlg::changeBase( %this ) { %ctrl = %this-->baseTexCtrl; %file = %ctrl.bitmap; if( getSubStr( %file, 0 , 6 ) $= "tools/" ) %file = ""; %file = TerrainMaterialDlg._selectTextureFileDialog( %file ); if( %file $= "" ) { if( %ctrl.bitmap !$= "" ) %file = %ctrl.bitmap; else %file = "tools/materialeditor/gui/unknownImage"; } %file = makeRelativePath( %file, getMainDotCsDir() ); %ctrl.setBitmap( %file ); } //----------------------------------------------------------------------------- function TerrainMaterialDlg::changeDetail( %this ) { %ctrl = %this-->detailTexCtrl; %file = %ctrl.bitmap; if( getSubStr( %file, 0 , 6 ) $= "tools/" ) %file = ""; %file = TerrainMaterialDlg._selectTextureFileDialog( %file ); if( %file $= "" ) { if( %ctrl.bitmap !$= "" ) %file = %ctrl.bitmap; else %file = "tools/materialeditor/gui/unknownImage"; } %file = makeRelativePath( %file, getMainDotCsDir() ); %ctrl.setBitmap( %file ); } //----------------------------------------------------------------------------- function TerrainMaterialDlg::changeNormal( %this ) { %ctrl = %this-->normTexCtrl; %file = %ctrl.bitmap; if( getSubStr( %file, 0 , 6 ) $= "tools/" ) %file = ""; %file = TerrainMaterialDlg._selectTextureFileDialog( %file ); if( %file $= "" ) { if( %ctrl.bitmap !$= "" ) %file = %ctrl.bitmap; else %file = "tools/materialeditor/gui/unknownImage"; } %file = makeRelativePath( %file, getMainDotCsDir() ); %ctrl.setBitmap( %file ); } //----------------------------------------------------------------------------- function TerrainMaterialDlg::newMat( %this ) { // Create a unique material name. %matName = getUniqueInternalName( "newMaterial", TerrainMaterialSet, true ); // Create the new material. %newMat = new TerrainMaterial() { internalName = %matName; parentGroup = TerrainMaterialDlgNewGroup; }; %newMat.setFileName( "art/terrains/materials.cs" ); // Mark it as dirty and to be saved in the default location. ETerrainMaterialPersistMan.setDirty( %newMat, "art/terrains/materials.cs" ); %matLibTree = %this-->matLibTree; %matLibTree.buildVisibleTree( true ); %item = %matLibTree.findItemByObjectId( %newMat ); %matLibTree.selectItem( %item ); } //----------------------------------------------------------------------------- function TerrainMaterialDlg::deleteMat( %this ) { if( !isObject( %this.activeMat ) ) return; // Cannot delete this material if it is the only one left on the Terrain if ( ( ETerrainEditor.getMaterialCount() == 1 ) && ( ETerrainEditor.getMaterialIndex( %this.activeMat.internalName ) != -1 ) ) { MessageBoxOK( "Error", "Cannot delete this Material, it is the only " @ "Material still in use by the active Terrain." ); return; } TerrainMaterialSet.remove( %this.activeMat ); TerrainMaterialDlgDeleteGroup.add( %this.activeMat ); %matLibTree = %this-->matLibTree; %matLibTree.open( TerrainMaterialSet, false ); %matLibTree.selectItem( 1 ); } //----------------------------------------------------------------------------- function TerrainMaterialDlg::activateMaterialCtrls( %this, %active ) { %parent = %this-->matSettingsParent; %count = %parent.getCount(); for ( %i = 0; %i < %count; %i++ ) %parent.getObject( %i ).setActive( %active ); } //----------------------------------------------------------------------------- function TerrainMaterialTreeCtrl::onSelect( %this, %item ) { TerrainMaterialDlg.setActiveMaterial( %item ); } //----------------------------------------------------------------------------- function TerrainMaterialTreeCtrl::onUnSelect( %this, %item ) { TerrainMaterialDlg.saveDirtyMaterial( %item ); TerrainMaterialDlg.setActiveMaterial( 0 ); } //----------------------------------------------------------------------------- function TerrainMaterialDlg::setActiveMaterial( %this, %mat ) { if ( isObject( %mat ) && %mat.isMemberOfClass( TerrainMaterial ) ) { %this.activeMat = %mat; %this-->matNameCtrl.setText( %mat.internalName ); if (%mat.diffuseMap $= ""){ %this-->baseTexCtrl.setBitmap( "tools/materialeditor/gui/unknownImage" ); }else{ %this-->baseTexCtrl.setBitmap( %mat.diffuseMap ); } if (%mat.detailMap $= ""){ %this-->detailTexCtrl.setBitmap( "tools/materialeditor/gui/unknownImage" ); }else{ %this-->detailTexCtrl.setBitmap( %mat.detailMap ); } if (%mat.normalMap $= ""){ %this-->normTexCtrl.setBitmap( "tools/materialeditor/gui/unknownImage" ); }else{ %this-->normTexCtrl.setBitmap( %mat.normalMap ); } %this-->detSizeCtrl.setText( %mat.detailSize ); %this-->baseSizeCtrl.setText( %mat.diffuseSize ); %this-->detStrengthCtrl.setText( %mat.detailStrength ); %this-->detDistanceCtrl.setText( %mat.detailDistance ); %this-->sideProjectionCtrl.setValue( %mat.useSideProjection ); %this-->parallaxScaleCtrl.setText( %mat.parallaxScale ); %this.activateMaterialCtrls( true ); } else { %this.activeMat = 0; %this.activateMaterialCtrls( false ); } } //----------------------------------------------------------------------------- function TerrainMaterialDlg::saveDirtyMaterial( %this, %mat ) { // Skip over obviously bad cases. if ( !isObject( %mat ) || !%mat.isMemberOfClass( TerrainMaterial ) ) return; // Read out properties from the dialog. %newName = %this-->matNameCtrl.getText(); if (%this-->baseTexCtrl.bitmap $= "tools/materialeditor/gui/unknownImage"){ %newDiffuse = ""; }else{ %newDiffuse = %this-->baseTexCtrl.bitmap; } if (%this-->normTexCtrl.bitmap $= "tools/materialeditor/gui/unknownImage"){ %newNormal = ""; }else{ %newNormal = %this-->normTexCtrl.bitmap; } if (%this-->detailTexCtrl.bitmap $= "tools/materialeditor/gui/unknownImage"){ %newDetail = ""; }else{ %newDetail = %this-->detailTexCtrl.bitmap; } %detailSize = %this-->detSizeCtrl.getText(); %diffuseSize = %this-->baseSizeCtrl.getText(); %detailStrength = %this-->detStrengthCtrl.getText(); %detailDistance = %this-->detDistanceCtrl.getText(); %useSideProjection = %this-->sideProjectionCtrl.getValue(); %parallaxScale = %this-->parallaxScaleCtrl.getText(); // If no properties of this materials have changed, // return. if ( %mat.internalName $= %newName && %mat.diffuseMap $= %newDiffuse && %mat.normalMap $= %newNormal && %mat.detailMap $= %newDetail && %mat.detailSize == %detailSize && %mat.diffuseSize == %diffuseSize && %mat.detailStrength == %detailStrength && %mat.detailDistance == %detailDistance && %mat.useSideProjection == %useSideProjection && %mat.parallaxScale == %parallaxScale ) return; // Make sure the material name is unique. if( %mat.internalName !$= %newName ) { %existingMat = TerrainMaterialSet.findObjectByInternalName( %newName ); if( isObject( %existingMat ) ) { MessageBoxOK( "Error", "There already is a terrain material called '" @ %newName @ "'.", "", "" ); // Reset the name edit control to the old name. %this-->matNameCtrl.setText( %mat.internalName ); } else %mat.setInternalName( %newName ); } %mat.diffuseMap = %newDiffuse; %mat.normalMap = %newNormal; %mat.detailMap = %newDetail; %mat.detailSize = %detailSize; %mat.diffuseSize = %diffuseSize; %mat.detailStrength = %detailStrength; %mat.detailDistance = %detailDistance; %mat.useSideProjection = %useSideProjection; %mat.parallaxScale = %parallaxScale; // Mark the material as dirty and needing saving. %fileName = %mat.getFileName(); if( %fileName $= "" ) %fileName = "art/terrains/materials.cs"; ETerrainMaterialPersistMan.setDirty( %mat, %fileName ); } //----------------------------------------------------------------------------- function TerrainMaterialDlg::snapshotMaterials( %this ) { if( !isObject( TerrainMaterialDlgSnapshot ) ) new SimGroup( TerrainMaterialDlgSnapshot ); %group = TerrainMaterialDlgSnapshot; %group.clear(); %matCount = TerrainMaterialSet.getCount(); for( %i = 0; %i < %matCount; %i ++ ) { %mat = TerrainMaterialSet.getObject( %i ); if( !isMemberOfClass( %mat.getClassName(), "TerrainMaterial" ) ) continue; %snapshot = new ScriptObject() { parentGroup = %group; material = %mat; internalName = %mat.internalName; diffuseMap = %mat.diffuseMap; normalMap = %mat.normalMap; detailMap = %mat.detailMap; detailSize = %mat.detailSize; diffuseSize = %mat.diffuseSize; detailStrength = %mat.detailStrength; detailDistance = %mat.detailDistance; useSideProjection = %mat.useSideProjection; parallaxScale = %mat.parallaxScale; }; } } //----------------------------------------------------------------------------- function TerrainMaterialDlg::restoreMaterials( %this ) { if( !isObject( TerrainMaterialDlgSnapshot ) ) { error( "TerrainMaterial::restoreMaterials - no snapshot present" ); return; } %count = TerrainMaterialDlgSnapshot.getCount(); for( %i = 0; %i < %count; %i ++ ) { %obj = TerrainMaterialDlgSnapshot.getObject( %i ); %mat = %obj.material; %mat.setInternalName( %obj.internalName ); %mat.diffuseMap = %obj.diffuseMap; %mat.normalMap = %obj.normalMap; %mat.detailMap = %obj.detailMap; %mat.detailSize = %obj.detailSize; %mat.diffuseSize = %obj.diffuseSize; %mat.detailStrength = %obj.detailStrength; %mat.detailDistance = %obj.detailDistance; %mat.useSideProjection = %obj.useSideProjection; %mat.parallaxScale = %obj.parallaxScale; } } //----------------------------------------------------------------------------- function TerrainMaterialDlg::_selectTextureFileDialog( %this, %defaultFileName ) { if( $Pref::TerrainEditor::LastPath $= "" ) $Pref::TerrainEditor::LastPath = "art/terrains"; %dlg = new OpenFileDialog() { Filters = $TerrainEditor::TextureFileSpec; DefaultPath = $Pref::TerrainEditor::LastPath; DefaultFile = %defaultFileName; ChangePath = false; MustExist = true; }; %ret = %dlg.Execute(); if ( %ret ) { $Pref::TerrainEditor::LastPath = filePath( %dlg.FileName ); %file = %dlg.FileName; } %dlg.delete(); if ( !%ret ) return; %file = filePath(%file) @ "/" @ fileBase(%file); return %file; }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Orleans.Concurrency; using Orleans.Configuration; using Orleans.Internal; using Orleans.Runtime; namespace Orleans.Streams { internal class PersistentStreamPullingAgent : SystemTarget, IPersistentStreamPullingAgent { private static readonly IBackoffProvider DeliveryBackoffProvider = new ExponentialBackoff(TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(30), TimeSpan.FromSeconds(1)); private static readonly IBackoffProvider ReadLoopBackoff = new ExponentialBackoff(TimeSpan.FromSeconds(10), TimeSpan.FromSeconds(20), TimeSpan.FromSeconds(1)); private const int ReadLoopRetryMax = 6; private const int StreamInactivityCheckFrequency = 10; private readonly string streamProviderName; private readonly IStreamPubSub pubSub; private readonly Dictionary<InternalStreamId, StreamConsumerCollection> pubSubCache; private readonly SafeRandom safeRandom; private readonly StreamPullingAgentOptions options; private readonly ILogger logger; private readonly CounterStatistic numReadMessagesCounter; private readonly CounterStatistic numSentMessagesCounter; private int numMessages; private IQueueAdapter queueAdapter; private IQueueCache queueCache; private IQueueAdapterReceiver receiver; private IStreamFailureHandler streamFailureHandler; private DateTime lastTimeCleanedPubSubCache; private IDisposable timer; internal readonly QueueId QueueId; private Task receiverInitTask; private bool IsShutdown => timer == null; private string StatisticUniquePostfix => streamProviderName + "." + QueueId; internal PersistentStreamPullingAgent( SystemTargetGrainId id, string strProviderName, IStreamProviderRuntime runtime, ILoggerFactory loggerFactory, IStreamPubSub streamPubSub, QueueId queueId, StreamPullingAgentOptions options, SiloAddress siloAddress) : base(id, siloAddress, true, loggerFactory) { if (runtime == null) throw new ArgumentNullException("runtime", "PersistentStreamPullingAgent: runtime reference should not be null"); if (strProviderName == null) throw new ArgumentNullException("runtime", "PersistentStreamPullingAgent: strProviderName should not be null"); QueueId = queueId; streamProviderName = strProviderName; pubSub = streamPubSub; pubSubCache = new Dictionary<InternalStreamId, StreamConsumerCollection>(); safeRandom = new SafeRandom(); this.options = options; numMessages = 0; logger = runtime.ServiceProvider.GetRequiredService<ILoggerFactory>().CreateLogger($"{this.GetType().Namespace}.{streamProviderName}"); logger.Info(ErrorCode.PersistentStreamPullingAgent_01, "Created {0} {1} for Stream Provider {2} on silo {3} for Queue {4}.", GetType().Name, ((ISystemTargetBase)this).GrainId.ToString(), streamProviderName, Silo, QueueId.ToStringWithHashCode()); numReadMessagesCounter = CounterStatistic.FindOrCreate(new StatisticName(StatisticNames.STREAMS_PERSISTENT_STREAM_NUM_READ_MESSAGES, StatisticUniquePostfix)); numSentMessagesCounter = CounterStatistic.FindOrCreate(new StatisticName(StatisticNames.STREAMS_PERSISTENT_STREAM_NUM_SENT_MESSAGES, StatisticUniquePostfix)); // TODO: move queue cache size statistics tracking into queue cache implementation once Telemetry APIs and LogStatistics have been reconciled. //IntValueStatistic.FindOrCreate(new StatisticName(StatisticNames.STREAMS_PERSISTENT_STREAM_QUEUE_CACHE_SIZE, statUniquePostfix), () => queueCache != null ? queueCache.Size : 0); } /// <summary> /// Take responsibility for a new queues that was assigned to me via a new range. /// We first store the new queue in our internal data structure, try to initialize it and start a pumping timer. /// ERROR HANDLING: /// The responsibility to handle initialization and shutdown failures is inside the INewQueueAdapterReceiver code. /// The agent will call Initialize once and log an error. It will not call initialize again. /// The receiver itself may attempt later to recover from this error and do initialization again. /// The agent will assume initialization has succeeded and will subsequently start calling pumping receive. /// Same applies to shutdown. /// </summary> /// <param name="qAdapter"></param> /// <param name="queueAdapterCache"></param> /// <param name="failureHandler"></param> /// <returns></returns> public Task Initialize(Immutable<IQueueAdapter> qAdapter, Immutable<IQueueAdapterCache> queueAdapterCache, Immutable<IStreamFailureHandler> failureHandler) { if (qAdapter.Value == null) throw new ArgumentNullException("qAdapter", "Init: queueAdapter should not be null"); if (failureHandler.Value == null) throw new ArgumentNullException("failureHandler", "Init: streamDeliveryFailureHandler should not be null"); return OrleansTaskExtentions.WrapInTask(() => InitializeInternal(qAdapter.Value, queueAdapterCache.Value, failureHandler.Value)); } private void InitializeInternal(IQueueAdapter qAdapter, IQueueAdapterCache queueAdapterCache, IStreamFailureHandler failureHandler) { logger.Info(ErrorCode.PersistentStreamPullingAgent_02, "Init of {0} {1} on silo {2} for queue {3}.", GetType().Name, ((ISystemTargetBase)this).GrainId.ToString(), Silo, QueueId.ToStringWithHashCode()); // Remove cast once we cleanup queueAdapter = qAdapter; streamFailureHandler = failureHandler; lastTimeCleanedPubSubCache = DateTime.UtcNow; try { receiver = queueAdapter.CreateReceiver(QueueId); } catch (Exception exc) { logger.Error(ErrorCode.PersistentStreamPullingAgent_02, "Exception while calling IQueueAdapter.CreateNewReceiver.", exc); throw; } try { if (queueAdapterCache != null) { queueCache = queueAdapterCache.CreateQueueCache(QueueId); } } catch (Exception exc) { logger.Error(ErrorCode.PersistentStreamPullingAgent_23, "Exception while calling IQueueAdapterCache.CreateQueueCache.", exc); throw; } try { receiverInitTask = OrleansTaskExtentions.SafeExecute(() => receiver.Initialize(this.options.InitQueueTimeout)) .LogException(logger, ErrorCode.PersistentStreamPullingAgent_03, $"QueueAdapterReceiver {QueueId.ToStringWithHashCode()} failed to Initialize."); receiverInitTask.Ignore(); } catch { // Just ignore this exception and proceed as if Initialize has succeeded. // We already logged individual exceptions for individual calls to Initialize. No need to log again. } // Setup a reader for a new receiver. // Even if the receiver failed to initialise, treat it as OK and start pumping it. It's receiver responsibility to retry initialization. var randomTimerOffset = safeRandom.NextTimeSpan(this.options.GetQueueMsgsTimerPeriod); timer = RegisterTimer(AsyncTimerCallback, QueueId, randomTimerOffset, this.options.GetQueueMsgsTimerPeriod); IntValueStatistic.FindOrCreate(new StatisticName(StatisticNames.STREAMS_PERSISTENT_STREAM_PUBSUB_CACHE_SIZE, StatisticUniquePostfix), () => pubSubCache.Count); logger.Info((int)ErrorCode.PersistentStreamPullingAgent_04, "Taking queue {0} under my responsibility.", QueueId.ToStringWithHashCode()); } public async Task Shutdown() { // Stop pulling from queues that are not in my range anymore. logger.Info(ErrorCode.PersistentStreamPullingAgent_05, "Shutdown of {0} responsible for queue: {1}", GetType().Name, QueueId.ToStringWithHashCode()); if (timer != null) { IDisposable tmp = timer; timer = null; Utils.SafeExecute(tmp.Dispose, this.logger); } this.queueCache = null; Task localReceiverInitTask = receiverInitTask; if (localReceiverInitTask != null) { try { await localReceiverInitTask; receiverInitTask = null; } catch (Exception) { receiverInitTask = null; // squelch } } try { IQueueAdapterReceiver localReceiver = this.receiver; this.receiver = null; if (localReceiver != null) { var task = OrleansTaskExtentions.SafeExecute(() => localReceiver.Shutdown(this.options.InitQueueTimeout)); task = task.LogException(logger, ErrorCode.PersistentStreamPullingAgent_07, $"QueueAdapterReceiver {QueueId} failed to Shutdown."); await task; } } catch { // Just ignore this exception and proceed as if Shutdown has succeeded. // We already logged individual exceptions for individual calls to Shutdown. No need to log again. } var unregisterTasks = new List<Task>(); var meAsStreamProducer = this.AsReference<IStreamProducerExtension>(); foreach (var tuple in pubSubCache) { tuple.Value.DisposeAll(logger); var streamId = tuple.Key; logger.Info(ErrorCode.PersistentStreamPullingAgent_06, "Unregister PersistentStreamPullingAgent Producer for stream {0}.", streamId); unregisterTasks.Add(pubSub.UnregisterProducer(streamId, meAsStreamProducer)); } try { await Task.WhenAll(unregisterTasks); } catch (Exception exc) { logger.Warn(ErrorCode.PersistentStreamPullingAgent_08, "Failed to unregister myself as stream producer to some streams that used to be in my responsibility.", exc); } pubSubCache.Clear(); IntValueStatistic.Delete(new StatisticName(StatisticNames.STREAMS_PERSISTENT_STREAM_PUBSUB_CACHE_SIZE, StatisticUniquePostfix)); //IntValueStatistic.Delete(new StatisticName(StatisticNames.STREAMS_PERSISTENT_STREAM_QUEUE_CACHE_SIZE, StatisticUniquePostfix)); } public Task AddSubscriber( GuidId subscriptionId, InternalStreamId streamId, IStreamConsumerExtension streamConsumer) { if (logger.IsEnabled(LogLevel.Debug)) logger.Debug(ErrorCode.PersistentStreamPullingAgent_09, "AddSubscriber: Stream={0} Subscriber={1}.", streamId, streamConsumer); // cannot await here because explicit consumers trigger this call, so it could cause a deadlock. AddSubscriber_Impl(subscriptionId, streamId, streamConsumer, null) .LogException(logger, ErrorCode.PersistentStreamPullingAgent_26, $"Failed to add subscription for stream {streamId}.") .Ignore(); return Task.CompletedTask; } // Called by rendezvous when new remote subscriber subscribes to this stream. private async Task AddSubscriber_Impl( GuidId subscriptionId, InternalStreamId streamId, IStreamConsumerExtension streamConsumer, StreamSequenceToken cacheToken) { if (IsShutdown) return; StreamConsumerCollection streamDataCollection; if (!pubSubCache.TryGetValue(streamId, out streamDataCollection)) { // If stream is not in pubsub cache, then we've received no events on this stream, and will aquire the subscriptions from pubsub when we do. return; } StreamConsumerData data; if (!streamDataCollection.TryGetConsumer(subscriptionId, out data)) data = streamDataCollection.AddConsumer(subscriptionId, streamId, streamConsumer); if (await DoHandshakeWithConsumer(data, cacheToken)) { if (data.State == StreamConsumerDataState.Inactive) RunConsumerCursor(data).Ignore(); // Start delivering events if not actively doing so } } private async Task<bool> DoHandshakeWithConsumer( StreamConsumerData consumerData, StreamSequenceToken cacheToken) { StreamHandshakeToken requestedHandshakeToken = null; // if not cache, then we can't get cursor and there is no reason to ask consumer for token. if (queueCache != null) { Exception exceptionOccured = null; try { requestedHandshakeToken = await AsyncExecutorWithRetries.ExecuteWithRetries( i => consumerData.StreamConsumer.GetSequenceToken(consumerData.SubscriptionId), AsyncExecutorWithRetries.INFINITE_RETRIES, (exception, i) => !(exception is ClientNotAvailableException), this.options.MaxEventDeliveryTime, DeliveryBackoffProvider); if (requestedHandshakeToken != null) { consumerData.SafeDisposeCursor(logger); consumerData.Cursor = queueCache.GetCacheCursor(consumerData.StreamId, requestedHandshakeToken.Token); } else { if (consumerData.Cursor == null) // if the consumer did not ask for a specific token and we already have a cursor, jsut keep using it. consumerData.Cursor = queueCache.GetCacheCursor(consumerData.StreamId, cacheToken); } } catch (Exception exception) { exceptionOccured = exception; } if (exceptionOccured != null) { bool faultedSubscription = await ErrorProtocol(consumerData, exceptionOccured, false, null, requestedHandshakeToken?.Token); if (faultedSubscription) return false; } } consumerData.LastToken = requestedHandshakeToken; // use what ever the consumer asked for as LastToken for next handshake (even if he asked for null). // if we don't yet have a cursor (had errors in the handshake or data not available exc), get a cursor at the event that triggered that consumer subscription. if (consumerData.Cursor == null && queueCache != null) { try { consumerData.Cursor = queueCache.GetCacheCursor(consumerData.StreamId, cacheToken); } catch (Exception) { consumerData.Cursor = queueCache.GetCacheCursor(consumerData.StreamId, null); // just in case last GetCacheCursor failed. } } return true; } public Task RemoveSubscriber(GuidId subscriptionId, InternalStreamId streamId) { RemoveSubscriber_Impl(subscriptionId, streamId); return Task.CompletedTask; } public void RemoveSubscriber_Impl(GuidId subscriptionId, InternalStreamId streamId) { if (IsShutdown) return; StreamConsumerCollection streamData; if (!pubSubCache.TryGetValue(streamId, out streamData)) return; // remove consumer bool removed = streamData.RemoveConsumer(subscriptionId, logger); if (removed && logger.IsEnabled(LogLevel.Debug)) logger.Debug(ErrorCode.PersistentStreamPullingAgent_10, "Removed Consumer: subscription={0}, for stream {1}.", subscriptionId, streamId); if (streamData.Count == 0) pubSubCache.Remove(streamId); } private async Task AsyncTimerCallback(object state) { var queueId = (QueueId)state; try { Task localReceiverInitTask = receiverInitTask; if (localReceiverInitTask != null) { await localReceiverInitTask; receiverInitTask = null; } if (IsShutdown) return; // timer was already removed, last tick // loop through the queue until it is empty. while (!IsShutdown) // timer will be set to null when we are asked to shudown. { int maxCacheAddCount = queueCache?.GetMaxAddCount() ?? QueueAdapterConstants.UNLIMITED_GET_QUEUE_MSG; if (maxCacheAddCount != QueueAdapterConstants.UNLIMITED_GET_QUEUE_MSG && maxCacheAddCount <= 0) return; // If read succeeds and there is more data, we continue reading. // If read succeeds and there is no more data, we break out of loop // If read fails, we retry 6 more times, with backoff policy. // we log each failure as warnings. After 6 times retry if still fail, we break out of loop and log an error bool moreData = await AsyncExecutorWithRetries.ExecuteWithRetries( i => ReadFromQueue(queueId, receiver, maxCacheAddCount), ReadLoopRetryMax, ReadLoopRetryExceptionFilter, Constants.INFINITE_TIMESPAN, ReadLoopBackoff); if (!moreData) return; } } catch (Exception exc) { receiverInitTask = null; logger.Error(ErrorCode.PersistentStreamPullingAgent_12, $"Giving up reading from queue {queueId} after retry attempts {ReadLoopRetryMax}", exc); } } private bool ReadLoopRetryExceptionFilter(Exception e, int retryCounter) { this.logger.Warn(ErrorCode.PersistentStreamPullingAgent_12, $"Exception while retrying the {retryCounter}th time reading from queue {this.QueueId}", e); return !IsShutdown; } /// <summary> /// Read from queue. /// Returns true, if data was read, false if it was not /// </summary> /// <param name="myQueueId"></param> /// <param name="rcvr"></param> /// <param name="maxCacheAddCount"></param> /// <returns></returns> private async Task<bool> ReadFromQueue(QueueId myQueueId, IQueueAdapterReceiver rcvr, int maxCacheAddCount) { if (rcvr == null) { return false; } var now = DateTime.UtcNow; // Try to cleanup the pubsub cache at the cadence of 10 times in the configurable StreamInactivityPeriod. if ((now - lastTimeCleanedPubSubCache) >= this.options.StreamInactivityPeriod.Divide(StreamInactivityCheckFrequency)) { lastTimeCleanedPubSubCache = now; CleanupPubSubCache(now); } if (queueCache != null) { IList<IBatchContainer> purgedItems; if (queueCache.TryPurgeFromCache(out purgedItems)) { try { await rcvr.MessagesDeliveredAsync(purgedItems); } catch (Exception exc) { logger.Warn(ErrorCode.PersistentStreamPullingAgent_27, $"Exception calling MessagesDeliveredAsync on queue {myQueueId}. Ignoring.", exc); } } } if (queueCache != null && queueCache.IsUnderPressure()) { // Under back pressure. Exit the loop. Will attempt again in the next timer callback. logger.Info((int)ErrorCode.PersistentStreamPullingAgent_24, "Stream cache is under pressure. Backing off."); return false; } // Retrieve one multiBatch from the queue. Every multiBatch has an IEnumerable of IBatchContainers, each IBatchContainer may have multiple events. IList<IBatchContainer> multiBatch = await rcvr.GetQueueMessagesAsync(maxCacheAddCount); if (multiBatch == null || multiBatch.Count == 0) return false; // queue is empty. Exit the loop. Will attempt again in the next timer callback. queueCache?.AddToCache(multiBatch); numMessages += multiBatch.Count; numReadMessagesCounter.IncrementBy(multiBatch.Count); if (logger.IsEnabled(LogLevel.Trace)) logger.Trace(ErrorCode.PersistentStreamPullingAgent_11, "Got {0} messages from queue {1}. So far {2} msgs from this queue.", multiBatch.Count, myQueueId.ToStringWithHashCode(), numMessages); foreach (var group in multiBatch .Where(m => m != null) .GroupBy(container => container.StreamId)) { var streamId = new InternalStreamId(queueAdapter.Name, group.Key); StreamSequenceToken startToken = group.First().SequenceToken; StreamConsumerCollection streamData; if (pubSubCache.TryGetValue(streamId, out streamData)) { streamData.RefreshActivity(now); if (streamData.StreamRegistered) { StartInactiveCursors(streamData, startToken); // if this is an existing stream, start any inactive cursors } else { if(this.logger.IsEnabled(LogLevel.Debug)) this.logger.LogDebug($"Pulled new messages in stream {streamId} from the queue, but pulling agent haven't succeeded in" + $"RegisterStream yet, will start deliver on this stream after RegisterStream succeeded"); } } else { RegisterStream(streamId, startToken, now).Ignore(); // if this is a new stream register as producer of stream in pub sub system } } return true; } private void CleanupPubSubCache(DateTime now) { if (pubSubCache.Count == 0) return; var toRemove = pubSubCache.Where(pair => pair.Value.IsInactive(now, this.options.StreamInactivityPeriod)) .ToList(); toRemove.ForEach(tuple => { pubSubCache.Remove(tuple.Key); tuple.Value.DisposeAll(logger); }); } private async Task RegisterStream(InternalStreamId streamId, StreamSequenceToken firstToken, DateTime now) { var streamData = new StreamConsumerCollection(now); pubSubCache.Add(streamId, streamData); // Create a fake cursor to point into a cache. // That way we will not purge the event from the cache, until we talk to pub sub. // This will help ensure the "casual consistency" between pre-existing subscripton (of a potentially new already subscribed consumer) // and later production. var pinCursor = queueCache?.GetCacheCursor(streamId, firstToken); try { await RegisterAsStreamProducer(streamId, firstToken); streamData.StreamRegistered = true; } finally { // Cleanup the fake pinning cursor. pinCursor?.Dispose(); } } private void StartInactiveCursors(StreamConsumerCollection streamData, StreamSequenceToken startToken) { foreach (StreamConsumerData consumerData in streamData.AllConsumers()) { consumerData.Cursor?.Refresh(startToken); if (consumerData.State == StreamConsumerDataState.Inactive) { // wake up inactive consumers RunConsumerCursor(consumerData).Ignore(); } } } private async Task RunConsumerCursor(StreamConsumerData consumerData) { try { // double check in case of interleaving if (consumerData.State == StreamConsumerDataState.Active || consumerData.Cursor == null) return; consumerData.State = StreamConsumerDataState.Active; while (consumerData.Cursor != null) { IBatchContainer batch = null; Exception exceptionOccured = null; try { batch = GetBatchForConsumer(consumerData.Cursor, consumerData.StreamId); if (batch == null) { break; } } catch (Exception exc) { exceptionOccured = exc; consumerData.SafeDisposeCursor(logger); consumerData.Cursor = queueCache.GetCacheCursor(consumerData.StreamId, null); } try { numSentMessagesCounter.Increment(); if (batch != null) { StreamHandshakeToken newToken = await AsyncExecutorWithRetries.ExecuteWithRetries( i => DeliverBatchToConsumer(consumerData, batch), AsyncExecutorWithRetries.INFINITE_RETRIES, (exception, i) => !(exception is ClientNotAvailableException), this.options.MaxEventDeliveryTime, DeliveryBackoffProvider); if (newToken != null) { consumerData.LastToken = newToken; IQueueCacheCursor newCursor = queueCache.GetCacheCursor(consumerData.StreamId, newToken.Token); consumerData.SafeDisposeCursor(logger); consumerData.Cursor = newCursor; } } } catch (Exception exc) { consumerData.Cursor?.RecordDeliveryFailure(); var message = $"Exception while trying to deliver msgs to stream {consumerData.StreamId} in PersistentStreamPullingAgentGrain.RunConsumerCursor"; logger.Error(ErrorCode.PersistentStreamPullingAgent_14, message, exc); exceptionOccured = exc is ClientNotAvailableException ? exc : new StreamEventDeliveryFailureException(consumerData.StreamId); } // if we failed to deliver a batch if (exceptionOccured != null) { bool faultedSubscription = await ErrorProtocol(consumerData, exceptionOccured, true, batch, batch?.SequenceToken); if (faultedSubscription) return; } } consumerData.State = StreamConsumerDataState.Inactive; } catch (Exception exc) { // RunConsumerCursor is fired with .Ignore so we should log if anything goes wrong, because there is no one to catch the exception logger.Error(ErrorCode.PersistentStreamPullingAgent_15, "Ignored RunConsumerCursor Error", exc); consumerData.State = StreamConsumerDataState.Inactive; throw; } } private IBatchContainer GetBatchForConsumer(IQueueCacheCursor cursor, StreamId streamId) { if (this.options.BatchContainerBatchSize <= 1) { Exception ignore; if (!cursor.MoveNext()) { return null; } return cursor.GetCurrent(out ignore); } else if (this.options.BatchContainerBatchSize > 1) { Exception ignore; int i = 0; var batchContainers = new List<IBatchContainer>(); while (i < this.options.BatchContainerBatchSize) { if (!cursor.MoveNext()) { break; } var batchContainer = cursor.GetCurrent(out ignore); batchContainers.Add(batchContainer); i++; } if (i == 0) { return null; } return new BatchContainerBatch(batchContainers); } return null; } private async Task<StreamHandshakeToken> DeliverBatchToConsumer(StreamConsumerData consumerData, IBatchContainer batch) { try { StreamHandshakeToken newToken = await ContextualizedDeliverBatchToConsumer(consumerData, batch); consumerData.LastToken = StreamHandshakeToken.CreateDeliveyToken(batch.SequenceToken); // this is the currently delivered token return newToken; } catch (Exception ex) { this.logger.LogWarning(ex, "Failed to deliver message to consumer on {SubscriptionId} for stream {StreamId}, may retry.", consumerData.SubscriptionId, consumerData.StreamId); throw; } } /// <summary> /// Add call context for batch delivery call, then clear context immediately, without giving up turn. /// </summary> private Task<StreamHandshakeToken> ContextualizedDeliverBatchToConsumer(StreamConsumerData consumerData, IBatchContainer batch) { bool isRequestContextSet = batch.ImportRequestContext(); try { return consumerData.StreamConsumer.DeliverBatch(consumerData.SubscriptionId, consumerData.StreamId, batch.AsImmutable(), consumerData.LastToken); } finally { if (isRequestContextSet) { // clear RequestContext before await! RequestContext.Clear(); } } } private static async Task DeliverErrorToConsumer(StreamConsumerData consumerData, Exception exc, IBatchContainer batch) { Task errorDeliveryTask; bool isRequestContextSet = batch != null && batch.ImportRequestContext(); try { errorDeliveryTask = consumerData.StreamConsumer.ErrorInStream(consumerData.SubscriptionId, exc); } finally { if (isRequestContextSet) { RequestContext.Clear(); // clear RequestContext before await! } } await errorDeliveryTask; } private async Task<bool> ErrorProtocol(StreamConsumerData consumerData, Exception exceptionOccured, bool isDeliveryError, IBatchContainer batch, StreamSequenceToken token) { // for loss of client, we just remove the subscription if (exceptionOccured is ClientNotAvailableException) { logger.Warn(ErrorCode.Stream_ConsumerIsDead, "Consumer {0} on stream {1} is no longer active - permanently removing Consumer.", consumerData.StreamConsumer, consumerData.StreamId); pubSub.UnregisterConsumer(consumerData.SubscriptionId, consumerData.StreamId).Ignore(); return true; } // notify consumer about the error or that the data is not available. await OrleansTaskExtentions.ExecuteAndIgnoreException( () => DeliverErrorToConsumer( consumerData, exceptionOccured, batch)); // record that there was a delivery failure if (isDeliveryError) { await OrleansTaskExtentions.ExecuteAndIgnoreException( () => streamFailureHandler.OnDeliveryFailure( consumerData.SubscriptionId, streamProviderName, consumerData.StreamId, token)); } else { await OrleansTaskExtentions.ExecuteAndIgnoreException( () => streamFailureHandler.OnSubscriptionFailure( consumerData.SubscriptionId, streamProviderName, consumerData.StreamId, token)); } // if configured to fault on delivery failure and this is not an implicit subscription, fault and remove the subscription if (streamFailureHandler.ShouldFaultSubsriptionOnError && !SubscriptionMarker.IsImplicitSubscription(consumerData.SubscriptionId.Guid)) { try { // notify consumer of faulted subscription, if we can. await OrleansTaskExtentions.ExecuteAndIgnoreException( () => DeliverErrorToConsumer( consumerData, new FaultedSubscriptionException(consumerData.SubscriptionId, consumerData.StreamId), batch)); // mark subscription as faulted. await pubSub.FaultSubscription(consumerData.StreamId, consumerData.SubscriptionId); } finally { // remove subscription RemoveSubscriber_Impl(consumerData.SubscriptionId, consumerData.StreamId); } return true; } return false; } private static async Task<ISet<PubSubSubscriptionState>> PubsubRegisterProducer(IStreamPubSub pubSub, InternalStreamId streamId, IStreamProducerExtension meAsStreamProducer, ILogger logger) { try { var streamData = await pubSub.RegisterProducer(streamId, meAsStreamProducer); return streamData; } catch (Exception e) { logger.Error(ErrorCode.PersistentStreamPullingAgent_17, $"RegisterAsStreamProducer failed due to {e}", e); throw e; } } private async Task RegisterAsStreamProducer(InternalStreamId streamId, StreamSequenceToken streamStartToken) { try { if (pubSub == null) throw new NullReferenceException("Found pubSub reference not set up correctly in RetreaveNewStream"); IStreamProducerExtension meAsStreamProducer = this.AsReference<IStreamProducerExtension>(); ISet<PubSubSubscriptionState> streamData = null; await AsyncExecutorWithRetries.ExecuteWithRetries( async i => { streamData = await PubsubRegisterProducer(pubSub, streamId, meAsStreamProducer, logger); }, AsyncExecutorWithRetries.INFINITE_RETRIES, (exception, i) => !IsShutdown, Constants.INFINITE_TIMESPAN, DeliveryBackoffProvider); if (logger.IsEnabled(LogLevel.Debug)) logger.Debug(ErrorCode.PersistentStreamPullingAgent_16, "Got back {0} Subscribers for stream {1}.", streamData.Count, streamId); var addSubscriptionTasks = new List<Task>(streamData.Count); foreach (PubSubSubscriptionState item in streamData) { addSubscriptionTasks.Add(AddSubscriber_Impl(item.SubscriptionId, item.Stream, item.Consumer, streamStartToken)); } await Task.WhenAll(addSubscriptionTasks); } catch (Exception exc) { // RegisterAsStreamProducer is fired with .Ignore so we should log if anything goes wrong, because there is no one to catch the exception logger.Error(ErrorCode.PersistentStreamPullingAgent_17, "Ignored RegisterAsStreamProducer Error", exc); throw; } } } }
// Copyright (c) 2012 DotNetAnywhere // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #if !LOCALTEST using System.Runtime.CompilerServices; using System.Collections; using System.Collections.Generic; namespace System { public abstract class Array : ICloneable, IList, ICollection, IEnumerable { private class NonGenericEnumerator : IEnumerator { private Array array; private int index, length; public NonGenericEnumerator(Array array) { this.array = array; this.index = -1; this.length = array.length; } public object Current { get { if (index < 0) { throw new InvalidOperationException("Enumeration has not started"); } if (index >= length) { throw new InvalidOperationException("Enumeration has finished"); } return array.GetValue(index); } } public bool MoveNext() { index++; return (index < length); } public void Reset() { index = -1; } } private struct GenericEnumerator<T> : IEnumerator<T> { private Array array; private int index, length; public GenericEnumerator(Array array) { this.array = array; this.index = -1; this.length = array.length; } public T Current { get { if (index < 0) { throw new InvalidOperationException("Enumeration has not started"); } if (index >= length) { throw new InvalidOperationException("Enumeration has finished"); } return (T)array.GetValue(index); } } public void Dispose() { } object IEnumerator.Current { get { return this.Current; } } public bool MoveNext() { index++; return (index < length); } public void Reset() { this.index = -1; } } private Array() { } #region Generic interface methods // The name of these methods are important. They are directly referenced in the interpreter. private IEnumerator<T> Internal_GetGenericEnumerator<T>() { return new GenericEnumerator<T>(this); } private bool Internal_GenericIsReadOnly() { return true; } private void Internal_GenericAdd<T>(T item) { throw new NotSupportedException("Collection is read-only"); } private void Internal_GenericClear() { Array.Clear(this, 0, this.length); } private bool Internal_GenericContains<T>(T item) { return Array.IndexOf(this, (object)item) >= 0; } private void Internal_GenericCopyTo<T>(T[] array, int arrayIndex) { Array.Copy(this, 0, (Array)array, arrayIndex, this.length); } private bool Internal_GenericRemove<T>(T item) { throw new NotSupportedException("Collection is read-only"); } private int Internal_GenericIndexOf<T>(T item) { return IndexOf(this, (object)item); } private void Internal_GenericInsert<T>(int index, T item) { throw new NotSupportedException("List is read-only"); } private void Internal_GenericRemoveAt(int index) { throw new NotSupportedException("List is read-only"); } private T Internal_GenericGetItem<T>(int index) { return (T)GetValue(index); } private void Internal_GenericSetItem<T>(int index, T value) { SetValue((object)value, index); } #endregion // This must be the only field, as it ties up with the Array definition in DNA #pragma warning disable 0169, 0649 private int length; #pragma warning restore 0169, 0649 public int Length { get { return this.length; } } [MethodImpl(MethodImplOptions.InternalCall)] extern private object Internal_GetValue(int index); /// <summary> /// Returns true if the value set ok, returns false if the Type was wrong /// </summary> [MethodImpl(MethodImplOptions.InternalCall)] extern public bool Internal_SetValue(object value, int index); [MethodImpl(MethodImplOptions.InternalCall)] extern public static void Clear(Array array, int index, int length); [MethodImpl(MethodImplOptions.InternalCall)] extern private static bool Internal_Copy(Array src, int srcIndex, Array dst, int dstIndex, int length); [MethodImpl(MethodImplOptions.InternalCall)] extern public static void Resize<T>(ref T[] array, int newSize); [MethodImpl(MethodImplOptions.InternalCall)] extern public static void Reverse(Array array, int index, int length); public static void Reverse(Array array) { Reverse(array, 0, array.length); } public static int IndexOf(Array array, object value) { return IndexOf(array, value, 0, array.length); } public static int IndexOf(Array array, object value, int startIndex) { return IndexOf(array, value, startIndex, array.length - startIndex); } public static int IndexOf(Array array, object value, int startIndex, int count) { if (array == null) { throw new ArgumentNullException("array"); } int max = startIndex + count; if (startIndex < 0 || max > array.length) { throw new ArgumentOutOfRangeException(); } for (int i = startIndex; i < max; i++) { if (object.Equals(value, array.GetValue(i))) { return i; } } return -1; } public static void Copy(Array srcArray, int srcIndex, Array dstArray, int dstIndex, int length) { if (srcArray == null || dstArray == null) { throw new ArgumentNullException((srcArray == null) ? "sourceArray" : "destinationArray"); } if (srcIndex < 0 || dstIndex < 0 || length < 0) { throw new ArgumentOutOfRangeException(); } if (srcIndex + length > srcArray.length || dstIndex + length > dstArray.length) { throw new ArgumentException(); } if (Internal_Copy(srcArray, srcIndex, dstArray, dstIndex, length)) { // When src element type can always be cast to dst element type, then can do a really fast copy. return; } int start, inc, end; // Need to make sure it works even if both arrays are the same if (dstIndex > srcIndex) { start = 0; inc = 1; end = length; } else { start = length - 1; inc = -1; end = -1; } for (int i = start; i != end; i += inc) { object item = srcArray.GetValue(srcIndex + i); dstArray.SetValue(item, dstIndex + i); } } public static void Copy(Array srcArray, Array dstArray, int length) { Copy(srcArray, 0, dstArray, 0, length); } public static int IndexOf<T>(T[] array, T value) { return IndexOf((Array)array, (object)value); } public static int IndexOf<T>(T[] array, T value, int startIndex) { return IndexOf((Array)array, (object)value, startIndex); } public static int IndexOf<T>(T[] array, T value, int startIndex, int count) { return IndexOf((Array)array, (object)value, startIndex, count); } public object GetValue(int index) { if (index < 0 || index >= this.length) { throw new IndexOutOfRangeException(); } return Internal_GetValue(index); } public void SetValue(object value, int index) { if (index < 0 || index >= this.length) { throw new IndexOutOfRangeException(); } if (!Internal_SetValue(value, index)) { throw new InvalidCastException(); } } public int Rank { get { return 1; } } public int GetLength(int dimension) { if (dimension != 0) { throw new IndexOutOfRangeException(); } return this.length; } public int GetLowerBound(int dimension) { if (dimension != 0) { throw new IndexOutOfRangeException(); } return 0; } public int GetUpperBound(int dimension) { if (dimension != 0) { throw new IndexOutOfRangeException(); } return this.length - 1; } public static TOutput[] ConvertAll<TInput, TOutput>(TInput[] array, Converter<TInput, TOutput> converter) { if (array == null) { throw new ArgumentNullException("array"); } if (converter == null) { throw new ArgumentNullException("converter"); } TOutput[] output = new TOutput[array.Length]; int arrayLen = array.Length; for (int i = 0; i < arrayLen; i++) { output[i] = converter(array[i]); } return output; } #region Interface Members public object Clone() { return object.Clone(this); } public bool IsFixedSize { get { return true; } } public bool IsReadOnly { get { return false; } } object IList.this[int index] { get { if (index < 0 || index >= this.length) { throw new ArgumentOutOfRangeException("index"); } return GetValue(index); } set { if (index < 0 || index >= this.length) { throw new ArgumentOutOfRangeException("index"); } SetValue(value, index); } } int IList.Add(object value) { throw new NotSupportedException("Collection is read-only"); } void IList.Clear() { Array.Clear(this, 0, this.length); } bool IList.Contains(object value) { return (IndexOf(this, value) >= 0); } int IList.IndexOf(object value) { return IndexOf(this, value); } void IList.Insert(int index, object value) { throw new NotSupportedException("Collection is read-only"); } void IList.Remove(object value) { throw new NotSupportedException("Collection is read-only"); } void IList.RemoveAt(int index) { throw new NotSupportedException("Collection is read-only"); } int ICollection.Count { get { return this.length; } } public bool IsSynchronized { get { return false; } } public object SyncRoot { get { return this; } } public void CopyTo(Array array, int index) { Copy(this, 0, array, index, this.length); } public IEnumerator GetEnumerator() { return new NonGenericEnumerator(this); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } #endregion } } #endif
// <copyright file="DiagonalMatrixTests.cs" company="Math.NET"> // Math.NET Numerics, part of the Math.NET Project // http://numerics.mathdotnet.com // http://github.com/mathnet/mathnet-numerics // // Copyright (c) 2009-2016 Math.NET // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. // </copyright> using System; using System.Collections.Generic; using MathNet.Numerics.Distributions; using MathNet.Numerics.LinearAlgebra; using MathNet.Numerics.LinearAlgebra.Double; using MathNet.Numerics.Random; using NUnit.Framework; namespace MathNet.Numerics.UnitTests.LinearAlgebraTests.Double { /// <summary> /// Diagonal matrix tests. /// </summary> public class DiagonalMatrixTests : MatrixTests { /// <summary> /// Setup test matrices. /// </summary> [SetUp] public override void SetupMatrices() { TestData2D = new Dictionary<string, double[,]> { {"Singular3x3", new[,] {{1.0, 0.0, 0.0}, {0.0, 0.0, 0.0}, {0.0, 0.0, 3.0}}}, {"Square3x3", new[,] {{-1.1, 0.0, 0.0}, {0.0, 1.1, 0.0}, {0.0, 0.0, 6.6}}}, {"Square4x4", new[,] {{-1.1, 0.0, 0.0, 0.0}, {0.0, 1.1, 0.0, 0.0}, {0.0, 0.0, 6.2, 0.0}, {0.0, 0.0, 0.0, -7.7}}}, {"Singular4x4", new[,] {{-1.1, 0.0, 0.0, 0.0}, {0.0, -2.2, 0.0, 0.0}, {0.0, 0.0, 0.0, 0.0}, {0.0, 0.0, 0.0, -4.4}}}, {"Tall3x2", new[,] {{-1.1, 0.0}, {0.0, 1.1}, {0.0, 0.0}}}, {"Wide2x3", new[,] {{-1.1, 0.0, 0.0}, {0.0, 1.1, 0.0}}} }; TestMatrices = new Dictionary<string, Matrix<double>>(); foreach (var name in TestData2D.Keys) { TestMatrices.Add(name, DiagonalMatrix.OfArray(TestData2D[name])); } } /// <summary> /// Creates a matrix for the given number of rows and columns. /// </summary> /// <param name="rows">The number of rows.</param> /// <param name="columns">The number of columns.</param> /// <returns>A matrix with the given dimensions.</returns> protected override Matrix<double> CreateMatrix(int rows, int columns) { return Matrix<double>.Build.Diagonal(rows, columns); } /// <summary> /// Creates a matrix from a 2D array. /// </summary> /// <param name="data">The 2D array to create this matrix from.</param> /// <returns>A matrix with the given values.</returns> protected override Matrix<double> CreateMatrix(double[,] data) { return DiagonalMatrix.OfArray(data); } /// <summary> /// Can create a matrix from a diagonal array. /// </summary> [Test] public void CanCreateMatrixFromDiagonalArray() { var testData = new Dictionary<string, Matrix<double>> { {"Singular3x3", new DiagonalMatrix(3, 3, new[] {1.0, 0.0, 3.0})}, {"Square3x3", new DiagonalMatrix(3, 3, new[] {-1.1, 1.1, 6.6})}, {"Square4x4", new DiagonalMatrix(4, 4, new[] {-1.1, 1.1, 6.2, -7.7})}, {"Tall3x2", new DiagonalMatrix(3, 2, new[] {-1.1, 1.1})}, {"Wide2x3", new DiagonalMatrix(2, 3, new[] {-1.1, 1.1})}, }; foreach (var name in testData.Keys) { Assert.That(testData[name], Is.EqualTo(TestMatrices[name])); } } /// <summary> /// Matrix from array is a reference. /// </summary> [Test] public void MatrixFrom1DArrayIsReference() { var data = new double[] {1, 2, 3, 4, 5}; var matrix = new DiagonalMatrix(5, 5, data); matrix[0, 0] = 10.0; Assert.AreEqual(10.0, data[0]); } /// <summary> /// Can create a matrix from two-dimensional array. /// </summary> /// <param name="name">Matrix name.</param> [TestCase("Singular3x3")] [TestCase("Singular4x4")] [TestCase("Square3x3")] [TestCase("Square4x4")] [TestCase("Tall3x2")] [TestCase("Wide2x3")] public void CanCreateMatrixFrom2DArray(string name) { var matrix = DiagonalMatrix.OfArray(TestData2D[name]); for (var i = 0; i < TestData2D[name].GetLength(0); i++) { for (var j = 0; j < TestData2D[name].GetLength(1); j++) { Assert.AreEqual(TestData2D[name][i, j], matrix[i, j]); } } } /// <summary> /// Can create a matrix with uniform values. /// </summary> [Test] public void CanCreateMatrixWithUniformValues() { var matrix = new DiagonalMatrix(10, 10, 10.0); for (var i = 0; i < matrix.RowCount; i++) { Assert.AreEqual(matrix[i, i], 10.0); } } /// <summary> /// Can create an identity matrix. /// </summary> [Test] public void CanCreateIdentity() { var matrix = Matrix<double>.Build.DiagonalIdentity(5); Assert.That(matrix, Is.TypeOf<DiagonalMatrix>()); for (var i = 0; i < matrix.RowCount; i++) { for (var j = 0; j < matrix.ColumnCount; j++) { Assert.AreEqual(i == j ? 1.0 : 0.0, matrix[i, j]); } } } /// <summary> /// Identity with wrong order throws <c>ArgumentOutOfRangeException</c>. /// </summary> /// <param name="order">The size of the square matrix</param> [TestCase(0)] [TestCase(-1)] public void IdentityWithWrongOrderThrowsArgumentOutOfRangeException(int order) { Assert.That(() => Matrix<double>.Build.DiagonalIdentity(order), Throws.TypeOf<ArgumentOutOfRangeException>()); } /// <summary> /// Can multiply a matrix with matrix. /// </summary> /// <param name="nameA">Matrix A name.</param> /// <param name="nameB">Matrix B name.</param> public override void CanMultiplyMatrixWithMatrixIntoResult(string nameA, string nameB) { var matrixA = TestMatrices[nameA]; var matrixB = TestMatrices[nameB]; var matrixC = Matrix<double>.Build.Sparse(matrixA.RowCount, matrixB.ColumnCount); matrixA.Multiply(matrixB, matrixC); Assert.AreEqual(matrixC.RowCount, matrixA.RowCount); Assert.AreEqual(matrixC.ColumnCount, matrixB.ColumnCount); for (var i = 0; i < matrixC.RowCount; i++) { for (var j = 0; j < matrixC.ColumnCount; j++) { AssertHelpers.AlmostEqualRelative(matrixA.Row(i)*matrixB.Column(j), matrixC[i, j], 15); } } } /// <summary> /// Permute matrix rows throws <c>InvalidOperationException</c>. /// </summary> [Test] public void PermuteMatrixRowsThrowsInvalidOperationException() { var matrixp = DiagonalMatrix.OfArray(TestData2D["Singular3x3"]); var permutation = new Permutation(new[] {2, 0, 1}); Assert.That(() => matrixp.PermuteRows(permutation), Throws.InvalidOperationException); } /// <summary> /// Permute matrix columns throws <c>InvalidOperationException</c>. /// </summary> [Test] public void PermuteMatrixColumnsThrowsInvalidOperationException() { var matrixp = DiagonalMatrix.OfArray(TestData2D["Singular3x3"]); var permutation = new Permutation(new[] {2, 0, 1}); Assert.That(() => matrixp.PermuteColumns(permutation), Throws.InvalidOperationException); } /// <summary> /// Can pointwise divide matrices into a result matrix. /// </summary> public override void CanPointwiseDivideIntoResult() { foreach (var data in TestMatrices.Values) { var other = data.Clone(); var result = data.Clone(); data.PointwiseDivide(other, result); var min = Math.Min(data.RowCount, data.ColumnCount); for (var i = 0; i < min; i++) { Assert.AreEqual(data[i, i]/other[i, i], result[i, i]); } result = data.PointwiseDivide(other); for (var i = 0; i < min; i++) { Assert.AreEqual(data[i, i]/other[i, i], result[i, i]); } } } /// <summary> /// Can compute Frobenius norm. /// </summary> public override void CanComputeFrobeniusNorm() { var matrix = TestMatrices["Square3x3"]; var denseMatrix = Matrix<double>.Build.DenseOfArray(TestData2D["Square3x3"]); AssertHelpers.AlmostEqualRelative(denseMatrix.FrobeniusNorm(), matrix.FrobeniusNorm(), 14); matrix = TestMatrices["Wide2x3"]; denseMatrix = Matrix<double>.Build.DenseOfArray(TestData2D["Wide2x3"]); AssertHelpers.AlmostEqualRelative(denseMatrix.FrobeniusNorm(), matrix.FrobeniusNorm(), 14); matrix = TestMatrices["Tall3x2"]; denseMatrix = Matrix<double>.Build.DenseOfArray(TestData2D["Tall3x2"]); AssertHelpers.AlmostEqualRelative(denseMatrix.FrobeniusNorm(), matrix.FrobeniusNorm(), 14); } /// <summary> /// Can compute Infinity norm. /// </summary> public override void CanComputeInfinityNorm() { var matrix = TestMatrices["Square3x3"]; var denseMatrix = Matrix<double>.Build.DenseOfArray(TestData2D["Square3x3"]); AssertHelpers.AlmostEqualRelative(denseMatrix.InfinityNorm(), matrix.InfinityNorm(), 14); matrix = TestMatrices["Wide2x3"]; denseMatrix = Matrix<double>.Build.DenseOfArray(TestData2D["Wide2x3"]); AssertHelpers.AlmostEqualRelative(denseMatrix.InfinityNorm(), matrix.InfinityNorm(), 14); matrix = TestMatrices["Tall3x2"]; denseMatrix = Matrix<double>.Build.DenseOfArray(TestData2D["Tall3x2"]); AssertHelpers.AlmostEqualRelative(denseMatrix.InfinityNorm(), matrix.InfinityNorm(), 14); } /// <summary> /// Can compute L1 norm. /// </summary> public override void CanComputeL1Norm() { var matrix = TestMatrices["Square3x3"]; var denseMatrix = Matrix<double>.Build.DenseOfArray(TestData2D["Square3x3"]); AssertHelpers.AlmostEqualRelative(denseMatrix.L1Norm(), matrix.L1Norm(), 14); matrix = TestMatrices["Wide2x3"]; denseMatrix = Matrix<double>.Build.DenseOfArray(TestData2D["Wide2x3"]); AssertHelpers.AlmostEqualRelative(denseMatrix.L1Norm(), matrix.L1Norm(), 14); matrix = TestMatrices["Tall3x2"]; denseMatrix = Matrix<double>.Build.DenseOfArray(TestData2D["Tall3x2"]); AssertHelpers.AlmostEqualRelative(denseMatrix.L1Norm(), matrix.L1Norm(), 14); } /// <summary> /// Can compute L2 norm. /// </summary> public override void CanComputeL2Norm() { var matrix = TestMatrices["Square3x3"]; var denseMatrix = Matrix<double>.Build.DenseOfArray(TestData2D["Square3x3"]); AssertHelpers.AlmostEqualRelative(denseMatrix.L2Norm(), matrix.L2Norm(), 14); matrix = TestMatrices["Wide2x3"]; denseMatrix = Matrix<double>.Build.DenseOfArray(TestData2D["Wide2x3"]); AssertHelpers.AlmostEqualRelative(denseMatrix.L2Norm(), matrix.L2Norm(), 14); matrix = TestMatrices["Tall3x2"]; denseMatrix = Matrix<double>.Build.DenseOfArray(TestData2D["Tall3x2"]); AssertHelpers.AlmostEqualRelative(denseMatrix.L2Norm(), matrix.L2Norm(), 14); } /// <summary> /// Can compute determinant. /// </summary> [Test] public void CanComputeDeterminant() { var matrix = TestMatrices["Square3x3"]; var denseMatrix = Matrix<double>.Build.DenseOfArray(TestData2D["Square3x3"]); AssertHelpers.AlmostEqualRelative(denseMatrix.Determinant(), matrix.Determinant(), 14); matrix = TestMatrices["Square4x4"]; denseMatrix = Matrix<double>.Build.DenseOfArray(TestData2D["Square4x4"]); AssertHelpers.AlmostEqualRelative(denseMatrix.Determinant(), matrix.Determinant(), 14); } /// <summary> /// Determinant of non-square matrix throws <c>ArgumentException</c>. /// </summary> [Test] public void DeterminantNotSquareMatrixThrowsArgumentException() { var matrix = TestMatrices["Tall3x2"]; Assert.That(() => matrix.Determinant(), Throws.ArgumentException); } /// <summary> /// Can check if a matrix is symmetric. /// </summary> [Test] public override void CanCheckIfMatrixIsSymmetric() { var matrix = TestMatrices["Square3x3"]; Assert.IsTrue(matrix.IsSymmetric()); } [Test] public void CanGetSubMatrix_Issue35() { // [ 1 0 0 ] // [ 0 2 0 ] // [ 0 0 3 ] var diagMatrix = new DiagonalMatrix(3); for (int i = 0; i < 3; i++) { diagMatrix[i, i] = i + 1; } // [ 0 0 ] // [ 2 0 ] var subM2 = diagMatrix.SubMatrix(0, 2, 1, 2); Assert.IsTrue(subM2.Equals(Matrix<double>.Build.Dense(2, 2, new[] { 0d, 2d, 0d, 0d }))); // [ 0 0 ] // [ 2 0 ] // [ 0 3 ] var subM3 = diagMatrix.SubMatrix(0, 3, 1, 2); Assert.IsTrue(subM3.Equals(Matrix<double>.Build.Dense(3, 2, new[] { 0d, 2d, 0d, 0d, 0d, 3d }))); } [Test] public void DiagonalDenseMatrixMultiplication_IssueCP5706() { Matrix<double> diagonal = Matrix<double>.Build.DiagonalIdentity(3); Matrix<double> dense = Matrix<double>.Build.DenseOfArray(new double[,] { { 1, 2, 3 }, { 1, 2, 3 }, { 1, 2, 3 } }); var test = diagonal*dense; var test2 = dense*diagonal; } [Test] public void DenseDiagonalMatrixMultiply() { var dist = new ContinuousUniform(-1.0, 1.0, new SystemRandomSource(1)); Assert.IsInstanceOf<DiagonalMatrix>(Matrix<double>.Build.DiagonalIdentity(3, 3)); var tall = Matrix<double>.Build.Random(8, 3, dist); Assert.IsTrue((tall*Matrix<double>.Build.DiagonalIdentity(3).Multiply(2d)).Equals(tall.Multiply(2d))); Assert.IsTrue((tall*Matrix<double>.Build.Diagonal(3, 5, 2d)).Equals(tall.Multiply(2d).Append(Matrix<double>.Build.Dense(8, 2)))); Assert.IsTrue((tall*Matrix<double>.Build.Diagonal(3, 2, 2d)).Equals(tall.Multiply(2d).SubMatrix(0, 8, 0, 2))); var wide = Matrix<double>.Build.Random(3, 8, dist); Assert.IsTrue((wide*Matrix<double>.Build.DiagonalIdentity(8).Multiply(2d)).Equals(wide.Multiply(2d))); Assert.IsTrue((wide*Matrix<double>.Build.Diagonal(8, 10, 2d)).Equals(wide.Multiply(2d).Append(Matrix<double>.Build.Dense(3, 2)))); Assert.IsTrue((wide*Matrix<double>.Build.Diagonal(8, 2, 2d)).Equals(wide.Multiply(2d).SubMatrix(0, 3, 0, 2))); } [Test] public void DenseDiagonalMatrixTransposeAndMultiply() { var dist = new ContinuousUniform(-1.0, 1.0, new SystemRandomSource(1)); Assert.IsInstanceOf<DiagonalMatrix>(Matrix<double>.Build.DiagonalIdentity(3, 3)); var tall = Matrix<double>.Build.Random(8, 3, dist); Assert.IsTrue(tall.TransposeAndMultiply(Matrix<double>.Build.DiagonalIdentity(3).Multiply(2d)).Equals(tall.Multiply(2d))); Assert.IsTrue(tall.TransposeAndMultiply(Matrix<double>.Build.Diagonal(5, 3, 2d)).Equals(tall.Multiply(2d).Append(Matrix<double>.Build.Dense(8, 2)))); Assert.IsTrue(tall.TransposeAndMultiply(Matrix<double>.Build.Diagonal(2, 3, 2d)).Equals(tall.Multiply(2d).SubMatrix(0, 8, 0, 2))); var wide = Matrix<double>.Build.Random(3, 8, dist); Assert.IsTrue(wide.TransposeAndMultiply(Matrix<double>.Build.DiagonalIdentity(8).Multiply(2d)).Equals(wide.Multiply(2d))); Assert.IsTrue(wide.TransposeAndMultiply(Matrix<double>.Build.Diagonal(10, 8, 2d)).Equals(wide.Multiply(2d).Append(Matrix<double>.Build.Dense(3, 2)))); Assert.IsTrue(wide.TransposeAndMultiply(Matrix<double>.Build.Diagonal(2, 8, 2d)).Equals(wide.Multiply(2d).SubMatrix(0, 3, 0, 2))); } [Test] public void DenseDiagonalMatrixTransposeThisAndMultiply() { var dist = new ContinuousUniform(-1.0, 1.0, new SystemRandomSource(1)); Assert.IsInstanceOf<DiagonalMatrix>(Matrix<double>.Build.DiagonalIdentity(3, 3)); var wide = Matrix<double>.Build.Random(3, 8, dist); Assert.IsTrue(wide.TransposeThisAndMultiply(Matrix<double>.Build.DiagonalIdentity(3).Multiply(2d)).Equals(wide.Transpose().Multiply(2d))); Assert.IsTrue(wide.TransposeThisAndMultiply(Matrix<double>.Build.Diagonal(3, 5, 2d)).Equals(wide.Transpose().Multiply(2d).Append(Matrix<double>.Build.Dense(8, 2)))); Assert.IsTrue(wide.TransposeThisAndMultiply(Matrix<double>.Build.Diagonal(3, 2, 2d)).Equals(wide.Transpose().Multiply(2d).SubMatrix(0, 8, 0, 2))); var tall = Matrix<double>.Build.Random(8, 3, dist); Assert.IsTrue(tall.TransposeThisAndMultiply(Matrix<double>.Build.DiagonalIdentity(8).Multiply(2d)).Equals(tall.Transpose().Multiply(2d))); Assert.IsTrue(tall.TransposeThisAndMultiply(Matrix<double>.Build.Diagonal(8, 10, 2d)).Equals(tall.Transpose().Multiply(2d).Append(Matrix<double>.Build.Dense(3, 2)))); Assert.IsTrue(tall.TransposeThisAndMultiply(Matrix<double>.Build.Diagonal(8, 2, 2d)).Equals(tall.Transpose().Multiply(2d).SubMatrix(0, 3, 0, 2))); } [Test] public void DiagonalDenseMatrixMultiply() { var dist = new ContinuousUniform(-1.0, 1.0, new SystemRandomSource(1)); Assert.IsInstanceOf<DiagonalMatrix>(Matrix<double>.Build.DiagonalIdentity(3, 3)); var wide = Matrix<double>.Build.Random(3, 8, dist); Assert.IsTrue((Matrix<double>.Build.DiagonalIdentity(3).Multiply(2d)*wide).Equals(wide.Multiply(2d))); Assert.IsTrue((Matrix<double>.Build.Diagonal(5, 3, 2d)*wide).Equals(wide.Multiply(2d).Stack(Matrix<double>.Build.Dense(2, 8)))); Assert.IsTrue((Matrix<double>.Build.Diagonal(2, 3, 2d)*wide).Equals(wide.Multiply(2d).SubMatrix(0, 2, 0, 8))); var tall = Matrix<double>.Build.Random(8, 3, dist); Assert.IsTrue((Matrix<double>.Build.DiagonalIdentity(8).Multiply(2d)*tall).Equals(tall.Multiply(2d))); Assert.IsTrue((Matrix<double>.Build.Diagonal(10, 8, 2d)*tall).Equals(tall.Multiply(2d).Stack(Matrix<double>.Build.Dense(2, 3)))); Assert.IsTrue((Matrix<double>.Build.Diagonal(2, 8, 2d)*tall).Equals(tall.Multiply(2d).SubMatrix(0, 2, 0, 3))); } [Test] public void DiagonalDenseMatrixTransposeAndMultiply() { var dist = new ContinuousUniform(-1.0, 1.0, new SystemRandomSource(1)); Assert.IsInstanceOf<DiagonalMatrix>(Matrix<double>.Build.DiagonalIdentity(3, 3)); var tall = Matrix<double>.Build.Random(8, 3, dist); Assert.IsTrue(Matrix<double>.Build.DiagonalIdentity(3).Multiply(2d).TransposeAndMultiply(tall).Equals(tall.Multiply(2d).Transpose())); Assert.IsTrue(Matrix<double>.Build.Diagonal(5, 3, 2d).TransposeAndMultiply(tall).Equals(tall.Multiply(2d).Append(Matrix<double>.Build.Dense(8, 2)).Transpose())); Assert.IsTrue(Matrix<double>.Build.Diagonal(2, 3, 2d).TransposeAndMultiply(tall).Equals(tall.Multiply(2d).SubMatrix(0, 8, 0, 2).Transpose())); var wide = Matrix<double>.Build.Random(3, 8, dist); Assert.IsTrue(Matrix<double>.Build.DiagonalIdentity(8).Multiply(2d).TransposeAndMultiply(wide).Equals(wide.Multiply(2d).Transpose())); Assert.IsTrue(Matrix<double>.Build.Diagonal(10, 8, 2d).TransposeAndMultiply(wide).Equals(wide.Multiply(2d).Append(Matrix<double>.Build.Dense(3, 2)).Transpose())); Assert.IsTrue(Matrix<double>.Build.Diagonal(2, 8, 2d).TransposeAndMultiply(wide).Equals(wide.Multiply(2d).SubMatrix(0, 3, 0, 2).Transpose())); } [Test] public void DiagonalDenseMatrixTransposeThisAndMultiply() { var dist = new ContinuousUniform(-1.0, 1.0, new SystemRandomSource(1)); Assert.IsInstanceOf<DiagonalMatrix>(Matrix<double>.Build.DiagonalIdentity(3, 3)); var wide = Matrix<double>.Build.Random(3, 8, dist); Assert.IsTrue((Matrix<double>.Build.DiagonalIdentity(3).Multiply(2d).TransposeThisAndMultiply(wide)).Equals(wide.Multiply(2d))); Assert.IsTrue((Matrix<double>.Build.Diagonal(3, 5, 2d).TransposeThisAndMultiply(wide)).Equals(wide.Multiply(2d).Stack(Matrix<double>.Build.Dense(2, 8)))); Assert.IsTrue((Matrix<double>.Build.Diagonal(3, 2, 2d).TransposeThisAndMultiply(wide)).Equals(wide.Multiply(2d).SubMatrix(0, 2, 0, 8))); var tall = Matrix<double>.Build.Random(8, 3, dist); Assert.IsTrue((Matrix<double>.Build.DiagonalIdentity(8).Multiply(2d).TransposeThisAndMultiply(tall)).Equals(tall.Multiply(2d))); Assert.IsTrue((Matrix<double>.Build.Diagonal(8, 10, 2d).TransposeThisAndMultiply(tall)).Equals(tall.Multiply(2d).Stack(Matrix<double>.Build.Dense(2, 3)))); Assert.IsTrue((Matrix<double>.Build.Diagonal(8, 2, 2d).TransposeThisAndMultiply(tall)).Equals(tall.Multiply(2d).SubMatrix(0, 2, 0, 3))); } } }
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the lambda-2015-03-31.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.Lambda.Model { /// <summary> /// A complex type that describes function metadata. /// </summary> public partial class GetFunctionConfigurationResponse : AmazonWebServiceResponse { private long? _codeSize; private string _description; private string _functionArn; private string _functionName; private string _handler; private string _lastModified; private int? _memorySize; private string _role; private Runtime _runtime; private int? _timeout; /// <summary> /// Gets and sets the property CodeSize. /// <para> /// The size, in bytes, of the function .zip file you uploaded. /// </para> /// </summary> public long CodeSize { get { return this._codeSize.GetValueOrDefault(); } set { this._codeSize = value; } } // Check to see if CodeSize property is set internal bool IsSetCodeSize() { return this._codeSize.HasValue; } /// <summary> /// Gets and sets the property Description. /// <para> /// The user-provided description. /// </para> /// </summary> public string Description { get { return this._description; } set { this._description = value; } } // Check to see if Description property is set internal bool IsSetDescription() { return this._description != null; } /// <summary> /// Gets and sets the property FunctionArn. /// <para> /// The Amazon Resource Name (ARN) assigned to the function. /// </para> /// </summary> public string FunctionArn { get { return this._functionArn; } set { this._functionArn = value; } } // Check to see if FunctionArn property is set internal bool IsSetFunctionArn() { return this._functionArn != null; } /// <summary> /// Gets and sets the property FunctionName. /// <para> /// The name of the function. /// </para> /// </summary> public string FunctionName { get { return this._functionName; } set { this._functionName = value; } } // Check to see if FunctionName property is set internal bool IsSetFunctionName() { return this._functionName != null; } /// <summary> /// Gets and sets the property Handler. /// <para> /// The function Lambda calls to begin executing your function. /// </para> /// </summary> public string Handler { get { return this._handler; } set { this._handler = value; } } // Check to see if Handler property is set internal bool IsSetHandler() { return this._handler != null; } /// <summary> /// Gets and sets the property LastModified. /// <para> /// The timestamp of the last time you updated the function. /// </para> /// </summary> public string LastModified { get { return this._lastModified; } set { this._lastModified = value; } } // Check to see if LastModified property is set internal bool IsSetLastModified() { return this._lastModified != null; } /// <summary> /// Gets and sets the property MemorySize. /// <para> /// The memory size, in MB, you configured for the function. Must be a multiple of 64 /// MB. /// </para> /// </summary> public int MemorySize { get { return this._memorySize.GetValueOrDefault(); } set { this._memorySize = value; } } // Check to see if MemorySize property is set internal bool IsSetMemorySize() { return this._memorySize.HasValue; } /// <summary> /// Gets and sets the property Role. /// <para> /// The Amazon Resource Name (ARN) of the IAM role that Lambda assumes when it executes /// your function to access any other Amazon Web Services (AWS) resources. /// </para> /// </summary> public string Role { get { return this._role; } set { this._role = value; } } // Check to see if Role property is set internal bool IsSetRole() { return this._role != null; } /// <summary> /// Gets and sets the property Runtime. /// <para> /// The runtime environment for the Lambda function. /// </para> /// </summary> public Runtime Runtime { get { return this._runtime; } set { this._runtime = value; } } // Check to see if Runtime property is set internal bool IsSetRuntime() { return this._runtime != null; } /// <summary> /// Gets and sets the property Timeout. /// <para> /// The function execution time at which Lambda should terminate the function. Because /// the execution time has cost implications, we recommend you set this value based on /// your expected execution time. The default is 3 seconds. /// </para> /// </summary> public int Timeout { get { return this._timeout.GetValueOrDefault(); } set { this._timeout = value; } } // Check to see if Timeout property is set internal bool IsSetTimeout() { return this._timeout.HasValue; } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using log4net; using System; using System.Collections.Generic; using System.IO; using System.Reflection; using Nini.Config; using OpenSim.Framework; using OpenSim.Framework.Communications; using OpenSim.Framework.Servers.HttpServer; using OpenSim.Services.Interfaces; using GridRegion = OpenSim.Services.Interfaces.GridRegion; using OpenSim.Server.Base; using OpenMetaverse; namespace OpenSim.Services.Connectors { public class PresenceServicesConnector : IPresenceService { private static readonly ILog m_log = LogManager.GetLogger( MethodBase.GetCurrentMethod().DeclaringType); private string m_ServerURI = String.Empty; public PresenceServicesConnector() { } public PresenceServicesConnector(string serverURI) { m_ServerURI = serverURI.TrimEnd('/'); } public PresenceServicesConnector(IConfigSource source) { Initialise(source); } public virtual void Initialise(IConfigSource source) { IConfig gridConfig = source.Configs["PresenceService"]; if (gridConfig == null) { m_log.Error("[PRESENCE CONNECTOR]: PresenceService missing from OpenSim.ini"); throw new Exception("Presence connector init error"); } string serviceURI = gridConfig.GetString("PresenceServerURI", String.Empty); if (serviceURI == String.Empty) { m_log.Error("[PRESENCE CONNECTOR]: No Server URI named in section PresenceService"); throw new Exception("Presence connector init error"); } m_ServerURI = serviceURI; } #region IPresenceService public bool LoginAgent(string userID, UUID sessionID, UUID secureSessionID) { Dictionary<string, object> sendData = new Dictionary<string, object>(); //sendData["SCOPEID"] = scopeID.ToString(); sendData["VERSIONMIN"] = ProtocolVersions.ClientProtocolVersionMin.ToString(); sendData["VERSIONMAX"] = ProtocolVersions.ClientProtocolVersionMax.ToString(); sendData["METHOD"] = "login"; sendData["UserID"] = userID; sendData["SessionID"] = sessionID.ToString(); sendData["SecureSessionID"] = secureSessionID.ToString(); string reqString = ServerUtils.BuildQueryString(sendData); // m_log.DebugFormat("[PRESENCE CONNECTOR]: queryString = {0}", reqString); try { string reply = SynchronousRestFormsRequester.MakeRequest("POST", m_ServerURI + "/presence", reqString); if (reply != string.Empty) { Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply); if (replyData.ContainsKey("result")) { if (replyData["result"].ToString().ToLower() == "success") return true; else return false; } else m_log.DebugFormat("[PRESENCE CONNECTOR]: LoginAgent reply data does not contain result field"); } else m_log.DebugFormat("[PRESENCE CONNECTOR]: LoginAgent received empty reply"); } catch (Exception e) { m_log.DebugFormat("[PRESENCE CONNECTOR]: Exception when contacting presence server: {0}", e.Message); } return false; } public bool LogoutAgent(UUID sessionID) { Dictionary<string, object> sendData = new Dictionary<string, object>(); //sendData["SCOPEID"] = scopeID.ToString(); sendData["VERSIONMIN"] = ProtocolVersions.ClientProtocolVersionMin.ToString(); sendData["VERSIONMAX"] = ProtocolVersions.ClientProtocolVersionMax.ToString(); sendData["METHOD"] = "logout"; sendData["SessionID"] = sessionID.ToString(); string reqString = ServerUtils.BuildQueryString(sendData); // m_log.DebugFormat("[PRESENCE CONNECTOR]: queryString = {0}", reqString); try { string reply = SynchronousRestFormsRequester.MakeRequest("POST", m_ServerURI + "/presence", reqString); if (reply != string.Empty) { Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply); if (replyData.ContainsKey("result")) { if (replyData["result"].ToString().ToLower() == "success") return true; else return false; } else m_log.DebugFormat("[PRESENCE CONNECTOR]: LogoutAgent reply data does not contain result field"); } else m_log.DebugFormat("[PRESENCE CONNECTOR]: LogoutAgent received empty reply"); } catch (Exception e) { m_log.DebugFormat("[PRESENCE CONNECTOR]: Exception when contacting presence server: {0}", e.Message); } return false; } public bool LogoutRegionAgents(UUID regionID) { Dictionary<string, object> sendData = new Dictionary<string, object>(); //sendData["SCOPEID"] = scopeID.ToString(); sendData["VERSIONMIN"] = ProtocolVersions.ClientProtocolVersionMin.ToString(); sendData["VERSIONMAX"] = ProtocolVersions.ClientProtocolVersionMax.ToString(); sendData["METHOD"] = "logoutregion"; sendData["RegionID"] = regionID.ToString(); string reqString = ServerUtils.BuildQueryString(sendData); // m_log.DebugFormat("[PRESENCE CONNECTOR]: queryString = {0}", reqString); try { string reply = SynchronousRestFormsRequester.MakeRequest("POST", m_ServerURI + "/presence", reqString); if (reply != string.Empty) { Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply); if (replyData.ContainsKey("result")) { if (replyData["result"].ToString().ToLower() == "success") return true; else return false; } else m_log.DebugFormat("[PRESENCE CONNECTOR]: LogoutRegionAgents reply data does not contain result field"); } else m_log.DebugFormat("[PRESENCE CONNECTOR]: LogoutRegionAgents received empty reply"); } catch (Exception e) { m_log.DebugFormat("[PRESENCE CONNECTOR]: Exception when contacting presence server: {0}", e.Message); } return false; } public bool ReportAgent(UUID sessionID, UUID regionID) { Dictionary<string, object> sendData = new Dictionary<string, object>(); //sendData["SCOPEID"] = scopeID.ToString(); sendData["VERSIONMIN"] = ProtocolVersions.ClientProtocolVersionMin.ToString(); sendData["VERSIONMAX"] = ProtocolVersions.ClientProtocolVersionMax.ToString(); sendData["METHOD"] = "report"; sendData["SessionID"] = sessionID.ToString(); sendData["RegionID"] = regionID.ToString(); string reqString = ServerUtils.BuildQueryString(sendData); // m_log.DebugFormat("[PRESENCE CONNECTOR]: queryString = {0}", reqString); try { string reply = SynchronousRestFormsRequester.MakeRequest("POST", m_ServerURI + "/presence", reqString); if (reply != string.Empty) { Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply); if (replyData.ContainsKey("result")) { if (replyData["result"].ToString().ToLower() == "success") return true; else return false; } else m_log.DebugFormat("[PRESENCE CONNECTOR]: ReportAgent reply data does not contain result field"); } else m_log.DebugFormat("[PRESENCE CONNECTOR]: ReportAgent received empty reply"); } catch (Exception e) { m_log.DebugFormat("[PRESENCE CONNECTOR]: Exception when contacting presence server: {0}", e.Message); } return false; } public PresenceInfo GetAgent(UUID sessionID) { Dictionary<string, object> sendData = new Dictionary<string, object>(); //sendData["SCOPEID"] = scopeID.ToString(); sendData["VERSIONMIN"] = ProtocolVersions.ClientProtocolVersionMin.ToString(); sendData["VERSIONMAX"] = ProtocolVersions.ClientProtocolVersionMax.ToString(); sendData["METHOD"] = "getagent"; sendData["SessionID"] = sessionID.ToString(); string reply = string.Empty; string reqString = ServerUtils.BuildQueryString(sendData); // m_log.DebugFormat("[PRESENCE CONNECTOR]: queryString = {0}", reqString); try { reply = SynchronousRestFormsRequester.MakeRequest("POST", m_ServerURI + "/presence", reqString); if (reply == null || (reply != null && reply == string.Empty)) { m_log.DebugFormat("[PRESENCE CONNECTOR]: GetAgent received null or empty reply"); return null; } } catch (Exception e) { m_log.DebugFormat("[PRESENCE CONNECTOR]: Exception when contacting presence server: {0}", e.Message); } Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply); PresenceInfo pinfo = null; if ((replyData != null) && replyData.ContainsKey("result") && (replyData["result"] != null)) { if (replyData["result"] is Dictionary<string, object>) { pinfo = new PresenceInfo((Dictionary<string, object>)replyData["result"]); } } return pinfo; } public PresenceInfo[] GetAgents(string[] userIDs) { Dictionary<string, object> sendData = new Dictionary<string, object>(); //sendData["SCOPEID"] = scopeID.ToString(); sendData["VERSIONMIN"] = ProtocolVersions.ClientProtocolVersionMin.ToString(); sendData["VERSIONMAX"] = ProtocolVersions.ClientProtocolVersionMax.ToString(); sendData["METHOD"] = "getagents"; sendData["uuids"] = new List<string>(userIDs); string reply = string.Empty; string reqString = ServerUtils.BuildQueryString(sendData); //m_log.DebugFormat("[PRESENCE CONNECTOR]: queryString = {0}", reqString); try { reply = SynchronousRestFormsRequester.MakeRequest("POST", m_ServerURI + "/presence", reqString); if (reply == null || (reply != null && reply == string.Empty)) { m_log.DebugFormat("[PRESENCE CONNECTOR]: GetAgents received null or empty reply"); return null; } } catch (Exception e) { m_log.DebugFormat("[PRESENCE CONNECTOR]: Exception when contacting presence server: {0}", e.Message); } List<PresenceInfo> rinfos = new List<PresenceInfo>(); Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply); if (replyData != null) { if (replyData.ContainsKey("result") && (replyData["result"].ToString() == "null" || replyData["result"].ToString() == "Failure")) { return new PresenceInfo[0]; } Dictionary<string, object>.ValueCollection pinfosList = replyData.Values; //m_log.DebugFormat("[PRESENCE CONNECTOR]: GetAgents returned {0} elements", pinfosList.Count); foreach (object presence in pinfosList) { if (presence is Dictionary<string, object>) { PresenceInfo pinfo = new PresenceInfo((Dictionary<string, object>)presence); rinfos.Add(pinfo); } else m_log.DebugFormat("[PRESENCE CONNECTOR]: GetAgents received invalid response type {0}", presence.GetType()); } } else m_log.DebugFormat("[PRESENCE CONNECTOR]: GetAgents received null response"); return rinfos.ToArray(); } #endregion } }
using System; using static OneOf.Functions; namespace OneOf { public class OneOfBase<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> : IOneOf { readonly T0 _value0; readonly T1 _value1; readonly T2 _value2; readonly T3 _value3; readonly T4 _value4; readonly T5 _value5; readonly T6 _value6; readonly T7 _value7; readonly T8 _value8; readonly T9 _value9; readonly T10 _value10; readonly T11 _value11; readonly int _index; protected OneOfBase(OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> input) { _index = input.Index; switch (_index) { case 0: _value0 = input.AsT0; break; case 1: _value1 = input.AsT1; break; case 2: _value2 = input.AsT2; break; case 3: _value3 = input.AsT3; break; case 4: _value4 = input.AsT4; break; case 5: _value5 = input.AsT5; break; case 6: _value6 = input.AsT6; break; case 7: _value7 = input.AsT7; break; case 8: _value8 = input.AsT8; break; case 9: _value9 = input.AsT9; break; case 10: _value10 = input.AsT10; break; case 11: _value11 = input.AsT11; break; default: throw new InvalidOperationException(); } } public object Value => _index switch { 0 => _value0, 1 => _value1, 2 => _value2, 3 => _value3, 4 => _value4, 5 => _value5, 6 => _value6, 7 => _value7, 8 => _value8, 9 => _value9, 10 => _value10, 11 => _value11, _ => throw new InvalidOperationException() }; public int Index => _index; public bool IsT0 => _index == 0; public bool IsT1 => _index == 1; public bool IsT2 => _index == 2; public bool IsT3 => _index == 3; public bool IsT4 => _index == 4; public bool IsT5 => _index == 5; public bool IsT6 => _index == 6; public bool IsT7 => _index == 7; public bool IsT8 => _index == 8; public bool IsT9 => _index == 9; public bool IsT10 => _index == 10; public bool IsT11 => _index == 11; public T0 AsT0 => _index == 0 ? _value0 : throw new InvalidOperationException($"Cannot return as T0 as result is T{_index}"); public T1 AsT1 => _index == 1 ? _value1 : throw new InvalidOperationException($"Cannot return as T1 as result is T{_index}"); public T2 AsT2 => _index == 2 ? _value2 : throw new InvalidOperationException($"Cannot return as T2 as result is T{_index}"); public T3 AsT3 => _index == 3 ? _value3 : throw new InvalidOperationException($"Cannot return as T3 as result is T{_index}"); public T4 AsT4 => _index == 4 ? _value4 : throw new InvalidOperationException($"Cannot return as T4 as result is T{_index}"); public T5 AsT5 => _index == 5 ? _value5 : throw new InvalidOperationException($"Cannot return as T5 as result is T{_index}"); public T6 AsT6 => _index == 6 ? _value6 : throw new InvalidOperationException($"Cannot return as T6 as result is T{_index}"); public T7 AsT7 => _index == 7 ? _value7 : throw new InvalidOperationException($"Cannot return as T7 as result is T{_index}"); public T8 AsT8 => _index == 8 ? _value8 : throw new InvalidOperationException($"Cannot return as T8 as result is T{_index}"); public T9 AsT9 => _index == 9 ? _value9 : throw new InvalidOperationException($"Cannot return as T9 as result is T{_index}"); public T10 AsT10 => _index == 10 ? _value10 : throw new InvalidOperationException($"Cannot return as T10 as result is T{_index}"); public T11 AsT11 => _index == 11 ? _value11 : throw new InvalidOperationException($"Cannot return as T11 as result is T{_index}"); public void Switch(Action<T0> f0, Action<T1> f1, Action<T2> f2, Action<T3> f3, Action<T4> f4, Action<T5> f5, Action<T6> f6, Action<T7> f7, Action<T8> f8, Action<T9> f9, Action<T10> f10, Action<T11> f11) { if (_index == 0 && f0 != null) { f0(_value0); return; } if (_index == 1 && f1 != null) { f1(_value1); return; } if (_index == 2 && f2 != null) { f2(_value2); return; } if (_index == 3 && f3 != null) { f3(_value3); return; } if (_index == 4 && f4 != null) { f4(_value4); return; } if (_index == 5 && f5 != null) { f5(_value5); return; } if (_index == 6 && f6 != null) { f6(_value6); return; } if (_index == 7 && f7 != null) { f7(_value7); return; } if (_index == 8 && f8 != null) { f8(_value8); return; } if (_index == 9 && f9 != null) { f9(_value9); return; } if (_index == 10 && f10 != null) { f10(_value10); return; } if (_index == 11 && f11 != null) { f11(_value11); return; } throw new InvalidOperationException(); } public TResult Match<TResult>(Func<T0, TResult> f0, Func<T1, TResult> f1, Func<T2, TResult> f2, Func<T3, TResult> f3, Func<T4, TResult> f4, Func<T5, TResult> f5, Func<T6, TResult> f6, Func<T7, TResult> f7, Func<T8, TResult> f8, Func<T9, TResult> f9, Func<T10, TResult> f10, Func<T11, TResult> f11) { if (_index == 0 && f0 != null) { return f0(_value0); } if (_index == 1 && f1 != null) { return f1(_value1); } if (_index == 2 && f2 != null) { return f2(_value2); } if (_index == 3 && f3 != null) { return f3(_value3); } if (_index == 4 && f4 != null) { return f4(_value4); } if (_index == 5 && f5 != null) { return f5(_value5); } if (_index == 6 && f6 != null) { return f6(_value6); } if (_index == 7 && f7 != null) { return f7(_value7); } if (_index == 8 && f8 != null) { return f8(_value8); } if (_index == 9 && f9 != null) { return f9(_value9); } if (_index == 10 && f10 != null) { return f10(_value10); } if (_index == 11 && f11 != null) { return f11(_value11); } throw new InvalidOperationException(); } public bool TryPickT0(out T0 value, out OneOf<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> remainder) { value = IsT0 ? AsT0 : default; remainder = _index switch { 0 => default, 1 => AsT1, 2 => AsT2, 3 => AsT3, 4 => AsT4, 5 => AsT5, 6 => AsT6, 7 => AsT7, 8 => AsT8, 9 => AsT9, 10 => AsT10, 11 => AsT11, _ => throw new InvalidOperationException() }; return this.IsT0; } public bool TryPickT1(out T1 value, out OneOf<T0, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> remainder) { value = IsT1 ? AsT1 : default; remainder = _index switch { 0 => AsT0, 1 => default, 2 => AsT2, 3 => AsT3, 4 => AsT4, 5 => AsT5, 6 => AsT6, 7 => AsT7, 8 => AsT8, 9 => AsT9, 10 => AsT10, 11 => AsT11, _ => throw new InvalidOperationException() }; return this.IsT1; } public bool TryPickT2(out T2 value, out OneOf<T0, T1, T3, T4, T5, T6, T7, T8, T9, T10, T11> remainder) { value = IsT2 ? AsT2 : default; remainder = _index switch { 0 => AsT0, 1 => AsT1, 2 => default, 3 => AsT3, 4 => AsT4, 5 => AsT5, 6 => AsT6, 7 => AsT7, 8 => AsT8, 9 => AsT9, 10 => AsT10, 11 => AsT11, _ => throw new InvalidOperationException() }; return this.IsT2; } public bool TryPickT3(out T3 value, out OneOf<T0, T1, T2, T4, T5, T6, T7, T8, T9, T10, T11> remainder) { value = IsT3 ? AsT3 : default; remainder = _index switch { 0 => AsT0, 1 => AsT1, 2 => AsT2, 3 => default, 4 => AsT4, 5 => AsT5, 6 => AsT6, 7 => AsT7, 8 => AsT8, 9 => AsT9, 10 => AsT10, 11 => AsT11, _ => throw new InvalidOperationException() }; return this.IsT3; } public bool TryPickT4(out T4 value, out OneOf<T0, T1, T2, T3, T5, T6, T7, T8, T9, T10, T11> remainder) { value = IsT4 ? AsT4 : default; remainder = _index switch { 0 => AsT0, 1 => AsT1, 2 => AsT2, 3 => AsT3, 4 => default, 5 => AsT5, 6 => AsT6, 7 => AsT7, 8 => AsT8, 9 => AsT9, 10 => AsT10, 11 => AsT11, _ => throw new InvalidOperationException() }; return this.IsT4; } public bool TryPickT5(out T5 value, out OneOf<T0, T1, T2, T3, T4, T6, T7, T8, T9, T10, T11> remainder) { value = IsT5 ? AsT5 : default; remainder = _index switch { 0 => AsT0, 1 => AsT1, 2 => AsT2, 3 => AsT3, 4 => AsT4, 5 => default, 6 => AsT6, 7 => AsT7, 8 => AsT8, 9 => AsT9, 10 => AsT10, 11 => AsT11, _ => throw new InvalidOperationException() }; return this.IsT5; } public bool TryPickT6(out T6 value, out OneOf<T0, T1, T2, T3, T4, T5, T7, T8, T9, T10, T11> remainder) { value = IsT6 ? AsT6 : default; remainder = _index switch { 0 => AsT0, 1 => AsT1, 2 => AsT2, 3 => AsT3, 4 => AsT4, 5 => AsT5, 6 => default, 7 => AsT7, 8 => AsT8, 9 => AsT9, 10 => AsT10, 11 => AsT11, _ => throw new InvalidOperationException() }; return this.IsT6; } public bool TryPickT7(out T7 value, out OneOf<T0, T1, T2, T3, T4, T5, T6, T8, T9, T10, T11> remainder) { value = IsT7 ? AsT7 : default; remainder = _index switch { 0 => AsT0, 1 => AsT1, 2 => AsT2, 3 => AsT3, 4 => AsT4, 5 => AsT5, 6 => AsT6, 7 => default, 8 => AsT8, 9 => AsT9, 10 => AsT10, 11 => AsT11, _ => throw new InvalidOperationException() }; return this.IsT7; } public bool TryPickT8(out T8 value, out OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T9, T10, T11> remainder) { value = IsT8 ? AsT8 : default; remainder = _index switch { 0 => AsT0, 1 => AsT1, 2 => AsT2, 3 => AsT3, 4 => AsT4, 5 => AsT5, 6 => AsT6, 7 => AsT7, 8 => default, 9 => AsT9, 10 => AsT10, 11 => AsT11, _ => throw new InvalidOperationException() }; return this.IsT8; } public bool TryPickT9(out T9 value, out OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T10, T11> remainder) { value = IsT9 ? AsT9 : default; remainder = _index switch { 0 => AsT0, 1 => AsT1, 2 => AsT2, 3 => AsT3, 4 => AsT4, 5 => AsT5, 6 => AsT6, 7 => AsT7, 8 => AsT8, 9 => default, 10 => AsT10, 11 => AsT11, _ => throw new InvalidOperationException() }; return this.IsT9; } public bool TryPickT10(out T10 value, out OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T11> remainder) { value = IsT10 ? AsT10 : default; remainder = _index switch { 0 => AsT0, 1 => AsT1, 2 => AsT2, 3 => AsT3, 4 => AsT4, 5 => AsT5, 6 => AsT6, 7 => AsT7, 8 => AsT8, 9 => AsT9, 10 => default, 11 => AsT11, _ => throw new InvalidOperationException() }; return this.IsT10; } public bool TryPickT11(out T11 value, out OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10> remainder) { value = IsT11 ? AsT11 : default; remainder = _index switch { 0 => AsT0, 1 => AsT1, 2 => AsT2, 3 => AsT3, 4 => AsT4, 5 => AsT5, 6 => AsT6, 7 => AsT7, 8 => AsT8, 9 => AsT9, 10 => AsT10, 11 => default, _ => throw new InvalidOperationException() }; return this.IsT11; } bool Equals(OneOfBase<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> other) => _index == other._index && _index switch { 0 => Equals(_value0, other._value0), 1 => Equals(_value1, other._value1), 2 => Equals(_value2, other._value2), 3 => Equals(_value3, other._value3), 4 => Equals(_value4, other._value4), 5 => Equals(_value5, other._value5), 6 => Equals(_value6, other._value6), 7 => Equals(_value7, other._value7), 8 => Equals(_value8, other._value8), 9 => Equals(_value9, other._value9), 10 => Equals(_value10, other._value10), 11 => Equals(_value11, other._value11), _ => false }; public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) { return false; } if (ReferenceEquals(this, obj)) { return true; } return obj is OneOfBase<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> o && Equals(o); } public override string ToString() => _index switch { 0 => FormatValue(_value0), 1 => FormatValue(_value1), 2 => FormatValue(_value2), 3 => FormatValue(_value3), 4 => FormatValue(_value4), 5 => FormatValue(_value5), 6 => FormatValue(_value6), 7 => FormatValue(_value7), 8 => FormatValue(_value8), 9 => FormatValue(_value9), 10 => FormatValue(_value10), 11 => FormatValue(_value11), _ => throw new InvalidOperationException("Unexpected index, which indicates a problem in the OneOf codegen.") }; public override int GetHashCode() { unchecked { int hashCode = _index switch { 0 => _value0?.GetHashCode(), 1 => _value1?.GetHashCode(), 2 => _value2?.GetHashCode(), 3 => _value3?.GetHashCode(), 4 => _value4?.GetHashCode(), 5 => _value5?.GetHashCode(), 6 => _value6?.GetHashCode(), 7 => _value7?.GetHashCode(), 8 => _value8?.GetHashCode(), 9 => _value9?.GetHashCode(), 10 => _value10?.GetHashCode(), 11 => _value11?.GetHashCode(), _ => 0 } ?? 0; return (hashCode*397) ^ _index; } } } }
//--------------------------------------------------------------------------- // // <copyright file=InputLanguageSource.cs company=Microsoft> // Copyright (C) Microsoft Corporation. All rights reserved. // </copyright> // // // Description: The source of the input language of the thread. // // History: // 07/30/2003 : yutakas - ported from dotnet tree. // //--------------------------------------------------------------------------- using System.Security; using System.Security.Permissions; using System.Collections; using System.Globalization; using System.Windows.Threading; using System.Windows.Input; using System.Windows.Media; using System.Runtime.InteropServices; using System.Diagnostics; using MS.Win32; using MS.Utility; namespace System.Windows.Input { //------------------------------------------------------ // // InputLanguageSource class // //------------------------------------------------------ /// <summary> /// This is an internal. The source for input languages. /// </summary> internal sealed class InputLanguageSource : IInputLanguageSource, IDisposable { //------------------------------------------------------ // // Constructors // //------------------------------------------------------ /// <summary> /// This is an internal. The source for input languages. /// </summary> internal InputLanguageSource(InputLanguageManager inputlanguagemanager) { _inputlanguagemanager = inputlanguagemanager; // initialize the current input language. _langid = (short)NativeMethods.IntPtrToInt32(SafeNativeMethods.GetKeyboardLayout(0)); // store the dispatcher thread id. This will be used to call GetKeyboardLayout() from // other thread. _dispatcherThreadId = SafeNativeMethods.GetCurrentThreadId(); // Register source _inputlanguagemanager.RegisterInputLanguageSource(this); } //------------------------------------------------------ // // Public Methods // //------------------------------------------------------ #region Public Methods /// <summary> /// Dispose method. /// </summary> public void Dispose() { if (_ipp != null) Uninitialize(); } /// <summary> /// IIInputLanguageSource.Initialize() /// This creates ITfInputProcessorProfile object and advice sink. /// </summary> public void Initialize() { EnsureInputProcessorProfile(); } /// <summary> /// IIInputLanguageSource.Uninitialize() /// This releases ITfInputProcessorProfile object and unadvice sink. /// </summary> public void Uninitialize() { if (_ipp != null) { _ipp.Uninitialize(); _ipp = null; } } #endregion Public Methods //------------------------------------------------------ // // Public Properties // //------------------------------------------------------ /// <summary> /// returns the current input language of this win32 thread. /// </summary> public CultureInfo CurrentInputLanguage { get { return new CultureInfo(_CurrentInputLanguage); } set { _CurrentInputLanguage = (short)value.LCID; } } /// <summary> /// returns the list of the available input languages of this win32 thread. /// </summary> public IEnumerable InputLanguageList { get { EnsureInputProcessorProfile(); if (_ipp == null) { ArrayList al = new ArrayList(); al.Add(CurrentInputLanguage); return al; } return _ipp.InputLanguageList; } } //------------------------------------------------------ // // Internal Methods // //------------------------------------------------------ /// <summary> /// The input language change call back from the sink. /// </summary> internal bool OnLanguageChange(short langid) { if (_langid != langid) { // Call InputLanguageManager if its current source is this. if (InputLanguageManager.Current.Source == this) { return InputLanguageManager.Current.ReportInputLanguageChanging(new CultureInfo(langid), new CultureInfo(_langid)); } } return true; } /// <summary> /// The input language changed call back from the sink. /// </summary> internal void OnLanguageChanged() { short langid = _CurrentInputLanguage; if (_langid != langid) { short prevlangid = _langid; _langid = langid; // Call InputLanguageManager if its current source is this. if (InputLanguageManager.Current.Source == this) { InputLanguageManager.Current.ReportInputLanguageChanged(new CultureInfo(langid), new CultureInfo(prevlangid)); } } } //------------------------------------------------------ // // Private Method // //------------------------------------------------------ /// <summary> /// This creates ITfInputProcessorProfile object and advice sink. /// </summary> /// <SecurityNote> /// Critical - calls unmanaged code (initializing input) /// TreatAsSafe - ok to call any number of times /// </SecurityNote> [SecurityCritical, SecurityTreatAsSafe] private void EnsureInputProcessorProfile() { // _ipp has been initialzied. Don't do this again. if (_ipp != null) return; // We don't need to initialize _ipp if there is onlyone keyboard layout. // Only one input language is available. if (SafeNativeMethods.GetKeyboardLayoutList(0, null) <= 1) return; Debug.Assert(_ipp == null, "_EnsureInputProcesoorProfile has been called."); InputLanguageProfileNotifySink lpns; lpns = new InputLanguageProfileNotifySink(this); _ipp= new InputProcessorProfiles(); if (!_ipp.Initialize(lpns)) { _ipp = null; } } //------------------------------------------------------ // // Private Properties // //------------------------------------------------------ /// <summary> /// The current input language in LANGID of this win32 thread. /// </summary> private short _CurrentInputLanguage { get { // Return input language of the dispatcher thread. return (short)NativeMethods.IntPtrToInt32(SafeNativeMethods.GetKeyboardLayout(_dispatcherThreadId)); } set { EnsureInputProcessorProfile(); if (_ipp != null) { _ipp.CurrentInputLanguage = value; } } } //------------------------------------------------------ // // Private Fields // //------------------------------------------------------ #region Private Fields // the current input language in LANGID. private short _langid; // The dispatcher thread id. private int _dispatcherThreadId; // the connected input language manager. InputLanguageManager _inputlanguagemanager; // the reference to ITfInputProcessorProfile. InputProcessorProfiles _ipp; #endregion Private Fields } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Generic; using System.Composition; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.DocumentationComments; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.SignatureHelp; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.SignatureHelp { [ExportSignatureHelpProvider("GenericNameSignatureHelpProvider", LanguageNames.CSharp), Shared] internal partial class GenericNameSignatureHelpProvider : AbstractCSharpSignatureHelpProvider { public override bool IsTriggerCharacter(char ch) { return ch == '<' || ch == ','; } public override bool IsRetriggerCharacter(char ch) { return ch == '>'; } protected virtual bool TryGetGenericIdentifier( SyntaxNode root, int position, ISyntaxFactsService syntaxFacts, SignatureHelpTriggerReason triggerReason, CancellationToken cancellationToken, out SyntaxToken genericIdentifier, out SyntaxToken lessThanToken) { if (CommonSignatureHelpUtilities.TryGetSyntax(root, position, syntaxFacts, triggerReason, IsTriggerToken, IsArgumentListToken, cancellationToken, out GenericNameSyntax name)) { genericIdentifier = name.Identifier; lessThanToken = name.TypeArgumentList.LessThanToken; return true; } genericIdentifier = default(SyntaxToken); lessThanToken = default(SyntaxToken); return false; } private bool IsTriggerToken(SyntaxToken token) { return !token.IsKind(SyntaxKind.None) && token.ValueText.Length == 1 && IsTriggerCharacter(token.ValueText[0]) && token.Parent is TypeArgumentListSyntax && token.Parent.Parent is GenericNameSyntax; } private bool IsArgumentListToken(GenericNameSyntax node, SyntaxToken token) { return node.TypeArgumentList != null && node.TypeArgumentList.Span.Contains(token.SpanStart) && token != node.TypeArgumentList.GreaterThanToken; } protected override async Task<SignatureHelpItems> GetItemsWorkerAsync(Document document, int position, SignatureHelpTriggerInfo triggerInfo, CancellationToken cancellationToken) { var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); if (!TryGetGenericIdentifier(root, position, document.GetLanguageService<ISyntaxFactsService>(), triggerInfo.TriggerReason, cancellationToken, out var genericIdentifier, out var lessThanToken)) { return null; } var simpleName = genericIdentifier.Parent as SimpleNameSyntax; if (simpleName == null) { return null; } var beforeDotExpression = simpleName.IsRightSideOfDot() ? simpleName.GetLeftSideOfDot() : null; var semanticModel = await document.GetSemanticModelForNodeAsync(simpleName, cancellationToken).ConfigureAwait(false); var leftSymbol = beforeDotExpression == null ? null : semanticModel.GetSymbolInfo(beforeDotExpression, cancellationToken).GetAnySymbol() as INamespaceOrTypeSymbol; var leftType = beforeDotExpression == null ? null : semanticModel.GetTypeInfo(beforeDotExpression, cancellationToken).Type as INamespaceOrTypeSymbol; var leftContainer = leftSymbol ?? leftType; var isBaseAccess = beforeDotExpression is BaseExpressionSyntax; var namespacesOrTypesOnly = SyntaxFacts.IsInNamespaceOrTypeContext(simpleName); var includeExtensions = leftSymbol == null && leftType != null; var name = genericIdentifier.ValueText; var symbols = isBaseAccess ? semanticModel.LookupBaseMembers(position, name) : namespacesOrTypesOnly ? semanticModel.LookupNamespacesAndTypes(position, leftContainer, name) : semanticModel.LookupSymbols(position, leftContainer, name, includeExtensions); var within = semanticModel.GetEnclosingNamedTypeOrAssembly(position, cancellationToken); if (within == null) { return null; } var symbolDisplayService = document.Project.LanguageServices.GetService<ISymbolDisplayService>(); var accessibleSymbols = symbols.WhereAsArray(s => s.GetArity() > 0) .WhereAsArray(s => s is INamedTypeSymbol || s is IMethodSymbol) .FilterToVisibleAndBrowsableSymbols(document.ShouldHideAdvancedMembers(), semanticModel.Compilation) .Sort(symbolDisplayService, semanticModel, genericIdentifier.SpanStart); if (!accessibleSymbols.Any()) { return null; } var anonymousTypeDisplayService = document.Project.LanguageServices.GetService<IAnonymousTypeDisplayService>(); var documentationCommentFormattingService = document.Project.LanguageServices.GetService<IDocumentationCommentFormattingService>(); var textSpan = GetTextSpan(genericIdentifier, lessThanToken); var syntaxFacts = document.GetLanguageService<ISyntaxFactsService>(); return CreateSignatureHelpItems(accessibleSymbols.Select(s => Convert(s, lessThanToken, semanticModel, symbolDisplayService, anonymousTypeDisplayService, documentationCommentFormattingService, cancellationToken)).ToList(), textSpan, GetCurrentArgumentState(root, position, syntaxFacts, textSpan, cancellationToken)); } public override SignatureHelpState GetCurrentArgumentState(SyntaxNode root, int position, ISyntaxFactsService syntaxFacts, TextSpan currentSpan, CancellationToken cancellationToken) { if (!TryGetGenericIdentifier(root, position, syntaxFacts, SignatureHelpTriggerReason.InvokeSignatureHelpCommand, cancellationToken, out var genericIdentifier, out var lessThanToken)) { return null; } if (genericIdentifier.TryParseGenericName(cancellationToken, out var genericName)) { // Because we synthesized the generic name, it will have an index starting at 0 // instead of at the actual position it's at in the text. Because of this, we need to // offset the position we are checking accordingly. var offset = genericIdentifier.SpanStart - genericName.SpanStart; position -= offset; return SignatureHelpUtilities.GetSignatureHelpState(genericName.TypeArgumentList, position); } return null; } protected virtual TextSpan GetTextSpan(SyntaxToken genericIdentifier, SyntaxToken lessThanToken) { Contract.ThrowIfFalse(lessThanToken.Parent is TypeArgumentListSyntax && lessThanToken.Parent.Parent is GenericNameSyntax); return SignatureHelpUtilities.GetSignatureHelpSpan(((GenericNameSyntax)lessThanToken.Parent.Parent).TypeArgumentList); } private SignatureHelpItem Convert( ISymbol symbol, SyntaxToken lessThanToken, SemanticModel semanticModel, ISymbolDisplayService symbolDisplayService, IAnonymousTypeDisplayService anonymousTypeDisplayService, IDocumentationCommentFormattingService documentationCommentFormattingService, CancellationToken cancellationToken) { var position = lessThanToken.SpanStart; SignatureHelpItem item; if (symbol is INamedTypeSymbol) { var namedType = (INamedTypeSymbol)symbol; item = CreateItem( symbol, semanticModel, position, symbolDisplayService, anonymousTypeDisplayService, false, symbol.GetDocumentationPartsFactory(semanticModel, position, documentationCommentFormattingService), GetPreambleParts(namedType, semanticModel, position), GetSeparatorParts(), GetPostambleParts(namedType), namedType.TypeParameters.Select(p => Convert(p, semanticModel, position, documentationCommentFormattingService, cancellationToken)).ToList()); } else { var method = (IMethodSymbol)symbol; item = CreateItem( symbol, semanticModel, position, symbolDisplayService, anonymousTypeDisplayService, false, c => symbol.GetDocumentationParts(semanticModel, position, documentationCommentFormattingService, c).Concat(GetAwaitableUsage(method, semanticModel, position)), GetPreambleParts(method, semanticModel, position), GetSeparatorParts(), GetPostambleParts(method, semanticModel, position), method.TypeParameters.Select(p => Convert(p, semanticModel, position, documentationCommentFormattingService, cancellationToken)).ToList()); } return item; } private static readonly SymbolDisplayFormat s_minimallyQualifiedFormat = SymbolDisplayFormat.MinimallyQualifiedFormat.WithGenericsOptions( SymbolDisplayFormat.MinimallyQualifiedFormat.GenericsOptions | SymbolDisplayGenericsOptions.IncludeVariance); private SignatureHelpSymbolParameter Convert( ITypeParameterSymbol parameter, SemanticModel semanticModel, int position, IDocumentationCommentFormattingService formatter, CancellationToken cancellationToken) { return new SignatureHelpSymbolParameter( parameter.Name, isOptional: false, documentationFactory: parameter.GetDocumentationPartsFactory(semanticModel, position, formatter), displayParts: parameter.ToMinimalDisplayParts(semanticModel, position, s_minimallyQualifiedFormat), selectedDisplayParts: GetSelectedDisplayParts(parameter, semanticModel, position, cancellationToken)); } private IList<SymbolDisplayPart> GetSelectedDisplayParts( ITypeParameterSymbol typeParam, SemanticModel semanticModel, int position, CancellationToken cancellationToken) { var parts = new List<SymbolDisplayPart>(); if (TypeParameterHasConstraints(typeParam)) { parts.Add(Space()); parts.Add(Keyword(SyntaxKind.WhereKeyword)); parts.Add(Space()); parts.Add(new SymbolDisplayPart(SymbolDisplayPartKind.TypeParameterName, typeParam, typeParam.Name)); parts.Add(Space()); parts.Add(Punctuation(SyntaxKind.ColonToken)); parts.Add(Space()); bool needComma = false; // class/struct constraint must be first if (typeParam.HasReferenceTypeConstraint) { parts.Add(Keyword(SyntaxKind.ClassKeyword)); needComma = true; } else if (typeParam.HasValueTypeConstraint) { parts.Add(Keyword(SyntaxKind.StructKeyword)); needComma = true; } foreach (var baseType in typeParam.ConstraintTypes) { if (needComma) { parts.Add(Punctuation(SyntaxKind.CommaToken)); parts.Add(Space()); } parts.AddRange(baseType.ToMinimalDisplayParts(semanticModel, position)); needComma = true; } // ctor constraint must be last if (typeParam.HasConstructorConstraint) { if (needComma) { parts.Add(Punctuation(SyntaxKind.CommaToken)); parts.Add(Space()); } parts.Add(Keyword(SyntaxKind.NewKeyword)); parts.Add(Punctuation(SyntaxKind.OpenParenToken)); parts.Add(Punctuation(SyntaxKind.CloseParenToken)); } } return parts; } private static bool TypeParameterHasConstraints(ITypeParameterSymbol typeParam) { return !typeParam.ConstraintTypes.IsDefaultOrEmpty || typeParam.HasConstructorConstraint || typeParam.HasReferenceTypeConstraint || typeParam.HasValueTypeConstraint; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. namespace Microsoft.Azure.Management.Sql.Fluent { using Microsoft.Azure.Management.ResourceManager.Fluent.Core.ChildResource.Definition; using Microsoft.Azure.Management.Sql.Fluent.SqlDatabaseOperations.Definition; using Microsoft.Azure.Management.Sql.Fluent.SqlElasticPool.Definition; using Microsoft.Azure.Management.Sql.Fluent.SqlElasticPool.SqlElasticPoolDefinition; internal partial class SqlElasticPoolForDatabaseImpl { /// <summary> /// Sets the minimum DTU all SQL Azure Databases are guaranteed. /// </summary> /// <param name="databaseDtuMin">Minimum DTU for all SQL Azure databases.</param> /// <return>The next stage of the definition.</return> SqlElasticPool.Definition.IWithAttach<SqlDatabaseOperations.Definition.IWithExistingDatabaseAfterElasticPool> SqlElasticPool.Definition.IWithDatabaseDtuMin<SqlDatabaseOperations.Definition.IWithExistingDatabaseAfterElasticPool>.WithDatabaseDtuMin(int databaseDtuMin) { return this.WithDatabaseDtuMin(databaseDtuMin); } /// <summary> /// Sets the storage limit for the SQL Azure Database Elastic Pool in MB. /// </summary> /// <param name="storageMB">Storage limit for the SQL Azure Database Elastic Pool in MB.</param> /// <return>The next stage of the definition.</return> SqlElasticPool.Definition.IWithAttach<SqlDatabaseOperations.Definition.IWithExistingDatabaseAfterElasticPool> SqlElasticPool.Definition.IWithStorageCapacity<SqlDatabaseOperations.Definition.IWithExistingDatabaseAfterElasticPool>.WithStorageCapacity(int storageMB) { return this.WithStorageCapacity(storageMB); } /// <summary> /// Sets the minimum number of eDTU for each database in the pool are regardless of its activity. /// </summary> /// <param name="eDTU">Minimum eDTU for all SQL Azure databases.</param> /// <return>The next stage of the definition.</return> SqlElasticPool.Definition.IWithBasicEdition<SqlDatabaseOperations.Definition.IWithExistingDatabaseAfterElasticPool> SqlElasticPool.Definition.IWithBasicEditionBeta<SqlDatabaseOperations.Definition.IWithExistingDatabaseAfterElasticPool>.WithDatabaseDtuMin(SqlElasticPoolBasicMinEDTUs eDTU) { return this.WithDatabaseDtuMin(eDTU); } /// <summary> /// Sets the maximum number of eDTU a database in the pool can consume. /// </summary> /// <param name="eDTU">Maximum eDTU a database in the pool can consume.</param> /// <return>The next stage of the definition.</return> SqlElasticPool.Definition.IWithBasicEdition<SqlDatabaseOperations.Definition.IWithExistingDatabaseAfterElasticPool> SqlElasticPool.Definition.IWithBasicEditionBeta<SqlDatabaseOperations.Definition.IWithExistingDatabaseAfterElasticPool>.WithDatabaseDtuMax(SqlElasticPoolBasicMaxEDTUs eDTU) { return this.WithDatabaseDtuMax(eDTU); } /// <summary> /// Sets the total shared eDTU for the SQL Azure Database Elastic Pool. /// </summary> /// <param name="eDTU">Total shared eDTU for the SQL Azure Database Elastic Pool.</param> /// <return>The next stage of the definition.</return> SqlElasticPool.Definition.IWithBasicEdition<SqlDatabaseOperations.Definition.IWithExistingDatabaseAfterElasticPool> SqlElasticPool.Definition.IWithBasicEditionBeta<SqlDatabaseOperations.Definition.IWithExistingDatabaseAfterElasticPool>.WithReservedDtu(SqlElasticPoolBasicEDTUs eDTU) { return this.WithReservedDtu(eDTU); } /// <summary> /// Sets the minimum number of eDTU for each database in the pool are regardless of its activity. /// </summary> /// <param name="eDTU">Minimum eDTU for all SQL Azure databases.</param> /// <return>The next stage of the definition.</return> SqlElasticPool.Definition.IWithPremiumEdition<SqlDatabaseOperations.Definition.IWithExistingDatabaseAfterElasticPool> SqlElasticPool.Definition.IWithPremiumEditionBeta<SqlDatabaseOperations.Definition.IWithExistingDatabaseAfterElasticPool>.WithDatabaseDtuMin(SqlElasticPoolPremiumMinEDTUs eDTU) { return this.WithDatabaseDtuMin(eDTU); } /// <summary> /// Sets the maximum number of eDTU a database in the pool can consume. /// </summary> /// <param name="eDTU">Maximum eDTU a database in the pool can consume.</param> /// <return>The next stage of the definition.</return> SqlElasticPool.Definition.IWithPremiumEdition<SqlDatabaseOperations.Definition.IWithExistingDatabaseAfterElasticPool> SqlElasticPool.Definition.IWithPremiumEditionBeta<SqlDatabaseOperations.Definition.IWithExistingDatabaseAfterElasticPool>.WithDatabaseDtuMax(SqlElasticPoolPremiumMaxEDTUs eDTU) { return this.WithDatabaseDtuMax(eDTU); } /// <summary> /// Sets the storage capacity for the SQL Azure Database Elastic Pool. /// </summary> /// <param name="storageCapacity">Storage capacity for the SQL Azure Database Elastic Pool.</param> /// <return>The next stage of the definition.</return> SqlElasticPool.Definition.IWithPremiumEdition<SqlDatabaseOperations.Definition.IWithExistingDatabaseAfterElasticPool> SqlElasticPool.Definition.IWithPremiumEditionBeta<SqlDatabaseOperations.Definition.IWithExistingDatabaseAfterElasticPool>.WithStorageCapacity(SqlElasticPoolPremiumSorage storageCapacity) { return this.WithStorageCapacity(storageCapacity); } /// <summary> /// Sets the total shared eDTU for the SQL Azure Database Elastic Pool. /// </summary> /// <param name="eDTU">Total shared eDTU for the SQL Azure Database Elastic Pool.</param> /// <return>The next stage of the definition.</return> SqlElasticPool.Definition.IWithPremiumEdition<SqlDatabaseOperations.Definition.IWithExistingDatabaseAfterElasticPool> SqlElasticPool.Definition.IWithPremiumEditionBeta<SqlDatabaseOperations.Definition.IWithExistingDatabaseAfterElasticPool>.WithReservedDtu(SqlElasticPoolPremiumEDTUs eDTU) { return this.WithReservedDtu(eDTU); } /// <summary> /// Sets the minimum number of eDTU for each database in the pool are regardless of its activity. /// </summary> /// <param name="eDTU">Minimum eDTU for all SQL Azure databases.</param> /// <return>The next stage of the definition.</return> SqlElasticPool.Definition.IWithStandardEdition<SqlDatabaseOperations.Definition.IWithExistingDatabaseAfterElasticPool> SqlElasticPool.Definition.IWithStandardEditionBeta<SqlDatabaseOperations.Definition.IWithExistingDatabaseAfterElasticPool>.WithDatabaseDtuMin(SqlElasticPoolStandardMinEDTUs eDTU) { return this.WithDatabaseDtuMin(eDTU); } /// <summary> /// Sets the maximum number of eDTU a database in the pool can consume. /// </summary> /// <param name="eDTU">Maximum eDTU a database in the pool can consume.</param> /// <return>The next stage of the definition.</return> SqlElasticPool.Definition.IWithStandardEdition<SqlDatabaseOperations.Definition.IWithExistingDatabaseAfterElasticPool> SqlElasticPool.Definition.IWithStandardEditionBeta<SqlDatabaseOperations.Definition.IWithExistingDatabaseAfterElasticPool>.WithDatabaseDtuMax(SqlElasticPoolStandardMaxEDTUs eDTU) { return this.WithDatabaseDtuMax(eDTU); } /// <summary> /// Sets the storage capacity for the SQL Azure Database Elastic Pool. /// </summary> /// <param name="storageCapacity">Storage capacity for the SQL Azure Database Elastic Pool.</param> /// <return>The next stage of the definition.</return> SqlElasticPool.Definition.IWithStandardEdition<SqlDatabaseOperations.Definition.IWithExistingDatabaseAfterElasticPool> SqlElasticPool.Definition.IWithStandardEditionBeta<SqlDatabaseOperations.Definition.IWithExistingDatabaseAfterElasticPool>.WithStorageCapacity(SqlElasticPoolStandardStorage storageCapacity) { return this.WithStorageCapacity(storageCapacity); } /// <summary> /// Sets the total shared eDTU for the SQL Azure Database Elastic Pool. /// </summary> /// <param name="eDTU">Total shared eDTU for the SQL Azure Database Elastic Pool.</param> /// <return>The next stage of the definition.</return> SqlElasticPool.Definition.IWithStandardEdition<SqlDatabaseOperations.Definition.IWithExistingDatabaseAfterElasticPool> SqlElasticPool.Definition.IWithStandardEditionBeta<SqlDatabaseOperations.Definition.IWithExistingDatabaseAfterElasticPool>.WithReservedDtu(SqlElasticPoolStandardEDTUs eDTU) { return this.WithReservedDtu(eDTU); } /// <summary> /// Sets the maximum DTU any one SQL Azure Database can consume. /// </summary> /// <param name="databaseDtuMax">Maximum DTU any one SQL Azure Database can consume.</param> /// <return>The next stage of the definition.</return> SqlElasticPool.Definition.IWithAttach<SqlDatabaseOperations.Definition.IWithExistingDatabaseAfterElasticPool> SqlElasticPool.Definition.IWithDatabaseDtuMax<SqlDatabaseOperations.Definition.IWithExistingDatabaseAfterElasticPool>.WithDatabaseDtuMax(int databaseDtuMax) { return this.WithDatabaseDtuMax(databaseDtuMax); } /// <summary> /// Attaches the child definition to the parent resource definiton. /// </summary> /// <return>The next stage of the parent definition.</return> SqlDatabaseOperations.Definition.IWithExistingDatabaseAfterElasticPool Microsoft.Azure.Management.ResourceManager.Fluent.Core.ChildResource.Definition.IInDefinition<SqlDatabaseOperations.Definition.IWithExistingDatabaseAfterElasticPool>.Attach() { return this.Attach(); } /// <summary> /// Sets the basic edition for the SQL Elastic Pool. /// </summary> /// <return>The next stage of the definition.</return> SqlElasticPool.Definition.IWithBasicEdition<SqlDatabaseOperations.Definition.IWithExistingDatabaseAfterElasticPool> SqlElasticPool.Definition.IWithEditionBeta<SqlDatabaseOperations.Definition.IWithExistingDatabaseAfterElasticPool>.WithBasicPool() { return this.WithBasicPool(); } /// <summary> /// Sets the premium edition for the SQL Elastic Pool. /// </summary> /// <return>The next stage of the definition.</return> SqlElasticPool.Definition.IWithPremiumEdition<SqlDatabaseOperations.Definition.IWithExistingDatabaseAfterElasticPool> SqlElasticPool.Definition.IWithEditionBeta<SqlDatabaseOperations.Definition.IWithExistingDatabaseAfterElasticPool>.WithPremiumPool() { return this.WithPremiumPool(); } /// <summary> /// Sets the edition for the SQL Elastic Pool. /// </summary> /// <param name="edition">Edition to be set for elastic pool.</param> /// <return>The next stage of the definition.</return> SqlElasticPool.Definition.IWithAttach<SqlDatabaseOperations.Definition.IWithExistingDatabaseAfterElasticPool> SqlElasticPool.Definition.IWithEditionBeta<SqlDatabaseOperations.Definition.IWithExistingDatabaseAfterElasticPool>.WithEdition(string edition) { return this.WithEdition(edition); } /// <summary> /// Sets the standard edition for the SQL Elastic Pool. /// </summary> /// <return>The next stage of the definition.</return> SqlElasticPool.Definition.IWithStandardEdition<SqlDatabaseOperations.Definition.IWithExistingDatabaseAfterElasticPool> SqlElasticPool.Definition.IWithEditionBeta<SqlDatabaseOperations.Definition.IWithExistingDatabaseAfterElasticPool>.WithStandardPool() { return this.WithStandardPool(); } /// <summary> /// Sets the total shared DTU for the SQL Azure Database Elastic Pool. /// </summary> /// <param name="dtu">Total shared DTU for the SQL Azure Database Elastic Pool.</param> /// <return>The next stage of the definition.</return> SqlElasticPool.Definition.IWithAttach<SqlDatabaseOperations.Definition.IWithExistingDatabaseAfterElasticPool> SqlElasticPool.Definition.IWithDtu<SqlDatabaseOperations.Definition.IWithExistingDatabaseAfterElasticPool>.WithDtu(int dtu) { return this.WithDtu(dtu); } } }
// 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.Globalization; using System.IdentityModel.Selectors; using System.IdentityModel.Tokens; using System.Net.Security; using System.ServiceModel.Security; using System.ServiceModel.Security.Tokens; using System.Text; using System.Xml; namespace System.ServiceModel.Channels { public abstract class SecurityBindingElement : BindingElement { internal static readonly SecurityAlgorithmSuite defaultDefaultAlgorithmSuite = SecurityAlgorithmSuite.Default; internal const bool defaultIncludeTimestamp = true; internal const bool defaultAllowInsecureTransport = false; internal const bool defaultRequireSignatureConfirmation = false; internal const bool defaultEnableUnsecuredResponse = false; internal const bool defaultProtectTokens = false; private SecurityAlgorithmSuite _defaultAlgorithmSuite; private SecurityKeyEntropyMode _keyEntropyMode; private Dictionary<string, SupportingTokenParameters> _operationSupportingTokenParameters; private Dictionary<string, SupportingTokenParameters> _optionalOperationSupportingTokenParameters; private MessageSecurityVersion _messageSecurityVersion; private SecurityHeaderLayout _securityHeaderLayout; private bool _protectTokens = defaultProtectTokens; internal SecurityBindingElement() : base() { _messageSecurityVersion = MessageSecurityVersion.Default; _keyEntropyMode = AcceleratedTokenProvider.defaultKeyEntropyMode; IncludeTimestamp = defaultIncludeTimestamp; _defaultAlgorithmSuite = defaultDefaultAlgorithmSuite; LocalClientSettings = new LocalClientSecuritySettings(); EndpointSupportingTokenParameters = new SupportingTokenParameters(); OptionalEndpointSupportingTokenParameters = new SupportingTokenParameters(); _operationSupportingTokenParameters = new Dictionary<string, SupportingTokenParameters>(); _optionalOperationSupportingTokenParameters = new Dictionary<string, SupportingTokenParameters>(); _securityHeaderLayout = SecurityProtocolFactory.defaultSecurityHeaderLayout; } internal SecurityBindingElement(SecurityBindingElement elementToBeCloned) : base(elementToBeCloned) { if (elementToBeCloned == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(elementToBeCloned)); } _defaultAlgorithmSuite = elementToBeCloned._defaultAlgorithmSuite; IncludeTimestamp = elementToBeCloned.IncludeTimestamp; _keyEntropyMode = elementToBeCloned._keyEntropyMode; _messageSecurityVersion = elementToBeCloned._messageSecurityVersion; _securityHeaderLayout = elementToBeCloned._securityHeaderLayout; EndpointSupportingTokenParameters = elementToBeCloned.EndpointSupportingTokenParameters.Clone(); OptionalEndpointSupportingTokenParameters = elementToBeCloned.OptionalEndpointSupportingTokenParameters.Clone(); _operationSupportingTokenParameters = new Dictionary<string, SupportingTokenParameters>(); foreach (string key in elementToBeCloned._operationSupportingTokenParameters.Keys) { _operationSupportingTokenParameters[key] = elementToBeCloned._operationSupportingTokenParameters[key].Clone(); } _optionalOperationSupportingTokenParameters = new Dictionary<string, SupportingTokenParameters>(); foreach (string key in elementToBeCloned._optionalOperationSupportingTokenParameters.Keys) { _optionalOperationSupportingTokenParameters[key] = elementToBeCloned._optionalOperationSupportingTokenParameters[key].Clone(); } LocalClientSettings = elementToBeCloned.LocalClientSettings.Clone(); MaxReceivedMessageSize = elementToBeCloned.MaxReceivedMessageSize; ReaderQuotas = elementToBeCloned.ReaderQuotas; EnableUnsecuredResponse = elementToBeCloned.EnableUnsecuredResponse; } public SupportingTokenParameters EndpointSupportingTokenParameters { get; } public SupportingTokenParameters OptionalEndpointSupportingTokenParameters { get; } public IDictionary<string, SupportingTokenParameters> OperationSupportingTokenParameters => _operationSupportingTokenParameters; public IDictionary<string, SupportingTokenParameters> OptionalOperationSupportingTokenParameters => _optionalOperationSupportingTokenParameters; public SecurityHeaderLayout SecurityHeaderLayout { get { return _securityHeaderLayout; } set { if (!SecurityHeaderLayoutHelper.IsDefined(value)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(value))); } _securityHeaderLayout = value; } } public MessageSecurityVersion MessageSecurityVersion { get { return _messageSecurityVersion; } set { _messageSecurityVersion = value ?? throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(value))); } } public bool EnableUnsecuredResponse { get; set; } public bool IncludeTimestamp { get; set; } public SecurityAlgorithmSuite DefaultAlgorithmSuite { get { return _defaultAlgorithmSuite; } set { _defaultAlgorithmSuite = value ?? throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(value))); } } public LocalClientSecuritySettings LocalClientSettings { get; } public SecurityKeyEntropyMode KeyEntropyMode { get { return _keyEntropyMode; } set { if (!SecurityKeyEntropyModeHelper.IsDefined(value)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(value))); } _keyEntropyMode = value; } } internal virtual bool SessionMode { get { return false; } } internal virtual bool SupportsDuplex { get { return false; } } internal virtual bool SupportsRequestReply { get { return false; } } internal long MaxReceivedMessageSize { get; set; } = TransportDefaults.MaxReceivedMessageSize; internal XmlDictionaryReaderQuotas ReaderQuotas { get; set; } private void GetSupportingTokensCapabilities(ICollection<SecurityTokenParameters> parameters, out bool supportsClientAuth, out bool supportsWindowsIdentity) { supportsClientAuth = false; supportsWindowsIdentity = false; foreach (SecurityTokenParameters p in parameters) { if (p.SupportsClientAuthentication) { supportsClientAuth = true; } if (p.SupportsClientWindowsIdentity) { supportsWindowsIdentity = true; } } } private void GetSupportingTokensCapabilities(SupportingTokenParameters requirements, out bool supportsClientAuth, out bool supportsWindowsIdentity) { supportsClientAuth = false; supportsWindowsIdentity = false; bool tmpSupportsClientAuth; bool tmpSupportsWindowsIdentity; GetSupportingTokensCapabilities(requirements.Endorsing, out tmpSupportsClientAuth, out tmpSupportsWindowsIdentity); supportsClientAuth = supportsClientAuth || tmpSupportsClientAuth; supportsWindowsIdentity = supportsWindowsIdentity || tmpSupportsWindowsIdentity; GetSupportingTokensCapabilities(requirements.SignedEndorsing, out tmpSupportsClientAuth, out tmpSupportsWindowsIdentity); supportsClientAuth = supportsClientAuth || tmpSupportsClientAuth; supportsWindowsIdentity = supportsWindowsIdentity || tmpSupportsWindowsIdentity; GetSupportingTokensCapabilities(requirements.SignedEncrypted, out tmpSupportsClientAuth, out tmpSupportsWindowsIdentity); supportsClientAuth = supportsClientAuth || tmpSupportsClientAuth; supportsWindowsIdentity = supportsWindowsIdentity || tmpSupportsWindowsIdentity; } internal void GetSupportingTokensCapabilities(out bool supportsClientAuth, out bool supportsWindowsIdentity) { GetSupportingTokensCapabilities(EndpointSupportingTokenParameters, out supportsClientAuth, out supportsWindowsIdentity); } protected static void SetIssuerBindingContextIfRequired(SecurityTokenParameters parameters, BindingContext issuerBindingContext) { // Only needed for SslSecurityTokenParameters and SspiSecurityTokenParameters which aren't supported } private static void SetIssuerBindingContextIfRequired(SupportingTokenParameters supportingParameters, BindingContext issuerBindingContext) { for (int i = 0; i < supportingParameters.Endorsing.Count; ++i) { SetIssuerBindingContextIfRequired(supportingParameters.Endorsing[i], issuerBindingContext); } for (int i = 0; i < supportingParameters.SignedEndorsing.Count; ++i) { SetIssuerBindingContextIfRequired(supportingParameters.SignedEndorsing[i], issuerBindingContext); } for (int i = 0; i < supportingParameters.Signed.Count; ++i) { SetIssuerBindingContextIfRequired(supportingParameters.Signed[i], issuerBindingContext); } for (int i = 0; i < supportingParameters.SignedEncrypted.Count; ++i) { SetIssuerBindingContextIfRequired(supportingParameters.SignedEncrypted[i], issuerBindingContext); } } private void SetIssuerBindingContextIfRequired(BindingContext issuerBindingContext) { SetIssuerBindingContextIfRequired(EndpointSupportingTokenParameters, issuerBindingContext); } internal bool RequiresChannelDemuxer(SecurityTokenParameters parameters) { return (parameters is SecureConversationSecurityTokenParameters); } internal virtual bool RequiresChannelDemuxer() { foreach (SecurityTokenParameters parameters in EndpointSupportingTokenParameters.Endorsing) { if (RequiresChannelDemuxer(parameters)) { return true; } } foreach (SecurityTokenParameters parameters in EndpointSupportingTokenParameters.SignedEndorsing) { if (RequiresChannelDemuxer(parameters)) { return true; } } return false; } private void SetPrivacyNoticeUriIfRequired(SecurityProtocolFactory factory, Binding binding) { // Only used for WS-Fed and configures a PrivacyNoticeBindingElement if present. // Not currently supported on .NET Core } internal void ConfigureProtocolFactory(SecurityProtocolFactory factory, SecurityCredentialsManager credentialsManager, bool isForService, BindingContext issuerBindingContext, Binding binding) { if (factory == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(factory))); } if (credentialsManager == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(credentialsManager))); } factory.AddTimestamp = IncludeTimestamp; factory.IncomingAlgorithmSuite = DefaultAlgorithmSuite; factory.OutgoingAlgorithmSuite = DefaultAlgorithmSuite; factory.SecurityHeaderLayout = SecurityHeaderLayout; if (!isForService) { factory.TimestampValidityDuration = LocalClientSettings.TimestampValidityDuration; factory.DetectReplays = LocalClientSettings.DetectReplays; factory.MaxCachedNonces = LocalClientSettings.ReplayCacheSize; factory.MaxClockSkew = LocalClientSettings.MaxClockSkew; factory.ReplayWindow = LocalClientSettings.ReplayWindow; if (LocalClientSettings.DetectReplays) { factory.NonceCache = LocalClientSettings.NonceCache; } } else { throw ExceptionHelper.PlatformNotSupported(); } factory.SecurityBindingElement = (SecurityBindingElement)Clone(); factory.SecurityBindingElement.SetIssuerBindingContextIfRequired(issuerBindingContext); factory.SecurityTokenManager = credentialsManager.CreateSecurityTokenManager(); SecurityTokenSerializer tokenSerializer = factory.SecurityTokenManager.CreateSecurityTokenSerializer(_messageSecurityVersion.SecurityTokenVersion); factory.StandardsManager = new SecurityStandardsManager(_messageSecurityVersion, tokenSerializer); if (!isForService) { SetPrivacyNoticeUriIfRequired(factory, binding); } } internal abstract SecurityProtocolFactory CreateSecurityProtocolFactory<TChannel>(BindingContext context, SecurityCredentialsManager credentialsManager, bool isForService, BindingContext issuanceBindingContext); public override IChannelFactory<TChannel> BuildChannelFactory<TChannel>(BindingContext context) { if (context == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(context)); } if (!CanBuildChannelFactory<TChannel>(context)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.Format(SR.ChannelTypeNotSupported, typeof(TChannel)), nameof(TChannel))); } ReaderQuotas = context.GetInnerProperty<XmlDictionaryReaderQuotas>(); if (ReaderQuotas == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.EncodingBindingElementDoesNotHandleReaderQuotas)); } TransportBindingElement transportBindingElement = null; if (context.RemainingBindingElements != null) { transportBindingElement = context.RemainingBindingElements.Find<TransportBindingElement>(); } if (transportBindingElement != null) { MaxReceivedMessageSize = transportBindingElement.MaxReceivedMessageSize; } IChannelFactory<TChannel> result = BuildChannelFactoryCore<TChannel>(context); return result; } protected abstract IChannelFactory<TChannel> BuildChannelFactoryCore<TChannel>(BindingContext context); public override bool CanBuildChannelFactory<TChannel>(BindingContext context) { if (context == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(context)); } if (SessionMode) { return CanBuildSessionChannelFactory<TChannel>(context); } if (!context.CanBuildInnerChannelFactory<TChannel>()) { return false; } return typeof(TChannel) == typeof(IOutputChannel) || typeof(TChannel) == typeof(IOutputSessionChannel) || (SupportsDuplex && (typeof(TChannel) == typeof(IDuplexChannel) || typeof(TChannel) == typeof(IDuplexSessionChannel))) || (SupportsRequestReply && (typeof(TChannel) == typeof(IRequestChannel) || typeof(TChannel) == typeof(IRequestSessionChannel))); } private bool CanBuildSessionChannelFactory<TChannel>(BindingContext context) { if (!(context.CanBuildInnerChannelFactory<IRequestChannel>() || context.CanBuildInnerChannelFactory<IRequestSessionChannel>() || context.CanBuildInnerChannelFactory<IDuplexChannel>() || context.CanBuildInnerChannelFactory<IDuplexSessionChannel>())) { return false; } if (typeof(TChannel) == typeof(IRequestSessionChannel)) { return (context.CanBuildInnerChannelFactory<IRequestChannel>() || context.CanBuildInnerChannelFactory<IRequestSessionChannel>()); } else if (typeof(TChannel) == typeof(IDuplexSessionChannel)) { return (context.CanBuildInnerChannelFactory<IDuplexChannel>() || context.CanBuildInnerChannelFactory<IDuplexSessionChannel>()); } else { return false; } } public virtual void SetKeyDerivation(bool requireDerivedKeys) { EndpointSupportingTokenParameters.SetKeyDerivation(requireDerivedKeys); } internal virtual bool IsSetKeyDerivation(bool requireDerivedKeys) { if (!EndpointSupportingTokenParameters.IsSetKeyDerivation(requireDerivedKeys)) { return false; } return true; } public override T GetProperty<T>(BindingContext context) { if (context == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(context)); } if (typeof(T) == typeof(ISecurityCapabilities)) { return (T)(object)GetSecurityCapabilities(context); } else if (typeof(T) == typeof(IdentityVerifier)) { return (T)(object)LocalClientSettings.IdentityVerifier; } else { return context.GetInnerProperty<T>(); } } internal abstract ISecurityCapabilities GetIndividualISecurityCapabilities(); private ISecurityCapabilities GetSecurityCapabilities(BindingContext context) { ISecurityCapabilities thisSecurityCapability = GetIndividualISecurityCapabilities(); ISecurityCapabilities lowerSecurityCapability = context.GetInnerProperty<ISecurityCapabilities>(); if (lowerSecurityCapability == null) { return thisSecurityCapability; } else { bool supportsClientAuth = thisSecurityCapability.SupportsClientAuthentication; bool supportsClientWindowsIdentity = thisSecurityCapability.SupportsClientWindowsIdentity; bool supportsServerAuth = thisSecurityCapability.SupportsServerAuthentication || lowerSecurityCapability.SupportsServerAuthentication; ProtectionLevel requestProtectionLevel = ProtectionLevelHelper.Max(thisSecurityCapability.SupportedRequestProtectionLevel, lowerSecurityCapability.SupportedRequestProtectionLevel); ProtectionLevel responseProtectionLevel = ProtectionLevelHelper.Max(thisSecurityCapability.SupportedResponseProtectionLevel, lowerSecurityCapability.SupportedResponseProtectionLevel); return new SecurityCapabilities(supportsClientAuth, supportsServerAuth, supportsClientWindowsIdentity, requestProtectionLevel, responseProtectionLevel); } } internal void ApplyPropertiesOnDemuxer(ChannelBuilder builder, BindingContext context) { // Only used for services } static public SecurityBindingElement CreateMutualCertificateBindingElement() { return CreateMutualCertificateBindingElement(MessageSecurityVersion.WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11); } static public SecurityBindingElement CreateMutualCertificateBindingElement(MessageSecurityVersion version) { return CreateMutualCertificateBindingElement(version, false); } static public SecurityBindingElement CreateMutualCertificateBindingElement(MessageSecurityVersion version, bool allowSerializedSigningTokenOnReply) { if (version == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(version)); } throw ExceptionHelper.PlatformNotSupported("SecurityBindingElement.CreateMutualCertificateBindingElement is not supported."); } static public TransportSecurityBindingElement CreateUserNameOverTransportBindingElement() { var result = new TransportSecurityBindingElement(); result.EndpointSupportingTokenParameters.SignedEncrypted.Add( new UserNameSecurityTokenParameters()); result.IncludeTimestamp = true; result.LocalClientSettings.DetectReplays = false; return result; } static public TransportSecurityBindingElement CreateCertificateOverTransportBindingElement() { return CreateCertificateOverTransportBindingElement(MessageSecurityVersion.Default); } static public TransportSecurityBindingElement CreateCertificateOverTransportBindingElement(MessageSecurityVersion version) { if (version == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(version)); } X509KeyIdentifierClauseType x509ReferenceType; if (version.SecurityVersion == SecurityVersion.WSSecurity10) { x509ReferenceType = X509KeyIdentifierClauseType.Any; } else { x509ReferenceType = X509KeyIdentifierClauseType.Thumbprint; } TransportSecurityBindingElement result = new TransportSecurityBindingElement(); X509SecurityTokenParameters x509Parameters = new X509SecurityTokenParameters( x509ReferenceType, SecurityTokenInclusionMode.AlwaysToRecipient, false); result.EndpointSupportingTokenParameters.Endorsing.Add( x509Parameters ); result.IncludeTimestamp = true; result.LocalClientSettings.DetectReplays = false; //result.LocalServiceSettings.DetectReplays = false; result.MessageSecurityVersion = version; return result; } public static TransportSecurityBindingElement CreateIssuedTokenOverTransportBindingElement(IssuedSecurityTokenParameters issuedTokenParameters) { if (issuedTokenParameters == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("issuedTokenParameters"); issuedTokenParameters.RequireDerivedKeys = false; TransportSecurityBindingElement result = new TransportSecurityBindingElement(); if (issuedTokenParameters.KeyType == SecurityKeyType.BearerKey) { result.EndpointSupportingTokenParameters.Signed.Add(issuedTokenParameters); result.MessageSecurityVersion = MessageSecurityVersion.WSSXDefault; } else { result.EndpointSupportingTokenParameters.Endorsing.Add(issuedTokenParameters); result.MessageSecurityVersion = MessageSecurityVersion.Default; } result.LocalClientSettings.DetectReplays = false; result.IncludeTimestamp = true; return result; } static public SecurityBindingElement CreateSecureConversationBindingElement(SecurityBindingElement bootstrapSecurity) { return CreateSecureConversationBindingElement(bootstrapSecurity, SecureConversationSecurityTokenParameters.defaultRequireCancellation, null); } static public SecurityBindingElement CreateSecureConversationBindingElement(SecurityBindingElement bootstrapSecurity, bool requireCancellation) { return CreateSecureConversationBindingElement(bootstrapSecurity, requireCancellation, null); } static public SecurityBindingElement CreateSecureConversationBindingElement(SecurityBindingElement bootstrapSecurity, bool requireCancellation, ChannelProtectionRequirements bootstrapProtectionRequirements) { if (bootstrapSecurity == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(bootstrapSecurity)); } SecurityBindingElement result; if (bootstrapSecurity is TransportSecurityBindingElement) { // there is no need to do replay detection or key derivation for transport bindings var primary = new TransportSecurityBindingElement(); var scParameters = new SecureConversationSecurityTokenParameters( bootstrapSecurity, requireCancellation, bootstrapProtectionRequirements); scParameters.RequireDerivedKeys = false; primary.EndpointSupportingTokenParameters.Endorsing.Add( scParameters); primary.LocalClientSettings.DetectReplays = false; primary.IncludeTimestamp = true; result = primary; } else // Symmetric- or AsymmetricSecurityBindingElement { throw ExceptionHelper.PlatformNotSupported(); } return result; } public override string ToString() { StringBuilder sb = new StringBuilder(); sb.AppendLine(string.Format(CultureInfo.InvariantCulture, "{0}:", GetType().ToString())); sb.AppendLine(string.Format(CultureInfo.InvariantCulture, "DefaultAlgorithmSuite: {0}", _defaultAlgorithmSuite.ToString())); sb.AppendLine(string.Format(CultureInfo.InvariantCulture, "IncludeTimestamp: {0}", IncludeTimestamp.ToString())); sb.AppendLine(string.Format(CultureInfo.InvariantCulture, "KeyEntropyMode: {0}", _keyEntropyMode.ToString())); sb.AppendLine(string.Format(CultureInfo.InvariantCulture, "MessageSecurityVersion: {0}", MessageSecurityVersion.ToString())); sb.AppendLine(string.Format(CultureInfo.InvariantCulture, "SecurityHeaderLayout: {0}", _securityHeaderLayout.ToString())); sb.AppendLine(string.Format(CultureInfo.InvariantCulture, "ProtectTokens: {0}", _protectTokens.ToString())); sb.AppendLine("EndpointSupportingTokenParameters:"); sb.AppendLine(" " + EndpointSupportingTokenParameters.ToString().Trim().Replace("\n", "\n ")); sb.AppendLine("OptionalEndpointSupportingTokenParameters:"); sb.AppendLine(" " + OptionalEndpointSupportingTokenParameters.ToString().Trim().Replace("\n", "\n ")); if (_operationSupportingTokenParameters.Count == 0) { sb.AppendLine(string.Format(CultureInfo.InvariantCulture, "OperationSupportingTokenParameters: none")); } else { foreach (string requestAction in OperationSupportingTokenParameters.Keys) { sb.AppendLine(string.Format(CultureInfo.InvariantCulture, "OperationSupportingTokenParameters[\"{0}\"]:", requestAction)); sb.AppendLine(" " + OperationSupportingTokenParameters[requestAction].ToString().Trim().Replace("\n", "\n ")); } } if (_optionalOperationSupportingTokenParameters.Count == 0) { sb.AppendLine(string.Format(CultureInfo.InvariantCulture, "OptionalOperationSupportingTokenParameters: none")); } else { foreach (string requestAction in OptionalOperationSupportingTokenParameters.Keys) { sb.AppendLine(string.Format(CultureInfo.InvariantCulture, "OptionalOperationSupportingTokenParameters[\"{0}\"]:", requestAction)); sb.AppendLine(" " + OptionalOperationSupportingTokenParameters[requestAction].ToString().Trim().Replace("\n", "\n ")); } } return sb.ToString().Trim(); } } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Class: StreamWriter ** ** <OWNER>gpaperin</OWNER> ** ** ** Purpose: For writing text to streams in a particular ** encoding. ** ** ===========================================================*/ using System; using System.Text; using System.Threading; using System.Globalization; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security.Permissions; using System.Runtime.Serialization; using System.Diagnostics.Contracts; using System.Runtime.InteropServices; #if FEATURE_ASYNC_IO using System.Threading.Tasks; #endif namespace System.IO { // This class implements a TextWriter for writing characters to a Stream. // This is designed for character output in a particular Encoding, // whereas the Stream class is designed for byte input and output. // [Serializable] [ComVisible(true)] public class StreamWriter : TextWriter { // For UTF-8, the values of 1K for the default buffer size and 4K for the // file stream buffer size are reasonable & give very reasonable // performance for in terms of construction time for the StreamWriter and // write perf. Note that for UTF-8, we end up allocating a 4K byte buffer, // which means we take advantage of adaptive buffering code. // The performance using UnicodeEncoding is acceptable. internal const int DefaultBufferSize = 1024; // char[] private const int DefaultFileStreamBufferSize = 4096; private const int MinBufferSize = 128; #if FEATURE_ASYNC_IO private const Int32 DontCopyOnWriteLineThreshold = 512; #endif // Bit bucket - Null has no backing store. Non closable. public new static readonly StreamWriter Null = new StreamWriter(Stream.Null, new UTF8Encoding(false, true), MinBufferSize, true); private Stream stream; private Encoding encoding; private Encoder encoder; private byte[] byteBuffer; private char[] charBuffer; private int charPos; private int charLen; private bool autoFlush; private bool haveWrittenPreamble; private bool closable; #if MDA_SUPPORTED [NonSerialized] // For StreamWriterBufferedDataLost MDA private MdaHelper mdaHelper; #endif #if FEATURE_ASYNC_IO // We don't guarantee thread safety on StreamWriter, but we should at // least prevent users from trying to write anything while an Async // write from the same thread is in progress. [NonSerialized] private volatile Task _asyncWriteTask; private void CheckAsyncTaskInProgress() { // We are not locking the access to _asyncWriteTask because this is not meant to guarantee thread safety. // We are simply trying to deter calling any Write APIs while an async Write from the same thread is in progress. Task t = _asyncWriteTask; if (t != null && !t.IsCompleted) throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_AsyncIOInProgress")); } #endif // The high level goal is to be tolerant of encoding errors when we read and very strict // when we write. Hence, default StreamWriter encoding will throw on encoding error. // Note: when StreamWriter throws on invalid encoding chars (for ex, high surrogate character // D800-DBFF without a following low surrogate character DC00-DFFF), it will cause the // internal StreamWriter's state to be irrecoverable as it would have buffered the // illegal chars and any subsequent call to Flush() would hit the encoding error again. // Even Close() will hit the exception as it would try to flush the unwritten data. // Maybe we can add a DiscardBufferedData() method to get out of such situation (like // StreamReader though for different reason). Either way, the buffered data will be lost! private static volatile Encoding _UTF8NoBOM; internal static Encoding UTF8NoBOM { [FriendAccessAllowed] get { if (_UTF8NoBOM == null) { // No need for double lock - we just want to avoid extra // allocations in the common case. UTF8Encoding noBOM = new UTF8Encoding(false, true); Thread.MemoryBarrier(); _UTF8NoBOM = noBOM; } return _UTF8NoBOM; } } internal StreamWriter(): base(null) { // Ask for CurrentCulture all the time } public StreamWriter(Stream stream) : this(stream, UTF8NoBOM, DefaultBufferSize, false) { } public StreamWriter(Stream stream, Encoding encoding) : this(stream, encoding, DefaultBufferSize, false) { } // Creates a new StreamWriter for the given stream. The // character encoding is set by encoding and the buffer size, // in number of 16-bit characters, is set by bufferSize. // public StreamWriter(Stream stream, Encoding encoding, int bufferSize) : this(stream, encoding, bufferSize, false) { } public StreamWriter(Stream stream, Encoding encoding, int bufferSize, bool leaveOpen) : base(null) // Ask for CurrentCulture all the time { if (stream == null || encoding == null) throw new ArgumentNullException((stream == null ? "stream" : "encoding")); if (!stream.CanWrite) throw new ArgumentException(Environment.GetResourceString("Argument_StreamNotWritable")); if (bufferSize <= 0) throw new ArgumentOutOfRangeException("bufferSize", Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum")); Contract.EndContractBlock(); Init(stream, encoding, bufferSize, leaveOpen); } #if FEATURE_LEGACYNETCFIOSECURITY [System.Security.SecurityCritical] #endif //FEATURE_LEGACYNETCFIOSECURITY [ResourceExposure(ResourceScope.Machine)] [ResourceConsumption(ResourceScope.Machine)] public StreamWriter(String path) : this(path, false, UTF8NoBOM, DefaultBufferSize) { } #if FEATURE_LEGACYNETCFIOSECURITY [System.Security.SecurityCritical] #endif //FEATURE_LEGACYNETCFIOSECURITY [ResourceExposure(ResourceScope.Machine)] [ResourceConsumption(ResourceScope.Machine)] public StreamWriter(String path, bool append) : this(path, append, UTF8NoBOM, DefaultBufferSize) { } #if FEATURE_LEGACYNETCFIOSECURITY [System.Security.SecurityCritical] #endif //FEATURE_LEGACYNETCFIOSECURITY [ResourceExposure(ResourceScope.Machine)] [ResourceConsumption(ResourceScope.Machine)] public StreamWriter(String path, bool append, Encoding encoding) : this(path, append, encoding, DefaultBufferSize) { } #if FEATURE_LEGACYNETCFIOSECURITY [System.Security.SecurityCritical] #else [System.Security.SecuritySafeCritical] #endif //FEATURE_LEGACYNETCFIOSECURITY [ResourceExposure(ResourceScope.Machine)] [ResourceConsumption(ResourceScope.Machine)] public StreamWriter(String path, bool append, Encoding encoding, int bufferSize): this(path, append, encoding, bufferSize, true) { } [System.Security.SecurityCritical] [ResourceExposure(ResourceScope.Machine)] [ResourceConsumption(ResourceScope.Machine)] internal StreamWriter(String path, bool append, Encoding encoding, int bufferSize, bool checkHost) : base(null) { // Ask for CurrentCulture all the time if (path == null) throw new ArgumentNullException("path"); if (encoding == null) throw new ArgumentNullException("encoding"); if (path.Length == 0) throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath")); if (bufferSize <= 0) throw new ArgumentOutOfRangeException("bufferSize", Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum")); Contract.EndContractBlock(); Stream stream = CreateFile(path, append, checkHost); Init(stream, encoding, bufferSize, false); } [System.Security.SecuritySafeCritical] private void Init(Stream streamArg, Encoding encodingArg, int bufferSize, bool shouldLeaveOpen) { this.stream = streamArg; this.encoding = encodingArg; this.encoder = encoding.GetEncoder(); if (bufferSize < MinBufferSize) bufferSize = MinBufferSize; charBuffer = new char[bufferSize]; byteBuffer = new byte[encoding.GetMaxByteCount(bufferSize)]; charLen = bufferSize; // If we're appending to a Stream that already has data, don't write // the preamble. if (stream.CanSeek && stream.Position > 0) haveWrittenPreamble = true; closable = !shouldLeaveOpen; #if MDA_SUPPORTED if (Mda.StreamWriterBufferedDataLost.Enabled) { String callstack = null; if (Mda.StreamWriterBufferedDataLost.CaptureAllocatedCallStack) callstack = Environment.GetStackTrace(null, false); mdaHelper = new MdaHelper(this, callstack); } #endif } [System.Security.SecurityCritical] [ResourceExposure(ResourceScope.Machine)] [ResourceConsumption(ResourceScope.Machine)] private static Stream CreateFile(String path, bool append, bool checkHost) { FileMode mode = append? FileMode.Append: FileMode.Create; FileStream f = new FileStream(path, mode, FileAccess.Write, FileShare.Read, DefaultFileStreamBufferSize, FileOptions.SequentialScan, Path.GetFileName(path), false, false, checkHost); return f; } public override void Close() { Dispose(true); GC.SuppressFinalize(this); } protected override void Dispose(bool disposing) { try { // We need to flush any buffered data if we are being closed/disposed. // Also, we never close the handles for stdout & friends. So we can safely // write any buffered data to those streams even during finalization, which // is generally the right thing to do. if (stream != null) { // Note: flush on the underlying stream can throw (ex., low disk space) if (disposing || (LeaveOpen && stream is __ConsoleStream)) { #if FEATURE_ASYNC_IO CheckAsyncTaskInProgress(); #endif Flush(true, true); #if MDA_SUPPORTED // Disable buffered data loss mda if (mdaHelper != null) GC.SuppressFinalize(mdaHelper); #endif } } } finally { // Dispose of our resources if this StreamWriter is closable. // Note: Console.Out and other such non closable streamwriters should be left alone if (!LeaveOpen && stream != null) { try { // Attempt to close the stream even if there was an IO error from Flushing. // Note that Stream.Close() can potentially throw here (may or may not be // due to the same Flush error). In this case, we still need to ensure // cleaning up internal resources, hence the finally block. if (disposing) stream.Close(); } finally { stream = null; byteBuffer = null; charBuffer = null; encoding = null; encoder = null; charLen = 0; base.Dispose(disposing); } } } } public override void Flush() { #if FEATURE_ASYNC_IO CheckAsyncTaskInProgress(); #endif Flush(true, true); } private void Flush(bool flushStream, bool flushEncoder) { // flushEncoder should be true at the end of the file and if // the user explicitly calls Flush (though not if AutoFlush is true). // This is required to flush any dangling characters from our UTF-7 // and UTF-8 encoders. if (stream == null) __Error.WriterClosed(); // Perf boost for Flush on non-dirty writers. if (charPos==0 && ((!flushStream && !flushEncoder) || CompatibilitySwitches.IsAppEarlierThanWindowsPhone8)) return; if (!haveWrittenPreamble) { haveWrittenPreamble = true; byte[] preamble = encoding.GetPreamble(); if (preamble.Length > 0) stream.Write(preamble, 0, preamble.Length); } int count = encoder.GetBytes(charBuffer, 0, charPos, byteBuffer, 0, flushEncoder); charPos = 0; if (count > 0) stream.Write(byteBuffer, 0, count); // By definition, calling Flush should flush the stream, but this is // only necessary if we passed in true for flushStream. The Web // Services guys have some perf tests where flushing needlessly hurts. if (flushStream) stream.Flush(); } public virtual bool AutoFlush { get { return autoFlush; } set { #if FEATURE_ASYNC_IO CheckAsyncTaskInProgress(); #endif autoFlush = value; if (value) Flush(true, false); } } public virtual Stream BaseStream { get { return stream; } } internal bool LeaveOpen { get { return !closable; } } internal bool HaveWrittenPreamble { set { haveWrittenPreamble= value; } } public override Encoding Encoding { get { return encoding; } } public override void Write(char value) { #if FEATURE_ASYNC_IO CheckAsyncTaskInProgress(); #endif if (charPos == charLen) Flush(false, false); charBuffer[charPos] = value; charPos++; if (autoFlush) Flush(true, false); } public override void Write(char[] buffer) { // This may be faster than the one with the index & count since it // has to do less argument checking. if (buffer==null) return; #if FEATURE_ASYNC_IO CheckAsyncTaskInProgress(); #endif int index = 0; int count = buffer.Length; while (count > 0) { if (charPos == charLen) Flush(false, false); int n = charLen - charPos; if (n > count) n = count; Contract.Assert(n > 0, "StreamWriter::Write(char[]) isn't making progress! This is most likely a ---- in user code."); Buffer.InternalBlockCopy(buffer, index * sizeof(char), charBuffer, charPos * sizeof(char), n * sizeof(char)); charPos += n; index += n; count -= n; } if (autoFlush) Flush(true, false); } public override void Write(char[] buffer, int index, int count) { if (buffer==null) throw new ArgumentNullException("buffer", Environment.GetResourceString("ArgumentNull_Buffer")); if (index < 0) throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (count < 0) throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (buffer.Length - index < count) throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen")); Contract.EndContractBlock(); #if FEATURE_ASYNC_IO CheckAsyncTaskInProgress(); #endif while (count > 0) { if (charPos == charLen) Flush(false, false); int n = charLen - charPos; if (n > count) n = count; Contract.Assert(n > 0, "StreamWriter::Write(char[], int, int) isn't making progress! This is most likely a race condition in user code."); Buffer.InternalBlockCopy(buffer, index * sizeof(char), charBuffer, charPos * sizeof(char), n * sizeof(char)); charPos += n; index += n; count -= n; } if (autoFlush) Flush(true, false); } public override void Write(String value) { if (value != null) { #if FEATURE_ASYNC_IO CheckAsyncTaskInProgress(); #endif int count = value.Length; int index = 0; while (count > 0) { if (charPos == charLen) Flush(false, false); int n = charLen - charPos; if (n > count) n = count; Contract.Assert(n > 0, "StreamWriter::Write(String) isn't making progress! This is most likely a race condition in user code."); value.CopyTo(index, charBuffer, charPos, n); charPos += n; index += n; count -= n; } if (autoFlush) Flush(true, false); } } #if FEATURE_ASYNC_IO #region Task based Async APIs [HostProtection(ExternalThreading = true)] [ComVisible(false)] public override Task WriteAsync(char value) { // If we have been inherited into a subclass, the following implementation could be incorrect // since it does not call through to Write() which a subclass might have overriden. // To be safe we will only use this implementation in cases where we know it is safe to do so, // and delegate to our base class (which will call into Write) when we are not sure. if (this.GetType() != typeof(StreamWriter)) return base.WriteAsync(value); if (stream == null) __Error.WriterClosed(); CheckAsyncTaskInProgress(); Task task = WriteAsyncInternal(this, value, charBuffer, charPos, charLen, CoreNewLine, autoFlush, appendNewLine: false); _asyncWriteTask = task; return task; } // We pass in private instance fields of this MarshalByRefObject-derived type as local params // to ensure performant access inside the state machine that corresponds this async method. // Fields that are written to must be assigned at the end of the method *and* before instance invocations. private static async Task WriteAsyncInternal(StreamWriter _this, Char value, Char[] charBuffer, Int32 charPos, Int32 charLen, Char[] coreNewLine, bool autoFlush, bool appendNewLine) { if (charPos == charLen) { await _this.FlushAsyncInternal(false, false, charBuffer, charPos).ConfigureAwait(false); Contract.Assert(_this.charPos == 0); charPos = 0; } charBuffer[charPos] = value; charPos++; if (appendNewLine) { for (Int32 i = 0; i < coreNewLine.Length; i++) // Expect 2 iterations, no point calling BlockCopy { if (charPos == charLen) { await _this.FlushAsyncInternal(false, false, charBuffer, charPos).ConfigureAwait(false); Contract.Assert(_this.charPos == 0); charPos = 0; } charBuffer[charPos] = coreNewLine[i]; charPos++; } } if (autoFlush) { await _this.FlushAsyncInternal(true, false, charBuffer, charPos).ConfigureAwait(false); Contract.Assert(_this.charPos == 0); charPos = 0; } _this.CharPos_Prop = charPos; } [HostProtection(ExternalThreading = true)] [ComVisible(false)] public override Task WriteAsync(String value) { // If we have been inherited into a subclass, the following implementation could be incorrect // since it does not call through to Write() which a subclass might have overriden. // To be safe we will only use this implementation in cases where we know it is safe to do so, // and delegate to our base class (which will call into Write) when we are not sure. if (this.GetType() != typeof(StreamWriter)) return base.WriteAsync(value); if (value != null) { if (stream == null) __Error.WriterClosed(); CheckAsyncTaskInProgress(); Task task = WriteAsyncInternal(this, value, charBuffer, charPos, charLen, CoreNewLine, autoFlush, appendNewLine: false); _asyncWriteTask = task; return task; } else { return Task.CompletedTask; } } // We pass in private instance fields of this MarshalByRefObject-derived type as local params // to ensure performant access inside the state machine that corresponds this async method. // Fields that are written to must be assigned at the end of the method *and* before instance invocations. private static async Task WriteAsyncInternal(StreamWriter _this, String value, Char[] charBuffer, Int32 charPos, Int32 charLen, Char[] coreNewLine, bool autoFlush, bool appendNewLine) { Contract.Requires(value != null); int count = value.Length; int index = 0; while (count > 0) { if (charPos == charLen) { await _this.FlushAsyncInternal(false, false, charBuffer, charPos).ConfigureAwait(false); Contract.Assert(_this.charPos == 0); charPos = 0; } int n = charLen - charPos; if (n > count) n = count; Contract.Assert(n > 0, "StreamWriter::Write(String) isn't making progress! This is most likely a race condition in user code."); value.CopyTo(index, charBuffer, charPos, n); charPos += n; index += n; count -= n; } if (appendNewLine) { for (Int32 i = 0; i < coreNewLine.Length; i++) // Expect 2 iterations, no point calling BlockCopy { if (charPos == charLen) { await _this.FlushAsyncInternal(false, false, charBuffer, charPos).ConfigureAwait(false); Contract.Assert(_this.charPos == 0); charPos = 0; } charBuffer[charPos] = coreNewLine[i]; charPos++; } } if (autoFlush) { await _this.FlushAsyncInternal(true, false, charBuffer, charPos).ConfigureAwait(false); Contract.Assert(_this.charPos == 0); charPos = 0; } _this.CharPos_Prop = charPos; } [HostProtection(ExternalThreading = true)] [ComVisible(false)] public override Task WriteAsync(char[] buffer, int index, int count) { if (buffer==null) throw new ArgumentNullException("buffer", Environment.GetResourceString("ArgumentNull_Buffer")); if (index < 0) throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (count < 0) throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (buffer.Length - index < count) throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen")); Contract.EndContractBlock(); // If we have been inherited into a subclass, the following implementation could be incorrect // since it does not call through to Write() which a subclass might have overriden. // To be safe we will only use this implementation in cases where we know it is safe to do so, // and delegate to our base class (which will call into Write) when we are not sure. if (this.GetType() != typeof(StreamWriter)) return base.WriteAsync(buffer, index, count); if (stream == null) __Error.WriterClosed(); CheckAsyncTaskInProgress(); Task task = WriteAsyncInternal(this, buffer, index, count, charBuffer, charPos, charLen, CoreNewLine, autoFlush, appendNewLine: false); _asyncWriteTask = task; return task; } // We pass in private instance fields of this MarshalByRefObject-derived type as local params // to ensure performant access inside the state machine that corresponds this async method. // Fields that are written to must be assigned at the end of the method *and* before instance invocations. private static async Task WriteAsyncInternal(StreamWriter _this, Char[] buffer, Int32 index, Int32 count, Char[] charBuffer, Int32 charPos, Int32 charLen, Char[] coreNewLine, bool autoFlush, bool appendNewLine) { Contract.Requires(count == 0 || (count > 0 && buffer != null)); Contract.Requires(index >= 0); Contract.Requires(count >= 0); Contract.Requires(buffer == null || (buffer != null && buffer.Length - index >= count)); while (count > 0) { if (charPos == charLen) { await _this.FlushAsyncInternal(false, false, charBuffer, charPos).ConfigureAwait(false); Contract.Assert(_this.charPos == 0); charPos = 0; } int n = charLen - charPos; if (n > count) n = count; Contract.Assert(n > 0, "StreamWriter::Write(char[], int, int) isn't making progress! This is most likely a race condition in user code."); Buffer.InternalBlockCopy(buffer, index * sizeof(char), charBuffer, charPos * sizeof(char), n * sizeof(char)); charPos += n; index += n; count -= n; } if (appendNewLine) { for (Int32 i = 0; i < coreNewLine.Length; i++) // Expect 2 iterations, no point calling BlockCopy { if (charPos == charLen) { await _this.FlushAsyncInternal(false, false, charBuffer, charPos).ConfigureAwait(false); Contract.Assert(_this.charPos == 0); charPos = 0; } charBuffer[charPos] = coreNewLine[i]; charPos++; } } if (autoFlush) { await _this.FlushAsyncInternal(true, false, charBuffer, charPos).ConfigureAwait(false); Contract.Assert(_this.charPos == 0); charPos = 0; } _this.CharPos_Prop = charPos; } [HostProtection(ExternalThreading = true)] [ComVisible(false)] public override Task WriteLineAsync() { // If we have been inherited into a subclass, the following implementation could be incorrect // since it does not call through to Write() which a subclass might have overriden. // To be safe we will only use this implementation in cases where we know it is safe to do so, // and delegate to our base class (which will call into Write) when we are not sure. if (this.GetType() != typeof(StreamWriter)) return base.WriteLineAsync(); if (stream == null) __Error.WriterClosed(); CheckAsyncTaskInProgress(); Task task = WriteAsyncInternal(this, null, 0, 0, charBuffer, charPos, charLen, CoreNewLine, autoFlush, appendNewLine: true); _asyncWriteTask = task; return task; } [HostProtection(ExternalThreading = true)] [ComVisible(false)] public override Task WriteLineAsync(char value) { // If we have been inherited into a subclass, the following implementation could be incorrect // since it does not call through to Write() which a subclass might have overriden. // To be safe we will only use this implementation in cases where we know it is safe to do so, // and delegate to our base class (which will call into Write) when we are not sure. if (this.GetType() != typeof(StreamWriter)) return base.WriteLineAsync(value); if (stream == null) __Error.WriterClosed(); CheckAsyncTaskInProgress(); Task task = WriteAsyncInternal(this, value, charBuffer, charPos, charLen, CoreNewLine, autoFlush, appendNewLine: true); _asyncWriteTask = task; return task; } [HostProtection(ExternalThreading = true)] [ComVisible(false)] public override Task WriteLineAsync(String value) { // If we have been inherited into a subclass, the following implementation could be incorrect // since it does not call through to Write() which a subclass might have overriden. // To be safe we will only use this implementation in cases where we know it is safe to do so, // and delegate to our base class (which will call into Write) when we are not sure. if (this.GetType() != typeof(StreamWriter)) return base.WriteLineAsync(value); if (stream == null) __Error.WriterClosed(); CheckAsyncTaskInProgress(); Task task = WriteAsyncInternal(this, value, charBuffer, charPos, charLen, CoreNewLine, autoFlush, appendNewLine: true); _asyncWriteTask = task; return task; } [HostProtection(ExternalThreading = true)] [ComVisible(false)] public override Task WriteLineAsync(char[] buffer, int index, int count) { if (buffer==null) throw new ArgumentNullException("buffer", Environment.GetResourceString("ArgumentNull_Buffer")); if (index < 0) throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (count < 0) throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (buffer.Length - index < count) throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen")); Contract.EndContractBlock(); // If we have been inherited into a subclass, the following implementation could be incorrect // since it does not call through to Write() which a subclass might have overriden. // To be safe we will only use this implementation in cases where we know it is safe to do so, // and delegate to our base class (which will call into Write) when we are not sure. if (this.GetType() != typeof(StreamWriter)) return base.WriteLineAsync(buffer, index, count); if (stream == null) __Error.WriterClosed(); CheckAsyncTaskInProgress(); Task task = WriteAsyncInternal(this, buffer, index, count, charBuffer, charPos, charLen, CoreNewLine, autoFlush, appendNewLine: true); _asyncWriteTask = task; return task; } [HostProtection(ExternalThreading = true)] [ComVisible(false)] public override Task FlushAsync() { // If we have been inherited into a subclass, the following implementation could be incorrect // since it does not call through to Flush() which a subclass might have overriden. To be safe // we will only use this implementation in cases where we know it is safe to do so, // and delegate to our base class (which will call into Flush) when we are not sure. if (this.GetType() != typeof(StreamWriter)) return base.FlushAsync(); // flushEncoder should be true at the end of the file and if // the user explicitly calls Flush (though not if AutoFlush is true). // This is required to flush any dangling characters from our UTF-7 // and UTF-8 encoders. if (stream == null) __Error.WriterClosed(); CheckAsyncTaskInProgress(); Task task = FlushAsyncInternal(true, true, charBuffer, charPos); _asyncWriteTask = task; return task; } private Int32 CharPos_Prop { set { this.charPos = value; } } private bool HaveWrittenPreamble_Prop { set { this.haveWrittenPreamble = value; } } private Task FlushAsyncInternal(bool flushStream, bool flushEncoder, Char[] sCharBuffer, Int32 sCharPos) { // Perf boost for Flush on non-dirty writers. if (sCharPos == 0 && !flushStream && !flushEncoder) return Task.CompletedTask; Task flushTask = FlushAsyncInternal(this, flushStream, flushEncoder, sCharBuffer, sCharPos, this.haveWrittenPreamble, this.encoding, this.encoder, this.byteBuffer, this.stream); this.charPos = 0; return flushTask; } // We pass in private instance fields of this MarshalByRefObject-derived type as local params // to ensure performant access inside the state machine that corresponds this async method. private static async Task FlushAsyncInternal(StreamWriter _this, bool flushStream, bool flushEncoder, Char[] charBuffer, Int32 charPos, bool haveWrittenPreamble, Encoding encoding, Encoder encoder, Byte[] byteBuffer, Stream stream) { if (!haveWrittenPreamble) { _this.HaveWrittenPreamble_Prop = true; byte[] preamble = encoding.GetPreamble(); if (preamble.Length > 0) await stream.WriteAsync(preamble, 0, preamble.Length).ConfigureAwait(false); } int count = encoder.GetBytes(charBuffer, 0, charPos, byteBuffer, 0, flushEncoder); if (count > 0) await stream.WriteAsync(byteBuffer, 0, count).ConfigureAwait(false); // By definition, calling Flush should flush the stream, but this is // only necessary if we passed in true for flushStream. The Web // Services guys have some perf tests where flushing needlessly hurts. if (flushStream) await stream.FlushAsync().ConfigureAwait(false); } #endregion #endif //FEATURE_ASYNC_IO #if MDA_SUPPORTED // StreamWriterBufferedDataLost MDA // Instead of adding a finalizer to StreamWriter for detecting buffered data loss // (ie, when the user forgets to call Close/Flush on the StreamWriter), we will // have a separate object with normal finalization semantics that maintains a // back pointer to this StreamWriter and alerts about any data loss private sealed class MdaHelper { private StreamWriter streamWriter; private String allocatedCallstack; // captures the callstack when this streamwriter was allocated internal MdaHelper(StreamWriter sw, String cs) { streamWriter = sw; allocatedCallstack = cs; } // Finalizer ~MdaHelper() { // Make sure people closed this StreamWriter, exclude StreamWriter::Null. if (streamWriter.charPos != 0 && streamWriter.stream != null && streamWriter.stream != Stream.Null) { String fileName = (streamWriter.stream is FileStream) ? ((FileStream)streamWriter.stream).NameInternal : "<unknown>"; String callStack = allocatedCallstack; if (callStack == null) callStack = Environment.GetResourceString("IO_StreamWriterBufferedDataLostCaptureAllocatedFromCallstackNotEnabled"); String message = Environment.GetResourceString("IO_StreamWriterBufferedDataLost", streamWriter.stream.GetType().FullName, fileName, callStack); Mda.StreamWriterBufferedDataLost.ReportError(message); } } } // class MdaHelper #endif // MDA_SUPPORTED } // class StreamWriter } // namespace
/* * 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.Text; using NDesk.Options; using OpenSim.Framework; using OpenSim.Framework.Console; using OpenSim.Region.Framework.Scenes; namespace OpenSim.Region.ClientStack.LindenUDP { public class LLUDPServerCommands { private ICommandConsole m_console; private LLUDPServer m_udpServer; public LLUDPServerCommands(ICommandConsole console, LLUDPServer udpServer) { m_console = console; m_udpServer = udpServer; } public void Register() { /* m_console.Commands.AddCommand( "Comms", false, "show server throttles", "show server throttles", "Show information about server throttles", HandleShowServerThrottlesCommand); m_console.Commands.AddCommand( "Debug", false, "debug lludp packet", "debug lludp packet [--default | --all] <level> [<avatar-first-name> <avatar-last-name>]", "Turn on packet debugging. This logs information when the client stack hands a processed packet off to downstream code or when upstream code first requests that a certain packet be sent.", "If level > 255 then all incoming and outgoing packets are logged.\n" + "If level <= 255 then incoming AgentUpdate and outgoing SimStats and SimulatorViewerTimeMessage packets are not logged.\n" + "If level <= 200 then incoming RequestImage and outgoing ImagePacket, ImageData, LayerData and CoarseLocationUpdate packets are not logged.\n" + "If level <= 100 then incoming ViewerEffect and AgentAnimation and outgoing ViewerEffect and AvatarAnimation packets are not logged.\n" + "If level <= 50 then outgoing ImprovedTerseObjectUpdate packets are not logged.\n" + "If level <= 0 then no packets are logged.\n" + "If --default is specified then the level becomes the default logging level for all subsequent agents.\n" + "If --all is specified then the level becomes the default logging level for all current and subsequent agents.\n" + "In these cases, you cannot also specify an avatar name.\n" + "If an avatar name is given then only packets from that avatar are logged.", HandlePacketCommand); m_console.Commands.AddCommand( "Debug", false, "debug lludp data out", "debug lludp data out <level> <avatar-first-name> <avatar-last-name>\"", "Turn on debugging for final outgoing data to the given user's client.", "This operates at a much lower level than the packet command and prints out available details when the data is actually sent.\n" + "If level > 0 then information about all outgoing UDP data for this avatar is logged.\n" + "If level <= 0 then no information about outgoing UDP data for this avatar is logged.", HandleDataCommand); m_console.Commands.AddCommand( "Debug", false, "debug lludp drop", "debug lludp drop <in|out> <add|remove> <packet-name>", "Drop all in or outbound packets that match the given name", "For test purposes.", HandleDropCommand); m_console.Commands.AddCommand( "Debug", false, "debug lludp start", "debug lludp start <in|out|all>", "Control LLUDP packet processing.", "No effect if packet processing has already started.\n" + "in - start inbound processing.\n" + "out - start outbound processing.\n" + "all - start in and outbound processing.\n", HandleStartCommand); m_console.Commands.AddCommand( "Debug", false, "debug lludp stop", "debug lludp stop <in|out|all>", "Stop LLUDP packet processing.", "No effect if packet processing has already stopped.\n" + "in - stop inbound processing.\n" + "out - stop outbound processing.\n" + "all - stop in and outbound processing.\n", HandleStopCommand); m_console.Commands.AddCommand( "Debug", false, "debug lludp pool", "debug lludp pool <on|off>", "Turn object pooling within the lludp component on or off.", HandlePoolCommand); m_console.Commands.AddCommand( "Debug", false, "debug lludp status", "debug lludp status", "Return status of LLUDP packet processing.", HandleStatusCommand); m_console.Commands.AddCommand( "Debug", false, "debug lludp throttles log", "debug lludp throttles log <level> [<avatar-first-name> <avatar-last-name>]", "Change debug logging level for throttles.", "If level >= 0 then throttle debug logging is performed.\n" + "If level <= 0 then no throttle debug logging is performed.", HandleThrottleCommand); m_console.Commands.AddCommand( "Debug", false, "debug lludp throttles get", "debug lludp throttles get [<avatar-first-name> <avatar-last-name>]", "Return debug settings for throttles.", "adaptive - true/false, controls adaptive throttle setting.\n" + "request - request drip rate in kbps.\n" + "max - the max kbps throttle allowed for the specified existing clients. Use 'debug lludp get new-client-throttle-max' to see the setting for new clients.\n", HandleThrottleGetCommand); m_console.Commands.AddCommand( "Debug", false, "debug lludp throttles set", "debug lludp throttles set <param> <value> [<avatar-first-name> <avatar-last-name>]", "Set a throttle parameter for the given client.", "adaptive - true/false, controls adaptive throttle setting.\n" + "current - current drip rate in kbps.\n" + "request - requested drip rate in kbps.\n" + "max - the max kbps throttle allowed for the specified existing clients. Use 'debug lludp set new-client-throttle-max' to change the settings for new clients.\n", HandleThrottleSetCommand); m_console.Commands.AddCommand( "Debug", false, "debug lludp get", "debug lludp get", "Get debug parameters for the server.", "max-scene-throttle - the current max cumulative kbps provided for this scene to clients.\n" + "max-new-client-throttle - the max kbps throttle allowed to new clients. Use 'debug lludp throttles get max' to see the settings for existing clients.", HandleGetCommand); m_console.Commands.AddCommand( "Debug", false, "debug lludp set", "debug lludp set <param> <value>", "Set a parameter for the server.", "max-scene-throttle - the current max cumulative kbps provided for this scene to clients.\n" + "max-new-client-throttle - the max kbps throttle allowed to each new client. Use 'debug lludp throttles set max' to set for existing clients.", HandleSetCommand); m_console.Commands.AddCommand( "Debug", false, "debug lludp toggle agentupdate", "debug lludp toggle agentupdate", "Toggle whether agentupdate packets are processed or simply discarded.", HandleAgentUpdateCommand); MainConsole.Instance.Commands.AddCommand( "Debug", false, "debug lludp oqre", "debug lludp oqre <start|stop|status>", "Start, stop or get status of OutgoingQueueRefillEngine.", "If stopped then refill requests are processed directly via the threadpool.", HandleOqreCommand); m_console.Commands.AddCommand( "Debug", false, "debug lludp client get", "debug lludp client get [<avatar-first-name> <avatar-last-name>]", "Get debug parameters for the client. If no name is given then all client information is returned.", "process-unacked-sends - Do we take action if a sent reliable packet has not been acked.", HandleClientGetCommand); m_console.Commands.AddCommand( "Debug", false, "debug lludp client set", "debug lludp client set <param> <value> [<avatar-first-name> <avatar-last-name>]", "Set a debug parameter for a particular client. If no name is given then the value is set on all clients.", "process-unacked-sends - Do we take action if a sent reliable packet has not been acked.", HandleClientSetCommand); */ } private void HandleShowServerThrottlesCommand(string module, string[] args) { if (SceneManager.Instance.CurrentScene != null && SceneManager.Instance.CurrentScene != m_udpServer.Scene) return; m_console.OutputFormat("Throttles for {0}", m_udpServer.Scene.Name); ConsoleDisplayList cdl = new ConsoleDisplayList(); cdl.AddRow("Adaptive throttles", m_udpServer.ThrottleRates.AdaptiveThrottlesEnabled); long maxSceneDripRate = (long)m_udpServer.Throttle.MaxDripRate; cdl.AddRow( "Max scene throttle", maxSceneDripRate != 0 ? string.Format("{0} kbps", maxSceneDripRate * 8 / 1000) : "unset"); int maxClientDripRate = m_udpServer.ThrottleRates.Total; cdl.AddRow( "Max new client throttle", maxClientDripRate != 0 ? string.Format("{0} kbps", maxClientDripRate * 8 / 1000) : "unset"); m_console.Output(cdl.ToString()); m_console.OutputFormat("{0}\n", GetServerThrottlesReport(m_udpServer)); } private string GetServerThrottlesReport(LLUDPServer udpServer) { StringBuilder report = new StringBuilder(); report.AppendFormat( "{0,7} {1,8} {2,7} {3,7} {4,7} {5,7} {6,9} {7,7}\n", "Total", "Resend", "Land", "Wind", "Cloud", "Task", "Texture", "Asset"); report.AppendFormat( "{0,7} {1,8} {2,7} {3,7} {4,7} {5,7} {6,9} {7,7}\n", "kb/s", "kb/s", "kb/s", "kb/s", "kb/s", "kb/s", "kb/s", "kb/s"); ThrottleRates throttleRates = udpServer.ThrottleRates; report.AppendFormat( "{0,7} {1,8} {2,7} {3,7} {4,7} {5,7} {6,9} {7,7}", (throttleRates.Total * 8) / 1000, (throttleRates.Resend * 8) / 1000, (throttleRates.Land * 8) / 1000, (throttleRates.Wind * 8) / 1000, (throttleRates.Cloud * 8) / 1000, (throttleRates.Task * 8) / 1000, (throttleRates.Texture * 8) / 1000, (throttleRates.Asset * 8) / 1000); return report.ToString(); } protected string GetColumnEntry(string entry, int maxLength, int columnPadding) { return string.Format( "{0,-" + maxLength + "}{1,-" + columnPadding + "}", entry.Length > maxLength ? entry.Substring(0, maxLength) : entry, ""); } private void HandleDataCommand(string module, string[] args) { if (SceneManager.Instance.CurrentScene != null && SceneManager.Instance.CurrentScene != m_udpServer.Scene) return; if (args.Length != 7) { MainConsole.Instance.OutputFormat("Usage: debug lludp data out <true|false> <avatar-first-name> <avatar-last-name>"); return; } int level; if (!ConsoleUtil.TryParseConsoleInt(MainConsole.Instance, args[4], out level)) return; string firstName = args[5]; string lastName = args[6]; m_udpServer.Scene.ForEachScenePresence(sp => { if (sp.Firstname == firstName && sp.Lastname == lastName) { MainConsole.Instance.OutputFormat( "Data debug for {0} ({1}) set to {2} in {3}", sp.Name, sp.IsChildAgent ? "child" : "root", level, m_udpServer.Scene.Name); ((LLClientView)sp.ControllingClient).UDPClient.DebugDataOutLevel = level; } }); } private void HandleThrottleCommand(string module, string[] args) { if (SceneManager.Instance.CurrentScene != null && SceneManager.Instance.CurrentScene != m_udpServer.Scene) return; bool all = args.Length == 5; bool one = args.Length == 7; if (!all && !one) { MainConsole.Instance.OutputFormat( "Usage: debug lludp throttles log <level> [<avatar-first-name> <avatar-last-name>]"); return; } int level; if (!ConsoleUtil.TryParseConsoleInt(MainConsole.Instance, args[4], out level)) return; string firstName = null; string lastName = null; if (one) { firstName = args[5]; lastName = args[6]; } m_udpServer.Scene.ForEachScenePresence(sp => { if (all || (sp.Firstname == firstName && sp.Lastname == lastName)) { MainConsole.Instance.OutputFormat( "Throttle log level for {0} ({1}) set to {2} in {3}", sp.Name, sp.IsChildAgent ? "child" : "root", level, m_udpServer.Scene.Name); ((LLClientView)sp.ControllingClient).UDPClient.ThrottleDebugLevel = level; } }); } private void HandleThrottleSetCommand(string module, string[] args) { if (SceneManager.Instance.CurrentScene != null && SceneManager.Instance.CurrentScene != m_udpServer.Scene) return; bool all = args.Length == 6; bool one = args.Length == 8; if (!all && !one) { MainConsole.Instance.OutputFormat( "Usage: debug lludp throttles set <param> <value> [<avatar-first-name> <avatar-last-name>]"); return; } string param = args[4]; string rawValue = args[5]; string firstName = null; string lastName = null; if (one) { firstName = args[6]; lastName = args[7]; } if (param == "adaptive") { bool newValue; if (!ConsoleUtil.TryParseConsoleBool(MainConsole.Instance, rawValue, out newValue)) return; m_udpServer.Scene.ForEachScenePresence(sp => { if (all || (sp.Firstname == firstName && sp.Lastname == lastName)) { MainConsole.Instance.OutputFormat( "Setting param {0} to {1} for {2} ({3}) in {4}", param, newValue, sp.Name, sp.IsChildAgent ? "child" : "root", m_udpServer.Scene.Name); LLUDPClient udpClient = ((LLClientView)sp.ControllingClient).UDPClient; udpClient.FlowThrottle.AdaptiveEnabled = newValue; // udpClient.FlowThrottle.MaxDripRate = 0; // udpClient.FlowThrottle.AdjustedDripRate = 0; } }); } else if (param == "request") { int newValue; if (!ConsoleUtil.TryParseConsoleInt(MainConsole.Instance, rawValue, out newValue)) return; int newCurrentThrottleKbps = newValue * 1000 / 8; m_udpServer.Scene.ForEachScenePresence(sp => { if (all || (sp.Firstname == firstName && sp.Lastname == lastName)) { MainConsole.Instance.OutputFormat( "Setting param {0} to {1} for {2} ({3}) in {4}", param, newValue, sp.Name, sp.IsChildAgent ? "child" : "root", m_udpServer.Scene.Name); LLUDPClient udpClient = ((LLClientView)sp.ControllingClient).UDPClient; udpClient.FlowThrottle.RequestedDripRate = newCurrentThrottleKbps; } }); } else if (param == "max") { int newValue; if (!ConsoleUtil.TryParseConsoleInt(MainConsole.Instance, rawValue, out newValue)) return; int newThrottleMaxKbps = newValue * 1000 / 8; m_udpServer.Scene.ForEachScenePresence(sp => { if (all || (sp.Firstname == firstName && sp.Lastname == lastName)) { MainConsole.Instance.OutputFormat( "Setting param {0} to {1} for {2} ({3}) in {4}", param, newValue, sp.Name, sp.IsChildAgent ? "child" : "root", m_udpServer.Scene.Name); LLUDPClient udpClient = ((LLClientView)sp.ControllingClient).UDPClient; udpClient.FlowThrottle.MaxDripRate = newThrottleMaxKbps; } }); } } private void HandleThrottleGetCommand(string module, string[] args) { if (SceneManager.Instance.CurrentScene != null && SceneManager.Instance.CurrentScene != m_udpServer.Scene) return; bool all = args.Length == 4; bool one = args.Length == 6; if (!all && !one) { MainConsole.Instance.OutputFormat( "Usage: debug lludp throttles get [<avatar-first-name> <avatar-last-name>]"); return; } string firstName = null; string lastName = null; if (one) { firstName = args[4]; lastName = args[5]; } m_udpServer.Scene.ForEachScenePresence(sp => { if (all || (sp.Firstname == firstName && sp.Lastname == lastName)) { m_console.OutputFormat( "Status for {0} ({1}) in {2}", sp.Name, sp.IsChildAgent ? "child" : "root", m_udpServer.Scene.Name); LLUDPClient udpClient = ((LLClientView)sp.ControllingClient).UDPClient; ConsoleDisplayList cdl = new ConsoleDisplayList(); cdl.AddRow("adaptive", udpClient.FlowThrottle.AdaptiveEnabled); cdl.AddRow("current", string.Format("{0} kbps", udpClient.FlowThrottle.DripRate * 8 / 1000)); cdl.AddRow("request", string.Format("{0} kbps", udpClient.FlowThrottle.RequestedDripRate * 8 / 1000)); cdl.AddRow("max", string.Format("{0} kbps", udpClient.FlowThrottle.MaxDripRate * 8 / 1000)); m_console.Output(cdl.ToString()); } }); } private void HandleGetCommand(string module, string[] args) { if (SceneManager.Instance.CurrentScene != null && SceneManager.Instance.CurrentScene != m_udpServer.Scene) return; m_console.OutputFormat("Debug settings for {0}", m_udpServer.Scene.Name); ConsoleDisplayList cdl = new ConsoleDisplayList(); long maxSceneDripRate = (long)m_udpServer.Throttle.MaxDripRate; cdl.AddRow( "max-scene-throttle", maxSceneDripRate != 0 ? string.Format("{0} kbps", maxSceneDripRate * 8 / 1000) : "unset"); int maxClientDripRate = m_udpServer.ThrottleRates.Total; cdl.AddRow( "max-new-client-throttle", maxClientDripRate != 0 ? string.Format("{0} kbps", maxClientDripRate * 8 / 1000) : "unset"); m_console.Output(cdl.ToString()); } private void HandleSetCommand(string module, string[] args) { if (SceneManager.Instance.CurrentScene != null && SceneManager.Instance.CurrentScene != m_udpServer.Scene) return; if (args.Length != 5) { MainConsole.Instance.OutputFormat("Usage: debug lludp set <param> <value>"); return; } string param = args[3]; string rawValue = args[4]; int newValue; if (param == "max-scene-throttle") { if (!ConsoleUtil.TryParseConsoleInt(MainConsole.Instance, rawValue, out newValue)) return; m_udpServer.Throttle.MaxDripRate = newValue * 1000 / 8; } else if (param == "max-new-client-throttle") { if (!ConsoleUtil.TryParseConsoleInt(MainConsole.Instance, rawValue, out newValue)) return; m_udpServer.ThrottleRates.Total = newValue * 1000 / 8; } else { return; } m_console.OutputFormat("{0} set to {1} in {2}", param, rawValue, m_udpServer.Scene.Name); } /* not in use, nothing to set/get from lludp private void HandleClientGetCommand(string module, string[] args) { if (SceneManager.Instance.CurrentScene != null && SceneManager.Instance.CurrentScene != m_udpServer.Scene) return; if (args.Length != 4 && args.Length != 6) { MainConsole.Instance.OutputFormat("Usage: debug lludp client get [<avatar-first-name> <avatar-last-name>]"); return; } string name = null; if (args.Length == 6) name = string.Format("{0} {1}", args[4], args[5]); m_udpServer.Scene.ForEachScenePresence( sp => { if ((name == null || sp.Name == name) && sp.ControllingClient is LLClientView) { LLUDPClient udpClient = ((LLClientView)sp.ControllingClient).UDPClient; m_console.OutputFormat( "Client debug parameters for {0} ({1}) in {2}", sp.Name, sp.IsChildAgent ? "child" : "root", m_udpServer.Scene.Name); } }); } private void HandleClientSetCommand(string module, string[] args) { if (SceneManager.Instance.CurrentScene != null && SceneManager.Instance.CurrentScene != m_udpServer.Scene) return; if (args.Length != 6 && args.Length != 8) { MainConsole.Instance.OutputFormat("Usage: debug lludp client set <param> <value> [<avatar-first-name> <avatar-last-name>]"); return; } string param = args[4]; string rawValue = args[5]; string name = null; if (args.Length == 8) name = string.Format("{0} {1}", args[6], args[7]); // nothing here now } */ private void HandlePacketCommand(string module, string[] args) { if (SceneManager.Instance.CurrentScene != null && SceneManager.Instance.CurrentScene != m_udpServer.Scene) return; bool setAsDefaultLevel = false; bool setAll = false; OptionSet optionSet = new OptionSet() .Add("default", o => setAsDefaultLevel = (o != null)) .Add("all", o => setAll = (o != null)); List<string> filteredArgs = optionSet.Parse(args); string name = null; if (filteredArgs.Count == 6) { if (!(setAsDefaultLevel || setAll)) { name = string.Format("{0} {1}", filteredArgs[4], filteredArgs[5]); } else { MainConsole.Instance.OutputFormat("ERROR: Cannot specify a user name when setting default/all logging level"); return; } } if (filteredArgs.Count > 3) { int newDebug; if (int.TryParse(filteredArgs[3], out newDebug)) { if (setAsDefaultLevel || setAll) { m_udpServer.DefaultClientPacketDebugLevel = newDebug; MainConsole.Instance.OutputFormat( "Packet debug for {0} clients set to {1} in {2}", (setAll ? "all" : "future"), m_udpServer.DefaultClientPacketDebugLevel, m_udpServer.Scene.Name); if (setAll) { m_udpServer.Scene.ForEachScenePresence(sp => { MainConsole.Instance.OutputFormat( "Packet debug for {0} ({1}) set to {2} in {3}", sp.Name, sp.IsChildAgent ? "child" : "root", newDebug, m_udpServer.Scene.Name); sp.ControllingClient.DebugPacketLevel = newDebug; }); } } else { m_udpServer.Scene.ForEachScenePresence(sp => { if (name == null || sp.Name == name) { MainConsole.Instance.OutputFormat( "Packet debug for {0} ({1}) set to {2} in {3}", sp.Name, sp.IsChildAgent ? "child" : "root", newDebug, m_udpServer.Scene.Name); sp.ControllingClient.DebugPacketLevel = newDebug; } }); } } else { MainConsole.Instance.Output("Usage: debug lludp packet [--default | --all] 0..255 [<first-name> <last-name>]"); } } } private void HandleDropCommand(string module, string[] args) { if (SceneManager.Instance.CurrentScene != null && SceneManager.Instance.CurrentScene != m_udpServer.Scene) return; if (args.Length != 6) { MainConsole.Instance.Output("Usage: debug lludp drop <in|out> <add|remove> <packet-name>"); return; } string direction = args[3]; string subCommand = args[4]; string packetName = args[5]; if (subCommand == "add") { MainConsole.Instance.OutputFormat( "Adding packet {0} to {1} drop list for all connections in {2}", direction, packetName, m_udpServer.Scene.Name); m_udpServer.Scene.ForEachScenePresence( sp => { LLClientView llcv = (LLClientView)sp.ControllingClient; if (direction == "in") llcv.AddInPacketToDropSet(packetName); else if (direction == "out") llcv.AddOutPacketToDropSet(packetName); } ); } else if (subCommand == "remove") { MainConsole.Instance.OutputFormat( "Removing packet {0} from {1} drop list for all connections in {2}", direction, packetName, m_udpServer.Scene.Name); m_udpServer.Scene.ForEachScenePresence( sp => { LLClientView llcv = (LLClientView)sp.ControllingClient; if (direction == "in") llcv.RemoveInPacketFromDropSet(packetName); else if (direction == "out") llcv.RemoveOutPacketFromDropSet(packetName); } ); } } private void HandleStartCommand(string module, string[] args) { if (SceneManager.Instance.CurrentScene != null && SceneManager.Instance.CurrentScene != m_udpServer.Scene) return; if (args.Length != 4) { MainConsole.Instance.Output("Usage: debug lludp start <in|out|all>"); return; } string subCommand = args[3]; if (subCommand == "in" || subCommand == "all") m_udpServer.StartInbound(); if (subCommand == "out" || subCommand == "all") m_udpServer.StartOutbound(); } private void HandleStopCommand(string module, string[] args) { if (SceneManager.Instance.CurrentScene != null && SceneManager.Instance.CurrentScene != m_udpServer.Scene) return; if (args.Length != 4) { MainConsole.Instance.Output("Usage: debug lludp stop <in|out|all>"); return; } string subCommand = args[3]; if (subCommand == "in" || subCommand == "all") m_udpServer.StopInbound(); if (subCommand == "out" || subCommand == "all") m_udpServer.StopOutbound(); } private void HandlePoolCommand(string module, string[] args) { if (SceneManager.Instance.CurrentScene != null && SceneManager.Instance.CurrentScene != m_udpServer.Scene) return; if (args.Length != 4) { MainConsole.Instance.Output("Usage: debug lludp pool <on|off>"); return; } string enabled = args[3]; if (enabled == "on") { if (m_udpServer.EnablePools()) { m_udpServer.EnablePoolStats(); MainConsole.Instance.OutputFormat("Packet pools enabled on {0}", m_udpServer.Scene.Name); } } else if (enabled == "off") { if (m_udpServer.DisablePools()) { m_udpServer.DisablePoolStats(); MainConsole.Instance.OutputFormat("Packet pools disabled on {0}", m_udpServer.Scene.Name); } } else { MainConsole.Instance.Output("Usage: debug lludp pool <on|off>"); } } private void HandleAgentUpdateCommand(string module, string[] args) { if (SceneManager.Instance.CurrentScene != null && SceneManager.Instance.CurrentScene != m_udpServer.Scene) return; m_udpServer.DiscardInboundAgentUpdates = !m_udpServer.DiscardInboundAgentUpdates; MainConsole.Instance.OutputFormat( "Discard AgentUpdates now {0} for {1}", m_udpServer.DiscardInboundAgentUpdates, m_udpServer.Scene.Name); } private void HandleStatusCommand(string module, string[] args) { if (SceneManager.Instance.CurrentScene != null && SceneManager.Instance.CurrentScene != m_udpServer.Scene) return; MainConsole.Instance.OutputFormat( "IN LLUDP packet processing for {0} is {1}", m_udpServer.Scene.Name, m_udpServer.IsRunningInbound ? "enabled" : "disabled"); MainConsole.Instance.OutputFormat( "OUT LLUDP packet processing for {0} is {1}", m_udpServer.Scene.Name, m_udpServer.IsRunningOutbound ? "enabled" : "disabled"); MainConsole.Instance.OutputFormat("LLUDP pools in {0} are {1}", m_udpServer.Scene.Name, m_udpServer.UsePools ? "on" : "off"); MainConsole.Instance.OutputFormat( "Packet debug level for new clients is {0}", m_udpServer.DefaultClientPacketDebugLevel); } private void HandleOqreCommand(string module, string[] args) { if (SceneManager.Instance.CurrentScene != null && SceneManager.Instance.CurrentScene != m_udpServer.Scene) return; if (args.Length != 4) { MainConsole.Instance.Output("Usage: debug lludp oqre <stop|start|status>"); return; } string subCommand = args[3]; if (subCommand == "stop") { m_udpServer.OqrEngine.Stop(); MainConsole.Instance.OutputFormat("Stopped OQRE for {0}", m_udpServer.Scene.Name); } else if (subCommand == "start") { m_udpServer.OqrEngine.Start(); MainConsole.Instance.OutputFormat("Started OQRE for {0}", m_udpServer.Scene.Name); } else if (subCommand == "status") { MainConsole.Instance.OutputFormat("OQRE in {0}", m_udpServer.Scene.Name); MainConsole.Instance.OutputFormat("Running: {0}", m_udpServer.OqrEngine.IsRunning); MainConsole.Instance.OutputFormat( "Requests waiting: {0}", m_udpServer.OqrEngine.IsRunning ? m_udpServer.OqrEngine.JobsWaiting.ToString() : "n/a"); } else { MainConsole.Instance.OutputFormat("Unrecognized OQRE subcommand {0}", subCommand); } } } }
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the ssm-2014-11-06.normal.json service model. */ using System; using Amazon.Runtime; namespace Amazon.SimpleSystemsManagement { /// <summary> /// Constants used for properties of type AssociationFilterKey. /// </summary> public class AssociationFilterKey : ConstantClass { /// <summary> /// Constant InstanceId for AssociationFilterKey /// </summary> public static readonly AssociationFilterKey InstanceId = new AssociationFilterKey("InstanceId"); /// <summary> /// Constant Name for AssociationFilterKey /// </summary> public static readonly AssociationFilterKey Name = new AssociationFilterKey("Name"); /// <summary> /// Default Constructor /// </summary> public AssociationFilterKey(string value) : base(value) { } /// <summary> /// Finds the constant for the unique value. /// </summary> /// <param name="value">The unique value for the constant</param> /// <returns>The constant for the unique value</returns> public static AssociationFilterKey FindValue(string value) { return FindValue<AssociationFilterKey>(value); } /// <summary> /// Utility method to convert strings to the constant class. /// </summary> /// <param name="value">The string value to convert to the constant class.</param> /// <returns></returns> public static implicit operator AssociationFilterKey(string value) { return FindValue(value); } } /// <summary> /// Constants used for properties of type AssociationStatusName. /// </summary> public class AssociationStatusName : ConstantClass { /// <summary> /// Constant Failed for AssociationStatusName /// </summary> public static readonly AssociationStatusName Failed = new AssociationStatusName("Failed"); /// <summary> /// Constant Pending for AssociationStatusName /// </summary> public static readonly AssociationStatusName Pending = new AssociationStatusName("Pending"); /// <summary> /// Constant Success for AssociationStatusName /// </summary> public static readonly AssociationStatusName Success = new AssociationStatusName("Success"); /// <summary> /// Default Constructor /// </summary> public AssociationStatusName(string value) : base(value) { } /// <summary> /// Finds the constant for the unique value. /// </summary> /// <param name="value">The unique value for the constant</param> /// <returns>The constant for the unique value</returns> public static AssociationStatusName FindValue(string value) { return FindValue<AssociationStatusName>(value); } /// <summary> /// Utility method to convert strings to the constant class. /// </summary> /// <param name="value">The string value to convert to the constant class.</param> /// <returns></returns> public static implicit operator AssociationStatusName(string value) { return FindValue(value); } } /// <summary> /// Constants used for properties of type DocumentFilterKey. /// </summary> public class DocumentFilterKey : ConstantClass { /// <summary> /// Constant Name for DocumentFilterKey /// </summary> public static readonly DocumentFilterKey Name = new DocumentFilterKey("Name"); /// <summary> /// Default Constructor /// </summary> public DocumentFilterKey(string value) : base(value) { } /// <summary> /// Finds the constant for the unique value. /// </summary> /// <param name="value">The unique value for the constant</param> /// <returns>The constant for the unique value</returns> public static DocumentFilterKey FindValue(string value) { return FindValue<DocumentFilterKey>(value); } /// <summary> /// Utility method to convert strings to the constant class. /// </summary> /// <param name="value">The string value to convert to the constant class.</param> /// <returns></returns> public static implicit operator DocumentFilterKey(string value) { return FindValue(value); } } /// <summary> /// Constants used for properties of type DocumentStatus. /// </summary> public class DocumentStatus : ConstantClass { /// <summary> /// Constant Active for DocumentStatus /// </summary> public static readonly DocumentStatus Active = new DocumentStatus("Active"); /// <summary> /// Constant Creating for DocumentStatus /// </summary> public static readonly DocumentStatus Creating = new DocumentStatus("Creating"); /// <summary> /// Constant Deleting for DocumentStatus /// </summary> public static readonly DocumentStatus Deleting = new DocumentStatus("Deleting"); /// <summary> /// Default Constructor /// </summary> public DocumentStatus(string value) : base(value) { } /// <summary> /// Finds the constant for the unique value. /// </summary> /// <param name="value">The unique value for the constant</param> /// <returns>The constant for the unique value</returns> public static DocumentStatus FindValue(string value) { return FindValue<DocumentStatus>(value); } /// <summary> /// Utility method to convert strings to the constant class. /// </summary> /// <param name="value">The string value to convert to the constant class.</param> /// <returns></returns> public static implicit operator DocumentStatus(string value) { return FindValue(value); } } /// <summary> /// Constants used for properties of type Fault. /// </summary> public class Fault : ConstantClass { /// <summary> /// Constant Client for Fault /// </summary> public static readonly Fault Client = new Fault("Client"); /// <summary> /// Constant Server for Fault /// </summary> public static readonly Fault Server = new Fault("Server"); /// <summary> /// Constant Unknown for Fault /// </summary> public static readonly Fault Unknown = new Fault("Unknown"); /// <summary> /// Default Constructor /// </summary> public Fault(string value) : base(value) { } /// <summary> /// Finds the constant for the unique value. /// </summary> /// <param name="value">The unique value for the constant</param> /// <returns>The constant for the unique value</returns> public static Fault FindValue(string value) { return FindValue<Fault>(value); } /// <summary> /// Utility method to convert strings to the constant class. /// </summary> /// <param name="value">The string value to convert to the constant class.</param> /// <returns></returns> public static implicit operator Fault(string value) { return FindValue(value); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. namespace Microsoft.Azure.Management.Dns.Fluent { using System.Threading; using DnsRecordSet.UpdateDefinition; using DnsRecordSet.Definition; using DnsRecordSet.UpdateCombined; using System.Threading.Tasks; using System.Collections.Generic; using Microsoft.Azure.Management.ResourceManager.Fluent.Core; using Models; using System; using ResourceManager.Fluent.Core.ChildResourceActions; using System.Linq; /// <summary> /// Implementation of DnsRecordSet. /// </summary> ///GENTHASH:Y29tLm1pY3Jvc29mdC5henVyZS5tYW5hZ2VtZW50LmRucy5pbXBsZW1lbnRhdGlvbi5EbnNSZWNvcmRTZXRJbXBs internal partial class DnsRecordSetImpl : ExternalChildResource<IDnsRecordSet, RecordSetInner, IDnsZone, DnsZoneImpl>, IDnsRecordSet, IDefinition<DnsZone.Definition.IWithCreate>, IUpdateDefinition<DnsZone.Update.IUpdate>, IUpdateCombined { private ETagState eTagState = new ETagState(); protected RecordSetInner recordSetRemoveInfo; protected string type; ///GENMHASH:6A42EB03FFE33A200BEB62492956E6E8:6BF10A0FF5A6F77B66504E985BF7084C internal DnsRecordSetImpl(string name, string type, DnsZoneImpl parent, RecordSetInner innerModel) : base(name, parent, innerModel) { this.type = type; this.recordSetRemoveInfo = new RecordSetInner { ARecords = new List<ARecord>(), AaaaRecords = new List<AaaaRecord>(), CaaRecords = new List<CaaRecord>(), CnameRecord = new CnameRecord(), MxRecords = new List<MxRecord>(), NsRecords = new List<NsRecord>(), PtrRecords = new List<PtrRecord>(), SrvRecords = new List<SrvRecord>(), TxtRecords = new List<TxtRecord>(), Metadata = new Dictionary<string, string>() }; } ///GENMHASH:1DB2BF1F42540E5CABB126B2B9970516:12FBAC3B63C70ED810BCC3C5AE182F93 internal DnsRecordSetImpl WithETagOnDelete(string eTagValue) { this.eTagState.WithExplicitETagCheckOnDelete(eTagValue); return this; } ///GENMHASH:F9C01790C5D58B1748BB35183FF3B0D8:000E3438232752188E9F410E5DCAC466 private async Task<IDnsRecordSet> CreateOrUpdateAsync(RecordSetInner resource, CancellationToken cancellationToken = default(CancellationToken)) { RecordSetInner inner = await Parent.Manager.Inner.RecordSets.CreateOrUpdateAsync( Parent.ResourceGroupName, Parent.Name, Name(), RecordType(), resource, ifMatch: this.eTagState.IfMatchValueOnUpdate(resource.Etag), ifNoneMatch: this.eTagState.IfNonMatchValueOnCreate(), cancellationToken: cancellationToken); SetInner(inner); this.eTagState.Clear(); return this; } ///GENMHASH:4F856FB578CC3E1352902BE5686B7CC9:D624DD59AB1913F5FF4AECA70621F115 private RecordSetInner Prepare(RecordSetInner resource) { if (this.recordSetRemoveInfo.Metadata.Count > 0) { if (resource.Metadata != null) { foreach (var key in this.recordSetRemoveInfo.Metadata.Keys) { if (resource.Metadata.ContainsKey(key)) { resource.Metadata.Remove(key); } } } this.recordSetRemoveInfo.Metadata.Clear(); } if (Inner.Metadata != null && Inner.Metadata.Count > 0) { if (resource.Metadata == null) { resource.Metadata = new Dictionary<string, string>(); } foreach (var keyVal in Inner.Metadata) { resource.Metadata.Add(keyVal.Key, keyVal.Value); } Inner.Metadata.Clear(); } if (Inner.TTL != null) { resource.TTL = Inner.TTL; Inner.TTL = null; } return PrepareForUpdate(resource); } ///GENMHASH:5AD91481A0966B059A478CD4E9DD9466:12B69CFE7F6114AB5C15C38A5DAE43C8 protected override async Task<RecordSetInner> GetInnerAsync(CancellationToken cancellationToken = default(CancellationToken)) { return await Parent.Manager.Inner.RecordSets.GetAsync( Parent.ResourceGroupName, Parent.Name, Name(), RecordType(), cancellationToken: cancellationToken); } ///GENMHASH:7D787B3687385E18B312D5F6D6DA9444:B566554D9AFEED430A7C1AC9E97ADBDB protected virtual RecordSetInner PrepareForUpdate(RecordSetInner resource) { return resource; } ///GENMHASH:077EB7776EFFBFAA141C1696E75EF7B3:8FF06E289719BB519BDB4F57C1488F6F public DnsZoneImpl Attach() { return this.Parent; } ///GENMHASH:B691CFA349658CF97DA3EBA649A8ADB3:B05F9E0B8B96C671F86EA89FD77BF7DA public override string ChildResourceKey { get { return this.Name() + "_" + this.RecordType().ToString(); } } ///GENMHASH:0202A00A1DCF248D2647DBDBEF2CA865:18B12FED433DF6A1F3CA0DD1940B789C public async override Task<IDnsRecordSet> CreateAsync(CancellationToken cancellationToken = default(CancellationToken)) { return await CreateOrUpdateAsync(Inner, cancellationToken); } ///GENMHASH:E24A9768E91CD60E963E43F00AA1FDFE:2B9DD1C564ED2E952CDE4348D8C25EE7 public async override Task DeleteAsync(CancellationToken cancellationToken = default(CancellationToken)) { await Parent.Manager.Inner.RecordSets.DeleteAsync( Parent.ResourceGroupName, Parent.Name, Name(), RecordType(), ifMatch: this.eTagState.IfMatchValueOnDelete(), cancellationToken: cancellationToken); } ///GENMHASH:4913BE5E272184975DDDF5335B476BBD:88ACBC17B6D51A9C055E4CC9834ED144 public string ETag() { return this.Inner.Etag; } ///GENMHASH:577F8437932AEC6E08E1A137969BDB4A:A1945CF277DF5AE74D653481F44D96CE public string Fqdn() { return this.Inner.Fqdn; } ///GENMHASH:ACA2D5620579D8158A29586CA1FF4BC6:43D11CBDAF5A13A288B18B4C8884B621 public string Id { get { return Inner.Id; } } ///GENMHASH:12F281B8230A0FD8CE8A0DF277EF885D:DF7D49CE4CC74DB0E5D593989B78CB8D public IReadOnlyDictionary<string, string> Metadata() { if (Inner.Metadata == null) { return new Dictionary<string, string>(); } else { return Inner.Metadata as Dictionary<string, string>; } } ///GENMHASH:3802EA6243E9AF80A622FF944E74B5EA:03D0507196E92D3034FCCE67ABC7ADA9 public RecordType RecordType() { var fullyQualifiedType = this.type; var parts = fullyQualifiedType.Split('/'); return (RecordType)Enum.Parse(typeof(RecordType), parts[parts.Length - 1]); } ///GENMHASH:2C0DB6B1F104247169DC6BCC9246747C:FD4CF3518891ACD11184E48644DB2B2F public long TimeToLive() { return Inner.TTL.Value; } ///GENMHASH:507A92D4DCD93CE9595A78198DEBDFCF:A945C11E2DCC935424E5B666E47F3D2C public async override Task<IDnsRecordSet> UpdateAsync(CancellationToken cancellationToken = default(CancellationToken)) { RecordSetInner resource = await Parent.Manager.Inner.RecordSets.GetAsync( Parent.ResourceGroupName, Parent.Name, Name(), RecordType(), cancellationToken); resource = Prepare(resource); return await CreateOrUpdateAsync(resource, cancellationToken); } ///GENMHASH:C638904A9672FCBF061409871819AB8D:41137108673CA51222538BEBDE37F159 public DnsRecordSetImpl WithAlias(string alias) { Inner.CnameRecord.Cname = alias; return this; } ///GENMHASH:E8E20943CC1653864072EDF514EE642D:10153E6B4A158154E1E8933759138F87 public DnsRecordSetImpl WithEmailServer(string emailServerHostName) { Inner.SoaRecord.Email = emailServerHostName; return this; } ///GENMHASH:791593DE94E8D431FBB634CF0578A424:D24CFEDBDBC40A8AF2B5216EA0D7C954 public DnsRecordSetImpl WithETagCheck() { this.eTagState.WithImplicitETagCheckOnCreate(); this.eTagState.WithImplicitETagCheckOnUpdate(); return this; } ///GENMHASH:CAE9667D3C5220302471B1AF817CBA6A:A7E77BD98437FA8383ED7A6B96761FD4 public DnsRecordSetImpl WithETagCheck(string eTagValue) { this.eTagState.WithExplicitETagCheckOnUpdate(eTagValue); return this; } ///GENMHASH:4ECEC95ECA7A8DC269D2A9F01EFAB22F:23360CE86BB90FDBC6677495A1E19515 public DnsRecordSetImpl WithExpireTimeInSeconds(long expireTimeInSeconds) { Inner.SoaRecord.ExpireTime = expireTimeInSeconds; return this; } ///GENMHASH:4CA65F8144FED160954BD87CFFBC0595:E0FC813C874E3B3480E4DA74E4253BCC public DnsRecordSetImpl WithIPv4Address(string ipv4Address) { Inner.ARecords.Add(new ARecord { Ipv4Address = ipv4Address }); return this; } ///GENMHASH:DC461002C137D25BAA574C45A4E811DF:F96F4FA644159C0CD0EBB1C5B9EEF1A0 public DnsRecordSetImpl WithIPv6Address(string ipv6Address) { Inner.AaaaRecords .Add(new AaaaRecord { Ipv6Address = ipv6Address }); return this; } ///GENMHASH:4784E7B75FB76CEEC96CAC590D7BC733:EE061C20B2C852EF45A468E94B59809D public DnsRecordSetImpl WithMailExchange(string mailExchangeHostName, int priority) { Inner.MxRecords.Add(new MxRecord { Exchange = mailExchangeHostName, Preference = priority }); return this; } ///GENMHASH:A8504DD39B3F14EC8A5C6530FB22292A:5BA5A4ACBB2C6A840606E1F8F35C4054 public DnsRecordSetImpl WithMetadata(string key, string value) { if (Inner.Metadata == null) { Inner.Metadata = new Dictionary<string, string>(); } if (!Inner.Metadata.ContainsKey(key)) { Inner.Metadata.Add(key, value); } else { Inner.Metadata[key] = value; } return this; } ///GENMHASH:A495194BB5D71557F5AA70FF3FAE37F2:DAF74D854B6F3C3F3FED97303FD90564 public DnsRecordSetImpl WithNameServer(string nameServerHostName) { Inner.NsRecords .Add(new NsRecord { Nsdname = nameServerHostName }); return this; } ///GENMHASH:F55643C465E2111FF58A74CD2FC02F67:E726662DDC93F264FBEC106CADBCFF38 public DnsRecordSetImpl WithNegativeResponseCachingTimeToLiveInSeconds(long negativeCachingTimeToLive) { Inner.SoaRecord.MinimumTtl = negativeCachingTimeToLive; return this; } ///GENMHASH:97641C527D3F880E3D6A071B23B1C220:5ED48E280A79185C34BAD7FC806CCBB5 public DnsRecordSetImpl WithoutIPv4Address(string ipv4Address) { this.recordSetRemoveInfo.ARecords .Add(new ARecord { Ipv4Address = ipv4Address }); return this; } ///GENMHASH:8629B1E65EA81A8A3221F7E2E342A5FD:5DA00DC8D7A2405A86C3DDBFD2B0DDC7 public DnsRecordSetImpl WithoutIPv6Address(string ipv6Address) { this.recordSetRemoveInfo.AaaaRecords .Add(new AaaaRecord { Ipv6Address = ipv6Address }); return this; } ///GENMHASH:2929561387ABF878940284424229C907:DC4598B10EC964C77018370FF2C1D2C2 public DnsRecordSetImpl WithoutMailExchange(string mailExchangeHostName, int priority) { this.recordSetRemoveInfo.MxRecords .Add(new MxRecord { Exchange = mailExchangeHostName, Preference = priority }); return this; } ///GENMHASH:40C52B3E2D072BD6B513ECBCC98E4F0B:C889D9872204B3122BF5D527764173CC public DnsRecordSetImpl WithoutMetadata(string key) { this.recordSetRemoveInfo.Metadata.Add(key, null); return this; } ///GENMHASH:449585720E8D8C838341BFC3501A2C54:445B56F8A7E0DD6E4B2F2B7EAB7A7AE2 public DnsRecordSetImpl WithoutNameServer(string nameServerHostName) { this.recordSetRemoveInfo.NsRecords .Add(new NsRecord { Nsdname = nameServerHostName }); return this; } ///GENMHASH:2965B3FB0030FC60CED746B78EE838F3:DFE43DACAEDDF987BEDF786B4989C489 public DnsRecordSetImpl WithoutRecord(int flags, string tag, string value) { this.recordSetRemoveInfo.CaaRecords .Add(new CaaRecord { Flags = flags, Tag = tag, Value = value }); return this; } ///GENMHASH:7E75EEC0B8C84C22E81E3BAFBC37AFB7:6901EFF3BEDF9329606BCF9A8C14052C public DnsRecordSetImpl WithoutRecord(string target, int port, int priority, int weight) { this.recordSetRemoveInfo.SrvRecords .Add(new SrvRecord { Target = target, Port = port, Priority = priority, Weight = weight }); return this; } ///GENMHASH:C37DFCF6F901676D7598649C45DBE65D:E77E730F4D50475504074AA0691BCCC8 public DnsRecordSetImpl WithoutTargetDomainName(string targetDomainName) { this.recordSetRemoveInfo.PtrRecords .Add(new PtrRecord { Ptrdname = targetDomainName }); return this; } ///GENMHASH:B9A12A61DE5C3FD7372657598F28C736:C0E78FE3325BAB97993FBD6D1EC3DD20 public DnsRecordSetImpl WithoutText(string text) { if (text == null) { return this; } List<string> chunks = new List<string>(); chunks.Add(text); return WithoutText(chunks); } ///GENMHASH:7514E74617844D31FA17DECC30EC7487:D45180FF29FB5C16A3FD358D567C01FD public DnsRecordSetImpl WithoutText(IList<string> textChunks) { this.recordSetRemoveInfo.TxtRecords .Add(new TxtRecord { Value = textChunks }); return this; } ///GENMHASH:6AA2FF71573E83BF2E72B639167FEB03:2CE5820762CA700DB500887C608143C5 public DnsRecordSetImpl WithRecord(int flags, string tag, string value) { Inner.CaaRecords .Add(new CaaRecord { Flags = flags, Tag = tag, Value = value }); return this; } ///GENMHASH:FB0C10CB41D7B922FF0580521AB216A6:8CAEADA4A5AF9EE51022E3AACA965264 public DnsRecordSetImpl WithRecord(string target, int port, int priority, int weight) { Inner.SrvRecords .Add(new SrvRecord { Target = target, Port = port, Priority = priority, Weight = weight }); return this; } ///GENMHASH:6D37E4EB187608D1444EE0B12AEEAB67:4B5F1BDCC88474FFF19319243A41B6F7 public DnsRecordSetImpl WithRefreshTimeInSeconds(long refreshTimeInSeconds) { Inner.SoaRecord.RefreshTime = refreshTimeInSeconds; return this; } ///GENMHASH:4B07DB88181953A1AA185580F8B1266A:B3424C4783A914D6F340B7301EAFAE8E public DnsRecordSetImpl WithRetryTimeInSeconds(long retryTimeInSeconds) { Inner.SoaRecord.RetryTime = retryTimeInSeconds; return this; } ///GENMHASH:EF847E8C645CB64D66F22F7C8F41EADF:668CAC97ECB380171D891C73BE38F63B public DnsRecordSetImpl WithSerialNumber(long serialNumber) { Inner.SoaRecord.SerialNumber = serialNumber; return this; } ///GENMHASH:7126FE6FA387F1E4960F18681C53EC88:B90619A2787B110ED29E0558824FCEEC public DnsRecordSetImpl WithTargetDomainName(string targetDomainName) { Inner.PtrRecords .Add(new PtrRecord { Ptrdname = targetDomainName }); return this; } ///GENMHASH:6300EBC9252C6530D70C1A6340171C08:0B11517DD7B5F9988EBD2D8574642F18 public DnsRecordSetImpl WithText(string text) { if (text == null) { return this; } List<string> value = new List<string>(); if (text.Length < 255) { value.Add(text); } else { value.AddRange(Enumerable.Range(0, (int)(Math.Ceiling(text.Length / (double)255))).Select(i => text.Substring(i * 255, 255))); } Inner.TxtRecords.Add(new TxtRecord { Value = value }); return this; } ///GENMHASH:06F60982829BD1FCB08F550025D02EC6:DB0A29B22B9B76C5DFDCA28B3F4AD95F public DnsRecordSetImpl WithTimeToLive(long ttlInSeconds) { Inner.TTL = ttlInSeconds; return this; } ///GENTHASH:Y29tLm1pY3Jvc29mdC5henVyZS5tYW5hZ2VtZW50LmRucy5pbXBsZW1lbnRhdGlvbi5EbnNSZWNvcmRTZXRJbXBsLkVUYWdTdGF0ZQ== class ETagState { private bool doImplicitETagCheckOnCreate; private bool doImplicitETagCheckOnUpdate; private string eTagOnDelete; private string eTagOnUpdate; ///GENMHASH:7F12CEB5CD4DF5F0961FA9BDFD4F1275:27E486AB74A10242FF421C0798DDC450 public ETagState() { } ///GENMHASH:BDEEEC08EF65465346251F0F99D16258:C50E159EF615C54F8F31030BCA0B7576 public ETagState Clear() { this.doImplicitETagCheckOnCreate = false; this.doImplicitETagCheckOnUpdate = false; this.eTagOnUpdate = null; this.eTagOnDelete = null; return this; } ///GENMHASH:D3CEF7E2B598DD354274A5AFE552A662:A20A52DB2A85D7C3C8296FDFB1961372 public string IfMatchValueOnDelete() { return this.eTagOnDelete; } ///GENMHASH:2FE5CB6C2E7B55F99613F61DA9EF4F1D:E1C7BCC3B078606C167311CDD4A1A54B public string IfMatchValueOnUpdate(string currentETagValue) { string eTagValue = null; if (this.doImplicitETagCheckOnUpdate) { eTagValue = currentETagValue; } if (this.eTagOnUpdate != null) { eTagValue = this.eTagOnUpdate; } return eTagValue; } ///GENMHASH:212FE0B4DFB2C1FB72091A3F8865BE1B:CE3736CC8D80616CC9B9031CC0D0E5CA public string IfNonMatchValueOnCreate() { if (this.doImplicitETagCheckOnCreate) { return "*"; } return null; } ///GENMHASH:C8126BDFD9A21FF4295AF1F12B4EA871:99938E9DF848049CBB209F4237FC0B7B public ETagState WithExplicitETagCheckOnDelete(string eTagValue) { this.eTagOnDelete = eTagValue; return this; } ///GENMHASH:A2B627C663DDB747C621FCA1D7BE24A8:76A309CFA4E29C8A8F8C92BCF73A1AB6 public ETagState WithExplicitETagCheckOnUpdate(string eTagValue) { this.eTagOnUpdate = eTagValue; return this; } ///GENMHASH:441A98D786D840B5B136CFD0CE477BAA:FFF1B40244858F3A733FD6117C08970B public ETagState WithImplicitETagCheckOnCreate() { this.doImplicitETagCheckOnCreate = true; return this; } ///GENMHASH:E56828D96951375F4EF1730388DE7346:5A4ECB9B6B7CBD3113C2CAA49D6DD200 public ETagState WithImplicitETagCheckOnUpdate() { this.doImplicitETagCheckOnUpdate = true; return this; } } DnsZone.Update.IUpdate ISettable<DnsZone.Update.IUpdate>.Parent() { return this.Parent; } } }
using System; using System.IO; using UnityEngine; namespace GifEncoder { public class AnimatedGifEncoder { protected int width; // image size protected int height; protected int repeat = 0; // no repeat protected int delay = 0; // frame delay (hundredths) protected FileStream fs; protected Color32[] currentFramePixels; // current frame pixels protected byte[] pixels; // BGR byte array from frame protected byte[] visiblePixels; protected byte[] indexedPixels; // converted frame indexed to palette protected int colorDepth; // number of bit planes protected byte[] colorTab; // RGB palette protected bool[] usedEntry = new bool[256]; // active palette entries protected int palSize; // color table size (bits-1) protected bool firstFrame = true; protected bool sizeSet = false; // if false, get size from first frame protected int sample = 10; // default sample interval for quantizer protected NeuQuant nq; public AnimatedGifEncoder(string filePath) { this.fs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None); this.WriteString("GIF89a"); // header } /// <summary> /// Sets the delay time between each frame, or changes it for subsequent frames (applies to last frame added). /// </summary> /// <param name="ms">delay time in milliseconds</param> public void SetDelay(int ms) { this.delay = (int)Math.Round(ms / 10.0f); } /// <summary> /// Adds a frame to the animated GIF. If this is the first frame, it will be used to specify the size and color palette of the GIF. /// </summary> public void AddFrame(Texture2D frame) { if (!this.sizeSet) { // use first frame's size this.width = frame.width; this.height = frame.height; this.sizeSet = true; } this.currentFramePixels = frame.GetPixels32(); this.GetImagePixels(); // convert to correct format if necessary this.AnalyzePixels(); // build color table & map pixels if (this.firstFrame) { this.WriteLSD(); // logical screen descriptior this.WritePalette(); // global color table if (this.repeat >= 0) { // use NS app extension to indicate reps this.WriteNetscapeExt(); } } this.WriteGraphicCtrlExt(); // write graphic control extension this.WriteImageDesc(); // image descriptor this.WritePixels(); // encode and write pixel data this.firstFrame = false; } /// <summary> /// Flushes any pending data and closes output file. /// </summary> public void Finish() { this.fs.WriteByte(0x3b); // gif trailer this.fs.Flush(); this.fs.Close(); } /// <summary> /// Cancels the encoding process and deletes the temporary file. /// </summary> public void Cancel() { string filePath = this.fs.Name; this.Finish(); File.Delete(filePath); } /// <summary> /// Analyzes image colors and creates color map. /// </summary> private void AnalyzePixels() { if (this.firstFrame) { // HEY YOU - THIS IS IMPORTANT! // // Unlike the code this project is built on, we generate a palette only once, using the data from the // first frame. This speeds up encoding (building the palette is slow) and makes it so that subsequent // frames use the same colors and look more consistent from frame to frame, but has an undesirable // side-effect of getting confused when radically different colors show up in later frames. This wasn't // a problem with Infinifactory, but if your game uses a deliberately reduced color palette you might // want to switch back to using per-frame palettes. // // This is, of course, left as an exercise for the reader. // initialize quantizer and create reduced palette this.nq = new NeuQuant(this.pixels, this.pixels.Length, this.sample); this.colorTab = nq.Process(); // create the buffer for the displayed pixel data: this.visiblePixels = new byte[this.pixels.Length]; } int nPix = this.pixels.Length / 3; this.indexedPixels = new byte[nPix]; // map image pixels to new palette for (int i = 0; i < nPix; i++) { int r = i * 3 + 0; int g = r + 1; int b = g + 1; // HEY YOU - THIS IS IMPORTANT! // // As you may know, animated GIFs aren't exactly the most efficient way to encode video; notably, // they lack the interframe compression found in real video formats. However, we can do something // similar by taking advantage of the GIF format's ability to "build on" a previous frame by // specifying pixels as transparent and allowing the previous frame's image to show through in those // locations. If a pixel doesn't change much from a previous pixel it will be replaced with the // transparent color, and if enough of those pixels are used in a frame it will compress much better // than if you had all the original color data for the frame. // // In a game like Infinifactory, where the recording camera is locked and only a small portion of // the scene is animated, this reduced the size of GIFs to about 1/3 of their original size. const int ChangeDelta = 3; bool pixelRequired = this.firstFrame || Math.Abs(this.pixels[r] - this.visiblePixels[r]) > ChangeDelta || Math.Abs(this.pixels[g] - this.visiblePixels[g]) > ChangeDelta || Math.Abs(this.pixels[b] - this.visiblePixels[b]) > ChangeDelta; int index; if (pixelRequired) { this.visiblePixels[r] = this.pixels[r]; this.visiblePixels[g] = this.pixels[g]; this.visiblePixels[b] = this.pixels[b]; index = this.nq.Map(this.pixels[r], this.pixels[g], this.pixels[b]); } else { index = NeuQuant.PaletteSize; } this.usedEntry[index] = true; this.indexedPixels[i] = (byte)index; } this.colorDepth = (int)Math.Log(NeuQuant.PaletteSize + 1, 2); this.palSize = this.colorDepth - 1; } /// <summary> /// Extracts image pixels into byte array "pixels", flipping vertically /// </summary> private void GetImagePixels() { this.pixels = new byte[3 * this.currentFramePixels.Length]; for (int y = 0; y < this.height; y++) { for (int x = 0; x < this.width; x++) { Color32 pixel = this.currentFramePixels[(this.height - 1 - y) * this.width + x]; this.pixels[y * this.width * 3 + x * 3 + 0] = pixel.r; this.pixels[y * this.width * 3 + x * 3 + 1] = pixel.g; this.pixels[y * this.width * 3 + x * 3 + 2] = pixel.b; } } } /// <summary> /// Writes Graphic Control Extension. /// </summary> private void WriteGraphicCtrlExt() { this.fs.WriteByte(0x21); // extension introducer this.fs.WriteByte(0xf9); // GCE label this.fs.WriteByte(4); // data block size if (this.firstFrame) { this.fs.WriteByte(0x00); // packed fields: disposal = 0, transparent = 0 } else { this.fs.WriteByte(0x05); // packed fields: disposal = 1, transparent = 1 } this.WriteShort(delay); // delay x 1/100 sec this.fs.WriteByte((byte)NeuQuant.PaletteSize); // transparent color index this.fs.WriteByte(0); // block terminator } private void WriteImageDesc() { this.fs.WriteByte(0x2c); // image separator this.WriteShort(0); // image position x,y = 0,0 this.WriteShort(0); this.WriteShort(width); // image size this.WriteShort(height); this.fs.WriteByte(0); // packed fields } private void WriteLSD() { // logical screen size this.WriteShort(width); this.WriteShort(height); // packed fields this.fs.WriteByte(Convert.ToByte(0x80 | // 1 : global color table flag = 1 (gct used) 0x70 | // 2-4 : color resolution = 7 0x00 | // 5 : gct sort flag = 0 this.palSize)); // 6-8 : gct size this.fs.WriteByte(0); // background color index this.fs.WriteByte(0); // pixel aspect ratio - assume 1:1 } private void WriteNetscapeExt() { this.fs.WriteByte(0x21); // extension introducer this.fs.WriteByte(0xff); // app extension label this.fs.WriteByte(11); // block size this.WriteString("NETSCAPE" + "2.0"); // app id + auth code this.fs.WriteByte(3); // sub-block size this.fs.WriteByte(1); // loop sub-block id this.WriteShort(repeat); // loop count (extra iterations, 0=repeat forever) this.fs.WriteByte(0); // block terminator } private void WritePalette() { this.fs.Write(this.colorTab, 0, this.colorTab.Length); int n = (3 * (NeuQuant.PaletteSize + 1)) - this.colorTab.Length; for (int i = 0; i < n; i++) { this.fs.WriteByte(0); } } private void WritePixels() { LZWEncoder encoder = new LZWEncoder(this.width, this.height, this.indexedPixels, this.colorDepth); encoder.Encode(this.fs); } private void WriteShort(int value) { this.fs.WriteByte(Convert.ToByte(value & 0xff)); this.fs.WriteByte(Convert.ToByte((value >> 8) & 0xff)); } private void WriteString(String s) { char[] chars = s.ToCharArray(); for (int i = 0; i < chars.Length; i++) { this.fs.WriteByte((byte)chars[i]); } } } }
/********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ using System.Collections; using System.Collections.ObjectModel; using System.Threading; using System.Runtime.Serialization; using Dbg = System.Management.Automation.Diagnostics; using System.Management.Automation.Internal; #if CORECLR // Use stub for SerializableAttribute, SystemException, ThreadAbortException and ISerializable related types. using Microsoft.PowerShell.CoreClr.Stubs; #endif namespace System.Management.Automation.Runspaces { #region Exceptions /// <summary> /// Defines exception which is thrown when state of the pipeline is different /// from expected state. /// </summary> [Serializable] public class InvalidPipelineStateException : SystemException { /// <summary> /// Initializes a new instance of the InvalidPipelineStateException class /// </summary> public InvalidPipelineStateException() : base(StringUtil.Format(RunspaceStrings.InvalidPipelineStateStateGeneral)) { } /// <summary> /// Initializes a new instance of the InvalidPipelineStateException class /// with a specified error message /// </summary> /// <param name="message"> /// The error message that explains the reason for the exception. /// </param> public InvalidPipelineStateException(string message) : base(message) { } /// <summary> /// Initializes a new instance of the InvalidPipelineStateException class /// with a specified error message and a reference to the inner exception that is the cause of this exception. /// </summary> /// <param name="message"> /// The error message that explains the reason for the exception. /// </param> /// <param name="innerException"> /// The exception that is the cause of the current exception. /// </param> public InvalidPipelineStateException(string message, Exception innerException) : base(message, innerException) { } /// <summary> /// Initializes a new instance of the InvalidPipelineStateException and defines value of /// CurrentState and ExpectedState /// </summary> /// <param name="message">The error message that explains the reason for the exception. /// </param> /// <param name="currentState">Current state of pipeline</param> /// <param name="expectedState">Expected state of pipeline</param> internal InvalidPipelineStateException(string message, PipelineState currentState, PipelineState expectedState) : base(message) { _expectedState = expectedState; _currentState = currentState; } #region ISerializable Members // 2005/04/20-JonN No need to implement GetObjectData // if all fields are static or [NonSerialized] /// <summary> /// Initializes a new instance of the <see cref="InvalidPipelineStateException"/> /// class with serialized data. /// </summary> /// <param name="info"> /// The <see cref="SerializationInfo"/> that holds the serialized object /// data about the exception being thrown. /// </param> /// <param name="context"> /// The <see cref="StreamingContext"/> that contains contextual information /// about the source or destination. /// </param> private InvalidPipelineStateException(SerializationInfo info, StreamingContext context) : base(info, context) { } #endregion /// <summary> /// Gets CurrentState of the pipeline /// </summary> public PipelineState CurrentState { get { return _currentState; } } /// <summary> /// Gets ExpectedState of the pipeline /// </summary> public PipelineState ExpectedState { get { return _expectedState; } } /// <summary> /// State of pipleine when exception was thrown. /// </summary> [NonSerialized] private PipelineState _currentState = 0; /// <summary> /// States of the pipeline expected in method which throws this exception. /// </summary> [NonSerialized] private PipelineState _expectedState = 0; } #endregion Exceptions #region PipelineState /// <summary> /// Enumerated type defining the state of the Pipeline /// </summary> public enum PipelineState { /// <summary> /// The pipeline has not been started /// </summary> NotStarted = 0, /// <summary> /// The pipeline is executing /// </summary> Running = 1, /// <summary> /// The pipeline is stoping execution. /// </summary> Stopping = 2, /// <summary> /// The pipeline is completed due to a stop request. /// </summary> Stopped = 3, /// <summary> /// The pipeline has completed. /// </summary> Completed = 4, /// <summary> /// The pipeline completed abnormally due to an error. /// </summary> Failed = 5, /// <summary> /// The pipeline is disconnected from remote running command. /// </summary> Disconnected = 6 } /// <summary> /// Type which has information about PipelineState and Exception /// associated with PipelineState /// </summary> public sealed class PipelineStateInfo { #region constructors /// <summary> /// Constructor for state changes not resulting from an error. /// </summary> /// <param name="state">Execution state</param> internal PipelineStateInfo(PipelineState state) : this(state, null) { } /// <summary> /// Constructor for state changes with an optional error. /// </summary> /// <param name="state">The new state.</param> /// <param name="reason">A non-null exception if the state change was /// caused by an error,otherwise; null. /// </param> internal PipelineStateInfo(PipelineState state, Exception reason) { State = state; Reason = reason; } /// <summary> /// Copy constructor to support cloning /// </summary> /// <param name="pipelineStateInfo">source information</param> /// <throws> /// ArgumentNullException when <paramref name="pipelineStateInfo"/> is null. /// </throws> internal PipelineStateInfo(PipelineStateInfo pipelineStateInfo) { Dbg.Assert(pipelineStateInfo != null, "caller should validate the parameter"); State = pipelineStateInfo.State; Reason = pipelineStateInfo.Reason; } #endregion constructors #region public_properties /// <summary> /// The state of the runspace. /// </summary> /// <remarks> /// This value indicates the state of the pipeline after the change. /// </remarks> public PipelineState State { get; } /// <summary> /// The reason for the state change, if caused by an error. /// </summary> /// <remarks> /// The value of this property is non-null if the state /// changed due to an error. Otherwise, the value of this /// property is null. /// </remarks> public Exception Reason { get; } #endregion public_properties /// <summary> /// Clones this object /// </summary> /// <returns>Cloned object</returns> internal PipelineStateInfo Clone() { return new PipelineStateInfo(this); } } /// <summary> /// Event arguments passed to PipelineStateEvent handlers /// <see cref="Pipeline.StateChanged"/> event. /// </summary> public sealed class PipelineStateEventArgs : EventArgs { #region constructors /// <summary> /// Constructor PipelineStateEventArgs from PipelineStateInfo /// </summary> /// <param name="pipelineStateInfo">The current state of the /// pipeline.</param> /// <throws> /// ArgumentNullException when <paramref name="pipelineStateInfo"/> is null. /// </throws> internal PipelineStateEventArgs(PipelineStateInfo pipelineStateInfo) { Dbg.Assert(pipelineStateInfo != null, "caller should validate the parameter"); PipelineStateInfo = pipelineStateInfo; } #endregion constructors #region public_properties /// <summary> /// Info about current state of pipeline. /// </summary> public PipelineStateInfo PipelineStateInfo { get; } #endregion public_properties } #endregion ExecutionState /// <summary> /// Defines a class which can be used to invoke a pipeline of commands. /// </summary> public abstract class Pipeline : IDisposable { #region constructor /// <summary> /// Explicit default constructor /// </summary> internal Pipeline(Runspace runspace) : this(runspace, new CommandCollection()) { } /// <summary> /// Constructor to initialize both Runspace and Command to invoke. /// Caller should make sure that "command" is not null. /// </summary> /// <param name="runspace"> /// Runspace to use for the command invocation. /// </param> /// <param name="command"> /// command to Invoke. /// Caller should make sure that "command" is not null. /// </param> internal Pipeline(Runspace runspace, CommandCollection command) { if (runspace == null) { PSTraceSource.NewArgumentNullException("runspace"); } // This constructor is used only internally. // Caller should make sure the input is valid Dbg.Assert(null != command, "Command cannot be null"); InstanceId = runspace.GeneratePipelineId(); Commands = command; // Reset the AMSI session so that it is re-initialized // when the next script block is parsed. AmsiUtils.CloseSession(); } #endregion constructor #region properties /// <summary> /// gets the runspace this pipeline is created on. /// </summary> public abstract Runspace Runspace { get; } /// <summary> /// Gets the property which indicates if this pipeline is nested. /// </summary> public abstract bool IsNested { get; } /// <summary> /// Gets the property which indicates if this pipeline is a child pipeline. /// /// IsChild flag makes it possible for the pipeline to differentiate between /// a true v1 nested pipeline and the cmdlets calling cmdlets case. See bug /// 211462. /// </summary> internal virtual bool IsChild { get { return false; } set { } } /// <summary> /// gets input writer for this pipeline. /// </summary> /// <remarks> /// When the caller calls Input.Write(), the caller writes to the /// input of the pipeline. Thus, <paramref name="Input"/> /// is a PipelineWriter or "thing which can be written to". /// Note:Input must be closed after Pipeline.InvokeAsync for InvokeAsync to /// finish. /// </remarks> public abstract PipelineWriter Input { get; } /// <summary> /// Gets the output reader for this pipeline. /// </summary> /// <remarks> /// When the caller calls Output.Read(), the caller reads from the /// output of the pipeline. Thus, <paramref name="Output"/> /// is a PipelineReader or "thing which can be read from". /// </remarks> public abstract PipelineReader<PSObject> Output { get; } /// <summary> /// gets the error output reader for this pipeline. /// </summary> /// <remarks> /// When the caller calls Error.Read(), the caller reads from the /// output of the pipeline. Thus, <paramref name="Error"/> /// is a PipelineReader or "thing which can be read from". /// /// This is the non-terminating error stream from the command. /// In this release, the objects read from this PipelineReader /// are PSObjects wrapping ErrorRecords. /// </remarks> public abstract PipelineReader<object> Error { get; } /// <summary> /// Gets Info about current state of the pipeline. /// </summary> /// <remarks> /// This value indicates the state of the pipeline after the change. /// </remarks> public abstract PipelineStateInfo PipelineStateInfo { get; } /// <summary> /// True if pipeline execution encountered and error. /// It will alwys be true if _reason is non-null /// since an exception occurred. For other error types, /// It has to be set manually. /// </summary> public virtual bool HadErrors { get { return _hadErrors; } } private bool _hadErrors; internal void SetHadErrors(bool status) { _hadErrors = _hadErrors || status; } /// <summary> /// gets the unique identifier for this pipeline. This indentifier is unique with in /// the scope of Runspace. /// </summary> public long InstanceId { get; } /// <summary> /// gets the collection of commands for this pipeline. /// </summary> public CommandCollection Commands { get; private set; } /// <summary> /// If this property is true, SessionState is updated for this /// pipeline state. /// </summary> public bool SetPipelineSessionState { get; set; } = true; /// <summary> /// Settings for the pipeline invocation thread. /// </summary> internal PSInvocationSettings InvocationSettings { get; set; } /// <summary> /// If this flag is true, the commands in this Pipeline will redirect the global error output pipe /// (ExecutionContext.ShellFunctionErrorOutputPipe) to the command's error output pipe. /// /// When the global error output pipe is not set, $ErrorActionPreference is not checked and all /// errors are treated as terminating errors. /// /// On V1, the global error output pipe is redirected to the command's error output pipe only when /// it has already been redirected. The command-line host achieves this redirection by merging the /// error output into the output pipe so it checks $ErrorActionPreference all right. However, when /// the Pipeline class is used programatically the global error output pipe is not set and the first /// error terminates the pipeline. /// /// This flag is used to force the redirection. By default it is false to maintain compatibility with /// V1, but the V2 hosting interface (PowerShell class) sets this flag to true to ensure the global /// error output pipe is always set and $ErrorActionPreference when invoking the Pipeline. /// </summary> internal bool RedirectShellErrorOutputPipe { get; set; } = false; #endregion properties #region events /// <summary> /// Event raised when Pipeline's state changes. /// </summary> public abstract event EventHandler<PipelineStateEventArgs> StateChanged; #endregion events #region methods /// <summary> /// Invoke the pipeline, synchronously, returning the results as an array of /// objects. /// </summary> /// <remarks>If using synchronous invoke, do not close /// input objectWriter. Synchronous invoke will always close the input /// objectWriter. /// </remarks> /// <exception cref="InvalidOperationException"> /// No command is added to pipeline /// </exception> /// <exception cref="InvalidPipelineStateException"> /// PipelineState is not NotStarted. /// </exception> /// <exception cref="InvalidOperationException"> /// 1) A pipeline is already executing. Pipeline cannot execute /// concurrently. /// 2) Attempt is made to invoke a nested pipeline directly. Nested /// pipeline must be invoked from a running pipeline. /// </exception> /// <exception cref="InvalidRunspaceStateException"> /// RunspaceState is not Open /// </exception> /// <exception cref="ObjectDisposedException"> /// Pipeline already disposed /// </exception> /// <exception cref="ScriptCallDepthException"> /// The script recursed too deeply into script functions. /// There is a fixed limit on the depth of recursion. /// </exception> /// <exception cref="System.Security.SecurityException"> /// A CLR security violation occurred. Typically, this happens /// because the current CLR permissions do not allow adequate /// reflextion access to a cmdlet assembly. /// </exception> /// <exception cref="ThreadAbortException"> /// The thread in which the pipeline was executing was aborted. /// </exception> /// <exception cref="RuntimeException"> /// Pipeline.Invoke can throw a variety of exceptions derived /// from RuntimeException. The most likely of these exceptions /// are listed below. /// </exception> /// <exception cref="ParameterBindingException"> /// One of more parameters or parameter values specified for /// a cmdlet are not valid, or mandatory parameters for a cmdlet /// were not specified. /// </exception> /// <exception cref="CmdletInvocationException"> /// A cmdlet generated a terminating error. /// </exception> /// <exception cref="CmdletProviderInvocationException"> /// A provider generated a terminating error. /// </exception> /// <exception cref="ActionPreferenceStopException"> /// The ActionPreference.Stop or ActionPreference.Inquire policy /// triggered a terminating error. /// </exception> /// <exception cref="PipelineStoppedException"> /// The pipeline was terminated asynchronously. /// </exception> /// <exception cref="MetadataException"> /// If there is an error generating the metadata for dynamic parameters. /// </exception> public Collection<PSObject> Invoke() { return Invoke(null); } /// <summary> /// Invoke the pipeline, synchronously, returning the results as an array of objects. /// </summary> /// <param name="input">an array of input objects to pass to the pipeline. /// Array may be empty but may not be null</param> /// <returns>An array of zero or more result objects</returns> /// <remarks>If using synchronous exectute, do not close /// input objectWriter. Synchronous invoke will always close the input /// objectWriter. /// </remarks> /// <exception cref="InvalidOperationException"> /// No command is added to pipeline /// </exception> /// <exception cref="InvalidPipelineStateException"> /// PipelineState is not NotStarted. /// </exception> /// <exception cref="InvalidOperationException"> /// 1) A pipeline is already executing. Pipeline cannot execute /// concurrently. /// 2) Attempt is made to invoke a nested pipeline directly. Nested /// pipeline must be invoked from a running pipeline. /// </exception> /// <exception cref="InvalidRunspaceStateException"> /// RunspaceState is not Open /// </exception> /// <exception cref="ObjectDisposedException"> /// Pipeline already disposed /// </exception> /// <exception cref="ScriptCallDepthException"> /// The script recursed too deeply into script functions. /// There is a fixed limit on the depth of recursion. /// </exception> /// <exception cref="System.Security.SecurityException"> /// A CLR security violation occurred. Typically, this happens /// because the current CLR permissions do not allow adequate /// reflextion access to a cmdlet assembly. /// </exception> /// <exception cref="ThreadAbortException"> /// The thread in which the pipeline was executing was aborted. /// </exception> /// <exception cref="RuntimeException"> /// Pipeline.Invoke can throw a variety of exceptions derived /// from RuntimeException. The most likely of these exceptions /// are listed below. /// </exception> /// <exception cref="ParameterBindingException"> /// One of more parameters or parameter values specified for /// a cmdlet are not valid, or mandatory parameters for a cmdlet /// were not specified. /// </exception> /// <exception cref="CmdletInvocationException"> /// A cmdlet generated a terminating error. /// </exception> /// <exception cref="CmdletProviderInvocationException"> /// A provider generated a terminating error. /// </exception> /// <exception cref="ActionPreferenceStopException"> /// The ActionPreference.Stop or ActionPreference.Inquire policy /// triggered a terminating error. /// </exception> /// <exception cref="PipelineStoppedException"> /// The pipeline was terminated asynchronously. /// </exception> /// <exception cref="MetadataException"> /// If there is an error generating the metadata for dynamic parameters. /// </exception> public abstract Collection<PSObject> Invoke(IEnumerable input); /// <summary> /// Invoke the pipeline asynchronously /// </summary> /// <remarks> /// 1) Results are returned through the <see cref="Pipeline.Output"/> reader. /// 2) When pipeline is invoked using InvokeAsync, invocation doesn't /// finish until Input to pipeline is closed. Caller of InvokeAsync must close /// the input pipe after all input has been written to input pipe. Input pipe /// is closed by calling Pipeline.Input.Close(); /// /// If you want this pipeline to execute as a standalone command /// (that is, using command-line parameters only), /// be sure to call Pipeline.Input.Close() before calling /// InvokeAsync(). Otherwise, the command will be executed /// as though it had external input. If you observe that the /// command isn't doing anything, this may be the reason. /// </remarks> /// <exception cref="InvalidOperationException"> /// No command is added to pipeline /// </exception> /// <exception cref="InvalidPipelineStateException"> /// PipelineState is not NotStarted. /// </exception> /// <exception cref="InvalidOperationException"> /// 1) A pipeline is already executing. Pipeline cannot execute /// concurrently. /// 2) InvokeAsync is called on nested pipeline. Nested pipeline /// cannot be executed Asynchronously. /// </exception> /// <exception cref="InvalidRunspaceStateException"> /// RunspaceState is not Open /// </exception> /// <exception cref="ObjectDisposedException"> /// Pipeline already disposed /// </exception> public abstract void InvokeAsync(); /// <summary> /// Synchronous call to stop the running pipeline. /// </summary> public abstract void Stop(); /// <summary> /// Asynchronous call to stop the running pipeline. /// </summary> public abstract void StopAsync(); /// <summary> /// Creates a new <see cref="Pipeline"/> that is a copy of the current instance. /// </summary> /// <returns>A new <see cref="Pipeline"/> that is a copy of this instance.</returns> public abstract Pipeline Copy(); /// <summary> /// Connects synchronously to a running command on a remote server. /// The pipeline object must be in the disconnected state. /// </summary> /// <returns>A collection of result objects.</returns> public abstract Collection<PSObject> Connect(); /// <summary> /// Connects asynchronously to a running command on a remote server. /// </summary> public abstract void ConnectAsync(); /// <summary> /// Sets the command collection. /// </summary> /// <param name="commands">command collection to set</param> /// <remarks>called by ClientRemotePipeline</remarks> internal void SetCommandCollection(CommandCollection commands) { Commands = commands; } /// <summary> /// Sets the history string to the one that is specified /// </summary> /// <param name="historyString">history string to set</param> internal abstract void SetHistoryString(String historyString); /// <summary> /// Invokes a remote command and immediately disconnects if /// transport layer supports it. /// </summary> internal abstract void InvokeAsyncAndDisconnect(); #endregion methods #region Remote data drain/block methods /// <summary> /// Blocks data arriving from remote session. /// </summary> internal virtual void SuspendIncomingData() { throw new PSNotImplementedException(); } /// <summary> /// Resumes data arrive from remote session. /// </summary> internal virtual void ResumeIncomingData() { throw new PSNotImplementedException(); } /// <summary> /// Blocking call that waits until the current remote data /// queue is empty. /// </summary> internal virtual void DrainIncomingData() { throw new PSNotImplementedException(); } #endregion #region IDisposable Members /// <summary> /// Disposes the pipeline. If pipeline is running, dispose first /// stops the pipeline. /// </summary> public void Dispose() { Dispose(!IsChild); GC.SuppressFinalize(this); } /// <summary> /// Protected dispose which can be overridden by derived classes. /// </summary> /// <param name="disposing"></param> protected virtual void Dispose(bool disposing) { } #endregion IDisposable Members } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Linq; using System.Net.Http.Headers; using System.Text; using Xunit; namespace System.Net.Http.Tests { public class HttpContentHeadersTest { private HttpContentHeaders _headers; public HttpContentHeadersTest() { _headers = new HttpContentHeaders(null); } [Fact] public void ContentLength_AddInvalidValueUsingUnusualCasing_ParserRetrievedUsingCaseInsensitiveComparison() { _headers = new HttpContentHeaders(() => { return 15; }); // Use uppercase header name to make sure the parser gets retrieved using case-insensitive comparison. Assert.Throws<FormatException>(() => { _headers.Add("CoNtEnT-LeNgTh", "this is invalid"); }); } [Fact] public void ContentLength_ReadValue_DelegateInvoked() { _headers = new HttpContentHeaders(() => { return 15; }); // The delegate is invoked to return the length. Assert.Equal(15, _headers.ContentLength); Assert.Equal((long)15, _headers.GetParsedValues(HttpKnownHeaderNames.ContentLength)); // After getting the calculated content length, set it to null. _headers.ContentLength = null; Assert.Equal(null, _headers.ContentLength); Assert.False(_headers.Contains(HttpKnownHeaderNames.ContentLength)); _headers.ContentLength = 27; Assert.Equal((long)27, _headers.ContentLength); Assert.Equal((long)27, _headers.GetParsedValues(HttpKnownHeaderNames.ContentLength)); } [Fact] public void ContentLength_SetCustomValue_DelegateNotInvoked() { _headers = new HttpContentHeaders(() => { Assert.True(false, "Delegate called."); return 0; }); _headers.ContentLength = 27; Assert.Equal((long)27, _headers.ContentLength); Assert.Equal((long)27, _headers.GetParsedValues(HttpKnownHeaderNames.ContentLength)); // After explicitly setting the content length, set it to null. _headers.ContentLength = null; Assert.Equal(null, _headers.ContentLength); Assert.False(_headers.Contains(HttpKnownHeaderNames.ContentLength)); // Make sure the header gets serialized correctly _headers.ContentLength = 12345; Assert.Equal("12345", _headers.GetValues("Content-Length").First()); } [Fact] public void ContentLength_UseAddMethod_AddedValueCanBeRetrievedUsingProperty() { _headers = new HttpContentHeaders(() => { Assert.True(false, "Delegate called."); return 0; }); _headers.TryAddWithoutValidation(HttpKnownHeaderNames.ContentLength, " 68 \r\n "); Assert.Equal(68, _headers.ContentLength); } [Fact] public void ContentType_ReadAndWriteProperty_ValueMatchesPriorSetValue() { MediaTypeHeaderValue value = new MediaTypeHeaderValue("text/plain"); value.CharSet = "utf-8"; value.Parameters.Add(new NameValueHeaderValue("custom", "value")); Assert.Null(_headers.ContentType); _headers.ContentType = value; Assert.Same(value, _headers.ContentType); _headers.ContentType = null; Assert.Null(_headers.ContentType); } [Fact] public void ContentType_UseAddMethod_AddedValueCanBeRetrievedUsingProperty() { _headers.TryAddWithoutValidation("Content-Type", "text/plain; charset=utf-8; custom=value"); MediaTypeHeaderValue value = new MediaTypeHeaderValue("text/plain"); value.CharSet = "utf-8"; value.Parameters.Add(new NameValueHeaderValue("custom", "value")); Assert.Equal(value, _headers.ContentType); } [Fact] public void ContentType_UseAddMethodWithInvalidValue_InvalidValueRecognized() { _headers.TryAddWithoutValidation("Content-Type", "text/plain; charset=utf-8; custom=value, other/type"); Assert.Null(_headers.ContentType); Assert.Equal(1, _headers.GetValues("Content-Type").Count()); Assert.Equal("text/plain; charset=utf-8; custom=value, other/type", _headers.GetValues("Content-Type").First()); _headers.Clear(); _headers.TryAddWithoutValidation("Content-Type", ",text/plain"); // leading separator Assert.Null(_headers.ContentType); Assert.Equal(1, _headers.GetValues("Content-Type").Count()); Assert.Equal(",text/plain", _headers.GetValues("Content-Type").First()); _headers.Clear(); _headers.TryAddWithoutValidation("Content-Type", "text/plain,"); // trailing separator Assert.Null(_headers.ContentType); Assert.Equal(1, _headers.GetValues("Content-Type").Count()); Assert.Equal("text/plain,", _headers.GetValues("Content-Type").First()); } [Fact] public void ContentRange_ReadAndWriteProperty_ValueMatchesPriorSetValue() { Assert.Null(_headers.ContentRange); ContentRangeHeaderValue value = new ContentRangeHeaderValue(1, 2, 3); _headers.ContentRange = value; Assert.Equal(value, _headers.ContentRange); _headers.ContentRange = null; Assert.Null(_headers.ContentRange); } [Fact] public void ContentRange_UseAddMethod_AddedValueCanBeRetrievedUsingProperty() { _headers.TryAddWithoutValidation("Content-Range", "custom 1-2/*"); ContentRangeHeaderValue value = new ContentRangeHeaderValue(1, 2); value.Unit = "custom"; Assert.Equal(value, _headers.ContentRange); } [Fact] public void ContentLocation_ReadAndWriteProperty_ValueMatchesPriorSetValue() { Assert.Null(_headers.ContentLocation); Uri expected = new Uri("http://example.com/path/"); _headers.ContentLocation = expected; Assert.Equal(expected, _headers.ContentLocation); _headers.ContentLocation = null; Assert.Null(_headers.ContentLocation); Assert.False(_headers.Contains("Content-Location")); } [Fact] public void ContentLocation_UseAddMethod_AddedValueCanBeRetrievedUsingProperty() { _headers.TryAddWithoutValidation("Content-Location", " http://www.example.com/path/?q=v "); Assert.Equal(new Uri("http://www.example.com/path/?q=v"), _headers.ContentLocation); _headers.Clear(); _headers.TryAddWithoutValidation("Content-Location", "/relative/uri/"); Assert.Equal(new Uri("/relative/uri/", UriKind.Relative), _headers.ContentLocation); } [Fact] public void ContentLocation_UseAddMethodWithInvalidValue_InvalidValueRecognized() { _headers.TryAddWithoutValidation("Content-Location", " http://example.com http://other"); Assert.Null(_headers.GetParsedValues("Content-Location")); Assert.Equal(1, _headers.GetValues("Content-Location").Count()); Assert.Equal(" http://example.com http://other", _headers.GetValues("Content-Location").First()); _headers.Clear(); _headers.TryAddWithoutValidation("Content-Location", "http://host /other"); Assert.Null(_headers.GetParsedValues("Content-Location")); Assert.Equal(1, _headers.GetValues("Content-Location").Count()); Assert.Equal("http://host /other", _headers.GetValues("Content-Location").First()); } [Fact] public void ContentEncoding_ReadAndWriteProperty_ValueMatchesPriorSetValue() { Assert.Equal(0, _headers.ContentEncoding.Count); _headers.ContentEncoding.Add("custom1"); _headers.ContentEncoding.Add("custom2"); Assert.Equal(2, _headers.ContentEncoding.Count); Assert.Equal(2, _headers.GetValues("Content-Encoding").Count()); Assert.Equal("custom1", _headers.ContentEncoding.ElementAt(0)); Assert.Equal("custom2", _headers.ContentEncoding.ElementAt(1)); _headers.ContentEncoding.Clear(); Assert.Equal(0, _headers.ContentEncoding.Count); Assert.False(_headers.Contains("Content-Encoding")); } [Fact] public void ContentEncoding_UseAddMethod_AddedValueCanBeRetrievedUsingProperty() { _headers.TryAddWithoutValidation("Content-Encoding", ",custom1, custom2, custom3,"); Assert.Equal(3, _headers.ContentEncoding.Count); Assert.Equal(3, _headers.GetValues("Content-Encoding").Count()); Assert.Equal("custom1", _headers.ContentEncoding.ElementAt(0)); Assert.Equal("custom2", _headers.ContentEncoding.ElementAt(1)); Assert.Equal("custom3", _headers.ContentEncoding.ElementAt(2)); _headers.ContentEncoding.Clear(); Assert.Equal(0, _headers.ContentEncoding.Count); Assert.False(_headers.Contains("Content-Encoding")); } [Fact] public void ContentEncoding_UseAddMethodWithInvalidValue_InvalidValueRecognized() { _headers.TryAddWithoutValidation("Content-Encoding", "custom1 custom2"); // no separator Assert.Equal(0, _headers.ContentEncoding.Count); Assert.Equal(1, _headers.GetValues("Content-Encoding").Count()); Assert.Equal("custom1 custom2", _headers.GetValues("Content-Encoding").First()); } [Fact] public void ContentLanguage_ReadAndWriteProperty_ValueMatchesPriorSetValue() { Assert.Equal(0, _headers.ContentLanguage.Count); // Note that Content-Language for us is just a list of tokens. We don't verify if the format is a valid // language tag. Users will pass the language tag to other classes like Encoding.GetEncoding() to retrieve // an encoding. These classes will do not only syntax checking but also verify if the language tag exists. _headers.ContentLanguage.Add("custom1"); _headers.ContentLanguage.Add("custom2"); Assert.Equal(2, _headers.ContentLanguage.Count); Assert.Equal(2, _headers.GetValues("Content-Language").Count()); Assert.Equal("custom1", _headers.ContentLanguage.ElementAt(0)); Assert.Equal("custom2", _headers.ContentLanguage.ElementAt(1)); _headers.ContentLanguage.Clear(); Assert.Equal(0, _headers.ContentLanguage.Count); Assert.False(_headers.Contains("Content-Language")); } [Fact] public void ContentLanguage_UseAddMethod_AddedValueCanBeRetrievedUsingProperty() { _headers.TryAddWithoutValidation("Content-Language", ",custom1, custom2, custom3,"); Assert.Equal(3, _headers.ContentLanguage.Count); Assert.Equal(3, _headers.GetValues("Content-Language").Count()); Assert.Equal("custom1", _headers.ContentLanguage.ElementAt(0)); Assert.Equal("custom2", _headers.ContentLanguage.ElementAt(1)); Assert.Equal("custom3", _headers.ContentLanguage.ElementAt(2)); _headers.ContentLanguage.Clear(); Assert.Equal(0, _headers.ContentLanguage.Count); Assert.False(_headers.Contains("Content-Language")); } [Fact] public void ContentLanguage_UseAddMethodWithInvalidValue_InvalidValueRecognized() { _headers.TryAddWithoutValidation("Content-Language", "custom1 custom2"); // no separator Assert.Equal(0, _headers.ContentLanguage.Count); Assert.Equal(1, _headers.GetValues("Content-Language").Count()); Assert.Equal("custom1 custom2", _headers.GetValues("Content-Language").First()); } [Fact] public void ContentMD5_ReadAndWriteProperty_ValueMatchesPriorSetValue() { Assert.Null(_headers.ContentMD5); byte[] expected = new byte[] { 1, 2, 3, 4, 5, 6, 7 }; _headers.ContentMD5 = expected; Assert.Equal(expected, _headers.ContentMD5); // must be the same object reference // Make sure the header gets serialized correctly Assert.Equal("AQIDBAUGBw==", _headers.GetValues("Content-MD5").First()); _headers.ContentMD5 = null; Assert.Null(_headers.ContentMD5); Assert.False(_headers.Contains("Content-MD5")); } [Fact] public void ContentMD5_UseAddMethod_AddedValueCanBeRetrievedUsingProperty() { _headers.TryAddWithoutValidation("Content-MD5", " lvpAKQ== "); Assert.Equal(new byte[] { 150, 250, 64, 41 }, _headers.ContentMD5); _headers.Clear(); _headers.TryAddWithoutValidation("Content-MD5", "+dIkS/MnOP8="); Assert.Equal(new byte[] { 249, 210, 36, 75, 243, 39, 56, 255 }, _headers.ContentMD5); } [Fact] public void ContentMD5_UseAddMethodWithInvalidValue_InvalidValueRecognized() { _headers.TryAddWithoutValidation("Content-MD5", "AQ--"); Assert.Null(_headers.GetParsedValues("Content-MD5")); Assert.Equal(1, _headers.GetValues("Content-MD5").Count()); Assert.Equal("AQ--", _headers.GetValues("Content-MD5").First()); _headers.Clear(); _headers.TryAddWithoutValidation("Content-MD5", "AQ==, CD"); Assert.Null(_headers.GetParsedValues("Content-MD5")); Assert.Equal(1, _headers.GetValues("Content-MD5").Count()); Assert.Equal("AQ==, CD", _headers.GetValues("Content-MD5").First()); } [Fact] public void Allow_ReadAndWriteProperty_ValueMatchesPriorSetValue() { Assert.Equal(0, _headers.Allow.Count); _headers.Allow.Add("custom1"); _headers.Allow.Add("custom2"); Assert.Equal(2, _headers.Allow.Count); Assert.Equal(2, _headers.GetValues("Allow").Count()); Assert.Equal("custom1", _headers.Allow.ElementAt(0)); Assert.Equal("custom2", _headers.Allow.ElementAt(1)); _headers.Allow.Clear(); Assert.Equal(0, _headers.Allow.Count); Assert.False(_headers.Contains("Allow")); } [Fact] public void Allow_UseAddMethod_AddedValueCanBeRetrievedUsingProperty() { _headers.TryAddWithoutValidation("Allow", ",custom1, custom2, custom3,"); Assert.Equal(3, _headers.Allow.Count); Assert.Equal(3, _headers.GetValues("Allow").Count()); Assert.Equal("custom1", _headers.Allow.ElementAt(0)); Assert.Equal("custom2", _headers.Allow.ElementAt(1)); Assert.Equal("custom3", _headers.Allow.ElementAt(2)); _headers.Allow.Clear(); Assert.Equal(0, _headers.Allow.Count); Assert.False(_headers.Contains("Allow")); } [Fact] public void Allow_UseAddMethodWithInvalidValue_InvalidValueRecognized() { _headers.TryAddWithoutValidation("Allow", "custom1 custom2"); // no separator Assert.Equal(0, _headers.Allow.Count); Assert.Equal(1, _headers.GetValues("Allow").Count()); Assert.Equal("custom1 custom2", _headers.GetValues("Allow").First()); } [Fact] public void Expires_ReadAndWriteProperty_ValueMatchesPriorSetValue() { Assert.Null(_headers.Expires); DateTimeOffset expected = DateTimeOffset.Now; _headers.Expires = expected; Assert.Equal(expected, _headers.Expires); _headers.Expires = null; Assert.Null(_headers.Expires); Assert.False(_headers.Contains("Expires")); } [Fact] public void Expires_UseAddMethod_AddedValueCanBeRetrievedUsingProperty() { _headers.TryAddWithoutValidation("Expires", " Sun, 06 Nov 1994 08:49:37 GMT "); Assert.Equal(new DateTimeOffset(1994, 11, 6, 8, 49, 37, TimeSpan.Zero), _headers.Expires); _headers.Clear(); _headers.TryAddWithoutValidation("Expires", "Sun, 06 Nov 1994 08:49:37 GMT"); Assert.Equal(new DateTimeOffset(1994, 11, 6, 8, 49, 37, TimeSpan.Zero), _headers.Expires); } [Fact] public void Expires_UseAddMethodWithInvalidValue_InvalidValueRecognized() { _headers.TryAddWithoutValidation("Expires", " Sun, 06 Nov 1994 08:49:37 GMT ,"); Assert.Null(_headers.GetParsedValues("Expires")); Assert.Equal(1, _headers.GetValues("Expires").Count()); Assert.Equal(" Sun, 06 Nov 1994 08:49:37 GMT ,", _headers.GetValues("Expires").First()); _headers.Clear(); _headers.TryAddWithoutValidation("Expires", " Sun, 06 Nov "); Assert.Null(_headers.GetParsedValues("Expires")); Assert.Equal(1, _headers.GetValues("Expires").Count()); Assert.Equal(" Sun, 06 Nov ", _headers.GetValues("Expires").First()); } [Fact] public void LastModified_ReadAndWriteProperty_ValueMatchesPriorSetValue() { Assert.Null(_headers.LastModified); DateTimeOffset expected = DateTimeOffset.Now; _headers.LastModified = expected; Assert.Equal(expected, _headers.LastModified); _headers.LastModified = null; Assert.Null(_headers.LastModified); Assert.False(_headers.Contains("Last-Modified")); } [Fact] public void LastModified_UseAddMethod_AddedValueCanBeRetrievedUsingProperty() { _headers.TryAddWithoutValidation("Last-Modified", " Sun, 06 Nov 1994 08:49:37 GMT "); Assert.Equal(new DateTimeOffset(1994, 11, 6, 8, 49, 37, TimeSpan.Zero), _headers.LastModified); _headers.Clear(); _headers.TryAddWithoutValidation("Last-Modified", "Sun, 06 Nov 1994 08:49:37 GMT"); Assert.Equal(new DateTimeOffset(1994, 11, 6, 8, 49, 37, TimeSpan.Zero), _headers.LastModified); } [Fact] public void LastModified_UseAddMethodWithInvalidValue_InvalidValueRecognized() { _headers.TryAddWithoutValidation("Last-Modified", " Sun, 06 Nov 1994 08:49:37 GMT ,"); Assert.Null(_headers.GetParsedValues("Last-Modified")); Assert.Equal(1, _headers.GetValues("Last-Modified").Count()); Assert.Equal(" Sun, 06 Nov 1994 08:49:37 GMT ,", _headers.GetValues("Last-Modified").First()); _headers.Clear(); _headers.TryAddWithoutValidation("Last-Modified", " Sun, 06 Nov "); Assert.Null(_headers.GetParsedValues("Last-Modified")); Assert.Equal(1, _headers.GetValues("Last-Modified").Count()); Assert.Equal(" Sun, 06 Nov ", _headers.GetValues("Last-Modified").First()); } [Fact] public void InvalidHeaders_AddRequestAndResponseHeaders_Throw() { // Try adding request, response, and general _headers. Use different casing to make sure case-insensitive // comparison is used. Assert.Throws<InvalidOperationException>(() => { _headers.Add("Accept-Ranges", "v"); }); Assert.Throws<InvalidOperationException>(() => { _headers.Add("age", "v"); }); Assert.Throws<InvalidOperationException>(() => { _headers.Add("ETag", "v"); }); Assert.Throws<InvalidOperationException>(() => { _headers.Add("Location", "v"); }); Assert.Throws<InvalidOperationException>(() => { _headers.Add("Proxy-Authenticate", "v"); }); Assert.Throws<InvalidOperationException>(() => { _headers.Add("Retry-After", "v"); }); Assert.Throws<InvalidOperationException>(() => { _headers.Add("Server", "v"); }); Assert.Throws<InvalidOperationException>(() => { _headers.Add("Vary", "v"); }); Assert.Throws<InvalidOperationException>(() => { _headers.Add("WWW-Authenticate", "v"); }); Assert.Throws<InvalidOperationException>(() => { _headers.Add("Accept", "v"); }); Assert.Throws<InvalidOperationException>(() => { _headers.Add("Accept-Charset", "v"); }); Assert.Throws<InvalidOperationException>(() => { _headers.Add("Accept-Encoding", "v"); }); Assert.Throws<InvalidOperationException>(() => { _headers.Add("Accept-Language", "v"); }); Assert.Throws<InvalidOperationException>(() => { _headers.Add("Authorization", "v"); }); Assert.Throws<InvalidOperationException>(() => { _headers.Add("Expect", "v"); }); Assert.Throws<InvalidOperationException>(() => { _headers.Add("From", "v"); }); Assert.Throws<InvalidOperationException>(() => { _headers.Add("Host", "v"); }); Assert.Throws<InvalidOperationException>(() => { _headers.Add("If-Match", "v"); }); Assert.Throws<InvalidOperationException>(() => { _headers.Add("If-Modified-Since", "v"); }); Assert.Throws<InvalidOperationException>(() => { _headers.Add("If-None-Match", "v"); }); Assert.Throws<InvalidOperationException>(() => { _headers.Add("If-Range", "v"); }); Assert.Throws<InvalidOperationException>(() => { _headers.Add("If-Unmodified-Since", "v"); }); Assert.Throws<InvalidOperationException>(() => { _headers.Add("Max-Forwards", "v"); }); Assert.Throws<InvalidOperationException>(() => { _headers.Add("Proxy-Authorization", "v"); }); Assert.Throws<InvalidOperationException>(() => { _headers.Add("Range", "v"); }); Assert.Throws<InvalidOperationException>(() => { _headers.Add("Referer", "v"); }); Assert.Throws<InvalidOperationException>(() => { _headers.Add("TE", "v"); }); Assert.Throws<InvalidOperationException>(() => { _headers.Add("User-Agent", "v"); }); Assert.Throws<InvalidOperationException>(() => { _headers.Add("Cache-Control", "v"); }); Assert.Throws<InvalidOperationException>(() => { _headers.Add("Connection", "v"); }); Assert.Throws<InvalidOperationException>(() => { _headers.Add("Date", "v"); }); Assert.Throws<InvalidOperationException>(() => { _headers.Add("Pragma", "v"); }); Assert.Throws<InvalidOperationException>(() => { _headers.Add("Trailer", "v"); }); Assert.Throws<InvalidOperationException>(() => { _headers.Add("Transfer-Encoding", "v"); }); Assert.Throws<InvalidOperationException>(() => { _headers.Add("Upgrade", "v"); }); Assert.Throws<InvalidOperationException>(() => { _headers.Add("Via", "v"); }); Assert.Throws<InvalidOperationException>(() => { _headers.Add("Warning", "v"); }); } } }
/* * 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.Collections.Generic; using ParquetSharp.Bytes; using ParquetSharp.External; using ParquetSharp.Format; using ParquetSharp.Hadoop.Metadata; namespace ParquetSharp.Hadoop { public class CodecFactory { protected static readonly Dictionary<string, CompressionCodec> CODEC_BY_NAME = Collections .synchronizedMap(new Dictionary<string, CompressionCodec>()); private readonly Dictionary<CompressionCodecName, BytesCompressor> compressors = new Dictionary<CompressionCodecName, BytesCompressor>(); private readonly Dictionary<CompressionCodecName, BytesDecompressor> decompressors = new Dictionary<CompressionCodecName, BytesDecompressor>(); protected readonly Configuration configuration; protected readonly int pageSize; /** * Create a new codec factory. * * @param configuration used to pass compression codec configuration information * @param pageSize the expected page size, does not set a hard limit, currently just * used to set the initial size of the output stream used when * compressing a buffer. If this factory is only used to construct * decompressors this parameter has no impact on the function of the factory */ public CodecFactory(Configuration configuration, int pageSize) { this.configuration = configuration; this.pageSize = pageSize; } /** * Create a codec factory that will provide compressors and decompressors * that will work natively with ByteBuffers backed by direct memory. * * @param config configuration options for different compression codecs * @param allocator an allocator for creating result buffers during compression * and decompression, must provide buffers backed by Direct * memory and return true for the isDirect() method * on the ByteBufferAllocator interface * @param pageSize the default page size. This does not set a hard limit on the * size of buffers that can be compressed, but performance may * be improved by setting it close to the expected size of buffers * (in the case of parquet, pages) that will be compressed. This * setting is unused in the case of decompressing data, as parquet * always records the uncompressed size of a buffer. If this * CodecFactory is only going to be used for decompressors, this * parameter will not impact the function of the factory. */ public static CodecFactory createDirectCodecFactory(Configuration config, ByteBufferAllocator allocator, int pageSize) { return new DirectCodecFactory(config, allocator, pageSize); } internal class HeapBytesDecompressor : BytesDecompressor { private readonly CompressionCodec codec; private readonly Decompressor decompressor; internal HeapBytesDecompressor(CodecFactory factory, CompressionCodecName codecName) { this.codec = factory.getCodec(codecName); if (codec != null) { decompressor = CodecPool.getDecompressor(codec); } else { decompressor = null; } } public override BytesInput decompress(BytesInput bytes, int uncompressedSize) { BytesInput decompressed; if (codec != null) { decompressor.reset(); InputStream @is = codec.createInputStream(bytes.toInputStream(), decompressor); decompressed = BytesInput.from(@is, uncompressedSize); } else { decompressed = bytes; } return decompressed; } public override void decompress(ByteBuffer input, int compressedSize, ByteBuffer output, int uncompressedSize) { ByteBuffer decompressed = decompress(BytesInput.from(input, 0, input.remaining()), uncompressedSize).toByteBuffer(); output.put(decompressed); } internal protected override void release() { if (decompressor != null) { CodecPool.returnDecompressor(decompressor); } } } /** * Encapsulates the logic around hadoop compression * * @author Julien Le Dem * */ internal class HeapBytesCompressor : BytesCompressor { private readonly CompressionCodec codec; private readonly Compressor compressor; private readonly ByteArrayOutputStream compressedOutBuffer; private readonly CompressionCodecName codecName; internal HeapBytesCompressor(CodecFactory factory, CompressionCodecName codecName) { this.codecName = codecName; this.codec = factory.getCodec(codecName); if (codec != null) { this.compressor = CodecPool.getCompressor(codec); this.compressedOutBuffer = new ByteArrayOutputStream(factory.pageSize); } else { this.compressor = null; this.compressedOutBuffer = null; } } public override BytesInput compress(BytesInput bytes) { BytesInput compressedBytes; if (codec == null) { compressedBytes = bytes; } else { compressedOutBuffer.reset(); if (compressor != null) { // null compressor for non-native gzip compressor.reset(); } CompressionOutputStream cos = codec.createOutputStream(compressedOutBuffer, compressor); bytes.writeAllTo(cos); cos.finish(); cos.close(); compressedBytes = BytesInput.from(compressedOutBuffer); } return compressedBytes; } internal protected override void release() { if (compressor != null) { CodecPool.returnCompressor(compressor); } } public override CompressionCodecName getCodecName() { return codecName; } } public BytesCompressor getCompressor(CompressionCodecName codecName) { BytesCompressor comp; if (!compressors.TryGetValue(codecName, out comp)) { comp = createCompressor(codecName); compressors.Add(codecName, comp); } return comp; } public BytesDecompressor getDecompressor(CompressionCodecName codecName) { BytesDecompressor decomp; if (!decompressors.TryGetValue(codecName, out decomp)) { decomp = createDecompressor(codecName); decompressors.Add(codecName, decomp); } return decomp; } protected virtual BytesCompressor createCompressor(CompressionCodecName codecName) { return new HeapBytesCompressor(this, codecName); } protected virtual BytesDecompressor createDecompressor(CompressionCodecName codecName) { return new HeapBytesDecompressor(this, codecName); } /** * * @param codecName * the requested codec * @return the corresponding hadoop codec. null if UNCOMPRESSED */ protected CompressionCodec getCodec(CompressionCodecName codecName) { string codecClassName = codecName.getHadoopCompressionCodecClassName(); if (codecClassName == null) { return CompressionCodec.UNCOMPRESSED; } CompressionCodec codec; if (!CODEC_BY_NAME.TryGetValue(codecClassName, out codec)) { return codec; } try { System.Type codecClass = Class.forName(codecClassName); codec = (CompressionCodec)ReflectionUtils.newInstance(codecClass, configuration); CODEC_BY_NAME[codecClassName] = codec; return codec; } catch (ClassNotFoundException e) { throw new BadConfigurationException("Class " + codecClassName + " was not found", e); } } public void release() { foreach (BytesCompressor compressor in compressors.Values) { compressor.release(); } compressors.Clear(); foreach (BytesDecompressor decompressor in decompressors.Values) { decompressor.release(); } decompressors.Clear(); } public abstract class BytesCompressor { public abstract BytesInput compress(BytesInput bytes); public abstract CompressionCodecName getCodecName(); internal protected abstract void release(); } public abstract class BytesDecompressor { public abstract BytesInput decompress(BytesInput bytes, int uncompressedSize); public abstract void decompress(ByteBuffer input, int compressedSize, ByteBuffer output, int uncompressedSize); internal protected abstract void release(); } } }
//--------------------------------------------------------------------- // Author: Keith Hill // // Description: Class to implement the Send-SmtpMail cmdlet. // // Creation Date: Nov 1, 2006 //--------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Globalization; using System.IO; using System.Management.Automation; using System.Management.Automation.Runspaces; using System.Net; using System.Net.Mail; using System.Text; using Pscx.IO; namespace Pscx.Commands.Net { [OutputType(typeof(MailMessage))] [Cmdlet(VerbsCommunications.Send, PscxNouns.SmtpMail, DefaultParameterSetName = "Authenticated", SupportsShouldProcess = true)] [Obsolete(@"The PSCX\Send-SmtpMail cmdlet is obsolete and will be removed in the next version of PSCX. Use the built-in Microsoft.PowerShell.Utility\Send-MailMessage cmdlet instead.")] public class SendSmtpMailCommand : PscxCmdlet { private const string SmtpHostPref = "SmtpHost"; private const string SmtpPortPref = "SmtpPort"; private const string SmtpFromPref = "SmtpFrom"; private const int DefaultSmtpPort = 25; private PSObject _inputObject; List<PSObject> _objects; private PSCredential _credentials; private StringBuilder _bodyStrBld; private SmtpClient _smtpClient; private string _host; private string _subject; private string _body; private string _from; private string _replyTo; private string[] _to; private string[] _cc = new string[0]; private string[] _bcc = new string[0]; private PscxPathInfo[] _attachmentPaths = new PscxPathInfo[0]; private List<string> _inputPath; private int _timeout = 100 * 1000; private int? _portNumber; private SwitchParameter _isBodyHtml; private SwitchParameter _anonymous; private SwitchParameter _passThru; private MailPriority _priority = MailPriority.Normal; private int? _width; #region Parameters [Parameter(ValueFromPipeline = true)] [AllowNull] [AllowEmptyString] public PSObject InputObject { get { return _inputObject; } set { _inputObject = value; } } [Parameter] [ValidateNotNullOrEmpty] [PreferenceVariable(SmtpHostPref)] public string SmtpHost { get { return _host; } set { _host = value; } } [Parameter] [PreferenceVariable(SmtpPortPref, DefaultSmtpPort)] public int? PortNumber { get { return _portNumber; } set { _portNumber = value; } } [Parameter(ParameterSetName = "Authenticated")] [Credential] [ValidateNotNull] public PSCredential Credential { get { return _credentials; } set { _credentials = value; } } [Parameter(ParameterSetName = "Anonymous")] public SwitchParameter Anonymous { get { return _anonymous; } set { _anonymous = value; } } [Parameter] public SwitchParameter PassThru { get { return _passThru; } set { _passThru = value; } } [Parameter] [ValidateNotNullOrEmpty] [PreferenceVariable(SmtpFromPref)] public string From { get { return _from; } set { _from = value; } } [Parameter] [ValidateNotNullOrEmpty] public string ReplyTo { get { return _replyTo; } set { _replyTo = value; } } [Parameter(Mandatory = true)] [ValidateNotNullOrEmpty] public string[] To { get { return _to; } set { _to = value; } } [Parameter] [ValidateNotNull] public string[] Cc { get { return _cc; } set { _cc = value; } } [Parameter] [ValidateNotNull] public string[] Bcc { get { return _bcc; } set { _bcc = value; } } [Parameter] public string Subject { get { return _subject; } set { _subject = value; } } [Parameter] public string Body { get { return _body; } set { _body = value; } } [Parameter, PscxPath] [ValidateNotNull] public PscxPathInfo[] AttachmentPath { get { return _attachmentPaths; } set { _attachmentPaths = value; } } [Parameter, PscxPath(NoGlobbing = true)] [ValidateNotNull] public PscxPathInfo[] AttachmentLiteralPath { get { return _attachmentPaths; } set { _attachmentPaths = value; } } [Parameter()] [ValidateRange(0, Int32.MaxValue)] public int Timeout { get { return _timeout; } set { _timeout = value; } } [Parameter()] public SwitchParameter HtmlBody { get { return _isBodyHtml; } set { _isBodyHtml = value; } } [Parameter()] public MailPriority Priority { get { return _priority; } set { _priority = value; } } [ValidateRange(2, Int32.MaxValue)] [Parameter()] public int? Width { get { return _width; } set { _width = value; } } #endregion protected override void BeginProcessing() { base.BeginProcessing(); WriteWarning(Properties.Resources.SmtpMailDeprecationWarning); _bodyStrBld = new StringBuilder(); _inputPath = new List<string>(); _objects = new List<PSObject>(); //_resolvedPaths = GetResolvedPaths(_attachmentPaths, _literalPathUsed); _smtpClient = new SmtpClient(_host); _smtpClient.Timeout = _timeout; _smtpClient.Port = _portNumber.Value; if (_anonymous) { _smtpClient.Credentials = null; _smtpClient.UseDefaultCredentials = false; } else if (_credentials != null) { _smtpClient.Credentials = _credentials.GetNetworkCredential(); } else { _smtpClient.Credentials = CredentialCache.DefaultNetworkCredentials; } } protected override void ProcessRecord() { if ((_inputObject == null) || (_inputObject.BaseObject == null)) return; object input = _inputObject.BaseObject; if (input is FileInfo) { FileInfo fileInfo = (FileInfo)input; _inputPath.Add(fileInfo.FullName); } else if (input is string) { string line = ((string)input).TrimEnd(null); _bodyStrBld.AppendLine(line); } else { // Save any other objects for formatting into text during EndProcessing _objects.Add(_inputObject); } } protected override void EndProcessing() { MailMessage message = null; try { message = new MailMessage(); message.From = new MailAddress(_from); message.IsBodyHtml = _isBodyHtml; message.Priority = _priority; if (!String.IsNullOrEmpty(_replyTo)) { message.ReplyToList.Add(new MailAddress(_replyTo)); } if (!String.IsNullOrEmpty(_subject)) { message.Subject = _subject; } if (!String.IsNullOrEmpty(_body)) { message.Body = _body; } if (_bodyStrBld.Length > 0) { message.Body += _bodyStrBld.ToString().TrimEnd(null); } if (_objects.Count > 0) { message.Body += RenderInputObjectsToText(); } foreach (string recipient in _to) { message.To.Add(recipient); } foreach (string recipient in _cc) { message.CC.Add(recipient); } foreach (string recipient in _bcc) { message.Bcc.Add(recipient); } foreach (PscxPathInfo attachmentPath in _attachmentPaths) { message.Attachments.Add(new Attachment(attachmentPath.ProviderPath)); } foreach (string attachment in _inputPath) { message.Attachments.Add(new Attachment(attachment)); } SendMessage(message); } finally { if (message != null) { message.Dispose(); } _bodyStrBld = null; _objects = null; _inputPath = null; } } private void SendMessage(MailMessage message) { try { if (ShouldProcess(message.ToString())) { _smtpClient.Send(message); WriteVerbose(Properties.Resources.SmtpMailSent); if (_passThru) { WriteObject(message); } } } catch (InvalidOperationException ex) { this.ErrorHandler.WriteInvalidOperationError(_smtpClient, ex); } catch (SmtpException ex) { this.ErrorHandler.WriteSmtpSendMessageError(_smtpClient, ex); } } private string RenderInputObjectsToText() { StringBuilder formattedOutput = new StringBuilder(); // Format any other object type using out-string string cmd = String.Empty; if (_width.HasValue) { cmd = String.Format(CultureInfo.InvariantCulture, "$input | out-string -width {0}", _width.Value); } else { cmd = "$input | out-string"; } Collection<PSObject> results = InvokeCommand.InvokeScript(cmd, false, PipelineResultTypes.None, _objects); foreach (PSObject obj in results) { string text = obj.ToString(); string[] lines = text.Split(new string[] { Environment.NewLine }, StringSplitOptions.None); foreach (string line in lines) { formattedOutput.AppendLine(line.TrimEnd(null)); } } return formattedOutput.ToString().TrimEnd(null); } } }
#if !DISABLE_PLAYFABENTITY_API && !DISABLE_PLAYFAB_STATIC_API using PlayFab.EconomyModels; using PlayFab.Internal; #pragma warning disable 0649 using System; // This is required for the Obsolete Attribute flag // which is not always present in all API's #pragma warning restore 0649 using System.Collections.Generic; using System.Threading.Tasks; namespace PlayFab { /// <summary> /// API methods for managing the catalog. Inventory manages in-game assets for any given entity. /// </summary> public static class PlayFabEconomyAPI { /// <summary> /// Verify entity login. /// </summary> public static bool IsEntityLoggedIn() { return PlayFabSettings.staticPlayer.IsEntityLoggedIn(); } /// <summary> /// Clear the Client SessionToken which allows this Client to call API calls requiring login. /// A new/fresh login will be required after calling this. /// </summary> public static void ForgetAllCredentials() { PlayFabSettings.staticPlayer.ForgetAllCredentials(); } /// <summary> /// Creates a new item in the working catalog using provided metadata. /// </summary> public static async Task<PlayFabResult<CreateDraftItemResponse>> CreateDraftItemAsync(CreateDraftItemRequest request, object customData = null, Dictionary<string, string> extraHeaders = null) { await new PlayFabUtil.SynchronizationContextRemover(); var requestContext = request?.AuthenticationContext ?? PlayFabSettings.staticPlayer; var requestSettings = PlayFabSettings.staticSettings; if (requestContext.EntityToken == null) throw new PlayFabException(PlayFabExceptionCode.EntityTokenNotSet, "Must call Client Login or GetEntityToken before calling this method"); var httpResult = await PlayFabHttp.DoPost("/Catalog/CreateDraftItem", request, "X-EntityToken", requestContext.EntityToken, extraHeaders); if (httpResult is PlayFabError) { var error = (PlayFabError)httpResult; PlayFabSettings.GlobalErrorHandler?.Invoke(error); return new PlayFabResult<CreateDraftItemResponse> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = PluginManager.GetPlugin<ISerializerPlugin>(PluginContract.PlayFab_Serializer).DeserializeObject<PlayFabJsonSuccess<CreateDraftItemResponse>>(resultRawJson); var result = resultData.data; return new PlayFabResult<CreateDraftItemResponse> { Result = result, CustomData = customData }; } /// <summary> /// Creates one or more upload URLs which can be used by the client to upload raw file data. /// </summary> public static async Task<PlayFabResult<CreateUploadUrlsResponse>> CreateUploadUrlsAsync(CreateUploadUrlsRequest request, object customData = null, Dictionary<string, string> extraHeaders = null) { await new PlayFabUtil.SynchronizationContextRemover(); var requestContext = request?.AuthenticationContext ?? PlayFabSettings.staticPlayer; var requestSettings = PlayFabSettings.staticSettings; if (requestContext.EntityToken == null) throw new PlayFabException(PlayFabExceptionCode.EntityTokenNotSet, "Must call Client Login or GetEntityToken before calling this method"); var httpResult = await PlayFabHttp.DoPost("/Catalog/CreateUploadUrls", request, "X-EntityToken", requestContext.EntityToken, extraHeaders); if (httpResult is PlayFabError) { var error = (PlayFabError)httpResult; PlayFabSettings.GlobalErrorHandler?.Invoke(error); return new PlayFabResult<CreateUploadUrlsResponse> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = PluginManager.GetPlugin<ISerializerPlugin>(PluginContract.PlayFab_Serializer).DeserializeObject<PlayFabJsonSuccess<CreateUploadUrlsResponse>>(resultRawJson); var result = resultData.data; return new PlayFabResult<CreateUploadUrlsResponse> { Result = result, CustomData = customData }; } /// <summary> /// Deletes all reviews, helpfulness votes, and ratings submitted by the entity specified. /// </summary> public static async Task<PlayFabResult<DeleteEntityItemReviewsResponse>> DeleteEntityItemReviewsAsync(DeleteEntityItemReviewsRequest request, object customData = null, Dictionary<string, string> extraHeaders = null) { await new PlayFabUtil.SynchronizationContextRemover(); var requestContext = request?.AuthenticationContext ?? PlayFabSettings.staticPlayer; var requestSettings = PlayFabSettings.staticSettings; if (requestContext.EntityToken == null) throw new PlayFabException(PlayFabExceptionCode.EntityTokenNotSet, "Must call Client Login or GetEntityToken before calling this method"); var httpResult = await PlayFabHttp.DoPost("/Catalog/DeleteEntityItemReviews", request, "X-EntityToken", requestContext.EntityToken, extraHeaders); if (httpResult is PlayFabError) { var error = (PlayFabError)httpResult; PlayFabSettings.GlobalErrorHandler?.Invoke(error); return new PlayFabResult<DeleteEntityItemReviewsResponse> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = PluginManager.GetPlugin<ISerializerPlugin>(PluginContract.PlayFab_Serializer).DeserializeObject<PlayFabJsonSuccess<DeleteEntityItemReviewsResponse>>(resultRawJson); var result = resultData.data; return new PlayFabResult<DeleteEntityItemReviewsResponse> { Result = result, CustomData = customData }; } /// <summary> /// Removes an item from working catalog and all published versions from the public catalog. /// </summary> public static async Task<PlayFabResult<DeleteItemResponse>> DeleteItemAsync(DeleteItemRequest request, object customData = null, Dictionary<string, string> extraHeaders = null) { await new PlayFabUtil.SynchronizationContextRemover(); var requestContext = request?.AuthenticationContext ?? PlayFabSettings.staticPlayer; var requestSettings = PlayFabSettings.staticSettings; if (requestContext.EntityToken == null) throw new PlayFabException(PlayFabExceptionCode.EntityTokenNotSet, "Must call Client Login or GetEntityToken before calling this method"); var httpResult = await PlayFabHttp.DoPost("/Catalog/DeleteItem", request, "X-EntityToken", requestContext.EntityToken, extraHeaders); if (httpResult is PlayFabError) { var error = (PlayFabError)httpResult; PlayFabSettings.GlobalErrorHandler?.Invoke(error); return new PlayFabResult<DeleteItemResponse> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = PluginManager.GetPlugin<ISerializerPlugin>(PluginContract.PlayFab_Serializer).DeserializeObject<PlayFabJsonSuccess<DeleteItemResponse>>(resultRawJson); var result = resultData.data; return new PlayFabResult<DeleteItemResponse> { Result = result, CustomData = customData }; } /// <summary> /// Gets the configuration for the catalog. /// </summary> public static async Task<PlayFabResult<GetCatalogConfigResponse>> GetCatalogConfigAsync(GetCatalogConfigRequest request, object customData = null, Dictionary<string, string> extraHeaders = null) { await new PlayFabUtil.SynchronizationContextRemover(); var requestContext = request?.AuthenticationContext ?? PlayFabSettings.staticPlayer; var requestSettings = PlayFabSettings.staticSettings; if (requestContext.EntityToken == null) throw new PlayFabException(PlayFabExceptionCode.EntityTokenNotSet, "Must call Client Login or GetEntityToken before calling this method"); var httpResult = await PlayFabHttp.DoPost("/Catalog/GetCatalogConfig", request, "X-EntityToken", requestContext.EntityToken, extraHeaders); if (httpResult is PlayFabError) { var error = (PlayFabError)httpResult; PlayFabSettings.GlobalErrorHandler?.Invoke(error); return new PlayFabResult<GetCatalogConfigResponse> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = PluginManager.GetPlugin<ISerializerPlugin>(PluginContract.PlayFab_Serializer).DeserializeObject<PlayFabJsonSuccess<GetCatalogConfigResponse>>(resultRawJson); var result = resultData.data; return new PlayFabResult<GetCatalogConfigResponse> { Result = result, CustomData = customData }; } /// <summary> /// Retrieves an item from the working catalog. This item represents the current working state of the item. /// </summary> public static async Task<PlayFabResult<GetDraftItemResponse>> GetDraftItemAsync(GetDraftItemRequest request, object customData = null, Dictionary<string, string> extraHeaders = null) { await new PlayFabUtil.SynchronizationContextRemover(); var requestContext = request?.AuthenticationContext ?? PlayFabSettings.staticPlayer; var requestSettings = PlayFabSettings.staticSettings; if (requestContext.EntityToken == null) throw new PlayFabException(PlayFabExceptionCode.EntityTokenNotSet, "Must call Client Login or GetEntityToken before calling this method"); var httpResult = await PlayFabHttp.DoPost("/Catalog/GetDraftItem", request, "X-EntityToken", requestContext.EntityToken, extraHeaders); if (httpResult is PlayFabError) { var error = (PlayFabError)httpResult; PlayFabSettings.GlobalErrorHandler?.Invoke(error); return new PlayFabResult<GetDraftItemResponse> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = PluginManager.GetPlugin<ISerializerPlugin>(PluginContract.PlayFab_Serializer).DeserializeObject<PlayFabJsonSuccess<GetDraftItemResponse>>(resultRawJson); var result = resultData.data; return new PlayFabResult<GetDraftItemResponse> { Result = result, CustomData = customData }; } /// <summary> /// Retrieves a paginated list of the items from the draft catalog. /// </summary> public static async Task<PlayFabResult<GetDraftItemsResponse>> GetDraftItemsAsync(GetDraftItemsRequest request, object customData = null, Dictionary<string, string> extraHeaders = null) { await new PlayFabUtil.SynchronizationContextRemover(); var requestContext = request?.AuthenticationContext ?? PlayFabSettings.staticPlayer; var requestSettings = PlayFabSettings.staticSettings; if (requestContext.EntityToken == null) throw new PlayFabException(PlayFabExceptionCode.EntityTokenNotSet, "Must call Client Login or GetEntityToken before calling this method"); var httpResult = await PlayFabHttp.DoPost("/Catalog/GetDraftItems", request, "X-EntityToken", requestContext.EntityToken, extraHeaders); if (httpResult is PlayFabError) { var error = (PlayFabError)httpResult; PlayFabSettings.GlobalErrorHandler?.Invoke(error); return new PlayFabResult<GetDraftItemsResponse> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = PluginManager.GetPlugin<ISerializerPlugin>(PluginContract.PlayFab_Serializer).DeserializeObject<PlayFabJsonSuccess<GetDraftItemsResponse>>(resultRawJson); var result = resultData.data; return new PlayFabResult<GetDraftItemsResponse> { Result = result, CustomData = customData }; } /// <summary> /// Retrieves a paginated list of the items from the draft catalog created by the Entity. /// </summary> public static async Task<PlayFabResult<GetEntityDraftItemsResponse>> GetEntityDraftItemsAsync(GetEntityDraftItemsRequest request, object customData = null, Dictionary<string, string> extraHeaders = null) { await new PlayFabUtil.SynchronizationContextRemover(); var requestContext = request?.AuthenticationContext ?? PlayFabSettings.staticPlayer; var requestSettings = PlayFabSettings.staticSettings; if (requestContext.EntityToken == null) throw new PlayFabException(PlayFabExceptionCode.EntityTokenNotSet, "Must call Client Login or GetEntityToken before calling this method"); var httpResult = await PlayFabHttp.DoPost("/Catalog/GetEntityDraftItems", request, "X-EntityToken", requestContext.EntityToken, extraHeaders); if (httpResult is PlayFabError) { var error = (PlayFabError)httpResult; PlayFabSettings.GlobalErrorHandler?.Invoke(error); return new PlayFabResult<GetEntityDraftItemsResponse> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = PluginManager.GetPlugin<ISerializerPlugin>(PluginContract.PlayFab_Serializer).DeserializeObject<PlayFabJsonSuccess<GetEntityDraftItemsResponse>>(resultRawJson); var result = resultData.data; return new PlayFabResult<GetEntityDraftItemsResponse> { Result = result, CustomData = customData }; } /// <summary> /// Gets the submitted review for the specified item by the authenticated entity. /// </summary> public static async Task<PlayFabResult<GetEntityItemReviewResponse>> GetEntityItemReviewAsync(GetEntityItemReviewRequest request, object customData = null, Dictionary<string, string> extraHeaders = null) { await new PlayFabUtil.SynchronizationContextRemover(); var requestContext = request?.AuthenticationContext ?? PlayFabSettings.staticPlayer; var requestSettings = PlayFabSettings.staticSettings; if (requestContext.EntityToken == null) throw new PlayFabException(PlayFabExceptionCode.EntityTokenNotSet, "Must call Client Login or GetEntityToken before calling this method"); var httpResult = await PlayFabHttp.DoPost("/Catalog/GetEntityItemReview", request, "X-EntityToken", requestContext.EntityToken, extraHeaders); if (httpResult is PlayFabError) { var error = (PlayFabError)httpResult; PlayFabSettings.GlobalErrorHandler?.Invoke(error); return new PlayFabResult<GetEntityItemReviewResponse> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = PluginManager.GetPlugin<ISerializerPlugin>(PluginContract.PlayFab_Serializer).DeserializeObject<PlayFabJsonSuccess<GetEntityItemReviewResponse>>(resultRawJson); var result = resultData.data; return new PlayFabResult<GetEntityItemReviewResponse> { Result = result, CustomData = customData }; } /// <summary> /// Retrieves an item from the public catalog. /// </summary> public static async Task<PlayFabResult<GetItemResponse>> GetItemAsync(GetItemRequest request, object customData = null, Dictionary<string, string> extraHeaders = null) { await new PlayFabUtil.SynchronizationContextRemover(); var requestContext = request?.AuthenticationContext ?? PlayFabSettings.staticPlayer; var requestSettings = PlayFabSettings.staticSettings; if (requestContext.EntityToken == null) throw new PlayFabException(PlayFabExceptionCode.EntityTokenNotSet, "Must call Client Login or GetEntityToken before calling this method"); var httpResult = await PlayFabHttp.DoPost("/Catalog/GetItem", request, "X-EntityToken", requestContext.EntityToken, extraHeaders); if (httpResult is PlayFabError) { var error = (PlayFabError)httpResult; PlayFabSettings.GlobalErrorHandler?.Invoke(error); return new PlayFabResult<GetItemResponse> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = PluginManager.GetPlugin<ISerializerPlugin>(PluginContract.PlayFab_Serializer).DeserializeObject<PlayFabJsonSuccess<GetItemResponse>>(resultRawJson); var result = resultData.data; return new PlayFabResult<GetItemResponse> { Result = result, CustomData = customData }; } /// <summary> /// Gets the moderation state for an item, including the concern category and string reason. /// </summary> public static async Task<PlayFabResult<GetItemModerationStateResponse>> GetItemModerationStateAsync(GetItemModerationStateRequest request, object customData = null, Dictionary<string, string> extraHeaders = null) { await new PlayFabUtil.SynchronizationContextRemover(); var requestContext = request?.AuthenticationContext ?? PlayFabSettings.staticPlayer; var requestSettings = PlayFabSettings.staticSettings; if (requestContext.EntityToken == null) throw new PlayFabException(PlayFabExceptionCode.EntityTokenNotSet, "Must call Client Login or GetEntityToken before calling this method"); var httpResult = await PlayFabHttp.DoPost("/Catalog/GetItemModerationState", request, "X-EntityToken", requestContext.EntityToken, extraHeaders); if (httpResult is PlayFabError) { var error = (PlayFabError)httpResult; PlayFabSettings.GlobalErrorHandler?.Invoke(error); return new PlayFabResult<GetItemModerationStateResponse> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = PluginManager.GetPlugin<ISerializerPlugin>(PluginContract.PlayFab_Serializer).DeserializeObject<PlayFabJsonSuccess<GetItemModerationStateResponse>>(resultRawJson); var result = resultData.data; return new PlayFabResult<GetItemModerationStateResponse> { Result = result, CustomData = customData }; } /// <summary> /// Gets the status of a publish of an item. /// </summary> public static async Task<PlayFabResult<GetItemPublishStatusResponse>> GetItemPublishStatusAsync(GetItemPublishStatusRequest request, object customData = null, Dictionary<string, string> extraHeaders = null) { await new PlayFabUtil.SynchronizationContextRemover(); var requestContext = request?.AuthenticationContext ?? PlayFabSettings.staticPlayer; var requestSettings = PlayFabSettings.staticSettings; if (requestContext.EntityToken == null) throw new PlayFabException(PlayFabExceptionCode.EntityTokenNotSet, "Must call Client Login or GetEntityToken before calling this method"); var httpResult = await PlayFabHttp.DoPost("/Catalog/GetItemPublishStatus", request, "X-EntityToken", requestContext.EntityToken, extraHeaders); if (httpResult is PlayFabError) { var error = (PlayFabError)httpResult; PlayFabSettings.GlobalErrorHandler?.Invoke(error); return new PlayFabResult<GetItemPublishStatusResponse> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = PluginManager.GetPlugin<ISerializerPlugin>(PluginContract.PlayFab_Serializer).DeserializeObject<PlayFabJsonSuccess<GetItemPublishStatusResponse>>(resultRawJson); var result = resultData.data; return new PlayFabResult<GetItemPublishStatusResponse> { Result = result, CustomData = customData }; } /// <summary> /// Get a paginated set of reviews associated with the specified item. /// </summary> public static async Task<PlayFabResult<GetItemReviewsResponse>> GetItemReviewsAsync(GetItemReviewsRequest request, object customData = null, Dictionary<string, string> extraHeaders = null) { await new PlayFabUtil.SynchronizationContextRemover(); var requestContext = request?.AuthenticationContext ?? PlayFabSettings.staticPlayer; var requestSettings = PlayFabSettings.staticSettings; if (requestContext.EntityToken == null) throw new PlayFabException(PlayFabExceptionCode.EntityTokenNotSet, "Must call Client Login or GetEntityToken before calling this method"); var httpResult = await PlayFabHttp.DoPost("/Catalog/GetItemReviews", request, "X-EntityToken", requestContext.EntityToken, extraHeaders); if (httpResult is PlayFabError) { var error = (PlayFabError)httpResult; PlayFabSettings.GlobalErrorHandler?.Invoke(error); return new PlayFabResult<GetItemReviewsResponse> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = PluginManager.GetPlugin<ISerializerPlugin>(PluginContract.PlayFab_Serializer).DeserializeObject<PlayFabJsonSuccess<GetItemReviewsResponse>>(resultRawJson); var result = resultData.data; return new PlayFabResult<GetItemReviewsResponse> { Result = result, CustomData = customData }; } /// <summary> /// Get a summary of all reviews associated with the specified item. /// </summary> public static async Task<PlayFabResult<GetItemReviewSummaryResponse>> GetItemReviewSummaryAsync(GetItemReviewSummaryRequest request, object customData = null, Dictionary<string, string> extraHeaders = null) { await new PlayFabUtil.SynchronizationContextRemover(); var requestContext = request?.AuthenticationContext ?? PlayFabSettings.staticPlayer; var requestSettings = PlayFabSettings.staticSettings; if (requestContext.EntityToken == null) throw new PlayFabException(PlayFabExceptionCode.EntityTokenNotSet, "Must call Client Login or GetEntityToken before calling this method"); var httpResult = await PlayFabHttp.DoPost("/Catalog/GetItemReviewSummary", request, "X-EntityToken", requestContext.EntityToken, extraHeaders); if (httpResult is PlayFabError) { var error = (PlayFabError)httpResult; PlayFabSettings.GlobalErrorHandler?.Invoke(error); return new PlayFabResult<GetItemReviewSummaryResponse> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = PluginManager.GetPlugin<ISerializerPlugin>(PluginContract.PlayFab_Serializer).DeserializeObject<PlayFabJsonSuccess<GetItemReviewSummaryResponse>>(resultRawJson); var result = resultData.data; return new PlayFabResult<GetItemReviewSummaryResponse> { Result = result, CustomData = customData }; } /// <summary> /// Retrieves items from the public catalog. /// </summary> public static async Task<PlayFabResult<GetItemsResponse>> GetItemsAsync(GetItemsRequest request, object customData = null, Dictionary<string, string> extraHeaders = null) { await new PlayFabUtil.SynchronizationContextRemover(); var requestContext = request?.AuthenticationContext ?? PlayFabSettings.staticPlayer; var requestSettings = PlayFabSettings.staticSettings; if (requestContext.EntityToken == null) throw new PlayFabException(PlayFabExceptionCode.EntityTokenNotSet, "Must call Client Login or GetEntityToken before calling this method"); var httpResult = await PlayFabHttp.DoPost("/Catalog/GetItems", request, "X-EntityToken", requestContext.EntityToken, extraHeaders); if (httpResult is PlayFabError) { var error = (PlayFabError)httpResult; PlayFabSettings.GlobalErrorHandler?.Invoke(error); return new PlayFabResult<GetItemsResponse> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = PluginManager.GetPlugin<ISerializerPlugin>(PluginContract.PlayFab_Serializer).DeserializeObject<PlayFabJsonSuccess<GetItemsResponse>>(resultRawJson); var result = resultData.data; return new PlayFabResult<GetItemsResponse> { Result = result, CustomData = customData }; } /// <summary> /// Initiates a publish of an item from the working catalog to the public catalog. /// </summary> public static async Task<PlayFabResult<PublishDraftItemResponse>> PublishDraftItemAsync(PublishDraftItemRequest request, object customData = null, Dictionary<string, string> extraHeaders = null) { await new PlayFabUtil.SynchronizationContextRemover(); var requestContext = request?.AuthenticationContext ?? PlayFabSettings.staticPlayer; var requestSettings = PlayFabSettings.staticSettings; if (requestContext.EntityToken == null) throw new PlayFabException(PlayFabExceptionCode.EntityTokenNotSet, "Must call Client Login or GetEntityToken before calling this method"); var httpResult = await PlayFabHttp.DoPost("/Catalog/PublishDraftItem", request, "X-EntityToken", requestContext.EntityToken, extraHeaders); if (httpResult is PlayFabError) { var error = (PlayFabError)httpResult; PlayFabSettings.GlobalErrorHandler?.Invoke(error); return new PlayFabResult<PublishDraftItemResponse> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = PluginManager.GetPlugin<ISerializerPlugin>(PluginContract.PlayFab_Serializer).DeserializeObject<PlayFabJsonSuccess<PublishDraftItemResponse>>(resultRawJson); var result = resultData.data; return new PlayFabResult<PublishDraftItemResponse> { Result = result, CustomData = customData }; } /// <summary> /// Submit a report for an item, indicating in what way the item is inappropriate. /// </summary> public static async Task<PlayFabResult<ReportItemResponse>> ReportItemAsync(ReportItemRequest request, object customData = null, Dictionary<string, string> extraHeaders = null) { await new PlayFabUtil.SynchronizationContextRemover(); var requestContext = request?.AuthenticationContext ?? PlayFabSettings.staticPlayer; var requestSettings = PlayFabSettings.staticSettings; if (requestContext.EntityToken == null) throw new PlayFabException(PlayFabExceptionCode.EntityTokenNotSet, "Must call Client Login or GetEntityToken before calling this method"); var httpResult = await PlayFabHttp.DoPost("/Catalog/ReportItem", request, "X-EntityToken", requestContext.EntityToken, extraHeaders); if (httpResult is PlayFabError) { var error = (PlayFabError)httpResult; PlayFabSettings.GlobalErrorHandler?.Invoke(error); return new PlayFabResult<ReportItemResponse> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = PluginManager.GetPlugin<ISerializerPlugin>(PluginContract.PlayFab_Serializer).DeserializeObject<PlayFabJsonSuccess<ReportItemResponse>>(resultRawJson); var result = resultData.data; return new PlayFabResult<ReportItemResponse> { Result = result, CustomData = customData }; } /// <summary> /// Submit a report for a review /// </summary> public static async Task<PlayFabResult<ReportItemReviewResponse>> ReportItemReviewAsync(ReportItemReviewRequest request, object customData = null, Dictionary<string, string> extraHeaders = null) { await new PlayFabUtil.SynchronizationContextRemover(); var requestContext = request?.AuthenticationContext ?? PlayFabSettings.staticPlayer; var requestSettings = PlayFabSettings.staticSettings; if (requestContext.EntityToken == null) throw new PlayFabException(PlayFabExceptionCode.EntityTokenNotSet, "Must call Client Login or GetEntityToken before calling this method"); var httpResult = await PlayFabHttp.DoPost("/Catalog/ReportItemReview", request, "X-EntityToken", requestContext.EntityToken, extraHeaders); if (httpResult is PlayFabError) { var error = (PlayFabError)httpResult; PlayFabSettings.GlobalErrorHandler?.Invoke(error); return new PlayFabResult<ReportItemReviewResponse> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = PluginManager.GetPlugin<ISerializerPlugin>(PluginContract.PlayFab_Serializer).DeserializeObject<PlayFabJsonSuccess<ReportItemReviewResponse>>(resultRawJson); var result = resultData.data; return new PlayFabResult<ReportItemReviewResponse> { Result = result, CustomData = customData }; } /// <summary> /// Creates or updates a review for the specified item. /// </summary> public static async Task<PlayFabResult<ReviewItemResponse>> ReviewItemAsync(ReviewItemRequest request, object customData = null, Dictionary<string, string> extraHeaders = null) { await new PlayFabUtil.SynchronizationContextRemover(); var requestContext = request?.AuthenticationContext ?? PlayFabSettings.staticPlayer; var requestSettings = PlayFabSettings.staticSettings; if (requestContext.EntityToken == null) throw new PlayFabException(PlayFabExceptionCode.EntityTokenNotSet, "Must call Client Login or GetEntityToken before calling this method"); var httpResult = await PlayFabHttp.DoPost("/Catalog/ReviewItem", request, "X-EntityToken", requestContext.EntityToken, extraHeaders); if (httpResult is PlayFabError) { var error = (PlayFabError)httpResult; PlayFabSettings.GlobalErrorHandler?.Invoke(error); return new PlayFabResult<ReviewItemResponse> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = PluginManager.GetPlugin<ISerializerPlugin>(PluginContract.PlayFab_Serializer).DeserializeObject<PlayFabJsonSuccess<ReviewItemResponse>>(resultRawJson); var result = resultData.data; return new PlayFabResult<ReviewItemResponse> { Result = result, CustomData = customData }; } /// <summary> /// Executes a search against the public catalog using the provided search parameters and returns a set of paginated /// results. /// </summary> public static async Task<PlayFabResult<SearchItemsResponse>> SearchItemsAsync(SearchItemsRequest request, object customData = null, Dictionary<string, string> extraHeaders = null) { await new PlayFabUtil.SynchronizationContextRemover(); var requestContext = request?.AuthenticationContext ?? PlayFabSettings.staticPlayer; var requestSettings = PlayFabSettings.staticSettings; if (requestContext.EntityToken == null) throw new PlayFabException(PlayFabExceptionCode.EntityTokenNotSet, "Must call Client Login or GetEntityToken before calling this method"); var httpResult = await PlayFabHttp.DoPost("/Catalog/SearchItems", request, "X-EntityToken", requestContext.EntityToken, extraHeaders); if (httpResult is PlayFabError) { var error = (PlayFabError)httpResult; PlayFabSettings.GlobalErrorHandler?.Invoke(error); return new PlayFabResult<SearchItemsResponse> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = PluginManager.GetPlugin<ISerializerPlugin>(PluginContract.PlayFab_Serializer).DeserializeObject<PlayFabJsonSuccess<SearchItemsResponse>>(resultRawJson); var result = resultData.data; return new PlayFabResult<SearchItemsResponse> { Result = result, CustomData = customData }; } /// <summary> /// Sets the moderation state for an item, including the concern category and string reason. /// </summary> public static async Task<PlayFabResult<SetItemModerationStateResponse>> SetItemModerationStateAsync(SetItemModerationStateRequest request, object customData = null, Dictionary<string, string> extraHeaders = null) { await new PlayFabUtil.SynchronizationContextRemover(); var requestContext = request?.AuthenticationContext ?? PlayFabSettings.staticPlayer; var requestSettings = PlayFabSettings.staticSettings; if (requestContext.EntityToken == null) throw new PlayFabException(PlayFabExceptionCode.EntityTokenNotSet, "Must call Client Login or GetEntityToken before calling this method"); var httpResult = await PlayFabHttp.DoPost("/Catalog/SetItemModerationState", request, "X-EntityToken", requestContext.EntityToken, extraHeaders); if (httpResult is PlayFabError) { var error = (PlayFabError)httpResult; PlayFabSettings.GlobalErrorHandler?.Invoke(error); return new PlayFabResult<SetItemModerationStateResponse> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = PluginManager.GetPlugin<ISerializerPlugin>(PluginContract.PlayFab_Serializer).DeserializeObject<PlayFabJsonSuccess<SetItemModerationStateResponse>>(resultRawJson); var result = resultData.data; return new PlayFabResult<SetItemModerationStateResponse> { Result = result, CustomData = customData }; } /// <summary> /// Submit a vote for a review, indicating whether the review was helpful or unhelpful. /// </summary> public static async Task<PlayFabResult<SubmitItemReviewVoteResponse>> SubmitItemReviewVoteAsync(SubmitItemReviewVoteRequest request, object customData = null, Dictionary<string, string> extraHeaders = null) { await new PlayFabUtil.SynchronizationContextRemover(); var requestContext = request?.AuthenticationContext ?? PlayFabSettings.staticPlayer; var requestSettings = PlayFabSettings.staticSettings; if (requestContext.EntityToken == null) throw new PlayFabException(PlayFabExceptionCode.EntityTokenNotSet, "Must call Client Login or GetEntityToken before calling this method"); var httpResult = await PlayFabHttp.DoPost("/Catalog/SubmitItemReviewVote", request, "X-EntityToken", requestContext.EntityToken, extraHeaders); if (httpResult is PlayFabError) { var error = (PlayFabError)httpResult; PlayFabSettings.GlobalErrorHandler?.Invoke(error); return new PlayFabResult<SubmitItemReviewVoteResponse> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = PluginManager.GetPlugin<ISerializerPlugin>(PluginContract.PlayFab_Serializer).DeserializeObject<PlayFabJsonSuccess<SubmitItemReviewVoteResponse>>(resultRawJson); var result = resultData.data; return new PlayFabResult<SubmitItemReviewVoteResponse> { Result = result, CustomData = customData }; } /// <summary> /// Submit a request to takedown one or more reviews. /// </summary> public static async Task<PlayFabResult<TakedownItemReviewsResponse>> TakedownItemReviewsAsync(TakedownItemReviewsRequest request, object customData = null, Dictionary<string, string> extraHeaders = null) { await new PlayFabUtil.SynchronizationContextRemover(); var requestContext = request?.AuthenticationContext ?? PlayFabSettings.staticPlayer; var requestSettings = PlayFabSettings.staticSettings; if (requestContext.EntityToken == null) throw new PlayFabException(PlayFabExceptionCode.EntityTokenNotSet, "Must call Client Login or GetEntityToken before calling this method"); var httpResult = await PlayFabHttp.DoPost("/Catalog/TakedownItemReviews", request, "X-EntityToken", requestContext.EntityToken, extraHeaders); if (httpResult is PlayFabError) { var error = (PlayFabError)httpResult; PlayFabSettings.GlobalErrorHandler?.Invoke(error); return new PlayFabResult<TakedownItemReviewsResponse> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = PluginManager.GetPlugin<ISerializerPlugin>(PluginContract.PlayFab_Serializer).DeserializeObject<PlayFabJsonSuccess<TakedownItemReviewsResponse>>(resultRawJson); var result = resultData.data; return new PlayFabResult<TakedownItemReviewsResponse> { Result = result, CustomData = customData }; } /// <summary> /// Updates the configuration for the catalog. /// </summary> public static async Task<PlayFabResult<UpdateCatalogConfigResponse>> UpdateCatalogConfigAsync(UpdateCatalogConfigRequest request, object customData = null, Dictionary<string, string> extraHeaders = null) { await new PlayFabUtil.SynchronizationContextRemover(); var requestContext = request?.AuthenticationContext ?? PlayFabSettings.staticPlayer; var requestSettings = PlayFabSettings.staticSettings; if (requestContext.EntityToken == null) throw new PlayFabException(PlayFabExceptionCode.EntityTokenNotSet, "Must call Client Login or GetEntityToken before calling this method"); var httpResult = await PlayFabHttp.DoPost("/Catalog/UpdateCatalogConfig", request, "X-EntityToken", requestContext.EntityToken, extraHeaders); if (httpResult is PlayFabError) { var error = (PlayFabError)httpResult; PlayFabSettings.GlobalErrorHandler?.Invoke(error); return new PlayFabResult<UpdateCatalogConfigResponse> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = PluginManager.GetPlugin<ISerializerPlugin>(PluginContract.PlayFab_Serializer).DeserializeObject<PlayFabJsonSuccess<UpdateCatalogConfigResponse>>(resultRawJson); var result = resultData.data; return new PlayFabResult<UpdateCatalogConfigResponse> { Result = result, CustomData = customData }; } /// <summary> /// Update the metadata for an item in the working catalog. /// </summary> public static async Task<PlayFabResult<UpdateDraftItemResponse>> UpdateDraftItemAsync(UpdateDraftItemRequest request, object customData = null, Dictionary<string, string> extraHeaders = null) { await new PlayFabUtil.SynchronizationContextRemover(); var requestContext = request?.AuthenticationContext ?? PlayFabSettings.staticPlayer; var requestSettings = PlayFabSettings.staticSettings; if (requestContext.EntityToken == null) throw new PlayFabException(PlayFabExceptionCode.EntityTokenNotSet, "Must call Client Login or GetEntityToken before calling this method"); var httpResult = await PlayFabHttp.DoPost("/Catalog/UpdateDraftItem", request, "X-EntityToken", requestContext.EntityToken, extraHeaders); if (httpResult is PlayFabError) { var error = (PlayFabError)httpResult; PlayFabSettings.GlobalErrorHandler?.Invoke(error); return new PlayFabResult<UpdateDraftItemResponse> { Error = error, CustomData = customData }; } var resultRawJson = (string)httpResult; var resultData = PluginManager.GetPlugin<ISerializerPlugin>(PluginContract.PlayFab_Serializer).DeserializeObject<PlayFabJsonSuccess<UpdateDraftItemResponse>>(resultRawJson); var result = resultData.data; return new PlayFabResult<UpdateDraftItemResponse> { Result = result, CustomData = customData }; } } } #endif
using System; using System.Globalization; /// <summary> /// System.Convert.ToDecimal(Object,IFormatProvider) /// </summary> public class ConvertToDecimal15 { #region Public Methods public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; retVal = PosTest4() && retVal; retVal = PosTest5() && retVal; retVal = PosTest6() && retVal; TestLibrary.TestFramework.LogInformation("[Negative]"); retVal = NegTest1() && retVal; return retVal; } #region Positive Test Cases public bool PosTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest1: The object is a byte"); try { byte i = TestLibrary.Generator.GetByte(-55); object ob = i; IFormatProvider iFormatProvider = new CultureInfo("en-US"); decimal decimalValue = Convert.ToDecimal(ob, iFormatProvider); if (decimalValue != i) { TestLibrary.TestFramework.LogError("001", "The result is not the value as expected,i is" + i); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest2: The object is an int32"); try { Int32 i = TestLibrary.Generator.GetInt32(-55); object ob = i; IFormatProvider iFormatProvider = new CultureInfo("fr-FR"); decimal decimalValue = Convert.ToDecimal(ob, iFormatProvider); if (decimalValue != i) { TestLibrary.TestFramework.LogError("003", "The result is not the value as expected,i is" + i); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("004", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest3() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest3: The object is a double and the Iformatprovider is a null reference"); try { double i = TestLibrary.Generator.GetDouble(-55); object ob = i; IFormatProvider iFormatProvider = null; decimal decimalValue = Convert.ToDecimal(ob, iFormatProvider); if (decimalValue != (i as IConvertible).ToDecimal(null)) { TestLibrary.TestFramework.LogError("005", "The result is not the value as expected,i is" + i); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("006", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest4() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest4: The object is a string and the cultureinfo is fr-FR"); try { string i = "-100 123 456"; object ob = i; IFormatProvider iFormatProvider = new CultureInfo("fr-FR"); decimal decimalValue = Convert.ToDecimal(ob, iFormatProvider); if (decimalValue != -100123456) { TestLibrary.TestFramework.LogError("007", "The result is not the value as expected,i is" + i); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("008", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest5() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest5: The object is a string and the cultureinfo is en-US"); try { string i = "-100,123,456.12345"; object ob = i; IFormatProvider iFormatProvider = new CultureInfo("en-US"); decimal decimalValue = Convert.ToDecimal(ob, iFormatProvider); if (decimalValue != -100123456.12345M) { TestLibrary.TestFramework.LogError("009", "The result is not the value as expected,i is" + i); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("010", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest6() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest6: The object is a custom class which implement the iconvertible interface"); try { MyClass myClass = new MyClass(); object ob = myClass; IFormatProvider iFormatProvider = new CultureInfo("en-US"); decimal decimalValue = Convert.ToDecimal(ob, iFormatProvider); if (decimalValue != -1) { TestLibrary.TestFramework.LogError("011", "The result is not the value as expected"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("012", "Unexpected exception: " + e); retVal = false; } return retVal; } #endregion #region Nagetive Test Cases public bool NegTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest1: The conversion is invalid"); try { char i = '1'; object ob = i; IFormatProvider iFormatProvider = new CultureInfo("en-US"); decimal decimalValue = Convert.ToDecimal(ob, iFormatProvider); TestLibrary.TestFramework.LogError("101", "The InvalidCastException was not thrown as expected"); retVal = false; } catch (InvalidCastException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("102", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } #endregion #endregion public static int Main() { ConvertToDecimal15 test = new ConvertToDecimal15(); TestLibrary.TestFramework.BeginTestCase("ConvertToDecimal15"); if (test.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } } public class MyClass : IConvertible { #region IConvertible Members public TypeCode GetTypeCode() { throw new System.Exception("The method or operation is not implemented."); } public bool ToBoolean(IFormatProvider provider) { throw new System.Exception("The method or operation is not implemented."); } public byte ToByte(IFormatProvider provider) { throw new System.Exception("The method or operation is not implemented."); } public char ToChar(IFormatProvider provider) { throw new System.Exception("The method or operation is not implemented."); } public DateTime ToDateTime(IFormatProvider provider) { throw new System.Exception("The method or operation is not implemented."); } public decimal ToDecimal(IFormatProvider provider) { if (((CultureInfo)provider).Equals(new CultureInfo("en-US"))) { return -1; } if (((CultureInfo)provider).Equals(new CultureInfo("fr-FR"))) { return 1; } return 0; } public double ToDouble(IFormatProvider provider) { throw new System.Exception("The method or operation is not implemented."); } public short ToInt16(IFormatProvider provider) { throw new System.Exception("The method or operation is not implemented."); } public int ToInt32(IFormatProvider provider) { throw new System.Exception("The method or operation is not implemented."); } public long ToInt64(IFormatProvider provider) { throw new System.Exception("The method or operation is not implemented."); } public sbyte ToSByte(IFormatProvider provider) { throw new System.Exception("The method or operation is not implemented."); } public float ToSingle(IFormatProvider provider) { throw new System.Exception("The method or operation is not implemented."); } public string ToString(IFormatProvider provider) { throw new System.Exception("The method or operation is not implemented."); } public object ToType(Type conversionType, IFormatProvider provider) { throw new System.Exception("The method or operation is not implemented."); } public ushort ToUInt16(IFormatProvider provider) { throw new System.Exception("The method or operation is not implemented."); } public uint ToUInt32(IFormatProvider provider) { throw new System.Exception("The method or operation is not implemented."); } public ulong ToUInt64(IFormatProvider provider) { throw new System.Exception("The method or operation is not implemented."); } #endregion }
// // 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.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Xml.Linq; using Hyak.Common; using Hyak.Common.Internals; using Microsoft.Azure; using Microsoft.WindowsAzure.Management.Compute; using Microsoft.WindowsAzure.Management.Compute.Models; namespace Microsoft.WindowsAzure.Management.Compute { /// <summary> /// Operations for managing service certificates for your subscription. /// (see /// http://msdn.microsoft.com/en-us/library/windowsazure/ee795178.aspx for /// more information) /// </summary> internal partial class ServiceCertificateOperations : IServiceOperations<ComputeManagementClient>, IServiceCertificateOperations { /// <summary> /// Initializes a new instance of the ServiceCertificateOperations /// class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal ServiceCertificateOperations(ComputeManagementClient client) { this._client = client; } private ComputeManagementClient _client; /// <summary> /// Gets a reference to the /// Microsoft.WindowsAzure.Management.Compute.ComputeManagementClient. /// </summary> public ComputeManagementClient Client { get { return this._client; } } /// <summary> /// The Begin Creating Service Certificate operation adds a certificate /// to a hosted service. This operation is an asynchronous operation. /// To determine whether the management service has finished /// processing the request, call Get Operation Status. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/ee460817.aspx /// for more information) /// </summary> /// <param name='serviceName'> /// Required. The DNS prefix name of your service. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the Begin Creating Service /// Certificate operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public async Task<AzureOperationResponse> BeginCreatingAsync(string serviceName, ServiceCertificateCreateParameters parameters, CancellationToken cancellationToken) { // Validate if (serviceName == null) { throw new ArgumentNullException("serviceName"); } // TODO: Validate serviceName is a valid DNS name. if (parameters == null) { throw new ArgumentNullException("parameters"); } if (parameters.Data == null) { throw new ArgumentNullException("parameters.Data"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("serviceName", serviceName); tracingParameters.Add("parameters", parameters); TracingAdapter.Enter(invocationId, this, "BeginCreatingAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/services/hostedservices/"; url = url + Uri.EscapeDataString(serviceName); url = url + "/certificates"; string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Post; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2015-04-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request string requestContent = null; XDocument requestDoc = new XDocument(); XElement certificateFileElement = new XElement(XName.Get("CertificateFile", "http://schemas.microsoft.com/windowsazure")); requestDoc.Add(certificateFileElement); XElement dataElement = new XElement(XName.Get("Data", "http://schemas.microsoft.com/windowsazure")); dataElement.Value = Convert.ToBase64String(parameters.Data); certificateFileElement.Add(dataElement); XElement certificateFormatElement = new XElement(XName.Get("CertificateFormat", "http://schemas.microsoft.com/windowsazure")); certificateFormatElement.Value = ComputeManagementClient.CertificateFormatToString(parameters.CertificateFormat); certificateFileElement.Add(certificateFormatElement); if (parameters.Password != null) { XElement passwordElement = new XElement(XName.Get("Password", "http://schemas.microsoft.com/windowsazure")); passwordElement.Value = parameters.Password; certificateFileElement.Add(passwordElement); } requestContent = requestDoc.ToString(); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/xml"); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.Accepted) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result AzureOperationResponse result = null; // Deserialize Response result = new AzureOperationResponse(); result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// The Begin Deleting Service Certificate operation deletes a service /// certificate from the certificate store of a hosted service. This /// operation is an asynchronous operation. To determine whether the /// management service has finished processing the request, call Get /// Operation Status. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/ee460803.aspx /// for more information) /// </summary> /// <param name='parameters'> /// Required. Parameters supplied to the Begin Deleting Service /// Certificate operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public async Task<AzureOperationResponse> BeginDeletingAsync(ServiceCertificateDeleteParameters parameters, CancellationToken cancellationToken) { // Validate if (parameters == null) { throw new ArgumentNullException("parameters"); } if (parameters.ServiceName == null) { throw new ArgumentNullException("parameters.ServiceName"); } // TODO: Validate parameters.ServiceName is a valid DNS name. if (parameters.Thumbprint == null) { throw new ArgumentNullException("parameters.Thumbprint"); } if (parameters.ThumbprintAlgorithm == null) { throw new ArgumentNullException("parameters.ThumbprintAlgorithm"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("parameters", parameters); TracingAdapter.Enter(invocationId, this, "BeginDeletingAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/services/hostedservices/"; url = url + Uri.EscapeDataString(parameters.ServiceName); url = url + "/certificates/"; url = url + Uri.EscapeDataString(parameters.ThumbprintAlgorithm); url = url + "-"; url = url + Uri.EscapeDataString(parameters.Thumbprint); string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Delete; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2015-04-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.Accepted) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result AzureOperationResponse result = null; // Deserialize Response result = new AzureOperationResponse(); result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// The Create Service Certificate operation adds a certificate to a /// hosted service. This operation is an asynchronous operation. To /// determine whether the management service has finished processing /// the request, call Get Operation Status. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/ee460817.aspx /// for more information) /// </summary> /// <param name='serviceName'> /// Required. The DNS prefix name of your service. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the Create Service Certificate /// operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is inprogress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request and error information regarding /// the failure. /// </returns> public async Task<OperationStatusResponse> CreateAsync(string serviceName, ServiceCertificateCreateParameters parameters, CancellationToken cancellationToken) { ComputeManagementClient client = this.Client; bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("serviceName", serviceName); tracingParameters.Add("parameters", parameters); TracingAdapter.Enter(invocationId, this, "CreateAsync", tracingParameters); } cancellationToken.ThrowIfCancellationRequested(); AzureOperationResponse response = await client.ServiceCertificates.BeginCreatingAsync(serviceName, parameters, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); OperationStatusResponse result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false); int delayInSeconds = 30; if (client.LongRunningOperationInitialTimeout >= 0) { delayInSeconds = client.LongRunningOperationInitialTimeout; } while (result.Status == OperationStatus.InProgress) { cancellationToken.ThrowIfCancellationRequested(); await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false); delayInSeconds = 30; if (client.LongRunningOperationRetryTimeout >= 0) { delayInSeconds = client.LongRunningOperationRetryTimeout; } } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } if (result.Status != OperationStatus.Succeeded) { if (result.Error != null) { CloudException ex = new CloudException(result.Error.Code + " : " + result.Error.Message); ex.Error = new CloudError(); ex.Error.Code = result.Error.Code; ex.Error.Message = result.Error.Message; if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } else { CloudException ex = new CloudException(""); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } } return result; } /// <summary> /// The Delete Service Certificate operation deletes a service /// certificate from the certificate store of a hosted service. This /// operation is an asynchronous operation. To determine whether the /// management service has finished processing the request, call Get /// Operation Status. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/ee460803.aspx /// for more information) /// </summary> /// <param name='parameters'> /// Required. Parameters supplied to the Delete Service Certificate /// operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is inprogress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request and error information regarding /// the failure. /// </returns> public async Task<OperationStatusResponse> DeleteAsync(ServiceCertificateDeleteParameters parameters, CancellationToken cancellationToken) { ComputeManagementClient client = this.Client; bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("parameters", parameters); TracingAdapter.Enter(invocationId, this, "DeleteAsync", tracingParameters); } cancellationToken.ThrowIfCancellationRequested(); AzureOperationResponse response = await client.ServiceCertificates.BeginDeletingAsync(parameters, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); OperationStatusResponse result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false); int delayInSeconds = 30; if (client.LongRunningOperationInitialTimeout >= 0) { delayInSeconds = client.LongRunningOperationInitialTimeout; } while (result.Status == OperationStatus.InProgress) { cancellationToken.ThrowIfCancellationRequested(); await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false); delayInSeconds = 30; if (client.LongRunningOperationRetryTimeout >= 0) { delayInSeconds = client.LongRunningOperationRetryTimeout; } } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } if (result.Status != OperationStatus.Succeeded) { if (result.Error != null) { CloudException ex = new CloudException(result.Error.Code + " : " + result.Error.Message); ex.Error = new CloudError(); ex.Error.Code = result.Error.Code; ex.Error.Message = result.Error.Message; if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } else { CloudException ex = new CloudException(""); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } } return result; } /// <summary> /// The Get Service Certificate operation returns the public data for /// the specified X.509 certificate associated with a hosted service. /// (see /// http://msdn.microsoft.com/en-us/library/windowsazure/ee460792.aspx /// for more information) /// </summary> /// <param name='parameters'> /// Required. Parameters supplied to the Get Service Certificate /// operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The Get Service Certificate operation response. /// </returns> public async Task<ServiceCertificateGetResponse> GetAsync(ServiceCertificateGetParameters parameters, CancellationToken cancellationToken) { // Validate if (parameters == null) { throw new ArgumentNullException("parameters"); } if (parameters.ServiceName == null) { throw new ArgumentNullException("parameters.ServiceName"); } // TODO: Validate parameters.ServiceName is a valid DNS name. if (parameters.Thumbprint == null) { throw new ArgumentNullException("parameters.Thumbprint"); } if (parameters.ThumbprintAlgorithm == null) { throw new ArgumentNullException("parameters.ThumbprintAlgorithm"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("parameters", parameters); TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/services/hostedservices/"; url = url + Uri.EscapeDataString(parameters.ServiceName); url = url + "/certificates/"; url = url + Uri.EscapeDataString(parameters.ThumbprintAlgorithm); url = url + "-"; url = url + Uri.EscapeDataString(parameters.Thumbprint); string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2015-04-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result ServiceCertificateGetResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new ServiceCertificateGetResponse(); XDocument responseDoc = XDocument.Parse(responseContent); XElement certificateElement = responseDoc.Element(XName.Get("Certificate", "http://schemas.microsoft.com/windowsazure")); if (certificateElement != null) { XElement dataElement = certificateElement.Element(XName.Get("Data", "http://schemas.microsoft.com/windowsazure")); if (dataElement != null) { byte[] dataInstance = Convert.FromBase64String(dataElement.Value); result.Data = dataInstance; } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// The List Service Certificates operation lists all of the service /// certificates associated with the specified hosted service. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/jj154105.aspx /// for more information) /// </summary> /// <param name='serviceName'> /// Required. The DNS prefix name of your hosted service. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The List Service Certificates operation response. /// </returns> public async Task<ServiceCertificateListResponse> ListAsync(string serviceName, CancellationToken cancellationToken) { // Validate if (serviceName == null) { throw new ArgumentNullException("serviceName"); } // TODO: Validate serviceName is a valid DNS name. // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("serviceName", serviceName); TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/services/hostedservices/"; url = url + Uri.EscapeDataString(serviceName); url = url + "/certificates"; string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2015-04-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result ServiceCertificateListResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new ServiceCertificateListResponse(); XDocument responseDoc = XDocument.Parse(responseContent); XElement certificatesSequenceElement = responseDoc.Element(XName.Get("Certificates", "http://schemas.microsoft.com/windowsazure")); if (certificatesSequenceElement != null) { foreach (XElement certificatesElement in certificatesSequenceElement.Elements(XName.Get("Certificate", "http://schemas.microsoft.com/windowsazure"))) { ServiceCertificateListResponse.Certificate certificateInstance = new ServiceCertificateListResponse.Certificate(); result.Certificates.Add(certificateInstance); XElement certificateUrlElement = certificatesElement.Element(XName.Get("CertificateUrl", "http://schemas.microsoft.com/windowsazure")); if (certificateUrlElement != null) { Uri certificateUrlInstance = TypeConversion.TryParseUri(certificateUrlElement.Value); certificateInstance.CertificateUri = certificateUrlInstance; } XElement thumbprintElement = certificatesElement.Element(XName.Get("Thumbprint", "http://schemas.microsoft.com/windowsazure")); if (thumbprintElement != null) { string thumbprintInstance = thumbprintElement.Value; certificateInstance.Thumbprint = thumbprintInstance; } XElement thumbprintAlgorithmElement = certificatesElement.Element(XName.Get("ThumbprintAlgorithm", "http://schemas.microsoft.com/windowsazure")); if (thumbprintAlgorithmElement != null) { string thumbprintAlgorithmInstance = thumbprintAlgorithmElement.Value; certificateInstance.ThumbprintAlgorithm = thumbprintAlgorithmInstance; } XElement dataElement = certificatesElement.Element(XName.Get("Data", "http://schemas.microsoft.com/windowsazure")); if (dataElement != null) { byte[] dataInstance = Convert.FromBase64String(dataElement.Value); certificateInstance.Data = dataInstance; } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } } }
/* * Copyright (c) 2007-2008, Second Life Reverse Engineering Team * All rights reserved. * * - Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * - Neither the name of the Second Life Reverse Engineering Team nor the names * of its contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.IO; using System.Reflection; using System.Drawing; using System.Drawing.Imaging; namespace libsecondlife.Imaging { /// <summary> /// A set of textures that are layered on texture of each other and "baked" /// in to a single texture, for avatar appearances /// </summary> public class Baker { public AssetTexture BakedTexture { get { return _bakedTexture; } } public Dictionary<int, float> ParamValues { get { return _paramValues; } } public Dictionary<AppearanceManager.TextureIndex, AssetTexture> Textures { get { return _textures; } } public int TextureCount { get { return _textureCount; } } public int BakeWidth { get { return _bakeWidth; } } public int BakeHeight { get { return _bakeHeight; } } public AppearanceManager.BakeType BakeType { get { return _bakeType; } } /// <summary>Reference to the SecondLife client</summary> protected SecondLife _client; /// <summary>Finald baked texture</summary> protected AssetTexture _bakedTexture; /// <summary>Appearance parameters the drive the baking process</summary> protected Dictionary<int, float> _paramValues; /// <summary>Wearable textures</summary> protected Dictionary<AppearanceManager.TextureIndex, AssetTexture> _textures = new Dictionary<AppearanceManager.TextureIndex, AssetTexture>(); /// <summary>Total number of textures in the bake</summary> protected int _textureCount; /// <summary>Width of the final baked image and scratchpad</summary> protected int _bakeWidth; /// <summary>Height of the final baked image and scratchpad</summary> protected int _bakeHeight; /// <summary>Bake type</summary> protected AppearanceManager.BakeType _bakeType; /// <summary> /// Default constructor /// </summary> /// <param name="client">Reference to the SecondLife client</param> /// <param name="bakeType"></param> /// <param name="textureCount">Total number of layers this layer set is /// composed of</param> /// <param name="paramValues">Appearance parameters the drive the /// baking process</param> public Baker(SecondLife client, AppearanceManager.BakeType bakeType, int textureCount, Dictionary<int, float> paramValues) { _client = client; _bakeType = bakeType; _textureCount = textureCount; if (bakeType == AppearanceManager.BakeType.Eyes) { _bakeWidth = 128; _bakeHeight = 128; } else { _bakeWidth = 512; _bakeHeight = 512; } _paramValues = paramValues; if (textureCount == 0) Bake(); } /// <summary> /// Adds an image to this baking texture and potentially processes it, or /// stores it for processing later /// </summary> /// <param name="index">The baking texture index of the image to be added</param> /// <param name="texture">JPEG2000 compressed image to be /// added to the baking texture</param> /// <param name="needsDecode">True if <code>Decode()</code> needs to be /// called for the texture, otherwise false</param> /// <returns>True if this texture is completely baked and JPEG2000 data /// is available, otherwise false</returns> public bool AddTexture(AppearanceManager.TextureIndex index, AssetTexture texture, bool needsDecode) { lock (_textures) { if (needsDecode) { try { texture.Decode(); } catch (Exception e) { Logger.Log(String.Format("AddTexture({0}, {1})", index, texture.AssetID), Helpers.LogLevel.Error, e); return false; } } _textures.Add(index, texture); Logger.DebugLog(String.Format("Added texture {0} (ID: {1}) to bake {2}", index, texture.AssetID, _bakeType), _client); } if (_textures.Count >= _textureCount) { Bake(); return true; } else { return false; } } public bool MissingTexture(AppearanceManager.TextureIndex index) { Logger.DebugLog(String.Format("Missing texture {0} in bake {1}", index, _bakeType), _client); _textureCount--; if (_textures.Count >= _textureCount) { Bake(); return true; } else { return false; } } protected void Bake() { _bakedTexture = new AssetTexture(new ManagedImage(_bakeWidth, _bakeHeight, ManagedImage.ImageChannels.Color | ManagedImage.ImageChannels.Alpha | ManagedImage.ImageChannels.Bump)); if (_bakeType == AppearanceManager.BakeType.Eyes) { InitBakedLayerColor(255, 255, 255); if (!DrawLayer(AppearanceManager.TextureIndex.EyesIris)) { Logger.Log("Missing texture for EYES - unable to bake layer", Helpers.LogLevel.Warning, _client); } } else if (_bakeType == AppearanceManager.BakeType.Head) { // FIXME: Need to use the visual parameters to determine the base skin color in RGB but // it's not apparent how to define RGB levels from the skin color parameters, so // for now use a grey foundation for the skin and skirt layers InitBakedLayerColor(128, 128, 128); DrawLayer(AppearanceManager.TextureIndex.HeadBodypaint); } else if (_bakeType == AppearanceManager.BakeType.Skirt) { float skirtRed = 1.0f, skirtGreen = 1.0f, skirtBlue = 1.0f; try { _paramValues.TryGetValue(VisualParams.Find("skirt_red", "skirt").ParamID, out skirtRed); _paramValues.TryGetValue(VisualParams.Find("skirt_green", "skirt").ParamID, out skirtGreen); _paramValues.TryGetValue(VisualParams.Find("skirt_blue", "skirt").ParamID, out skirtBlue); } catch { Logger.Log("Unable to determine skirt color from visual params", Helpers.LogLevel.Warning, _client); } InitBakedLayerColor((byte)(skirtRed * 255.0f), (byte)(skirtGreen * 255.0f), (byte)(skirtBlue * 255.0f)); DrawLayer(AppearanceManager.TextureIndex.Skirt); } else if (_bakeType == AppearanceManager.BakeType.UpperBody) { InitBakedLayerColor(128, 128, 128); DrawLayer(AppearanceManager.TextureIndex.UpperBodypaint); DrawLayer(AppearanceManager.TextureIndex.UpperUndershirt); DrawLayer(AppearanceManager.TextureIndex.UpperGloves); DrawLayer(AppearanceManager.TextureIndex.UpperShirt); DrawLayer(AppearanceManager.TextureIndex.UpperJacket); } else if (_bakeType == AppearanceManager.BakeType.LowerBody) { InitBakedLayerColor(128, 128, 128); DrawLayer(AppearanceManager.TextureIndex.LowerBodypaint); DrawLayer(AppearanceManager.TextureIndex.LowerUnderpants); DrawLayer(AppearanceManager.TextureIndex.LowerSocks); DrawLayer(AppearanceManager.TextureIndex.LowerShoes); DrawLayer(AppearanceManager.TextureIndex.LowerPants); DrawLayer(AppearanceManager.TextureIndex.LowerJacket); } _bakedTexture.Encode(); } private bool DrawLayer(AppearanceManager.TextureIndex textureIndex) { AssetTexture texture; ManagedImage source; bool sourceHasAlpha; bool sourceHasBump; bool copySourceAlphaToBakedLayer; int i = 0; try { if (!_textures.TryGetValue(textureIndex, out texture)) return false; source = texture.Image; sourceHasAlpha = ((source.Channels & ManagedImage.ImageChannels.Alpha) != 0 && source.Alpha != null); sourceHasBump = ((source.Channels & ManagedImage.ImageChannels.Bump) != 0 && source.Bump != null); copySourceAlphaToBakedLayer = sourceHasAlpha && ( textureIndex == AppearanceManager.TextureIndex.HeadBodypaint || textureIndex == AppearanceManager.TextureIndex.Skirt ); if (source.Width != _bakeWidth || source.Height != _bakeHeight) source.ResizeNearestNeighbor(_bakeWidth, _bakeHeight); } catch { return false; } int alpha = 255; //int alphaInv = 255 - alpha; int alphaInv = 256 - alpha; byte[] bakedRed = _bakedTexture.Image.Red; byte[] bakedGreen = _bakedTexture.Image.Green; byte[] bakedBlue = _bakedTexture.Image.Blue; byte[] bakedAlpha = _bakedTexture.Image.Alpha; byte[] bakedBump = _bakedTexture.Image.Bump; byte[] sourceRed = source.Red; byte[] sourceGreen = source.Green; byte[] sourceBlue = source.Blue; byte[] sourceAlpha = null; byte[] sourceBump = null; if (sourceHasAlpha) sourceAlpha = source.Alpha; if (sourceHasBump) sourceBump = source.Bump; for (int y = 0; y < _bakeHeight; y++) { for (int x = 0; x < _bakeWidth; x++) { if (sourceHasAlpha) { alpha = sourceAlpha[i]; //alphaInv = 255 - alpha; alphaInv = 256 - alpha; } bakedRed[i] = (byte)((bakedRed[i] * alphaInv + sourceRed[i] * alpha) >> 8); bakedGreen[i] = (byte)((bakedGreen[i] * alphaInv + sourceGreen[i] * alpha) >> 8); bakedBlue[i] = (byte)((bakedBlue[i] * alphaInv + sourceBlue[i] * alpha) >> 8); if (copySourceAlphaToBakedLayer) bakedAlpha[i] = sourceAlpha[i]; if (sourceHasBump) bakedBump[i] = sourceBump[i]; i++; } } return true; } /// <summary> /// Fills a baked layer as a solid *appearing* color. The colors are /// subtly dithered on a 16x16 grid to prevent the JPEG2000 stage from /// compressing it too far since it seems to cause upload failures if /// the image is a pure solid color /// </summary> /// <param name="r">Red value</param> /// <param name="g">Green value</param> /// <param name="b">Blue value</param> private void InitBakedLayerColor(byte r, byte g, byte b) { byte rByte = r; byte gByte = g; byte bByte = b; byte rAlt, gAlt, bAlt; rAlt = rByte; gAlt = gByte; bAlt = bByte; if (rByte < byte.MaxValue) rAlt++; else rAlt--; if (gByte < byte.MaxValue) gAlt++; else gAlt--; if (bByte < byte.MaxValue) bAlt++; else bAlt--; int i = 0; byte[] red = _bakedTexture.Image.Red; byte[] green = _bakedTexture.Image.Green; byte[] blue = _bakedTexture.Image.Blue; byte[] alpha = _bakedTexture.Image.Alpha; byte[] bump = _bakedTexture.Image.Bump; for (int y = 0; y < _bakeHeight; y++) { for (int x = 0; x < _bakeWidth; x++) { if (((x ^ y) & 0x10) == 0) { red[i] = rAlt; green[i] = gByte; blue[i] = bByte; alpha[i] = 255; bump[i] = 0; } else { red[i] = rByte; green[i] = gAlt; blue[i] = bAlt; alpha[i] = 255; bump[i] = 0; } ++i; } } } public static AppearanceManager.BakeType BakeTypeFor(AppearanceManager.TextureIndex index) { switch (index) { case AppearanceManager.TextureIndex.HeadBodypaint: return AppearanceManager.BakeType.Head; case AppearanceManager.TextureIndex.UpperBodypaint: case AppearanceManager.TextureIndex.UpperGloves: case AppearanceManager.TextureIndex.UpperUndershirt: case AppearanceManager.TextureIndex.UpperShirt: case AppearanceManager.TextureIndex.UpperJacket: return AppearanceManager.BakeType.UpperBody; case AppearanceManager.TextureIndex.LowerBodypaint: case AppearanceManager.TextureIndex.LowerUnderpants: case AppearanceManager.TextureIndex.LowerSocks: case AppearanceManager.TextureIndex.LowerShoes: case AppearanceManager.TextureIndex.LowerPants: case AppearanceManager.TextureIndex.LowerJacket: return AppearanceManager.BakeType.LowerBody; case AppearanceManager.TextureIndex.EyesIris: return AppearanceManager.BakeType.Eyes; case AppearanceManager.TextureIndex.Skirt: return AppearanceManager.BakeType.Skirt; default: return AppearanceManager.BakeType.Unknown; } } } }
/* * Copyright (c) .NET Foundation and Contributors * * This software may be modified and distributed under the terms * of the MIT license. See the LICENSE file for details. * * https://github.com/piranhacms/piranha.core * */ using System; using System.IO; using System.Linq; using System.Threading.Tasks; using Microsoft.Extensions.Caching.Memory; using Microsoft.Extensions.Caching.Distributed; using Xunit; using Piranha.Models; namespace Piranha.Tests.Services { [Collection("Integration tests")] public class MediaTestsMemoryCache: MediaTests { public override Task InitializeAsync() { _cache = new Cache.MemoryCache((IMemoryCache)_services.GetService(typeof(IMemoryCache))); return base.InitializeAsync(); } } [Collection("Integration tests")] public class MediaTestsDistributedCache: MediaTests { public override Task InitializeAsync() { _cache = new Cache.DistributedCache((IDistributedCache)_services.GetService(typeof(IDistributedCache))); return base.InitializeAsync(); } } [Collection("Integration tests")] public class MediaTests : BaseTestsAsync { private Guid image1Id; private Guid image2Id; private Guid image3Id; private Guid image4Id; private Guid image5Id; private Guid folder1Id; public override async Task InitializeAsync() { using (var api = CreateApi()) { Piranha.App.Init(api); // Add media folders var folder1 = new MediaFolder { Name = "Images" }; await api.Media.SaveFolderAsync(folder1); folder1Id = folder1.Id; // Add media using (var stream = File.OpenRead("../../../Assets/HLD_Screenshot_01_mech_1080.png")) { var image1 = new Models.StreamMediaContent { Filename = "HLD_Screenshot_01_mech_1080.png", Data = stream }; await api.Media.SaveAsync(image1); image1Id = image1.Id.Value; // Add some additional meta data var image = await api.Media.GetByIdAsync(image1Id); image.Title = "Screenshot"; image.AltText = "This is a screenshot"; image.Description = "Screenshot from Hyper Light Drifter"; image.Properties["Game"] = "Hyper Light Drifter"; await api.Media.SaveAsync(image); } using (var stream = File.OpenRead("../../../Assets/HLD_Screenshot_01_rise_1080.png")) { var image2 = new Models.StreamMediaContent { FolderId = folder1Id, Filename = "HLD_Screenshot_01_rise_1080.png", Data = stream }; await api.Media.SaveAsync(image2); image2Id = image2.Id.Value; } using (var stream = File.OpenRead("../../../Assets/HLD_Screenshot_01_robot_1080.png")) { var image3 = new Models.StreamMediaContent { Filename = "HLD_Screenshot_01_robot_1080.png", Data = stream }; await api.Media.SaveAsync(image3); image3Id = image3.Id.Value; } using (var stream = File.OpenRead("../../../Assets/HLD Screenshot 01 mech 1080.png")) { var image5 = new Models.StreamMediaContent { Filename = "HLD Screenshot 01 mech 1080.png", Data = stream }; await api.Media.SaveAsync(image5); image5Id = image5.Id.Value; } } } public override async Task DisposeAsync() { using (var api = CreateApi()) { var media = await api.Media.GetAllByFolderIdAsync(); foreach (var item in media) { await api.Media.DeleteAsync(item); } var folders = await api.Media.GetAllFoldersAsync(); foreach (var folder in folders) { media = await api.Media.GetAllByFolderIdAsync(folder.Id); foreach (var item in media) { await api.Media.DeleteAsync(item); } await api.Media.DeleteFolderAsync(folder); } } } [Fact] public void IsCached() { using (var api = CreateApi()) { Assert.Equal(((Api)api).IsCached, this.GetType() == typeof(MediaTestsMemoryCache) || this.GetType() == typeof(MediaTestsDistributedCache)); } } [Fact] public async Task GetAll() { using (var api = CreateApi()) { var media = await api.Media.GetAllByFolderIdAsync(); Assert.NotEmpty(media); } } [Fact] public async Task GetById() { using (var api = CreateApi()) { var media = await api.Media.GetByIdAsync(image1Id); Assert.NotNull(media); Assert.Equal("HLD_Screenshot_01_mech_1080.png", media.Filename); Assert.Equal("image/png", media.ContentType); Assert.Equal(Models.MediaType.Image, media.Type); } } [Fact] public async Task GetByFolderId() { using (var api = CreateApi()) { var media = (await api.Media.GetAllByFolderIdAsync(folder1Id)).ToList(); Assert.NotEmpty(media); Assert.Equal("HLD_Screenshot_01_rise_1080.png", media[0].Filename); } } [Fact] public async Task FilenameHasNoSpaces() { using (var api = CreateApi()) { var media = await api.Media.GetByIdAsync(image5Id); Assert.NotNull(media); Assert.Equal("HLD_Screenshot_01_mech_1080.png", media.Filename); } } [Fact] public async Task TitleNotNull() { using (var api = CreateApi()) { var media = await api.Media.GetByIdAsync(image1Id); Assert.NotNull(media.Title); Assert.Equal("Screenshot", media.Title); } } [Fact] public async Task AltTextNotNull() { using (var api = CreateApi()) { var media = await api.Media.GetByIdAsync(image1Id); Assert.NotNull(media.AltText); Assert.Equal("This is a screenshot", media.AltText); } } [Fact] public async Task DescriptionNotNull() { using (var api = CreateApi()) { var media = await api.Media.GetByIdAsync(image1Id); Assert.NotNull(media.Description); Assert.Equal("Screenshot from Hyper Light Drifter", media.Description); } } [Fact] public async Task HasProperty() { using (var api = CreateApi()) { var media = await api.Media.GetByIdAsync(image1Id); Assert.Equal("Hyper Light Drifter", media.Properties["Game"]); } } [Fact] public async Task Move() { using (var api = CreateApi()) { var media = await api.Media.GetByIdAsync(image1Id); Assert.NotNull(media); Assert.Null(media.FolderId); await api.Media.MoveAsync(media, folder1Id); media = await api.Media.GetByIdAsync(image1Id); Assert.NotNull(media.FolderId); Assert.Equal(folder1Id, media.FolderId.Value); await api.Media.MoveAsync(media, null); } } [Fact] public async Task Insert() { using (var api = CreateApi()) { using (var stream = File.OpenRead("../../../Assets/HLD_Screenshot_BETA_entrance.png")) { var image = new Models.StreamMediaContent { Filename = "HLD_Screenshot_BETA_entrance.png", Data = stream }; await api.Media.SaveAsync(image); Assert.NotNull(image.Id); image4Id = image.Id.Value; } } } [Fact] public async Task PublicUrl() { using (var api = CreateApi()) { using (var config = new Piranha.Config(api)) { config.MediaCDN = null; } var media = await api.Media.GetByIdAsync(image1Id); Assert.NotNull(media); Assert.Equal($"~/uploads/{image1Id}-HLD_Screenshot_01_mech_1080.png", media.PublicUrl); } } [Fact] public async Task PublicUrlCDN() { using (var api = CreateApi()) { using (var config = new Piranha.Config(api)) { config.MediaCDN = "https://mycdn.org/uploads"; } var media = await api.Media.GetByIdAsync(image1Id); Assert.NotNull(media); Assert.Equal($"https://mycdn.org/uploads/{image1Id}-HLD_Screenshot_01_mech_1080.png", media.PublicUrl); } } [Fact] public async Task Delete() { using (var api = CreateApi()) { var media = await api.Media.GetByIdAsync(image3Id); await api.Media.DeleteAsync(media); } } [Fact] public async Task DeleteById() { using (var api = CreateApi()) { await api.Media.DeleteAsync(image4Id); } } } }
#region Apache License // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion using System; #if NETSTANDARD1_3 using System.Runtime.InteropServices; #else using System.Configuration; #endif using System.Reflection; using log4net.Util; using log4net.Repository; namespace log4net.Core { /// <summary> /// Static manager that controls the creation of repositories /// </summary> /// <remarks> /// <para> /// Static manager that controls the creation of repositories /// </para> /// <para> /// This class is used by the wrapper managers (e.g. <see cref="log4net.LogManager"/>) /// to provide access to the <see cref="ILogger"/> objects. /// </para> /// <para> /// This manager also holds the <see cref="IRepositorySelector"/> that is used to /// lookup and create repositories. The selector can be set either programmatically using /// the <see cref="RepositorySelector"/> property, or by setting the <c>log4net.RepositorySelector</c> /// AppSetting in the applications config file to the fully qualified type name of the /// selector to use. /// </para> /// </remarks> /// <author>Nicko Cadell</author> /// <author>Gert Driesen</author> public sealed class LoggerManager { #region Private Instance Constructors /// <summary> /// Private constructor to prevent instances. Only static methods should be used. /// </summary> /// <remarks> /// <para> /// Private constructor to prevent instances. Only static methods should be used. /// </para> /// </remarks> private LoggerManager() { } #endregion Private Instance Constructors #region Static Constructor /// <summary> /// Hook the shutdown event /// </summary> /// <remarks> /// <para> /// On the full .NET runtime, the static constructor hooks up the /// <c>AppDomain.ProcessExit</c> and <c>AppDomain.DomainUnload</c>> events. /// These are used to shutdown the log4net system as the application exits. /// </para> /// </remarks> static LoggerManager() { try { // Register the AppDomain events, note we have to do this with a // method call rather than directly here because the AppDomain // makes a LinkDemand which throws the exception during the JIT phase. RegisterAppDomainEvents(); } catch(System.Security.SecurityException) { LogLog.Debug(declaringType, "Security Exception (ControlAppDomain LinkDemand) while trying "+ "to register Shutdown handler with the AppDomain. LoggerManager.Shutdown() "+ "will not be called automatically when the AppDomain exits. It must be called "+ "programmatically."); } // Dump out our assembly version into the log if debug is enabled LogLog.Debug(declaringType, GetVersionInfo()); // Set the default repository selector #if NETCF s_repositorySelector = new CompactRepositorySelector(typeof(log4net.Repository.Hierarchy.Hierarchy)); return; #elif !NETSTANDARD1_3 // Look for the RepositorySelector type specified in the AppSettings 'log4net.RepositorySelector' string appRepositorySelectorTypeName = SystemInfo.GetAppSetting("log4net.RepositorySelector"); if (appRepositorySelectorTypeName != null && appRepositorySelectorTypeName.Length > 0) { // Resolve the config string into a Type Type appRepositorySelectorType = null; try { appRepositorySelectorType = SystemInfo.GetTypeFromString(appRepositorySelectorTypeName, false, true); } catch(Exception ex) { LogLog.Error(declaringType, "Exception while resolving RepositorySelector Type ["+appRepositorySelectorTypeName+"]", ex); } if (appRepositorySelectorType != null) { // Create an instance of the RepositorySelectorType object appRepositorySelectorObj = null; try { appRepositorySelectorObj = Activator.CreateInstance(appRepositorySelectorType); } catch(Exception ex) { LogLog.Error(declaringType, "Exception while creating RepositorySelector ["+appRepositorySelectorType.FullName+"]", ex); } if (appRepositorySelectorObj != null && appRepositorySelectorObj is IRepositorySelector) { s_repositorySelector = (IRepositorySelector)appRepositorySelectorObj; } else { LogLog.Error(declaringType, "RepositorySelector Type ["+appRepositorySelectorType.FullName+"] is not an IRepositorySelector"); } } } #endif // Create the DefaultRepositorySelector if not configured above if (s_repositorySelector == null) { s_repositorySelector = new DefaultRepositorySelector(typeof(log4net.Repository.Hierarchy.Hierarchy)); } } /// <summary> /// Register for ProcessExit and DomainUnload events on the AppDomain /// </summary> /// <remarks> /// <para> /// This needs to be in a separate method because the events make /// a LinkDemand for the ControlAppDomain SecurityPermission. Because /// this is a LinkDemand it is demanded at JIT time. Therefore we cannot /// catch the exception in the method itself, we have to catch it in the /// caller. /// </para> /// </remarks> private static void RegisterAppDomainEvents() { #if !(NETCF || NETSTANDARD1_3) // ProcessExit seems to be fired if we are part of the default domain AppDomain.CurrentDomain.ProcessExit += new EventHandler(OnProcessExit); // Otherwise DomainUnload is fired AppDomain.CurrentDomain.DomainUnload += new EventHandler(OnDomainUnload); #endif } #endregion Static Constructor #region Public Static Methods /// <summary> /// Return the default <see cref="ILoggerRepository"/> instance. /// </summary> /// <param name="repository">the repository to lookup in</param> /// <returns>Return the default <see cref="ILoggerRepository"/> instance</returns> /// <remarks> /// <para> /// Gets the <see cref="ILoggerRepository"/> for the repository specified /// by the <paramref name="repository"/> argument. /// </para> /// </remarks> [Obsolete("Use GetRepository instead of GetLoggerRepository. Scheduled removal in v10.0.0.")] public static ILoggerRepository GetLoggerRepository(string repository) { return GetRepository(repository); } /// <summary> /// Returns the default <see cref="ILoggerRepository"/> instance. /// </summary> /// <param name="repositoryAssembly">The assembly to use to lookup the repository.</param> /// <returns>The default <see cref="ILoggerRepository"/> instance.</returns> [Obsolete("Use GetRepository instead of GetLoggerRepository. Scheduled removal in v10.0.0.")] public static ILoggerRepository GetLoggerRepository(Assembly repositoryAssembly) { return GetRepository(repositoryAssembly); } /// <summary> /// Return the default <see cref="ILoggerRepository"/> instance. /// </summary> /// <param name="repository">the repository to lookup in</param> /// <returns>Return the default <see cref="ILoggerRepository"/> instance</returns> /// <remarks> /// <para> /// Gets the <see cref="ILoggerRepository"/> for the repository specified /// by the <paramref name="repository"/> argument. /// </para> /// </remarks> public static ILoggerRepository GetRepository(string repository) { if (repository == null) { throw new ArgumentNullException("repository"); } return RepositorySelector.GetRepository(repository); } /// <summary> /// Returns the default <see cref="ILoggerRepository"/> instance. /// </summary> /// <param name="repositoryAssembly">The assembly to use to lookup the repository.</param> /// <returns>The default <see cref="ILoggerRepository"/> instance.</returns> /// <remarks> /// <para> /// Returns the default <see cref="ILoggerRepository"/> instance. /// </para> /// </remarks> public static ILoggerRepository GetRepository(Assembly repositoryAssembly) { if (repositoryAssembly == null) { throw new ArgumentNullException("repositoryAssembly"); } return RepositorySelector.GetRepository(repositoryAssembly); } /// <summary> /// Returns the named logger if it exists. /// </summary> /// <param name="repository">The repository to lookup in.</param> /// <param name="name">The fully qualified logger name to look for.</param> /// <returns> /// The logger found, or <c>null</c> if the named logger does not exist in the /// specified repository. /// </returns> /// <remarks> /// <para> /// If the named logger exists (in the specified repository) then it /// returns a reference to the logger, otherwise it returns /// <c>null</c>. /// </para> /// </remarks> public static ILogger Exists(string repository, string name) { if (repository == null) { throw new ArgumentNullException("repository"); } if (name == null) { throw new ArgumentNullException("name"); } return RepositorySelector.GetRepository(repository).Exists(name); } /// <summary> /// Returns the named logger if it exists. /// </summary> /// <param name="repositoryAssembly">The assembly to use to lookup the repository.</param> /// <param name="name">The fully qualified logger name to look for.</param> /// <returns> /// The logger found, or <c>null</c> if the named logger does not exist in the /// specified assembly's repository. /// </returns> /// <remarks> /// <para> /// If the named logger exists (in the specified assembly's repository) then it /// returns a reference to the logger, otherwise it returns /// <c>null</c>. /// </para> /// </remarks> public static ILogger Exists(Assembly repositoryAssembly, string name) { if (repositoryAssembly == null) { throw new ArgumentNullException("repositoryAssembly"); } if (name == null) { throw new ArgumentNullException("name"); } return RepositorySelector.GetRepository(repositoryAssembly).Exists(name); } /// <summary> /// Returns all the currently defined loggers in the specified repository. /// </summary> /// <param name="repository">The repository to lookup in.</param> /// <returns>All the defined loggers.</returns> /// <remarks> /// <para> /// The root logger is <b>not</b> included in the returned array. /// </para> /// </remarks> public static ILogger[] GetCurrentLoggers(string repository) { if (repository == null) { throw new ArgumentNullException("repository"); } return RepositorySelector.GetRepository(repository).GetCurrentLoggers(); } /// <summary> /// Returns all the currently defined loggers in the specified assembly's repository. /// </summary> /// <param name="repositoryAssembly">The assembly to use to lookup the repository.</param> /// <returns>All the defined loggers.</returns> /// <remarks> /// <para> /// The root logger is <b>not</b> included in the returned array. /// </para> /// </remarks> public static ILogger[] GetCurrentLoggers(Assembly repositoryAssembly) { if (repositoryAssembly == null) { throw new ArgumentNullException("repositoryAssembly"); } return RepositorySelector.GetRepository(repositoryAssembly).GetCurrentLoggers(); } /// <summary> /// Retrieves or creates a named logger. /// </summary> /// <param name="repository">The repository to lookup in.</param> /// <param name="name">The name of the logger to retrieve.</param> /// <returns>The logger with the name specified.</returns> /// <remarks> /// <para> /// Retrieves a logger named as the <paramref name="name"/> /// parameter. If the named logger already exists, then the /// existing instance will be returned. Otherwise, a new instance is /// created. /// </para> /// <para> /// By default, loggers do not have a set level but inherit /// it from the hierarchy. This is one of the central features of /// log4net. /// </para> /// </remarks> public static ILogger GetLogger(string repository, string name) { if (repository == null) { throw new ArgumentNullException("repository"); } if (name == null) { throw new ArgumentNullException("name"); } return RepositorySelector.GetRepository(repository).GetLogger(name); } /// <summary> /// Retrieves or creates a named logger. /// </summary> /// <param name="repositoryAssembly">The assembly to use to lookup the repository.</param> /// <param name="name">The name of the logger to retrieve.</param> /// <returns>The logger with the name specified.</returns> /// <remarks> /// <para> /// Retrieves a logger named as the <paramref name="name"/> /// parameter. If the named logger already exists, then the /// existing instance will be returned. Otherwise, a new instance is /// created. /// </para> /// <para> /// By default, loggers do not have a set level but inherit /// it from the hierarchy. This is one of the central features of /// log4net. /// </para> /// </remarks> public static ILogger GetLogger(Assembly repositoryAssembly, string name) { if (repositoryAssembly == null) { throw new ArgumentNullException("repositoryAssembly"); } if (name == null) { throw new ArgumentNullException("name"); } return RepositorySelector.GetRepository(repositoryAssembly).GetLogger(name); } /// <summary> /// Shorthand for <see cref="M:LogManager.GetLogger(string)"/>. /// </summary> /// <param name="repository">The repository to lookup in.</param> /// <param name="type">The <paramref name="type"/> of which the fullname will be used as the name of the logger to retrieve.</param> /// <returns>The logger with the name specified.</returns> /// <remarks> /// <para> /// Gets the logger for the fully qualified name of the type specified. /// </para> /// </remarks> public static ILogger GetLogger(string repository, Type type) { if (repository == null) { throw new ArgumentNullException("repository"); } if (type == null) { throw new ArgumentNullException("type"); } return RepositorySelector.GetRepository(repository).GetLogger(type.FullName); } /// <summary> /// Shorthand for <see cref="M:LogManager.GetLogger(string)"/>. /// </summary> /// <param name="repositoryAssembly">the assembly to use to lookup the repository</param> /// <param name="type">The <paramref name="type"/> of which the fullname will be used as the name of the logger to retrieve.</param> /// <returns>The logger with the name specified.</returns> /// <remarks> /// <para> /// Gets the logger for the fully qualified name of the type specified. /// </para> /// </remarks> public static ILogger GetLogger(Assembly repositoryAssembly, Type type) { if (repositoryAssembly == null) { throw new ArgumentNullException("repositoryAssembly"); } if (type == null) { throw new ArgumentNullException("type"); } return RepositorySelector.GetRepository(repositoryAssembly).GetLogger(type.FullName); } /// <summary> /// Shuts down the log4net system. /// </summary> /// <remarks> /// <para> /// Calling this method will <b>safely</b> close and remove all /// appenders in all the loggers including root contained in all the /// default repositories. /// </para> /// <para> /// Some appenders need to be closed before the application exists. /// Otherwise, pending logging events might be lost. /// </para> /// <para> /// The <c>shutdown</c> method is careful to close nested /// appenders before closing regular appenders. This is allows /// configurations where a regular appender is attached to a logger /// and again to a nested appender. /// </para> /// </remarks> public static void Shutdown() { foreach(ILoggerRepository repository in GetAllRepositories()) { repository.Shutdown(); } } /// <summary> /// Shuts down the repository for the repository specified. /// </summary> /// <param name="repository">The repository to shutdown.</param> /// <remarks> /// <para> /// Calling this method will <b>safely</b> close and remove all /// appenders in all the loggers including root contained in the /// repository for the <paramref name="repository"/> specified. /// </para> /// <para> /// Some appenders need to be closed before the application exists. /// Otherwise, pending logging events might be lost. /// </para> /// <para> /// The <c>shutdown</c> method is careful to close nested /// appenders before closing regular appenders. This is allows /// configurations where a regular appender is attached to a logger /// and again to a nested appender. /// </para> /// </remarks> public static void ShutdownRepository(string repository) { if (repository == null) { throw new ArgumentNullException("repository"); } RepositorySelector.GetRepository(repository).Shutdown(); } /// <summary> /// Shuts down the repository for the repository specified. /// </summary> /// <param name="repositoryAssembly">The assembly to use to lookup the repository.</param> /// <remarks> /// <para> /// Calling this method will <b>safely</b> close and remove all /// appenders in all the loggers including root contained in the /// repository for the repository. The repository is looked up using /// the <paramref name="repositoryAssembly"/> specified. /// </para> /// <para> /// Some appenders need to be closed before the application exists. /// Otherwise, pending logging events might be lost. /// </para> /// <para> /// The <c>shutdown</c> method is careful to close nested /// appenders before closing regular appenders. This is allows /// configurations where a regular appender is attached to a logger /// and again to a nested appender. /// </para> /// </remarks> public static void ShutdownRepository(Assembly repositoryAssembly) { if (repositoryAssembly == null) { throw new ArgumentNullException("repositoryAssembly"); } RepositorySelector.GetRepository(repositoryAssembly).Shutdown(); } /// <summary> /// Resets all values contained in this repository instance to their defaults. /// </summary> /// <param name="repository">The repository to reset.</param> /// <remarks> /// <para> /// Resets all values contained in the repository instance to their /// defaults. This removes all appenders from all loggers, sets /// the level of all non-root loggers to <c>null</c>, /// sets their additivity flag to <c>true</c> and sets the level /// of the root logger to <see cref="Level.Debug"/>. Moreover, /// message disabling is set its default "off" value. /// </para> /// </remarks> public static void ResetConfiguration(string repository) { if (repository == null) { throw new ArgumentNullException("repository"); } RepositorySelector.GetRepository(repository).ResetConfiguration(); } /// <summary> /// Resets all values contained in this repository instance to their defaults. /// </summary> /// <param name="repositoryAssembly">The assembly to use to lookup the repository to reset.</param> /// <remarks> /// <para> /// Resets all values contained in the repository instance to their /// defaults. This removes all appenders from all loggers, sets /// the level of all non-root loggers to <c>null</c>, /// sets their additivity flag to <c>true</c> and sets the level /// of the root logger to <see cref="Level.Debug"/>. Moreover, /// message disabling is set its default "off" value. /// </para> /// </remarks> public static void ResetConfiguration(Assembly repositoryAssembly) { if (repositoryAssembly == null) { throw new ArgumentNullException("repositoryAssembly"); } RepositorySelector.GetRepository(repositoryAssembly).ResetConfiguration(); } /// <summary> /// Creates a repository with the specified name. /// </summary> /// <param name="repository">The name of the repository, this must be unique amongst repositories.</param> /// <returns>The <see cref="ILoggerRepository"/> created for the repository.</returns> /// <remarks> /// <para> /// <b>CreateDomain is obsolete. Use CreateRepository instead of CreateDomain.</b> /// </para> /// <para> /// Creates the default type of <see cref="ILoggerRepository"/> which is a /// <see cref="log4net.Repository.Hierarchy.Hierarchy"/> object. /// </para> /// <para> /// The <paramref name="repository"/> name must be unique. Repositories cannot be redefined. /// An <see cref="Exception"/> will be thrown if the repository already exists. /// </para> /// </remarks> /// <exception cref="LogException">The specified repository already exists.</exception> [Obsolete("Use CreateRepository instead of CreateDomain. Scheduled removal in v10.0.0.")] public static ILoggerRepository CreateDomain(string repository) { return CreateRepository(repository); } /// <summary> /// Creates a repository with the specified name. /// </summary> /// <param name="repository">The name of the repository, this must be unique amongst repositories.</param> /// <returns>The <see cref="ILoggerRepository"/> created for the repository.</returns> /// <remarks> /// <para> /// Creates the default type of <see cref="ILoggerRepository"/> which is a /// <see cref="log4net.Repository.Hierarchy.Hierarchy"/> object. /// </para> /// <para> /// The <paramref name="repository"/> name must be unique. Repositories cannot be redefined. /// An <see cref="Exception"/> will be thrown if the repository already exists. /// </para> /// </remarks> /// <exception cref="LogException">The specified repository already exists.</exception> public static ILoggerRepository CreateRepository(string repository) { if (repository == null) { throw new ArgumentNullException("repository"); } return RepositorySelector.CreateRepository(repository, null); } /// <summary> /// Creates a repository with the specified name and repository type. /// </summary> /// <param name="repository">The name of the repository, this must be unique to the repository.</param> /// <param name="repositoryType">A <see cref="Type"/> that implements <see cref="ILoggerRepository"/> /// and has a no arg constructor. An instance of this type will be created to act /// as the <see cref="ILoggerRepository"/> for the repository specified.</param> /// <returns>The <see cref="ILoggerRepository"/> created for the repository.</returns> /// <remarks> /// <para> /// <b>CreateDomain is obsolete. Use CreateRepository instead of CreateDomain.</b> /// </para> /// <para> /// The <paramref name="repository"/> name must be unique. Repositories cannot be redefined. /// An Exception will be thrown if the repository already exists. /// </para> /// </remarks> /// <exception cref="LogException">The specified repository already exists.</exception> [Obsolete("Use CreateRepository instead of CreateDomain. Scheduled removal in v10.0.0.")] public static ILoggerRepository CreateDomain(string repository, Type repositoryType) { return CreateRepository(repository, repositoryType); } /// <summary> /// Creates a repository with the specified name and repository type. /// </summary> /// <param name="repository">The name of the repository, this must be unique to the repository.</param> /// <param name="repositoryType">A <see cref="Type"/> that implements <see cref="ILoggerRepository"/> /// and has a no arg constructor. An instance of this type will be created to act /// as the <see cref="ILoggerRepository"/> for the repository specified.</param> /// <returns>The <see cref="ILoggerRepository"/> created for the repository.</returns> /// <remarks> /// <para> /// The <paramref name="repository"/> name must be unique. Repositories cannot be redefined. /// An Exception will be thrown if the repository already exists. /// </para> /// </remarks> /// <exception cref="LogException">The specified repository already exists.</exception> public static ILoggerRepository CreateRepository(string repository, Type repositoryType) { if (repository == null) { throw new ArgumentNullException("repository"); } if (repositoryType == null) { throw new ArgumentNullException("repositoryType"); } return RepositorySelector.CreateRepository(repository, repositoryType); } /// <summary> /// Creates a repository for the specified assembly and repository type. /// </summary> /// <param name="repositoryAssembly">The assembly to use to get the name of the repository.</param> /// <param name="repositoryType">A <see cref="Type"/> that implements <see cref="ILoggerRepository"/> /// and has a no arg constructor. An instance of this type will be created to act /// as the <see cref="ILoggerRepository"/> for the repository specified.</param> /// <returns>The <see cref="ILoggerRepository"/> created for the repository.</returns> /// <remarks> /// <para> /// <b>CreateDomain is obsolete. Use CreateRepository instead of CreateDomain.</b> /// </para> /// <para> /// The <see cref="ILoggerRepository"/> created will be associated with the repository /// specified such that a call to <see cref="M:GetRepository(Assembly)"/> with the /// same assembly specified will return the same repository instance. /// </para> /// </remarks> [Obsolete("Use CreateRepository instead of CreateDomain. Scheduled removal in v10.0.0.")] public static ILoggerRepository CreateDomain(Assembly repositoryAssembly, Type repositoryType) { return CreateRepository(repositoryAssembly, repositoryType); } /// <summary> /// Creates a repository for the specified assembly and repository type. /// </summary> /// <param name="repositoryAssembly">The assembly to use to get the name of the repository.</param> /// <param name="repositoryType">A <see cref="Type"/> that implements <see cref="ILoggerRepository"/> /// and has a no arg constructor. An instance of this type will be created to act /// as the <see cref="ILoggerRepository"/> for the repository specified.</param> /// <returns>The <see cref="ILoggerRepository"/> created for the repository.</returns> /// <remarks> /// <para> /// The <see cref="ILoggerRepository"/> created will be associated with the repository /// specified such that a call to <see cref="M:GetRepository(Assembly)"/> with the /// same assembly specified will return the same repository instance. /// </para> /// </remarks> public static ILoggerRepository CreateRepository(Assembly repositoryAssembly, Type repositoryType) { if (repositoryAssembly == null) { throw new ArgumentNullException("repositoryAssembly"); } if (repositoryType == null) { throw new ArgumentNullException("repositoryType"); } return RepositorySelector.CreateRepository(repositoryAssembly, repositoryType); } /// <summary> /// Gets an array of all currently defined repositories. /// </summary> /// <returns>An array of all the known <see cref="ILoggerRepository"/> objects.</returns> /// <remarks> /// <para> /// Gets an array of all currently defined repositories. /// </para> /// </remarks> public static ILoggerRepository[] GetAllRepositories() { return RepositorySelector.GetAllRepositories(); } /// <summary> /// Gets or sets the repository selector used by the <see cref="LogManager" />. /// </summary> /// <value> /// The repository selector used by the <see cref="LogManager" />. /// </value> /// <remarks> /// <para> /// The repository selector (<see cref="IRepositorySelector"/>) is used by /// the <see cref="LogManager"/> to create and select repositories /// (<see cref="ILoggerRepository"/>). /// </para> /// <para> /// The caller to <see cref="LogManager"/> supplies either a string name /// or an assembly (if not supplied the assembly is inferred using /// <see cref="M:Assembly.GetCallingAssembly()"/>). /// </para> /// <para> /// This context is used by the selector to lookup a specific repository. /// </para> /// <para> /// For the full .NET Framework, the default repository is <c>DefaultRepositorySelector</c>; /// for the .NET Compact Framework <c>CompactRepositorySelector</c> is the default /// repository. /// </para> /// </remarks> public static IRepositorySelector RepositorySelector { get { return s_repositorySelector; } set { s_repositorySelector = value; } } #endregion Public Static Methods #region Private Static Methods /// <summary> /// Internal method to get pertinent version info. /// </summary> /// <returns>A string of version info.</returns> private static string GetVersionInfo() { System.Text.StringBuilder sb = new System.Text.StringBuilder(); #if NETSTANDARD1_3 Assembly myAssembly = typeof(LoggerManager).GetTypeInfo().Assembly; sb.Append($"log4net assembly [{myAssembly.FullName}]. "); //sb.Append($"Loaded from [{myAssembly.Location}]. "); // TODO Assembly.Location available in netstandard1.5 sb.Append($"(.NET Framework [{RuntimeInformation.FrameworkDescription}] on {RuntimeInformation.OSDescription}"); #else Assembly myAssembly = Assembly.GetExecutingAssembly(); sb.Append("log4net assembly [").Append(myAssembly.FullName).Append("]. "); sb.Append("Loaded from [").Append(SystemInfo.AssemblyLocationInfo(myAssembly)).Append("]. "); sb.Append("(.NET Runtime [").Append(Environment.Version.ToString()).Append("]"); #if (!SSCLI) sb.Append(" on ").Append(Environment.OSVersion.ToString()); #endif #endif // NETSTANDARD1_3 sb.Append(")"); return sb.ToString(); } #if (!NETCF) /// <summary> /// Called when the <see cref="AppDomain.DomainUnload"/> event fires /// </summary> /// <param name="sender">the <see cref="AppDomain"/> that is exiting</param> /// <param name="e">null</param> /// <remarks> /// <para> /// Called when the <see cref="AppDomain.DomainUnload"/> event fires. /// </para> /// <para> /// When the event is triggered the log4net system is <see cref="M:Shutdown()"/>. /// </para> /// </remarks> private static void OnDomainUnload(object sender, EventArgs e) { Shutdown(); } /// <summary> /// Called when the <see cref="AppDomain.ProcessExit"/> event fires /// </summary> /// <param name="sender">the <see cref="AppDomain"/> that is exiting</param> /// <param name="e">null</param> /// <remarks> /// <para> /// Called when the <see cref="AppDomain.ProcessExit"/> event fires. /// </para> /// <para> /// When the event is triggered the log4net system is <see cref="M:Shutdown()"/>. /// </para> /// </remarks> private static void OnProcessExit(object sender, EventArgs e) { Shutdown(); } #endif #endregion Private Static Methods #region Private Static Fields /// <summary> /// The fully qualified type of the LoggerManager class. /// </summary> /// <remarks> /// Used by the internal logger to record the Type of the /// log message. /// </remarks> private readonly static Type declaringType = typeof(LoggerManager); /// <summary> /// Initialize the default repository selector /// </summary> private static IRepositorySelector s_repositorySelector; #endregion Private Static Fields } }
// // Copyright (c) 2004-2021 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.LayoutRenderers { using System; using System.Text; using System.Collections.Generic; using System.ComponentModel; using NLog.Config; using NLog.Internal; /// <summary> /// Log event context data. /// </summary> [LayoutRenderer("all-event-properties")] [ThreadAgnostic] [ThreadSafe] [MutableUnsafe] public class AllEventPropertiesLayoutRenderer : LayoutRenderer { private string _format; private string _beforeKey; private string _afterKey; private string _afterValue; /// <summary> /// Initializes a new instance of the <see cref="AllEventPropertiesLayoutRenderer"/> class. /// </summary> public AllEventPropertiesLayoutRenderer() { Separator = ", "; Format = "[key]=[value]"; Exclude = new HashSet<string>( #if NET4_5 CallerInformationAttributeNames, #else ArrayHelper.Empty<string>(), #endif StringComparer.OrdinalIgnoreCase); } /// <summary> /// Gets or sets string that will be used to separate key/value pairs. /// </summary> /// <docgen category='Rendering Options' order='10' /> public string Separator { get; set; } /// <summary> /// Get or set if empty values should be included. /// /// A value is empty when null or in case of a string, null or empty string. /// </summary> /// <docgen category='Rendering Options' order='10' /> [DefaultValue(false)] public bool IncludeEmptyValues { get; set; } = false; /// <summary> /// Gets or sets the keys to exclude from the output. If omitted, none are excluded. /// </summary> /// <docgen category='Rendering Options' order='10' /> #if NET3_5 public HashSet<string> Exclude { get; set; } #else public ISet<string> Exclude { get; set; } #endif #if NET4_5 /// <summary> /// Also render the caller information attributes? (<see cref="System.Runtime.CompilerServices.CallerMemberNameAttribute"/>, /// <see cref="System.Runtime.CompilerServices.CallerFilePathAttribute"/>, <see cref="System.Runtime.CompilerServices.CallerLineNumberAttribute"/>). /// /// See https://msdn.microsoft.com/en-us/library/hh534540.aspx /// </summary> /// <docgen category='Rendering Options' order='10' /> [Obsolete("Instead use the Exclude-property. Marked obsolete on NLog 4.6.8")] [DefaultValue(false)] public bool IncludeCallerInformation { get => Exclude?.Contains(CallerInformationAttributeNames[0]) != true; set { if (!value) { if (Exclude == null) { Exclude = new HashSet<string>(CallerInformationAttributeNames, StringComparer.OrdinalIgnoreCase); } else { foreach (var item in CallerInformationAttributeNames) Exclude.Add(item); } } else if (Exclude?.Count > 0) { foreach (var item in CallerInformationAttributeNames) Exclude.Remove(item); } } } #endif /// <summary> /// Gets or sets how key/value pairs will be formatted. /// </summary> /// <docgen category='Rendering Options' order='10' /> public string Format { get => _format; set { if (!value.Contains("[key]")) throw new ArgumentException("Invalid format: [key] placeholder is missing."); if (!value.Contains("[value]")) throw new ArgumentException("Invalid format: [value] placeholder is missing."); _format = value; var formatSplit = _format.Split(new[] { "[key]", "[value]" }, StringSplitOptions.None); if (formatSplit.Length == 3) { _beforeKey = formatSplit[0]; _afterKey = formatSplit[1]; _afterValue = formatSplit[2]; } else { _beforeKey = null; _afterKey = null; _afterValue = null; } } } /// <summary> /// Renders all log event's properties and appends them to the specified <see cref="StringBuilder" />. /// </summary> /// <param name="builder">The <see cref="StringBuilder"/> to append the rendered data to.</param> /// <param name="logEvent">Logging event.</param> protected override void Append(StringBuilder builder, LogEventInfo logEvent) { if (!logEvent.HasProperties) return; var formatProvider = GetFormatProvider(logEvent); bool checkForExclude = CheckForExclude(logEvent); bool nonStandardFormat = _beforeKey == null || _afterKey == null || _afterValue == null; bool first = true; foreach (var property in logEvent.Properties) { if (!IncludeEmptyValues && IsEmptyPropertyValue(property.Value)) continue; if (checkForExclude && property.Key is string propertyKey && Exclude.Contains(propertyKey)) continue; if (!first) { builder.Append(Separator); } first = false; if (nonStandardFormat) { var key = Convert.ToString(property.Key, formatProvider); var value = Convert.ToString(property.Value, formatProvider); var pair = Format.Replace("[key]", key) .Replace("[value]", value); builder.Append(pair); } else { builder.Append(_beforeKey); builder.AppendFormattedValue(property.Key, null, formatProvider); builder.Append(_afterKey); builder.AppendFormattedValue(property.Value, null, formatProvider); builder.Append(_afterValue); } } } private bool CheckForExclude(LogEventInfo logEvent) { bool checkForExclude = Exclude?.Count > 0; #if NET4_5 if (checkForExclude) { // Skip Exclude check when only to exclude CallSiteInformation, and there is none checkForExclude = !(logEvent.CallSiteInformation == null && Exclude.Count == CallerInformationAttributeNames.Length && Exclude.Contains(CallerInformationAttributeNames[0])); } #endif return checkForExclude; } private static bool IsEmptyPropertyValue(object value) { if (value is string s) { return string.IsNullOrEmpty(s); } return value == null; } #if NET4_5 /// <summary> /// The names of caller information attributes. /// <see cref="System.Runtime.CompilerServices.CallerMemberNameAttribute"/>, <see cref="System.Runtime.CompilerServices.CallerFilePathAttribute"/>, <see cref="System.Runtime.CompilerServices.CallerLineNumberAttribute"/>). /// https://msdn.microsoft.com/en-us/library/hh534540.aspx /// TODO NLog ver. 5 - Remove these properties /// </summary> private static string[] CallerInformationAttributeNames = { "CallerMemberName", "CallerFilePath", "CallerLineNumber", }; #endif } }
namespace java.sql { [global::MonoJavaBridge.JavaInterface(typeof(global::java.sql.PreparedStatement_))] public partial interface PreparedStatement : Statement { void setBoolean(int arg0, bool arg1); void setByte(int arg0, byte arg1); void setShort(int arg0, short arg1); void setInt(int arg0, int arg1); void setLong(int arg0, long arg1); void setFloat(int arg0, float arg1); void setDouble(int arg0, double arg1); void setTimestamp(int arg0, java.sql.Timestamp arg1); void setTimestamp(int arg0, java.sql.Timestamp arg1, java.util.Calendar arg2); void setURL(int arg0, java.net.URL arg1); void setTime(int arg0, java.sql.Time arg1, java.util.Calendar arg2); void setTime(int arg0, java.sql.Time arg1); void setDate(int arg0, java.sql.Date arg1, java.util.Calendar arg2); void setDate(int arg0, java.sql.Date arg1); bool execute(); void addBatch(); void setString(int arg0, java.lang.String arg1); void setObject(int arg0, java.lang.Object arg1, int arg2); void setObject(int arg0, java.lang.Object arg1, int arg2, int arg3); void setObject(int arg0, java.lang.Object arg1); global::java.sql.ResultSetMetaData getMetaData(); void setBytes(int arg0, byte[] arg1); void setBinaryStream(int arg0, java.io.InputStream arg1); void setBinaryStream(int arg0, java.io.InputStream arg1, int arg2); void setBinaryStream(int arg0, java.io.InputStream arg1, long arg2); void setNull(int arg0, int arg1, java.lang.String arg2); void setNull(int arg0, int arg1); void setBigDecimal(int arg0, java.math.BigDecimal arg1); void setAsciiStream(int arg0, java.io.InputStream arg1, int arg2); void setAsciiStream(int arg0, java.io.InputStream arg1); void setAsciiStream(int arg0, java.io.InputStream arg1, long arg2); void setCharacterStream(int arg0, java.io.Reader arg1, int arg2); void setCharacterStream(int arg0, java.io.Reader arg1, long arg2); void setCharacterStream(int arg0, java.io.Reader arg1); void setNString(int arg0, java.lang.String arg1); void setNCharacterStream(int arg0, java.io.Reader arg1, long arg2); void setNCharacterStream(int arg0, java.io.Reader arg1); void setNClob(int arg0, java.io.Reader arg1); void setNClob(int arg0, java.io.Reader arg1, long arg2); void setClob(int arg0, java.sql.Clob arg1); void setClob(int arg0, java.io.Reader arg1, long arg2); void setClob(int arg0, java.io.Reader arg1); void setBlob(int arg0, java.sql.Blob arg1); void setBlob(int arg0, java.io.InputStream arg1, long arg2); void setBlob(int arg0, java.io.InputStream arg1); global::java.sql.ResultSet executeQuery(); int executeUpdate(); void setUnicodeStream(int arg0, java.io.InputStream arg1, int arg2); void clearParameters(); void setRef(int arg0, java.sql.Ref arg1); void setArray(int arg0, java.sql.Array arg1); global::java.sql.ParameterMetaData getParameterMetaData(); } [global::MonoJavaBridge.JavaProxy(typeof(global::java.sql.PreparedStatement))] internal sealed partial class PreparedStatement_ : java.lang.Object, PreparedStatement { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; internal PreparedStatement_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } private static global::MonoJavaBridge.MethodId _m0; void java.sql.PreparedStatement.setBoolean(int arg0, bool arg1) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.sql.PreparedStatement_.staticClass, "setBoolean", "(IZ)V", ref global::java.sql.PreparedStatement_._m0, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m1; void java.sql.PreparedStatement.setByte(int arg0, byte arg1) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.sql.PreparedStatement_.staticClass, "setByte", "(IB)V", ref global::java.sql.PreparedStatement_._m1, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m2; void java.sql.PreparedStatement.setShort(int arg0, short arg1) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.sql.PreparedStatement_.staticClass, "setShort", "(IS)V", ref global::java.sql.PreparedStatement_._m2, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m3; void java.sql.PreparedStatement.setInt(int arg0, int arg1) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.sql.PreparedStatement_.staticClass, "setInt", "(II)V", ref global::java.sql.PreparedStatement_._m3, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m4; void java.sql.PreparedStatement.setLong(int arg0, long arg1) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.sql.PreparedStatement_.staticClass, "setLong", "(IJ)V", ref global::java.sql.PreparedStatement_._m4, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m5; void java.sql.PreparedStatement.setFloat(int arg0, float arg1) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.sql.PreparedStatement_.staticClass, "setFloat", "(IF)V", ref global::java.sql.PreparedStatement_._m5, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m6; void java.sql.PreparedStatement.setDouble(int arg0, double arg1) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.sql.PreparedStatement_.staticClass, "setDouble", "(ID)V", ref global::java.sql.PreparedStatement_._m6, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m7; void java.sql.PreparedStatement.setTimestamp(int arg0, java.sql.Timestamp arg1) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.sql.PreparedStatement_.staticClass, "setTimestamp", "(ILjava/sql/Timestamp;)V", ref global::java.sql.PreparedStatement_._m7, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m8; void java.sql.PreparedStatement.setTimestamp(int arg0, java.sql.Timestamp arg1, java.util.Calendar arg2) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.sql.PreparedStatement_.staticClass, "setTimestamp", "(ILjava/sql/Timestamp;Ljava/util/Calendar;)V", ref global::java.sql.PreparedStatement_._m8, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } private static global::MonoJavaBridge.MethodId _m9; void java.sql.PreparedStatement.setURL(int arg0, java.net.URL arg1) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.sql.PreparedStatement_.staticClass, "setURL", "(ILjava/net/URL;)V", ref global::java.sql.PreparedStatement_._m9, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m10; void java.sql.PreparedStatement.setTime(int arg0, java.sql.Time arg1, java.util.Calendar arg2) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.sql.PreparedStatement_.staticClass, "setTime", "(ILjava/sql/Time;Ljava/util/Calendar;)V", ref global::java.sql.PreparedStatement_._m10, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } private static global::MonoJavaBridge.MethodId _m11; void java.sql.PreparedStatement.setTime(int arg0, java.sql.Time arg1) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.sql.PreparedStatement_.staticClass, "setTime", "(ILjava/sql/Time;)V", ref global::java.sql.PreparedStatement_._m11, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m12; void java.sql.PreparedStatement.setDate(int arg0, java.sql.Date arg1, java.util.Calendar arg2) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.sql.PreparedStatement_.staticClass, "setDate", "(ILjava/sql/Date;Ljava/util/Calendar;)V", ref global::java.sql.PreparedStatement_._m12, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } private static global::MonoJavaBridge.MethodId _m13; void java.sql.PreparedStatement.setDate(int arg0, java.sql.Date arg1) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.sql.PreparedStatement_.staticClass, "setDate", "(ILjava/sql/Date;)V", ref global::java.sql.PreparedStatement_._m13, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m14; bool java.sql.PreparedStatement.execute() { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::java.sql.PreparedStatement_.staticClass, "execute", "()Z", ref global::java.sql.PreparedStatement_._m14); } private static global::MonoJavaBridge.MethodId _m15; void java.sql.PreparedStatement.addBatch() { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.sql.PreparedStatement_.staticClass, "addBatch", "()V", ref global::java.sql.PreparedStatement_._m15); } private static global::MonoJavaBridge.MethodId _m16; void java.sql.PreparedStatement.setString(int arg0, java.lang.String arg1) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.sql.PreparedStatement_.staticClass, "setString", "(ILjava/lang/String;)V", ref global::java.sql.PreparedStatement_._m16, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m17; void java.sql.PreparedStatement.setObject(int arg0, java.lang.Object arg1, int arg2) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.sql.PreparedStatement_.staticClass, "setObject", "(ILjava/lang/Object;I)V", ref global::java.sql.PreparedStatement_._m17, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } private static global::MonoJavaBridge.MethodId _m18; void java.sql.PreparedStatement.setObject(int arg0, java.lang.Object arg1, int arg2, int arg3) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.sql.PreparedStatement_.staticClass, "setObject", "(ILjava/lang/Object;II)V", ref global::java.sql.PreparedStatement_._m18, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3)); } private static global::MonoJavaBridge.MethodId _m19; void java.sql.PreparedStatement.setObject(int arg0, java.lang.Object arg1) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.sql.PreparedStatement_.staticClass, "setObject", "(ILjava/lang/Object;)V", ref global::java.sql.PreparedStatement_._m19, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m20; global::java.sql.ResultSetMetaData java.sql.PreparedStatement.getMetaData() { return global::MonoJavaBridge.JavaBridge.CallIJavaObjectMethod<java.sql.ResultSetMetaData>(this, global::java.sql.PreparedStatement_.staticClass, "getMetaData", "()Ljava/sql/ResultSetMetaData;", ref global::java.sql.PreparedStatement_._m20) as java.sql.ResultSetMetaData; } private static global::MonoJavaBridge.MethodId _m21; void java.sql.PreparedStatement.setBytes(int arg0, byte[] arg1) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.sql.PreparedStatement_.staticClass, "setBytes", "(I[B)V", ref global::java.sql.PreparedStatement_._m21, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m22; void java.sql.PreparedStatement.setBinaryStream(int arg0, java.io.InputStream arg1) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.sql.PreparedStatement_.staticClass, "setBinaryStream", "(ILjava/io/InputStream;)V", ref global::java.sql.PreparedStatement_._m22, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m23; void java.sql.PreparedStatement.setBinaryStream(int arg0, java.io.InputStream arg1, int arg2) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.sql.PreparedStatement_.staticClass, "setBinaryStream", "(ILjava/io/InputStream;I)V", ref global::java.sql.PreparedStatement_._m23, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } private static global::MonoJavaBridge.MethodId _m24; void java.sql.PreparedStatement.setBinaryStream(int arg0, java.io.InputStream arg1, long arg2) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.sql.PreparedStatement_.staticClass, "setBinaryStream", "(ILjava/io/InputStream;J)V", ref global::java.sql.PreparedStatement_._m24, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } private static global::MonoJavaBridge.MethodId _m25; void java.sql.PreparedStatement.setNull(int arg0, int arg1, java.lang.String arg2) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.sql.PreparedStatement_.staticClass, "setNull", "(IILjava/lang/String;)V", ref global::java.sql.PreparedStatement_._m25, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } private static global::MonoJavaBridge.MethodId _m26; void java.sql.PreparedStatement.setNull(int arg0, int arg1) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.sql.PreparedStatement_.staticClass, "setNull", "(II)V", ref global::java.sql.PreparedStatement_._m26, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m27; void java.sql.PreparedStatement.setBigDecimal(int arg0, java.math.BigDecimal arg1) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.sql.PreparedStatement_.staticClass, "setBigDecimal", "(ILjava/math/BigDecimal;)V", ref global::java.sql.PreparedStatement_._m27, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m28; void java.sql.PreparedStatement.setAsciiStream(int arg0, java.io.InputStream arg1, int arg2) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.sql.PreparedStatement_.staticClass, "setAsciiStream", "(ILjava/io/InputStream;I)V", ref global::java.sql.PreparedStatement_._m28, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } private static global::MonoJavaBridge.MethodId _m29; void java.sql.PreparedStatement.setAsciiStream(int arg0, java.io.InputStream arg1) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.sql.PreparedStatement_.staticClass, "setAsciiStream", "(ILjava/io/InputStream;)V", ref global::java.sql.PreparedStatement_._m29, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m30; void java.sql.PreparedStatement.setAsciiStream(int arg0, java.io.InputStream arg1, long arg2) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.sql.PreparedStatement_.staticClass, "setAsciiStream", "(ILjava/io/InputStream;J)V", ref global::java.sql.PreparedStatement_._m30, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } private static global::MonoJavaBridge.MethodId _m31; void java.sql.PreparedStatement.setCharacterStream(int arg0, java.io.Reader arg1, int arg2) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.sql.PreparedStatement_.staticClass, "setCharacterStream", "(ILjava/io/Reader;I)V", ref global::java.sql.PreparedStatement_._m31, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } private static global::MonoJavaBridge.MethodId _m32; void java.sql.PreparedStatement.setCharacterStream(int arg0, java.io.Reader arg1, long arg2) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.sql.PreparedStatement_.staticClass, "setCharacterStream", "(ILjava/io/Reader;J)V", ref global::java.sql.PreparedStatement_._m32, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } private static global::MonoJavaBridge.MethodId _m33; void java.sql.PreparedStatement.setCharacterStream(int arg0, java.io.Reader arg1) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.sql.PreparedStatement_.staticClass, "setCharacterStream", "(ILjava/io/Reader;)V", ref global::java.sql.PreparedStatement_._m33, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m34; void java.sql.PreparedStatement.setNString(int arg0, java.lang.String arg1) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.sql.PreparedStatement_.staticClass, "setNString", "(ILjava/lang/String;)V", ref global::java.sql.PreparedStatement_._m34, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m35; void java.sql.PreparedStatement.setNCharacterStream(int arg0, java.io.Reader arg1, long arg2) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.sql.PreparedStatement_.staticClass, "setNCharacterStream", "(ILjava/io/Reader;J)V", ref global::java.sql.PreparedStatement_._m35, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } private static global::MonoJavaBridge.MethodId _m36; void java.sql.PreparedStatement.setNCharacterStream(int arg0, java.io.Reader arg1) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.sql.PreparedStatement_.staticClass, "setNCharacterStream", "(ILjava/io/Reader;)V", ref global::java.sql.PreparedStatement_._m36, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m37; void java.sql.PreparedStatement.setNClob(int arg0, java.io.Reader arg1) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.sql.PreparedStatement_.staticClass, "setNClob", "(ILjava/io/Reader;)V", ref global::java.sql.PreparedStatement_._m37, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m38; void java.sql.PreparedStatement.setNClob(int arg0, java.io.Reader arg1, long arg2) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.sql.PreparedStatement_.staticClass, "setNClob", "(ILjava/io/Reader;J)V", ref global::java.sql.PreparedStatement_._m38, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } private static global::MonoJavaBridge.MethodId _m39; void java.sql.PreparedStatement.setClob(int arg0, java.sql.Clob arg1) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.sql.PreparedStatement_.staticClass, "setClob", "(ILjava/sql/Clob;)V", ref global::java.sql.PreparedStatement_._m39, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m40; void java.sql.PreparedStatement.setClob(int arg0, java.io.Reader arg1, long arg2) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.sql.PreparedStatement_.staticClass, "setClob", "(ILjava/io/Reader;J)V", ref global::java.sql.PreparedStatement_._m40, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } private static global::MonoJavaBridge.MethodId _m41; void java.sql.PreparedStatement.setClob(int arg0, java.io.Reader arg1) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.sql.PreparedStatement_.staticClass, "setClob", "(ILjava/io/Reader;)V", ref global::java.sql.PreparedStatement_._m41, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m42; void java.sql.PreparedStatement.setBlob(int arg0, java.sql.Blob arg1) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.sql.PreparedStatement_.staticClass, "setBlob", "(ILjava/sql/Blob;)V", ref global::java.sql.PreparedStatement_._m42, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m43; void java.sql.PreparedStatement.setBlob(int arg0, java.io.InputStream arg1, long arg2) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.sql.PreparedStatement_.staticClass, "setBlob", "(ILjava/io/InputStream;J)V", ref global::java.sql.PreparedStatement_._m43, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } private static global::MonoJavaBridge.MethodId _m44; void java.sql.PreparedStatement.setBlob(int arg0, java.io.InputStream arg1) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.sql.PreparedStatement_.staticClass, "setBlob", "(ILjava/io/InputStream;)V", ref global::java.sql.PreparedStatement_._m44, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m45; global::java.sql.ResultSet java.sql.PreparedStatement.executeQuery() { return global::MonoJavaBridge.JavaBridge.CallIJavaObjectMethod<java.sql.ResultSet>(this, global::java.sql.PreparedStatement_.staticClass, "executeQuery", "()Ljava/sql/ResultSet;", ref global::java.sql.PreparedStatement_._m45) as java.sql.ResultSet; } private static global::MonoJavaBridge.MethodId _m46; int java.sql.PreparedStatement.executeUpdate() { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::java.sql.PreparedStatement_.staticClass, "executeUpdate", "()I", ref global::java.sql.PreparedStatement_._m46); } private static global::MonoJavaBridge.MethodId _m47; void java.sql.PreparedStatement.setUnicodeStream(int arg0, java.io.InputStream arg1, int arg2) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.sql.PreparedStatement_.staticClass, "setUnicodeStream", "(ILjava/io/InputStream;I)V", ref global::java.sql.PreparedStatement_._m47, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } private static global::MonoJavaBridge.MethodId _m48; void java.sql.PreparedStatement.clearParameters() { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.sql.PreparedStatement_.staticClass, "clearParameters", "()V", ref global::java.sql.PreparedStatement_._m48); } private static global::MonoJavaBridge.MethodId _m49; void java.sql.PreparedStatement.setRef(int arg0, java.sql.Ref arg1) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.sql.PreparedStatement_.staticClass, "setRef", "(ILjava/sql/Ref;)V", ref global::java.sql.PreparedStatement_._m49, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m50; void java.sql.PreparedStatement.setArray(int arg0, java.sql.Array arg1) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.sql.PreparedStatement_.staticClass, "setArray", "(ILjava/sql/Array;)V", ref global::java.sql.PreparedStatement_._m50, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m51; global::java.sql.ParameterMetaData java.sql.PreparedStatement.getParameterMetaData() { return global::MonoJavaBridge.JavaBridge.CallIJavaObjectMethod<java.sql.ParameterMetaData>(this, global::java.sql.PreparedStatement_.staticClass, "getParameterMetaData", "()Ljava/sql/ParameterMetaData;", ref global::java.sql.PreparedStatement_._m51) as java.sql.ParameterMetaData; } private static global::MonoJavaBridge.MethodId _m52; void java.sql.Statement.close() { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.sql.PreparedStatement_.staticClass, "close", "()V", ref global::java.sql.PreparedStatement_._m52); } private static global::MonoJavaBridge.MethodId _m53; bool java.sql.Statement.isClosed() { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::java.sql.PreparedStatement_.staticClass, "isClosed", "()Z", ref global::java.sql.PreparedStatement_._m53); } private static global::MonoJavaBridge.MethodId _m54; bool java.sql.Statement.execute(java.lang.String arg0, int[] arg1) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::java.sql.PreparedStatement_.staticClass, "execute", "(Ljava/lang/String;[I)Z", ref global::java.sql.PreparedStatement_._m54, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m55; bool java.sql.Statement.execute(java.lang.String arg0, int arg1) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::java.sql.PreparedStatement_.staticClass, "execute", "(Ljava/lang/String;I)Z", ref global::java.sql.PreparedStatement_._m55, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m56; bool java.sql.Statement.execute(java.lang.String arg0) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::java.sql.PreparedStatement_.staticClass, "execute", "(Ljava/lang/String;)Z", ref global::java.sql.PreparedStatement_._m56, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m57; bool java.sql.Statement.execute(java.lang.String arg0, java.lang.String[] arg1) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::java.sql.PreparedStatement_.staticClass, "execute", "(Ljava/lang/String;[Ljava/lang/String;)Z", ref global::java.sql.PreparedStatement_._m57, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m58; void java.sql.Statement.cancel() { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.sql.PreparedStatement_.staticClass, "cancel", "()V", ref global::java.sql.PreparedStatement_._m58); } private static global::MonoJavaBridge.MethodId _m59; void java.sql.Statement.addBatch(java.lang.String arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.sql.PreparedStatement_.staticClass, "addBatch", "(Ljava/lang/String;)V", ref global::java.sql.PreparedStatement_._m59, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m60; global::java.sql.Connection java.sql.Statement.getConnection() { return global::MonoJavaBridge.JavaBridge.CallIJavaObjectMethod<java.sql.Connection>(this, global::java.sql.PreparedStatement_.staticClass, "getConnection", "()Ljava/sql/Connection;", ref global::java.sql.PreparedStatement_._m60) as java.sql.Connection; } private static global::MonoJavaBridge.MethodId _m61; global::java.sql.ResultSet java.sql.Statement.getResultSet() { return global::MonoJavaBridge.JavaBridge.CallIJavaObjectMethod<java.sql.ResultSet>(this, global::java.sql.PreparedStatement_.staticClass, "getResultSet", "()Ljava/sql/ResultSet;", ref global::java.sql.PreparedStatement_._m61) as java.sql.ResultSet; } private static global::MonoJavaBridge.MethodId _m62; global::java.sql.SQLWarning java.sql.Statement.getWarnings() { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.sql.PreparedStatement_.staticClass, "getWarnings", "()Ljava/sql/SQLWarning;", ref global::java.sql.PreparedStatement_._m62) as java.sql.SQLWarning; } private static global::MonoJavaBridge.MethodId _m63; void java.sql.Statement.clearWarnings() { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.sql.PreparedStatement_.staticClass, "clearWarnings", "()V", ref global::java.sql.PreparedStatement_._m63); } private static global::MonoJavaBridge.MethodId _m64; void java.sql.Statement.setFetchDirection(int arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.sql.PreparedStatement_.staticClass, "setFetchDirection", "(I)V", ref global::java.sql.PreparedStatement_._m64, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m65; int java.sql.Statement.getFetchDirection() { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::java.sql.PreparedStatement_.staticClass, "getFetchDirection", "()I", ref global::java.sql.PreparedStatement_._m65); } private static global::MonoJavaBridge.MethodId _m66; void java.sql.Statement.setFetchSize(int arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.sql.PreparedStatement_.staticClass, "setFetchSize", "(I)V", ref global::java.sql.PreparedStatement_._m66, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m67; int java.sql.Statement.getFetchSize() { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::java.sql.PreparedStatement_.staticClass, "getFetchSize", "()I", ref global::java.sql.PreparedStatement_._m67); } private static global::MonoJavaBridge.MethodId _m68; global::java.sql.ResultSet java.sql.Statement.executeQuery(java.lang.String arg0) { return global::MonoJavaBridge.JavaBridge.CallIJavaObjectMethod<java.sql.ResultSet>(this, global::java.sql.PreparedStatement_.staticClass, "executeQuery", "(Ljava/lang/String;)Ljava/sql/ResultSet;", ref global::java.sql.PreparedStatement_._m68, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as java.sql.ResultSet; } private static global::MonoJavaBridge.MethodId _m69; int java.sql.Statement.executeUpdate(java.lang.String arg0, int arg1) { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::java.sql.PreparedStatement_.staticClass, "executeUpdate", "(Ljava/lang/String;I)I", ref global::java.sql.PreparedStatement_._m69, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m70; int java.sql.Statement.executeUpdate(java.lang.String arg0, int[] arg1) { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::java.sql.PreparedStatement_.staticClass, "executeUpdate", "(Ljava/lang/String;[I)I", ref global::java.sql.PreparedStatement_._m70, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m71; int java.sql.Statement.executeUpdate(java.lang.String arg0) { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::java.sql.PreparedStatement_.staticClass, "executeUpdate", "(Ljava/lang/String;)I", ref global::java.sql.PreparedStatement_._m71, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m72; int java.sql.Statement.executeUpdate(java.lang.String arg0, java.lang.String[] arg1) { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::java.sql.PreparedStatement_.staticClass, "executeUpdate", "(Ljava/lang/String;[Ljava/lang/String;)I", ref global::java.sql.PreparedStatement_._m72, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m73; int java.sql.Statement.getMaxFieldSize() { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::java.sql.PreparedStatement_.staticClass, "getMaxFieldSize", "()I", ref global::java.sql.PreparedStatement_._m73); } private static global::MonoJavaBridge.MethodId _m74; void java.sql.Statement.setMaxFieldSize(int arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.sql.PreparedStatement_.staticClass, "setMaxFieldSize", "(I)V", ref global::java.sql.PreparedStatement_._m74, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m75; int java.sql.Statement.getMaxRows() { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::java.sql.PreparedStatement_.staticClass, "getMaxRows", "()I", ref global::java.sql.PreparedStatement_._m75); } private static global::MonoJavaBridge.MethodId _m76; void java.sql.Statement.setMaxRows(int arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.sql.PreparedStatement_.staticClass, "setMaxRows", "(I)V", ref global::java.sql.PreparedStatement_._m76, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m77; void java.sql.Statement.setEscapeProcessing(bool arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.sql.PreparedStatement_.staticClass, "setEscapeProcessing", "(Z)V", ref global::java.sql.PreparedStatement_._m77, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m78; int java.sql.Statement.getQueryTimeout() { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::java.sql.PreparedStatement_.staticClass, "getQueryTimeout", "()I", ref global::java.sql.PreparedStatement_._m78); } private static global::MonoJavaBridge.MethodId _m79; void java.sql.Statement.setQueryTimeout(int arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.sql.PreparedStatement_.staticClass, "setQueryTimeout", "(I)V", ref global::java.sql.PreparedStatement_._m79, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m80; void java.sql.Statement.setCursorName(java.lang.String arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.sql.PreparedStatement_.staticClass, "setCursorName", "(Ljava/lang/String;)V", ref global::java.sql.PreparedStatement_._m80, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m81; int java.sql.Statement.getUpdateCount() { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::java.sql.PreparedStatement_.staticClass, "getUpdateCount", "()I", ref global::java.sql.PreparedStatement_._m81); } private static global::MonoJavaBridge.MethodId _m82; bool java.sql.Statement.getMoreResults() { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::java.sql.PreparedStatement_.staticClass, "getMoreResults", "()Z", ref global::java.sql.PreparedStatement_._m82); } private static global::MonoJavaBridge.MethodId _m83; bool java.sql.Statement.getMoreResults(int arg0) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::java.sql.PreparedStatement_.staticClass, "getMoreResults", "(I)Z", ref global::java.sql.PreparedStatement_._m83, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m84; int java.sql.Statement.getResultSetConcurrency() { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::java.sql.PreparedStatement_.staticClass, "getResultSetConcurrency", "()I", ref global::java.sql.PreparedStatement_._m84); } private static global::MonoJavaBridge.MethodId _m85; int java.sql.Statement.getResultSetType() { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::java.sql.PreparedStatement_.staticClass, "getResultSetType", "()I", ref global::java.sql.PreparedStatement_._m85); } private static global::MonoJavaBridge.MethodId _m86; void java.sql.Statement.clearBatch() { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.sql.PreparedStatement_.staticClass, "clearBatch", "()V", ref global::java.sql.PreparedStatement_._m86); } private static global::MonoJavaBridge.MethodId _m87; int[] java.sql.Statement.executeBatch() { return global::MonoJavaBridge.JavaBridge.CallArrayObjectMethod<int>(this, global::java.sql.PreparedStatement_.staticClass, "executeBatch", "()[I", ref global::java.sql.PreparedStatement_._m87) as int[]; } private static global::MonoJavaBridge.MethodId _m88; global::java.sql.ResultSet java.sql.Statement.getGeneratedKeys() { return global::MonoJavaBridge.JavaBridge.CallIJavaObjectMethod<java.sql.ResultSet>(this, global::java.sql.PreparedStatement_.staticClass, "getGeneratedKeys", "()Ljava/sql/ResultSet;", ref global::java.sql.PreparedStatement_._m88) as java.sql.ResultSet; } private static global::MonoJavaBridge.MethodId _m89; int java.sql.Statement.getResultSetHoldability() { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::java.sql.PreparedStatement_.staticClass, "getResultSetHoldability", "()I", ref global::java.sql.PreparedStatement_._m89); } private static global::MonoJavaBridge.MethodId _m90; void java.sql.Statement.setPoolable(bool arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.sql.PreparedStatement_.staticClass, "setPoolable", "(Z)V", ref global::java.sql.PreparedStatement_._m90, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m91; bool java.sql.Statement.isPoolable() { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::java.sql.PreparedStatement_.staticClass, "isPoolable", "()Z", ref global::java.sql.PreparedStatement_._m91); } static PreparedStatement_() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::java.sql.PreparedStatement_.staticClass = @__env.NewGlobalRef(@__env.FindClass("java/sql/PreparedStatement")); } } }
//------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. //------------------------------------------------------------ namespace System.ServiceModel.Channels { using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Globalization; using System.IdentityModel.Policy; using System.IdentityModel.Selectors; using System.IdentityModel.Tokens; using System.IO; using System.Net; using System.Net.Http; using System.Net.WebSockets; using System.Runtime; using System.Runtime.CompilerServices; using System.Runtime.Diagnostics; using System.Security.Authentication.ExtendedProtection; using System.Security.Cryptography.X509Certificates; using System.Security.Principal; using System.ServiceModel; using System.ServiceModel.Activation; using System.ServiceModel.Description; using System.ServiceModel.Diagnostics; using System.ServiceModel.Diagnostics.Application; using System.ServiceModel.Dispatcher; using System.ServiceModel.Security; using System.ServiceModel.Security.Tokens; using System.Threading; using System.Threading.Tasks; using System.Xml; abstract class HttpChannelListener : TransportChannelListener, IHttpTransportFactorySettings { AuthenticationSchemes authenticationScheme; bool extractGroupsForWindowsAccounts; EndpointIdentity identity; bool keepAliveEnabled; int maxBufferSize; readonly int maxPendingAccepts; string method; string realm; readonly TimeSpan requestInitializationTimeout; TransferMode transferMode; bool unsafeConnectionNtlmAuthentication; ISecurityCapabilities securityCapabilities; SecurityCredentialsManager credentialProvider; SecurityTokenAuthenticator userNameTokenAuthenticator; SecurityTokenAuthenticator windowsTokenAuthenticator; ExtendedProtectionPolicy extendedProtectionPolicy; bool usingDefaultSpnList; HttpAnonymousUriPrefixMatcher anonymousUriPrefixMatcher; HttpMessageSettings httpMessageSettings; WebSocketTransportSettings webSocketSettings; static UriPrefixTable<ITransportManagerRegistration> transportManagerTable = new UriPrefixTable<ITransportManagerRegistration>(true); public HttpChannelListener(HttpTransportBindingElement bindingElement, BindingContext context) : base(bindingElement, context, HttpTransportDefaults.GetDefaultMessageEncoderFactory(), bindingElement.HostNameComparisonMode) { if (bindingElement.TransferMode == TransferMode.Buffered) { if (bindingElement.MaxReceivedMessageSize > int.MaxValue) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new ArgumentOutOfRangeException("bindingElement.MaxReceivedMessageSize", SR.GetString(SR.MaxReceivedMessageSizeMustBeInIntegerRange))); } if (bindingElement.MaxBufferSize != bindingElement.MaxReceivedMessageSize) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("bindingElement", SR.GetString(SR.MaxBufferSizeMustMatchMaxReceivedMessageSize)); } } else { if (bindingElement.MaxBufferSize > bindingElement.MaxReceivedMessageSize) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("bindingElement", SR.GetString(SR.MaxBufferSizeMustNotExceedMaxReceivedMessageSize)); } } if (bindingElement.AuthenticationScheme.IsSet(AuthenticationSchemes.Basic) && bindingElement.AuthenticationScheme.IsNotSet(AuthenticationSchemes.Digest | AuthenticationSchemes.Ntlm | AuthenticationSchemes.Negotiate) && bindingElement.ExtendedProtectionPolicy.PolicyEnforcement == PolicyEnforcement.Always) { //Basic auth + PolicyEnforcement.Always doesn't make sense because basic auth can't support CBT. throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString(SR.ExtendedProtectionPolicyBasicAuthNotSupported))); } this.authenticationScheme = bindingElement.AuthenticationScheme; this.keepAliveEnabled = bindingElement.KeepAliveEnabled; this.InheritBaseAddressSettings = bindingElement.InheritBaseAddressSettings; this.maxBufferSize = bindingElement.MaxBufferSize; this.maxPendingAccepts = HttpTransportDefaults.GetEffectiveMaxPendingAccepts(bindingElement.MaxPendingAccepts); this.method = bindingElement.Method; this.realm = bindingElement.Realm; this.requestInitializationTimeout = bindingElement.RequestInitializationTimeout; this.transferMode = bindingElement.TransferMode; this.unsafeConnectionNtlmAuthentication = bindingElement.UnsafeConnectionNtlmAuthentication; this.credentialProvider = context.BindingParameters.Find<SecurityCredentialsManager>(); this.securityCapabilities = bindingElement.GetProperty<ISecurityCapabilities>(context); this.extendedProtectionPolicy = GetPolicyWithDefaultSpnCollection(bindingElement.ExtendedProtectionPolicy, this.authenticationScheme, this.HostNameComparisonModeInternal, base.Uri, out this.usingDefaultSpnList); this.webSocketSettings = WebSocketHelper.GetRuntimeWebSocketSettings(bindingElement.WebSocketSettings); if (bindingElement.AnonymousUriPrefixMatcher != null) { this.anonymousUriPrefixMatcher = new HttpAnonymousUriPrefixMatcher(bindingElement.AnonymousUriPrefixMatcher); } this.httpMessageSettings = context.BindingParameters.Find<HttpMessageSettings>() ?? new HttpMessageSettings(); if (this.httpMessageSettings.HttpMessagesSupported && this.MessageVersion != MessageVersion.None) { throw FxTrace.Exception.AsError( new NotSupportedException(SR.GetString( SR.MessageVersionNoneRequiredForHttpMessageSupport, typeof(HttpRequestMessage).Name, typeof(HttpResponseMessage).Name, typeof(HttpMessageSettings).Name, typeof(MessageVersion).Name, typeof(MessageEncodingBindingElement).Name, this.MessageVersion.ToString(), MessageVersion.None.ToString()))); } } public TimeSpan RequestInitializationTimeout { get { return this.requestInitializationTimeout; } } public WebSocketTransportSettings WebSocketSettings { get { return this.webSocketSettings; } } public HttpMessageSettings HttpMessageSettings { get { return this.httpMessageSettings; } } public ExtendedProtectionPolicy ExtendedProtectionPolicy { get { return this.extendedProtectionPolicy; } } public virtual bool IsChannelBindingSupportEnabled { get { return false; } } public abstract bool UseWebSocketTransport { get; } internal HttpAnonymousUriPrefixMatcher AnonymousUriPrefixMatcher { get { return this.anonymousUriPrefixMatcher; } } protected SecurityTokenAuthenticator UserNameTokenAuthenticator { get { return this.userNameTokenAuthenticator; } } internal override void ApplyHostedContext(string virtualPath, bool isMetadataListener) { base.ApplyHostedContext(virtualPath, isMetadataListener); AspNetEnvironment.Current.ValidateHttpSettings(virtualPath, isMetadataListener, this.usingDefaultSpnList, ref this.authenticationScheme, ref this.extendedProtectionPolicy, ref this.realm); } public AuthenticationSchemes AuthenticationScheme { get { return this.authenticationScheme; } } public bool KeepAliveEnabled { get { return this.keepAliveEnabled; } } public bool ExtractGroupsForWindowsAccounts { get { return this.extractGroupsForWindowsAccounts; } } public HostNameComparisonMode HostNameComparisonMode { get { return this.HostNameComparisonModeInternal; } } //Returns true if one of the non-anonymous authentication schemes is set on this.AuthenticationScheme protected bool IsAuthenticationSupported { get { return this.authenticationScheme != AuthenticationSchemes.Anonymous; } } bool IsAuthenticationRequired { get { return this.AuthenticationScheme.IsNotSet(AuthenticationSchemes.Anonymous); } } public int MaxBufferSize { get { return this.maxBufferSize; } } public int MaxPendingAccepts { get { return this.maxPendingAccepts; } } public virtual string Method { get { return this.method; } } public TransferMode TransferMode { get { return transferMode; } } public string Realm { get { return this.realm; } } int IHttpTransportFactorySettings.MaxBufferSize { get { return MaxBufferSize; } } TransferMode IHttpTransportFactorySettings.TransferMode { get { return TransferMode; } } public override string Scheme { get { return Uri.UriSchemeHttp; } } internal static UriPrefixTable<ITransportManagerRegistration> StaticTransportManagerTable { get { return transportManagerTable; } } public bool UnsafeConnectionNtlmAuthentication { get { return this.unsafeConnectionNtlmAuthentication; } } internal override UriPrefixTable<ITransportManagerRegistration> TransportManagerTable { get { return transportManagerTable; } } internal override ITransportManagerRegistration CreateTransportManagerRegistration(Uri listenUri) { return new SharedHttpTransportManager(listenUri, this); } string GetAuthType(HttpListenerContext listenerContext) { string authType = null; IPrincipal principal = listenerContext.User; if ((principal != null) && (principal.Identity != null)) { authType = principal.Identity.AuthenticationType; } return authType; } protected string GetAuthType(IHttpAuthenticationContext authenticationContext) { string authType = null; if (authenticationContext.LogonUserIdentity != null) { authType = authenticationContext.LogonUserIdentity.AuthenticationType; } return authType; } bool IsAuthSchemeValid(string authType) { return AuthenticationSchemesHelper.DoesAuthTypeMatch(this.authenticationScheme, authType); } internal override int GetMaxBufferSize() { return MaxBufferSize; } public override T GetProperty<T>() { if (typeof(T) == typeof(EndpointIdentity)) { return (T)(object)(this.identity); } else if (typeof(T) == typeof(ILogonTokenCacheManager)) { object cacheManager = (object)GetIdentityModelProperty<T>(); if (cacheManager != null) { return (T)cacheManager; } } else if (typeof(T) == typeof(ISecurityCapabilities)) { return (T)(object)this.securityCapabilities; } else if (typeof(T) == typeof(ExtendedProtectionPolicy)) { return (T)(object)this.extendedProtectionPolicy; } return base.GetProperty<T>(); } [MethodImpl(MethodImplOptions.NoInlining)] T GetIdentityModelProperty<T>() { if (typeof(T) == typeof(EndpointIdentity)) { if (this.identity == null) { if (this.authenticationScheme.IsSet(AuthenticationSchemes.Negotiate) || this.authenticationScheme.IsSet(AuthenticationSchemes.Ntlm)) { this.identity = SecurityUtils.CreateWindowsIdentity(); } } return (T)(object)this.identity; } else if (typeof(T) == typeof(ILogonTokenCacheManager) && (this.userNameTokenAuthenticator != null)) { ILogonTokenCacheManager retVal = this.userNameTokenAuthenticator as ILogonTokenCacheManager; if (retVal != null) { return (T)(object)retVal; } } return default(T); } internal abstract IAsyncResult BeginHttpContextReceived( HttpRequestContext context, Action acceptorCallback, AsyncCallback callback, object state); internal abstract bool EndHttpContextReceived(IAsyncResult result); [MethodImpl(MethodImplOptions.NoInlining)] void InitializeSecurityTokenAuthenticator() { Fx.Assert(this.IsAuthenticationSupported, "SecurityTokenAuthenticator should only be initialized when authentication is supported."); ServiceCredentials serviceCredentials = this.credentialProvider as ServiceCredentials; if (serviceCredentials != null) { if (this.AuthenticationScheme == AuthenticationSchemes.Basic) { // when Basic authentiction is enabled - but Digest and Windows are disabled use the UsernameAuthenticationSetting this.extractGroupsForWindowsAccounts = serviceCredentials.UserNameAuthentication.IncludeWindowsGroups; } else { if (this.AuthenticationScheme.IsSet(AuthenticationSchemes.Basic) && serviceCredentials.UserNameAuthentication.IncludeWindowsGroups != serviceCredentials.WindowsAuthentication.IncludeWindowsGroups) { // Ensure there are no inconsistencies when Basic and (Digest and/or Ntlm and/or Negotiate) are both enabled throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString(SR.SecurityTokenProviderIncludeWindowsGroupsInconsistent, (AuthenticationSchemes)authenticationScheme - AuthenticationSchemes.Basic, serviceCredentials.UserNameAuthentication.IncludeWindowsGroups, serviceCredentials.WindowsAuthentication.IncludeWindowsGroups))); } this.extractGroupsForWindowsAccounts = serviceCredentials.WindowsAuthentication.IncludeWindowsGroups; } // we will only support custom and windows validation modes, if anything else is specified, we'll fall back to windows user name. if (serviceCredentials.UserNameAuthentication.UserNamePasswordValidationMode == UserNamePasswordValidationMode.Custom) { this.userNameTokenAuthenticator = new CustomUserNameSecurityTokenAuthenticator(serviceCredentials.UserNameAuthentication.GetUserNamePasswordValidator()); } else { if (serviceCredentials.UserNameAuthentication.CacheLogonTokens) { this.userNameTokenAuthenticator = new WindowsUserNameCachingSecurityTokenAuthenticator(this.extractGroupsForWindowsAccounts, serviceCredentials.UserNameAuthentication.MaxCachedLogonTokens, serviceCredentials.UserNameAuthentication.CachedLogonTokenLifetime); } else { this.userNameTokenAuthenticator = new WindowsUserNameSecurityTokenAuthenticator(this.extractGroupsForWindowsAccounts); } } } else { this.extractGroupsForWindowsAccounts = TransportDefaults.ExtractGroupsForWindowsAccounts; this.userNameTokenAuthenticator = new WindowsUserNameSecurityTokenAuthenticator(this.extractGroupsForWindowsAccounts); } this.windowsTokenAuthenticator = new WindowsSecurityTokenAuthenticator(this.extractGroupsForWindowsAccounts); } protected override void OnOpened() { base.OnOpened(); if (this.IsAuthenticationSupported) { InitializeSecurityTokenAuthenticator(); this.identity = GetIdentityModelProperty<EndpointIdentity>(); } } [MethodImpl(MethodImplOptions.NoInlining)] protected void CloseUserNameTokenAuthenticator(TimeSpan timeout) { SecurityUtils.CloseTokenAuthenticatorIfRequired(this.userNameTokenAuthenticator, timeout); } [MethodImpl(MethodImplOptions.NoInlining)] protected void AbortUserNameTokenAuthenticator() { SecurityUtils.AbortTokenAuthenticatorIfRequired(this.userNameTokenAuthenticator); } bool ShouldProcessAuthentication(IHttpAuthenticationContext authenticationContext) { Fx.Assert(authenticationContext != null, "IsAuthenticated should only be called if authenticationContext != null"); Fx.Assert(authenticationContext.LogonUserIdentity != null, "IsAuthenticated should only be called if authenticationContext.LogonUserIdentity != null"); return this.IsAuthenticationRequired || (this.IsAuthenticationSupported && authenticationContext.LogonUserIdentity.IsAuthenticated); } bool ShouldProcessAuthentication(HttpListenerContext listenerContext) { Fx.Assert(listenerContext != null, "IsAuthenticated should only be called if listenerContext != null"); Fx.Assert(listenerContext.Request != null, "IsAuthenticated should only be called if listenerContext.Request != null"); return this.IsAuthenticationRequired || (this.IsAuthenticationSupported && listenerContext.Request.IsAuthenticated); } public virtual SecurityMessageProperty ProcessAuthentication(IHttpAuthenticationContext authenticationContext) { if (this.ShouldProcessAuthentication(authenticationContext)) { SecurityMessageProperty retValue; try { retValue = this.ProcessAuthentication(authenticationContext.LogonUserIdentity, GetAuthType(authenticationContext)); } #pragma warning suppress 56500 // covered by FXCop catch (Exception exception) { if (Fx.IsFatal(exception)) throw; // Audit Authentication failure if (AuditLevel.Failure == (this.AuditBehavior.MessageAuthenticationAuditLevel & AuditLevel.Failure)) WriteAuditEvent(AuditLevel.Failure, (authenticationContext.LogonUserIdentity != null) ? authenticationContext.LogonUserIdentity.Name : String.Empty, exception); throw; } // Audit Authentication success if (AuditLevel.Success == (this.AuditBehavior.MessageAuthenticationAuditLevel & AuditLevel.Success)) WriteAuditEvent(AuditLevel.Success, (authenticationContext.LogonUserIdentity != null) ? authenticationContext.LogonUserIdentity.Name : String.Empty, null); return retValue; } else { return null; } } public virtual SecurityMessageProperty ProcessAuthentication(HttpListenerContext listenerContext) { if (this.ShouldProcessAuthentication(listenerContext)) { return this.ProcessRequiredAuthentication(listenerContext); } else { return null; } } SecurityMessageProperty ProcessRequiredAuthentication(HttpListenerContext listenerContext) { SecurityMessageProperty retValue; HttpListenerBasicIdentity identity = null; WindowsIdentity wid = null; try { Fx.Assert(listenerContext.User != null, "HttpListener delivered authenticated request without an IPrincipal."); wid = listenerContext.User.Identity as WindowsIdentity; if (this.AuthenticationScheme.IsSet(AuthenticationSchemes.Basic) && wid == null) { identity = listenerContext.User.Identity as HttpListenerBasicIdentity; Fx.Assert(identity != null, "HttpListener delivered Basic authenticated request with a non-Basic IIdentity."); retValue = this.ProcessAuthentication(identity); } else { Fx.Assert(wid != null, "HttpListener delivered non-Basic authenticated request with a non-Windows IIdentity."); retValue = this.ProcessAuthentication(wid, GetAuthType(listenerContext)); } } #pragma warning suppress 56500 // covered by FXCop catch (Exception exception) { if (!Fx.IsFatal(exception)) { // Audit Authentication failure if (AuditLevel.Failure == (this.AuditBehavior.MessageAuthenticationAuditLevel & AuditLevel.Failure)) { WriteAuditEvent(AuditLevel.Failure, (identity != null) ? identity.Name : ((wid != null) ? wid.Name : String.Empty), exception); } } throw; } // Audit Authentication success if (AuditLevel.Success == (this.AuditBehavior.MessageAuthenticationAuditLevel & AuditLevel.Success)) { WriteAuditEvent(AuditLevel.Success, (identity != null) ? identity.Name : ((wid != null) ? wid.Name : String.Empty), null); } return retValue; } protected override bool TryGetTransportManagerRegistration(HostNameComparisonMode hostNameComparisonMode, out ITransportManagerRegistration registration) { if (this.TransportManagerTable.TryLookupUri(this.Uri, hostNameComparisonMode, out registration)) { HttpTransportManager httpTransportManager = registration as HttpTransportManager; if (httpTransportManager != null && httpTransportManager.IsHosted) { return true; } // Due to HTTP.SYS behavior, we don't reuse registrations from a higher point in the URI hierarchy. if (registration.ListenUri.Segments.Length >= this.BaseUri.Segments.Length) { return true; } } return false; } protected void WriteAuditEvent(AuditLevel auditLevel, string primaryIdentity, Exception exception) { try { if (auditLevel == AuditLevel.Success) { SecurityAuditHelper.WriteTransportAuthenticationSuccessEvent(this.AuditBehavior.AuditLogLocation, this.AuditBehavior.SuppressAuditFailure, null, this.Uri, primaryIdentity); } else { SecurityAuditHelper.WriteTransportAuthenticationFailureEvent(this.AuditBehavior.AuditLogLocation, this.AuditBehavior.SuppressAuditFailure, null, this.Uri, primaryIdentity, exception); } } #pragma warning suppress 56500 catch (Exception auditException) { if (Fx.IsFatal(auditException) || auditLevel == AuditLevel.Success) throw; DiagnosticUtility.TraceHandledException(auditException, TraceEventType.Error); } } SecurityMessageProperty ProcessAuthentication(HttpListenerBasicIdentity identity) { SecurityToken securityToken = new UserNameSecurityToken(identity.Name, identity.Password); ReadOnlyCollection<IAuthorizationPolicy> authorizationPolicies = this.userNameTokenAuthenticator.ValidateToken(securityToken); SecurityMessageProperty security = new SecurityMessageProperty(); security.TransportToken = new SecurityTokenSpecification(securityToken, authorizationPolicies); security.ServiceSecurityContext = new ServiceSecurityContext(authorizationPolicies); return security; } SecurityMessageProperty ProcessAuthentication(WindowsIdentity identity, string authenticationType) { SecurityUtils.ValidateAnonymityConstraint(identity, false); SecurityToken securityToken = new WindowsSecurityToken(identity, SecurityUniqueId.Create().Value, authenticationType); ReadOnlyCollection<IAuthorizationPolicy> authorizationPolicies = this.windowsTokenAuthenticator.ValidateToken(securityToken); SecurityMessageProperty security = new SecurityMessageProperty(); security.TransportToken = new SecurityTokenSpecification(securityToken, authorizationPolicies); security.ServiceSecurityContext = new ServiceSecurityContext(authorizationPolicies); return security; } HttpStatusCode ValidateAuthentication(string authType) { if (this.IsAuthSchemeValid(authType)) { return HttpStatusCode.OK; } else { // Audit Authentication failure if (AuditLevel.Failure == (this.AuditBehavior.MessageAuthenticationAuditLevel & AuditLevel.Failure)) { string message = SR.GetString(SR.HttpAuthenticationFailed, this.AuthenticationScheme, HttpStatusCode.Unauthorized); Exception exception = DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(message)); WriteAuditEvent(AuditLevel.Failure, String.Empty, exception); } return HttpStatusCode.Unauthorized; } } public virtual HttpStatusCode ValidateAuthentication(IHttpAuthenticationContext authenticationContext) { HttpStatusCode result = HttpStatusCode.OK; if (this.IsAuthenticationSupported) { string authType = GetAuthType(authenticationContext); result = ValidateAuthentication(authType); } if (result == HttpStatusCode.OK && authenticationContext.LogonUserIdentity != null && authenticationContext.LogonUserIdentity.IsAuthenticated && this.ExtendedProtectionPolicy.PolicyEnforcement == PolicyEnforcement.Always && !authenticationContext.IISSupportsExtendedProtection) { Exception exception = DiagnosticUtility.ExceptionUtility.ThrowHelperError( new PlatformNotSupportedException(SR.GetString(SR.ExtendedProtectionNotSupported))); WriteAuditEvent(AuditLevel.Failure, String.Empty, exception); result = HttpStatusCode.Unauthorized; } return result; } public virtual HttpStatusCode ValidateAuthentication(HttpListenerContext listenerContext) { HttpStatusCode result = HttpStatusCode.OK; if (this.IsAuthenticationSupported) { string authType = GetAuthType(listenerContext); result = ValidateAuthentication(authType); } return result; } static ExtendedProtectionPolicy GetPolicyWithDefaultSpnCollection(ExtendedProtectionPolicy policy, AuthenticationSchemes authenticationScheme, HostNameComparisonMode hostNameComparisonMode, Uri listenUri, out bool usingDefaultSpnList) { if (policy.PolicyEnforcement != PolicyEnforcement.Never && policy.CustomServiceNames == null && //null indicates "use default" policy.CustomChannelBinding == null && //not needed if a channel binding is provided. authenticationScheme != AuthenticationSchemes.Anonymous && //SPN list only needed with authentication (mixed mode uses own default list) string.Equals(listenUri.Scheme, Uri.UriSchemeHttp, StringComparison.OrdinalIgnoreCase))//SPN list not used for HTTPS (CBT is used instead). { usingDefaultSpnList = true; return new ExtendedProtectionPolicy(policy.PolicyEnforcement, policy.ProtectionScenario, GetDefaultSpnList(hostNameComparisonMode, listenUri)); } usingDefaultSpnList = false; return policy; } static ServiceNameCollection GetDefaultSpnList(HostNameComparisonMode hostNameComparisonMode, Uri listenUri) { //In 3.5 SP1, we started sending the HOST/xyz format, so we have to accept it for compat reasons. //with this change, we will be changing our client so that it lets System.Net pick the SPN by default //which will usually mean they use the HTTP/xyz format, which is more likely to interop with //other web service stacks that support windows auth... const string hostSpnFormat = "HOST/{0}"; const string httpSpnFormat = "HTTP/{0}"; const string localhost = "localhost"; Dictionary<string, string> serviceNames = new Dictionary<string, string>(); string hostName = null; string dnsSafeHostName = listenUri.DnsSafeHost; switch (hostNameComparisonMode) { case HostNameComparisonMode.Exact: UriHostNameType hostNameType = listenUri.HostNameType; if (hostNameType == UriHostNameType.IPv4 || hostNameType == UriHostNameType.IPv6) { hostName = Dns.GetHostEntry(string.Empty).HostName; AddSpn(serviceNames, string.Format(CultureInfo.InvariantCulture, hostSpnFormat, hostName)); AddSpn(serviceNames, string.Format(CultureInfo.InvariantCulture, httpSpnFormat, hostName)); } else { if (listenUri.DnsSafeHost.Contains(".")) { //since we are listening explicitly on the FQDN, we should add only the FQDN SPN AddSpn(serviceNames, string.Format(CultureInfo.InvariantCulture, hostSpnFormat, dnsSafeHostName)); AddSpn(serviceNames, string.Format(CultureInfo.InvariantCulture, httpSpnFormat, dnsSafeHostName)); } else { hostName = Dns.GetHostEntry(string.Empty).HostName; //add the short name (from the URI) and the FQDN (from Dns) AddSpn(serviceNames, string.Format(CultureInfo.InvariantCulture, hostSpnFormat, dnsSafeHostName)); AddSpn(serviceNames, string.Format(CultureInfo.InvariantCulture, httpSpnFormat, dnsSafeHostName)); AddSpn(serviceNames, string.Format(CultureInfo.InvariantCulture, hostSpnFormat, hostName)); AddSpn(serviceNames, string.Format(CultureInfo.InvariantCulture, httpSpnFormat, hostName)); } } break; case HostNameComparisonMode.StrongWildcard: case HostNameComparisonMode.WeakWildcard: hostName = Dns.GetHostEntry(string.Empty).HostName; AddSpn(serviceNames, string.Format(CultureInfo.InvariantCulture, hostSpnFormat, hostName)); AddSpn(serviceNames, string.Format(CultureInfo.InvariantCulture, httpSpnFormat, hostName)); break; default: Fx.Assert("Unhandled HostNameComparisonMode: " + hostNameComparisonMode); break; } AddSpn(serviceNames, string.Format(CultureInfo.InvariantCulture, hostSpnFormat, localhost)); AddSpn(serviceNames, string.Format(CultureInfo.InvariantCulture, httpSpnFormat, localhost)); return new ServiceNameCollection(serviceNames.Values); } static void AddSpn(Dictionary<string, string> list, string value) { string key = value.ToLowerInvariant(); if (!list.ContainsKey(key)) { list.Add(key, value); } } public abstract bool CreateWebSocketChannelAndEnqueue(HttpRequestContext httpRequestContext, HttpPipeline httpPipeline, HttpResponseMessage httpResponseMessage, string subProtocol, Action dequeuedCallback); public abstract byte[] TakeWebSocketInternalBuffer(); public abstract void ReturnWebSocketInternalBuffer(byte[] buffer); internal interface IHttpAuthenticationContext { WindowsIdentity LogonUserIdentity { get; } X509Certificate2 GetClientCertificate(out bool isValidCertificate); bool IISSupportsExtendedProtection { get; } TraceRecord CreateTraceRecord(); } } class HttpChannelListener<TChannel> : HttpChannelListener, IChannelListener<TChannel> where TChannel : class, IChannel { InputQueueChannelAcceptor<TChannel> acceptor; bool useWebSocketTransport; CommunicationObjectManager<ServerWebSocketTransportDuplexSessionChannel> webSocketLifetimeManager; TransportIntegrationHandler transportIntegrationHandler; ConnectionBufferPool bufferPool; string currentWebSocketVersion; public HttpChannelListener(HttpTransportBindingElement bindingElement, BindingContext context) : base(bindingElement, context) { this.useWebSocketTransport = bindingElement.WebSocketSettings.TransportUsage == WebSocketTransportUsage.Always || (bindingElement.WebSocketSettings.TransportUsage == WebSocketTransportUsage.WhenDuplex && typeof(TChannel) != typeof(IReplyChannel)); if (this.useWebSocketTransport) { if (AspNetEnvironment.Enabled) { AspNetEnvironment env = AspNetEnvironment.Current; // When IIS hosted, WebSockets can be used if the pipeline mode is integrated and the WebSocketModule is loaded. // Otherwise, the client requests will not be upgraded to web sockets (see the code in HostedHttpTransportManager.HttpContextReceived(..)). // We do the checks below (and fail the service activation), to avoid starting a WebSockets listener that won't get called. if (!env.UsingIntegratedPipeline) { throw FxTrace.Exception.AsError(new NotSupportedException(SR.GetString(SR.WebSocketsNotSupportedInClassicPipeline))); } else if (!env.IsWebSocketModuleLoaded) { throw FxTrace.Exception.AsError(new NotSupportedException(SR.GetString(SR.WebSocketModuleNotLoaded))); } } else if (!WebSocketHelper.OSSupportsWebSockets()) { throw FxTrace.Exception.AsError(new PlatformNotSupportedException(SR.GetString(SR.WebSocketsServerSideNotSupported))); } this.currentWebSocketVersion = WebSocketHelper.GetCurrentVersion(); this.acceptor = new InputQueueChannelAcceptor<TChannel>(this); int webSocketBufferSize = WebSocketHelper.ComputeServerBufferSize(bindingElement.MaxReceivedMessageSize); this.bufferPool = new ConnectionBufferPool(webSocketBufferSize); this.webSocketLifetimeManager = new CommunicationObjectManager<ServerWebSocketTransportDuplexSessionChannel>(this.ThisLock); } else { this.acceptor = (InputQueueChannelAcceptor<TChannel>)(object)(new TransportReplyChannelAcceptor(this)); } this.CreatePipeline(bindingElement.MessageHandlerFactory); } public override bool UseWebSocketTransport { get { return this.useWebSocketTransport; } } public InputQueueChannelAcceptor<TChannel> Acceptor { get { return this.acceptor; } } public override string Method { get { if (this.UseWebSocketTransport) { return WebSocketTransportSettings.WebSocketMethod; } return base.Method; } } public TChannel AcceptChannel() { return this.AcceptChannel(this.DefaultReceiveTimeout); } public IAsyncResult BeginAcceptChannel(AsyncCallback callback, object state) { return this.BeginAcceptChannel(this.DefaultReceiveTimeout, callback, state); } public TChannel AcceptChannel(TimeSpan timeout) { base.ThrowIfNotOpened(); return this.Acceptor.AcceptChannel(timeout); } public IAsyncResult BeginAcceptChannel(TimeSpan timeout, AsyncCallback callback, object state) { base.ThrowIfNotOpened(); return this.Acceptor.BeginAcceptChannel(timeout, callback, state); } public TChannel EndAcceptChannel(IAsyncResult result) { base.ThrowPending(); return this.Acceptor.EndAcceptChannel(result); } public override bool CreateWebSocketChannelAndEnqueue(HttpRequestContext httpRequestContext, HttpPipeline pipeline, HttpResponseMessage httpResponseMessage, string subProtocol, Action dequeuedCallback) { Fx.Assert(this.WebSocketSettings.MaxPendingConnections > 0, "MaxPendingConnections should be positive."); if (this.Acceptor.PendingCount >= this.WebSocketSettings.MaxPendingConnections) { if (TD.MaxPendingConnectionsExceededIsEnabled()) { TD.MaxPendingConnectionsExceeded(SR.GetString(SR.WebSocketMaxPendingConnectionsReached, this.WebSocketSettings.MaxPendingConnections, WebSocketHelper.MaxPendingConnectionsString, WebSocketHelper.WebSocketTransportSettingsString)); } if (DiagnosticUtility.ShouldTraceWarning) { TraceUtility.TraceEvent(TraceEventType.Warning, TraceCode.MaxPendingConnectionsReached, SR.GetString(SR.WebSocketMaxPendingConnectionsReached, this.WebSocketSettings.MaxPendingConnections, WebSocketHelper.MaxPendingConnectionsString, WebSocketHelper.WebSocketTransportSettingsString), new StringTraceRecord(WebSocketHelper.MaxPendingConnectionsString, this.WebSocketSettings.MaxPendingConnections.ToString(System.Globalization.CultureInfo.InvariantCulture)), this, null); } return false; } ServerWebSocketTransportDuplexSessionChannel channel = new ServerWebSocketTransportDuplexSessionChannel(this, new EndpointAddress(this.Uri), this.Uri, this.bufferPool, httpRequestContext, pipeline, httpResponseMessage, subProtocol); httpRequestContext.WebSocketChannel = channel; // webSocketLifetimeManager hooks into the channel.Closed event as well and will take care of cleaning itself up OnClosed. // We want to be called before any user-specified close handlers are called. this.webSocketLifetimeManager.Add(channel); this.Acceptor.EnqueueAndDispatch((TChannel)(object)channel, dequeuedCallback, true); return true; } public override byte[] TakeWebSocketInternalBuffer() { Fx.Assert(this.bufferPool != null, "bufferPool should not be null."); return this.bufferPool.Take(); } public override void ReturnWebSocketInternalBuffer(byte[] buffer) { Fx.Assert(this.bufferPool != null, "bufferPool should not be null."); this.bufferPool.Return(buffer); } protected override IAsyncResult OnBeginOpen(TimeSpan timeout, AsyncCallback callback, object state) { return new ChainedOpenAsyncResult(timeout, callback, state, base.OnBeginOpen, base.OnEndOpen, this.Acceptor); } protected override void OnOpen(TimeSpan timeout) { TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); base.OnOpen(timeoutHelper.RemainingTime()); this.Acceptor.Open(timeoutHelper.RemainingTime()); } protected override void OnEndOpen(IAsyncResult result) { ChainedOpenAsyncResult.End(result); } protected override void OnClose(TimeSpan timeout) { TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); this.Acceptor.Close(timeoutHelper.RemainingTime()); if (this.IsAuthenticationSupported) { CloseUserNameTokenAuthenticator(timeoutHelper.RemainingTime()); } if (this.useWebSocketTransport) { this.webSocketLifetimeManager.Close(timeoutHelper.RemainingTime()); } base.OnClose(timeoutHelper.RemainingTime()); } protected override IAsyncResult OnBeginClose(TimeSpan timeout, AsyncCallback callback, object state) { TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); ICommunicationObject[] communicationObjects; ICommunicationObject communicationObject = this.UserNameTokenAuthenticator as ICommunicationObject; if (communicationObject == null) { if (this.IsAuthenticationSupported) { CloseUserNameTokenAuthenticator(timeoutHelper.RemainingTime()); } communicationObjects = new ICommunicationObject[] { this.Acceptor }; } else { communicationObjects = new ICommunicationObject[] { this.Acceptor, communicationObject }; } if (this.useWebSocketTransport) { return new LifetimeWrappedCloseAsyncResult<ServerWebSocketTransportDuplexSessionChannel>( timeoutHelper.RemainingTime(), callback, state, this.webSocketLifetimeManager, base.OnBeginClose, base.OnEndClose, communicationObjects); } else { return new ChainedCloseAsyncResult(timeoutHelper.RemainingTime(), callback, state, base.OnBeginClose, base.OnEndClose, communicationObjects); } } protected override void OnEndClose(IAsyncResult result) { if (this.useWebSocketTransport) { LifetimeWrappedCloseAsyncResult<ServerWebSocketTransportDuplexSessionChannel>.End(result); } else { ChainedCloseAsyncResult.End(result); } } protected override void OnClosed() { base.OnClosed(); if (this.bufferPool != null) { this.bufferPool.Close(); } if (this.transportIntegrationHandler != null) { this.transportIntegrationHandler.Dispose(); } } protected override void OnAbort() { if (this.IsAuthenticationSupported) { AbortUserNameTokenAuthenticator(); } this.Acceptor.Abort(); if (this.useWebSocketTransport) { this.webSocketLifetimeManager.Abort(); } base.OnAbort(); } protected override bool OnWaitForChannel(TimeSpan timeout) { return Acceptor.WaitForChannel(timeout); } protected override IAsyncResult OnBeginWaitForChannel(TimeSpan timeout, AsyncCallback callback, object state) { return Acceptor.BeginWaitForChannel(timeout, callback, state); } protected override bool OnEndWaitForChannel(IAsyncResult result) { return Acceptor.EndWaitForChannel(result); } internal override IAsyncResult BeginHttpContextReceived(HttpRequestContext context, Action acceptorCallback, AsyncCallback callback, object state) { return new HttpContextReceivedAsyncResult<TChannel>( context, acceptorCallback, this, callback, state); } internal override bool EndHttpContextReceived(IAsyncResult result) { return HttpContextReceivedAsyncResult<TChannel>.End(result); } void CreatePipeline(HttpMessageHandlerFactory httpMessageHandlerFactory) { HttpMessageHandler innerPipeline; if (this.UseWebSocketTransport) { innerPipeline = new DefaultWebSocketConnectionHandler(this.WebSocketSettings.SubProtocol, this.currentWebSocketVersion, this.MessageVersion, this.MessageEncoderFactory, this.TransferMode); if (httpMessageHandlerFactory != null) { innerPipeline = httpMessageHandlerFactory.Create(innerPipeline); } } else { if (httpMessageHandlerFactory == null) { return; } innerPipeline = httpMessageHandlerFactory.Create(new ChannelModelIntegrationHandler()); } if (innerPipeline == null) { throw FxTrace.Exception.AsError( new InvalidOperationException(SR.GetString(SR.HttpMessageHandlerChannelFactoryNullPipeline, httpMessageHandlerFactory.GetType().Name, typeof(HttpRequestContext).Name))); } this.transportIntegrationHandler = new TransportIntegrationHandler(innerPipeline); } static void HandleProcessInboundException(Exception ex, HttpRequestContext context) { if (Fx.IsFatal(ex)) { return; } if (ex is ProtocolException) { ProtocolException protocolException = (ProtocolException)ex; HttpStatusCode statusCode = HttpStatusCode.BadRequest; string statusDescription = string.Empty; if (protocolException.Data.Contains(HttpChannelUtilities.HttpStatusCodeExceptionKey)) { statusCode = (HttpStatusCode)protocolException.Data[HttpChannelUtilities.HttpStatusCodeExceptionKey]; protocolException.Data.Remove(HttpChannelUtilities.HttpStatusCodeExceptionKey); } if (protocolException.Data.Contains(HttpChannelUtilities.HttpStatusDescriptionExceptionKey)) { statusDescription = (string)protocolException.Data[HttpChannelUtilities.HttpStatusDescriptionExceptionKey]; protocolException.Data.Remove(HttpChannelUtilities.HttpStatusDescriptionExceptionKey); } context.SendResponseAndClose(statusCode, statusDescription); } else { try { context.SendResponseAndClose(HttpStatusCode.BadRequest); } catch (Exception closeException) { if (Fx.IsFatal(closeException)) { throw; } DiagnosticUtility.TraceHandledException(closeException, TraceEventType.Error); } } } static bool ContextReceiveExceptionHandled(Exception e) { if (Fx.IsFatal(e)) { return false; } if (e is CommunicationException) { DiagnosticUtility.TraceHandledException(e, TraceEventType.Information); } else if (e is XmlException) { DiagnosticUtility.TraceHandledException(e, TraceEventType.Information); } else if (e is IOException) { DiagnosticUtility.TraceHandledException(e, TraceEventType.Information); } else if (e is TimeoutException) { if (TD.ReceiveTimeoutIsEnabled()) { TD.ReceiveTimeout(e.Message); } DiagnosticUtility.TraceHandledException(e, TraceEventType.Information); } else if (e is OperationCanceledException) { DiagnosticUtility.TraceHandledException(e, TraceEventType.Information); } else if (!ExceptionHandler.HandleTransportExceptionHelper(e)) { return false; } return true; } class HttpContextReceivedAsyncResult<TListenerChannel> : TraceAsyncResult where TListenerChannel : class, IChannel { static AsyncCallback onProcessInboundRequest = Fx.ThunkCallback(OnProcessInboundRequest); bool enqueued; HttpRequestContext context; Action acceptorCallback; HttpChannelListener<TListenerChannel> listener; public HttpContextReceivedAsyncResult( HttpRequestContext requestContext, Action acceptorCallback, HttpChannelListener<TListenerChannel> listener, AsyncCallback callback, object state) : base(callback, state) { this.context = requestContext; this.acceptorCallback = acceptorCallback; this.listener = listener; if (this.ProcessHttpContextAsync() == AsyncCompletionResult.Completed) { base.Complete(true); } } public static bool End(IAsyncResult result) { return AsyncResult.End<HttpContextReceivedAsyncResult<TListenerChannel>>(result).enqueued; } static void OnProcessInboundRequest(IAsyncResult result) { if (result.CompletedSynchronously) { return; } HttpContextReceivedAsyncResult<TListenerChannel> thisPtr = (HttpContextReceivedAsyncResult<TListenerChannel>)result.AsyncState; Exception completionException = null; try { thisPtr.HandleProcessInboundRequest(result); } catch (Exception ex) { if (Fx.IsFatal(ex)) { throw; } completionException = ex; } thisPtr.Complete(false, completionException); } AsyncCompletionResult ProcessHttpContextAsync() { bool abort = false; try { this.context.InitializeHttpPipeline(this.listener.transportIntegrationHandler); if (!this.Authenticate()) { return AsyncCompletionResult.Completed; } if (listener.UseWebSocketTransport && !context.IsWebSocketRequest) { this.context.SendResponseAndClose(HttpStatusCode.BadRequest, SR.GetString(SR.WebSocketEndpointOnlySupportWebSocketError)); return AsyncCompletionResult.Completed; } if (!listener.UseWebSocketTransport && context.IsWebSocketRequest) { this.context.SendResponseAndClose(HttpStatusCode.BadRequest, SR.GetString(SR.WebSocketEndpointDoesNotSupportWebSocketError)); return AsyncCompletionResult.Completed; } try { IAsyncResult result = context.BeginProcessInboundRequest(listener.Acceptor as ReplyChannelAcceptor, this.acceptorCallback, onProcessInboundRequest, this); if (result.CompletedSynchronously) { this.EndInboundProcessAndEnqueue(result); return AsyncCompletionResult.Completed; } } catch (Exception ex) { HandleProcessInboundException(ex, this.context); throw; } } catch (Exception ex) { // containment -- we abort the context in all error cases, no additional containment action needed abort = true; if (!ContextReceiveExceptionHandled(ex)) { throw; } } finally { if (abort) { context.Abort(); } } return abort ? AsyncCompletionResult.Completed : AsyncCompletionResult.Queued; } bool Authenticate() { if (!this.context.ProcessAuthentication()) { if (TD.HttpAuthFailedIsEnabled()) { TD.HttpAuthFailed(context.EventTraceActivity); } if (DiagnosticUtility.ShouldTraceInformation) { TraceUtility.TraceEvent(TraceEventType.Information, TraceCode.HttpAuthFailed, SR.GetString(SR.TraceCodeHttpAuthFailed), this); } return false; } return true; } void HandleProcessInboundRequest(IAsyncResult result) { bool abort = true; try { try { this.EndInboundProcessAndEnqueue(result); abort = false; } catch (Exception ex) { HandleProcessInboundException(ex, this.context); throw; } } catch (Exception ex) { // containment -- we abort the context in all error cases, no additional containment action needed if (!ContextReceiveExceptionHandled(ex)) { throw; } } finally { if (abort) { context.Abort(); } } } void EndInboundProcessAndEnqueue(IAsyncResult result) { Fx.Assert(result != null, "Trying to complete without issuing a BeginProcessInboundRequest."); context.EndProcessInboundRequest(result); //We have finally managed to enqueue the message. this.enqueued = true; } } class LifetimeWrappedCloseAsyncResult<TCommunicationObject> : AsyncResult where TCommunicationObject : CommunicationObject { static AsyncCompletion handleLifetimeManagerClose = new AsyncCompletion(HandleLifetimeManagerClose); static AsyncCompletion handleChannelClose = new AsyncCompletion(HandleChannelClose); TimeoutHelper timeoutHelper; ICommunicationObject[] communicationObjects; CommunicationObjectManager<TCommunicationObject> communicationObjectManager; ChainedBeginHandler begin1; ChainedEndHandler end1; public LifetimeWrappedCloseAsyncResult(TimeSpan timeout, AsyncCallback callback, object state, CommunicationObjectManager<TCommunicationObject> communicationObjectManager, ChainedBeginHandler begin1, ChainedEndHandler end1, ICommunicationObject[] communicationObjects) : base(callback, state) { this.timeoutHelper = new TimeoutHelper(timeout); this.begin1 = begin1; this.end1 = end1; this.communicationObjects = communicationObjects; this.communicationObjectManager = communicationObjectManager; IAsyncResult result = communicationObjectManager.BeginClose( this.timeoutHelper.RemainingTime(), PrepareAsyncCompletion(handleLifetimeManagerClose), this); bool completeSelf = SyncContinue(result); if (completeSelf) { this.Complete(true); } } public static void End(IAsyncResult result) { AsyncResult.End<LifetimeWrappedCloseAsyncResult<TCommunicationObject>>(result); } static bool HandleLifetimeManagerClose(IAsyncResult result) { LifetimeWrappedCloseAsyncResult<TCommunicationObject> thisPtr = (LifetimeWrappedCloseAsyncResult<TCommunicationObject>)result.AsyncState; thisPtr.communicationObjectManager.EndClose(result); // begin second step of the close... ChainedCloseAsyncResult closeResult = new ChainedCloseAsyncResult( thisPtr.timeoutHelper.RemainingTime(), thisPtr.PrepareAsyncCompletion(handleChannelClose), thisPtr, thisPtr.begin1, thisPtr.end1, thisPtr.communicationObjects); return thisPtr.SyncContinue(closeResult); } static bool HandleChannelClose(IAsyncResult result) { ChainedCloseAsyncResult.End(result); return true; } } } /// <summary> /// Handler wrapping the bottom (towards network) of the <see cref="HttpMessageHandler"/> and integrates /// back into the <see cref="IReplyChannel"/>. /// </summary> class TransportIntegrationHandler : DelegatingHandler { /// <summary> /// Initializes a new instance of the <see cref="TransportIntegrationHandler"/> class. /// </summary> /// <param name="innerChannel">The inner <see cref="HttpMessageHandler"/> on which we send the <see cref="HttpRequestMessage"/>.</param> public TransportIntegrationHandler(HttpMessageHandler innerChannel) : base(innerChannel) { } /// <summary> /// Submits an <see cref="HttpRequestMessage"/> on the inner channel asynchronously. /// </summary> /// <param name="request"><see cref="HttpRequestMessage"/> to submit</param> /// <param name="cancellationToken">Token used to cancel operation.</param> /// <returns>A <see cref="Task&lt;T&gt;"/> representing the operation.</returns> public Task<HttpResponseMessage> ProcessPipelineAsync(HttpRequestMessage request, CancellationToken cancellationToken) { return base.SendAsync(request, cancellationToken).ContinueWith(task => { HttpResponseMessage httpResponse; if (task.IsFaulted) { if (Fx.IsFatal(task.Exception)) { throw task.Exception; } // We must inspect task.Exception -- otherwise it is automatically rethrown. FxTrace.Exception.AsError<FaultException>(task.Exception); httpResponse = TraceFaultAndGetResponseMessasge(request); } else if (task.IsCanceled) { HttpPipeline pipeline = HttpPipeline.GetHttpPipeline(request); if (TD.HttpPipelineTimeoutExceptionIsEnabled()) { TD.HttpPipelineTimeoutException(pipeline != null ? pipeline.EventTraceActivity : null); } FxTrace.Exception.AsError(new TimeoutException(SR.GetString(SR.HttpPipelineOperationCanceledError))); pipeline.Cancel(); httpResponse = null; } else { httpResponse = task.Result; if (httpResponse == null) { FxTrace.Exception.AsError(new NotSupportedException(SR.GetString(SR.HttpPipelineNotSupportNullResponseMessage, typeof(DelegatingHandler).Name, typeof(HttpResponseMessage).Name))); httpResponse = TraceFaultAndGetResponseMessasge(request); } } return httpResponse; }, TaskContinuationOptions.ExecuteSynchronously); } static HttpResponseMessage TraceFaultAndGetResponseMessasge(HttpRequestMessage request) { HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.InternalServerError); response.RequestMessage = request; if (TD.HttpPipelineFaultedIsEnabled()) { HttpPipeline pipeline = HttpPipeline.GetHttpPipeline(request); TD.HttpPipelineFaulted(pipeline != null ? pipeline.EventTraceActivity : null); } return response; } } /// <summary> /// Handler wrapping the top (towards Channel Model) of the <see cref="HttpMessageHandler"/> and integrates /// bask into the <see cref="IReplyChannel"/>. /// </summary> class ChannelModelIntegrationHandler : HttpMessageHandler { /// <summary> /// Submits an <see cref="HttpRequestMessage"/> on the inner channel asynchronously. /// </summary> /// <param name="request"><see cref="HttpRequestMessage"/> to submit</param> /// <param name="cancellationToken">Token used to cancel operation.</param> /// <returns>A <see cref="Task&lt;T&gt;"/> representing the operation.</returns> protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { if (request == null) { throw FxTrace.Exception.ArgumentNull("request"); } if (cancellationToken == null) { throw FxTrace.Exception.ArgumentNull("cancellationToken"); } cancellationToken.ThrowIfCancellationRequested(); HttpChannelUtilities.EnsureHttpRequestMessageContentNotNull(request); //// We ran up through the pipeline and are now ready to hook back into the WCF channel model HttpPipeline httpPipeline = HttpPipeline.GetHttpPipeline(request); return httpPipeline.Dispatch(request); } } }
// 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.Diagnostics; using System.Text; using Internal.Metadata.NativeFormat; namespace Internal.StackTraceMetadata { class MethodNameFormatter { /// <summary> /// Metadata reader used for the purpose of method name formatting. /// </summary> private readonly MetadataReader _metadataReader; /// <summary> /// String builder used to construct formatted method name. /// </summary> private readonly StringBuilder _outputBuilder; /// <summary> /// Initialize the reader used for method name formatting. /// </summary> private MethodNameFormatter(MetadataReader metadataReader) { _metadataReader = metadataReader; _outputBuilder = new StringBuilder(); } public static string FormatMethodName(MetadataReader metadataReader, Handle methodHandle) { MethodNameFormatter formatter = new MethodNameFormatter(metadataReader); formatter.EmitMethodName(methodHandle); return formatter._outputBuilder.ToString(); } /// <summary> /// Emit a given method signature to a specified string builder. /// </summary> /// <param name="methodToken">Method reference or instantiation token</param> private void EmitMethodName(Handle methodHandle) { switch (methodHandle.HandleType) { case HandleType.MemberReference: EmitMethodReferenceName(methodHandle.ToMemberReferenceHandle(_metadataReader)); break; case HandleType.MethodInstantiation: EmitMethodInstantiationName(methodHandle.ToMethodInstantiationHandle(_metadataReader)); break; default: Debug.Assert(false); _outputBuilder.Append("???"); break; } } /// <summary> /// Emit method reference to the output string builder. /// </summary> /// <param name="memberRefHandle">Member reference handle</param> private void EmitMethodReferenceName(MemberReferenceHandle memberRefHandle) { MemberReference methodRef = _metadataReader.GetMemberReference(memberRefHandle); MethodSignature methodSignature; EmitReturnTypeContainingTypeAndMethodName(methodRef, out methodSignature); EmitMethodParameters(methodSignature); } /// <summary> /// Emit generic method instantiation to the output string builder. /// </summary> /// <param name="methodInstHandle">Method instantiation handle</param> private void EmitMethodInstantiationName(MethodInstantiationHandle methodInstHandle) { MethodInstantiation methodInst = _metadataReader.GetMethodInstantiation(methodInstHandle); MemberReferenceHandle methodRefHandle = methodInst.Method.ToMemberReferenceHandle(_metadataReader); MemberReference methodRef = methodRefHandle.GetMemberReference(_metadataReader); MethodSignature methodSignature; EmitReturnTypeContainingTypeAndMethodName(methodRef, out methodSignature); EmitGenericArguments(methodInst.GenericTypeArguments); EmitMethodParameters(methodSignature); } /// <summary> /// Emit containing type and method name and extract the method signature from a method reference. /// </summary> /// <param name="methodRef">Method reference to format</param> /// <param name="methodSignature">Output method signature</param> private void EmitReturnTypeContainingTypeAndMethodName(MemberReference methodRef, out MethodSignature methodSignature) { methodSignature = _metadataReader.GetMethodSignature(methodRef.Signature.ToMethodSignatureHandle(_metadataReader)); EmitTypeName(methodSignature.ReturnType, namespaceQualified: false); _outputBuilder.Append(" "); EmitTypeName(methodRef.Parent, namespaceQualified: true); _outputBuilder.Append("."); EmitString(methodRef.Name); } /// <summary> /// Emit parenthesized method argument type list. /// </summary> /// <param name="methodSignature">Method signature to use for parameter formatting</param> private void EmitMethodParameters(MethodSignature methodSignature) { _outputBuilder.Append("("); EmitTypeVector(methodSignature.Parameters); _outputBuilder.Append(")"); } /// <summary> /// Emit comma-separated list of type names into the output string builder. /// </summary> /// <param name="typeVector">Enumeration of type handles to output</param> private void EmitTypeVector(HandleCollection typeVector) { bool first = true; foreach (Handle handle in typeVector) { if (first) { first = false; } else { _outputBuilder.Append(", "); } EmitTypeName(handle, namespaceQualified: false); } } /// <summary> /// Emit the name of a given type to the output string builder. /// </summary> /// <param name="typeHandle">Type handle to format</param> /// <param name="namespaceQualified">When set to true, include namespace information</param> private void EmitTypeName(Handle typeHandle, bool namespaceQualified) { switch (typeHandle.HandleType) { case HandleType.TypeReference: EmitTypeReferenceName(typeHandle.ToTypeReferenceHandle(_metadataReader), namespaceQualified); break; case HandleType.TypeSpecification: EmitTypeSpecificationName(typeHandle.ToTypeSpecificationHandle(_metadataReader), namespaceQualified); break; case HandleType.TypeInstantiationSignature: EmitTypeInstantiationName(typeHandle.ToTypeInstantiationSignatureHandle(_metadataReader), namespaceQualified); break; case HandleType.SZArraySignature: EmitSZArrayTypeName(typeHandle.ToSZArraySignatureHandle(_metadataReader), namespaceQualified); break; case HandleType.ArraySignature: EmitArrayTypeName(typeHandle.ToArraySignatureHandle(_metadataReader), namespaceQualified); break; case HandleType.PointerSignature: EmitPointerTypeName(typeHandle.ToPointerSignatureHandle(_metadataReader)); break; case HandleType.ByReferenceSignature: EmitByRefTypeName(typeHandle.ToByReferenceSignatureHandle(_metadataReader)); break; default: Debug.Assert(false); _outputBuilder.Append("???"); break; } } /// <summary> /// Emit namespace reference. /// </summary> /// <param name="namespaceRefHandle">Namespace reference handle</param> private void EmitNamespaceReferenceName(NamespaceReferenceHandle namespaceRefHandle) { NamespaceReference namespaceRef = _metadataReader.GetNamespaceReference(namespaceRefHandle); if (!namespaceRef.ParentScopeOrNamespace.IsNull(_metadataReader) && namespaceRef.ParentScopeOrNamespace.HandleType == HandleType.NamespaceReference) { EmitNamespaceReferenceName(namespaceRef.ParentScopeOrNamespace.ToNamespaceReferenceHandle(_metadataReader)); _outputBuilder.Append('.'); } EmitString(namespaceRef.Name); } /// <summary> /// Emit type reference. /// </summary> /// <param name="typeRefHandle">Type reference handle</param> /// <param name="namespaceQualified">When set to true, include namespace information</param> private void EmitTypeReferenceName(TypeReferenceHandle typeRefHandle, bool namespaceQualified) { TypeReference typeRef = _metadataReader.GetTypeReference(typeRefHandle); if (!typeRef.ParentNamespaceOrType.IsNull(_metadataReader)) { if (typeRef.ParentNamespaceOrType.HandleType != HandleType.NamespaceReference) { // Nested type EmitTypeName(typeRef.ParentNamespaceOrType, namespaceQualified); _outputBuilder.Append('+'); } else if (namespaceQualified) { EmitNamespaceReferenceName(typeRef.ParentNamespaceOrType.ToNamespaceReferenceHandle(_metadataReader)); _outputBuilder.Append('.'); } } EmitString(typeRef.TypeName); } /// <summary> /// Emit an arbitrary type specification. /// </summary> /// <param name="typeSpecHandle">Type specification handle</param> /// <param name="namespaceQualified">When set to true, include namespace information</param> private void EmitTypeSpecificationName(TypeSpecificationHandle typeSpecHandle, bool namespaceQualified) { TypeSpecification typeSpec = _metadataReader.GetTypeSpecification(typeSpecHandle); EmitTypeName(typeSpec.Signature, namespaceQualified); } /// <summary> /// Emit generic instantiation type. /// </summary> /// <param name="typeInstHandle">Instantiated type specification signature handle</param> /// <param name="namespaceQualified">When set to true, include namespace information</param> private void EmitTypeInstantiationName(TypeInstantiationSignatureHandle typeInstHandle, bool namespaceQualified) { TypeInstantiationSignature typeInst = _metadataReader.GetTypeInstantiationSignature(typeInstHandle); EmitTypeName(typeInst.GenericType, namespaceQualified); EmitGenericArguments(typeInst.GenericTypeArguments); } /// <summary> /// Emit SZArray (single-dimensional array with zero lower bound) type. /// </summary> /// <param name="szArraySigHandle">SZArray type specification signature handle</param> /// <param name="namespaceQualified">When set to true, include namespace information</param> private void EmitSZArrayTypeName(SZArraySignatureHandle szArraySigHandle, bool namespaceQualified) { SZArraySignature szArraySig = _metadataReader.GetSZArraySignature(szArraySigHandle); EmitTypeName(szArraySig.ElementType, namespaceQualified); _outputBuilder.Append("[]"); } /// <summary> /// Emit multi-dimensional array type. /// </summary> /// <param name="arraySigHandle">Multi-dimensional array type specification signature handle</param> /// <param name="namespaceQualified">When set to true, include namespace information</param> private void EmitArrayTypeName(ArraySignatureHandle arraySigHandle, bool namespaceQualified) { ArraySignature arraySig = _metadataReader.GetArraySignature(arraySigHandle); EmitTypeName(arraySig.ElementType, namespaceQualified); _outputBuilder.Append('['); if (arraySig.Rank > 1) { _outputBuilder.Append(',', arraySig.Rank - 1); } else { _outputBuilder.Append('*'); } _outputBuilder.Append(']'); } /// <summary> /// Emit pointer type. /// </summary> /// <param name="pointerSigHandle">Pointer type specification signature handle</param> private void EmitPointerTypeName(PointerSignatureHandle pointerSigHandle) { PointerSignature pointerSig = _metadataReader.GetPointerSignature(pointerSigHandle); EmitTypeName(pointerSig.Type, namespaceQualified: false); _outputBuilder.Append('*'); } /// <summary> /// Emit by-reference type. /// </summary> /// <param name="byRefSigHandle">ByReference type specification signature handle</param> private void EmitByRefTypeName(ByReferenceSignatureHandle byRefSigHandle) { ByReferenceSignature byRefSig = _metadataReader.GetByReferenceSignature(byRefSigHandle); EmitTypeName(byRefSig.Type, namespaceQualified: false); _outputBuilder.Append('&'); } /// <summary> /// Emit angle-bracketed list of type / method generic arguments. /// </summary> /// <param name="genericArguments">Collection of generic argument type handles</param> private void EmitGenericArguments(HandleCollection genericArguments) { _outputBuilder.Append('['); EmitTypeVector(genericArguments); _outputBuilder.Append(']'); } /// <summary> /// Emit a string (represented by a serialized ConstantStringValue) to the output string builder. /// </summary> /// <param name="stringToken">Constant string value token (offset within stack trace native metadata)</param> private void EmitString(ConstantStringValueHandle stringHandle) { _outputBuilder.Append(_metadataReader.GetConstantStringValue(stringHandle).Value); } } }
using System; using System.IO; using System.Net; using System.Xml; using System.Globalization; using System.Diagnostics; using System.Text.RegularExpressions; using System.Drawing; using System.Drawing.Drawing2D; using SharpVectors.Net; namespace SharpVectors.Dom.Svg { public class SvgImageElement : SvgTransformableElement, ISvgImageElement { #region Constructors internal SvgImageElement(string prefix, string localname, string ns, SvgDocument doc) : base(prefix, localname, ns, doc) { svgExternalResourcesRequired = new SvgExternalResourcesRequired(this); svgTests = new SvgTests(this); svgURIReference = new SvgURIReference(this); svgFitToViewBox = new SvgFitToViewBox(this); } #endregion #region Implementation of ISvgImageElement private ISvgAnimatedLength width; public ISvgAnimatedLength Width { get { if(width == null) { width = new SvgAnimatedLength(this, "width", SvgLengthDirection.Horizontal, "0"); } return width; } } private ISvgAnimatedLength height; public ISvgAnimatedLength Height { get { if(height == null) { height = new SvgAnimatedLength(this, "height", SvgLengthDirection.Vertical, "0"); } return height; } } private ISvgAnimatedLength x; public ISvgAnimatedLength X { get { if(x == null) { x = new SvgAnimatedLength(this, "x", SvgLengthDirection.Horizontal, "0"); } return x; } } private ISvgAnimatedLength y; public ISvgAnimatedLength Y { get { if(y == null) { y = new SvgAnimatedLength(this, "y", SvgLengthDirection.Vertical, "0"); } return y; } } #endregion #region Implementation of ISvgURIReference private SvgURIReference svgURIReference; public ISvgAnimatedString Href { get { return svgURIReference.Href; } } public XmlElement ReferencedElement { get { return svgURIReference.ReferencedNode as XmlElement; } } #endregion #region Implementation of ISvgFitToViewBox private SvgFitToViewBox svgFitToViewBox; public ISvgAnimatedPreserveAspectRatio PreserveAspectRatio { get { return svgFitToViewBox.PreserveAspectRatio; } } #endregion #region Implementation of ISvgImageElement from SVG 1.2 public SvgDocument GetImageDocument() { SvgWindow window = SvgWindow; if(window == null) { return null; } else { return (SvgDocument)window.Document; } } #endregion #region Public properties public SvgRect CalulatedViewbox { get { SvgRect viewBox; if ( IsSvgImage ) { SvgDocument doc = GetImageDocument(); SvgSvgElement outerSvg = (SvgSvgElement)doc.DocumentElement; if ( outerSvg.HasAttribute("viewBox") ) { viewBox = (SvgRect)outerSvg.ViewBox.AnimVal; } else { viewBox = SvgRect.Empty; } } else { viewBox = new SvgRect(0,0, Bitmap.Size.Width, Bitmap.Size.Height); } return viewBox; } } public bool IsSvgImage { get { if(!Href.AnimVal.StartsWith("data:")) { WebResponse resource = svgURIReference.ReferencedResource; // local files are returning as binary/octet-stream // this "fix" tests the file extension for .svg and .svgz string name = resource.ResponseUri.ToString().ToLower(CultureInfo.InvariantCulture); return ( resource.ContentType.StartsWith("image/svg+xml") || name.EndsWith(".svg") || name.EndsWith(".svgz") ); } else return false; } } public Bitmap Bitmap { get { if(!IsSvgImage) { if(!Href.AnimVal.StartsWith("data:")) { Stream stream = svgURIReference.ReferencedResource.GetResponseStream(); return (Bitmap)Bitmap.FromStream(stream); } else { string sURI = Href.AnimVal; int nColon = sURI.IndexOf(":"); int nSemiColon = sURI.IndexOf(";"); int nComma = sURI.IndexOf(","); string sMimeType = sURI.Substring(nColon + 1,nSemiColon - nColon - 1); string sContent = sURI.Substring(nComma + 1); byte[] bResult = Convert.FromBase64CharArray(sContent.ToCharArray(),0,sContent.Length); MemoryStream ms = new MemoryStream(bResult); return (Bitmap)Bitmap.FromStream(ms); } } else { return null; } } } public SvgWindow SvgWindow { get { if(IsSvgImage) { SvgWindow parentWindow = (SvgWindow)OwnerDocument.Window; SvgWindow wnd = new SvgWindow(parentWindow, (long)Width.AnimVal.Value, (long)Height.AnimVal.Value); SvgDocument doc = new SvgDocument(wnd); wnd.Document = doc; string absoluteUri = svgURIReference.AbsoluteUri; Stream resStream = svgURIReference.ReferencedResource.GetResponseStream(); doc.Load(absoluteUri, resStream); return wnd; } else { return null; } } } #endregion #region Update handling public override void HandleAttributeChange(XmlAttribute attribute) { if(attribute.NamespaceURI.Length == 0) { // This list may be too long to be useful... switch(attribute.LocalName) { // Additional attributes case "x": x = null; return; case "y": y = null; return; case "width": width = null; return; case "height": height = null; return; } base.HandleAttributeChange(attribute); } } #endregion #region Implementation of ISvgExternalResourcesRequired private SvgExternalResourcesRequired svgExternalResourcesRequired; public ISvgAnimatedBoolean ExternalResourcesRequired { get { return svgExternalResourcesRequired.ExternalResourcesRequired; } } #endregion #region Implementation of ISvgTests private SvgTests svgTests; public ISvgStringList RequiredFeatures { get { return svgTests.RequiredFeatures; } } public ISvgStringList RequiredExtensions { get { return svgTests.RequiredExtensions; } } public ISvgStringList SystemLanguage { get { return svgTests.SystemLanguage; } } public bool HasExtension(string extension) { return svgTests.HasExtension(extension); } #endregion #region UnitTests #endregion } }
/* * Copyright 2012-2016 The Pkcs11Interop Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Written for the Pkcs11Interop project by: * Jaroslav IMRICH <jimrich@jimrich.sk> */ using System; using Net.Pkcs11Interop.Common; using Net.Pkcs11Interop.LowLevelAPI81; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Net.Pkcs11Interop.Tests.LowLevelAPI81 { /// <summary> /// C_GenerateKey and C_GenerateKeyPair tests. /// </summary> [TestClass] public class _19_GenerateKeyAndKeyPairTest { /// <summary> /// C_GenerateKey test. /// </summary> [TestMethod] public void _01_GenerateKeyTest() { if (Platform.UnmanagedLongSize != 8 || Platform.StructPackingSize != 1) Assert.Inconclusive("Test cannot be executed on this platform"); CKR rv = CKR.CKR_OK; using (Pkcs11 pkcs11 = new Pkcs11(Settings.Pkcs11LibraryPath)) { rv = pkcs11.C_Initialize(Settings.InitArgs81); if ((rv != CKR.CKR_OK) && (rv != CKR.CKR_CRYPTOKI_ALREADY_INITIALIZED)) Assert.Fail(rv.ToString()); // Find first slot with token present ulong slotId = Helpers.GetUsableSlot(pkcs11); ulong session = CK.CK_INVALID_HANDLE; rv = pkcs11.C_OpenSession(slotId, (CKF.CKF_SERIAL_SESSION | CKF.CKF_RW_SESSION), IntPtr.Zero, IntPtr.Zero, ref session); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Login as normal user rv = pkcs11.C_Login(session, CKU.CKU_USER, Settings.NormalUserPinArray, Convert.ToUInt64(Settings.NormalUserPinArray.Length)); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Prepare attribute template of new key CK_ATTRIBUTE[] template = new CK_ATTRIBUTE[4]; template[0] = CkaUtils.CreateAttribute(CKA.CKA_CLASS, CKO.CKO_SECRET_KEY); template[1] = CkaUtils.CreateAttribute(CKA.CKA_KEY_TYPE, CKK.CKK_DES3); template[2] = CkaUtils.CreateAttribute(CKA.CKA_ENCRYPT, true); template[3] = CkaUtils.CreateAttribute(CKA.CKA_DECRYPT, true); // Specify key generation mechanism (needs no parameter => no unamanaged memory is needed) CK_MECHANISM mechanism = CkmUtils.CreateMechanism(CKM.CKM_DES3_KEY_GEN); // Generate key ulong keyId = CK.CK_INVALID_HANDLE; rv = pkcs11.C_GenerateKey(session, ref mechanism, template, Convert.ToUInt64(template.Length), ref keyId); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // In LowLevelAPI we have to free unmanaged memory taken by attributes for (int i = 0; i < template.Length; i++) { UnmanagedMemory.Free(ref template[i].value); template[i].valueLen = 0; } // Do something interesting with generated key // Destroy object rv = pkcs11.C_DestroyObject(session, keyId); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); rv = pkcs11.C_Logout(session); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); rv = pkcs11.C_CloseSession(session); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); rv = pkcs11.C_Finalize(IntPtr.Zero); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); } } /// <summary> /// C_GenerateKeyPair test. /// </summary> [TestMethod] public void _02_GenerateKeyPairTest() { if (Platform.UnmanagedLongSize != 8 || Platform.StructPackingSize != 1) Assert.Inconclusive("Test cannot be executed on this platform"); CKR rv = CKR.CKR_OK; using (Pkcs11 pkcs11 = new Pkcs11(Settings.Pkcs11LibraryPath)) { rv = pkcs11.C_Initialize(Settings.InitArgs81); if ((rv != CKR.CKR_OK) && (rv != CKR.CKR_CRYPTOKI_ALREADY_INITIALIZED)) Assert.Fail(rv.ToString()); // Find first slot with token present ulong slotId = Helpers.GetUsableSlot(pkcs11); ulong session = CK.CK_INVALID_HANDLE; rv = pkcs11.C_OpenSession(slotId, (CKF.CKF_SERIAL_SESSION | CKF.CKF_RW_SESSION), IntPtr.Zero, IntPtr.Zero, ref session); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Login as normal user rv = pkcs11.C_Login(session, CKU.CKU_USER, Settings.NormalUserPinArray, Convert.ToUInt64(Settings.NormalUserPinArray.Length)); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // The CKA_ID attribute is intended as a means of distinguishing multiple key pairs held by the same subject byte[] ckaId = new byte[20]; rv = pkcs11.C_GenerateRandom(session, ckaId, Convert.ToUInt64(ckaId.Length)); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // Prepare attribute template of new public key CK_ATTRIBUTE[] pubKeyTemplate = new CK_ATTRIBUTE[10]; pubKeyTemplate[0] = CkaUtils.CreateAttribute(CKA.CKA_TOKEN, true); pubKeyTemplate[1] = CkaUtils.CreateAttribute(CKA.CKA_PRIVATE, false); pubKeyTemplate[2] = CkaUtils.CreateAttribute(CKA.CKA_LABEL, Settings.ApplicationName); pubKeyTemplate[3] = CkaUtils.CreateAttribute(CKA.CKA_ID, ckaId); pubKeyTemplate[4] = CkaUtils.CreateAttribute(CKA.CKA_ENCRYPT, true); pubKeyTemplate[5] = CkaUtils.CreateAttribute(CKA.CKA_VERIFY, true); pubKeyTemplate[6] = CkaUtils.CreateAttribute(CKA.CKA_VERIFY_RECOVER, true); pubKeyTemplate[7] = CkaUtils.CreateAttribute(CKA.CKA_WRAP, true); pubKeyTemplate[8] = CkaUtils.CreateAttribute(CKA.CKA_MODULUS_BITS, 1024); pubKeyTemplate[9] = CkaUtils.CreateAttribute(CKA.CKA_PUBLIC_EXPONENT, new byte[] { 0x01, 0x00, 0x01 }); // Prepare attribute template of new private key CK_ATTRIBUTE[] privKeyTemplate = new CK_ATTRIBUTE[9]; privKeyTemplate[0] = CkaUtils.CreateAttribute(CKA.CKA_TOKEN, true); privKeyTemplate[1] = CkaUtils.CreateAttribute(CKA.CKA_PRIVATE, true); privKeyTemplate[2] = CkaUtils.CreateAttribute(CKA.CKA_LABEL, Settings.ApplicationName); privKeyTemplate[3] = CkaUtils.CreateAttribute(CKA.CKA_ID, ckaId); privKeyTemplate[4] = CkaUtils.CreateAttribute(CKA.CKA_SENSITIVE, true); privKeyTemplate[5] = CkaUtils.CreateAttribute(CKA.CKA_DECRYPT, true); privKeyTemplate[6] = CkaUtils.CreateAttribute(CKA.CKA_SIGN, true); privKeyTemplate[7] = CkaUtils.CreateAttribute(CKA.CKA_SIGN_RECOVER, true); privKeyTemplate[8] = CkaUtils.CreateAttribute(CKA.CKA_UNWRAP, true); // Specify key generation mechanism (needs no parameter => no unamanaged memory is needed) CK_MECHANISM mechanism = CkmUtils.CreateMechanism(CKM.CKM_RSA_PKCS_KEY_PAIR_GEN); // Generate key pair ulong pubKeyId = CK.CK_INVALID_HANDLE; ulong privKeyId = CK.CK_INVALID_HANDLE; rv = pkcs11.C_GenerateKeyPair(session, ref mechanism, pubKeyTemplate, Convert.ToUInt64(pubKeyTemplate.Length), privKeyTemplate, Convert.ToUInt64(privKeyTemplate.Length), ref pubKeyId, ref privKeyId); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); // In LowLevelAPI we have to free unmanaged memory taken by attributes for (int i = 0; i < privKeyTemplate.Length; i++) { UnmanagedMemory.Free(ref privKeyTemplate[i].value); privKeyTemplate[i].valueLen = 0; } for (int i = 0; i < pubKeyTemplate.Length; i++) { UnmanagedMemory.Free(ref pubKeyTemplate[i].value); pubKeyTemplate[i].valueLen = 0; } // Do something interesting with generated key pair // Destroy object rv = pkcs11.C_DestroyObject(session, privKeyId); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); rv = pkcs11.C_DestroyObject(session, pubKeyId); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); rv = pkcs11.C_Logout(session); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); rv = pkcs11.C_CloseSession(session); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); rv = pkcs11.C_Finalize(IntPtr.Zero); if (rv != CKR.CKR_OK) Assert.Fail(rv.ToString()); } } } }
using J2N.Threading; using Lucene.Net.Documents; using Lucene.Net.Index.Extensions; using Lucene.Net.Search; using NUnit.Framework; using System; using System.Collections.Generic; using System.IO; using System.Threading; using JCG = J2N.Collections.Generic; using Assert = Lucene.Net.TestFramework.Assert; using Console = Lucene.Net.Util.SystemConsole; namespace Lucene.Net.Index { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using BinaryDocValuesField = BinaryDocValuesField; using BytesRef = Lucene.Net.Util.BytesRef; using Directory = Lucene.Net.Store.Directory; using Document = Documents.Document; using LuceneTestCase = Lucene.Net.Util.LuceneTestCase; using MockAnalyzer = Lucene.Net.Analysis.MockAnalyzer; using NumericDocValuesField = NumericDocValuesField; using SortedDocValuesField = SortedDocValuesField; using TestUtil = Lucene.Net.Util.TestUtil; [SuppressCodecs("Lucene3x")] [TestFixture] public class TestDocValuesWithThreads : LuceneTestCase { [Test] public virtual void Test() { Directory dir = NewDirectory(); IndexWriter w = new IndexWriter(dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random)).SetMergePolicy(NewLogMergePolicy())); IList<long?> numbers = new List<long?>(); IList<BytesRef> binary = new List<BytesRef>(); IList<BytesRef> sorted = new List<BytesRef>(); int numDocs = AtLeast(100); for (int i = 0; i < numDocs; i++) { Document d = new Document(); long number = Random.NextInt64(); d.Add(new NumericDocValuesField("number", number)); BytesRef bytes = new BytesRef(TestUtil.RandomRealisticUnicodeString(Random)); d.Add(new BinaryDocValuesField("bytes", bytes)); binary.Add(bytes); bytes = new BytesRef(TestUtil.RandomRealisticUnicodeString(Random)); d.Add(new SortedDocValuesField("sorted", bytes)); sorted.Add(bytes); w.AddDocument(d); numbers.Add(number); } w.ForceMerge(1); IndexReader r = w.GetReader(); w.Dispose(); Assert.AreEqual(1, r.Leaves.Count); AtomicReader ar = (AtomicReader)r.Leaves[0].Reader; int numThreads = TestUtil.NextInt32(Random, 2, 5); IList<ThreadJob> threads = new List<ThreadJob>(); CountdownEvent startingGun = new CountdownEvent(1); for (int t = 0; t < numThreads; t++) { Random threadRandom = new Random(Random.Next()); ThreadJob thread = new ThreadAnonymousInnerClassHelper(this, numbers, binary, sorted, numDocs, ar, startingGun, threadRandom); thread.Start(); threads.Add(thread); } startingGun.Signal(); foreach (ThreadJob thread in threads) { thread.Join(); } r.Dispose(); dir.Dispose(); } private class ThreadAnonymousInnerClassHelper : ThreadJob { private readonly TestDocValuesWithThreads outerInstance; private readonly IList<long?> numbers; private readonly IList<BytesRef> binary; private readonly IList<BytesRef> sorted; private readonly int numDocs; private readonly AtomicReader ar; private readonly CountdownEvent startingGun; private readonly Random threadRandom; public ThreadAnonymousInnerClassHelper(TestDocValuesWithThreads outerInstance, IList<long?> numbers, IList<BytesRef> binary, IList<BytesRef> sorted, int numDocs, AtomicReader ar, CountdownEvent startingGun, Random threadRandom) { this.outerInstance = outerInstance; this.numbers = numbers; this.binary = binary; this.sorted = sorted; this.numDocs = numDocs; this.ar = ar; this.startingGun = startingGun; this.threadRandom = threadRandom; } public override void Run() { try { //NumericDocValues ndv = ar.GetNumericDocValues("number"); FieldCache.Int64s ndv = FieldCache.DEFAULT.GetInt64s(ar, "number", false); //BinaryDocValues bdv = ar.GetBinaryDocValues("bytes"); BinaryDocValues bdv = FieldCache.DEFAULT.GetTerms(ar, "bytes", false); SortedDocValues sdv = FieldCache.DEFAULT.GetTermsIndex(ar, "sorted"); startingGun.Wait(); int iters = AtLeast(1000); BytesRef scratch = new BytesRef(); BytesRef scratch2 = new BytesRef(); for (int iter = 0; iter < iters; iter++) { int docID = threadRandom.Next(numDocs); switch (threadRandom.Next(6)) { #pragma warning disable 612, 618 case 0: Assert.AreEqual((long)(sbyte)numbers[docID], (sbyte)FieldCache.DEFAULT.GetBytes(ar, "number", false).Get(docID)); break; case 1: Assert.AreEqual((long)(short)numbers[docID], FieldCache.DEFAULT.GetInt16s(ar, "number", false).Get(docID)); break; #pragma warning restore 612, 618 case 2: Assert.AreEqual((long)(int)numbers[docID], FieldCache.DEFAULT.GetInt32s(ar, "number", false).Get(docID)); break; case 3: Assert.AreEqual((long)numbers[docID], FieldCache.DEFAULT.GetInt64s(ar, "number", false).Get(docID)); break; case 4: Assert.AreEqual(J2N.BitConversion.Int32BitsToSingle((int)numbers[docID]), FieldCache.DEFAULT.GetSingles(ar, "number", false).Get(docID), 0.0f); break; case 5: Assert.AreEqual(J2N.BitConversion.Int64BitsToDouble((long)numbers[docID]), FieldCache.DEFAULT.GetDoubles(ar, "number", false).Get(docID), 0.0); break; } bdv.Get(docID, scratch); Assert.AreEqual(binary[docID], scratch); // Cannot share a single scratch against two "sources": sdv.Get(docID, scratch2); Assert.AreEqual(sorted[docID], scratch2); } } catch (Exception e) { throw new Exception(e.Message, e); } } } [Test] [Timeout(600000)] public virtual void Test2() { Random random = Random; int NUM_DOCS = AtLeast(100); Directory dir = NewDirectory(); RandomIndexWriter writer = new RandomIndexWriter( #if FEATURE_INSTANCE_TESTDATA_INITIALIZATION this, #endif random, dir); bool allowDups = random.NextBoolean(); ISet<string> seen = new JCG.HashSet<string>(); if (Verbose) { Console.WriteLine("TEST: NUM_DOCS=" + NUM_DOCS + " allowDups=" + allowDups); } int numDocs = 0; IList<BytesRef> docValues = new List<BytesRef>(); // TODO: deletions while (numDocs < NUM_DOCS) { string s; if (random.NextBoolean()) { s = TestUtil.RandomSimpleString(random); } else { s = TestUtil.RandomUnicodeString(random); } BytesRef br = new BytesRef(s); if (!allowDups) { if (seen.Contains(s)) { continue; } seen.Add(s); } if (Verbose) { Console.WriteLine(" " + numDocs + ": s=" + s); } Document doc = new Document(); doc.Add(new SortedDocValuesField("stringdv", br)); doc.Add(new NumericDocValuesField("id", numDocs)); docValues.Add(br); writer.AddDocument(doc); numDocs++; if (random.Next(40) == 17) { // force flush writer.GetReader().Dispose(); } } writer.ForceMerge(1); DirectoryReader r = writer.GetReader(); writer.Dispose(); AtomicReader sr = GetOnlySegmentReader(r); long END_TIME = Environment.TickCount + (TestNightly ? 30 : 1); int NUM_THREADS = TestUtil.NextInt32(LuceneTestCase.Random, 1, 10); ThreadJob[] threads = new ThreadJob[NUM_THREADS]; for (int thread = 0; thread < NUM_THREADS; thread++) { threads[thread] = new ThreadAnonymousInnerClassHelper2(random, docValues, sr, END_TIME); threads[thread].Start(); } foreach (ThreadJob thread in threads) { thread.Join(); } r.Dispose(); dir.Dispose(); } private class ThreadAnonymousInnerClassHelper2 : ThreadJob { private readonly Random random; private readonly IList<BytesRef> docValues; private readonly AtomicReader sr; private readonly long endTime; public ThreadAnonymousInnerClassHelper2(Random random, IList<BytesRef> docValues, AtomicReader sr, long endTime) { this.random = random; this.docValues = docValues; this.sr = sr; this.endTime = endTime; } public override void Run() { SortedDocValues stringDVDirect; NumericDocValues docIDToID; try { stringDVDirect = sr.GetSortedDocValues("stringdv"); docIDToID = sr.GetNumericDocValues("id"); Assert.IsNotNull(stringDVDirect); } catch (IOException ioe) { throw new Exception(ioe.ToString(), ioe); } while (Environment.TickCount < endTime) { SortedDocValues source; source = stringDVDirect; BytesRef scratch = new BytesRef(); for (int iter = 0; iter < 100; iter++) { int docID = random.Next(sr.MaxDoc); source.Get(docID, scratch); Assert.AreEqual(docValues[(int)docIDToID.Get(docID)], scratch); } } } } } }
// <copyright file="B3Propagator.cs" company="OpenTelemetry Authors"> // Copyright The OpenTelemetry 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. // </copyright> using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using OpenTelemetry.Internal; namespace OpenTelemetry.Context.Propagation { /// <summary> /// A text map propagator for B3. See https://github.com/openzipkin/b3-propagation. /// </summary> public sealed class B3Propagator : TextMapPropagator { internal const string XB3TraceId = "X-B3-TraceId"; internal const string XB3SpanId = "X-B3-SpanId"; internal const string XB3ParentSpanId = "X-B3-ParentSpanId"; internal const string XB3Sampled = "X-B3-Sampled"; internal const string XB3Flags = "X-B3-Flags"; internal const string XB3Combined = "b3"; internal const char XB3CombinedDelimiter = '-'; // Used as the upper ActivityTraceId.SIZE hex characters of the traceID. B3-propagation used to send // ActivityTraceId.SIZE hex characters (8-bytes traceId) in the past. internal const string UpperTraceId = "0000000000000000"; // Sampled values via the X_B3_SAMPLED header. internal const string SampledValue = "1"; // Some old zipkin implementations may send true/false for the sampled header. Only use this for checking incoming values. internal const string LegacySampledValue = "true"; // "Debug" sampled value. internal const string FlagsValue = "1"; private static readonly HashSet<string> AllFields = new HashSet<string>() { XB3TraceId, XB3SpanId, XB3ParentSpanId, XB3Sampled, XB3Flags }; private static readonly HashSet<string> SampledValues = new HashSet<string>(StringComparer.Ordinal) { SampledValue, LegacySampledValue }; private readonly bool singleHeader; /// <summary> /// Initializes a new instance of the <see cref="B3Propagator"/> class. /// </summary> public B3Propagator() : this(false) { } /// <summary> /// Initializes a new instance of the <see cref="B3Propagator"/> class. /// </summary> /// <param name="singleHeader">Determines whether to use single or multiple headers when extracting or injecting span context.</param> public B3Propagator(bool singleHeader) { this.singleHeader = singleHeader; } /// <inheritdoc/> public override ISet<string> Fields => AllFields; /// <inheritdoc/> public override PropagationContext Extract<T>(PropagationContext context, T carrier, Func<T, string, IEnumerable<string>> getter) { if (context.ActivityContext.IsValid()) { // If a valid context has already been extracted, perform a noop. return context; } if (carrier == null) { OpenTelemetryApiEventSource.Log.FailedToExtractActivityContext(nameof(B3Propagator), "null carrier"); return context; } if (getter == null) { OpenTelemetryApiEventSource.Log.FailedToExtractActivityContext(nameof(B3Propagator), "null getter"); return context; } if (this.singleHeader) { return ExtractFromSingleHeader(context, carrier, getter); } else { return ExtractFromMultipleHeaders(context, carrier, getter); } } /// <inheritdoc/> public override void Inject<T>(PropagationContext context, T carrier, Action<T, string, string> setter) { if (context.ActivityContext.TraceId == default || context.ActivityContext.SpanId == default) { OpenTelemetryApiEventSource.Log.FailedToInjectActivityContext(nameof(B3Propagator), "invalid context"); return; } if (carrier == null) { OpenTelemetryApiEventSource.Log.FailedToInjectActivityContext(nameof(B3Propagator), "null carrier"); return; } if (setter == null) { OpenTelemetryApiEventSource.Log.FailedToInjectActivityContext(nameof(B3Propagator), "null setter"); return; } if (this.singleHeader) { var sb = new StringBuilder(); sb.Append(context.ActivityContext.TraceId.ToHexString()); sb.Append(XB3CombinedDelimiter); sb.Append(context.ActivityContext.SpanId.ToHexString()); if ((context.ActivityContext.TraceFlags & ActivityTraceFlags.Recorded) != 0) { sb.Append(XB3CombinedDelimiter); sb.Append(SampledValue); } setter(carrier, XB3Combined, sb.ToString()); } else { setter(carrier, XB3TraceId, context.ActivityContext.TraceId.ToHexString()); setter(carrier, XB3SpanId, context.ActivityContext.SpanId.ToHexString()); if ((context.ActivityContext.TraceFlags & ActivityTraceFlags.Recorded) != 0) { setter(carrier, XB3Sampled, SampledValue); } } } private static PropagationContext ExtractFromMultipleHeaders<T>(PropagationContext context, T carrier, Func<T, string, IEnumerable<string>> getter) { try { ActivityTraceId traceId; var traceIdStr = getter(carrier, XB3TraceId)?.FirstOrDefault(); if (traceIdStr != null) { if (traceIdStr.Length == 16) { // This is an 8-byte traceID. traceIdStr = UpperTraceId + traceIdStr; } traceId = ActivityTraceId.CreateFromString(traceIdStr.AsSpan()); } else { return context; } ActivitySpanId spanId; var spanIdStr = getter(carrier, XB3SpanId)?.FirstOrDefault(); if (spanIdStr != null) { spanId = ActivitySpanId.CreateFromString(spanIdStr.AsSpan()); } else { return context; } var traceOptions = ActivityTraceFlags.None; if (SampledValues.Contains(getter(carrier, XB3Sampled)?.FirstOrDefault()) || FlagsValue.Equals(getter(carrier, XB3Flags)?.FirstOrDefault(), StringComparison.Ordinal)) { traceOptions |= ActivityTraceFlags.Recorded; } return new PropagationContext( new ActivityContext(traceId, spanId, traceOptions, isRemote: true), context.Baggage); } catch (Exception e) { OpenTelemetryApiEventSource.Log.ActivityContextExtractException(nameof(B3Propagator), e); return context; } } private static PropagationContext ExtractFromSingleHeader<T>(PropagationContext context, T carrier, Func<T, string, IEnumerable<string>> getter) { try { var header = getter(carrier, XB3Combined)?.FirstOrDefault(); if (string.IsNullOrWhiteSpace(header)) { return context; } var parts = header.Split(XB3CombinedDelimiter); if (parts.Length < 2 || parts.Length > 4) { return context; } var traceIdStr = parts[0]; if (string.IsNullOrWhiteSpace(traceIdStr)) { return context; } if (traceIdStr.Length == 16) { // This is an 8-byte traceID. traceIdStr = UpperTraceId + traceIdStr; } var traceId = ActivityTraceId.CreateFromString(traceIdStr.AsSpan()); var spanIdStr = parts[1]; if (string.IsNullOrWhiteSpace(spanIdStr)) { return context; } var spanId = ActivitySpanId.CreateFromString(spanIdStr.AsSpan()); var traceOptions = ActivityTraceFlags.None; if (parts.Length > 2) { var traceFlagsStr = parts[2]; if (SampledValues.Contains(traceFlagsStr) || FlagsValue.Equals(traceFlagsStr, StringComparison.Ordinal)) { traceOptions |= ActivityTraceFlags.Recorded; } } return new PropagationContext( new ActivityContext(traceId, spanId, traceOptions, isRemote: true), context.Baggage); } catch (Exception e) { OpenTelemetryApiEventSource.Log.ActivityContextExtractException(nameof(B3Propagator), e); return context; } } } }
/* * Copyright (c) InWorldz Halcyon Developers * Copyright (c) Contributors, http://opensimulator.org/ * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSim 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. */ /* This version has been heavily modified from it's original version by InWorldz,LLC * Beth Reischl - 3/25/2010 */ using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Net; using System.Net.Sockets; using System.Reflection; using OpenMetaverse; using TransactionInfoBlock = OpenMetaverse.Packets.MoneyBalanceReplyPacket.TransactionInfoBlock; using log4net; using Nini.Config; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Framework.Servers.HttpServer; using OpenSim.Framework.Communications.Cache; using OpenSim.Region.CoreModules.Avatar.Dialog; using OpenSim.Data.SimpleDB; namespace OpenSim.Region.CoreModules.Avatar.Currency { public class AvatarCurrency : IMoneyModule, IRegionModule { // // Log module // private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); // // Module vars // private Dictionary<ulong, Scene> m_scenel = new Dictionary<ulong, Scene>(); private ConnectionFactory _connFactory; public static UUID CURRENCY_ACCOUNT_ID = new UUID("efbfe4e6-95c2-4af3-9d27-25a35c2fd575"); /// <summary> /// Setup of the base vars that will be pulled from the ini file /// </summary> /// private float EnergyEfficiency = 0f; //private ObjectPaid handlerOnObjectPaid; private int ObjectCapacity = OpenSim.Framework.RegionInfo.DEFAULT_REGION_PRIM_LIMIT; private int ObjectCount = 0; private int PriceEnergyUnit = 0; private int PriceGroupCreate = 0; private int PriceObjectClaim = 0; private float PriceObjectRent = 0f; private float PriceObjectScaleFactor = 0f; private int PriceParcelClaim = 0; private float PriceParcelClaimFactor = 0f; private int PriceParcelRent = 0; private int PricePublicObjectDecay = 0; private int PricePublicObjectDelete = 0; private int PriceRentLight = 0; private int PriceUpload = 0; private int TeleportMinPrice = 0; private int MinDebugMoney = Int32.MinValue; private float TeleportPriceExponent = 0f; #region AvatarCurrency Members public event ObjectPaid OnObjectPaid; public void Initialize(Scene scene, IConfigSource config) { IConfig economyConfig = config.Configs["Economy"]; // Adding the line from Profile in order to get the connection string // TODO: clean up the ini file to just allow this connection for Profile, Search and Money IConfig profileConfig = config.Configs["Profile"]; string connstr = profileConfig.GetString("ProfileConnString", String.Empty); _connFactory = new ConnectionFactory("MySQL", connstr); m_log.Info("[CURRENCY] InWorldz Currency Module is activated"); const int DEFAULT_PRICE_ENERGY_UNIT = 100; const int DEFAULT_PRICE_OBJECT_CLAIM = 10; const int DEFAULT_PRICE_PUBLIC_OBJECT_DECAY = 4; const int DEFAULT_PRICE_PUBLIC_OBJECT_DELETE = 4; const int DEFAULT_PRICE_PARCEL_CLAIM = 1; const float DEFAULT_PRICE_PARCEL_CLAIM_FACTOR = 1f; const int DEFAULT_PRICE_UPLOAD = 0; const int DEFAULT_PRICE_RENT_LIGHT = 5; const int DEFAULT_TELEPORT_MIN_PRICE = 2; const float DEFAULT_TELEPORT_PRICE_EXPONENT = 2f; const int DEFAULT_ENERGY_EFFICIENCY = 1; const int DEFALULT_PRICE_OBJECT_RENT = 1; const int DEFAULT_PRICE_OBJECT_SCALE_FACTOR = 10; const int DEFAULT_PRICE_PARCEL_RENT = 1; const int DEFAULT_PRICE_GROUP_CREATE = -1; if (economyConfig != null) { ObjectCapacity = economyConfig.GetInt("ObjectCapacity", OpenSim.Framework.RegionInfo.DEFAULT_REGION_PRIM_LIMIT); PriceEnergyUnit = economyConfig.GetInt("PriceEnergyUnit", DEFAULT_PRICE_ENERGY_UNIT); PriceObjectClaim = economyConfig.GetInt("PriceObjectClaim", DEFAULT_PRICE_OBJECT_CLAIM); PricePublicObjectDecay = economyConfig.GetInt("PricePublicObjectDecay", DEFAULT_PRICE_PUBLIC_OBJECT_DECAY); PricePublicObjectDelete = economyConfig.GetInt("PricePublicObjectDelete", DEFAULT_PRICE_PUBLIC_OBJECT_DELETE); PriceParcelClaim = economyConfig.GetInt("PriceParcelClaim", DEFAULT_PRICE_PARCEL_CLAIM); PriceParcelClaimFactor = economyConfig.GetFloat("PriceParcelClaimFactor", DEFAULT_PRICE_PARCEL_CLAIM_FACTOR); PriceUpload = economyConfig.GetInt("PriceUpload", DEFAULT_PRICE_UPLOAD); PriceRentLight = economyConfig.GetInt("PriceRentLight", DEFAULT_PRICE_RENT_LIGHT); TeleportMinPrice = economyConfig.GetInt("TeleportMinPrice", DEFAULT_TELEPORT_MIN_PRICE); TeleportPriceExponent = economyConfig.GetFloat("TeleportPriceExponent", DEFAULT_TELEPORT_PRICE_EXPONENT); EnergyEfficiency = economyConfig.GetFloat("EnergyEfficiency", DEFAULT_ENERGY_EFFICIENCY); PriceObjectRent = economyConfig.GetFloat("PriceObjectRent", DEFALULT_PRICE_OBJECT_RENT); PriceObjectScaleFactor = economyConfig.GetFloat("PriceObjectScaleFactor", DEFAULT_PRICE_OBJECT_SCALE_FACTOR); PriceParcelRent = economyConfig.GetInt("PriceParcelRent", DEFAULT_PRICE_PARCEL_RENT); PriceGroupCreate = economyConfig.GetInt("PriceGroupCreate", DEFAULT_PRICE_GROUP_CREATE); // easy way for all accounts on debug servers to have some cash to test Buy operations and transfers MinDebugMoney = economyConfig.GetInt("MinDebugMoney", Int32.MinValue); if (MinDebugMoney != Int32.MinValue) m_log.InfoFormat("[CURRENCY] MinDebugMoney activated at: {0}", MinDebugMoney); } else { ObjectCapacity = OpenSim.Framework.RegionInfo.DEFAULT_REGION_PRIM_LIMIT; PriceEnergyUnit = DEFAULT_PRICE_ENERGY_UNIT; PriceObjectClaim = DEFAULT_PRICE_OBJECT_CLAIM; PricePublicObjectDecay = DEFAULT_PRICE_PUBLIC_OBJECT_DECAY; PricePublicObjectDelete = DEFAULT_PRICE_PUBLIC_OBJECT_DELETE; PriceParcelClaim = DEFAULT_PRICE_PARCEL_CLAIM; PriceParcelClaimFactor = DEFAULT_PRICE_PARCEL_CLAIM_FACTOR; PriceUpload = DEFAULT_PRICE_UPLOAD; PriceRentLight = DEFAULT_PRICE_RENT_LIGHT; TeleportMinPrice = DEFAULT_TELEPORT_MIN_PRICE; TeleportPriceExponent = DEFAULT_TELEPORT_PRICE_EXPONENT; EnergyEfficiency = DEFAULT_ENERGY_EFFICIENCY; PriceObjectRent = DEFALULT_PRICE_OBJECT_RENT; PriceObjectScaleFactor = DEFAULT_PRICE_OBJECT_SCALE_FACTOR; PriceParcelRent = DEFAULT_PRICE_PARCEL_RENT; PriceGroupCreate = DEFAULT_PRICE_GROUP_CREATE; MinDebugMoney = Int32.MinValue; } scene.RegisterModuleInterface<IMoneyModule>(this); IHttpServer httpServer = scene.CommsManager.HttpServer; if (m_scenel.ContainsKey(scene.RegionInfo.RegionHandle)) { m_scenel[scene.RegionInfo.RegionHandle] = scene; } else { m_scenel.Add(scene.RegionInfo.RegionHandle, scene); } scene.EventManager.OnNewClient += OnNewClient; scene.EventManager.OnMoneyTransfer += MoneyTransferAction; scene.EventManager.OnClassifiedPayment += ClassifiedPayment; scene.EventManager.OnValidateLandBuy += ValidateLandBuy; scene.EventManager.OnLandBuy += processLandBuy; /* scene.EventManager.OnAvatarEnteringNewParcel += AvatarEnteringParcel; scene.EventManager.OnMakeChildAgent += MakeChildAgent; scene.EventManager.OnClientClosed += ClientLoggedOut; */ } public bool UploadChargeApplies(AssetType type) { if (PriceUpload <= 0) return false; return (type == AssetType.Texture) || (type == AssetType.Sound) || (type == AssetType.ImageTGA) || (type == AssetType.TextureTGA) || (type == AssetType.Animation); } public bool UploadCovered(UUID agentID) { return AmountCovered(agentID, PriceUpload); } public void ApplyUploadCharge(UUID agentID) { if (PriceUpload > 0) ApplyCharge(agentID, (int)MoneyTransactionType.UploadCharge, PriceUpload, "upload"); } public int MeshUploadCharge(int meshCount, int textureCount) { return (meshCount * PriceUpload) + (textureCount * PriceUpload); } public bool MeshUploadCovered(UUID agentID, int meshCount, int textureCount) { int amount = MeshUploadCharge(meshCount, textureCount); return AmountCovered(agentID, amount); } public void ApplyMeshUploadCharge(UUID agentID, int meshCount, int textureCount) { int transAmount = MeshUploadCharge(meshCount, textureCount); if (transAmount <= 0) return; string transDesc = "mesh upload"; int transCode = (int)MoneyTransactionType.UploadCharge; UUID transID = ApplyCharge(agentID, transCode, transAmount, transDesc); // The viewer notifies the user for most upload transactions, except for mesh uploads. // So if there's a client, notify them now. IClientAPI client = LocateClientObject(agentID); if (client != null) { TransactionInfoBlock transInfo = new TransactionInfoBlock(); transInfo.Amount = transAmount; transInfo.TransactionType = transCode; transInfo.SourceID = agentID; transInfo.DestID = UUID.Zero; transInfo.IsSourceGroup = false; transInfo.IsDestGroup = false; transInfo.ItemDescription = Util.StringToBytes256(transDesc); string message; if (String.IsNullOrEmpty(transDesc)) message = "You paid $" + transAmount.ToString() + "."; else message = "You paid $" + transAmount.ToString() + " for " + transDesc + "."; SendMoneyBalanceTransaction(client, transID, true, message, transInfo); } } public bool GroupCreationCovered(UUID agentID) { m_log.Debug("[MONEY]: In Group Creating, of GroupCreationCovered."); return AmountCovered(agentID, PriceGroupCreate); } public void ApplyGroupCreationCharge(UUID agentID) { if (PriceGroupCreate > 0) ApplyCharge(agentID, (int)MoneyTransactionType.GroupCreate, PriceGroupCreate, "group creation"); } // transCode is the transaction code, e.g. 1101 for uploads public UUID ApplyCharge(UUID agentID, int transCode, int transAmount, string transDesc) { // for transCodes, see comments at EOF UUID transID = doMoneyTransfer(agentID, CURRENCY_ACCOUNT_ID, transAmount, transCode, transDesc); return transID; } public void PostInitialize() { } public void Close() { } public string Name { get { return "InWorldzCurrencyModule"; } } public bool IsSharedModule { get { return true; } } #endregion public EconomyData GetEconomyData() { EconomyData edata = new EconomyData(); edata.ObjectCapacity = ObjectCapacity; edata.ObjectCount = ObjectCount; edata.PriceEnergyUnit = PriceEnergyUnit; edata.PriceGroupCreate = PriceGroupCreate; edata.PriceObjectClaim = PriceObjectClaim; edata.PriceObjectRent = PriceObjectRent; edata.PriceObjectScaleFactor = PriceObjectScaleFactor; edata.PriceParcelClaim = PriceParcelClaim; edata.PriceParcelClaimFactor = PriceParcelClaimFactor; edata.PriceParcelRent = PriceParcelRent; edata.PricePublicObjectDecay = PricePublicObjectDecay; edata.PricePublicObjectDelete = PricePublicObjectDelete; edata.PriceRentLight = PriceRentLight; edata.PriceUpload = PriceUpload; edata.TeleportMinPrice = TeleportMinPrice; return edata; } private void OnNewClient(IClientAPI client) { client.OnEconomyDataRequest += EconomyDataRequestHandler; //client.OnMoneyBalanceRequest += GetClientFunds(client); client.OnRequestPayPrice += requestPayPrice; client.OnObjectBuy += ObjectBuy; client.OnMoneyBalanceRequest += OnMoneyBalanceRequest; } private void EconomyDataRequestHandler(IClientAPI client, UUID agentID) { client.SendEconomyData(EnergyEfficiency, ObjectCapacity, ObjectCount, PriceEnergyUnit, PriceGroupCreate, PriceObjectClaim, PriceObjectRent, PriceObjectScaleFactor, PriceParcelClaim, PriceParcelClaimFactor, PriceParcelRent, PricePublicObjectDecay, PricePublicObjectDelete, PriceRentLight, PriceUpload, TeleportMinPrice, TeleportPriceExponent); } private void OnMoneyBalanceRequest(IClientAPI remoteClient, UUID agentID, UUID sessionID, UUID TransactionID) { Util.FireAndForget(delegate(object obj) { SendMoneyBalance(remoteClient); }); } /// <summary> /// Get the Current Balance /// </summary> /// <param name="avatarID">UUID of the avatar we're getting balance for</param> /// <returns></returns> private int getCurrentBalance(UUID avatarID) { int avatarFunds = 0; using (ISimpleDB db = _connFactory.GetConnection()) { const string TOTALS_SEARCH = "SELECT total FROM economy_totals WHERE user_id=?avatarID"; Dictionary<string, object> parms = new Dictionary<string, object>(); parms.Add("?avatarID", avatarID); List<Dictionary<string, string>> fundsResult = db.QueryWithResults(TOTALS_SEARCH, parms); if (fundsResult.Count == 1) { avatarFunds = Convert.ToInt32(fundsResult[0]["total"]); } else if (fundsResult.Count == 0) { //this user does not yet have a totals entry, we need to insert one const string TOTALS_POPULATOR = "INSERT IGNORE INTO economy_totals(user_id, total) " + "SELECT ?avatarID, SUM(transactionAmount) FROM economy_transaction WHERE destAvatarID = ?avatarID;"; db.QueryNoResults(TOTALS_POPULATOR, parms); //search again for the new total we just inserted fundsResult = db.QueryWithResults(TOTALS_SEARCH, parms); if (fundsResult.Count == 0) { //something is horribly wrong m_log.ErrorFormat("[CURRENCY]: Could not obtain currency total for avatar {0} after initial population", avatarID); avatarFunds = 0; } else { avatarFunds = Convert.ToInt32(fundsResult[0]["total"]); } } else { //something is horribly wrong m_log.ErrorFormat("[CURRENCY]: Multiple currency totals found for {0}. Table corrupt?", avatarID); avatarFunds = 0; } if (avatarFunds < MinDebugMoney) // only if configfile has MinDebugMoney=nnn avatarFunds = MinDebugMoney; // allow testing with fake money that restocks on login return avatarFunds; } } // See comments at the end of this file for the meaning of 'type' here (transaction type). private UUID doMoneyTransfer(UUID sourceAvatarID, UUID destAvatarID, int amount, int type, string description) { if (amount < 0) return UUID.Zero; // This is where we do all transfers of monies. This is a two step process, one to update the giver, and one // to update the recipient. using (ISimpleDB db = _connFactory.GetConnection()) { //verify the existance of the source and destination avatars Dictionary<string, object> testParms = new Dictionary<string, object>(); testParms.Add("?sourceAvatarID", sourceAvatarID); testParms.Add("?destAvatarID", destAvatarID); List<Dictionary<string, string>> results = db.QueryWithResults("SELECT COUNT(*) as matchCount FROM users WHERE UUID IN (?sourceAvatarID, ?destAvatarID);", testParms); if (results[0]["matchCount"] != "2") { if ((sourceAvatarID != destAvatarID) || (results[0]["matchCount"] != "1")) // don't report user paying themself m_log.Debug("[CURRENCY]: Source or destination avatar(s) do not exist in transaction. This is most likely a spoofed destination."); return UUID.Zero; } DateTime saveNow = DateTime.Now; int saveTime = Util.ToUnixTime(saveNow); Dictionary<string, object> parms = new Dictionary<string, object>(); parms.Add("?sourceAvatarID", sourceAvatarID); parms.Add("?destAvatarID", destAvatarID); parms.Add("?amount", amount); parms.Add("?debit", -amount); parms.Add("?type", type); parms.Add("?description", description); parms.Add("?time", saveTime); string bankQuery1 = "insert into economy_transaction (sourceAvatarID, destAvatarID, transactionAmount, transactionType, transactionDescription, timeOccurred) " + "VALUES (?sourceAvatarID, ?destAvatarID, ?amount, ?type, ?description, ?time)"; db.QueryNoResults(bankQuery1, parms); testParms.Clear(); results = db.QueryWithResults("SELECT LAST_INSERT_ID() AS id;", testParms); ulong transationID = Convert.ToUInt64(results[0]["id"]); string bankQuery2 = "insert into economy_transaction (sourceAvatarID, destAvatarID, transactionAmount, transactionType, transactionDescription, timeOccurred) " + "VALUES (?destAvatarID, ?sourceAvatarID, ?debit, ?type, ?description, ?time)"; db.QueryNoResults(bankQuery2, parms); return new UUID(transationID); } } /// <summary> /// Send the Balance to the viewer /// </summary> /// <param name="client">Client requesting information</param> private void SendMoneyBalanceTransaction(IClientAPI client, UUID transaction, bool success, string transactionDescription, TransactionInfoBlock transInfo) { UUID avatarID = client.AgentId; int avatarFunds = getCurrentBalance(avatarID); client.SendMoneyBalance(transaction, success, transactionDescription, avatarFunds, transInfo); } // Send a pure balance notification only. private void SendMoneyBalance(IClientAPI client) { SendMoneyBalanceTransaction(client, UUID.Zero, true, String.Empty, null); } // Returns the transaction ID that shows up in the transaction history. public string ObjectGiveMoney(UUID objectID, UUID sourceAvatarID, UUID destAvatarID, int amount, out string reason) { reason = String.Empty; if (amount <= 0) { reason = "INVALID_AMOUNT"; return String.Empty; } SceneObjectPart part = findPrim(objectID); if (part == null) { reason = "MISSING_PERMISSION_DEBIT"; // if you can't find it, no perms either return String.Empty; } string objName = part.ParentGroup.Name; string description = String.Format("{0} paid {1}", objName, resolveAgentName(destAvatarID)); int transType = (int)MoneyTransactionType.ObjectPays; if (amount > 0) { // allow users with negative balances to buy freebies int sourceAvatarFunds = getCurrentBalance(sourceAvatarID); if (sourceAvatarFunds < amount) { reason = "LINDENDOLLAR_INSUFFICIENTFUNDS"; return String.Empty; } } UUID transID = doMoneyTransfer(sourceAvatarID, destAvatarID, amount, transType, description); // the transID UUID is actually a ulong stored in a UUID. string result = transID.GetULong().ToString(); reason = String.Empty; TransactionInfoBlock transInfo = new TransactionInfoBlock(); transInfo.Amount = amount; transInfo.TransactionType = transType; transInfo.SourceID = sourceAvatarID; transInfo.DestID = destAvatarID; transInfo.IsSourceGroup = false; transInfo.IsDestGroup = false; transInfo.ItemDescription = Util.StringToBytes256(objName); IClientAPI sourceAvatarClient = LocateClientObject(sourceAvatarID); if (sourceAvatarClient == null) { // Just a quick catch for a null reference, just cause they can't be found doesn't // mean the item can't pay out the money. } else { string sourceText = objName + " paid out Iz$" + amount + " to " + resolveAgentName(destAvatarID); SendMoneyBalanceTransaction(sourceAvatarClient, transID, true, sourceText, transInfo); } IClientAPI destAvatarClient = LocateClientObject(destAvatarID); if(destAvatarClient == null) { // Quick catch due to scene issues, don't want to it to fall down if // the destination avatar is not in the same scene list or online at all. } else { string destText = "You were paid Iz$" + amount + " by " + part.ParentGroup.Name; SendMoneyBalanceTransaction(destAvatarClient, transID, true, destText, transInfo); } return result; } private bool CheckPayObjectAmount(SceneObjectPart part, int amount) { SceneObjectPart root = part.ParentGroup.RootPart; if (amount < 0) return false; // must be positive amount if (part.ParentGroup.RootPart.PayPrice[0] != SceneObjectPart.PAY_HIDE) return true; // any other value is legal for (int x = 1; x <= 4; x++) { if (root.PayPrice[x] == SceneObjectPart.PAY_DEFAULT) { // amount is only implied, check the implied value switch (x) { case 1: if (amount == SceneObjectPart.PAY_DEFAULT1) return true; break; case 2: if (amount == SceneObjectPart.PAY_DEFAULT2) return true; break; case 3: if (amount == SceneObjectPart.PAY_DEFAULT3) return true; break; case 4: if (amount == SceneObjectPart.PAY_DEFAULT4) return true; break; } } else { // not PAY_DEFAULT, a specific amount on the button if (amount == part.ParentGroup.RootPart.PayPrice[x]) return true; // it's one of the legal amounts listed } } return false; // not one of the listed amounts } // Returns true if the operation should be blocked. private static IMuteListModule m_muteListModule = null; private bool IsMutedObject(SceneObjectGroup group, UUID senderID) { // This may seem backwards but if the payer has this object // or its owner muted, the object cannot give anything back // for payment. Do not allow payment to objects that are muted. if (m_muteListModule == null) m_muteListModule = group.Scene.RequestModuleInterface<IMuteListModule>(); if (m_muteListModule == null) return false; // payer has object owner muted? if (m_muteListModule.IsMuted(group.OwnerID, senderID)) return true; // payer has the object muted? if (m_muteListModule.IsMuted(group.UUID, senderID)) return true; // neither the object nor owner are muted return false; } private void MoneyTransferAction(Object osender, EventManager.MoneyTransferArgs e) { if (e.amount < 0) return; //ScenePresence sourceAvatar = m_scene.GetScenePresence(e.sender); //IClientAPI sourceAvatarClient = sourceAvatar.ControllingClient; UUID sourceAvatarID = e.sender; int transType = e.transactiontype; string transDesc = e.description; UUID destAvatarID = e.receiver; int transAmount = e.amount; IClientAPI sourceAvatarClient; IClientAPI destAvatarClient; string sourceText = String.Empty; string destText = String.Empty; TransactionInfoBlock transInfo = new TransactionInfoBlock(); transInfo.Amount = transAmount; transInfo.TransactionType = transType; transInfo.SourceID = sourceAvatarID; transInfo.DestID = destAvatarID; transInfo.IsSourceGroup = false; transInfo.IsDestGroup = false; transInfo.ItemDescription = new byte[0]; sourceAvatarClient = LocateClientObject(sourceAvatarID); if (sourceAvatarClient == null) { m_log.Debug("[CURRENCY]: Source Avatar not found!"); } if (transType == (int)MoneyTransactionType.PayObject) { SceneObjectPart part = findPrim(e.receiver); if (!CheckPayObjectAmount(part, e.amount)) { sourceAvatarClient.SendAgentAlertMessage("Invalid amount used for payment to object.", false); return; } // Check if the object or owner are muted. if (IsMutedObject(part.ParentGroup, sourceAvatarID)) { sourceAvatarClient.SendAgentAlertMessage("Cannot give money to an object or object owner that you have muted. If the viewer has automatically unblocked the owner, you can retry payment.", false); return; } destAvatarID = part.OwnerID; destAvatarClient = LocateClientObject(destAvatarID); Vector3 pos = part.AbsolutePosition; int posx = (int)(pos.X + 0.5); // round to nearest int posy = (int)(pos.Y + 0.5); // round to nearest int posz = (int)(pos.Z + 0.5); // round to nearest transInfo.DestID = destAvatarID; transInfo.ItemDescription = Util.StringToBytes256(part.ParentGroup.RootPart.Name); transDesc = String.Format("Paid {0} via object {1} in {2} at <{3},{4},{5}>", resolveAgentName(destAvatarID), part.ParentGroup.Name, part.ParentGroup.Scene.RegionInfo.RegionName, posx, posy, posz); sourceText = "You paid " + resolveAgentName(destAvatarID) + " Iz$" + transAmount + " via " + part.ParentGroup.Name; destText = resolveAgentName(sourceAvatarID) + " paid you Iz$" + transAmount; } else { destAvatarID = (e.receiver); destAvatarClient = LocateClientObject(destAvatarID); if (destAvatarClient == null) { } else if (LocateSceneClientIn(destAvatarID).GetScenePresence(destAvatarID).IsBot) { sourceAvatarClient.SendAgentAlertMessage("You cannot pay a bot.", false); return; } transDesc = "Gift"; sourceText = "You paid " + resolveAgentName(destAvatarID) + " Iz$" + transAmount; destText = resolveAgentName(sourceAvatarID) + " paid you Iz$" + transAmount; } if (transAmount > 0) { // allow users with negative balances to buy freebies int avatarFunds = getCurrentBalance(sourceAvatarID); if (avatarFunds < transAmount) { sourceAvatarClient.SendAgentAlertMessage("Insufficient funds at this time", false); return; } } UUID transID; bool success; if (sourceAvatarID == destAvatarID) { // catching here, they can test but no reason to stuff crap in the db for testing transID = UUID.Zero; success = true; } else { transID = doMoneyTransfer(sourceAvatarID, destAvatarID, transAmount, transType, transDesc); success = (transID != UUID.Zero); } //if this is a scripted transaction let the script know money has changed hands if (transType == (int)MoneyTransactionType.PayObject) { this.OnObjectPaid(e.receiver, sourceAvatarID, transAmount); } SendMoneyBalanceTransaction(sourceAvatarClient, transID, success, sourceText, transInfo); if (destAvatarClient == null) { // don't want to do anything, as they can not be found, this is ugly but will suffice // until we get the scene working correctly to pull every avatar } else { SendMoneyBalanceTransaction(destAvatarClient, transID, success, destText, transInfo); } } private void ClassifiedPayment(Object osender, EventManager.ClassifiedPaymentArgs e) { IClientAPI remoteClient = (IClientAPI)osender; e.mIsAuthorized = false; int costToApply = e.mUpdatedPrice - e.mOrigPrice; if (costToApply > 0) // no refunds for lower prices { // Handle the actual money transaction here. int avatarFunds = getCurrentBalance(e.mBuyerID); if (avatarFunds < costToApply) { string costText = String.Empty; if (e.mOrigPrice != 0) // this is an updated classified costText = "increase "; remoteClient.SendAgentAlertMessage("The classified price " + costText + " (I'z$" + costToApply.ToString() + ") exceeds your current balance (" + avatarFunds.ToString() + ").", true); return; } } e.mIsAuthorized = true; if (e.mIsPreCheck) return; // perform actual money transaction doMoneyTransfer(e.mBuyerID, CURRENCY_ACCOUNT_ID, costToApply, (int)MoneyTransactionType.ClassifiedCharge, e.mDescription); SendMoneyBalance(remoteClient); // send balance update if (e.mOrigPrice == 0) // this is an initial classified charge. remoteClient.SendAgentAlertMessage("You have paid I'z$" + costToApply.ToString() + " for this classified ad.", false); else // this is an updated classified remoteClient.SendAgentAlertMessage("You have paid an additional I'z$" + costToApply.ToString() + " for this classified ad.", false); } public void ObjectBuy(IClientAPI remoteClient, UUID agentID, UUID sessionID, UUID groupID, UUID categoryID, uint localID, byte saleType, int salePrice) { if (salePrice < 0) return; if (salePrice > 0) { // allow users with negative balances to buy freebies int avatarFunds = getCurrentBalance(agentID); if (avatarFunds < salePrice) { // The viewer runs a check on monies balance, however, let's make sure another viewer // can't exploit this by removing and check their funds ourselves. remoteClient.SendAgentAlertMessage("Insufficient funds to purchase this item!", false); return; } } IClientAPI sourceAvatarClient = LocateClientObject(remoteClient.AgentId); if (sourceAvatarClient == null) { sourceAvatarClient.SendAgentAlertMessage("Purchase failed. No Controlling client found for sourceAvatar!", false); return; } Scene s = LocateSceneClientIn(remoteClient.AgentId); //Scene s = GetScenePresence(remoteClient.AgentId); SceneObjectPart objectPart = s.GetSceneObjectPart(localID); if (objectPart == null) { sourceAvatarClient.SendAgentAlertMessage("Purchase failed. The object was not found.", false); return; } ///// Prevent purchase spoofing, as well as viewer bugs. ///// // Verify that the object is actually for sale if (objectPart.ObjectSaleType == (byte)SaleType.Not) { remoteClient.SendAgentAlertMessage("Purchase failed. The item is not for sale.", false); return; } // Verify that the viewer sale type actually matches the correct sale type of the object if (saleType != objectPart.ObjectSaleType) { remoteClient.SendAgentAlertMessage("Purchase failed. The sale type does not match.", false); return; } // Verify that the buyer is paying the correct amount if (salePrice != objectPart.SalePrice) { remoteClient.SendAgentAlertMessage("Purchase failed. The payment price does not match the sale price.", false); return; } string objName = objectPart.ParentGroup.RootPart.Name; Vector3 pos = objectPart.AbsolutePosition; int posx = (int)(pos.X + 0.5); int posy = (int)(pos.Y + 0.5); int posz = (int)(pos.Z + 0.5); string transDesc = String.Format("{0} in {1} at <{2},{3},{4}>", objName, objectPart.ParentGroup.Scene.RegionInfo.RegionName, posx, posy, posz); string sourceAlertText = "Purchased " + objName + " for Iz$" + salePrice; string destAlertText = resolveAgentName(agentID) + " paid you Iz$" + salePrice + " via " + objName; int transType = (int)MoneyTransactionType.ObjectSale; UUID transID = UUID.Zero; TransactionInfoBlock transInfo = new TransactionInfoBlock(); transInfo.Amount = salePrice; transInfo.TransactionType = transType; transInfo.SourceID = remoteClient.AgentId; transInfo.DestID = objectPart.OwnerID; transInfo.IsSourceGroup = false; transInfo.IsDestGroup = false; transInfo.ItemDescription = Util.StringToBytes256(objName); if (agentID == objectPart.OwnerID) { // we'll let them test the buy, but nothing happens money wise. if (!s.PerformObjectBuy(remoteClient, categoryID, localID, saleType)) return; sourceAvatarClient.SendBlueBoxMessage(agentID, String.Empty, sourceAlertText); } else { if (salePrice == 0) { // We need to add a counter here for Freebies thus bypassing the DB for transactions cause // Freebies are a pain to have to track in the transaction history. if (!s.PerformObjectBuy(remoteClient, categoryID, localID, saleType)) return; } else { UUID originalOwnerID = objectPart.OwnerID; // capture the original seller's UUID for the money transfer if (!s.PerformObjectBuy(remoteClient, categoryID, localID, saleType)) // changes objectPart.OwnerID return; transID = doMoneyTransfer(remoteClient.AgentId, originalOwnerID, salePrice, transType, transDesc); } SendMoneyBalanceTransaction(sourceAvatarClient, transID, true, sourceAlertText, transInfo); } IClientAPI destAvatarClient = LocateClientObject(objectPart.OwnerID); if (destAvatarClient == null) { return; } else { SendMoneyBalanceTransaction(destAvatarClient, transID, true, destAlertText, transInfo); } } // This method is called after LandManagementModule's handleLandValidationRequest() method has performed that. // All land-related validation belongs there. private void ValidateLandBuy(Object osender, EventManager.LandBuyArgs e) { // internal system parameters (validated) // Scene scene = (Scene)osender; if (e.landValidated && e.parcel != null) { UUID sourceClientID = e.agentId; // this viewer parameter has been validated by LLCV int avatarFunds = getCurrentBalance(sourceClientID); LandData parcel = e.parcel.landData; UUID destClientID = parcel.OwnerID; int transAmount = parcel.SalePrice; if (avatarFunds >= transAmount) e.economyValidated = true; } } private void processLandBuy(Object osender, EventManager.LandBuyArgs e) { if (e.transactionID != 0) { // Not sure what this error is, duplicate purchase request for if the packet comes in a second time? return; } e.transactionID = Util.UnixTimeSinceEpoch(); // This method should not do any additional validation. // Any required validation should have been performed either // in LandManagementModule handleLandValidationRequest() or // in ValidateLandBuy above. int transType = (int)MoneyTransactionType.LandSale; string transDesc = "Land purchase"; UUID sourceClientID = e.agentId; IClientAPI sourceClient = LocateClientObject(sourceClientID); if (!e.economyValidated) { if (sourceClient != null) sourceClient.SendAgentAlertMessage("Could not validate user account balance for purchase.", false); return; } if ((e.parcel == null) || (!e.landValidated)) return; LandData parcel = e.parcel.landData; int transAmount = e.originalParcelPrice; UUID transID = UUID.Zero; UUID destClientID = e.originalParcelOwner; IClientAPI destClient = LocateClientObject(destClientID); // Pick a spot inside the parcel. Since blocks are 4x4, pick a spot 2m inside the bottom corner block. Vector3 pos = parcel.AABBMin; pos.X += 2; pos.Y += 2; transDesc += " at " + e.parcel.regionName + " (" + pos.X + "," + pos.Y + "): " + parcel.Name; // limit the result to 255 for the db storage if (transDesc.Length > 255) transDesc = transDesc.Substring(0, 255); // requires 2 users: source and dest clients must both be users (not groups, not same) transID = doMoneyTransfer(sourceClientID, destClientID, transAmount, transType, transDesc); TransactionInfoBlock transInfo = new TransactionInfoBlock(); transInfo.Amount = transAmount; transInfo.TransactionType = transType; transInfo.ItemDescription = Util.StringToBytes256(transDesc); transInfo.SourceID = sourceClientID; transInfo.IsSourceGroup = false; transInfo.DestID = e.originalParcelOwner; if (e.originalIsGroup) { // not currently supported (blocked in LandManagementModule handleLandValidationRequest()) // unless price is 0, because we cannot pass a group ID to doMoneyTransfer above. transInfo.IsDestGroup = true; } else { transInfo.IsDestGroup = false; } if (sourceClient != null) { string destName = resolveAgentName(destClientID); if (String.IsNullOrEmpty(destName)) destName = "a group (or unknown user)"; string sourceText = "You paid Iz$" + transAmount + " to " + destName + " for a parcel of land."; SendMoneyBalanceTransaction(sourceClient, transID, true, sourceText, transInfo); } if (destClient != null) { string destName = resolveAgentName(sourceClientID); if (String.IsNullOrEmpty(destName)) destName = "a group (or unknown user)"; string destText = "You were paid Iz$" + transAmount + " by " + destName + " for a parcel of land."; SendMoneyBalanceTransaction(destClient, transID, true, destText, transInfo); } } public bool AmountCovered(UUID agentID, int amount) { if (amount <= 0) return true; // allow users with 0 or negative balance to buy freebies int avatarFunds = getCurrentBalance(agentID); return avatarFunds >= amount; } public void requestPayPrice(IClientAPI client, UUID objectID) { Scene scene = LocateSceneClientIn(client.AgentId); if (scene == null) return; SceneObjectPart task = scene.GetSceneObjectPart(objectID); if (task == null) return; SceneObjectGroup group = task.ParentGroup; SceneObjectPart root = group.RootPart; client.SendPayPrice(objectID, root.PayPrice); } #region AvatarCurrency Helper Functions private SceneObjectPart findPrim(UUID objectID) { lock (m_scenel) { foreach (Scene s in m_scenel.Values) { SceneObjectPart part = s.GetSceneObjectPart(objectID); if (part != null) { return part; } } } return null; } private SceneObjectPart findPrimID(uint localID) { lock (m_scenel) { foreach (Scene objectScene in m_scenel.Values) { SceneObjectPart part = objectScene.GetSceneObjectPart(localID); if (part != null) { return part; } } } return null; } private string resolveAgentName(UUID agentID) { // try avatar username surname Scene scene = GetRandomScene(); string name = scene.CommsManager.UserService.Key2Name(agentID,false); if (String.IsNullOrEmpty(name)) m_log.ErrorFormat("[MONEY]: Could not resolve user {0}", agentID); return name; } public Scene GetRandomScene() { lock (m_scenel) { foreach (Scene rs in m_scenel.Values) return rs; } return null; } private Scene LocateSceneClientIn(UUID AgentId) { lock (m_scenel) { foreach (Scene _scene in m_scenel.Values) { ScenePresence tPresence = _scene.GetScenePresence(AgentId); if (tPresence != null) { if (!tPresence.IsChildAgent) { return _scene; } } } } return null; } private IClientAPI LocateClientObject(UUID AgentID) { ScenePresence tPresence = null; IClientAPI rclient = null; lock (m_scenel) { foreach (Scene _scene in m_scenel.Values) { tPresence = _scene.GetScenePresence(AgentID); if (tPresence != null) { if (!tPresence.IsChildAgent) { rclient = tPresence.ControllingClient; } } if (rclient != null) { return rclient; } } } return null; } } #endregion } // Transaction types, from https://lists.secondlife.com/pipermail/sldev-commits/2009-September.txt /* +class MoneyTransactionType(object): + String.Empty" Money transaction type constants String.Empty" + + Null = 0 + +# Codes 1000-1999 reserved for one-time charges + ObjectClaim = 1000 + LandClaim = 1001 + GroupCreate = 1002 + ObjectPublicClaim = 1003 + GroupJoin = 1004 # May be moved to group transactions eventually + TeleportCharge = 1100 # FF not sure why this jumps to 1100... + UploadCharge = 1101 + LandAuction = 1102 + ClassifiedCharge = 1103 + +# Codes 2000-2999 reserved for recurrent charges + ObjectTax = 2000 + LandTax = 2001 + LightTax = 2002 + ParcelDirFee = 2003 + GroupTax = 2004 # Taxes incurred as part of group membership + ClassifiedRenew = 2005 + +# Codes 3000-3999 reserved for inventory transactions + GiveInventory = 3000 + +# Codes 5000-5999 reserved for transfers between users + ObjectSale = 5000 + Gift = 5001 + LandSale = 5002 + ReferBonus = 5003 + InventorySale = 5004 + RefundPurchase = 5005 + LandPassSale = 5006 + DwellBonus = 5007 + PayObject = 5008 + ObjectPays = 5009 + +# Codes 6000-6999 reserved for group transactions +# GroupJoin = 6000 # reserved for future use + GroupLandDeed = 6001 + GroupObjectDeed = 6002 + GroupLiability = 6003 + GroupDividend = 6004 + MembershipDues = 6005 + +# Codes 8000-8999 reserved for one-type credits + ObjectRelease = 8000 + LandRelease = 8001 + ObjectDelete = 8002 + ObjectPublicDecay = 8003 + ObjectPublicDelete = 8004 + +# Code 9000-9099 reserved for usertool transactions + LindenAdjustment = 9000 + LindenGrant = 9001 + LindenPenalty = 9002 + EventFee = 9003 + EventPrize = 9004 + +# Codes 10000-10999 reserved for stipend credits + StipendBasic = 10000 + StipendDeveloper = 10001 + StipendAlways = 10002 + StipendDaily = 10003 + StipendRating = 10004 + StipendDelta = 10005 + +class TransactionFlags(object): + Null = 0 + SourceGroup = 1 + DestGroup = 2 + OwnerGroup = 4 + SimultaneousContribution = 8 + SimultaneousContributionRemoval = 16 */
namespace FakeItEasy.Core { using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; /// <summary> /// The central point in the API for proxied fake objects handles interception /// of fake object calls by using a set of rules. User defined rules can be inserted /// by using the AddRule-method. /// </summary> public partial class FakeManager : IFakeCallProcessor { private static readonly SharedFakeObjectCallRule[] SharedPostUserRules = { new ObjectMemberRule(), new AutoFakePropertyRule(), new PropertySetterRule(), new CancellationRule(), new DefaultReturnValueRule(), }; private readonly EventRule eventRule; private readonly LinkedList<IInterceptionListener> interceptionListeners; private readonly WeakReference objectReference; private readonly LinkedList<CallRuleMetadata> allUserRules; private EventCallHandler? eventCallHandler; private ConcurrentQueue<CompletedFakeObjectCall> recordedCalls; private int lastSequenceNumber = -1; /// <summary> /// Initializes a new instance of the <see cref="FakeManager"/> class. /// </summary> /// <param name="fakeObjectType">The faked type.</param> /// <param name="proxy">The faked proxy object.</param> /// <param name="fakeObjectName">The name of the fake object.</param> internal FakeManager(Type fakeObjectType, object proxy, string? fakeObjectName) { Guard.AgainstNull(fakeObjectType); Guard.AgainstNull(proxy); this.objectReference = new WeakReference(proxy); this.FakeObjectType = fakeObjectType; this.FakeObjectName = fakeObjectName; this.eventRule = new EventRule(this); this.allUserRules = new LinkedList<CallRuleMetadata>(); this.recordedCalls = new ConcurrentQueue<CompletedFakeObjectCall>(); this.interceptionListeners = new LinkedList<IInterceptionListener>(); } /// <summary> /// A delegate responsible for creating FakeObject instances. /// </summary> /// <param name="fakeObjectType">The faked type.</param> /// <param name="proxy">The faked proxy object.</param> /// <param name="fakeObjectName">The name of the fake object.</param> /// <returns>An instance of <see cref="FakeManager"/>.</returns> internal delegate FakeManager Factory(Type fakeObjectType, object proxy, string? fakeObjectName); /// <summary> /// Gets the faked proxy object. /// </summary> /// <remarks>Can be null if the proxy object has been collected by the garbage collector.</remarks> #pragma warning disable CA1716, CA1720 // Identifier contains keyword, Identifier contains type name public virtual object? Object => this.objectReference.Target; #pragma warning restore CA1716, CA1720 // Identifier contains keyword, Identifier contains type name /// <summary> /// Gets the faked type. /// </summary> public virtual Type FakeObjectType { get; } /// <summary> /// Gets the name of the fake. /// </summary> public string? FakeObjectName { get; } /// <summary> /// Gets the interceptions that are currently registered with the fake object. /// </summary> public virtual IEnumerable<IFakeObjectCallRule> Rules { get { lock (this.allUserRules) { return this.allUserRules.Select(x => x.Rule).ToList(); } } } internal string FakeObjectDisplayName => string.IsNullOrEmpty(this.FakeObjectName) ? "Faked " + this.FakeObjectType : this.FakeObjectName!; internal EventCallHandler EventCallHandler => this.eventCallHandler ??= new EventCallHandler(this); /// <summary> /// Adds a call rule to the fake object. /// </summary> /// <param name="rule">The rule to add.</param> public virtual void AddRuleFirst(IFakeObjectCallRule rule) { Guard.AgainstNull(rule); lock (this.allUserRules) { this.allUserRules.AddFirst(CallRuleMetadata.NeverCalled(rule)); } } /// <summary> /// Adds a call rule last in the list of user rules, meaning it has the lowest priority possible. /// </summary> /// <param name="rule">The rule to add.</param> public virtual void AddRuleLast(IFakeObjectCallRule rule) { Guard.AgainstNull(rule); lock (this.allUserRules) { this.allUserRules.AddLast(CallRuleMetadata.NeverCalled(rule)); } } /// <summary> /// Removes the specified rule for the fake object. /// </summary> /// <param name="rule">The rule to remove.</param> public virtual void RemoveRule(IFakeObjectCallRule rule) { Guard.AgainstNull(rule); lock (this.allUserRules) { var ruleToRemove = this.allUserRules.FirstOrDefault(x => x.Rule.Equals(rule)); if (ruleToRemove is not null) { this.allUserRules.Remove(ruleToRemove); } } } /// <summary> /// Adds an interception listener to the manager. /// </summary> /// <param name="listener">The listener to add.</param> public void AddInterceptionListener(IInterceptionListener listener) { Guard.AgainstNull(listener); this.interceptionListeners.AddFirst(listener); } [SuppressMessage("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes", Justification = "Explicit implementation to be able to make the IFakeCallProcessor interface internal.")] void IFakeCallProcessor.Process(InterceptedFakeObjectCall fakeObjectCall) { for (var listenerNode = this.interceptionListeners.First; listenerNode is not null; listenerNode = listenerNode.Next) { listenerNode.Value.OnBeforeCallIntercepted(fakeObjectCall); } var callToRecord = fakeObjectCall.ToCompletedCall(); this.RecordCall(callToRecord); try { this.ApplyBestRule(fakeObjectCall); } finally { callToRecord.ReturnValue = fakeObjectCall.ReturnValue; for (var listenerNode = this.interceptionListeners.Last; listenerNode is not null; listenerNode = listenerNode.Previous) { listenerNode.Value.OnAfterCallIntercepted(callToRecord); } } } internal int GetLastRecordedSequenceNumber() => this.lastSequenceNumber; /// <summary> /// Returns a list of all calls on the managed object. /// </summary> /// <returns>A list of all calls on the managed object.</returns> internal IEnumerable<CompletedFakeObjectCall> GetRecordedCalls() { return this.recordedCalls; } /// <summary> /// Removes any specified user rules. /// </summary> internal virtual void ClearUserRules() { lock (this.allUserRules) { this.allUserRules.Clear(); } } /// <summary> /// Removes any recorded calls. /// </summary> internal virtual void ClearRecordedCalls() { this.recordedCalls = new ConcurrentQueue<CompletedFakeObjectCall>(); } /// <summary> /// Adds a call rule to the fake object after the specified rule. /// </summary> /// <param name="previousRule">The rule after which to add a rule.</param> /// <param name="newRule">The rule to add.</param> internal void AddRuleAfter(IFakeObjectCallRule previousRule, IFakeObjectCallRule newRule) { lock (this.allUserRules) { var previousNode = this.allUserRules.Nodes().FirstOrDefault(n => n.Value.Rule == previousRule); if (previousNode is null) { throw new InvalidOperationException(ExceptionMessages.CannotFindPreviousRule); } this.allUserRules.AddAfter(previousNode, CallRuleMetadata.NeverCalled(newRule)); } } // Apply the best rule to the call. There will always be at least one applicable rule. private void ApplyBestRule(IInterceptedFakeObjectCall fakeObjectCall) { CallRuleMetadata? bestUserRule = null; lock (this.allUserRules) { foreach (var rule in this.allUserRules) { if (rule.Rule.IsApplicableTo(fakeObjectCall) && rule.HasNotBeenCalledSpecifiedNumberOfTimes()) { bestUserRule = rule; break; } } } if (bestUserRule is not null) { bestUserRule.RecordCall(); bestUserRule.Rule.Apply(fakeObjectCall); return; } if (this.eventRule.IsApplicableTo(fakeObjectCall)) { this.eventRule.Apply(fakeObjectCall); return; } foreach (var postUserRule in SharedPostUserRules) { if (postUserRule.IsApplicableTo(fakeObjectCall)) { postUserRule.Apply(fakeObjectCall); return; } } } /// <summary> /// Provides exclusive access the list of defined user rules so a client can /// inspect and optionally modify the list without interfering with concurrent /// actions on other threads. /// </summary> /// <param name="action">An action that can inspect and update the user rules without fear of conflict.</param> private void MutateUserRules(Action<LinkedList<CallRuleMetadata>> action) { lock (this.allUserRules) { action.Invoke(this.allUserRules); } } /// <summary> /// Records that a call has occurred on the managed object. /// </summary> /// <param name="call">The call to remember.</param> private void RecordCall(CompletedFakeObjectCall call) { this.UpdateLastSequenceNumber(call.SequenceNumber); this.recordedCalls.Enqueue(call); } private void UpdateLastSequenceNumber(int sequenceNumber) { //// Set the specified sequence number as the last sequence number if it's greater than the current last sequence number. //// We use this number in FakeAsserter to separate calls made before the assertion starts from those made during the //// assertion. //// Because lastSequenceNumber might be changed by another thread after the comparison, we use CompareExchange to //// only assign it if it has the same value as the one we compared with. If it's not the case, we retry. int last; do { last = this.lastSequenceNumber; } while (sequenceNumber > last && sequenceNumber != Interlocked.CompareExchange(ref this.lastSequenceNumber, sequenceNumber, last)); } private abstract class SharedFakeObjectCallRule : IFakeObjectCallRule { int? IFakeObjectCallRule.NumberOfTimesToCall => null; public abstract bool IsApplicableTo(IFakeObjectCall fakeObjectCall); public abstract void Apply(IInterceptedFakeObjectCall fakeObjectCall); } } }
using System; using Microsoft.Data.Entity; using Microsoft.Data.Entity.Infrastructure; using Microsoft.Data.Entity.Metadata; using Microsoft.Data.Entity.Migrations; using Aurora.DataAccess; namespace Aurora.DataAccess.Migrations { [DbContext(typeof(AuroraContext))] partial class AuroraContextModelSnapshot : ModelSnapshot { protected override void BuildModel(ModelBuilder modelBuilder) { modelBuilder .HasAnnotation("ProductVersion", "7.0.0-rc1-16348") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("Aurora.DataAccess.Entities.BacklogItemEntity", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<DateTime>("CreatedDate"); b.Property<string>("Description"); b.Property<bool>("IsActive"); b.Property<int>("SprintId"); b.Property<int>("State"); b.Property<string>("Title"); b.Property<DateTime>("UpdatedDate"); b.HasKey("Id"); }); modelBuilder.Entity("Aurora.DataAccess.Entities.LabelEntity", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("Color"); b.Property<DateTime>("CreatedDate"); b.Property<bool>("IsActive"); b.Property<string>("Name"); b.Property<int>("ProjectId"); b.Property<DateTime>("UpdatedDate"); b.HasKey("Id"); }); modelBuilder.Entity("Aurora.DataAccess.Entities.ProjectEntity", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<DateTime>("CreatedDate"); b.Property<string>("Description"); b.Property<bool>("IsActive"); b.Property<Guid>("MemberToken"); b.Property<string>("Name"); b.Property<DateTime>("UpdatedDate"); b.HasKey("Id"); }); modelBuilder.Entity("Aurora.DataAccess.Entities.SprintEntity", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<DateTime>("CreatedDate"); b.Property<DateTime>("EstimatedEndDate"); b.Property<DateTime>("EstimatedStartDate"); b.Property<bool>("IsActive"); b.Property<string>("Name"); b.Property<int>("ProjectId"); b.Property<int>("State"); b.Property<DateTime>("UpdatedDate"); b.HasKey("Id"); }); modelBuilder.Entity("Aurora.DataAccess.Entities.TaskEntity", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<int>("BacklogItemId"); b.Property<DateTime>("CreatedDate"); b.Property<string>("Description"); b.Property<bool>("IsActive"); b.Property<string>("Tite"); b.Property<DateTime>("UpdatedDate"); b.Property<int>("UserProjectId"); b.HasKey("Id"); }); modelBuilder.Entity("Aurora.DataAccess.Entities.TaskLabelEntity", b => { b.Property<int>("TaskId"); b.Property<int>("LabelId"); b.HasKey("TaskId", "LabelId"); }); modelBuilder.Entity("Aurora.DataAccess.Entities.UserEntity", b => { b.Property<string>("Id"); b.Property<int>("AccessFailedCount"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken(); b.Property<string>("Email") .HasAnnotation("MaxLength", 256); b.Property<bool>("EmailConfirmed"); b.Property<string>("FirstName"); b.Property<byte[]>("Gravatar"); b.Property<bool>("IsActive"); b.Property<bool>("IsLocked"); b.Property<string>("LastName"); b.Property<bool>("LockoutEnabled"); b.Property<DateTimeOffset?>("LockoutEnd"); b.Property<string>("NormalizedEmail") .HasAnnotation("MaxLength", 256); b.Property<string>("NormalizedUserName") .HasAnnotation("MaxLength", 256); b.Property<string>("PasswordHash"); b.Property<string>("PhoneNumber"); b.Property<bool>("PhoneNumberConfirmed"); b.Property<string>("SecurityStamp"); b.Property<bool>("TwoFactorEnabled"); b.Property<string>("UserName") .HasAnnotation("MaxLength", 256); b.HasKey("Id"); b.HasIndex("NormalizedEmail") .HasAnnotation("Relational:Name", "EmailIndex"); b.HasIndex("NormalizedUserName") .HasAnnotation("Relational:Name", "UserNameIndex"); b.HasAnnotation("Relational:Schema", "usr"); b.HasAnnotation("Relational:TableName", "AspNetUsers"); }); modelBuilder.Entity("Aurora.DataAccess.Entities.UserProjectEntity", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<DateTime>("CreatedDate"); b.Property<bool>("IsActivated"); b.Property<bool>("IsActive"); b.Property<bool>("IsDeafult"); b.Property<int>("ProjectId"); b.Property<DateTime>("UpdatedDate"); b.Property<string>("UserId"); b.HasKey("Id"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRole", b => { b.Property<string>("Id"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken(); b.Property<string>("Name") .HasAnnotation("MaxLength", 256); b.Property<string>("NormalizedName") .HasAnnotation("MaxLength", 256); b.HasKey("Id"); b.HasIndex("NormalizedName") .HasAnnotation("Relational:Name", "RoleNameIndex"); b.HasAnnotation("Relational:TableName", "AspNetRoles"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRoleClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("ClaimType"); b.Property<string>("ClaimValue"); b.Property<string>("RoleId") .IsRequired(); b.HasKey("Id"); b.HasAnnotation("Relational:TableName", "AspNetRoleClaims"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("ClaimType"); b.Property<string>("ClaimValue"); b.Property<string>("UserId") .IsRequired(); b.HasKey("Id"); b.HasAnnotation("Relational:TableName", "AspNetUserClaims"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin<string>", b => { b.Property<string>("LoginProvider"); b.Property<string>("ProviderKey"); b.Property<string>("ProviderDisplayName"); b.Property<string>("UserId") .IsRequired(); b.HasKey("LoginProvider", "ProviderKey"); b.HasAnnotation("Relational:TableName", "AspNetUserLogins"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole<string>", b => { b.Property<string>("UserId"); b.Property<string>("RoleId"); b.HasKey("UserId", "RoleId"); b.HasAnnotation("Relational:TableName", "AspNetUserRoles"); }); modelBuilder.Entity("Aurora.DataAccess.Entities.BacklogItemEntity", b => { b.HasOne("Aurora.DataAccess.Entities.SprintEntity") .WithMany() .HasForeignKey("SprintId"); }); modelBuilder.Entity("Aurora.DataAccess.Entities.LabelEntity", b => { b.HasOne("Aurora.DataAccess.Entities.ProjectEntity") .WithMany() .HasForeignKey("ProjectId"); }); modelBuilder.Entity("Aurora.DataAccess.Entities.SprintEntity", b => { b.HasOne("Aurora.DataAccess.Entities.ProjectEntity") .WithMany() .HasForeignKey("ProjectId"); }); modelBuilder.Entity("Aurora.DataAccess.Entities.TaskEntity", b => { b.HasOne("Aurora.DataAccess.Entities.BacklogItemEntity") .WithMany() .HasForeignKey("BacklogItemId"); b.HasOne("Aurora.DataAccess.Entities.UserProjectEntity") .WithMany() .HasForeignKey("UserProjectId"); }); modelBuilder.Entity("Aurora.DataAccess.Entities.TaskLabelEntity", b => { b.HasOne("Aurora.DataAccess.Entities.LabelEntity") .WithMany() .HasForeignKey("LabelId"); b.HasOne("Aurora.DataAccess.Entities.TaskEntity") .WithMany() .HasForeignKey("TaskId"); }); modelBuilder.Entity("Aurora.DataAccess.Entities.UserProjectEntity", b => { b.HasOne("Aurora.DataAccess.Entities.ProjectEntity") .WithMany() .HasForeignKey("ProjectId"); b.HasOne("Aurora.DataAccess.Entities.UserEntity") .WithMany() .HasForeignKey("UserId"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRoleClaim<string>", b => { b.HasOne("Microsoft.AspNet.Identity.EntityFramework.IdentityRole") .WithMany() .HasForeignKey("RoleId"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim<string>", b => { b.HasOne("Aurora.DataAccess.Entities.UserEntity") .WithMany() .HasForeignKey("UserId"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin<string>", b => { b.HasOne("Aurora.DataAccess.Entities.UserEntity") .WithMany() .HasForeignKey("UserId"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole<string>", b => { b.HasOne("Microsoft.AspNet.Identity.EntityFramework.IdentityRole") .WithMany() .HasForeignKey("RoleId"); b.HasOne("Aurora.DataAccess.Entities.UserEntity") .WithMany() .HasForeignKey("UserId"); }); } } }
using System; using System.Collections.Generic; using System.Text; using System.Net; using System.Net.Sockets; using Project858.Diagnostics; using System.ComponentModel; namespace Project858.Net { /// <summary> /// Nadstavba TCP servera s rozsirenim /// </summary> public abstract class TcpContractServer : TcpServer { #region - Constructor - /// <summary> /// Initialize this class /// </summary> public TcpContractServer() : base() { } /// <summary> /// Initialize this class /// </summary> /// <param name="ipAddress">Ip adresa servera</param> /// <param name="ipPort">Ip port servera</param> public TcpContractServer(IPAddress ipAddress, Int32 ipPort) : base(ipAddress, ipPort) { } #endregion #region - Events - /// <summary> /// Event with transport client which was added /// </summary> private event TransportClientEventHandler mTransportClientAdded = null; /// <summary> /// Event with transport client which was added /// </summary> /// <exception cref="ObjectDisposedException"> /// Ak je object v stave _isDisposed /// </exception> [EditorBrowsable(EditorBrowsableState.Always)] public event TransportClientEventHandler TransportClientAdded { add { //je objekt _isDisposed ? if (this.IsDisposed) throw new ObjectDisposedException("Object was disposed"); lock (this.m_eventLock) this.mTransportClientAdded += value; } remove { //je objekt _isDisposed ? if (this.IsDisposed) throw new ObjectDisposedException("Object was disposed"); lock (this.m_eventLock) this.mTransportClientAdded -= value; } } /// <summary> /// Event with transport client which was removed /// </summary> private event TransportClientEventHandler mTransportClientRemoved = null; /// <summary> /// Event with transport client which was removed /// </summary> /// <exception cref="ObjectDisposedException"> /// Ak je object v stave _isDisposed /// </exception> [EditorBrowsable(EditorBrowsableState.Always)] public event TransportClientEventHandler TransportClientRemoved { add { //je objekt _isDisposed ? if (this.IsDisposed) throw new ObjectDisposedException("Object was disposed"); lock (this.m_eventLock) this.mTransportClientRemoved += value; } remove { //je objekt _isDisposed ? if (this.IsDisposed) throw new ObjectDisposedException("Object was disposed"); lock (this.m_eventLock) this.mTransportClientRemoved -= value; } } #endregion #region - Properties - /// <summary> /// (Get) Kolekcia aktualne pripojenych klientov a ich obsluh /// </summary> public List<ITransportClient> Contracts { get { return m_contracts; } } /// <summary> /// (Get / Set) Maximalny pocet pripojenych klientov. Povoleny rozsah je od 1 do 100 /// </summary> /// <exception cref="ObjectDisposedException"> /// Ak je object v stave _isDisposed /// </exception> /// <exception cref="ArgumentOutOfRangeException"> /// Mimo povoleneho rozsahu. Povoleny rozsah je od 1 do 100 /// </exception> public Int32 IsConnected { get { //je objekt _isDisposed ? if (this.IsDisposed) throw new ObjectDisposedException("Object was disposed"); return this.m_maxConnection; } set { //je objekt _isDisposed ? if (this.IsDisposed) throw new ObjectDisposedException("Object was disposed"); //osetrenie rozsahu if (value < 1 || value > 100) throw new ArgumentOutOfRangeException("value"); //nastavime hodnotu m_maxConnection = value; } } #endregion #region - Variable - /// <summary> /// Maximalny pocet pripojenych klientov /// </summary> private Int32 m_maxConnection = 10; /// <summary> /// Kolekcia aktualne pripojenych klientov a ich obsluh /// </summary> private List<ITransportClient> m_contracts = null; #endregion #region - Protected and Private Method - /// <summary> /// Inicializuje server na pzoadovanej adrese a porte /// </summary> /// <returns>True = start klienta bol uspesny</returns> protected override bool InternalStart() { //spustime tcp server if (!base.InternalStart()) { //start servera sa nepodaril return false; } //inicializujeme this.m_contracts = new List<ITransportClient>(); //start servera bol uspesny return true; } /// <summary> /// Ukonci server a akceptovanie klientov /// </summary> protected override void InternalStop() { try { //ukoncime base server base.InternalStop(); //ukoncime contracty this.InternalStopAllContract(); } catch (Exception) { //preposleme vynimku vyssie throw; } finally { //deinicializujeme this.m_contracts.Clear(); this.m_contracts = null; } } /// <summary> /// Inicializuje, spusti a vrati contract na obsluhu akceptovaneho klienta /// </summary> /// <param name="client">Client ktory bol akceptovany</param> /// <returns>Contract na obsluhu akceptovaneho klienta</returns> protected virtual ITransportClient InternalCreateContract(TcpClient client) { throw new NotImplementedException(); } /// <summary> /// Odoberie contract klienta ktory sa odpojil. Prepis metody by mal zabezpecit volanie base.InternalRemoveContract(ITransportClient contrat); /// </summary> /// <param name="contrat">Contract ktory vykonaval obsluhu klienta ktory zrusil spojenie</param> protected virtual void InternalRemoveContract(ITransportClient contrat) { //odstranime klienta this.InternalRemoveSpecifiedContract(contrat); } /// <summary> /// Ukonci vsetky contracty pred ukoncim celeho servera /// </summary> protected virtual void InternalStopAllContract() { //ukoncime beziace contracty lock (this) { for (int i = this.m_contracts.Count - 1; i > -1; i--) { try { //ziskame pristup ITransportClient contract = this.m_contracts[i]; //ukoncime contract this.InternalStopContract(contract); //remove contract this.InternalRemoveContract(contract); } catch (Exception ex) { //chybu ignorujeme } } } } /// <summary> /// Ukonci contract pred ukoncenim celeho servera /// </summary> /// <param name="contract">Contract ktory chceme ukoncit</param> protected virtual void InternalStopContract(ITransportClient contract) { //ukoncime klienta if (!contract.IsDisposed) if (contract.IsRun) { //odoberieme event oznamujuci odhlasenie klienta contract.DisconnectedEvent -= new EventHandler(contract_DisconnectedEvent); contract.Stop(); } } /// <summary> /// Prepis a rozsirenie prijatia / akceptovania klienta /// </summary> /// <param name="e">TcpClientEventArgs</param> protected override void OnTcpClientReceived(TcpClientEventArgs e) { //base volanie na vytvorenie eventu base.OnTcpClientReceived(e); //overime ci je mozne pridat dalsieho klienta if (this.InternalCheckContracts()) { try { //pridame instaniu servera ITransportClient contract = this.InternalCreateContract(e.Client); //validate contract if (contract != null && contract.IsConnected) { //namapujeme event oznamujuci odhlasenie klienta contract.DisconnectedEvent += new EventHandler(contract_DisconnectedEvent); //pridame contract this.InternalCreateContract(contract); //create event about new client this.OnTransportClientAdded(new TransportClientEventArgs(contract)); } else { //ukoncime inicializovany contract if (contract != null) { contract.Dispose(); contract = null; } } } catch (Exception ex) { //chybu ignorujeme this.InternalTrace(TraceTypes.Error, "Interna chyba pri udalostiach spojenych z pridavanim pripojeneho klienta. {0}", ex.Message); } } else { try { //zalogujeme this.InternalTrace(TraceTypes.Verbose, "Ukoncovanie akceptovaneho klienta..."); //ziskame pristup TcpClient client = e.Client; client.Close(); } catch (Exception) { //ignorujeme } } } /// <summary> /// Reaguje na ukoncenie klienta. Odoberie contract z kolekcie /// </summary> /// <param name="sender">Odosielatel udalosti</param> /// <param name="e">EventArgs</param> private void contract_DisconnectedEvent(object sender, EventArgs e) { //zalogujeme this.InternalTrace(TraceTypes.Verbose, "Removing the client which was exited."); //ziskame pristup ITransportClient contract = sender as ITransportClient; try { //odoberame klienta this.InternalRemoveContract(contract); } catch (Exception ex) { this.InternalException(ex, "Removing the client failed. {0}", ex.Message); } } /// <summary> /// Prida instanciu ktora obsluhuje prijateho / akceptovaneho klienta /// </summary> /// <param name="contract">Contract obsluhujuci akceptovaneho klienta</param> private void InternalCreateContract(ITransportClient contract) { //overime instaniu if (contract == null || contract.IsRun == false || contract.IsDisposed) return; lock (this) { //pridame dalsi contract do kolekcia this.m_contracts.Add(contract); #if DEBUG ConsoleLogger.Info("Pocet klientov: po prijati dalsieho {0}", this.m_contracts.Count); #endif } } /// <summary> /// Odoberie instanciu ktora obsluhovala prijateho / akceptovaneho klienta ktory ukoncil spojenie /// </summary> /// <param name="contract">Contract obsluhujuci akceptovaneho klienta</param> private void InternalRemoveSpecifiedContract(ITransportClient contract) { //overime instaniu if (contract == null) return; lock (this) { //zalofujeme this.InternalTrace(TraceTypes.Info, "Pocet klientov: pred odobratim dalsieho {0}", this.m_contracts.Count); //odoberieme contract this.m_contracts.Remove(contract); //create event about remove client this.OnTransportClientRemoved(new TransportClientEventArgs(contract)); //zalogujeme this.InternalTrace(TraceTypes.Info, "Pocet klientov: po odobrati dalsieho {0}", this.m_contracts.Count); } //ukoncime inicializovany contract if (contract != null) { contract.Dispose(); contract = null; } } /// <summary> /// Overi maximalny pocet moznych klientov a vykona start alebo stop listenera /// </summary> /// <returns>True = je mozne aktivovat dalsieho klient</returns> private Boolean InternalCheckContracts() { //ziskame pocet aktualnych instancii Int32 count = 0; //synchronizujeme pristup lock (this) { count = this.m_contracts.Count; } //zalogujeme this.InternalTrace(TraceTypes.Verbose, "Overovanie stavu listenera. {0}", count); //ak je pocet vacsi ako povoleny if (count >= this.m_maxConnection) { //zalogujeme this.InternalTrace(TraceTypes.Verbose, "Maximalny pocet pripojenych klientov bol dosiahnuty. [IsListened: {0}]", this.IsListened); return false; } //ak este mozme prijimat klientov else { //zalogujeme this.InternalTrace(TraceTypes.Verbose, "Maximalny pocet pripojenych klientov este nebol dosiahnuty. [IsListened: {0}]", this.IsListened); return true; } } #endregion #region - Protected Event Methods - /// <summary> /// This method executes event with client which was removed /// </summary> /// <param name="e">Arguments</param> protected virtual void OnTransportClientRemoved(TransportClientEventArgs e) { TransportClientEventHandler handler = this.mTransportClientRemoved; if (handler != null) handler(this, e); } /// <summary> /// This method executes event with client which was added /// </summary> /// <param name="e">Arguments</param> protected virtual void OnTransportClientAdded(TransportClientEventArgs e) { TransportClientEventHandler handler = this.mTransportClientAdded; if (handler != null) handler(this, e); } #endregion } }
// *********************************************************************** // Copyright (c) 2008 Charlie Poole // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** using System; namespace NUnit.Framework.Constraints { /// <summary> /// The Numerics class contains common operations on numeric values. /// </summary> public class Numerics { #region Numeric Type Recognition /// <summary> /// Checks the type of the object, returning true if /// the object is a numeric type. /// </summary> /// <param name="obj">The object to check</param> /// <returns>true if the object is a numeric type</returns> public static bool IsNumericType(Object obj) { return IsFloatingPointNumeric(obj) || IsFixedPointNumeric(obj); } /// <summary> /// Checks the type of the object, returning true if /// the object is a floating point numeric type. /// </summary> /// <param name="obj">The object to check</param> /// <returns>true if the object is a floating point numeric type</returns> public static bool IsFloatingPointNumeric(Object obj) { if (null != obj) { if (obj is System.Double) return true; if (obj is System.Single) return true; } return false; } /// <summary> /// Checks the type of the object, returning true if /// the object is a fixed point numeric type. /// </summary> /// <param name="obj">The object to check</param> /// <returns>true if the object is a fixed point numeric type</returns> public static bool IsFixedPointNumeric(Object obj) { if (null != obj) { if (obj is System.Byte) return true; if (obj is System.SByte) return true; if (obj is System.Decimal) return true; if (obj is System.Int32) return true; if (obj is System.UInt32) return true; if (obj is System.Int64) return true; if (obj is System.UInt64) return true; if (obj is System.Int16) return true; if (obj is System.UInt16) return true; } return false; } #endregion #region Numeric Equality /// <summary> /// Test two numeric values for equality, performing the usual numeric /// conversions and using a provided or default tolerance. If the tolerance /// provided is Empty, this method may set it to a default tolerance. /// </summary> /// <param name="expected">The expected value</param> /// <param name="actual">The actual value</param> /// <param name="tolerance">A reference to the tolerance in effect</param> /// <returns>True if the values are equal</returns> public static bool AreEqual(object expected, object actual, ref Tolerance tolerance) { if (expected is double || actual is double) return AreEqual(Convert.ToDouble(expected), Convert.ToDouble(actual), ref tolerance); if (expected is float || actual is float) return AreEqual(Convert.ToSingle(expected), Convert.ToSingle(actual), ref tolerance); if (tolerance.Mode == ToleranceMode.Ulps) throw new InvalidOperationException("Ulps may only be specified for floating point arguments"); if (expected is decimal || actual is decimal) return AreEqual(Convert.ToDecimal(expected), Convert.ToDecimal(actual), tolerance); if (expected is ulong || actual is ulong) return AreEqual(Convert.ToUInt64(expected), Convert.ToUInt64(actual), tolerance); if (expected is long || actual is long) return AreEqual(Convert.ToInt64(expected), Convert.ToInt64(actual), tolerance); if (expected is uint || actual is uint) return AreEqual(Convert.ToUInt32(expected), Convert.ToUInt32(actual), tolerance); return AreEqual(Convert.ToInt32(expected), Convert.ToInt32(actual), tolerance); } private static bool AreEqual(double expected, double actual, ref Tolerance tolerance) { if (double.IsNaN(expected) && double.IsNaN(actual)) return true; // Handle infinity specially since subtracting two infinite values gives // NaN and the following test fails. mono also needs NaN to be handled // specially although ms.net could use either method. Also, handle // situation where no tolerance is used. if (double.IsInfinity(expected) || double.IsNaN(expected) || double.IsNaN(actual)) { return expected.Equals(actual); } if (tolerance.IsEmpty && GlobalSettings.DefaultFloatingPointTolerance > 0.0d) tolerance = new Tolerance(GlobalSettings.DefaultFloatingPointTolerance); switch (tolerance.Mode) { case ToleranceMode.None: return expected.Equals(actual); case ToleranceMode.Linear: return Math.Abs(expected - actual) <= Convert.ToDouble(tolerance.Value); case ToleranceMode.Percent: if (expected == 0.0) return expected.Equals(actual); double relativeError = Math.Abs((expected - actual) / expected); return (relativeError <= Convert.ToDouble(tolerance.Value) / 100.0); case ToleranceMode.Ulps: return FloatingPointNumerics.AreAlmostEqualUlps( expected, actual, Convert.ToInt64(tolerance.Value)); default: throw new ArgumentException("Unknown tolerance mode specified", "mode"); } } private static bool AreEqual(float expected, float actual, ref Tolerance tolerance) { if (float.IsNaN(expected) && float.IsNaN(actual)) return true; // handle infinity specially since subtracting two infinite values gives // NaN and the following test fails. mono also needs NaN to be handled // specially although ms.net could use either method. if (float.IsInfinity(expected) || float.IsNaN(expected) || float.IsNaN(actual)) { return expected.Equals(actual); } if (tolerance.IsEmpty && GlobalSettings.DefaultFloatingPointTolerance > 0.0d) tolerance = new Tolerance(GlobalSettings.DefaultFloatingPointTolerance); switch (tolerance.Mode) { case ToleranceMode.None: return expected.Equals(actual); case ToleranceMode.Linear: return Math.Abs(expected - actual) <= Convert.ToDouble(tolerance.Value); case ToleranceMode.Percent: if (expected == 0.0f) return expected.Equals(actual); float relativeError = Math.Abs((expected - actual) / expected); return (relativeError <= Convert.ToSingle(tolerance.Value) / 100.0f); case ToleranceMode.Ulps: return FloatingPointNumerics.AreAlmostEqualUlps( expected, actual, Convert.ToInt32(tolerance.Value)); default: throw new ArgumentException("Unknown tolerance mode specified", "mode"); } } private static bool AreEqual(decimal expected, decimal actual, Tolerance tolerance) { switch (tolerance.Mode) { case ToleranceMode.None: return expected.Equals(actual); case ToleranceMode.Linear: decimal decimalTolerance = Convert.ToDecimal(tolerance.Value); if (decimalTolerance > 0m) return Math.Abs(expected - actual) <= decimalTolerance; return expected.Equals(actual); case ToleranceMode.Percent: if (expected == 0m) return expected.Equals(actual); double relativeError = Math.Abs( (double)(expected - actual) / (double)expected); return (relativeError <= Convert.ToDouble(tolerance.Value) / 100.0); default: throw new ArgumentException("Unknown tolerance mode specified", "mode"); } } private static bool AreEqual(ulong expected, ulong actual, Tolerance tolerance) { switch (tolerance.Mode) { case ToleranceMode.None: return expected.Equals(actual); case ToleranceMode.Linear: ulong ulongTolerance = Convert.ToUInt64(tolerance.Value); if (ulongTolerance > 0ul) { ulong diff = expected >= actual ? expected - actual : actual - expected; return diff <= ulongTolerance; } return expected.Equals(actual); case ToleranceMode.Percent: if (expected == 0ul) return expected.Equals(actual); // Can't do a simple Math.Abs() here since it's unsigned ulong difference = Math.Max(expected, actual) - Math.Min(expected, actual); double relativeError = Math.Abs((double)difference / (double)expected); return (relativeError <= Convert.ToDouble(tolerance.Value) / 100.0); default: throw new ArgumentException("Unknown tolerance mode specified", "mode"); } } private static bool AreEqual(long expected, long actual, Tolerance tolerance) { switch (tolerance.Mode) { case ToleranceMode.None: return expected.Equals(actual); case ToleranceMode.Linear: long longTolerance = Convert.ToInt64(tolerance.Value); if (longTolerance > 0L) return Math.Abs(expected - actual) <= longTolerance; return expected.Equals(actual); case ToleranceMode.Percent: if (expected == 0L) return expected.Equals(actual); double relativeError = Math.Abs( (double)(expected - actual) / (double)expected); return (relativeError <= Convert.ToDouble(tolerance.Value) / 100.0); default: throw new ArgumentException("Unknown tolerance mode specified", "mode"); } } private static bool AreEqual(uint expected, uint actual, Tolerance tolerance) { switch (tolerance.Mode) { case ToleranceMode.None: return expected.Equals(actual); case ToleranceMode.Linear: uint uintTolerance = Convert.ToUInt32(tolerance.Value); if (uintTolerance > 0) { uint diff = expected >= actual ? expected - actual : actual - expected; return diff <= uintTolerance; } return expected.Equals(actual); case ToleranceMode.Percent: if (expected == 0u) return expected.Equals(actual); // Can't do a simple Math.Abs() here since it's unsigned uint difference = Math.Max(expected, actual) - Math.Min(expected, actual); double relativeError = Math.Abs((double)difference / (double)expected); return (relativeError <= Convert.ToDouble(tolerance.Value) / 100.0); default: throw new ArgumentException("Unknown tolerance mode specified", "mode"); } } private static bool AreEqual(int expected, int actual, Tolerance tolerance) { switch (tolerance.Mode) { case ToleranceMode.None: return expected.Equals(actual); case ToleranceMode.Linear: int intTolerance = Convert.ToInt32(tolerance.Value); if (intTolerance > 0) return Math.Abs(expected - actual) <= intTolerance; return expected.Equals(actual); case ToleranceMode.Percent: if (expected == 0) return expected.Equals(actual); double relativeError = Math.Abs( (double)(expected - actual) / (double)expected); return (relativeError <= Convert.ToDouble(tolerance.Value) / 100.0); default: throw new ArgumentException("Unknown tolerance mode specified", "mode"); } } #endregion #region Numeric Comparisons /// <summary> /// Compare two numeric values, performing the usual numeric conversions. /// </summary> /// <param name="expected">The expected value</param> /// <param name="actual">The actual value</param> /// <returns>The relationship of the values to each other</returns> public static int Compare(object expected, object actual) { if (!IsNumericType(expected) || !IsNumericType(actual)) throw new ArgumentException("Both arguments must be numeric"); if (IsFloatingPointNumeric(expected) || IsFloatingPointNumeric(actual)) return Convert.ToDouble(expected).CompareTo(Convert.ToDouble(actual)); if (expected is decimal || actual is decimal) return Convert.ToDecimal(expected).CompareTo(Convert.ToDecimal(actual)); if (expected is ulong || actual is ulong) return Convert.ToUInt64(expected).CompareTo(Convert.ToUInt64(actual)); if (expected is long || actual is long) return Convert.ToInt64(expected).CompareTo(Convert.ToInt64(actual)); if (expected is uint || actual is uint) return Convert.ToUInt32(expected).CompareTo(Convert.ToUInt32(actual)); return Convert.ToInt32(expected).CompareTo(Convert.ToInt32(actual)); } #endregion private Numerics() { } } }
// Copyright 2004-2006 University of Wisconsin // All rights reserved. // // Contributors: // James Domingo, UW-Madison, Forest Landscape Ecology Lab using Landis.SpatialModeling; using System.Collections; using System.Collections.Generic; namespace Landis.Landscapes { internal class Landscape : Grid, ILandscape, IEnumerable<Site> { private DataIndexes.Collection dataIndexes; private int inactiveSiteCount; //--------------------------------------------------------------------- public new Dimensions Dimensions { get { return base.Dimensions; } } //--------------------------------------------------------------------- public int ActiveSiteCount { get { return (int) dataIndexes.ActiveLocationCount; } } //--------------------------------------------------------------------- public int InactiveSiteCount { get { return inactiveSiteCount; } } //--------------------------------------------------------------------- public Location FirstInactiveSite { get { throw new System.NotImplementedException(); } } //--------------------------------------------------------------------- public uint InactiveSiteDataIndex { get { if (inactiveSiteCount == 0) throw new System.InvalidOperationException("No inactive sites"); return InactiveSite.DataIndex; } } //--------------------------------------------------------------------- public int SiteCount { get { return (int) Count; } } //--------------------------------------------------------------------- /// <summary> /// Initializes a new instance using an input grid of active sites. /// </summary> /// <param name="activeSites"> /// A grid that indicates which sites are active. /// </param> internal Landscape(IInputGrid<bool> activeSites) : base(activeSites.Dimensions) { Initialize(activeSites); } //--------------------------------------------------------------------- /// <summary> /// Initializes a new instance using an indexable grid of active sites. /// </summary> /// <param name="activeSites"> /// A grid that indicates which sites are active. /// </param> internal Landscape(IIndexableGrid<bool> activeSites) : base(activeSites.Dimensions) { Initialize(new InputGrid<bool>(activeSites)); } //--------------------------------------------------------------------- private void Initialize(IInputGrid<bool> activeSites) { if (Count > int.MaxValue) { string mesg = string.Format("Landscape dimensions are too big; maximum # of sites = {0:#,###}", int.MaxValue); throw new System.ApplicationException(mesg); } dataIndexes = new Landscapes.DataIndexes.Array2D(activeSites); activeSites.Close(); inactiveSiteCount = SiteCount - (int) dataIndexes.ActiveLocationCount; } //--------------------------------------------------------------------- public ActiveSite this[Location location] { get { Site site = GetSite(location); if (site && site.IsActive) return (ActiveSite) site; else return new ActiveSite(); } } //--------------------------------------------------------------------- public ActiveSite this[int row, int column] { get { return this[new Location(row, column)]; } } //--------------------------------------------------------------------- public IEnumerable<ActiveSite> ActiveSites { get { return this; } } //--------------------------------------------------------------------- public IEnumerator<ActiveSite> GetEnumerator() { return GetActiveSiteEnumerator(); } //--------------------------------------------------------------------- IEnumerator IEnumerable.GetEnumerator() { return GetActiveSiteEnumerator(); } //--------------------------------------------------------------------- public ActiveSiteEnumerator GetActiveSiteEnumerator() { return new ActiveSiteEnumerator(this, dataIndexes); } //--------------------------------------------------------------------- public IEnumerable<Site> AllSites { get { return this; } } //--------------------------------------------------------------------- IEnumerator<Site> IEnumerable<Site>.GetEnumerator() { return GetSiteEnumerator(); } //--------------------------------------------------------------------- public SiteEnumerator GetSiteEnumerator() { return new SiteEnumerator(this); } //--------------------------------------------------------------------- public bool IsValid(Location location) { return (1 <= location.Row) && (location.Row <= Rows) && (1 <= location.Column) && (location.Column <= Columns); } //--------------------------------------------------------------------- public Site GetSite(Location location) { if (! IsValid(location)) return new Site(); uint index = dataIndexes[location]; return new Site(this, location, index); } //--------------------------------------------------------------------- public Site GetSite(int row, int column) { return GetSite(new Location(row, column)); } //--------------------------------------------------------------------- public ISiteVar<T> NewSiteVar<T>(InactiveSiteMode mode) { if (mode == InactiveSiteMode.Share1Value) return new SiteVarShare<T>(this); else return new SiteVarDistinct<T>(this); } //--------------------------------------------------------------------- public ISiteVar<T> NewSiteVar<T>() { return NewSiteVar<T>(InactiveSiteMode.Share1Value); } } }
// 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 TestNotZAndNotCInt64() { var test = new BooleanTwoComparisonOpTest__TestNotZAndNotCInt64(); 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 works test.RunLclFldScenario(); // Validates passing an instance member works test.RunFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class BooleanTwoComparisonOpTest__TestNotZAndNotCInt64 { private const int VectorSize = 16; private const int Op1ElementCount = VectorSize / sizeof(Int64); private const int Op2ElementCount = VectorSize / sizeof(Int64); private static Int64[] _data1 = new Int64[Op1ElementCount]; private static Int64[] _data2 = new Int64[Op2ElementCount]; private static Vector128<Int64> _clsVar1; private static Vector128<Int64> _clsVar2; private Vector128<Int64> _fld1; private Vector128<Int64> _fld2; private BooleanTwoComparisonOpTest__DataTable<Int64, Int64> _dataTable; static BooleanTwoComparisonOpTest__TestNotZAndNotCInt64() { var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (long)(random.Next(int.MinValue, int.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref _clsVar1), ref Unsafe.As<Int64, byte>(ref _data1[0]), VectorSize); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (long)(random.Next(int.MinValue, int.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref _clsVar2), ref Unsafe.As<Int64, byte>(ref _data2[0]), VectorSize); } public BooleanTwoComparisonOpTest__TestNotZAndNotCInt64() { Succeeded = true; var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (long)(random.Next(int.MinValue, int.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref _fld1), ref Unsafe.As<Int64, byte>(ref _data1[0]), VectorSize); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (long)(random.Next(int.MinValue, int.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int64>, byte>(ref _fld2), ref Unsafe.As<Int64, byte>(ref _data2[0]), VectorSize); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (long)(random.Next(int.MinValue, int.MaxValue)); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (long)(random.Next(int.MinValue, int.MaxValue)); } _dataTable = new BooleanTwoComparisonOpTest__DataTable<Int64, Int64>(_data1, _data2, VectorSize); } public bool IsSupported => Sse41.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { var result = Sse41.TestNotZAndNotC( Unsafe.Read<Vector128<Int64>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int64>>(_dataTable.inArray2Ptr) ); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result); } public void RunBasicScenario_Load() { var result = Sse41.TestNotZAndNotC( Sse2.LoadVector128((Int64*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Int64*)(_dataTable.inArray2Ptr)) ); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result); } public void RunBasicScenario_LoadAligned() { var result = Sse41.TestNotZAndNotC( Sse2.LoadAlignedVector128((Int64*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Int64*)(_dataTable.inArray2Ptr)) ); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result); } public void RunReflectionScenario_UnsafeRead() { var method = typeof(Sse41).GetMethod(nameof(Sse41.TestNotZAndNotC), new Type[] { typeof(Vector128<Int64>), typeof(Vector128<Int64>) }); if (method != null) { var result = method.Invoke(null, new object[] { Unsafe.Read<Vector128<Int64>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int64>>(_dataTable.inArray2Ptr) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result)); } } public void RunReflectionScenario_Load() { var method = typeof(Sse41).GetMethod(nameof(Sse41.TestNotZAndNotC), new Type[] { typeof(Vector128<Int64>), typeof(Vector128<Int64>) }); if (method != null) { var result = method.Invoke(null, new object[] { Sse2.LoadVector128((Int64*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Int64*)(_dataTable.inArray2Ptr)) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result)); } } public void RunReflectionScenario_LoadAligned() {var method = typeof(Sse41).GetMethod(nameof(Sse41.TestNotZAndNotC), new Type[] { typeof(Vector128<Int64>), typeof(Vector128<Int64>) }); if (method != null) { var result = method.Invoke(null, new object[] { Sse2.LoadAlignedVector128((Int64*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Int64*)(_dataTable.inArray2Ptr)) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result)); } } public void RunClsVarScenario() { var result = Sse41.TestNotZAndNotC( _clsVar1, _clsVar2 ); ValidateResult(_clsVar1, _clsVar2, result); } public void RunLclVarScenario_UnsafeRead() { var left = Unsafe.Read<Vector128<Int64>>(_dataTable.inArray1Ptr); var right = Unsafe.Read<Vector128<Int64>>(_dataTable.inArray2Ptr); var result = Sse41.TestNotZAndNotC(left, right); ValidateResult(left, right, result); } public void RunLclVarScenario_Load() { var left = Sse2.LoadVector128((Int64*)(_dataTable.inArray1Ptr)); var right = Sse2.LoadVector128((Int64*)(_dataTable.inArray2Ptr)); var result = Sse41.TestNotZAndNotC(left, right); ValidateResult(left, right, result); } public void RunLclVarScenario_LoadAligned() { var left = Sse2.LoadAlignedVector128((Int64*)(_dataTable.inArray1Ptr)); var right = Sse2.LoadAlignedVector128((Int64*)(_dataTable.inArray2Ptr)); var result = Sse41.TestNotZAndNotC(left, right); ValidateResult(left, right, result); } public void RunLclFldScenario() { var test = new BooleanTwoComparisonOpTest__TestNotZAndNotCInt64(); var result = Sse41.TestNotZAndNotC(test._fld1, test._fld2); ValidateResult(test._fld1, test._fld2, result); } public void RunFldScenario() { var result = Sse41.TestNotZAndNotC(_fld1, _fld2); ValidateResult(_fld1, _fld2, result); } public void RunUnsupportedScenario() { Succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector128<Int64> left, Vector128<Int64> right, bool result, [CallerMemberName] string method = "") { Int64[] inArray1 = new Int64[Op1ElementCount]; Int64[] inArray2 = new Int64[Op2ElementCount]; Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left); Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right); ValidateResult(inArray1, inArray2, result, method); } private void ValidateResult(void* left, void* right, bool result, [CallerMemberName] string method = "") { Int64[] inArray1 = new Int64[Op1ElementCount]; Int64[] inArray2 = new Int64[Op2ElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize); ValidateResult(inArray1, inArray2, result, method); } private void ValidateResult(Int64[] left, Int64[] right, bool result, [CallerMemberName] string method = "") { var expectedResult1 = true; for (var i = 0; i < Op1ElementCount; i++) { expectedResult1 &= (((left[i] & right[i]) == 0)); } var expectedResult2 = true; for (var i = 0; i < Op1ElementCount; i++) { expectedResult2 &= (((~left[i] & right[i]) == 0)); } if (((expectedResult1 == false) && (expectedResult2 == false)) != result) { Succeeded = false; Console.WriteLine($"{nameof(Sse41)}.{nameof(Sse41.TestNotZAndNotC)}<Int64>(Vector128<Int64>, Vector128<Int64>): {method} failed:"); Console.WriteLine($" left: ({string.Join(", ", left)})"); Console.WriteLine($" right: ({string.Join(", ", right)})"); Console.WriteLine($" result: ({string.Join(", ", result)})"); Console.WriteLine(); } } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // // This file was autogenerated by a tool. // Do not modify it. // namespace Microsoft.Azure.Batch { using Models = Microsoft.Azure.Batch.Protocol.Models; using System; using System.Collections.Generic; using System.Linq; /// <summary> /// A task which is run when a compute node joins a pool in the Azure Batch service, or when the compute node is rebooted /// or reimaged. /// </summary> /// <remarks> /// <para>Batch will retry tasks when a recovery operation is triggered on a compute node. Examples of recovery operations /// include (but are not limited to) when an unhealthy compute node is rebooted or a compute node disappeared due to /// host failure. Retries due to recovery operations are independent of and are not counted against the <see cref="TaskConstraints.MaxTaskRetryCount" /// />. Even if the <see cref="TaskConstraints.MaxTaskRetryCount" /> is 0, an internal retry due to a recovery operation /// may occur. Because of this, all tasks should be idempotent. This means tasks need to tolerate being interrupted and /// restarted without causing any corruption or duplicate data.</para><para>The best practice for long running tasks /// is to use some form of checkpointing. Special care should be taken to avoid start tasks which create breakaway process /// or install/launch services from the start task working directory, as this will block Batch from being able to re-run /// the start task.</para> /// </remarks> public partial class StartTask : ITransportObjectProvider<Models.StartTask>, IPropertyMetadata { private class PropertyContainer : PropertyCollection { public readonly PropertyAccessor<string> CommandLineProperty; public readonly PropertyAccessor<TaskContainerSettings> ContainerSettingsProperty; public readonly PropertyAccessor<IList<EnvironmentSetting>> EnvironmentSettingsProperty; public readonly PropertyAccessor<int?> MaxTaskRetryCountProperty; public readonly PropertyAccessor<IList<ResourceFile>> ResourceFilesProperty; public readonly PropertyAccessor<UserIdentity> UserIdentityProperty; public readonly PropertyAccessor<bool?> WaitForSuccessProperty; public PropertyContainer() : base(BindingState.Unbound) { this.CommandLineProperty = this.CreatePropertyAccessor<string>(nameof(CommandLine), BindingAccess.Read | BindingAccess.Write); this.ContainerSettingsProperty = this.CreatePropertyAccessor<TaskContainerSettings>(nameof(ContainerSettings), BindingAccess.Read | BindingAccess.Write); this.EnvironmentSettingsProperty = this.CreatePropertyAccessor<IList<EnvironmentSetting>>(nameof(EnvironmentSettings), BindingAccess.Read | BindingAccess.Write); this.MaxTaskRetryCountProperty = this.CreatePropertyAccessor<int?>(nameof(MaxTaskRetryCount), BindingAccess.Read | BindingAccess.Write); this.ResourceFilesProperty = this.CreatePropertyAccessor<IList<ResourceFile>>(nameof(ResourceFiles), BindingAccess.Read | BindingAccess.Write); this.UserIdentityProperty = this.CreatePropertyAccessor<UserIdentity>(nameof(UserIdentity), BindingAccess.Read | BindingAccess.Write); this.WaitForSuccessProperty = this.CreatePropertyAccessor<bool?>(nameof(WaitForSuccess), BindingAccess.Read | BindingAccess.Write); } public PropertyContainer(Models.StartTask protocolObject) : base(BindingState.Bound) { this.CommandLineProperty = this.CreatePropertyAccessor( protocolObject.CommandLine, nameof(CommandLine), BindingAccess.Read | BindingAccess.Write); this.ContainerSettingsProperty = this.CreatePropertyAccessor( UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.ContainerSettings, o => new TaskContainerSettings(o).Freeze()), nameof(ContainerSettings), BindingAccess.Read); this.EnvironmentSettingsProperty = this.CreatePropertyAccessor( EnvironmentSetting.ConvertFromProtocolCollection(protocolObject.EnvironmentSettings), nameof(EnvironmentSettings), BindingAccess.Read | BindingAccess.Write); this.MaxTaskRetryCountProperty = this.CreatePropertyAccessor( protocolObject.MaxTaskRetryCount, nameof(MaxTaskRetryCount), BindingAccess.Read | BindingAccess.Write); this.ResourceFilesProperty = this.CreatePropertyAccessor( ResourceFile.ConvertFromProtocolCollection(protocolObject.ResourceFiles), nameof(ResourceFiles), BindingAccess.Read | BindingAccess.Write); this.UserIdentityProperty = this.CreatePropertyAccessor( UtilitiesInternal.CreateObjectWithNullCheck(protocolObject.UserIdentity, o => new UserIdentity(o)), nameof(UserIdentity), BindingAccess.Read | BindingAccess.Write); this.WaitForSuccessProperty = this.CreatePropertyAccessor( protocolObject.WaitForSuccess, nameof(WaitForSuccess), BindingAccess.Read | BindingAccess.Write); } } private readonly PropertyContainer propertyContainer; #region Constructors /// <summary> /// Initializes a new instance of the <see cref="StartTask"/> class. /// </summary> /// <param name='commandLine'>The command line of the task.</param> public StartTask( string commandLine) { this.propertyContainer = new PropertyContainer(); this.CommandLine = commandLine; } internal StartTask(Models.StartTask protocolObject) { this.propertyContainer = new PropertyContainer(protocolObject); } #endregion Constructors #region StartTask /// <summary> /// Gets or sets the command line of the task. /// </summary> /// <remarks> /// The command line does not run under a shell, and therefore cannot take advantage of shell features such as environment /// variable expansion. If you want to take advantage of such features, you should invoke the shell in the command /// line, for example using "cmd /c MyCommand" in Windows or "/bin/sh -c MyCommand" in Linux. If the command line /// refers to file paths, it should use a relative path (relative to the task working directory), or use the Batch /// provided environment variables (https://docs.microsoft.com/en-us/azure/batch/batch-compute-node-environment-variables). /// </remarks> public string CommandLine { get { return this.propertyContainer.CommandLineProperty.Value; } set { this.propertyContainer.CommandLineProperty.Value = value; } } /// <summary> /// Gets or sets the settings for the container under which the task runs. /// </summary> /// <remarks> /// When this is specified, all directories recursively below the AZ_BATCH_NODE_ROOT_DIR (the root of Azure Batch /// directories on the node) are mapped into the container, all task environment variables are mapped into the container, /// and the task command line is executed in the container. Files produced in the container outside of AZ_BATCH_NODE_ROOT_DIR /// might not be reflected to the host disk, meaning that Batch file APIs will not be able to access them. /// </remarks> public TaskContainerSettings ContainerSettings { get { return this.propertyContainer.ContainerSettingsProperty.Value; } set { this.propertyContainer.ContainerSettingsProperty.Value = value; } } /// <summary> /// Gets or sets a set of environment settings for the start task. /// </summary> public IList<EnvironmentSetting> EnvironmentSettings { get { return this.propertyContainer.EnvironmentSettingsProperty.Value; } set { this.propertyContainer.EnvironmentSettingsProperty.Value = ConcurrentChangeTrackedModifiableList<EnvironmentSetting>.TransformEnumerableToConcurrentModifiableList(value); } } /// <summary> /// Gets or sets the maximum number of retries for the task. /// </summary> public int? MaxTaskRetryCount { get { return this.propertyContainer.MaxTaskRetryCountProperty.Value; } set { this.propertyContainer.MaxTaskRetryCountProperty.Value = value; } } /// <summary> /// Gets or sets a list of files that the Batch service will download to the compute node before running the command /// line. /// </summary> /// <remarks> /// There is a maximum size for the list of resource files. When the max size is exceeded, the request will fail /// and the response error code will be RequestEntityTooLarge. If this occurs, the collection of resource files must /// be reduced in size. This can be achieved using .zip files, Application Packages, or Docker Containers. /// </remarks> public IList<ResourceFile> ResourceFiles { get { return this.propertyContainer.ResourceFilesProperty.Value; } set { this.propertyContainer.ResourceFilesProperty.Value = ConcurrentChangeTrackedModifiableList<ResourceFile>.TransformEnumerableToConcurrentModifiableList(value); } } /// <summary> /// Gets or sets the user identity under which the task runs. /// </summary> /// <remarks> /// If omitted, the task runs as a non-administrative user unique to the task. /// </remarks> public UserIdentity UserIdentity { get { return this.propertyContainer.UserIdentityProperty.Value; } set { this.propertyContainer.UserIdentityProperty.Value = value; } } /// <summary> /// Gets or sets a value indicating whether the Batch service should wait for the start task to complete before scheduling /// any tasks on the compute node. /// </summary> /// <remarks> /// If this is not specified, the default is true. /// </remarks> public bool? WaitForSuccess { get { return this.propertyContainer.WaitForSuccessProperty.Value; } set { this.propertyContainer.WaitForSuccessProperty.Value = value; } } #endregion // StartTask #region IPropertyMetadata bool IModifiable.HasBeenModified { get { return this.propertyContainer.HasBeenModified; } } bool IReadOnly.IsReadOnly { get { return this.propertyContainer.IsReadOnly; } set { this.propertyContainer.IsReadOnly = value; } } #endregion //IPropertyMetadata #region Internal/private methods /// <summary> /// Return a protocol object of the requested type. /// </summary> /// <returns>The protocol object of the requested type.</returns> Models.StartTask ITransportObjectProvider<Models.StartTask>.GetTransportObject() { Models.StartTask result = new Models.StartTask() { CommandLine = this.CommandLine, ContainerSettings = UtilitiesInternal.CreateObjectWithNullCheck(this.ContainerSettings, (o) => o.GetTransportObject()), EnvironmentSettings = UtilitiesInternal.ConvertToProtocolCollection(this.EnvironmentSettings), MaxTaskRetryCount = this.MaxTaskRetryCount, ResourceFiles = UtilitiesInternal.ConvertToProtocolCollection(this.ResourceFiles), UserIdentity = UtilitiesInternal.CreateObjectWithNullCheck(this.UserIdentity, (o) => o.GetTransportObject()), WaitForSuccess = this.WaitForSuccess, }; return result; } #endregion // Internal/private methods } }
using Media.Plugin.Abstractions; // // Copyright 2011-2013, Xamarin Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // using System; using System.Threading.Tasks; using System.Threading; using System.IO; using System.Linq; #if __UNIFIED__ using UIKit; using CoreGraphics; #else using MonoTouch.UIKit; using CGRect = global::System.Drawing.RectangleF; #endif namespace Media.Plugin { /// <summary> /// Implementation for Media /// </summary> public class MediaImplementation : IMedia { public static UIStatusBarStyle StatusBarStyle { get; set; } /// <summary> /// Implementation /// </summary> public MediaImplementation() { StatusBarStyle = UIApplication.SharedApplication.StatusBarStyle; IsCameraAvailable = UIImagePickerController.IsSourceTypeAvailable(UIImagePickerControllerSourceType.Camera); var availableCameraMedia = UIImagePickerController.AvailableMediaTypes(UIImagePickerControllerSourceType.Camera) ?? new string[0]; var avaialbleLibraryMedia = UIImagePickerController.AvailableMediaTypes(UIImagePickerControllerSourceType.PhotoLibrary) ?? new string[0]; foreach (string type in availableCameraMedia.Concat(avaialbleLibraryMedia)) { if (type == TypeMovie) IsTakeVideoSupported = IsPickVideoSupported = true; else if (type == TypeImage) IsTakePhotoSupported = IsPickPhotoSupported = true; } } /// <inheritdoc/> public bool IsCameraAvailable { get; private set; } /// <inheritdoc/> public bool IsTakePhotoSupported { get; private set; } /// <inheritdoc/> public bool IsPickPhotoSupported { get; private set; } /// <inheritdoc/> public bool IsTakeVideoSupported { get; private set; } /// <inheritdoc/> public bool IsPickVideoSupported { get; private set; } /// <summary> /// /// </summary> /// <returns></returns> public MediaPickerController GetPickPhotoUI() { if (!IsPickPhotoSupported) throw new NotSupportedException(); var d = new MediaPickerDelegate(null, UIImagePickerControllerSourceType.PhotoLibrary, null); return SetupController(d, UIImagePickerControllerSourceType.PhotoLibrary, TypeImage); } /// <summary> /// Picks a photo from the default gallery /// </summary> /// <returns>Media file or null if canceled</returns> public Task<MediaFile> PickPhotoAsync() { if (!IsPickPhotoSupported) throw new NotSupportedException(); return GetMediaAsync(UIImagePickerControllerSourceType.PhotoLibrary, TypeImage); } /// <summary> /// /// </summary> /// <param name="options"></param> /// <returns></returns> public MediaPickerController GetTakePhotoUI(StoreCameraMediaOptions options) { if (!IsTakePhotoSupported) throw new NotSupportedException(); if (!IsCameraAvailable) throw new NotSupportedException(); VerifyCameraOptions(options); var d = new MediaPickerDelegate(null, UIImagePickerControllerSourceType.PhotoLibrary, options); return SetupController(d, UIImagePickerControllerSourceType.Camera, TypeImage, options); } /// <summary> /// Take a photo async with specified options /// </summary> /// <param name="options">Camera Media Options</param> /// <returns>Media file of photo or null if canceled</returns> public Task<MediaFile> TakePhotoAsync(StoreCameraMediaOptions options) { if (!IsTakePhotoSupported) throw new NotSupportedException(); if (!IsCameraAvailable) throw new NotSupportedException(); VerifyCameraOptions(options); return GetMediaAsync(UIImagePickerControllerSourceType.Camera, TypeImage, options); } /// <summary> /// /// </summary> /// <returns></returns> public MediaPickerController GetPickVideoUI() { if (!IsPickVideoSupported) throw new NotSupportedException(); var d = new MediaPickerDelegate(null, UIImagePickerControllerSourceType.PhotoLibrary, null); return SetupController(d, UIImagePickerControllerSourceType.PhotoLibrary, TypeMovie); } /// <summary> /// Picks a video from the default gallery /// </summary> /// <returns>Media file of video or null if canceled</returns> public Task<MediaFile> PickVideoAsync() { if (!IsPickVideoSupported) throw new NotSupportedException(); return GetMediaAsync(UIImagePickerControllerSourceType.PhotoLibrary, TypeMovie); } /// <summary> /// /// </summary> /// <param name="options"></param> /// <returns></returns> public MediaPickerController GetTakeVideoUI(StoreVideoOptions options) { if (!IsTakeVideoSupported) throw new NotSupportedException(); if (!IsCameraAvailable) throw new NotSupportedException(); VerifyCameraOptions(options); var d = new MediaPickerDelegate(null, UIImagePickerControllerSourceType.Camera, options); return SetupController(d, UIImagePickerControllerSourceType.Camera, TypeMovie, options); } /// <summary> /// Take a video with specified options /// </summary> /// <param name="options">Video Media Options</param> /// <returns>Media file of new video or null if canceled</returns> public Task<MediaFile> TakeVideoAsync(StoreVideoOptions options) { if (!IsTakeVideoSupported) throw new NotSupportedException(); if (!IsCameraAvailable) throw new NotSupportedException(); VerifyCameraOptions(options); return GetMediaAsync(UIImagePickerControllerSourceType.Camera, TypeMovie, options); } private UIPopoverController popover; private UIImagePickerControllerDelegate pickerDelegate; /// <summary> /// image type /// </summary> public const string TypeImage = "public.image"; /// <summary> /// movie type /// </summary> public const string TypeMovie = "public.movie"; private void VerifyOptions(StoreMediaOptions options) { if (options == null) throw new ArgumentNullException("options"); if (options.Directory != null && Path.IsPathRooted(options.Directory)) throw new ArgumentException("options.Directory must be a relative path", "options"); } private void VerifyCameraOptions(StoreCameraMediaOptions options) { VerifyOptions(options); if (!Enum.IsDefined(typeof(CameraDevice), options.DefaultCamera)) throw new ArgumentException("options.Camera is not a member of CameraDevice"); } private static MediaPickerController SetupController(MediaPickerDelegate mpDelegate, UIImagePickerControllerSourceType sourceType, string mediaType, StoreCameraMediaOptions options = null) { var picker = new MediaPickerController(mpDelegate); picker.MediaTypes = new[] { mediaType }; picker.SourceType = sourceType; if (sourceType == UIImagePickerControllerSourceType.Camera) { picker.CameraDevice = GetUICameraDevice(options.DefaultCamera); if (options.OverlayViewProvider != null) { var overlay = options.OverlayViewProvider (); if (overlay is UIView) { picker.CameraOverlayView = overlay as UIView; } } if (mediaType == TypeImage) picker.CameraCaptureMode = UIImagePickerControllerCameraCaptureMode.Photo; else if (mediaType == TypeMovie) { StoreVideoOptions voptions = (StoreVideoOptions)options; picker.CameraCaptureMode = UIImagePickerControllerCameraCaptureMode.Video; picker.VideoQuality = GetQuailty(voptions.Quality); picker.VideoMaximumDuration = voptions.DesiredLength.TotalSeconds; } } return picker; } private Task<MediaFile> GetMediaAsync(UIImagePickerControllerSourceType sourceType, string mediaType, StoreCameraMediaOptions options = null) { UIWindow window = UIApplication.SharedApplication.KeyWindow; if (window == null) throw new InvalidOperationException("There's no current active window"); UIViewController viewController = window.RootViewController; if (viewController == null) { window = UIApplication.SharedApplication.Windows.OrderByDescending(w => w.WindowLevel).FirstOrDefault(w => w.RootViewController != null); if (window == null) throw new InvalidOperationException("Could not find current view controller"); else viewController = window.RootViewController; } while (viewController.PresentedViewController != null) viewController = viewController.PresentedViewController; MediaPickerDelegate ndelegate = new MediaPickerDelegate(viewController, sourceType, options); var od = Interlocked.CompareExchange(ref this.pickerDelegate, ndelegate, null); if (od != null) throw new InvalidOperationException("Only one operation can be active at at time"); var picker = SetupController(ndelegate, sourceType, mediaType, options); if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad && sourceType == UIImagePickerControllerSourceType.PhotoLibrary) { ndelegate.Popover = new UIPopoverController(picker); ndelegate.Popover.Delegate = new MediaPickerPopoverDelegate(ndelegate, picker); ndelegate.DisplayPopover(); } else viewController.PresentViewController(picker, true, null); return ndelegate.Task.ContinueWith(t => { if (this.popover != null) { this.popover.Dispose(); this.popover = null; } Interlocked.Exchange(ref this.pickerDelegate, null); return t; }).Unwrap(); } private static UIImagePickerControllerCameraDevice GetUICameraDevice(CameraDevice device) { switch (device) { case CameraDevice.Front: return UIImagePickerControllerCameraDevice.Front; case CameraDevice.Rear: return UIImagePickerControllerCameraDevice.Rear; default: throw new NotSupportedException(); } } private static UIImagePickerControllerQualityType GetQuailty(VideoQuality quality) { switch (quality) { case VideoQuality.Low: return UIImagePickerControllerQualityType.Low; case VideoQuality.Medium: return UIImagePickerControllerQualityType.Medium; default: return UIImagePickerControllerQualityType.High; } } } }
using J2N.Threading.Atomic; using Lucene.Net.Support.Threading; using System.Collections.Generic; using System.Diagnostics; namespace Lucene.Net.Index { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using FlushedSegment = Lucene.Net.Index.DocumentsWriterPerThread.FlushedSegment; /// <summary> /// @lucene.internal /// </summary> internal class DocumentsWriterFlushQueue { private readonly LinkedList<FlushTicket> queue = new LinkedList<FlushTicket>(); // we track tickets separately since count must be present even before the ticket is // constructed ie. queue.size would not reflect it. private readonly AtomicInt32 ticketCount = new AtomicInt32(); private readonly ReentrantLock purgeLock = new ReentrantLock(); internal virtual void AddDeletes(DocumentsWriterDeleteQueue deleteQueue) { lock (this) { IncTickets(); // first inc the ticket count - freeze opens // a window for #anyChanges to fail bool success = false; try { queue.AddLast(new GlobalDeletesTicket(deleteQueue.FreezeGlobalBuffer(null))); success = true; } finally { if (!success) { DecTickets(); } } } } private void IncTickets() { int numTickets = ticketCount.IncrementAndGet(); Debug.Assert(numTickets > 0); } private void DecTickets() { int numTickets = ticketCount.DecrementAndGet(); Debug.Assert(numTickets >= 0); } internal virtual SegmentFlushTicket AddFlushTicket(DocumentsWriterPerThread dwpt) { lock (this) { // Each flush is assigned a ticket in the order they acquire the ticketQueue // lock IncTickets(); bool success = false; try { // prepare flush freezes the global deletes - do in synced block! SegmentFlushTicket ticket = new SegmentFlushTicket(dwpt.PrepareFlush()); queue.AddLast(ticket); success = true; return ticket; } finally { if (!success) { DecTickets(); } } } } internal virtual void AddSegment(SegmentFlushTicket ticket, FlushedSegment segment) { lock (this) { // the actual flush is done asynchronously and once done the FlushedSegment // is passed to the flush ticket ticket.SetSegment(segment); } } internal virtual void MarkTicketFailed(SegmentFlushTicket ticket) { lock (this) { // to free the queue we mark tickets as failed just to clean up the queue. ticket.SetFailed(); } } internal virtual bool HasTickets { get { Debug.Assert(ticketCount >= 0, "ticketCount should be >= 0 but was: " + ticketCount); return ticketCount != 0; } } private int InnerPurge(IndexWriter writer) { //Debug.Assert(PurgeLock.HeldByCurrentThread); int numPurged = 0; while (true) { FlushTicket head; bool canPublish; lock (this) { head = queue.Count <= 0 ? null : queue.First.Value; canPublish = head != null && head.CanPublish; // do this synced } if (canPublish) { numPurged++; try { /* * if we block on publish -> lock IW -> lock BufferedDeletes we don't block * concurrent segment flushes just because they want to append to the queue. * the downside is that we need to force a purge on fullFlush since ther could * be a ticket still in the queue. */ head.Publish(writer); } finally { lock (this) { // finally remove the published ticket from the queue FlushTicket poll = queue.First.Value; queue.Remove(poll); ticketCount.DecrementAndGet(); Debug.Assert(poll == head); } } } else { break; } } return numPurged; } internal virtual int ForcePurge(IndexWriter writer) { //Debug.Assert(!Thread.HoldsLock(this)); //Debug.Assert(!Thread.holdsLock(writer)); purgeLock.@Lock(); try { return InnerPurge(writer); } finally { purgeLock.Unlock(); } } internal virtual int TryPurge(IndexWriter writer) { //Debug.Assert(!Thread.holdsLock(this)); //Debug.Assert(!Thread.holdsLock(writer)); if (purgeLock.TryLock()) { try { return InnerPurge(writer); } finally { purgeLock.Unlock(); } } return 0; } public virtual int TicketCount => ticketCount; internal virtual void Clear() { lock (this) { queue.Clear(); ticketCount.Value = 0; } } internal abstract class FlushTicket { protected FrozenBufferedUpdates m_frozenUpdates; protected bool m_published = false; protected FlushTicket(FrozenBufferedUpdates frozenUpdates) { Debug.Assert(frozenUpdates != null); this.m_frozenUpdates = frozenUpdates; } protected internal abstract void Publish(IndexWriter writer); protected internal abstract bool CanPublish { get; } /// <summary> /// Publishes the flushed segment, segment private deletes (if any) and its /// associated global delete (if present) to <see cref="IndexWriter"/>. The actual /// publishing operation is synced on IW -> BDS so that the <see cref="SegmentInfo"/>'s /// delete generation is always <see cref="FrozenBufferedUpdates.DelGen"/> (<paramref name="globalPacket"/>) + 1 /// </summary> protected void PublishFlushedSegment(IndexWriter indexWriter, FlushedSegment newSegment, FrozenBufferedUpdates globalPacket) { Debug.Assert(newSegment != null); Debug.Assert(newSegment.segmentInfo != null); FrozenBufferedUpdates segmentUpdates = newSegment.segmentUpdates; //System.out.println("FLUSH: " + newSegment.segmentInfo.info.name); if (indexWriter.infoStream.IsEnabled("DW")) { indexWriter.infoStream.Message("DW", "publishFlushedSegment seg-private updates=" + segmentUpdates); } if (segmentUpdates != null && indexWriter.infoStream.IsEnabled("DW")) { indexWriter.infoStream.Message("DW", "flush: push buffered seg private updates: " + segmentUpdates); } // now publish! indexWriter.PublishFlushedSegment(newSegment.segmentInfo, segmentUpdates, globalPacket); } protected void FinishFlush(IndexWriter indexWriter, FlushedSegment newSegment, FrozenBufferedUpdates bufferedUpdates) { // Finish the flushed segment and publish it to IndexWriter if (newSegment == null) { Debug.Assert(bufferedUpdates != null); if (bufferedUpdates != null && bufferedUpdates.Any()) { indexWriter.PublishFrozenUpdates(bufferedUpdates); if (indexWriter.infoStream.IsEnabled("DW")) { indexWriter.infoStream.Message("DW", "flush: push buffered updates: " + bufferedUpdates); } } } else { PublishFlushedSegment(indexWriter, newSegment, bufferedUpdates); } } } internal sealed class GlobalDeletesTicket : FlushTicket { internal GlobalDeletesTicket(FrozenBufferedUpdates frozenUpdates) // LUCENENET NOTE: Made internal rather than protected because class is sealed : base(frozenUpdates) { } protected internal override void Publish(IndexWriter writer) { Debug.Assert(!m_published, "ticket was already publised - can not publish twice"); m_published = true; // its a global ticket - no segment to publish FinishFlush(writer, null, m_frozenUpdates); } protected internal override bool CanPublish => true; } internal sealed class SegmentFlushTicket : FlushTicket { internal FlushedSegment segment; internal bool failed = false; internal SegmentFlushTicket(FrozenBufferedUpdates frozenDeletes) // LUCENENET NOTE: Made internal rather than protected because class is sealed : base(frozenDeletes) { } protected internal override void Publish(IndexWriter writer) { Debug.Assert(!m_published, "ticket was already publised - can not publish twice"); m_published = true; FinishFlush(writer, segment, m_frozenUpdates); } internal void SetSegment(FlushedSegment segment) // LUCENENET NOTE: Made internal rather than protected because class is sealed { Debug.Assert(!failed); this.segment = segment; } internal void SetFailed() // LUCENENET NOTE: Made internal rather than protected because class is sealed { Debug.Assert(segment == null); failed = true; } protected internal override bool CanPublish => segment != null || failed; } } }
// <copyright file="GPGSAndroidSetupUI.cs" company="Google Inc."> // Copyright (C) Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> #if UNITY_ANDROID namespace GooglePlayGames.Editor { using System; using System.Collections; using System.IO; using System.Xml; using GooglePlayServices; using UnityEditor; using UnityEngine; /// <summary> /// Google Play Game Services Setup dialog for Android. /// </summary> public class GPGSAndroidSetupUI : EditorWindow { /// <summary> /// The configuration data from the play games console "resource data" /// </summary> private string mConfigData = string.Empty; /// <summary> /// The name of the class to generate containing the resource constants. /// </summary> private string mClassName = "GPGSIds"; /// <summary>True if G+ is needed for this application.</summary> private bool mRequiresGooglePlus = false; /// <summary> /// The scroll position /// </summary> private Vector2 scroll; /// <summary> /// The directory for the constants class. /// </summary> private string mConstantDirectory = "Assets"; /// <summary> /// The web client identifier. /// </summary> private string mWebClientId = string.Empty; /// <summary> /// Menus the item for GPGS android setup. /// </summary> [MenuItem("Window/Google Play Games/Setup/Android setup...", false, 1)] public static void MenuItemFileGPGSAndroidSetup() { EditorWindow window = EditorWindow.GetWindow( typeof(GPGSAndroidSetupUI), true, GPGSStrings.AndroidSetup.Title); window.minSize = new Vector2(500, 400); } /// <summary> /// Performs setup using the Android resources downloaded XML file /// from the play console. /// </summary> /// <returns><c>true</c>, if setup was performed, <c>false</c> otherwise.</returns> /// <param name="clientId">The web client id.</param> /// <param name="classDirectory">the directory to write the constants file to.</param> /// <param name="className">Fully qualified class name for the resource Ids.</param> /// <param name="resourceXmlData">Resource xml data.</param> /// <param name="nearbySvcId">Nearby svc identifier.</param> /// <param name="requiresGooglePlus">Indicates this app requires G+</param> public static bool PerformSetup( string clientId, string classDirectory, string className, string resourceXmlData, string nearbySvcId, bool requiresGooglePlus) { if (string.IsNullOrEmpty(resourceXmlData) && !string.IsNullOrEmpty(nearbySvcId)) { return PerformSetup( clientId, GPGSProjectSettings.Instance.Get(GPGSUtil.APPIDKEY), nearbySvcId, requiresGooglePlus); } if (ParseResources(classDirectory, className, resourceXmlData)) { GPGSProjectSettings.Instance.Set(GPGSUtil.CLASSDIRECTORYKEY, classDirectory); GPGSProjectSettings.Instance.Set(GPGSUtil.CLASSNAMEKEY, className); GPGSProjectSettings.Instance.Set(GPGSUtil.ANDROIDRESOURCEKEY, resourceXmlData); // check the bundle id and set it if needed. CheckBundleId(); GPGSDependencies.svcSupport.ClearDependencies(); GPGSDependencies.RegisterDependencies(); PlayServicesResolver.Resolver.DoResolution( GPGSDependencies.svcSupport, "Assets/Plugins/Android", PlayServicesResolver.HandleOverwriteConfirmation); return PerformSetup( clientId, GPGSProjectSettings.Instance.Get(GPGSUtil.APPIDKEY), nearbySvcId, requiresGooglePlus); } return false; } /// <summary> /// Provide static access to setup for facilitating automated builds. /// </summary> /// <param name="webClientId">The oauth2 client id for the game. This is only /// needed if the ID Token or access token are needed.</param> /// <param name="appId">App identifier.</param> /// <param name="nearbySvcId">Optional nearby connection serviceId</param> /// <param name="requiresGooglePlus">Indicates that GooglePlus should be enabled</param> /// <returns>true if successful</returns> public static bool PerformSetup(string webClientId, string appId, string nearbySvcId, bool requiresGooglePlus) { if (!string.IsNullOrEmpty(webClientId)) { if (!GPGSUtil.LooksLikeValidClientId(webClientId)) { GPGSUtil.Alert(GPGSStrings.Setup.ClientIdError); return false; } string serverAppId = webClientId.Split('-')[0]; if (!serverAppId.Equals(appId)) { GPGSUtil.Alert(GPGSStrings.Setup.AppIdMismatch); return false; } } // check for valid app id if (!GPGSUtil.LooksLikeValidAppId(appId) && string.IsNullOrEmpty(nearbySvcId)) { GPGSUtil.Alert(GPGSStrings.Setup.AppIdError); return false; } if (nearbySvcId != null) { if (!NearbyConnectionUI.PerformSetup(nearbySvcId, true)) { return false; } } GPGSProjectSettings.Instance.Set(GPGSUtil.APPIDKEY, appId); GPGSProjectSettings.Instance.Set(GPGSUtil.WEBCLIENTIDKEY, webClientId); GPGSProjectSettings.Instance.Set(GPGSUtil.REQUIREGOOGLEPLUSKEY, requiresGooglePlus); GPGSProjectSettings.Instance.Save(); GPGSUtil.UpdateGameInfo(); // check that Android SDK is there if (!GPGSUtil.HasAndroidSdk()) { Debug.LogError("Android SDK not found."); EditorUtility.DisplayDialog( GPGSStrings.AndroidSetup.SdkNotFound, GPGSStrings.AndroidSetup.SdkNotFoundBlurb, GPGSStrings.Ok); return false; } // Generate AndroidManifest.xml GPGSUtil.GenerateAndroidManifest(); // refresh assets, and we're done AssetDatabase.Refresh(); GPGSProjectSettings.Instance.Set(GPGSUtil.ANDROIDSETUPDONEKEY, true); GPGSProjectSettings.Instance.Save(); return true; } /// <summary> /// Called when this object is enabled by Unity editor. /// </summary> public void OnEnable() { GPGSProjectSettings settings = GPGSProjectSettings.Instance; mConstantDirectory = settings.Get("ConstDir", mConstantDirectory); mClassName = settings.Get(GPGSUtil.CLASSNAMEKEY); mConfigData = settings.Get(GPGSUtil.ANDROIDRESOURCEKEY); mWebClientId = settings.Get(GPGSUtil.WEBCLIENTIDKEY); mRequiresGooglePlus = settings.GetBool(GPGSUtil.REQUIREGOOGLEPLUSKEY, false); } /// <summary> /// Called when the GUI should be rendered. /// </summary> public void OnGUI() { GUI.skin.label.wordWrap = true; GUILayout.BeginVertical(); GUIStyle link = new GUIStyle(GUI.skin.label); link.normal.textColor = new Color(0f, 0f, 1f); GUILayout.Space(10); GUILayout.Label(GPGSStrings.AndroidSetup.Blurb); if (GUILayout.Button("Open Play Games Console", link, GUILayout.ExpandWidth(false))) { Application.OpenURL("https://play.google.com/apps/publish"); } Rect last = GUILayoutUtility.GetLastRect(); last.y += last.height - 2; last.x += 3; last.width -= 6; last.height = 2; GUI.Box(last, string.Empty); GUILayout.Space(15); GUILayout.Label("Constants class name", EditorStyles.boldLabel); GUILayout.Label("Enter the fully qualified name of the class to create containing the constants"); GUILayout.Space(10); mConstantDirectory = EditorGUILayout.TextField( "Directory to save constants", mConstantDirectory, GUILayout.Width(480)); mClassName = EditorGUILayout.TextField( "Constants class name", mClassName, GUILayout.Width(480)); GUILayout.Label("Resources Definition", EditorStyles.boldLabel); GUILayout.Label("Paste in the Android Resources from the Play Console"); GUILayout.Space(10); scroll = GUILayout.BeginScrollView(scroll); mConfigData = EditorGUILayout.TextArea( mConfigData, GUILayout.Width(475), GUILayout.Height(Screen.height)); GUILayout.EndScrollView(); GUILayout.Space(10); // Requires G+ field GUILayout.BeginHorizontal(); GUILayout.Label(GPGSStrings.Setup.RequiresGPlusTitle, EditorStyles.boldLabel); mRequiresGooglePlus = EditorGUILayout.Toggle(mRequiresGooglePlus); GUILayout.EndHorizontal(); GUILayout.Label(GPGSStrings.Setup.RequiresGPlusBlurb); // Client ID field GUILayout.Label(GPGSStrings.Setup.WebClientIdTitle, EditorStyles.boldLabel); GUILayout.Label(GPGSStrings.AndroidSetup.WebClientIdBlurb); mWebClientId = EditorGUILayout.TextField( GPGSStrings.Setup.ClientId, mWebClientId, GUILayout.Width(450)); GUILayout.Space(10); GUILayout.FlexibleSpace(); GUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); if (GUILayout.Button(GPGSStrings.Setup.SetupButton, GUILayout.Width(100))) { // check that the classname entered is valid try { if (GPGSUtil.LooksLikeValidPackageName(mClassName)) { DoSetup(); } } catch (Exception e) { GPGSUtil.Alert( GPGSStrings.Error, "Invalid classname: " + e.Message); } } if (GUILayout.Button("Cancel", GUILayout.Width(100))) { Close(); } GUILayout.FlexibleSpace(); GUILayout.EndHorizontal(); GUILayout.Space(20); GUILayout.EndVertical(); } /// <summary> /// Starts the setup process. /// </summary> public void DoSetup() { if (PerformSetup(mWebClientId, mConstantDirectory, mClassName, mConfigData, null, mRequiresGooglePlus)) { CheckBundleId(); EditorUtility.DisplayDialog( GPGSStrings.Success, GPGSStrings.AndroidSetup.SetupComplete, GPGSStrings.Ok); GPGSProjectSettings.Instance.Set(GPGSUtil.ANDROIDSETUPDONEKEY, true); Close(); } else { GPGSUtil.Alert( GPGSStrings.Error, "Invalid or missing XML resource data. Make sure the data is" + " valid and contains the app_id element"); } } /// <summary> /// Checks the bundle identifier. /// </summary> /// <remarks> /// Check the package id. If one is set the gpgs properties, /// and the player settings are the default or empty, set it. /// if the player settings is not the default, then prompt before /// overwriting. /// </remarks> public static void CheckBundleId() { string packageName = GPGSProjectSettings.Instance.Get( GPGSUtil.ANDROIDBUNDLEIDKEY, string.Empty); string currentId = PlayerSettings.applicationIdentifier; if (!string.IsNullOrEmpty(packageName)) { if (string.IsNullOrEmpty(currentId) || currentId == "com.Company.ProductName") { PlayerSettings.applicationIdentifier = packageName; } else if (currentId != packageName) { if (EditorUtility.DisplayDialog( "Set Bundle Identifier?", "The server configuration is using " + packageName + ", but the player settings is set to " + currentId + ".\nSet the Bundle Identifier to " + packageName + "?", "OK", "Cancel")) { PlayerSettings.applicationIdentifier = packageName; } } } else { Debug.Log("NULL package!!"); } } /// <summary> /// Parses the resources xml and set the properties. Also generates the /// constants file. /// </summary> /// <returns><c>true</c>, if resources was parsed, <c>false</c> otherwise.</returns> /// <param name="classDirectory">Class directory.</param> /// <param name="className">Class name.</param> /// <param name="res">Res. the data to parse.</param> private static bool ParseResources(string classDirectory, string className, string res) { XmlTextReader reader = new XmlTextReader(new StringReader(res)); bool inResource = false; string lastProp = null; Hashtable resourceKeys = new Hashtable(); string appId = null; while (reader.Read()) { if (reader.Name == "resources") { inResource = true; } if (inResource && reader.Name == "string") { lastProp = reader.GetAttribute("name"); } else if (inResource && !string.IsNullOrEmpty(lastProp)) { if (reader.HasValue) { if (lastProp == "app_id") { appId = reader.Value; GPGSProjectSettings.Instance.Set(GPGSUtil.APPIDKEY, appId); } else if (lastProp == "package_name") { GPGSProjectSettings.Instance.Set(GPGSUtil.ANDROIDBUNDLEIDKEY, reader.Value); } else { resourceKeys[lastProp] = reader.Value; } lastProp = null; } } } reader.Close(); if (resourceKeys.Count > 0) { GPGSUtil.WriteResourceIds(classDirectory, className, resourceKeys); } return appId != null; } } } #endif
using System; using System.Text; using System.Data; using System.Data.SqlClient; using System.Data.Common; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Xml; using System.Xml.Serialization; using SubSonic; using SubSonic.Utilities; // <auto-generated /> namespace DalSic { /// <summary> /// Strongly-typed collection for the PnNomencladorXPatologium class. /// </summary> [Serializable] public partial class PnNomencladorXPatologiumCollection : ActiveList<PnNomencladorXPatologium, PnNomencladorXPatologiumCollection> { public PnNomencladorXPatologiumCollection() {} /// <summary> /// Filters an existing collection based on the set criteria. This is an in-memory filter /// Thanks to developingchris for this! /// </summary> /// <returns>PnNomencladorXPatologiumCollection</returns> public PnNomencladorXPatologiumCollection Filter() { for (int i = this.Count - 1; i > -1; i--) { PnNomencladorXPatologium o = this[i]; foreach (SubSonic.Where w in this.wheres) { bool remove = false; System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName); if (pi.CanRead) { object val = pi.GetValue(o, null); switch (w.Comparison) { case SubSonic.Comparison.Equals: if (!val.Equals(w.ParameterValue)) { remove = true; } break; } } if (remove) { this.Remove(o); break; } } } return this; } } /// <summary> /// This is an ActiveRecord class which wraps the PN_NomencladorXPatologia table. /// </summary> [Serializable] public partial class PnNomencladorXPatologium : ActiveRecord<PnNomencladorXPatologium>, IActiveRecord { #region .ctors and Default Settings public PnNomencladorXPatologium() { SetSQLProps(); InitSetDefaults(); MarkNew(); } private void InitSetDefaults() { SetDefaults(); } public PnNomencladorXPatologium(bool useDatabaseDefaults) { SetSQLProps(); if(useDatabaseDefaults) ForceDefaults(); MarkNew(); } public PnNomencladorXPatologium(object keyID) { SetSQLProps(); InitSetDefaults(); LoadByKey(keyID); } public PnNomencladorXPatologium(string columnName, object columnValue) { SetSQLProps(); InitSetDefaults(); LoadByParam(columnName,columnValue); } protected static void SetSQLProps() { GetTableSchema(); } #endregion #region Schema and Query Accessor public static Query CreateQuery() { return new Query(Schema); } public static TableSchema.Table Schema { get { if (BaseSchema == null) SetSQLProps(); return BaseSchema; } } private static void GetTableSchema() { if(!IsSchemaInitialized) { //Schema declaration TableSchema.Table schema = new TableSchema.Table("PN_NomencladorXPatologia", TableType.Table, DataService.GetInstance("sicProvider")); schema.Columns = new TableSchema.TableColumnCollection(); schema.SchemaName = @"dbo"; //columns TableSchema.TableColumn colvarIdNomencladorXPatologia = new TableSchema.TableColumn(schema); colvarIdNomencladorXPatologia.ColumnName = "idNomencladorXPatologia"; colvarIdNomencladorXPatologia.DataType = DbType.Int32; colvarIdNomencladorXPatologia.MaxLength = 0; colvarIdNomencladorXPatologia.AutoIncrement = true; colvarIdNomencladorXPatologia.IsNullable = false; colvarIdNomencladorXPatologia.IsPrimaryKey = true; colvarIdNomencladorXPatologia.IsForeignKey = false; colvarIdNomencladorXPatologia.IsReadOnly = false; colvarIdNomencladorXPatologia.DefaultSetting = @""; colvarIdNomencladorXPatologia.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdNomencladorXPatologia); TableSchema.TableColumn colvarIdNomenclador = new TableSchema.TableColumn(schema); colvarIdNomenclador.ColumnName = "idNomenclador"; colvarIdNomenclador.DataType = DbType.Int32; colvarIdNomenclador.MaxLength = 0; colvarIdNomenclador.AutoIncrement = false; colvarIdNomenclador.IsNullable = true; colvarIdNomenclador.IsPrimaryKey = false; colvarIdNomenclador.IsForeignKey = true; colvarIdNomenclador.IsReadOnly = false; colvarIdNomenclador.DefaultSetting = @""; colvarIdNomenclador.ForeignKeyTableName = "PN_nomenclador"; schema.Columns.Add(colvarIdNomenclador); TableSchema.TableColumn colvarIdPatologia = new TableSchema.TableColumn(schema); colvarIdPatologia.ColumnName = "idPatologia"; colvarIdPatologia.DataType = DbType.Int32; colvarIdPatologia.MaxLength = 0; colvarIdPatologia.AutoIncrement = false; colvarIdPatologia.IsNullable = true; colvarIdPatologia.IsPrimaryKey = false; colvarIdPatologia.IsForeignKey = true; colvarIdPatologia.IsReadOnly = false; colvarIdPatologia.DefaultSetting = @""; colvarIdPatologia.ForeignKeyTableName = "PN_patologias"; schema.Columns.Add(colvarIdPatologia); BaseSchema = schema; //add this schema to the provider //so we can query it later DataService.Providers["sicProvider"].AddSchema("PN_NomencladorXPatologia",schema); } } #endregion #region Props [XmlAttribute("IdNomencladorXPatologia")] [Bindable(true)] public int IdNomencladorXPatologia { get { return GetColumnValue<int>(Columns.IdNomencladorXPatologia); } set { SetColumnValue(Columns.IdNomencladorXPatologia, value); } } [XmlAttribute("IdNomenclador")] [Bindable(true)] public int? IdNomenclador { get { return GetColumnValue<int?>(Columns.IdNomenclador); } set { SetColumnValue(Columns.IdNomenclador, value); } } [XmlAttribute("IdPatologia")] [Bindable(true)] public int? IdPatologia { get { return GetColumnValue<int?>(Columns.IdPatologia); } set { SetColumnValue(Columns.IdPatologia, value); } } #endregion #region ForeignKey Properties /// <summary> /// Returns a PnNomenclador ActiveRecord object related to this PnNomencladorXPatologium /// /// </summary> public DalSic.PnNomenclador PnNomenclador { get { return DalSic.PnNomenclador.FetchByID(this.IdNomenclador); } set { SetColumnValue("idNomenclador", value.IdNomenclador); } } /// <summary> /// Returns a PnPatologia ActiveRecord object related to this PnNomencladorXPatologium /// /// </summary> public DalSic.PnPatologia PnPatologia { get { return DalSic.PnPatologia.FetchByID(this.IdPatologia); } set { SetColumnValue("idPatologia", value.IdPatologias); } } #endregion //no ManyToMany tables defined (0) #region ObjectDataSource support /// <summary> /// Inserts a record, can be used with the Object Data Source /// </summary> public static void Insert(int? varIdNomenclador,int? varIdPatologia) { PnNomencladorXPatologium item = new PnNomencladorXPatologium(); item.IdNomenclador = varIdNomenclador; item.IdPatologia = varIdPatologia; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } /// <summary> /// Updates a record, can be used with the Object Data Source /// </summary> public static void Update(int varIdNomencladorXPatologia,int? varIdNomenclador,int? varIdPatologia) { PnNomencladorXPatologium item = new PnNomencladorXPatologium(); item.IdNomencladorXPatologia = varIdNomencladorXPatologia; item.IdNomenclador = varIdNomenclador; item.IdPatologia = varIdPatologia; item.IsNew = false; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } #endregion #region Typed Columns public static TableSchema.TableColumn IdNomencladorXPatologiaColumn { get { return Schema.Columns[0]; } } public static TableSchema.TableColumn IdNomencladorColumn { get { return Schema.Columns[1]; } } public static TableSchema.TableColumn IdPatologiaColumn { get { return Schema.Columns[2]; } } #endregion #region Columns Struct public struct Columns { public static string IdNomencladorXPatologia = @"idNomencladorXPatologia"; public static string IdNomenclador = @"idNomenclador"; public static string IdPatologia = @"idPatologia"; } #endregion #region Update PK Collections #endregion #region Deep Save #endregion } }
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Reflection; namespace NFig.UI { public class SettingsJsonModel<TTier, TDataCenter> where TTier : struct where TDataCenter : struct { static readonly ConcurrentDictionary<KeyValuePair<TTier, TDataCenter>, ValueBySpecificityComparer> s_specificityComparers = new ConcurrentDictionary<KeyValuePair<TTier, TDataCenter>, ValueBySpecificityComparer>(); [SuppressMessage("ReSharper", "UnusedMember.Local", Justification = "Used only for Jil serialization ")] SettingsJsonModel() { } public SettingsJsonModel( TTier tier, TDataCenter dataCenter, SettingInfo<TTier, TDataCenter>[] infos, IList<TDataCenter> availableDataCenters) { Settings = infos.OrderBy(i => i.Name) .Select( i => new Setting(tier, dataCenter, i, availableDataCenters)) .ToList(); AvailableDataCenters = availableDataCenters; CurrentTier = tier; } public List<Setting> Settings { get; } public IList<TDataCenter> AvailableDataCenters { get; } public TTier CurrentTier { get; } static ValueBySpecificityComparer GetComparerFor(TTier tier, TDataCenter dataCenter) { return s_specificityComparers.GetOrAdd( new KeyValuePair<TTier, TDataCenter>(tier, dataCenter), pair => new ValueBySpecificityComparer(tier, dataCenter) ); } public class ValueBySpecificityComparer : IComparer<SettingValue<TTier, TDataCenter>> { readonly TDataCenter _currentDataCenter; readonly TTier _currentTier; public ValueBySpecificityComparer(TTier currentTier, TDataCenter currentDataCenter) { _currentTier = currentTier; _currentDataCenter = currentDataCenter; } public int Compare(SettingValue<TTier, TDataCenter> x, SettingValue<TTier, TDataCenter> y) { if (EqualityComparer<TTier>.Default.Equals(x.Tier, y.Tier) && EqualityComparer<TDataCenter>.Default.Equals(x.DataCenter, y.DataCenter)) return 0; if (EqualityComparer<TTier>.Default.Equals(x.Tier, _currentTier) && EqualityComparer<TTier>.Default.Equals(y.Tier, _currentTier)) return -1; if (EqualityComparer<TTier>.Default.Equals(y.Tier, _currentTier) && EqualityComparer<TTier>.Default.Equals(x.Tier, _currentTier)) return 1; if (EqualityComparer<TDataCenter>.Default.Equals(x.DataCenter, _currentDataCenter) && EqualityComparer<TDataCenter>.Default.Equals(y.DataCenter, _currentDataCenter)) return -1; if (EqualityComparer<TDataCenter>.Default.Equals(y.DataCenter, _currentDataCenter) && EqualityComparer<TDataCenter>.Default.Equals(x.DataCenter, _currentDataCenter)) return 1; if (x.IsMoreSpecificThan(y)) return -1; if (y.IsMoreSpecificThan(x)) return 1; return 0; } } public class Setting { // Serialization [SuppressMessage("ReSharper", "UnusedMember.Local")] Setting() { } internal Setting( TTier currentTier, TDataCenter currentDataCenter, SettingInfo<TTier, TDataCenter> info, IList<TDataCenter> availableDataCenters) { Name = info.Name; Description = info.Description; TypeName = info.PropertyInfo.PropertyType.FullName; IsEnum = info.PropertyInfo.PropertyType.IsEnum; var activeValue = info.GetActiveValueFor(currentTier, currentDataCenter); if (activeValue.IsOverride) ActiveOverride = activeValue; DefaultValue = info.GetDefaultFor(currentTier, currentDataCenter); var sorter = GetComparerFor(currentTier, currentDataCenter); AllDefaults = info.Defaults.OrderBy(v => v, sorter).ToList(); AllOverrides = info.Overrides.OrderBy(v => v, sorter).ToList(); if (IsEnum) EnumNames = EnumToDictionary(info.PropertyInfo.PropertyType); AllowsOverrides = availableDataCenters.ToDictionary( dc => dc.ToString(), dc => info.CanSetOverrideFor(currentTier, dc)); RequiresRestart = Attribute.IsDefined(info.PropertyInfo, typeof(ChangeRequiresRestartAttribute)); } public string Name { get; } public string Description { get; } public SettingValue<TTier, TDataCenter> ActiveOverride { get; set; } public SettingValue<TTier, TDataCenter> DefaultValue { get; set; } public string TypeName { get; } public bool IsEnum { get; } public bool RequiresRestart { get; } public Dictionary<string, bool> AllowsOverrides { get; } /// <summary> /// Guaranteed to be in order of specificy /// </summary> public List<SettingValue<TTier, TDataCenter>> AllDefaults { get; } /// <summary> /// Guaranteed to be in order of specificy /// </summary> public List<SettingValue<TTier, TDataCenter>> AllOverrides { get; } /// <summary> /// If the type of this setting is an emum, /// this property will contain the available values /// for the setting /// </summary> public Dictionary<string, SettingEnumName> EnumNames { get; } static Dictionary<string, SettingEnumName> EnumToDictionary(Type enumType) { if (enumType == null) throw new ArgumentNullException(nameof(enumType)); if (!enumType.IsEnum) throw new ArgumentException($"{enumType} is not an enum type", nameof(enumType)); return Enum.GetNames(enumType).ToDictionary( n => Convert.ChangeType(Enum.Parse(enumType, n), enumType.GetEnumUnderlyingType()).ToString(), n => { var desc = enumType.GetField(n).GetCustomAttribute<DescriptionAttribute>(); return new SettingEnumName(n, desc?.Description); } ); } public class SettingEnumName { public SettingEnumName(string name) : this(name, null) { } public SettingEnumName(string name, string description) { Name = name; Description = description; } public string Name { get; } public string Description { get; } } } } }
//--------------------------------------------------------------------------- // // Copyright (C) Microsoft Corporation. All rights reserved. // // Description: Collection of Inline elements // //--------------------------------------------------------------------------- namespace System.Windows.Documents { using MS.Internal; // Invariant using System.Windows.Markup; // ContentWrapper using System.Windows.Controls; // TextBlock using System.Collections; /// <summary> /// Collection of Inline elements - elements allowed as children /// of Paragraph, Span and TextBlock elements. /// </summary> [ContentWrapper(typeof(Run))] [ContentWrapper(typeof(InlineUIContainer))] [WhitespaceSignificantCollection] public class InlineCollection : TextElementCollection<Inline>, IList { //------------------------------------------------------------------- // // Constructors // //------------------------------------------------------------------- #region Constructors // Constructor is internal. We allow InlineCollection creation only from inside owning elements such as TextBlock or TextElement. // Note that when a SiblingInlines collection is created for an Inline, the owner of collection is that member Inline object. // Flag isOwnerParent indicates whether owner is a parent or a member of the collection. internal InlineCollection(DependencyObject owner, bool isOwnerParent) : base(owner, isOwnerParent) { } #endregion Constructors //------------------------------------------------------------------- // // Public Methods // //------------------------------------------------------------------- #region Public Methods /// <summary> /// Implementation of Add method from IList /// </summary> internal override int OnAdd(object value) { int index; string text = value as string; if (text != null) { index = AddText(text, true /* returnIndex */); } else { this.TextContainer.BeginChange(); try { UIElement uiElement = value as UIElement; if (uiElement != null) { index = AddUIElement(uiElement, true /* returnIndex */); } else { index = base.OnAdd(value); } } finally { this.TextContainer.EndChange(); } } return index; } /// <summary> /// Adds an implicit Run element with a given text /// </summary> /// <param name="text"> /// Text set as a Text property for implicit Run. /// </param> public void Add(string text) { AddText(text, false /* returnIndex */); } /// <summary> /// Adds an implicit InlineUIContainer with a given UIElement in it. /// </summary> /// <param name="uiElement"> /// UIElement set as a Child property for the implicit InlineUIContainer. /// </param> public void Add(UIElement uiElement) { AddUIElement(uiElement, false /* returnIndex */); } #endregion Public Methods //------------------------------------------------------------------- // // Public Properties // //------------------------------------------------------------------- #region Public Properties /// <value> /// Returns a first Inline element of this collection /// </value> public Inline FirstInline { get { return this.FirstChild; } } /// <value> /// Returns a last Inline element of this collection /// </value> public Inline LastInline { get { return this.LastChild; } } #endregion Public Properties //------------------------------------------------------------------- // // Internal Methods // //------------------------------------------------------------------- #region Internal Methods /// <summary> /// This method performs schema validation for inline collections. /// (1) We want to disallow nested Hyperlink elements. /// (2) Also, a Hyperlink element allows only these child types: Run, InlineUIContainer and Span elements other than Hyperlink. /// </summary> internal override void ValidateChild(Inline child) { base.ValidateChild(child); if (this.Parent is TextElement) { TextSchema.ValidateChild((TextElement)this.Parent, child, true /* throwIfIllegalChild */, true /* throwIfIllegalHyperlinkDescendent */); } else { if (!TextSchema.IsValidChildOfContainer(this.Parent.GetType(), child.GetType())) { throw new InvalidOperationException(SR.Get(SRID.TextSchema_ChildTypeIsInvalid, this.Parent.GetType().Name, child.GetType().Name)); } } } #endregion Internal Methods //------------------------------------------------------------------- // // Private Methods // //------------------------------------------------------------------- #region Private Methods // Worker for OnAdd and Add(string). // If returnIndex == true, uses the more costly IList.Add // to calculate and return the index of the newly inserted // Run, otherwise returns -1. private int AddText(string text, bool returnIndex) { if (text == null) { throw new ArgumentNullException("text"); } // Special case for TextBlock - to keep its simple content in simple state if (this.Parent is TextBlock) { TextBlock textBlock = (TextBlock)this.Parent; if (!textBlock.HasComplexContent) { textBlock.Text = textBlock.Text + text; return 0; // There's always one implicit Run with simple content, at index 0. } } this.TextContainer.BeginChange(); try { Run implicitRun = Run.CreateImplicitRun(this.Parent); int index; if (returnIndex) { index = base.OnAdd(implicitRun); } else { this.Add(implicitRun); index = -1; } // Set the Text property after inserting the Run to avoid allocating // a temporary TextContainer. implicitRun.Text = text; return index; } finally { this.TextContainer.EndChange(); } } // Worker for OnAdd and Add(UIElement). // If returnIndex == true, uses the more costly IList.Add // to calculate and return the index of the newly inserted // Run, otherwise returns -1. private int AddUIElement(UIElement uiElement, bool returnIndex) { if (uiElement == null) { throw new ArgumentNullException("uiElement"); } InlineUIContainer implicitInlineUIContainer = Run.CreateImplicitInlineUIContainer(this.Parent); int index; if (returnIndex) { index = base.OnAdd(implicitInlineUIContainer); } else { this.Add(implicitInlineUIContainer); index = -1; } implicitInlineUIContainer.Child = uiElement; return index; } #endregion Private Methods } }
using System; using System.Text; using System.Data; using System.Data.SqlClient; using System.Data.Common; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Xml; using System.Xml.Serialization; using SubSonic; using SubSonic.Utilities; namespace DalSic { /// <summary> /// Strongly-typed collection for the PnZonaSani class. /// </summary> [Serializable] public partial class PnZonaSaniCollection : ActiveList<PnZonaSani, PnZonaSaniCollection> { public PnZonaSaniCollection() {} /// <summary> /// Filters an existing collection based on the set criteria. This is an in-memory filter /// Thanks to developingchris for this! /// </summary> /// <returns>PnZonaSaniCollection</returns> public PnZonaSaniCollection Filter() { for (int i = this.Count - 1; i > -1; i--) { PnZonaSani o = this[i]; foreach (SubSonic.Where w in this.wheres) { bool remove = false; System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName); if (pi.CanRead) { object val = pi.GetValue(o, null); switch (w.Comparison) { case SubSonic.Comparison.Equals: if (!val.Equals(w.ParameterValue)) { remove = true; } break; } } if (remove) { this.Remove(o); break; } } } return this; } } /// <summary> /// This is an ActiveRecord class which wraps the PN_zona_sani table. /// </summary> [Serializable] public partial class PnZonaSani : ActiveRecord<PnZonaSani>, IActiveRecord { #region .ctors and Default Settings public PnZonaSani() { SetSQLProps(); InitSetDefaults(); MarkNew(); } private void InitSetDefaults() { SetDefaults(); } public PnZonaSani(bool useDatabaseDefaults) { SetSQLProps(); if(useDatabaseDefaults) ForceDefaults(); MarkNew(); } public PnZonaSani(object keyID) { SetSQLProps(); InitSetDefaults(); LoadByKey(keyID); } public PnZonaSani(string columnName, object columnValue) { SetSQLProps(); InitSetDefaults(); LoadByParam(columnName,columnValue); } protected static void SetSQLProps() { GetTableSchema(); } #endregion #region Schema and Query Accessor public static Query CreateQuery() { return new Query(Schema); } public static TableSchema.Table Schema { get { if (BaseSchema == null) SetSQLProps(); return BaseSchema; } } private static void GetTableSchema() { if(!IsSchemaInitialized) { //Schema declaration TableSchema.Table schema = new TableSchema.Table("PN_zona_sani", TableType.Table, DataService.GetInstance("sicProvider")); schema.Columns = new TableSchema.TableColumnCollection(); schema.SchemaName = @"dbo"; //columns TableSchema.TableColumn colvarIdZonaSani = new TableSchema.TableColumn(schema); colvarIdZonaSani.ColumnName = "id_zona_sani"; colvarIdZonaSani.DataType = DbType.Int32; colvarIdZonaSani.MaxLength = 0; colvarIdZonaSani.AutoIncrement = true; colvarIdZonaSani.IsNullable = false; colvarIdZonaSani.IsPrimaryKey = true; colvarIdZonaSani.IsForeignKey = false; colvarIdZonaSani.IsReadOnly = false; colvarIdZonaSani.DefaultSetting = @""; colvarIdZonaSani.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdZonaSani); TableSchema.TableColumn colvarNombreZona = new TableSchema.TableColumn(schema); colvarNombreZona.ColumnName = "nombre_zona"; colvarNombreZona.DataType = DbType.AnsiString; colvarNombreZona.MaxLength = -1; colvarNombreZona.AutoIncrement = false; colvarNombreZona.IsNullable = true; colvarNombreZona.IsPrimaryKey = false; colvarNombreZona.IsForeignKey = false; colvarNombreZona.IsReadOnly = false; colvarNombreZona.DefaultSetting = @""; colvarNombreZona.ForeignKeyTableName = ""; schema.Columns.Add(colvarNombreZona); BaseSchema = schema; //add this schema to the provider //so we can query it later DataService.Providers["sicProvider"].AddSchema("PN_zona_sani",schema); } } #endregion #region Props [XmlAttribute("IdZonaSani")] [Bindable(true)] public int IdZonaSani { get { return GetColumnValue<int>(Columns.IdZonaSani); } set { SetColumnValue(Columns.IdZonaSani, value); } } [XmlAttribute("NombreZona")] [Bindable(true)] public string NombreZona { get { return GetColumnValue<string>(Columns.NombreZona); } set { SetColumnValue(Columns.NombreZona, value); } } #endregion #region PrimaryKey Methods protected override void SetPrimaryKey(object oValue) { base.SetPrimaryKey(oValue); SetPKValues(); } private DalSic.PnEfeConvCollection colPnEfeConvRecords; public DalSic.PnEfeConvCollection PnEfeConvRecords { get { if(colPnEfeConvRecords == null) { colPnEfeConvRecords = new DalSic.PnEfeConvCollection().Where(PnEfeConv.Columns.IdZonaSani, IdZonaSani).Load(); colPnEfeConvRecords.ListChanged += new ListChangedEventHandler(colPnEfeConvRecords_ListChanged); } return colPnEfeConvRecords; } set { colPnEfeConvRecords = value; colPnEfeConvRecords.ListChanged += new ListChangedEventHandler(colPnEfeConvRecords_ListChanged); } } void colPnEfeConvRecords_ListChanged(object sender, ListChangedEventArgs e) { if (e.ListChangedType == ListChangedType.ItemAdded) { // Set foreign key value colPnEfeConvRecords[e.NewIndex].IdZonaSani = IdZonaSani; } } #endregion //no foreign key tables defined (0) //no ManyToMany tables defined (0) #region ObjectDataSource support /// <summary> /// Inserts a record, can be used with the Object Data Source /// </summary> public static void Insert(string varNombreZona) { PnZonaSani item = new PnZonaSani(); item.NombreZona = varNombreZona; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } /// <summary> /// Updates a record, can be used with the Object Data Source /// </summary> public static void Update(int varIdZonaSani,string varNombreZona) { PnZonaSani item = new PnZonaSani(); item.IdZonaSani = varIdZonaSani; item.NombreZona = varNombreZona; item.IsNew = false; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } #endregion #region Typed Columns public static TableSchema.TableColumn IdZonaSaniColumn { get { return Schema.Columns[0]; } } public static TableSchema.TableColumn NombreZonaColumn { get { return Schema.Columns[1]; } } #endregion #region Columns Struct public struct Columns { public static string IdZonaSani = @"id_zona_sani"; public static string NombreZona = @"nombre_zona"; } #endregion #region Update PK Collections public void SetPKValues() { if (colPnEfeConvRecords != null) { foreach (DalSic.PnEfeConv item in colPnEfeConvRecords) { if (item.IdZonaSani != IdZonaSani) { item.IdZonaSani = IdZonaSani; } } } } #endregion #region Deep Save public void DeepSave() { Save(); if (colPnEfeConvRecords != null) { colPnEfeConvRecords.SaveAll(); } } #endregion } }
using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Security; // ReSharper disable RedundantNameQualifier namespace Sawczyn.EFDesigner.EFModel.EditingOnly { // ReSharper disable once UnusedMember.Global public partial class GeneratedTextTransformation { #region Template // EFDesigner v3.0.8.0 // Copyright (c) 2017-2021 Michael Sawczyn // https://github.com/msawczyn/EFDesigner protected void NL() { WriteLine(string.Empty); } protected void Output(List<string> segments) { if (ModelRoot.ChopMethodChains) OutputChopped(segments); else Output(string.Join(".", segments) + ";"); segments.Clear(); } protected void Output(string text) { if (text == "}") PopIndent(); WriteLine(text); if (text == "{") PushIndent(ModelRoot.UseTabs ? "\t" : " "); } protected void Output(string template, params object[] items) { string text = string.Format(template, items); Output(text); } protected void OutputChopped(List<string> segments) { string[] segmentArray = segments?.ToArray() ?? new string[0]; if (!segmentArray.Any()) return; int indent = segmentArray[0].IndexOf('.'); if (indent == -1) { if (segmentArray.Length > 1) { segmentArray[0] = $"{segmentArray[0]}.{segmentArray[1]}"; indent = segmentArray[0].IndexOf('.'); segmentArray = segmentArray.Where((source, index) => index != 1).ToArray(); } } for (int index = 1; index < segmentArray.Length; ++index) segmentArray[index] = $"{new string(' ', indent)}.{segmentArray[index]}"; if (!segmentArray[segmentArray.Length - 1].Trim().EndsWith(";")) segmentArray[segmentArray.Length - 1] = segmentArray[segmentArray.Length - 1] + ";"; foreach (string segment in segmentArray) Output(segment); segments.Clear(); } public abstract class EFModelGenerator { protected static string[] xmlDocTags = { @"<([\s]*c[\s]*[/]?[\s]*)>" , @"<(/[\s]*c[\s]*)>" , @"<([\s]*code[\s]*[/]?[\s]*)>" , @"<(/[\s]*code[\s]*)>" , @"<([\s]*description[\s]*[/]?[\s]*)>" , @"<(/[\s]*description[\s]*)>" , @"<([\s]*example[\s]*[/]?[\s]*)>" , @"<(/[\s]*example[\s]*)>" , @"<([\s]*exception cref=""[^""]+""[\s]*[/]?[\s]*)>" , @"<(/[\s]*exception[\s]*)>" , @"<([\s]*include file='[^']+' path='tagpath\[@name=""[^""]+""\]'[\s]*/)>" , @"<([\s]*inheritdoc/[\s]*)>" , @"<([\s]*item[\s]*[/]?[\s]*)>" , @"<(/[\s]*item[\s]*)>" , @"<([\s]*list type=""[^""]+""[\s]*[/]?[\s]*)>" , @"<(/[\s]*list[\s]*)>" , @"<([\s]*listheader[\s]*[/]?[\s]*)>" , @"<(/[\s]*listheader[\s]*)>" , @"<([\s]*para[\s]*[/]?[\s]*)>" , @"<(/[\s]*para[\s]*)>" , @"<([\s]*param name=""[^""]+""[\s]*[/]?[\s]*)>" , @"<(/[\s]*param[\s]*)>" , @"<([\s]*paramref name=""[^""]+""/[\s]*)>" , @"<([\s]*permission cref=""[^""]+""[\s]*[/]?[\s]*)>" , @"<(/[\s]*permission[\s]*)>" , @"<([\s]*remarks[\s]*[/]?[\s]*)>" , @"<(/[\s]*remarks[\s]*)>" , @"<([\s]*returns[\s]*[/]?[\s]*)>" , @"<(/[\s]*returns[\s]*)>" , @"<([\s]*see cref=""[^""]+""/[\s]*)>" , @"<([\s]*seealso cref=""[^""]+""/[\s]*)>" , @"<([\s]*summary[\s]*[/]?[\s]*)>" , @"<(/[\s]*summary[\s]*)>" , @"<([\s]*term[\s]*[/]?[\s]*)>" , @"<(/[\s]*term[\s]*)>" , @"<([\s]*typeparam name=""[^""]+""[\s]*[/]?[\s]*)>" , @"<(/[\s]*typeparam[\s]*)>" , @"<([\s]*typeparamref name=""[^""]+""/[\s]*)>" , @"<([\s]*value[\s]*[/]?[\s]*)>" , @"<(/[\s]*value[\s]*)>" }; protected EFModelGenerator(GeneratedTextTransformation host) { this.host = host; modelRoot = host.ModelRoot; } #pragma warning disable IDE1006 // Naming Styles protected ModelRoot modelRoot { get; set; } protected GeneratedTextTransformation host { get; set; } #pragma warning restore IDE1006 // Naming Styles // implementations delegated to the surrounding GeneratedTextTransformation for backward compatability protected void NL() { host.NL(); } protected void Output(List<string> segments) { host.Output(segments); } protected void Output(string text) { host.Output(text); } protected void Output(string template, params object[] items) { host.Output(template, items); } protected void ClearIndent() { host.ClearIndent(); } public static string[] NonNullableTypes { get { return new[] { "Binary" , "Geography" , "GeographyCollection" , "GeographyLineString" , "GeographyMultiLineString" , "GeographyMultiPoint" , "GeographyMultiPolygon" , "GeographyPoint" , "GeographyPolygon" , "Geometry" , "GeometryCollection" , "GeometryLineString" , "GeometryMultiLineString" , "GeometryMultiPoint" , "GeometryMultiPolygon" , "GeometryPoint" , "GeometryPolygon" , "String" }; } } protected bool AllSuperclassesAreNullOrAbstract(ModelClass modelClass) { ModelClass superClass = modelClass.Superclass; while (superClass != null) { if (!superClass.IsAbstract) return false; superClass = superClass.Superclass; } return true; } protected void BeginNamespace(string ns) { if (!string.IsNullOrEmpty(ns)) { Output($"namespace {ns}"); Output("{"); } } protected static string CreateShadowPropertyName(Association association, List<string> foreignKeyColumns, ModelAttribute identityAttribute) { string separator = identityAttribute.ModelClass.ModelRoot.ShadowKeyNamePattern == ShadowKeyPattern.TableColumn ? string.Empty : "_"; string GetShadowPropertyName(string nameBase) { return $"{nameBase}{separator}{identityAttribute.Name}"; } string GetShadowPropertyNameBase() { if (association.SourceRole == EndpointRole.Dependent) return association.TargetPropertyName; if (association is BidirectionalAssociation b) return b.SourcePropertyName; return $"{association.Source.Name}{separator}{association.TargetPropertyName}"; } string shadowNameBase = GetShadowPropertyNameBase(); string shadowPropertyName = GetShadowPropertyName(shadowNameBase); int index = 0; while (foreignKeyColumns.Contains(shadowPropertyName)) shadowPropertyName = GetShadowPropertyName($"{shadowNameBase}{++index}"); return shadowPropertyName; } protected void EndNamespace(string ns) { if (!string.IsNullOrEmpty(ns)) Output("}"); } protected string FullyQualified(string typeName) { string[] parts = typeName.Split('.'); if (parts.Length == 1) return typeName; string simpleName = parts[0]; ModelEnum modelEnum = modelRoot.Store.ElementDirectory.AllElements.OfType<ModelEnum>().FirstOrDefault(e => e.Name == simpleName); return modelEnum != null ? $"{modelEnum.FullName}.{parts.Last()}" : typeName; } public abstract void Generate(Manager efModelFileManager); protected void GeneratePropertyAnnotations(ModelAttribute modelAttribute) { if (modelAttribute.Persistent) { if (modelAttribute.IsIdentity) Output("[Key]"); if (modelAttribute.IsConcurrencyToken) Output("[ConcurrencyCheck]"); } else Output("[NotMapped]"); if (modelAttribute.Required) Output("[Required]"); if (modelAttribute.FQPrimitiveType == "string") { if (modelAttribute.MinLength > 0) Output($"[MinLength({modelAttribute.MinLength})]"); if (modelAttribute.MaxLength > 0) { Output($"[MaxLength({modelAttribute.MaxLength})]"); Output($"[StringLength({modelAttribute.MaxLength})]"); } } if (!string.IsNullOrWhiteSpace(modelAttribute.DisplayText)) Output($"[Display(Name=\"{modelAttribute.DisplayText.Replace("\"", "\\\"")}\")]"); if (!string.IsNullOrWhiteSpace(modelAttribute.Summary)) Output($"[System.ComponentModel.Description(\"{modelAttribute.Summary.Replace("\"", "\\\"")}\")]"); } protected abstract List<string> GetAdditionalUsingStatements(); protected string GetDefaultConstructorVisibility(ModelClass modelClass) { if (modelClass.DefaultConstructorVisibility == TypeAccessModifierExt.Default) { bool hasRequiredParameters = GetRequiredParameters(modelClass, false, true).Any(); string visibility = (hasRequiredParameters || modelClass.IsAbstract) && !modelClass.IsDependentType ? "protected" : "public"; return visibility; } return modelClass.DefaultConstructorVisibility.ToString().ToLowerInvariant(); } protected string GetFullContainerName(string containerType, string payloadType) { string result; switch (containerType) { case "HashSet": result = "System.Collections.Generic.HashSet<T>"; break; case "LinkedList": result = "System.Collections.Generic.LinkedList<T>"; break; case "List": result = "System.Collections.Generic.List<T>"; break; case "SortedSet": result = "System.Collections.Generic.SortedSet<T>"; break; case "Collection": result = "System.Collections.ObjectModel.Collection<T>"; break; case "ObservableCollection": result = "System.Collections.ObjectModel.ObservableCollection<T>"; break; case "BindingList": result = "System.ComponentModel.BindingList<T>"; break; default: result = containerType; break; } if (result.EndsWith("<T>")) result = result.Replace("<T>", $"<{payloadType}>"); return result; } protected string GetMigrationNamespace() { List<string> nsParts = modelRoot.Namespace.Split('.').ToList(); nsParts = nsParts.Take(nsParts.Count - 1).ToList(); nsParts.Add("Migrations"); return string.Join(".", nsParts); } protected List<string> GetRequiredParameterNames(ModelClass modelClass, bool publicOnly = false) { return GetRequiredParameters(modelClass, null, publicOnly).Select(p => p.Split(' ')[1]).ToList(); } /// <summary>Gets the local required properties for the ModelClass in formal parameter format</summary> /// <param name="modelClass">Source</param> /// <param name="haveDefaults">If true, only return those with default values. If false, only return those without default values. If null, return both.</param> /// <param name="publicOnly">If true, only return those with public setters. If false, only return those without public setters. If null, return both.</param> protected List<string> GetRequiredParameters(ModelClass modelClass, bool? haveDefaults, bool publicOnly = false) { List<string> requiredParameters = new List<string>(); if (haveDefaults != true) { // false or null - get those without default values requiredParameters.AddRange(modelClass.AllRequiredAttributes .Where(x => (!x.IsIdentity || x.IdentityType == IdentityType.Manual) && !x.IsConcurrencyToken && (x.SetterVisibility == SetterAccessModifier.Public || !publicOnly) && string.IsNullOrEmpty(x.InitialValue)) .Select(x => $"{x.FQPrimitiveType} {x.Name.ToLower()}")); // don't use 1..1 associations in constructor parameters. Becomes a Catch-22 scenario. requiredParameters.AddRange(modelClass.AllRequiredNavigationProperties() .Where(np => np.AssociationObject.SourceMultiplicity != Sawczyn.EFDesigner.EFModel.Multiplicity.One || np.AssociationObject.TargetMultiplicity != Sawczyn.EFDesigner.EFModel.Multiplicity.One) .Select(x => $"{x.ClassType.FullName} {x.PropertyName.ToLower()}")); } if (haveDefaults != false) { // true or null - get those with default values requiredParameters.AddRange(modelClass.AllRequiredAttributes .Where(x => (!x.IsIdentity || x.IdentityType == IdentityType.Manual) && !x.IsConcurrencyToken && (x.SetterVisibility == SetterAccessModifier.Public || !publicOnly) && !string.IsNullOrEmpty(x.InitialValue)) .Select(x => { string quote = x.PrimitiveType == "string" ? "\"" : x.PrimitiveType == "char" ? "'" : string.Empty; string value = FullyQualified(quote.Length > 0 ? x.InitialValue.Trim(quote[0]) : x.InitialValue); if (x.FQPrimitiveType == "decimal") value += "m"; return $"{x.FQPrimitiveType} {x.Name.ToLower()} = {quote}{value}{quote}"; })); } return requiredParameters; } public static bool IsNullable(ModelAttribute modelAttribute) { return !modelAttribute.Required && !modelAttribute.IsIdentity && !modelAttribute.IsConcurrencyToken && !NonNullableTypes.Contains(modelAttribute.Type); } protected virtual void WriteClass(ModelClass modelClass) { Output("using System;"); Output("using System.Collections.Generic;"); Output("using System.Collections.ObjectModel;"); Output("using System.ComponentModel;"); Output("using System.ComponentModel.DataAnnotations;"); Output("using System.ComponentModel.DataAnnotations.Schema;"); Output("using System.Linq;"); Output("using System.Runtime.CompilerServices;"); List<string> additionalUsings = GetAdditionalUsingStatements(); if (additionalUsings.Any()) Output(string.Join("\n", additionalUsings)); NL(); BeginNamespace(modelClass.EffectiveNamespace); string isAbstract = modelClass.IsAbstract ? "abstract " : string.Empty; List<string> bases = new List<string>(); if (modelClass.Superclass != null) bases.Add(modelClass.Superclass.FullName); if (!string.IsNullOrEmpty(modelClass.CustomInterfaces)) bases.AddRange(modelClass.CustomInterfaces.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)); string baseClass = string.Join(", ", bases.Select(x => x.Trim())); if (!string.IsNullOrEmpty(modelClass.Summary)) { Output("/// <summary>"); WriteCommentBody(modelClass.Summary); Output("/// </summary>"); } if (!string.IsNullOrEmpty(modelClass.Description)) { Output("/// <remarks>"); WriteCommentBody(modelClass.Description); Output("/// </remarks>"); } if (!string.IsNullOrWhiteSpace(modelClass.CustomAttributes)) Output($"[{modelClass.CustomAttributes.Trim('[', ']')}]"); if (!string.IsNullOrWhiteSpace(modelClass.Summary)) Output($"[System.ComponentModel.Description(\"{modelClass.Summary.Replace("\"", "\\\"")}\")]"); Output(baseClass.Length > 0 ? $"public {isAbstract}partial class {modelClass.Name}: {baseClass}" : $"public {isAbstract}partial class {modelClass.Name}"); Output("{"); WriteConstructor(modelClass); WriteProperties(modelClass); WriteNavigationProperties(modelClass); Output("}"); EndNamespace(modelClass.EffectiveNamespace); NL(); } protected string[] GenerateCommentBody(string comment) { List<string> result = new List<string>(); if (!string.IsNullOrEmpty(comment)) { int chunkSize = 80; string[] parts = comment.Split(new[] {"\r\n", "\r", "\n"}, StringSplitOptions.RemoveEmptyEntries); foreach (string value in parts) { string text = value; while (text.Length > 0) { string outputText = text; if (outputText.Length > chunkSize) { outputText = (text.IndexOf(' ', chunkSize) > 0 ? text.Substring(0, text.IndexOf(' ', chunkSize)) : text).Trim(); text = text.Substring(outputText.Length).Trim(); } else text = string.Empty; result.Add(SecurityElement.Escape(outputText)); } } } return result.ToArray(); } protected void WriteCommentBody(string comment) { foreach (string s in GenerateCommentBody(comment)) Output($"/// {s}"); } protected void WriteConstructor(ModelClass modelClass) { Output("partial void Init();"); NL(); /***********************************************************************/ // Default constructor /***********************************************************************/ bool hasRequiredParameters = GetRequiredParameters(modelClass, false, true).Any(); bool hasOneToOneAssociations = modelClass.AllRequiredNavigationProperties() .Any(np => np.AssociationObject.SourceMultiplicity == Sawczyn.EFDesigner.EFModel.Multiplicity.One && np.AssociationObject.TargetMultiplicity != Sawczyn.EFDesigner.EFModel.Multiplicity.One); string visibility = GetDefaultConstructorVisibility(modelClass); if (visibility == "public") { Output("/// <summary>"); Output("/// Default constructor"); Output("/// </summary>"); } else if (modelClass.IsAbstract) { Output("/// <summary>"); Output("/// Default constructor. Protected due to being abstract."); Output("/// </summary>"); } else if (hasRequiredParameters) { Output("/// <summary>"); Output("/// Default constructor. Protected due to required properties, but present because EF needs it."); Output("/// </summary>"); } List<string> remarks = new List<string>(); if (hasOneToOneAssociations) { List<Association> oneToOneAssociations = modelClass.AllRequiredNavigationProperties() .Where(np => np.AssociationObject.SourceMultiplicity == Sawczyn.EFDesigner.EFModel.Multiplicity.One && np.AssociationObject.TargetMultiplicity == Sawczyn.EFDesigner.EFModel.Multiplicity.One) .Select(np => np.AssociationObject) .ToList(); List<ModelClass> otherEndsOneToOne = oneToOneAssociations.Where(a => a.Source != modelClass).Select(a => a.Target) .Union(oneToOneAssociations.Where(a => a.Target != modelClass).Select(a => a.Source)) .ToList(); if (oneToOneAssociations.Any(a => a.Source.Name == modelClass.Name && a.Target.Name == modelClass.Name)) otherEndsOneToOne.Add(modelClass); if (otherEndsOneToOne.Any()) { string nameList = otherEndsOneToOne.Count == 1 ? otherEndsOneToOne.First().Name : string.Join(", ", otherEndsOneToOne.Take(otherEndsOneToOne.Count - 1).Select(c => c.Name)) + " and " + (otherEndsOneToOne.Last().Name != modelClass.Name ? otherEndsOneToOne.Last().Name : "itself"); remarks.Add($"// NOTE: This class has one-to-one associations with {nameList}."); remarks.Add("// One-to-one associations are not validated in constructors since this causes a scenario where each one must be constructed before the other."); } } Output(modelClass.Superclass != null ? $"{visibility} {modelClass.Name}(): base()" : $"{visibility} {modelClass.Name}()"); Output("{"); if (remarks.Count > 0) { foreach (string remark in remarks) Output(remark); NL(); } WriteDefaultConstructorBody(modelClass); Output("}"); NL(); if (visibility != "public" && !modelClass.IsAbstract) { Output("/// <summary>"); Output("/// Replaces default constructor, since it's protected. Caller assumes responsibility for setting all required values before saving."); Output("/// </summary>"); Output($"public static {modelClass.Name} Create{modelClass.Name}Unsafe()"); Output("{"); Output($"return new {modelClass.Name}();"); Output("}"); NL(); } /***********************************************************************/ // Constructor with required parameters (if necessary) /***********************************************************************/ if (hasRequiredParameters) { visibility = modelClass.IsAbstract ? "protected" : "public"; Output("/// <summary>"); Output("/// Public constructor with required data"); Output("/// </summary>"); WriteConstructorComments(modelClass); Output($"{visibility} {modelClass.Name}({string.Join(", ", GetRequiredParameters(modelClass, null, true))})"); Output("{"); if (remarks.Count > 0) { foreach (string remark in remarks) Output(remark); NL(); } foreach (ModelAttribute requiredAttribute in modelClass.AllRequiredAttributes .Where(x => (!x.IsIdentity || x.IdentityType == IdentityType.Manual) && !x.IsConcurrencyToken && x.SetterVisibility == SetterAccessModifier.Public)) { if (requiredAttribute.Type == "String") Output($"if (string.IsNullOrEmpty({requiredAttribute.Name.ToLower()})) throw new ArgumentNullException(nameof({requiredAttribute.Name.ToLower()}));"); else if (requiredAttribute.Type.StartsWith("Geo")) Output($"if ({requiredAttribute.Name.ToLower()} == null) throw new ArgumentNullException(nameof({requiredAttribute.Name.ToLower()}));"); Output($"this.{requiredAttribute.Name} = {requiredAttribute.Name.ToLower()};"); NL(); } foreach (ModelAttribute modelAttribute in modelClass.Attributes.Where(x => x.SetterVisibility == SetterAccessModifier.Public && !x.Required && !string.IsNullOrEmpty(x.InitialValue) && x.InitialValue != "null")) { string quote = modelAttribute.Type == "String" ? "\"" : modelAttribute.Type == "Char" ? "'" : string.Empty; string initialValue = modelAttribute.InitialValue; if (modelAttribute.Type == "decimal") initialValue += "m"; Output(quote.Length > 0 ? $"this.{modelAttribute.Name} = {quote}{FullyQualified(initialValue.Trim(quote[0]))}{quote};" : $"this.{modelAttribute.Name} = {quote}{FullyQualified(initialValue)}{quote};"); } // all required navigation properties that aren't a 1..1 relationship foreach (NavigationProperty requiredNavigationProperty in modelClass.AllRequiredNavigationProperties() .Where(np => np.AssociationObject.SourceMultiplicity != Sawczyn.EFDesigner.EFModel.Multiplicity.One || np.AssociationObject.TargetMultiplicity != Sawczyn.EFDesigner.EFModel.Multiplicity.One)) { NavigationProperty otherSide = requiredNavigationProperty.OtherSide; string parameterName = requiredNavigationProperty.PropertyName.ToLower(); Output($"if ({parameterName} == null) throw new ArgumentNullException(nameof({parameterName}));"); if (!requiredNavigationProperty.ConstructorParameterOnly) { Output(requiredNavigationProperty.IsCollection ? $"{requiredNavigationProperty.PropertyName}.Add({parameterName});" : $"this.{requiredNavigationProperty.PropertyName} = {parameterName};"); } if (!string.IsNullOrEmpty(otherSide.PropertyName)) { Output(otherSide.IsCollection ? $"{parameterName}.{otherSide.PropertyName}.Add(this);" : $"{parameterName}.{otherSide.PropertyName} = this;"); } NL(); } WriteNavigationInitializersForConstructors(modelClass); Output("Init();"); Output("}"); NL(); if (!modelClass.IsAbstract) { Output("/// <summary>"); Output("/// Static create function (for use in LINQ queries, etc.)"); Output("/// </summary>"); WriteConstructorComments(modelClass); string newToken = string.Empty; List<string> requiredParameters = GetRequiredParameters(modelClass, null, true); if (!AllSuperclassesAreNullOrAbstract(modelClass)) { List<string> superclassRequiredParameters = GetRequiredParameters(modelClass.Superclass, null, true); if (!requiredParameters.Except(superclassRequiredParameters).Any()) newToken = "new "; } List<string> requiredParameterNames = GetRequiredParameterNames(modelClass, true); Output($"public static {newToken}{modelClass.Name} Create({string.Join(", ", requiredParameters)})"); Output("{"); Output($"return new {modelClass.Name}({string.Join(", ", requiredParameterNames)});"); Output("}"); NL(); } } } private int WriteNavigationInitializersForConstructors(ModelClass modelClass) { int lineCount = 0; foreach (NavigationProperty navigationProperty in modelClass.LocalNavigationProperties() .Where(x => x.AssociationObject.Persistent && x.IsCollection && !x.ConstructorParameterOnly)) { string collectionType = GetFullContainerName(navigationProperty.AssociationObject.CollectionClass, navigationProperty.ClassType.FullName); Output(navigationProperty.IsAutoProperty || string.IsNullOrEmpty(navigationProperty.BackingFieldName) ? $"{navigationProperty.PropertyName} = new {collectionType}();" : $"{navigationProperty.BackingFieldName} = new {collectionType}();"); ++lineCount; } foreach (NavigationProperty navigationProperty in modelClass.LocalNavigationProperties() .Where(x => x.AssociationObject.Persistent && !x.IsCollection && !x.ConstructorParameterOnly && x.Required && x.OtherSide.ClassType.IsDependentType)) { Output(navigationProperty.IsAutoProperty || string.IsNullOrEmpty(navigationProperty.BackingFieldName) ? $"{navigationProperty.PropertyName} = new {navigationProperty.OtherSide.ClassType.Namespace}.{navigationProperty.OtherSide.ClassType.Name}();" : $"{navigationProperty.BackingFieldName} = new {navigationProperty.OtherSide.ClassType.Namespace}.{navigationProperty.OtherSide.ClassType.Name}();"); ++lineCount; } return lineCount; } protected void WriteConstructorComments(ModelClass modelClass) { foreach (ModelAttribute requiredAttribute in modelClass.AllRequiredAttributes.Where(x => (!x.IsIdentity || x.IdentityType == IdentityType.Manual) && !x.IsConcurrencyToken && x.SetterVisibility == SetterAccessModifier.Public)) Output($@"/// <param name=""{requiredAttribute.Name.ToLower()}"">{string.Join(" ", GenerateCommentBody(requiredAttribute.Summary))}</param>"); foreach (NavigationProperty requiredNavigationProperty in modelClass.AllRequiredNavigationProperties() .Where(np => np.AssociationObject.SourceMultiplicity != Sawczyn.EFDesigner.EFModel.Multiplicity.One || np.AssociationObject.TargetMultiplicity != Sawczyn.EFDesigner.EFModel.Multiplicity.One)) Output($@"/// <param name=""{requiredNavigationProperty.PropertyName.ToLower()}"">{string.Join(" ", GenerateCommentBody(requiredNavigationProperty.Summary))}</param>"); } protected void WriteDbContextComments() { if (!string.IsNullOrEmpty(modelRoot.Summary)) { Output("/// <summary>"); WriteCommentBody(modelRoot.Summary); Output("/// </summary>"); if (!string.IsNullOrEmpty(modelRoot.Description)) { Output("/// <remarks>"); WriteCommentBody(modelRoot.Description); Output("/// </remarks>"); } } else Output("/// <inheritdoc/>"); } protected void WriteDefaultConstructorBody(ModelClass modelClass) { int lineCount = 0; foreach (ModelAttribute modelAttribute in modelClass.Attributes.Where(x => x.SetterVisibility == SetterAccessModifier.Public && !string.IsNullOrEmpty(x.InitialValue) && x.InitialValue.Trim('"') != "null")) { string quote = modelAttribute.Type == "String" ? "\"" : modelAttribute.Type == "Char" ? "'" : string.Empty; string initialValue = modelAttribute.InitialValue; if (modelAttribute.Type == "decimal") initialValue += "m"; Output(quote.Length == 1 ? $"{modelAttribute.Name} = {quote}{FullyQualified(initialValue.Trim(quote[0]))}{quote};" : $"{modelAttribute.Name} = {quote}{FullyQualified(initialValue)}{quote};"); ++lineCount; } lineCount += WriteNavigationInitializersForConstructors(modelClass); if (lineCount > 0) NL(); Output("Init();"); } protected void WriteEnum(ModelEnum modelEnum) { Output("using System;"); NL(); BeginNamespace(modelEnum.EffectiveNamespace); if (!string.IsNullOrEmpty(modelEnum.Summary)) { Output("/// <summary>"); WriteCommentBody(modelEnum.Summary); Output("/// </summary>"); } if (!string.IsNullOrEmpty(modelEnum.Description)) { Output("/// <remarks>"); WriteCommentBody(modelEnum.Description); Output("/// </remarks>"); } if (modelEnum.IsFlags) Output("[Flags]"); if (!string.IsNullOrWhiteSpace(modelEnum.CustomAttributes)) Output($"[{modelEnum.CustomAttributes.Trim('[', ']')}]"); if (!string.IsNullOrWhiteSpace(modelEnum.Summary)) Output($"[System.ComponentModel.Description(\"{modelEnum.Summary.Replace("\"", "\\\"")}\")]"); Output($"public enum {modelEnum.Name} : {modelEnum.ValueType}"); Output("{"); ModelEnumValue[] values = modelEnum.Values.ToArray(); for (int index = 0; index < values.Length; ++index) { if (!string.IsNullOrEmpty(values[index].Summary)) { Output("/// <summary>"); WriteCommentBody(values[index].Summary); Output("/// </summary>"); } if (!string.IsNullOrEmpty(values[index].Description)) { Output("/// <remarks>"); WriteCommentBody(values[index].Description); Output("/// </remarks>"); } if (!string.IsNullOrWhiteSpace(values[index].CustomAttributes)) Output($"[{values[index].CustomAttributes.Trim('[', ']')}]"); if (!string.IsNullOrWhiteSpace(values[index].Summary)) Output($"[System.ComponentModel.Description(\"{values[index].Summary.Replace("\"", "\\\"")}\")]"); if (!string.IsNullOrWhiteSpace(values[index].DisplayText)) Output($"[System.ComponentModel.DataAnnotations.Display(Name=\"{values[index].DisplayText.Replace("\"", "\\\"")}\")]"); Output(string.IsNullOrEmpty(values[index].Value) ? $"{values[index].Name}{(index < values.Length - 1 ? "," : string.Empty)}" : $"{values[index].Name} = {values[index].Value}{(index < values.Length - 1 ? "," : string.Empty)}"); } Output("}"); EndNamespace(modelEnum.EffectiveNamespace); } [SuppressMessage("ReSharper", "ConvertIfStatementToConditionalTernaryExpression")] protected void WriteNavigationProperties(ModelClass modelClass) { if (!modelClass.LocalNavigationProperties().Any(x => x.AssociationObject.Persistent)) return; Output("/*************************************************************************"); Output(" * Navigation properties"); Output(" *************************************************************************/"); NL(); foreach (NavigationProperty navigationProperty in modelClass.LocalNavigationProperties().Where(x => !x.ConstructorParameterOnly)) { string type = navigationProperty.IsCollection ? $"ICollection<{navigationProperty.ClassType.FullName}>" : navigationProperty.ClassType.FullName; if (!navigationProperty.IsAutoProperty) { Output("/// <summary>"); Output($"/// Backing field for {navigationProperty.PropertyName}"); Output("/// </summary>"); Output($"protected {type} {navigationProperty.BackingFieldName};"); NL(); if (!navigationProperty.IsCollection) { Output("/// <summary>"); Output($"/// When provided in a partial class, allows value of {navigationProperty.PropertyName} to be changed before setting."); Output("/// </summary>"); Output($"partial void Set{navigationProperty.PropertyName}({type} oldValue, ref {type} newValue);"); NL(); Output("/// <summary>"); Output($"/// When provided in a partial class, allows value of {navigationProperty.PropertyName} to be changed before returning."); Output("/// </summary>"); Output($"partial void Get{navigationProperty.PropertyName}(ref {type} result);"); NL(); } } List<string> comments = new List<string>(); if (navigationProperty.Required) comments.Add("Required"); string comment = comments.Count > 0 ? string.Join(", ", comments) : string.Empty; if (!string.IsNullOrEmpty(navigationProperty.Summary) || !string.IsNullOrEmpty(comment)) { Output("/// <summary>"); if (!string.IsNullOrEmpty(comment) && !string.IsNullOrEmpty(navigationProperty.Summary)) comment += "<br/>"; if (!string.IsNullOrEmpty(comment)) WriteCommentBody(comment); if (!string.IsNullOrEmpty(navigationProperty.Summary)) WriteCommentBody(navigationProperty.Summary); Output("/// </summary>"); } if (!string.IsNullOrEmpty(navigationProperty.Description)) { Output("/// <remarks>"); WriteCommentBody(navigationProperty.Description); Output("/// </remarks>"); } if (!string.IsNullOrWhiteSpace(navigationProperty.CustomAttributes)) Output($"[{navigationProperty.CustomAttributes.Trim('[', ']')}]"); if (!string.IsNullOrWhiteSpace(navigationProperty.Summary)) Output($"[Description(\"{navigationProperty.Summary.Replace("\"", "\\\"")}\")]"); if (!string.IsNullOrWhiteSpace(navigationProperty.DisplayText)) Output($"[Display(Name=\"{navigationProperty.DisplayText.Replace("\"", "\\\"")}\")]"); if (navigationProperty.IsAutoProperty) { if (navigationProperty.IsCollection) Output($"public virtual {type} {navigationProperty.PropertyName} {{ get; private set; }}"); else Output($"public virtual {type} {navigationProperty.PropertyName} {{ get; set; }}"); } else if (navigationProperty.IsCollection) { Output($"public virtual {type} {navigationProperty.PropertyName}"); Output("{"); Output("get"); Output("{"); Output($"return {navigationProperty.BackingFieldName};"); Output("}"); Output("private set"); Output("{"); Output($"{navigationProperty.BackingFieldName} = value;"); Output("}"); Output("}"); } else { Output($"public virtual {type} {navigationProperty.PropertyName}"); Output("{"); Output("get"); Output("{"); Output($"{type} value = {navigationProperty.BackingFieldName};"); Output($"Get{navigationProperty.PropertyName}(ref value);"); Output($"return ({navigationProperty.BackingFieldName} = value);"); Output("}"); Output("set"); Output("{"); Output($"{type} oldValue = {navigationProperty.BackingFieldName};"); Output($"Set{navigationProperty.PropertyName}(oldValue, ref value);"); Output("if (oldValue != value)"); Output("{"); Output($"{navigationProperty.BackingFieldName} = value;"); if (navigationProperty.ImplementNotify) Output("OnPropertyChanged();"); Output("}"); Output("}"); Output("}"); } NL(); } } protected void WriteProperties(ModelClass modelClass) { Output("/*************************************************************************"); Output(" * Properties"); Output(" *************************************************************************/"); NL(); List<string> segments = new List<string>(); foreach (ModelAttribute modelAttribute in modelClass.Attributes) { segments.Clear(); if (modelAttribute.IsIdentity) segments.Add("Identity"); if (modelAttribute.Indexed) segments.Add("Indexed"); if (modelAttribute.Required || modelAttribute.IsIdentity) segments.Add("Required"); if (modelAttribute.MinLength > 0) segments.Add($"Min length = {modelAttribute.MinLength}"); if (modelAttribute.MaxLength > 0) segments.Add($"Max length = {modelAttribute.MaxLength}"); if (!string.IsNullOrEmpty(modelAttribute.InitialValue)) { string quote = modelAttribute.PrimitiveType == "string" ? "\"" : modelAttribute.PrimitiveType == "char" ? "'" : string.Empty; string initialValue = modelAttribute.InitialValue; if (modelAttribute.Type == "decimal") initialValue += "m"; segments.Add($"Default value = {quote}{FullyQualified(initialValue.Trim('"'))}{quote}"); } string nullable = IsNullable(modelAttribute) ? "?" : string.Empty; if (!modelAttribute.IsConcurrencyToken && !modelAttribute.AutoProperty) { string visibility = modelAttribute.Indexed ? "internal" : "protected"; Output("/// <summary>"); Output($"/// Backing field for {modelAttribute.Name}"); Output("/// </summary>"); Output($"{visibility} {modelAttribute.FQPrimitiveType}{nullable} {modelAttribute.BackingFieldName};"); Output("/// <summary>"); Output($"/// When provided in a partial class, allows value of {modelAttribute.Name} to be changed before setting."); Output("/// </summary>"); Output($"partial void Set{modelAttribute.Name}({modelAttribute.FQPrimitiveType}{nullable} oldValue, ref {modelAttribute.FQPrimitiveType}{nullable} newValue);"); Output("/// <summary>"); Output($"/// When provided in a partial class, allows value of {modelAttribute.Name} to be changed before returning."); Output("/// </summary>"); Output($"partial void Get{modelAttribute.Name}(ref {modelAttribute.FQPrimitiveType}{nullable} result);"); NL(); } if (!string.IsNullOrEmpty(modelAttribute.Summary) || segments.Any()) { Output("/// <summary>"); if (segments.Any()) WriteCommentBody($"{string.Join(", ", segments)}"); if (!string.IsNullOrEmpty(modelAttribute.Summary)) WriteCommentBody(modelAttribute.Summary); Output("/// </summary>"); } if (!string.IsNullOrEmpty(modelAttribute.Description)) { Output("/// <remarks>"); WriteCommentBody(modelAttribute.Description); Output("/// </remarks>"); } string setterVisibility = modelAttribute.SetterVisibility == SetterAccessModifier.Protected ? "protected " : modelAttribute.SetterVisibility == SetterAccessModifier.Internal ? "internal " : string.Empty; GeneratePropertyAnnotations(modelAttribute); if (!string.IsNullOrWhiteSpace(modelAttribute.CustomAttributes)) Output($"[{modelAttribute.CustomAttributes.Trim('[', ']')}]"); if (modelAttribute.IsAbstract) Output($"public abstract {modelAttribute.FQPrimitiveType}{nullable} {modelAttribute.Name} {{ get; {setterVisibility}set; }}"); else if (modelAttribute.IsConcurrencyToken || modelAttribute.AutoProperty) Output($"public {modelAttribute.FQPrimitiveType}{nullable} {modelAttribute.Name} {{ get; {setterVisibility}set; }}"); else { Output($"public {modelAttribute.FQPrimitiveType}{nullable} {modelAttribute.Name}"); Output("{"); Output("get"); Output("{"); Output($"{modelAttribute.FQPrimitiveType}{nullable} value = {modelAttribute.BackingFieldName};"); Output($"Get{modelAttribute.Name}(ref value);"); Output($"return ({modelAttribute.BackingFieldName} = value);"); Output("}"); Output($"{setterVisibility}set"); Output("{"); Output($"{modelAttribute.FQPrimitiveType}{nullable} oldValue = {modelAttribute.BackingFieldName};"); Output($"Set{modelAttribute.Name}(oldValue, ref value);"); Output("if (oldValue != value)"); Output("{"); Output($"{modelAttribute.BackingFieldName} = value;"); if (modelAttribute.ImplementNotify) Output("OnPropertyChanged();"); Output("}"); Output("}"); Output("}"); } NL(); } if (!modelClass.AllAttributes.Any(x => x.IsConcurrencyToken) && (modelClass.Concurrency == ConcurrencyOverride.Optimistic || modelRoot.ConcurrencyDefault == Concurrency.Optimistic)) { Output("/// <summary>"); Output("/// Concurrency token"); Output("/// </summary>"); Output("[Timestamp]"); Output("public Byte[] Timestamp { get; set; }"); NL(); } } } #endregion Template } }
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Text; using Orleans.CodeGeneration; namespace Orleans.Runtime { /// <summary> /// A collection of utility functions for dealing with Type information. /// </summary> internal static class TypeUtils { /// <summary> /// The assembly name of the core Orleans assembly. /// </summary> private static readonly AssemblyName OrleansCoreAssembly = typeof(IGrain).GetTypeInfo().Assembly.GetName(); private static readonly ConcurrentDictionary<Tuple<Type, TypeFormattingOptions>, string> ParseableNameCache = new ConcurrentDictionary<Tuple<Type, TypeFormattingOptions>, string>(); private static readonly ConcurrentDictionary<Tuple<Type, bool>, List<Type>> ReferencedTypes = new ConcurrentDictionary<Tuple<Type, bool>, List<Type>>(); public static string GetSimpleTypeName(Type t, Predicate<Type> fullName = null) { return GetSimpleTypeName(t.GetTypeInfo(), fullName); } public static string GetSimpleTypeName(TypeInfo typeInfo, Predicate<Type> fullName = null) { if (typeInfo.IsNestedPublic || typeInfo.IsNestedPrivate) { if (typeInfo.DeclaringType.GetTypeInfo().IsGenericType) { return GetTemplatedName( GetUntemplatedTypeName(typeInfo.DeclaringType.Name), typeInfo.DeclaringType, typeInfo.GetGenericArguments(), _ => true) + "." + GetUntemplatedTypeName(typeInfo.Name); } return GetTemplatedName(typeInfo.DeclaringType) + "." + GetUntemplatedTypeName(typeInfo.Name); } var type = typeInfo.AsType(); if (typeInfo.IsGenericType) return GetSimpleTypeName(fullName != null && fullName(type) ? GetFullName(type) : typeInfo.Name); return fullName != null && fullName(type) ? GetFullName(type) : typeInfo.Name; } public static string GetUntemplatedTypeName(string typeName) { int i = typeName.IndexOf('`'); if (i > 0) { typeName = typeName.Substring(0, i); } i = typeName.IndexOf('<'); if (i > 0) { typeName = typeName.Substring(0, i); } return typeName; } public static string GetSimpleTypeName(string typeName) { int i = typeName.IndexOf('`'); if (i > 0) { typeName = typeName.Substring(0, i); } i = typeName.IndexOf('['); if (i > 0) { typeName = typeName.Substring(0, i); } i = typeName.IndexOf('<'); if (i > 0) { typeName = typeName.Substring(0, i); } return typeName; } public static bool IsConcreteTemplateType(Type t) { if (t.GetTypeInfo().IsGenericType) return true; return t.IsArray && IsConcreteTemplateType(t.GetElementType()); } public static string GetTemplatedName(Type t, Predicate<Type> fullName = null) { if (fullName == null) fullName = _ => true; // default to full type names var typeInfo = t.GetTypeInfo(); if (typeInfo.IsGenericType) return GetTemplatedName(GetSimpleTypeName(typeInfo, fullName), t, typeInfo.GetGenericArguments(), fullName); if (t.IsArray) { return GetTemplatedName(t.GetElementType(), fullName) + "[" + new string(',', t.GetArrayRank() - 1) + "]"; } return GetSimpleTypeName(typeInfo, fullName); } public static bool IsConstructedGenericType(this TypeInfo typeInfo) { // is there an API that returns this info without converting back to type already? return typeInfo.AsType().IsConstructedGenericType; } internal static IEnumerable<TypeInfo> GetTypeInfos(this Type[] types) { return types.Select(t => t.GetTypeInfo()); } public static string GetTemplatedName(string baseName, Type t, Type[] genericArguments, Predicate<Type> fullName) { var typeInfo = t.GetTypeInfo(); if (!typeInfo.IsGenericType || (t.DeclaringType != null && t.DeclaringType.GetTypeInfo().IsGenericType)) return baseName; string s = baseName; s += "<"; s += GetGenericTypeArgs(genericArguments, fullName); s += ">"; return s; } public static string GetGenericTypeArgs(IEnumerable<Type> args, Predicate<Type> fullName) { string s = string.Empty; bool first = true; foreach (var genericParameter in args) { if (!first) { s += ","; } if (!genericParameter.GetTypeInfo().IsGenericType) { s += GetSimpleTypeName(genericParameter, fullName); } else { s += GetTemplatedName(genericParameter, fullName); } first = false; } return s; } public static string GetParameterizedTemplateName(TypeInfo typeInfo, bool applyRecursively = false, Predicate<Type> fullName = null) { if (fullName == null) fullName = tt => true; return GetParameterizedTemplateName(typeInfo, fullName, applyRecursively); } public static string GetParameterizedTemplateName(TypeInfo typeInfo, Predicate<Type> fullName, bool applyRecursively = false) { if (typeInfo.IsGenericType) { return GetParameterizedTemplateName(GetSimpleTypeName(typeInfo, fullName), typeInfo, applyRecursively, fullName); } var t = typeInfo.AsType(); if (fullName != null && fullName(t) == true) { return t.FullName; } return t.Name; } public static string GetParameterizedTemplateName(string baseName, TypeInfo typeInfo, bool applyRecursively = false, Predicate<Type> fullName = null) { if (fullName == null) fullName = tt => false; if (!typeInfo.IsGenericType) return baseName; string s = baseName; s += "<"; bool first = true; foreach (var genericParameter in typeInfo.GetGenericArguments()) { if (!first) { s += ","; } var genericParameterTypeInfo = genericParameter.GetTypeInfo(); if (applyRecursively && genericParameterTypeInfo.IsGenericType) { s += GetParameterizedTemplateName(genericParameterTypeInfo, applyRecursively); } else { s += genericParameter.FullName == null || !fullName(genericParameter) ? genericParameter.Name : genericParameter.FullName; } first = false; } s += ">"; return s; } public static string GetRawClassName(string baseName, Type t) { var typeInfo = t.GetTypeInfo(); return typeInfo.IsGenericType ? baseName + '`' + typeInfo.GetGenericArguments().Length : baseName; } public static string GetRawClassName(string typeName) { int i = typeName.IndexOf('['); return i <= 0 ? typeName : typeName.Substring(0, i); } public static Type[] GenericTypeArgsFromClassName(string className) { return GenericTypeArgsFromArgsString(GenericTypeArgsString(className)); } public static Type[] GenericTypeArgsFromArgsString(string genericArgs) { if (string.IsNullOrEmpty(genericArgs)) return Type.EmptyTypes; var genericTypeDef = genericArgs.Replace("[]", "##"); // protect array arguments return InnerGenericTypeArgs(genericTypeDef); } private static Type[] InnerGenericTypeArgs(string className) { var typeArgs = new List<Type>(); var innerTypes = GetInnerTypes(className); foreach (var innerType in innerTypes) { if (innerType.StartsWith("[[")) // Resolve and load generic types recursively { InnerGenericTypeArgs(GenericTypeArgsString(innerType)); string genericTypeArg = className.Trim('[', ']'); typeArgs.Add(Type.GetType(genericTypeArg.Replace("##", "[]"))); } else { string nonGenericTypeArg = innerType.Trim('[', ']'); typeArgs.Add(Type.GetType(nonGenericTypeArg.Replace("##", "[]"))); } } return typeArgs.ToArray(); } private static string[] GetInnerTypes(string input) { // Iterate over strings of length 2 positionwise. var charsWithPositions = input.Zip(Enumerable.Range(0, input.Length), (c, i) => new { Ch = c, Pos = i }); var candidatesWithPositions = charsWithPositions.Zip(charsWithPositions.Skip(1), (c1, c2) => new { Str = c1.Ch.ToString() + c2.Ch, Pos = c1.Pos }); var results = new List<string>(); int startPos = -1; int endPos = -1; int endTokensNeeded = 0; string curStartToken = ""; string curEndToken = ""; var tokenPairs = new[] { new { Start = "[[", End = "]]" }, new { Start = "[", End = "]" } }; // Longer tokens need to come before shorter ones foreach (var candidate in candidatesWithPositions) { if (startPos == -1) { foreach (var token in tokenPairs) { if (candidate.Str.StartsWith(token.Start)) { curStartToken = token.Start; curEndToken = token.End; startPos = candidate.Pos; break; } } } if (curStartToken != "" && candidate.Str.StartsWith(curStartToken)) endTokensNeeded++; if (curEndToken != "" && candidate.Str.EndsWith(curEndToken)) { endPos = candidate.Pos; endTokensNeeded--; } if (endTokensNeeded == 0 && startPos != -1) { results.Add(input.Substring(startPos, endPos - startPos + 2)); startPos = -1; curStartToken = ""; } } return results.ToArray(); } public static string GenericTypeArgsString(string className) { int startIndex = className.IndexOf('['); int endIndex = className.LastIndexOf(']'); return className.Substring(startIndex + 1, endIndex - startIndex - 1); } public static bool IsGenericClass(string name) { return name.Contains("`") || name.Contains("["); } public static string GetFullName(TypeInfo typeInfo) { if (typeInfo == null) throw new ArgumentNullException(nameof(typeInfo)); return GetFullName(typeInfo.AsType()); } public static string GetFullName(Type t) { if (t == null) throw new ArgumentNullException(nameof(t)); if (t.IsNested && !t.IsGenericParameter) { return t.Namespace + "." + t.DeclaringType.Name + "." + t.Name; } if (t.IsArray) { return GetFullName(t.GetElementType()) + "[" + new string(',', t.GetArrayRank() - 1) + "]"; } return t.FullName ?? (t.IsGenericParameter ? t.Name : t.Namespace + "." + t.Name); } /// <summary> /// Returns all fields of the specified type. /// </summary> /// <param name="type">The type.</param> /// <returns>All fields of the specified type.</returns> public static IEnumerable<FieldInfo> GetAllFields(this Type type) { const BindingFlags AllFields = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly; var current = type; while ((current != typeof(object)) && (current != null)) { var fields = current.GetFields(AllFields); foreach (var field in fields) { yield return field; } current = current.GetTypeInfo().BaseType; } } /// <summary> /// Returns <see langword="true"/> if <paramref name="field"/> is marked as /// <see cref="FieldAttributes.NotSerialized"/>, <see langword="false"/> otherwise. /// </summary> /// <param name="field">The field.</param> /// <returns> /// <see langword="true"/> if <paramref name="field"/> is marked as /// <see cref="FieldAttributes.NotSerialized"/>, <see langword="false"/> otherwise. /// </returns> public static bool IsNotSerialized(this FieldInfo field) => (field.Attributes & FieldAttributes.NotSerialized) == FieldAttributes.NotSerialized; /// <summary> /// decide whether the class is derived from Grain /// </summary> public static bool IsGrainClass(Type type) { var grainType = typeof(Grain); var grainChevronType = typeof(Grain<>); #if !NETSTANDARD if (type.Assembly.ReflectionOnly) { grainType = ToReflectionOnlyType(grainType); grainChevronType = ToReflectionOnlyType(grainChevronType); } #endif if (grainType == type || grainChevronType == type) return false; if (!grainType.IsAssignableFrom(type)) return false; // exclude generated classes. return !IsGeneratedType(type); } public static bool IsConcreteGrainClass(Type type, out IEnumerable<string> complaints, bool complain) { complaints = null; if (!IsGrainClass(type)) return false; if (!type.GetTypeInfo().IsAbstract) return true; complaints = complain ? new[] { string.Format("Grain type {0} is abstract and cannot be instantiated.", type.FullName) } : null; return false; } public static bool IsConcreteGrainClass(Type type, out IEnumerable<string> complaints) { return IsConcreteGrainClass(type, out complaints, complain: true); } public static bool IsConcreteGrainClass(Type type) { IEnumerable<string> complaints; return IsConcreteGrainClass(type, out complaints, complain: false); } public static bool IsGeneratedType(Type type) { return TypeHasAttribute(type, typeof(GeneratedAttribute)); } /// <summary> /// Returns true if the provided <paramref name="type"/> is in any of the provided /// <paramref name="namespaces"/>, false otherwise. /// </summary> /// <param name="type">The type to check.</param> /// <param name="namespaces"></param> /// <returns> /// true if the provided <paramref name="type"/> is in any of the provided <paramref name="namespaces"/>, false /// otherwise. /// </returns> public static bool IsInNamespace(Type type, List<string> namespaces) { if (type.Namespace == null) { return false; } foreach (var ns in namespaces) { if (ns.Length > type.Namespace.Length) { continue; } // If the candidate namespace is a prefix of the type's namespace, return true. if (type.Namespace.StartsWith(ns, StringComparison.Ordinal) && (type.Namespace.Length == ns.Length || type.Namespace[ns.Length] == '.')) { return true; } } return false; } /// <summary> /// Returns true if <paramref name="type"/> has implementations of all serialization methods, false otherwise. /// </summary> /// <param name="type">The type.</param> /// <returns> /// true if <paramref name="type"/> has implementations of all serialization methods, false otherwise. /// </returns> public static bool HasAllSerializationMethods(Type type) { // Check if the type has any of the serialization methods. var hasCopier = false; var hasSerializer = false; var hasDeserializer = false; foreach (var method in type.GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)) { hasSerializer |= method.GetCustomAttribute<SerializerMethodAttribute>(false) != null; hasDeserializer |= method.GetCustomAttribute<DeserializerMethodAttribute>(false) != null; hasCopier |= method.GetCustomAttribute<CopierMethodAttribute>(false) != null; } var hasAllSerializationMethods = hasCopier && hasSerializer && hasDeserializer; return hasAllSerializationMethods; } public static bool IsGrainMethodInvokerType(Type type) { var generalType = typeof(IGrainMethodInvoker); #if !NETSTANDARD if (type.Assembly.ReflectionOnly) { generalType = ToReflectionOnlyType(generalType); } #endif return generalType.IsAssignableFrom(type) && TypeHasAttribute(type, typeof(MethodInvokerAttribute)); } public static Type ResolveType(string fullName) { return CachedTypeResolver.Instance.ResolveType(fullName); } public static bool TryResolveType(string fullName, out Type type) { return CachedTypeResolver.Instance.TryResolveType(fullName, out type); } #if !NETSTANDARD public static Type ResolveReflectionOnlyType(string assemblyQualifiedName) { return CachedReflectionOnlyTypeResolver.Instance.ResolveType(assemblyQualifiedName); } public static Type ToReflectionOnlyType(Type type) { return type.Assembly.ReflectionOnly ? type : ResolveReflectionOnlyType(type.AssemblyQualifiedName); } #endif public static IEnumerable<Type> GetTypes(Assembly assembly, Predicate<Type> whereFunc, Logger logger) { return assembly.IsDynamic ? Enumerable.Empty<Type>() : GetDefinedTypes(assembly, logger).Select(t => t.AsType()).Where(type => !type.GetTypeInfo().IsNestedPrivate && whereFunc(type)); } public static IEnumerable<TypeInfo> GetDefinedTypes(Assembly assembly, Logger logger) { try { return assembly.DefinedTypes; } catch (Exception exception) { if (logger != null && logger.IsWarning) { var message = $"Exception loading types from assembly '{assembly.FullName}': {LogFormatter.PrintException(exception)}."; logger.Warn(ErrorCode.Loader_TypeLoadError_5, message, exception); } var typeLoadException = exception as ReflectionTypeLoadException; if (typeLoadException != null) { return typeLoadException.Types?.Where(type => type != null).Select(type => type.GetTypeInfo()) ?? Enumerable.Empty<TypeInfo>(); } return Enumerable.Empty<TypeInfo>(); } } public static IEnumerable<Type> GetTypes(Predicate<Type> whereFunc, Logger logger) { var assemblies = AppDomain.CurrentDomain.GetAssemblies(); var result = new List<Type>(); foreach (var assembly in assemblies) { // there's no point in evaluating nested private types-- one of them fails to coerce to a reflection-only type anyhow. var types = GetTypes(assembly, whereFunc, logger); result.AddRange(types); } return result; } public static IEnumerable<Type> GetTypes(List<string> assemblies, Predicate<Type> whereFunc, Logger logger) { var currentAssemblies = AppDomain.CurrentDomain.GetAssemblies(); var result = new List<Type>(); foreach (var assembly in currentAssemblies.Where(loaded => !loaded.IsDynamic && assemblies.Contains(loaded.Location))) { // there's no point in evaluating nested private types-- one of them fails to coerce to a reflection-only type anyhow. var types = GetTypes(assembly, whereFunc, logger); result.AddRange(types); } return result; } /// <summary> /// Returns a value indicating whether or not the provided <paramref name="methodInfo"/> is a grain method. /// </summary> /// <param name="methodInfo">The method.</param> /// <returns>A value indicating whether or not the provided <paramref name="methodInfo"/> is a grain method.</returns> public static bool IsGrainMethod(MethodInfo methodInfo) { if (methodInfo == null) throw new ArgumentNullException("methodInfo", "Cannot inspect null method info"); if (methodInfo.IsStatic || methodInfo.IsSpecialName || methodInfo.DeclaringType == null) { return false; } return methodInfo.DeclaringType.GetTypeInfo().IsInterface && typeof(IAddressable).IsAssignableFrom(methodInfo.DeclaringType); } public static bool TypeHasAttribute(Type type, Type attribType) { #if !NETSTANDARD if (type.Assembly.ReflectionOnly || attribType.Assembly.ReflectionOnly) { type = ToReflectionOnlyType(type); attribType = ToReflectionOnlyType(attribType); // we can't use Type.GetCustomAttributes here because we could potentially be working with a reflection-only type. return CustomAttributeData.GetCustomAttributes(type).Any( attrib => attribType.IsAssignableFrom(attrib.AttributeType)); } #endif return TypeHasAttribute(type.GetTypeInfo(), attribType); } public static bool TypeHasAttribute(TypeInfo typeInfo, Type attribType) { return typeInfo.GetCustomAttributes(attribType, true).Any(); } /// <summary> /// Returns a sanitized version of <paramref name="type"/>s name which is suitable for use as a class name. /// </summary> /// <param name="type"> /// The grain type. /// </param> /// <returns> /// A sanitized version of <paramref name="type"/>s name which is suitable for use as a class name. /// </returns> public static string GetSuitableClassName(Type type) { return GetClassNameFromInterfaceName(type.GetUnadornedTypeName()); } /// <summary> /// Returns a class-like version of <paramref name="interfaceName"/>. /// </summary> /// <param name="interfaceName"> /// The interface name. /// </param> /// <returns> /// A class-like version of <paramref name="interfaceName"/>. /// </returns> public static string GetClassNameFromInterfaceName(string interfaceName) { string cleanName; if (interfaceName.StartsWith("i", StringComparison.OrdinalIgnoreCase)) { cleanName = interfaceName.Substring(1); } else { cleanName = interfaceName; } return cleanName; } /// <summary> /// Returns the non-generic type name without any special characters. /// </summary> /// <param name="type"> /// The type. /// </param> /// <returns> /// The non-generic type name without any special characters. /// </returns> public static string GetUnadornedTypeName(this Type type) { var index = type.Name.IndexOf('`'); // An ampersand can appear as a suffix to a by-ref type. return (index > 0 ? type.Name.Substring(0, index) : type.Name).TrimEnd('&'); } /// <summary> /// Returns the non-generic method name without any special characters. /// </summary> /// <param name="method"> /// The method. /// </param> /// <returns> /// The non-generic method name without any special characters. /// </returns> public static string GetUnadornedMethodName(this MethodInfo method) { var index = method.Name.IndexOf('`'); return index > 0 ? method.Name.Substring(0, index) : method.Name; } /// <summary>Returns a string representation of <paramref name="type"/>.</summary> /// <param name="type">The type.</param> /// <param name="options">The type formatting options.</param> /// <returns>A string representation of the <paramref name="type"/>.</returns> public static string GetParseableName(this Type type, TypeFormattingOptions options = null) { options = options ?? new TypeFormattingOptions(); return ParseableNameCache.GetOrAdd( Tuple.Create(type, options), _ => { var builder = new StringBuilder(); var typeInfo = type.GetTypeInfo(); GetParseableName( type, builder, new Queue<Type>( typeInfo.IsGenericTypeDefinition ? typeInfo.GetGenericArguments() : typeInfo.GenericTypeArguments), options); return builder.ToString(); }); } /// <summary>Returns a string representation of <paramref name="type"/>.</summary> /// <param name="type">The type.</param> /// <param name="builder">The <see cref="StringBuilder"/> to append results to.</param> /// <param name="typeArguments">The type arguments of <paramref name="type"/>.</param> /// <param name="options">The type formatting options.</param> private static void GetParseableName( Type type, StringBuilder builder, Queue<Type> typeArguments, TypeFormattingOptions options) { var typeInfo = type.GetTypeInfo(); if (typeInfo.IsArray) { builder.AppendFormat( "{0}[{1}]", typeInfo.GetElementType().GetParseableName(options), string.Concat(Enumerable.Range(0, type.GetArrayRank() - 1).Select(_ => ','))); return; } if (typeInfo.IsGenericParameter) { if (options.IncludeGenericTypeParameters) { builder.Append(type.GetUnadornedTypeName()); } return; } if (typeInfo.DeclaringType != null) { // This is not the root type. GetParseableName(typeInfo.DeclaringType, builder, typeArguments, options); builder.Append(options.NestedTypeSeparator); } else if (!string.IsNullOrWhiteSpace(type.Namespace) && options.IncludeNamespace) { // This is the root type, so include the namespace. var namespaceName = type.Namespace; if (options.NestedTypeSeparator != '.') { namespaceName = namespaceName.Replace('.', options.NestedTypeSeparator); } if (options.IncludeGlobal) { builder.AppendFormat("global::"); } builder.AppendFormat("{0}{1}", namespaceName, options.NestedTypeSeparator); } if (type.IsConstructedGenericType) { // Get the unadorned name, the generic parameters, and add them together. var unadornedTypeName = type.GetUnadornedTypeName() + options.NameSuffix; builder.Append(EscapeIdentifier(unadornedTypeName)); var generics = Enumerable.Range(0, Math.Min(typeInfo.GetGenericArguments().Count(), typeArguments.Count)) .Select(_ => typeArguments.Dequeue()) .ToList(); if (generics.Count > 0 && options.IncludeTypeParameters) { var genericParameters = string.Join( ",", generics.Select(generic => GetParseableName(generic, options))); builder.AppendFormat("<{0}>", genericParameters); } } else if (typeInfo.IsGenericTypeDefinition) { // Get the unadorned name, the generic parameters, and add them together. var unadornedTypeName = type.GetUnadornedTypeName() + options.NameSuffix; builder.Append(EscapeIdentifier(unadornedTypeName)); var generics = Enumerable.Range(0, Math.Min(type.GetGenericArguments().Count(), typeArguments.Count)) .Select(_ => typeArguments.Dequeue()) .ToList(); if (generics.Count > 0 && options.IncludeTypeParameters) { var genericParameters = string.Join( ",", generics.Select(_ => options.IncludeGenericTypeParameters ? _.ToString() : string.Empty)); builder.AppendFormat("<{0}>", genericParameters); } } else { builder.Append(EscapeIdentifier(type.GetUnadornedTypeName() + options.NameSuffix)); } } /// <summary> /// Returns the namespaces of the specified types. /// </summary> /// <param name="types"> /// The types to include. /// </param> /// <returns> /// The namespaces of the specified types. /// </returns> public static IEnumerable<string> GetNamespaces(params Type[] types) { return types.Select(type => "global::" + type.Namespace).Distinct(); } /// <summary> /// Returns the <see cref="MethodInfo"/> for the simple method call in the provided <paramref name="expression"/>. /// </summary> /// <typeparam name="T"> /// The containing type of the method. /// </typeparam> /// <typeparam name="TResult"> /// The return type of the method. /// </typeparam> /// <param name="expression"> /// The expression. /// </param> /// <returns> /// The <see cref="MethodInfo"/> for the simple method call in the provided <paramref name="expression"/>. /// </returns> public static MethodInfo Method<T, TResult>(Expression<Func<T, TResult>> expression) { var methodCall = expression.Body as MethodCallExpression; if (methodCall != null) { return methodCall.Method; } throw new ArgumentException("Expression type unsupported."); } /// <summary> /// Returns the <see cref="PropertyInfo"/> for the simple member access in the provided <paramref name="expression"/>. /// </summary> /// <typeparam name="T"> /// The containing type of the property. /// </typeparam> /// <typeparam name="TResult"> /// The return type of the property. /// </typeparam> /// <param name="expression"> /// The expression. /// </param> /// <returns> /// The <see cref="PropertyInfo"/> for the simple member access call in the provided <paramref name="expression"/>. /// </returns> public static PropertyInfo Property<T, TResult>(Expression<Func<T, TResult>> expression) { var property = expression.Body as MemberExpression; if (property != null) { return property.Member as PropertyInfo; } throw new ArgumentException("Expression type unsupported."); } /// <summary> /// Returns the <see cref="PropertyInfo"/> for the simple member access in the provided <paramref name="expression"/>. /// </summary> /// <typeparam name="TResult"> /// The return type of the property. /// </typeparam> /// <param name="expression"> /// The expression. /// </param> /// <returns> /// The <see cref="PropertyInfo"/> for the simple member access call in the provided <paramref name="expression"/>. /// </returns> public static PropertyInfo Property<TResult>(Expression<Func<TResult>> expression) { var property = expression.Body as MemberExpression; if (property != null) { return property.Member as PropertyInfo; } throw new ArgumentException("Expression type unsupported."); } /// <summary> /// Returns the <see cref="MemberInfo"/> for the simple member access in the provided <paramref name="expression"/>. /// </summary> /// <typeparam name="T"> /// The containing type of the method. /// </typeparam> /// <typeparam name="TResult"> /// The return type of the method. /// </typeparam> /// <param name="expression"> /// The expression. /// </param> /// <returns> /// The <see cref="MemberInfo"/> for the simple member access call in the provided <paramref name="expression"/>. /// </returns> public static MemberInfo Member<T, TResult>(Expression<Func<T, TResult>> expression) { var methodCall = expression.Body as MethodCallExpression; if (methodCall != null) { return methodCall.Method; } var property = expression.Body as MemberExpression; if (property != null) { return property.Member; } throw new ArgumentException("Expression type unsupported."); } /// <summary>Returns the <see cref="MemberInfo"/> for the simple member access in the provided <paramref name="expression"/>.</summary> /// <typeparam name="TResult">The return type of the method.</typeparam> /// <param name="expression">The expression.</param> /// <returns>The <see cref="MemberInfo"/> for the simple member access call in the provided <paramref name="expression"/>.</returns> public static MemberInfo Member<TResult>(Expression<Func<TResult>> expression) { var methodCall = expression.Body as MethodCallExpression; if (methodCall != null) { return methodCall.Method; } var property = expression.Body as MemberExpression; if (property != null) { return property.Member; } throw new ArgumentException("Expression type unsupported."); } /// <summary>Returns the <see cref="MethodInfo"/> for the simple method call in the provided <paramref name="expression"/>.</summary> /// <typeparam name="T">The containing type of the method.</typeparam> /// <param name="expression">The expression.</param> /// <returns>The <see cref="MethodInfo"/> for the simple method call in the provided <paramref name="expression"/>.</returns> public static MethodInfo Method<T>(Expression<Func<T>> expression) { var methodCall = expression.Body as MethodCallExpression; if (methodCall != null) { return methodCall.Method; } throw new ArgumentException("Expression type unsupported."); } /// <summary>Returns the <see cref="MethodInfo"/> for the simple method call in the provided <paramref name="expression"/>. /// </summary> /// <typeparam name="T">The containing type of the method.</typeparam> /// <param name="expression">The expression.</param> /// <returns>The <see cref="MethodInfo"/> for the simple method call in the provided <paramref name="expression"/>.</returns> public static MethodInfo Method<T>(Expression<Action<T>> expression) { var methodCall = expression.Body as MethodCallExpression; if (methodCall != null) { return methodCall.Method; } throw new ArgumentException("Expression type unsupported."); } /// <summary> /// Returns the <see cref="MethodInfo"/> for the simple method call in the provided <paramref name="expression"/>. /// </summary> /// <param name="expression"> /// The expression. /// </param> /// <returns> /// The <see cref="MethodInfo"/> for the simple method call in the provided <paramref name="expression"/>. /// </returns> public static MethodInfo Method(Expression<Action> expression) { var methodCall = expression.Body as MethodCallExpression; if (methodCall != null) { return methodCall.Method; } throw new ArgumentException("Expression type unsupported."); } /// <summary>Returns the namespace of the provided type, or <see cref="string.Empty"/> if the type has no namespace.</summary> /// <param name="type">The type.</param> /// <returns>The namespace of the provided type, or <see cref="string.Empty"/> if the type has no namespace.</returns> public static string GetNamespaceOrEmpty(this Type type) { if (type == null || string.IsNullOrEmpty(type.Namespace)) { return string.Empty; } return type.Namespace; } /// <summary>Returns the types referenced by the provided <paramref name="type"/>.</summary> /// <param name="type">The type.</param> /// <param name="includeMethods">Whether or not to include the types referenced in the methods of this type.</param> /// <returns>The types referenced by the provided <paramref name="type"/>.</returns> public static IList<Type> GetTypes(this Type type, bool includeMethods = false) { List<Type> results; var key = Tuple.Create(type, includeMethods); if (!ReferencedTypes.TryGetValue(key, out results)) { results = GetTypes(type, includeMethods, null).ToList(); ReferencedTypes.TryAdd(key, results); } return results; } /// <summary> /// Get a public or non-public constructor that matches the constructor arguments signature /// </summary> /// <param name="type">The type to use.</param> /// <param name="constructorArguments">The constructor argument types to match for the signature.</param> /// <returns>A constructor that matches the signature or <see langword="null"/>.</returns> public static ConstructorInfo GetConstructorThatMatches(Type type, Type[] constructorArguments) { #if NETSTANDARD var candidates = type.GetTypeInfo().GetConstructors(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); foreach (ConstructorInfo candidate in candidates) { if (ConstructorMatches(candidate, constructorArguments)) { return candidate; } } return null; #else var constructorInfo = type.GetConstructor( BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, constructorArguments, null); return constructorInfo; #endif } private static bool ConstructorMatches(ConstructorInfo candidate, Type[] constructorArguments) { ParameterInfo[] parameters = candidate.GetParameters(); if (parameters.Length == constructorArguments.Length) { for (int i = 0; i < constructorArguments.Length; i++) { if (parameters[i].ParameterType != constructorArguments[i]) { return false; } } return true; } return false; } /// <summary> /// Returns a value indicating whether or not the provided assembly is the Orleans assembly or references it. /// </summary> /// <param name="assembly">The assembly.</param> /// <returns>A value indicating whether or not the provided assembly is the Orleans assembly or references it.</returns> internal static bool IsOrleansOrReferencesOrleans(Assembly assembly) { // We want to be loosely coupled to the assembly version if an assembly depends on an older Orleans, // but we want a strong assembly match for the Orleans binary itself // (so we don't load 2 different versions of Orleans by mistake) return DoReferencesContain(assembly.GetReferencedAssemblies(), OrleansCoreAssembly) || string.Equals(assembly.GetName().FullName, OrleansCoreAssembly.FullName, StringComparison.Ordinal); } /// <summary> /// Returns a value indicating whether or not the specified references contain the provided assembly name. /// </summary> /// <param name="references">The references.</param> /// <param name="assemblyName">The assembly name.</param> /// <returns>A value indicating whether or not the specified references contain the provided assembly name.</returns> private static bool DoReferencesContain(IReadOnlyCollection<AssemblyName> references, AssemblyName assemblyName) { if (references.Count == 0) { return false; } return references.Any(asm => string.Equals(asm.Name, assemblyName.Name, StringComparison.Ordinal)); } /// <summary>Returns the types referenced by the provided <paramref name="type"/>.</summary> /// <param name="type">The type.</param> /// <param name="includeMethods">Whether or not to include the types referenced in the methods of this type.</param> /// <param name="exclude">Types to exclude</param> /// <returns>The types referenced by the provided <paramref name="type"/>.</returns> private static IEnumerable<Type> GetTypes( this Type type, bool includeMethods, HashSet<Type> exclude) { exclude = exclude ?? new HashSet<Type>(); if (!exclude.Add(type)) { yield break; } yield return type; if (type.IsArray) { foreach (var elementType in type.GetElementType().GetTypes(false, exclude: exclude)) { yield return elementType; } } if (type.IsConstructedGenericType) { foreach (var genericTypeArgument in type.GetGenericArguments().SelectMany(_ => GetTypes(_, false, exclude: exclude))) { yield return genericTypeArgument; } } if (!includeMethods) { yield break; } foreach (var method in type.GetMethods()) { foreach (var referencedType in GetTypes(method.ReturnType, false, exclude: exclude)) { yield return referencedType; } foreach (var parameter in method.GetParameters()) { foreach (var referencedType in GetTypes(parameter.ParameterType, false, exclude: exclude)) { yield return referencedType; } } } } private static string EscapeIdentifier(string identifier) { switch (identifier) { case "abstract": case "add": case "base": case "bool": case "break": case "byte": case "case": case "catch": case "char": case "checked": case "class": case "const": case "continue": case "decimal": case "default": case "delegate": case "do": case "double": case "else": case "enum": case "event": case "explicit": case "extern": case "false": case "finally": case "fixed": case "float": case "for": case "foreach": case "get": case "goto": case "if": case "implicit": case "in": case "int": case "interface": case "internal": case "lock": case "long": case "namespace": case "new": case "null": case "object": case "operator": case "out": case "override": case "params": case "partial": case "private": case "protected": case "public": case "readonly": case "ref": case "remove": case "return": case "sbyte": case "sealed": case "set": case "short": case "sizeof": case "static": case "string": case "struct": case "switch": case "this": case "throw": case "true": case "try": case "typeof": case "uint": case "ulong": case "unsafe": case "ushort": case "using": case "virtual": case "where": case "while": return "@" + identifier; default: return identifier; } } } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: supply/rpc/incidental_item_svc.proto #pragma warning disable 1591 #region Designer generated code using System; using System.Threading; using System.Threading.Tasks; using grpc = global::Grpc.Core; namespace HOLMS.Types.Supply.RPC { public static partial class IncidentalItemSvc { static readonly string __ServiceName = "holms.types.supply.rpc.IncidentalItemSvc"; static readonly grpc::Marshaller<global::Google.Protobuf.WellKnownTypes.Empty> __Marshaller_Empty = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Protobuf.WellKnownTypes.Empty.Parser.ParseFrom); static readonly grpc::Marshaller<global::HOLMS.Types.Supply.RPC.IncidentalItemSvcAllResponse> __Marshaller_IncidentalItemSvcAllResponse = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Supply.RPC.IncidentalItemSvcAllResponse.Parser.ParseFrom); static readonly grpc::Marshaller<global::HOLMS.Types.Supply.IncidentalItems.IncidentalItemIndicator> __Marshaller_IncidentalItemIndicator = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Supply.IncidentalItems.IncidentalItemIndicator.Parser.ParseFrom); static readonly grpc::Marshaller<global::HOLMS.Types.Supply.IncidentalItems.IncidentalItem> __Marshaller_IncidentalItem = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Supply.IncidentalItems.IncidentalItem.Parser.ParseFrom); static readonly grpc::Marshaller<global::HOLMS.Types.Primitive.ServerActionConfirmation> __Marshaller_ServerActionConfirmation = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::HOLMS.Types.Primitive.ServerActionConfirmation.Parser.ParseFrom); static readonly grpc::Method<global::Google.Protobuf.WellKnownTypes.Empty, global::HOLMS.Types.Supply.RPC.IncidentalItemSvcAllResponse> __Method_All = new grpc::Method<global::Google.Protobuf.WellKnownTypes.Empty, global::HOLMS.Types.Supply.RPC.IncidentalItemSvcAllResponse>( grpc::MethodType.Unary, __ServiceName, "All", __Marshaller_Empty, __Marshaller_IncidentalItemSvcAllResponse); static readonly grpc::Method<global::HOLMS.Types.Supply.IncidentalItems.IncidentalItemIndicator, global::HOLMS.Types.Supply.IncidentalItems.IncidentalItem> __Method_GetById = new grpc::Method<global::HOLMS.Types.Supply.IncidentalItems.IncidentalItemIndicator, global::HOLMS.Types.Supply.IncidentalItems.IncidentalItem>( grpc::MethodType.Unary, __ServiceName, "GetById", __Marshaller_IncidentalItemIndicator, __Marshaller_IncidentalItem); static readonly grpc::Method<global::HOLMS.Types.Supply.IncidentalItems.IncidentalItem, global::HOLMS.Types.Supply.IncidentalItems.IncidentalItem> __Method_Create = new grpc::Method<global::HOLMS.Types.Supply.IncidentalItems.IncidentalItem, global::HOLMS.Types.Supply.IncidentalItems.IncidentalItem>( grpc::MethodType.Unary, __ServiceName, "Create", __Marshaller_IncidentalItem, __Marshaller_IncidentalItem); static readonly grpc::Method<global::HOLMS.Types.Supply.IncidentalItems.IncidentalItem, global::HOLMS.Types.Supply.IncidentalItems.IncidentalItem> __Method_Update = new grpc::Method<global::HOLMS.Types.Supply.IncidentalItems.IncidentalItem, global::HOLMS.Types.Supply.IncidentalItems.IncidentalItem>( grpc::MethodType.Unary, __ServiceName, "Update", __Marshaller_IncidentalItem, __Marshaller_IncidentalItem); static readonly grpc::Method<global::HOLMS.Types.Supply.IncidentalItems.IncidentalItem, global::HOLMS.Types.Primitive.ServerActionConfirmation> __Method_Delete = new grpc::Method<global::HOLMS.Types.Supply.IncidentalItems.IncidentalItem, global::HOLMS.Types.Primitive.ServerActionConfirmation>( grpc::MethodType.Unary, __ServiceName, "Delete", __Marshaller_IncidentalItem, __Marshaller_ServerActionConfirmation); /// <summary>Service descriptor</summary> public static global::Google.Protobuf.Reflection.ServiceDescriptor Descriptor { get { return global::HOLMS.Types.Supply.RPC.IncidentalItemSvcReflection.Descriptor.Services[0]; } } /// <summary>Base class for server-side implementations of IncidentalItemSvc</summary> public abstract partial class IncidentalItemSvcBase { public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.Supply.RPC.IncidentalItemSvcAllResponse> All(global::Google.Protobuf.WellKnownTypes.Empty request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.Supply.IncidentalItems.IncidentalItem> GetById(global::HOLMS.Types.Supply.IncidentalItems.IncidentalItemIndicator request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.Supply.IncidentalItems.IncidentalItem> Create(global::HOLMS.Types.Supply.IncidentalItems.IncidentalItem request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.Supply.IncidentalItems.IncidentalItem> Update(global::HOLMS.Types.Supply.IncidentalItems.IncidentalItem request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } public virtual global::System.Threading.Tasks.Task<global::HOLMS.Types.Primitive.ServerActionConfirmation> Delete(global::HOLMS.Types.Supply.IncidentalItems.IncidentalItem request, grpc::ServerCallContext context) { throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, "")); } } /// <summary>Client for IncidentalItemSvc</summary> public partial class IncidentalItemSvcClient : grpc::ClientBase<IncidentalItemSvcClient> { /// <summary>Creates a new client for IncidentalItemSvc</summary> /// <param name="channel">The channel to use to make remote calls.</param> public IncidentalItemSvcClient(grpc::Channel channel) : base(channel) { } /// <summary>Creates a new client for IncidentalItemSvc that uses a custom <c>CallInvoker</c>.</summary> /// <param name="callInvoker">The callInvoker to use to make remote calls.</param> public IncidentalItemSvcClient(grpc::CallInvoker callInvoker) : base(callInvoker) { } /// <summary>Protected parameterless constructor to allow creation of test doubles.</summary> protected IncidentalItemSvcClient() : base() { } /// <summary>Protected constructor to allow creation of configured clients.</summary> /// <param name="configuration">The client configuration.</param> protected IncidentalItemSvcClient(ClientBaseConfiguration configuration) : base(configuration) { } public virtual global::HOLMS.Types.Supply.RPC.IncidentalItemSvcAllResponse All(global::Google.Protobuf.WellKnownTypes.Empty request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return All(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } public virtual global::HOLMS.Types.Supply.RPC.IncidentalItemSvcAllResponse All(global::Google.Protobuf.WellKnownTypes.Empty request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_All, null, options, request); } public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Supply.RPC.IncidentalItemSvcAllResponse> AllAsync(global::Google.Protobuf.WellKnownTypes.Empty request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return AllAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Supply.RPC.IncidentalItemSvcAllResponse> AllAsync(global::Google.Protobuf.WellKnownTypes.Empty request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_All, null, options, request); } public virtual global::HOLMS.Types.Supply.IncidentalItems.IncidentalItem GetById(global::HOLMS.Types.Supply.IncidentalItems.IncidentalItemIndicator request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return GetById(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } public virtual global::HOLMS.Types.Supply.IncidentalItems.IncidentalItem GetById(global::HOLMS.Types.Supply.IncidentalItems.IncidentalItemIndicator request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_GetById, null, options, request); } public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Supply.IncidentalItems.IncidentalItem> GetByIdAsync(global::HOLMS.Types.Supply.IncidentalItems.IncidentalItemIndicator request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return GetByIdAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Supply.IncidentalItems.IncidentalItem> GetByIdAsync(global::HOLMS.Types.Supply.IncidentalItems.IncidentalItemIndicator request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_GetById, null, options, request); } public virtual global::HOLMS.Types.Supply.IncidentalItems.IncidentalItem Create(global::HOLMS.Types.Supply.IncidentalItems.IncidentalItem request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return Create(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } public virtual global::HOLMS.Types.Supply.IncidentalItems.IncidentalItem Create(global::HOLMS.Types.Supply.IncidentalItems.IncidentalItem request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_Create, null, options, request); } public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Supply.IncidentalItems.IncidentalItem> CreateAsync(global::HOLMS.Types.Supply.IncidentalItems.IncidentalItem request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return CreateAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Supply.IncidentalItems.IncidentalItem> CreateAsync(global::HOLMS.Types.Supply.IncidentalItems.IncidentalItem request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_Create, null, options, request); } public virtual global::HOLMS.Types.Supply.IncidentalItems.IncidentalItem Update(global::HOLMS.Types.Supply.IncidentalItems.IncidentalItem request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return Update(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } public virtual global::HOLMS.Types.Supply.IncidentalItems.IncidentalItem Update(global::HOLMS.Types.Supply.IncidentalItems.IncidentalItem request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_Update, null, options, request); } public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Supply.IncidentalItems.IncidentalItem> UpdateAsync(global::HOLMS.Types.Supply.IncidentalItems.IncidentalItem request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return UpdateAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Supply.IncidentalItems.IncidentalItem> UpdateAsync(global::HOLMS.Types.Supply.IncidentalItems.IncidentalItem request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_Update, null, options, request); } public virtual global::HOLMS.Types.Primitive.ServerActionConfirmation Delete(global::HOLMS.Types.Supply.IncidentalItems.IncidentalItem request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return Delete(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } public virtual global::HOLMS.Types.Primitive.ServerActionConfirmation Delete(global::HOLMS.Types.Supply.IncidentalItems.IncidentalItem request, grpc::CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_Delete, null, options, request); } public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Primitive.ServerActionConfirmation> DeleteAsync(global::HOLMS.Types.Supply.IncidentalItems.IncidentalItem request, grpc::Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return DeleteAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken)); } public virtual grpc::AsyncUnaryCall<global::HOLMS.Types.Primitive.ServerActionConfirmation> DeleteAsync(global::HOLMS.Types.Supply.IncidentalItems.IncidentalItem request, grpc::CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_Delete, null, options, request); } /// <summary>Creates a new instance of client from given <c>ClientBaseConfiguration</c>.</summary> protected override IncidentalItemSvcClient NewInstance(ClientBaseConfiguration configuration) { return new IncidentalItemSvcClient(configuration); } } /// <summary>Creates service definition that can be registered with a server</summary> /// <param name="serviceImpl">An object implementing the server-side handling logic.</param> public static grpc::ServerServiceDefinition BindService(IncidentalItemSvcBase serviceImpl) { return grpc::ServerServiceDefinition.CreateBuilder() .AddMethod(__Method_All, serviceImpl.All) .AddMethod(__Method_GetById, serviceImpl.GetById) .AddMethod(__Method_Create, serviceImpl.Create) .AddMethod(__Method_Update, serviceImpl.Update) .AddMethod(__Method_Delete, serviceImpl.Delete).Build(); } } } #endregion
using System; using System.Globalization; using System.Runtime.InteropServices; namespace Vanara.PInvoke { /// <summary> /// An LCID is a 4-byte value. The value supplied in an LCID is a standard numeric substitution for the international [RFC5646] string. /// </summary> /// <seealso cref="System.IComparable{T}"/> /// <seealso cref="System.IConvertible"/> /// <seealso cref="System.IEquatable{T}"/> /// <seealso cref="System.IEquatable{T}"/> /// <seealso cref="System.IComparable"/> /// <seealso cref="System.IComparable{T}"/> /// <seealso cref="System.IEquatable{T}"/> [StructLayout(LayoutKind.Sequential)] [PInvokeData("winnls.h")] public partial struct LCID : IComparable, IComparable<LCID>, IConvertible, IEquatable<LCID>, IEquatable<uint> { /// <summary>Sort order identifiers.</summary> public enum SORT : byte { /// <summary>sorting default</summary> SORT_DEFAULT = 0x0, /// <summary>Invariant (Mathematical Symbols)</summary> SORT_INVARIANT_MATH = 0x1, /// <summary>Japanese XJIS order</summary> SORT_JAPANESE_XJIS = 0x0, /// <summary>Japanese Unicode order (no longer supported)</summary> SORT_JAPANESE_UNICODE = 0x1, /// <summary>Japanese radical/stroke order</summary> SORT_JAPANESE_RADICALSTROKE = 0x4, /// <summary>Chinese BIG5 order</summary> SORT_CHINESE_BIG5 = 0x0, /// <summary>PRC Chinese Phonetic order</summary> SORT_CHINESE_PRCP = 0x0, /// <summary>Chinese Unicode order (no longer supported)</summary> SORT_CHINESE_UNICODE = 0x1, /// <summary>PRC Chinese Stroke Count order</summary> SORT_CHINESE_PRC = 0x2, /// <summary>Traditional Chinese Bopomofo order</summary> SORT_CHINESE_BOPOMOFO = 0x3, /// <summary>Traditional Chinese radical/stroke order.</summary> SORT_CHINESE_RADICALSTROKE = 0x4, /// <summary>Korean KSC order</summary> SORT_KOREAN_KSC = 0x0, /// <summary>Korean Unicode order (no longer supported)</summary> SORT_KOREAN_UNICODE = 0x1, /// <summary>German Phone Book order</summary> SORT_GERMAN_PHONE_BOOK = 0x1, /// <summary>Hungarian Default order</summary> SORT_HUNGARIAN_DEFAULT = 0x0, /// <summary>Hungarian Technical order</summary> SORT_HUNGARIAN_TECHNICAL = 0x1, /// <summary>Georgian Traditional order</summary> SORT_GEORGIAN_TRADITIONAL = 0x0, /// <summary>Georgian Modern order</summary> SORT_GEORGIAN_MODERN = 0x1, } internal uint _value; private const int langMask = 0x0FFFF; private const uint sortMask = 0xF0000; private const int sortShift = 16; /// <summary>Initializes a new instance of the <see cref="LCID"/> structure.</summary> /// <param name="rawValue">The raw LCID value.</param> public LCID(uint rawValue) => _value = rawValue; /// <summary>Initializes a new instance of the <see cref="LCID"/> structure.</summary> /// <param name="lgid"> /// Language identifier. This parameter is a combination of a primary language identifier and a sublanguage identifier. /// </param> /// <param name="srtid">Sort order identifier.</param> public LCID(LANGID lgid, SORT srtid) => _value = (((uint)(ushort)srtid) << sortShift) | lgid; /// <summary>Retrieves a language identifier from a locale identifier.</summary> public LANGID LANGID => (LANGID)_value; /// <summary>Retrieves a sort order identifier from a locale identifier.</summary> public SORT SORTID => (SORT)(((_value) >> sortShift) & 0xf); /// <summary>Gets the value.</summary> /// <value>The value.</value> public uint Value { get => _value; private set => _value = value; } /// <summary>Compares the current object with another object of the same type.</summary> /// <param name="other">An object to compare with this object.</param> /// <returns> /// A value that indicates the relative order of the objects being compared. The return value has the following /// meanings: Value Meaning Less than zero This object is less than the <paramref name="other"/> parameter.Zero This object is equal /// to <paramref name="other"/>. Greater than zero This object is greater than <paramref name="other"/>. /// </returns> public int CompareTo(LCID other) => _value.CompareTo(other._value); /// <summary> /// Compares the current instance with another object of the same type and returns an integer that indicates whether the current /// instance precedes, follows, or occurs in the same position in the sort order as the other object. /// </summary> /// <param name="obj">An object to compare with this instance.</param> /// <returns> /// A value that indicates the relative order of the objects being compared. The return value has these meanings: Value Meaning Less /// than zero This instance precedes <paramref name="obj"/> in the sort order. Zero This instance occurs in the same position in the /// sort order as <paramref name="obj"/> . Greater than zero This instance follows <paramref name="obj"/> in the sort order. /// </returns> public int CompareTo(object obj) => obj is IConvertible c ? _value.CompareTo(c.ToUInt32(null)) : throw new ArgumentException(@"Object cannot be converted to a UInt32 value for comparison.", nameof(obj)); /// <summary>Determines whether the specified <see cref="object"/>, is equal to this instance.</summary> /// <param name="obj">The <see cref="object"/> to compare with this instance.</param> /// <returns><c>true</c> if the specified <see cref="object"/> is equal to this instance; otherwise, <c>false</c>.</returns> public override bool Equals(object obj) => obj is IConvertible c && _value.Equals(c.ToUInt32(null)); /// <summary>Indicates whether the current object is equal to another object of the same type.</summary> /// <param name="other">An object to compare with this object.</param> /// <returns>true if the current object is equal to the <paramref name="other"/> parameter; otherwise, false.</returns> public bool Equals(LCID other) => other._value == _value; /// <summary>Indicates whether the current object is equal to another object of the same type.</summary> /// <param name="other">An object to compare with this object.</param> /// <returns>true if the current object is equal to the <paramref name="other"/> parameter; otherwise, false.</returns> public bool Equals(uint other) => other == _value; /// <summary>Returns a hash code for this instance.</summary> /// <returns>A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table.</returns> public override int GetHashCode() => _value.GetHashCode(); /// <inheritdoc/> public TypeCode GetTypeCode() => Value.GetTypeCode(); /// <summary>Returns a <see cref="string"/> that represents this instance.</summary> /// <returns>A <see cref="string"/> that represents this instance.</returns> public override string ToString() => ToString(CultureInfo.InvariantCulture); /// <inheritdoc/> public string ToString(IFormatProvider provider) => string.Format(provider, "0x{0:X8}", _value); /// <summary>Implements the operator ==.</summary> /// <param name="hrLeft">The first <see cref="LCID"/>.</param> /// <param name="hrRight">The second <see cref="LCID"/>.</param> /// <returns>The result of the operator.</returns> public static bool operator ==(LCID hrLeft, LCID hrRight) => hrLeft._value == hrRight._value; /// <summary>Implements the operator ==.</summary> /// <param name="hrLeft">The first <see cref="LCID"/>.</param> /// <param name="hrRight">The second <see cref="uint"/>.</param> /// <returns>The result of the operator.</returns> public static bool operator ==(LCID hrLeft, uint hrRight) => hrLeft._value == hrRight; /// <summary>Implements the operator !=.</summary> /// <param name="hrLeft">The first <see cref="LCID"/>.</param> /// <param name="hrRight">The second <see cref="LCID"/>.</param> /// <returns>The result of the operator.</returns> public static bool operator !=(LCID hrLeft, LCID hrRight) => !(hrLeft == hrRight); /// <summary>Implements the operator !=.</summary> /// <param name="hrLeft">The first <see cref="LCID"/>.</param> /// <param name="hrRight">The second <see cref="uint"/>.</param> /// <returns>The result of the operator.</returns> public static bool operator !=(LCID hrLeft, uint hrRight) => !(hrLeft == hrRight); /// <summary>Performs an implicit conversion from <see cref="int"/> to <see cref="LCID"/>.</summary> /// <param name="value">The value.</param> /// <returns>The result of the conversion.</returns> public static implicit operator LCID(uint value) => new(value); /// <summary>Performs an explicit conversion from <see cref="LCID"/> to <see cref="int"/>.</summary> /// <param name="value">The value.</param> /// <returns>The result of the conversion.</returns> public static explicit operator uint(LCID value) => value._value; /// <summary>The default locale for the operating system. The value of this constant is 0x0800.</summary> public static LCID LOCALE_SYSTEM_DEFAULT = new(LANGID.LANG_SYSTEM_DEFAULT, SORT.SORT_DEFAULT); /// <summary>The default locale for the user or process. The value of this constant is 0x0400.</summary> public static LCID LOCALE_USER_DEFAULT = new(LANGID.LANG_USER_DEFAULT, SORT.SORT_DEFAULT); /// <summary> /// Windows Vista and later: The default custom locale. When an NLS function must return a locale identifier for a supplemental /// locale for the current user, the function returns this value instead of LOCALE_USER_DEFAULT. The value of LOCALE_CUSTOM_DEFAULT /// is 0x0C00. /// </summary> public static LCID LOCALE_CUSTOM_DEFAULT => new(new LANGID(LANGID.LANG.LANG_NEUTRAL, LANGID.SUBLANG.SUBLANG_CUSTOM_DEFAULT), SORT.SORT_DEFAULT); /// <summary> /// Windows Vista and later: An unspecified custom locale, used to identify all supplemental locales except the locale for the /// current user. Supplemental locales cannot be distinguished from one another by their locale identifiers, but can be /// distinguished by their locale names. Certain NLS functions can return this constant to indicate that they cannot provide a /// useful identifier for a particular locale. The value of LOCALE_CUSTOM_UNSPECIFIED is 0x1000. /// </summary> public static LCID LOCALE_CUSTOM_UNSPECIFIED => new(new LANGID(LANGID.LANG.LANG_NEUTRAL, LANGID.SUBLANG.SUBLANG_CUSTOM_UNSPECIFIED), SORT.SORT_DEFAULT); /// <summary> /// Windows Vista and later: The default custom locale for MUI. The user preferred UI languages and the system preferred UI /// languages can include at most a single language that is implemented by a Language Interface Pack (LIP) and for which the /// language identifier corresponds to a supplemental locale. If there is such a language in a list, the constant is used to refer /// to that language in certain contexts. The value of LOCALE_CUSTOM_UI_DEFAULT is 0x1400. /// </summary> public static LCID LOCALE_CUSTOM_UI_DEFAULT => new(new LANGID(LANGID.LANG.LANG_NEUTRAL, LANGID.SUBLANG.SUBLANG_UI_CUSTOM_DEFAULT), SORT.SORT_DEFAULT); /// <summary> /// The neutral locale. This constant is generally not used when calling NLS APIs. Instead, use either LOCALE_SYSTEM_DEFAULT or /// LOCALE_USER_DEFAULT. The value of LOCALE_NEUTRAL is 0x0000. /// </summary> public static LCID LOCALE_NEUTRAL => new(new LANGID(LANGID.LANG.LANG_NEUTRAL, LANGID.SUBLANG.SUBLANG_NEUTRAL), SORT.SORT_DEFAULT); /// <summary> /// Windows XP: The locale used for operating system-level functions that require consistent and locale-independent results. For /// example, the invariant locale is used when an application compares character strings using the CompareString function and /// expects a consistent result regardless of the user locale. The settings of the invariant locale are similar to those for English /// (United States) but should not be used to display formatted data. Typically, an application does not use LOCALE_INVARIANT /// because it expects the results of an action to depend on the rules governing each individual locale. The value of /// LOCALE_INVARIANT IS 0x007f. /// </summary> public static LCID LOCALE_INVARIANT => new(new LANGID(LANGID.LANG.LANG_INVARIANT, LANGID.SUBLANG.SUBLANG_NEUTRAL), SORT.SORT_DEFAULT); /// <inheritdoc/> bool IConvertible.ToBoolean(IFormatProvider provider) => ((IConvertible)Value).ToBoolean(provider); /// <inheritdoc/> byte IConvertible.ToByte(IFormatProvider provider) => ((IConvertible)Value).ToByte(provider); /// <inheritdoc/> char IConvertible.ToChar(IFormatProvider provider) => ((IConvertible)Value).ToChar(provider); /// <inheritdoc/> DateTime IConvertible.ToDateTime(IFormatProvider provider) => ((IConvertible)Value).ToDateTime(provider); /// <inheritdoc/> decimal IConvertible.ToDecimal(IFormatProvider provider) => ((IConvertible)Value).ToDecimal(provider); /// <inheritdoc/> double IConvertible.ToDouble(IFormatProvider provider) => ((IConvertible)Value).ToDouble(provider); /// <inheritdoc/> short IConvertible.ToInt16(IFormatProvider provider) => ((IConvertible)Value).ToInt16(provider); /// <inheritdoc/> int IConvertible.ToInt32(IFormatProvider provider) => ((IConvertible)Value).ToInt32(provider); /// <inheritdoc/> long IConvertible.ToInt64(IFormatProvider provider) => ((IConvertible)Value).ToInt64(provider); /// <inheritdoc/> sbyte IConvertible.ToSByte(IFormatProvider provider) => ((IConvertible)Value).ToSByte(provider); /// <inheritdoc/> float IConvertible.ToSingle(IFormatProvider provider) => ((IConvertible)Value).ToSingle(provider); /// <inheritdoc/> object IConvertible.ToType(Type conversionType, IFormatProvider provider) => ((IConvertible)Value).ToBoolean(provider); /// <inheritdoc/> ushort IConvertible.ToUInt16(IFormatProvider provider) => ((IConvertible)Value).ToUInt16(provider); /// <inheritdoc/> uint IConvertible.ToUInt32(IFormatProvider provider) => ((IConvertible)Value).ToUInt32(provider); /// <inheritdoc/> ulong IConvertible.ToUInt64(IFormatProvider provider) => ((IConvertible)Value).ToUInt64(provider); } }
#region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System; using System.Collections.Generic; using System.Text; #if !(PORTABLE || PORTABLE40 || NET35 || NET20) || NETSTANDARD1_3 || NETSTANDARD2_0 using System.Numerics; #endif using Newtonsoft.Json.Linq.JsonPath; using Newtonsoft.Json.Tests.Bson; #if DNXCORE50 using Xunit; using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; using TestCaseSource = Xunit.MemberDataAttribute; #else using NUnit.Framework; #endif using Newtonsoft.Json.Linq; #if NET20 using Newtonsoft.Json.Utilities.LinqBridge; #else using System.Linq; #endif namespace Newtonsoft.Json.Tests.Linq.JsonPath { [TestFixture] public class JPathExecuteTests : TestFixtureBase { [Test] public void GreaterThanIssue1518() { string statusJson = @"{""usingmem"": ""214376""}";//214,376 JObject jObj = JObject.Parse(statusJson); var aa = jObj.SelectToken("$..[?(@.usingmem>10)]");//found,10 Assert.AreEqual(jObj, aa); var bb = jObj.SelectToken("$..[?(@.usingmem>27000)]");//null, 27,000 Assert.AreEqual(jObj, bb); var cc = jObj.SelectToken("$..[?(@.usingmem>21437)]");//found, 21,437 Assert.AreEqual(jObj, cc); var dd = jObj.SelectToken("$..[?(@.usingmem>21438)]");//null,21,438 Assert.AreEqual(jObj, dd); } [Test] public void GreaterThanWithIntegerParameterAndStringValue() { string json = @"{ ""persons"": [ { ""name"" : ""John"", ""age"": ""26"" }, { ""name"" : ""Jane"", ""age"": ""2"" } ] }"; JObject models = JObject.Parse(json); var results = models.SelectTokens("$.persons[?(@.age > 3)]").ToList(); Assert.AreEqual(1, results.Count); } [Test] public void GreaterThanWithStringParameterAndIntegerValue() { string json = @"{ ""persons"": [ { ""name"" : ""John"", ""age"": 26 }, { ""name"" : ""Jane"", ""age"": 2 } ] }"; JObject models = JObject.Parse(json); var results = models.SelectTokens("$.persons[?(@.age > '3')]").ToList(); Assert.AreEqual(1, results.Count); } [Test] public void RecursiveWildcard() { string json = @"{ ""a"": [ { ""id"": 1 } ], ""b"": [ { ""id"": 2 }, { ""id"": 3, ""c"": { ""id"": 4 } } ], ""d"": [ { ""id"": 5 } ] }"; JObject models = JObject.Parse(json); var results = models.SelectTokens("$.b..*.id").ToList(); Assert.AreEqual(3, results.Count); Assert.AreEqual(2, (int)results[0]); Assert.AreEqual(3, (int)results[1]); Assert.AreEqual(4, (int)results[2]); } [Test] public void ScanFilter() { string json = @"{ ""elements"": [ { ""id"": ""A"", ""children"": [ { ""id"": ""AA"", ""children"": [ { ""id"": ""AAA"" }, { ""id"": ""AAB"" } ] }, { ""id"": ""AB"" } ] }, { ""id"": ""B"", ""children"": [] } ] }"; JObject models = JObject.Parse(json); var results = models.SelectTokens("$.elements..[?(@.id=='AAA')]").ToList(); Assert.AreEqual(1, results.Count); Assert.AreEqual(models["elements"][0]["children"][0]["children"][0], results[0]); } [Test] public void FilterTrue() { string json = @"{ ""elements"": [ { ""id"": ""A"", ""children"": [ { ""id"": ""AA"", ""children"": [ { ""id"": ""AAA"" }, { ""id"": ""AAB"" } ] }, { ""id"": ""AB"" } ] }, { ""id"": ""B"", ""children"": [] } ] }"; JObject models = JObject.Parse(json); var results = models.SelectTokens("$.elements[?(true)]").ToList(); Assert.AreEqual(2, results.Count); Assert.AreEqual(results[0], models["elements"][0]); Assert.AreEqual(results[1], models["elements"][1]); } [Test] public void ScanFilterTrue() { string json = @"{ ""elements"": [ { ""id"": ""A"", ""children"": [ { ""id"": ""AA"", ""children"": [ { ""id"": ""AAA"" }, { ""id"": ""AAB"" } ] }, { ""id"": ""AB"" } ] }, { ""id"": ""B"", ""children"": [] } ] }"; JObject models = JObject.Parse(json); var results = models.SelectTokens("$.elements..[?(true)]").ToList(); Assert.AreEqual(25, results.Count); } [Test] public void ScanQuoted() { string json = @"{ ""Node1"": { ""Child1"": { ""Name"": ""IsMe"", ""TargetNode"": { ""Prop1"": ""Val1"", ""Prop2"": ""Val2"" } }, ""My.Child.Node"": { ""TargetNode"": { ""Prop1"": ""Val1"", ""Prop2"": ""Val2"" } } }, ""Node2"": { ""TargetNode"": { ""Prop1"": ""Val1"", ""Prop2"": ""Val2"" } } }"; JObject models = JObject.Parse(json); int result = models.SelectTokens("$..['My.Child.Node']").Count(); Assert.AreEqual(1, result); result = models.SelectTokens("..['My.Child.Node']").Count(); Assert.AreEqual(1, result); } [Test] public void ScanMultipleQuoted() { string json = @"{ ""Node1"": { ""Child1"": { ""Name"": ""IsMe"", ""TargetNode"": { ""Prop1"": ""Val1"", ""Prop2"": ""Val2"" } }, ""My.Child.Node"": { ""TargetNode"": { ""Prop1"": ""Val3"", ""Prop2"": ""Val4"" } } }, ""Node2"": { ""TargetNode"": { ""Prop1"": ""Val5"", ""Prop2"": ""Val6"" } } }"; JObject models = JObject.Parse(json); var results = models.SelectTokens("$..['My.Child.Node','Prop1','Prop2']").ToList(); Assert.AreEqual("Val1", (string)results[0]); Assert.AreEqual("Val2", (string)results[1]); Assert.AreEqual(JTokenType.Object, results[2].Type); Assert.AreEqual("Val3", (string)results[3]); Assert.AreEqual("Val4", (string)results[4]); Assert.AreEqual("Val5", (string)results[5]); Assert.AreEqual("Val6", (string)results[6]); } [Test] public void ParseWithEmptyArrayContent() { var json = @"{ 'controls': [ { 'messages': { 'addSuggestion': { 'en-US': 'Add' } } }, { 'header': { 'controls': [] }, 'controls': [ { 'controls': [ { 'defaultCaption': { 'en-US': 'Sort by' }, 'sortOptions': [ { 'label': { 'en-US': 'Name' } } ] } ] } ] } ] }"; JObject jToken = JObject.Parse(json); IList<JToken> tokens = jToken.SelectTokens("$..en-US").ToList(); Assert.AreEqual(3, tokens.Count); Assert.AreEqual("Add", (string)tokens[0]); Assert.AreEqual("Sort by", (string)tokens[1]); Assert.AreEqual("Name", (string)tokens[2]); } [Test] public void SelectTokenAfterEmptyContainer() { string json = @"{ 'cont': [], 'test': 'no one will find me' }"; JObject o = JObject.Parse(json); IList<JToken> results = o.SelectTokens("$..test").ToList(); Assert.AreEqual(1, results.Count); Assert.AreEqual("no one will find me", (string)results[0]); } [Test] public void EvaluatePropertyWithRequired() { string json = "{\"bookId\":\"1000\"}"; JObject o = JObject.Parse(json); string bookId = (string)o.SelectToken("bookId", true); Assert.AreEqual("1000", bookId); } [Test] public void EvaluateEmptyPropertyIndexer() { JObject o = new JObject( new JProperty("", 1)); JToken t = o.SelectToken("['']"); Assert.AreEqual(1, (int)t); } [Test] public void EvaluateEmptyString() { JObject o = new JObject( new JProperty("Blah", 1)); JToken t = o.SelectToken(""); Assert.AreEqual(o, t); t = o.SelectToken("['']"); Assert.AreEqual(null, t); } [Test] public void EvaluateEmptyStringWithMatchingEmptyProperty() { JObject o = new JObject( new JProperty(" ", 1)); JToken t = o.SelectToken("[' ']"); Assert.AreEqual(1, (int)t); } [Test] public void EvaluateWhitespaceString() { JObject o = new JObject( new JProperty("Blah", 1)); JToken t = o.SelectToken(" "); Assert.AreEqual(o, t); } [Test] public void EvaluateDollarString() { JObject o = new JObject( new JProperty("Blah", 1)); JToken t = o.SelectToken("$"); Assert.AreEqual(o, t); } [Test] public void EvaluateDollarTypeString() { JObject o = new JObject( new JProperty("$values", new JArray(1, 2, 3))); JToken t = o.SelectToken("$values[1]"); Assert.AreEqual(2, (int)t); } [Test] public void EvaluateSingleProperty() { JObject o = new JObject( new JProperty("Blah", 1)); JToken t = o.SelectToken("Blah"); Assert.IsNotNull(t); Assert.AreEqual(JTokenType.Integer, t.Type); Assert.AreEqual(1, (int)t); } [Test] public void EvaluateWildcardProperty() { JObject o = new JObject( new JProperty("Blah", 1), new JProperty("Blah2", 2)); IList<JToken> t = o.SelectTokens("$.*").ToList(); Assert.IsNotNull(t); Assert.AreEqual(2, t.Count); Assert.AreEqual(1, (int)t[0]); Assert.AreEqual(2, (int)t[1]); } [Test] public void QuoteName() { JObject o = new JObject( new JProperty("Blah", 1)); JToken t = o.SelectToken("['Blah']"); Assert.IsNotNull(t); Assert.AreEqual(JTokenType.Integer, t.Type); Assert.AreEqual(1, (int)t); } [Test] public void EvaluateMissingProperty() { JObject o = new JObject( new JProperty("Blah", 1)); JToken t = o.SelectToken("Missing[1]"); Assert.IsNull(t); } [Test] public void EvaluateIndexerOnObject() { JObject o = new JObject( new JProperty("Blah", 1)); JToken t = o.SelectToken("[1]"); Assert.IsNull(t); } [Test] public void EvaluateIndexerOnObjectWithError() { JObject o = new JObject( new JProperty("Blah", 1)); ExceptionAssert.Throws<JsonException>(() => { o.SelectToken("[1]", true); }, @"Index 1 not valid on JObject."); } [Test] public void EvaluateWildcardIndexOnObjectWithError() { JObject o = new JObject( new JProperty("Blah", 1)); ExceptionAssert.Throws<JsonException>(() => { o.SelectToken("[*]", true); }, @"Index * not valid on JObject."); } [Test] public void EvaluateSliceOnObjectWithError() { JObject o = new JObject( new JProperty("Blah", 1)); ExceptionAssert.Throws<JsonException>(() => { o.SelectToken("[:]", true); }, @"Array slice is not valid on JObject."); } [Test] public void EvaluatePropertyOnArray() { JArray a = new JArray(1, 2, 3, 4, 5); JToken t = a.SelectToken("BlahBlah"); Assert.IsNull(t); } [Test] public void EvaluateMultipleResultsError() { JArray a = new JArray(1, 2, 3, 4, 5); ExceptionAssert.Throws<JsonException>(() => { a.SelectToken("[0, 1]"); }, @"Path returned multiple tokens."); } [Test] public void EvaluatePropertyOnArrayWithError() { JArray a = new JArray(1, 2, 3, 4, 5); ExceptionAssert.Throws<JsonException>(() => { a.SelectToken("BlahBlah", true); }, @"Property 'BlahBlah' not valid on JArray."); } [Test] public void EvaluateNoResultsWithMultipleArrayIndexes() { JArray a = new JArray(1, 2, 3, 4, 5); ExceptionAssert.Throws<JsonException>(() => { a.SelectToken("[9,10]", true); }, @"Index 9 outside the bounds of JArray."); } [Test] public void EvaluateConstructorOutOfBoundsIndxerWithError() { JConstructor c = new JConstructor("Blah"); ExceptionAssert.Throws<JsonException>(() => { c.SelectToken("[1]", true); }, @"Index 1 outside the bounds of JConstructor."); } [Test] public void EvaluateConstructorOutOfBoundsIndxer() { JConstructor c = new JConstructor("Blah"); Assert.IsNull(c.SelectToken("[1]")); } [Test] public void EvaluateMissingPropertyWithError() { JObject o = new JObject( new JProperty("Blah", 1)); ExceptionAssert.Throws<JsonException>(() => { o.SelectToken("Missing", true); }, "Property 'Missing' does not exist on JObject."); } [Test] public void EvaluatePropertyWithoutError() { JObject o = new JObject( new JProperty("Blah", 1)); JValue v = (JValue)o.SelectToken("Blah", true); Assert.AreEqual(1, v.Value); } [Test] public void EvaluateMissingPropertyIndexWithError() { JObject o = new JObject( new JProperty("Blah", 1)); ExceptionAssert.Throws<JsonException>(() => { o.SelectToken("['Missing','Missing2']", true); }, "Property 'Missing' does not exist on JObject."); } [Test] public void EvaluateMultiPropertyIndexOnArrayWithError() { JArray a = new JArray(1, 2, 3, 4, 5); ExceptionAssert.Throws<JsonException>(() => { a.SelectToken("['Missing','Missing2']", true); }, "Properties 'Missing', 'Missing2' not valid on JArray."); } [Test] public void EvaluateArraySliceWithError() { JArray a = new JArray(1, 2, 3, 4, 5); ExceptionAssert.Throws<JsonException>(() => { a.SelectToken("[99:]", true); }, "Array slice of 99 to * returned no results."); ExceptionAssert.Throws<JsonException>(() => { a.SelectToken("[1:-19]", true); }, "Array slice of 1 to -19 returned no results."); ExceptionAssert.Throws<JsonException>(() => { a.SelectToken("[:-19]", true); }, "Array slice of * to -19 returned no results."); a = new JArray(); ExceptionAssert.Throws<JsonException>(() => { a.SelectToken("[:]", true); }, "Array slice of * to * returned no results."); } [Test] public void EvaluateOutOfBoundsIndxer() { JArray a = new JArray(1, 2, 3, 4, 5); JToken t = a.SelectToken("[1000].Ha"); Assert.IsNull(t); } [Test] public void EvaluateArrayOutOfBoundsIndxerWithError() { JArray a = new JArray(1, 2, 3, 4, 5); ExceptionAssert.Throws<JsonException>(() => { a.SelectToken("[1000].Ha", true); }, "Index 1000 outside the bounds of JArray."); } [Test] public void EvaluateArray() { JArray a = new JArray(1, 2, 3, 4); JToken t = a.SelectToken("[1]"); Assert.IsNotNull(t); Assert.AreEqual(JTokenType.Integer, t.Type); Assert.AreEqual(2, (int)t); } [Test] public void EvaluateArraySlice() { JArray a = new JArray(1, 2, 3, 4, 5, 6, 7, 8, 9); IList<JToken> t = null; t = a.SelectTokens("[-3:]").ToList(); Assert.AreEqual(3, t.Count); Assert.AreEqual(7, (int)t[0]); Assert.AreEqual(8, (int)t[1]); Assert.AreEqual(9, (int)t[2]); t = a.SelectTokens("[-1:-2:-1]").ToList(); Assert.AreEqual(1, t.Count); Assert.AreEqual(9, (int)t[0]); t = a.SelectTokens("[-2:-1]").ToList(); Assert.AreEqual(1, t.Count); Assert.AreEqual(8, (int)t[0]); t = a.SelectTokens("[1:1]").ToList(); Assert.AreEqual(0, t.Count); t = a.SelectTokens("[1:2]").ToList(); Assert.AreEqual(1, t.Count); Assert.AreEqual(2, (int)t[0]); t = a.SelectTokens("[::-1]").ToList(); Assert.AreEqual(9, t.Count); Assert.AreEqual(9, (int)t[0]); Assert.AreEqual(8, (int)t[1]); Assert.AreEqual(7, (int)t[2]); Assert.AreEqual(6, (int)t[3]); Assert.AreEqual(5, (int)t[4]); Assert.AreEqual(4, (int)t[5]); Assert.AreEqual(3, (int)t[6]); Assert.AreEqual(2, (int)t[7]); Assert.AreEqual(1, (int)t[8]); t = a.SelectTokens("[::-2]").ToList(); Assert.AreEqual(5, t.Count); Assert.AreEqual(9, (int)t[0]); Assert.AreEqual(7, (int)t[1]); Assert.AreEqual(5, (int)t[2]); Assert.AreEqual(3, (int)t[3]); Assert.AreEqual(1, (int)t[4]); } [Test] public void EvaluateWildcardArray() { JArray a = new JArray(1, 2, 3, 4); List<JToken> t = a.SelectTokens("[*]").ToList(); Assert.IsNotNull(t); Assert.AreEqual(4, t.Count); Assert.AreEqual(1, (int)t[0]); Assert.AreEqual(2, (int)t[1]); Assert.AreEqual(3, (int)t[2]); Assert.AreEqual(4, (int)t[3]); } [Test] public void EvaluateArrayMultipleIndexes() { JArray a = new JArray(1, 2, 3, 4); IEnumerable<JToken> t = a.SelectTokens("[1,2,0]"); Assert.IsNotNull(t); Assert.AreEqual(3, t.Count()); Assert.AreEqual(2, (int)t.ElementAt(0)); Assert.AreEqual(3, (int)t.ElementAt(1)); Assert.AreEqual(1, (int)t.ElementAt(2)); } [Test] public void EvaluateScan() { JObject o1 = new JObject { { "Name", 1 } }; JObject o2 = new JObject { { "Name", 2 } }; JArray a = new JArray(o1, o2); IList<JToken> t = a.SelectTokens("$..Name").ToList(); Assert.IsNotNull(t); Assert.AreEqual(2, t.Count); Assert.AreEqual(1, (int)t[0]); Assert.AreEqual(2, (int)t[1]); } [Test] public void EvaluateWildcardScan() { JObject o1 = new JObject { { "Name", 1 } }; JObject o2 = new JObject { { "Name", 2 } }; JArray a = new JArray(o1, o2); IList<JToken> t = a.SelectTokens("$..*").ToList(); Assert.IsNotNull(t); Assert.AreEqual(5, t.Count); Assert.IsTrue(JToken.DeepEquals(a, t[0])); Assert.IsTrue(JToken.DeepEquals(o1, t[1])); Assert.AreEqual(1, (int)t[2]); Assert.IsTrue(JToken.DeepEquals(o2, t[3])); Assert.AreEqual(2, (int)t[4]); } [Test] public void EvaluateScanNestResults() { JObject o1 = new JObject { { "Name", 1 } }; JObject o2 = new JObject { { "Name", 2 } }; JObject o3 = new JObject { { "Name", new JObject { { "Name", new JArray(3) } } } }; JArray a = new JArray(o1, o2, o3); IList<JToken> t = a.SelectTokens("$..Name").ToList(); Assert.IsNotNull(t); Assert.AreEqual(4, t.Count); Assert.AreEqual(1, (int)t[0]); Assert.AreEqual(2, (int)t[1]); Assert.IsTrue(JToken.DeepEquals(new JObject { { "Name", new JArray(3) } }, t[2])); Assert.IsTrue(JToken.DeepEquals(new JArray(3), t[3])); } [Test] public void EvaluateWildcardScanNestResults() { JObject o1 = new JObject { { "Name", 1 } }; JObject o2 = new JObject { { "Name", 2 } }; JObject o3 = new JObject { { "Name", new JObject { { "Name", new JArray(3) } } } }; JArray a = new JArray(o1, o2, o3); IList<JToken> t = a.SelectTokens("$..*").ToList(); Assert.IsNotNull(t); Assert.AreEqual(9, t.Count); Assert.IsTrue(JToken.DeepEquals(a, t[0])); Assert.IsTrue(JToken.DeepEquals(o1, t[1])); Assert.AreEqual(1, (int)t[2]); Assert.IsTrue(JToken.DeepEquals(o2, t[3])); Assert.AreEqual(2, (int)t[4]); Assert.IsTrue(JToken.DeepEquals(o3, t[5])); Assert.IsTrue(JToken.DeepEquals(new JObject { { "Name", new JArray(3) } }, t[6])); Assert.IsTrue(JToken.DeepEquals(new JArray(3), t[7])); Assert.AreEqual(3, (int)t[8]); } [Test] public void EvaluateSinglePropertyReturningArray() { JObject o = new JObject( new JProperty("Blah", new[] { 1, 2, 3 })); JToken t = o.SelectToken("Blah"); Assert.IsNotNull(t); Assert.AreEqual(JTokenType.Array, t.Type); t = o.SelectToken("Blah[2]"); Assert.AreEqual(JTokenType.Integer, t.Type); Assert.AreEqual(3, (int)t); } [Test] public void EvaluateLastSingleCharacterProperty() { JObject o2 = JObject.Parse("{'People':[{'N':'Jeff'}]}"); string a2 = (string)o2.SelectToken("People[0].N"); Assert.AreEqual("Jeff", a2); } [Test] public void ExistsQuery() { JArray a = new JArray(new JObject(new JProperty("hi", "ho")), new JObject(new JProperty("hi2", "ha"))); IList<JToken> t = a.SelectTokens("[ ?( @.hi ) ]").ToList(); Assert.IsNotNull(t); Assert.AreEqual(1, t.Count); Assert.IsTrue(JToken.DeepEquals(new JObject(new JProperty("hi", "ho")), t[0])); } [Test] public void EqualsQuery() { JArray a = new JArray( new JObject(new JProperty("hi", "ho")), new JObject(new JProperty("hi", "ha"))); IList<JToken> t = a.SelectTokens("[ ?( @.['hi'] == 'ha' ) ]").ToList(); Assert.IsNotNull(t); Assert.AreEqual(1, t.Count); Assert.IsTrue(JToken.DeepEquals(new JObject(new JProperty("hi", "ha")), t[0])); } [Test] public void NotEqualsQuery() { JArray a = new JArray( new JArray(new JObject(new JProperty("hi", "ho"))), new JArray(new JObject(new JProperty("hi", "ha")))); IList<JToken> t = a.SelectTokens("[ ?( @..hi <> 'ha' ) ]").ToList(); Assert.IsNotNull(t); Assert.AreEqual(1, t.Count); Assert.IsTrue(JToken.DeepEquals(new JArray(new JObject(new JProperty("hi", "ho"))), t[0])); } [Test] public void NoPathQuery() { JArray a = new JArray(1, 2, 3); IList<JToken> t = a.SelectTokens("[ ?( @ > 1 ) ]").ToList(); Assert.IsNotNull(t); Assert.AreEqual(2, t.Count); Assert.AreEqual(2, (int)t[0]); Assert.AreEqual(3, (int)t[1]); } [Test] public void MultipleQueries() { JArray a = new JArray(1, 2, 3, 4, 5, 6, 7, 8, 9); // json path does item based evaluation - http://www.sitepen.com/blog/2008/03/17/jsonpath-support/ // first query resolves array to ints // int has no children to query IList<JToken> t = a.SelectTokens("[?(@ <> 1)][?(@ <> 4)][?(@ < 7)]").ToList(); Assert.IsNotNull(t); Assert.AreEqual(0, t.Count); } [Test] public void GreaterQuery() { JArray a = new JArray( new JObject(new JProperty("hi", 1)), new JObject(new JProperty("hi", 2)), new JObject(new JProperty("hi", 3))); IList<JToken> t = a.SelectTokens("[ ?( @.hi > 1 ) ]").ToList(); Assert.IsNotNull(t); Assert.AreEqual(2, t.Count); Assert.IsTrue(JToken.DeepEquals(new JObject(new JProperty("hi", 2)), t[0])); Assert.IsTrue(JToken.DeepEquals(new JObject(new JProperty("hi", 3)), t[1])); } [Test] public void LesserQuery_ValueFirst() { JArray a = new JArray( new JObject(new JProperty("hi", 1)), new JObject(new JProperty("hi", 2)), new JObject(new JProperty("hi", 3))); IList<JToken> t = a.SelectTokens("[ ?( 1 < @.hi ) ]").ToList(); Assert.IsNotNull(t); Assert.AreEqual(2, t.Count); Assert.IsTrue(JToken.DeepEquals(new JObject(new JProperty("hi", 2)), t[0])); Assert.IsTrue(JToken.DeepEquals(new JObject(new JProperty("hi", 3)), t[1])); } #if !(PORTABLE || DNXCORE50 || PORTABLE40 || NET35 || NET20) || NETSTANDARD1_3 || NETSTANDARD2_0 [Test] public void GreaterQueryBigInteger() { JArray a = new JArray( new JObject(new JProperty("hi", new BigInteger(1))), new JObject(new JProperty("hi", new BigInteger(2))), new JObject(new JProperty("hi", new BigInteger(3)))); IList<JToken> t = a.SelectTokens("[ ?( @.hi > 1 ) ]").ToList(); Assert.IsNotNull(t); Assert.AreEqual(2, t.Count); Assert.IsTrue(JToken.DeepEquals(new JObject(new JProperty("hi", 2)), t[0])); Assert.IsTrue(JToken.DeepEquals(new JObject(new JProperty("hi", 3)), t[1])); } #endif [Test] public void GreaterOrEqualQuery() { JArray a = new JArray( new JObject(new JProperty("hi", 1)), new JObject(new JProperty("hi", 2)), new JObject(new JProperty("hi", 2.0)), new JObject(new JProperty("hi", 3))); IList<JToken> t = a.SelectTokens("[ ?( @.hi >= 1 ) ]").ToList(); Assert.IsNotNull(t); Assert.AreEqual(4, t.Count); Assert.IsTrue(JToken.DeepEquals(new JObject(new JProperty("hi", 1)), t[0])); Assert.IsTrue(JToken.DeepEquals(new JObject(new JProperty("hi", 2)), t[1])); Assert.IsTrue(JToken.DeepEquals(new JObject(new JProperty("hi", 2.0)), t[2])); Assert.IsTrue(JToken.DeepEquals(new JObject(new JProperty("hi", 3)), t[3])); } [Test] public void NestedQuery() { JArray a = new JArray( new JObject( new JProperty("name", "Bad Boys"), new JProperty("cast", new JArray( new JObject(new JProperty("name", "Will Smith"))))), new JObject( new JProperty("name", "Independence Day"), new JProperty("cast", new JArray( new JObject(new JProperty("name", "Will Smith"))))), new JObject( new JProperty("name", "The Rock"), new JProperty("cast", new JArray( new JObject(new JProperty("name", "Nick Cage"))))) ); IList<JToken> t = a.SelectTokens("[?(@.cast[?(@.name=='Will Smith')])].name").ToList(); Assert.IsNotNull(t); Assert.AreEqual(2, t.Count); Assert.AreEqual("Bad Boys", (string)t[0]); Assert.AreEqual("Independence Day", (string)t[1]); } [Test] public void PathWithConstructor() { JArray a = JArray.Parse(@"[ { ""Property1"": [ 1, [ [ [] ] ] ] }, { ""Property2"": new Constructor1( null, [ 1 ] ) } ]"); JValue v = (JValue)a.SelectToken("[1].Property2[1][0]"); Assert.AreEqual(1L, v.Value); } [Test] public void MultiplePaths() { JArray a = JArray.Parse(@"[ { ""price"": 199, ""max_price"": 200 }, { ""price"": 200, ""max_price"": 200 }, { ""price"": 201, ""max_price"": 200 } ]"); var results = a.SelectTokens("[?(@.price > @.max_price)]").ToList(); Assert.AreEqual(1, results.Count); Assert.AreEqual(a[2], results[0]); } [Test] public void Exists_True() { JArray a = JArray.Parse(@"[ { ""price"": 199, ""max_price"": 200 }, { ""price"": 200, ""max_price"": 200 }, { ""price"": 201, ""max_price"": 200 } ]"); var results = a.SelectTokens("[?(true)]").ToList(); Assert.AreEqual(3, results.Count); Assert.AreEqual(a[0], results[0]); Assert.AreEqual(a[1], results[1]); Assert.AreEqual(a[2], results[2]); } [Test] public void Exists_Null() { JArray a = JArray.Parse(@"[ { ""price"": 199, ""max_price"": 200 }, { ""price"": 200, ""max_price"": 200 }, { ""price"": 201, ""max_price"": 200 } ]"); var results = a.SelectTokens("[?(true)]").ToList(); Assert.AreEqual(3, results.Count); Assert.AreEqual(a[0], results[0]); Assert.AreEqual(a[1], results[1]); Assert.AreEqual(a[2], results[2]); } [Test] public void WildcardWithProperty() { JObject o = JObject.Parse(@"{ ""station"": 92000041000001, ""containers"": [ { ""id"": 1, ""text"": ""Sort system"", ""containers"": [ { ""id"": ""2"", ""text"": ""Yard 11"" }, { ""id"": ""92000020100006"", ""text"": ""Sort yard 12"" }, { ""id"": ""92000020100005"", ""text"": ""Yard 13"" } ] }, { ""id"": ""92000020100011"", ""text"": ""TSP-1"" }, { ""id"":""92000020100007"", ""text"": ""Passenger 15"" } ] }"); IList<JToken> tokens = o.SelectTokens("$..*[?(@.text)]").ToList(); int i = 0; Assert.AreEqual("Sort system", (string)tokens[i++]["text"]); Assert.AreEqual("TSP-1", (string)tokens[i++]["text"]); Assert.AreEqual("Passenger 15", (string)tokens[i++]["text"]); Assert.AreEqual("Yard 11", (string)tokens[i++]["text"]); Assert.AreEqual("Sort yard 12", (string)tokens[i++]["text"]); Assert.AreEqual("Yard 13", (string)tokens[i++]["text"]); Assert.AreEqual(6, tokens.Count); } [Test] public void QueryAgainstNonStringValues() { IList<object> values = new List<object> { "ff2dc672-6e15-4aa2-afb0-18f4f69596ad", new Guid("ff2dc672-6e15-4aa2-afb0-18f4f69596ad"), "http://localhost", new Uri("http://localhost"), "2000-12-05T05:07:59Z", new DateTime(2000, 12, 5, 5, 7, 59, DateTimeKind.Utc), #if !NET20 "2000-12-05T05:07:59-10:00", new DateTimeOffset(2000, 12, 5, 5, 7, 59, -TimeSpan.FromHours(10)), #endif "SGVsbG8gd29ybGQ=", Encoding.UTF8.GetBytes("Hello world"), "365.23:59:59", new TimeSpan(365, 23, 59, 59) }; JObject o = new JObject( new JProperty("prop", new JArray( values.Select(v => new JObject(new JProperty("childProp", v))) ) ) ); IList<JToken> t = o.SelectTokens("$.prop[?(@.childProp =='ff2dc672-6e15-4aa2-afb0-18f4f69596ad')]").ToList(); Assert.AreEqual(2, t.Count); t = o.SelectTokens("$.prop[?(@.childProp =='http://localhost')]").ToList(); Assert.AreEqual(2, t.Count); t = o.SelectTokens("$.prop[?(@.childProp =='2000-12-05T05:07:59Z')]").ToList(); Assert.AreEqual(2, t.Count); #if !NET20 t = o.SelectTokens("$.prop[?(@.childProp =='2000-12-05T05:07:59-10:00')]").ToList(); Assert.AreEqual(2, t.Count); #endif t = o.SelectTokens("$.prop[?(@.childProp =='SGVsbG8gd29ybGQ=')]").ToList(); Assert.AreEqual(2, t.Count); t = o.SelectTokens("$.prop[?(@.childProp =='365.23:59:59')]").ToList(); Assert.AreEqual(2, t.Count); } [Test] public void Example() { JObject o = JObject.Parse(@"{ ""Stores"": [ ""Lambton Quay"", ""Willis Street"" ], ""Manufacturers"": [ { ""Name"": ""Acme Co"", ""Products"": [ { ""Name"": ""Anvil"", ""Price"": 50 } ] }, { ""Name"": ""Contoso"", ""Products"": [ { ""Name"": ""Elbow Grease"", ""Price"": 99.95 }, { ""Name"": ""Headlight Fluid"", ""Price"": 4 } ] } ] }"); string name = (string)o.SelectToken("Manufacturers[0].Name"); // Acme Co decimal productPrice = (decimal)o.SelectToken("Manufacturers[0].Products[0].Price"); // 50 string productName = (string)o.SelectToken("Manufacturers[1].Products[0].Name"); // Elbow Grease Assert.AreEqual("Acme Co", name); Assert.AreEqual(50m, productPrice); Assert.AreEqual("Elbow Grease", productName); IList<string> storeNames = o.SelectToken("Stores").Select(s => (string)s).ToList(); // Lambton Quay // Willis Street IList<string> firstProductNames = o["Manufacturers"].Select(m => (string)m.SelectToken("Products[1].Name")).ToList(); // null // Headlight Fluid decimal totalPrice = o["Manufacturers"].Sum(m => (decimal)m.SelectToken("Products[0].Price")); // 149.95 Assert.AreEqual(2, storeNames.Count); Assert.AreEqual("Lambton Quay", storeNames[0]); Assert.AreEqual("Willis Street", storeNames[1]); Assert.AreEqual(2, firstProductNames.Count); Assert.AreEqual(null, firstProductNames[0]); Assert.AreEqual("Headlight Fluid", firstProductNames[1]); Assert.AreEqual(149.95m, totalPrice); } [Test] public void NotEqualsAndNonPrimativeValues() { string json = @"[ { ""name"": ""string"", ""value"": ""aString"" }, { ""name"": ""number"", ""value"": 123 }, { ""name"": ""array"", ""value"": [ 1, 2, 3, 4 ] }, { ""name"": ""object"", ""value"": { ""1"": 1 } } ]"; JArray a = JArray.Parse(json); List<JToken> result = a.SelectTokens("$.[?(@.value!=1)]").ToList(); Assert.AreEqual(4, result.Count); result = a.SelectTokens("$.[?(@.value!='2000-12-05T05:07:59-10:00')]").ToList(); Assert.AreEqual(4, result.Count); result = a.SelectTokens("$.[?(@.value!=null)]").ToList(); Assert.AreEqual(4, result.Count); result = a.SelectTokens("$.[?(@.value!=123)]").ToList(); Assert.AreEqual(3, result.Count); result = a.SelectTokens("$.[?(@.value)]").ToList(); Assert.AreEqual(4, result.Count); } [Test] public void RootInFilter() { string json = @"[ { ""store"" : { ""book"" : [ { ""category"" : ""reference"", ""author"" : ""Nigel Rees"", ""title"" : ""Sayings of the Century"", ""price"" : 8.95 }, { ""category"" : ""fiction"", ""author"" : ""Evelyn Waugh"", ""title"" : ""Sword of Honour"", ""price"" : 12.99 }, { ""category"" : ""fiction"", ""author"" : ""Herman Melville"", ""title"" : ""Moby Dick"", ""isbn"" : ""0-553-21311-3"", ""price"" : 8.99 }, { ""category"" : ""fiction"", ""author"" : ""J. R. R. Tolkien"", ""title"" : ""The Lord of the Rings"", ""isbn"" : ""0-395-19395-8"", ""price"" : 22.99 } ], ""bicycle"" : { ""color"" : ""red"", ""price"" : 19.95 } }, ""expensive"" : 10 } ]"; JArray a = JArray.Parse(json); List<JToken> result = a.SelectTokens("$.[?($.[0].store.bicycle.price < 20)]").ToList(); Assert.AreEqual(1, result.Count); result = a.SelectTokens("$.[?($.[0].store.bicycle.price < 10)]").ToList(); Assert.AreEqual(0, result.Count); } [Test] public void RootInFilterWithRootObject() { string json = @"{ ""store"" : { ""book"" : [ { ""category"" : ""reference"", ""author"" : ""Nigel Rees"", ""title"" : ""Sayings of the Century"", ""price"" : 8.95 }, { ""category"" : ""fiction"", ""author"" : ""Evelyn Waugh"", ""title"" : ""Sword of Honour"", ""price"" : 12.99 }, { ""category"" : ""fiction"", ""author"" : ""Herman Melville"", ""title"" : ""Moby Dick"", ""isbn"" : ""0-553-21311-3"", ""price"" : 8.99 }, { ""category"" : ""fiction"", ""author"" : ""J. R. R. Tolkien"", ""title"" : ""The Lord of the Rings"", ""isbn"" : ""0-395-19395-8"", ""price"" : 22.99 } ], ""bicycle"" : [ { ""color"" : ""red"", ""price"" : 19.95 } ] }, ""expensive"" : 10 }"; JObject a = JObject.Parse(json); List<JToken> result = a.SelectTokens("$..book[?(@.price <= $['expensive'])]").ToList(); Assert.AreEqual(2, result.Count); result = a.SelectTokens("$.store..[?(@.price > $.expensive)]").ToList(); Assert.AreEqual(3, result.Count); } [Test] public void RootInFilterWithInitializers() { JObject rootObject = new JObject { { "referenceDate", new JValue(DateTime.MinValue) }, { "dateObjectsArray", new JArray() { new JObject { { "date", new JValue(DateTime.MinValue) } }, new JObject { { "date", new JValue(DateTime.MaxValue) } }, new JObject { { "date", new JValue(DateTime.Now) } }, new JObject { { "date", new JValue(DateTime.MinValue) } }, } } }; List<JToken> result = rootObject.SelectTokens("$.dateObjectsArray[?(@.date == $.referenceDate)]").ToList(); Assert.AreEqual(2, result.Count); } [Test] public void IdentityOperator() { JObject o = JObject.Parse(@"{ 'Values': [{ 'Coercible': 1, 'Name': 'Number' }, { 'Coercible': '1', 'Name': 'String' }] }"); // just to verify expected behavior hasn't changed IEnumerable<string> sanity1 = o.SelectTokens("Values[?(@.Coercible == '1')].Name").Select(x => (string)x); IEnumerable<string> sanity2 = o.SelectTokens("Values[?(@.Coercible != '1')].Name").Select(x => (string)x); // new behavior IEnumerable<string> mustBeNumber1 = o.SelectTokens("Values[?(@.Coercible === 1)].Name").Select(x => (string)x); IEnumerable<string> mustBeString1 = o.SelectTokens("Values[?(@.Coercible !== 1)].Name").Select(x => (string)x); IEnumerable<string> mustBeString2 = o.SelectTokens("Values[?(@.Coercible === '1')].Name").Select(x => (string)x); IEnumerable<string> mustBeNumber2 = o.SelectTokens("Values[?(@.Coercible !== '1')].Name").Select(x => (string)x); // FAILS-- JPath returns { "String" } //CollectionAssert.AreEquivalent(new[] { "Number", "String" }, sanity1); // FAILS-- JPath returns { "Number" } //Assert.IsTrue(!sanity2.Any()); Assert.AreEqual("Number", mustBeNumber1.Single()); Assert.AreEqual("String", mustBeString1.Single()); Assert.AreEqual("Number", mustBeNumber2.Single()); Assert.AreEqual("String", mustBeString2.Single()); } [Test] public void Equals_FloatWithInt() { JToken t = JToken.Parse(@"{ ""Values"": [ { ""Property"": 1 } ] }"); Assert.IsNotNull(t.SelectToken(@"Values[?(@.Property == 1.0)]")); } #if DNXCORE50 [Theory] #endif [TestCaseSource(nameof(StrictMatchWithInverseTestData))] public static void EqualsStrict(string value1, string value2, bool matchStrict) { string completeJson = @"{ ""Values"": [ { ""Property"": " + value1 + @" } ] }"; string completeEqualsStrictPath = "$.Values[?(@.Property === " + value2 + ")]"; string completeNotEqualsStrictPath = "$.Values[?(@.Property !== " + value2 + ")]"; JToken t = JToken.Parse(completeJson); bool hasEqualsStrict = t.SelectTokens(completeEqualsStrictPath).Any(); Assert.AreEqual( matchStrict, hasEqualsStrict, $"Expected {value1} and {value2} to match: {matchStrict}" + Environment.NewLine + completeJson + Environment.NewLine + completeEqualsStrictPath); bool hasNotEqualsStrict = t.SelectTokens(completeNotEqualsStrictPath).Any(); Assert.AreNotEqual( matchStrict, hasNotEqualsStrict, $"Expected {value1} and {value2} to match: {!matchStrict}" + Environment.NewLine + completeJson + Environment.NewLine + completeEqualsStrictPath); } public static IEnumerable<object[]> StrictMatchWithInverseTestData() { foreach (var item in StrictMatchTestData()) { yield return new object[] { item[0], item[1], item[2] }; if (!item[0].Equals(item[1])) { // Test the inverse yield return new object[] { item[1], item[0], item[2] }; } } } private static IEnumerable<object[]> StrictMatchTestData() { yield return new object[] { "1", "1", true }; yield return new object[] { "1", "1.0", true }; yield return new object[] { "1", "true", false }; yield return new object[] { "1", "'1'", false }; yield return new object[] { "'1'", "'1'", true }; yield return new object[] { "false", "false", true }; yield return new object[] { "true", "false", false }; yield return new object[] { "1", "1.1", false }; yield return new object[] { "1", "null", false }; yield return new object[] { "null", "null", true }; yield return new object[] { "null", "'null'", false }; } } }
using System; using System.Collections; using System.IO; using BigMath; using Raksha.Asn1; using Raksha.Asn1.X509; using Raksha.Math; using Raksha.Utilities.Collections; using Raksha.Utilities.Date; using Raksha.X509.Extension; namespace Raksha.X509.Store { /** * This class is an <code>Selector</code> like implementation to select * attribute certificates from a given set of criteria. * * @see org.bouncycastle.x509.X509AttributeCertificate * @see org.bouncycastle.x509.X509Store */ public class X509AttrCertStoreSelector : IX509Selector { // TODO: name constraints??? private IX509AttributeCertificate attributeCert; private DateTimeObject attributeCertificateValid; private AttributeCertificateHolder holder; private AttributeCertificateIssuer issuer; private BigInteger serialNumber; private ISet targetNames = new HashSet(); private ISet targetGroups = new HashSet(); public X509AttrCertStoreSelector() { } private X509AttrCertStoreSelector( X509AttrCertStoreSelector o) { this.attributeCert = o.attributeCert; this.attributeCertificateValid = o.attributeCertificateValid; this.holder = o.holder; this.issuer = o.issuer; this.serialNumber = o.serialNumber; this.targetGroups = new HashSet(o.targetGroups); this.targetNames = new HashSet(o.targetNames); } /// <summary> /// Decides if the given attribute certificate should be selected. /// </summary> /// <param name="obj">The attribute certificate to be checked.</param> /// <returns><code>true</code> if the object matches this selector.</returns> public bool Match( object obj) { if (obj == null) throw new ArgumentNullException("obj"); IX509AttributeCertificate attrCert = obj as IX509AttributeCertificate; if (attrCert == null) return false; if (this.attributeCert != null && !this.attributeCert.Equals(attrCert)) return false; if (serialNumber != null && !attrCert.SerialNumber.Equals(serialNumber)) return false; if (holder != null && !attrCert.Holder.Equals(holder)) return false; if (issuer != null && !attrCert.Issuer.Equals(issuer)) return false; if (attributeCertificateValid != null && !attrCert.IsValid(attributeCertificateValid.Value)) return false; if (targetNames.Count > 0 || targetGroups.Count > 0) { Asn1OctetString targetInfoExt = attrCert.GetExtensionValue( X509Extensions.TargetInformation); if (targetInfoExt != null) { TargetInformation targetinfo; try { targetinfo = TargetInformation.GetInstance( X509ExtensionUtilities.FromExtensionValue(targetInfoExt)); } catch (Exception) { return false; } Targets[] targetss = targetinfo.GetTargetsObjects(); if (targetNames.Count > 0) { bool found = false; for (int i = 0; i < targetss.Length && !found; i++) { Target[] targets = targetss[i].GetTargets(); for (int j = 0; j < targets.Length; j++) { GeneralName targetName = targets[j].TargetName; if (targetName != null && targetNames.Contains(targetName)) { found = true; break; } } } if (!found) { return false; } } if (targetGroups.Count > 0) { bool found = false; for (int i = 0; i < targetss.Length && !found; i++) { Target[] targets = targetss[i].GetTargets(); for (int j = 0; j < targets.Length; j++) { GeneralName targetGroup = targets[j].TargetGroup; if (targetGroup != null && targetGroups.Contains(targetGroup)) { found = true; break; } } } if (!found) { return false; } } } } return true; } public object Clone() { return new X509AttrCertStoreSelector(this); } /// <summary>The attribute certificate which must be matched.</summary> /// <remarks>If <c>null</c> is given, any will do.</remarks> public IX509AttributeCertificate AttributeCert { get { return attributeCert; } set { this.attributeCert = value; } } [Obsolete("Use AttributeCertificateValid instead")] public DateTimeObject AttribueCertificateValid { get { return attributeCertificateValid; } set { this.attributeCertificateValid = value; } } /// <summary>The criteria for validity</summary> /// <remarks>If <c>null</c> is given any will do.</remarks> public DateTimeObject AttributeCertificateValid { get { return attributeCertificateValid; } set { this.attributeCertificateValid = value; } } /// <summary>The holder.</summary> /// <remarks>If <c>null</c> is given any will do.</remarks> public AttributeCertificateHolder Holder { get { return holder; } set { this.holder = value; } } /// <summary>The issuer.</summary> /// <remarks>If <c>null</c> is given any will do.</remarks> public AttributeCertificateIssuer Issuer { get { return issuer; } set { this.issuer = value; } } /// <summary>The serial number.</summary> /// <remarks>If <c>null</c> is given any will do.</remarks> public BigInteger SerialNumber { get { return serialNumber; } set { this.serialNumber = value; } } /** * Adds a target name criterion for the attribute certificate to the target * information extension criteria. The <code>X509AttributeCertificate</code> * must contain at least one of the specified target names. * <p> * Each attribute certificate may contain a target information extension * limiting the servers where this attribute certificate can be used. If * this extension is not present, the attribute certificate is not targeted * and may be accepted by any server. * </p> * * @param name The name as a GeneralName (not <code>null</code>) */ public void AddTargetName( GeneralName name) { targetNames.Add(name); } /** * Adds a target name criterion for the attribute certificate to the target * information extension criteria. The <code>X509AttributeCertificate</code> * must contain at least one of the specified target names. * <p> * Each attribute certificate may contain a target information extension * limiting the servers where this attribute certificate can be used. If * this extension is not present, the attribute certificate is not targeted * and may be accepted by any server. * </p> * * @param name a byte array containing the name in ASN.1 DER encoded form of a GeneralName * @throws IOException if a parsing error occurs. */ public void AddTargetName( byte[] name) { AddTargetName(GeneralName.GetInstance(Asn1Object.FromByteArray(name))); } /** * Adds a collection with target names criteria. If <code>null</code> is * given any will do. * <p> * The collection consists of either GeneralName objects or byte[] arrays representing * DER encoded GeneralName structures. * </p> * * @param names A collection of target names. * @throws IOException if a parsing error occurs. * @see #AddTargetName(byte[]) * @see #AddTargetName(GeneralName) */ public void SetTargetNames( IEnumerable names) { targetNames = ExtractGeneralNames(names); } /** * Gets the target names. The collection consists of <code>List</code>s * made up of an <code>Integer</code> in the first entry and a DER encoded * byte array or a <code>String</code> in the second entry. * <p>The returned collection is immutable.</p> * * @return The collection of target names * @see #setTargetNames(Collection) */ public IEnumerable GetTargetNames() { return new EnumerableProxy(targetNames); } /** * Adds a target group criterion for the attribute certificate to the target * information extension criteria. The <code>X509AttributeCertificate</code> * must contain at least one of the specified target groups. * <p> * Each attribute certificate may contain a target information extension * limiting the servers where this attribute certificate can be used. If * this extension is not present, the attribute certificate is not targeted * and may be accepted by any server. * </p> * * @param group The group as GeneralName form (not <code>null</code>) */ public void AddTargetGroup( GeneralName group) { targetGroups.Add(group); } /** * Adds a target group criterion for the attribute certificate to the target * information extension criteria. The <code>X509AttributeCertificate</code> * must contain at least one of the specified target groups. * <p> * Each attribute certificate may contain a target information extension * limiting the servers where this attribute certificate can be used. If * this extension is not present, the attribute certificate is not targeted * and may be accepted by any server. * </p> * * @param name a byte array containing the group in ASN.1 DER encoded form of a GeneralName * @throws IOException if a parsing error occurs. */ public void AddTargetGroup( byte[] name) { AddTargetGroup(GeneralName.GetInstance(Asn1Object.FromByteArray(name))); } /** * Adds a collection with target groups criteria. If <code>null</code> is * given any will do. * <p> * The collection consists of <code>GeneralName</code> objects or <code>byte[]</code> * representing DER encoded GeneralNames. * </p> * * @param names A collection of target groups. * @throws IOException if a parsing error occurs. * @see #AddTargetGroup(byte[]) * @see #AddTargetGroup(GeneralName) */ public void SetTargetGroups( IEnumerable names) { targetGroups = ExtractGeneralNames(names); } /** * Gets the target groups. The collection consists of <code>List</code>s * made up of an <code>Integer</code> in the first entry and a DER encoded * byte array or a <code>String</code> in the second entry. * <p>The returned collection is immutable.</p> * * @return The collection of target groups. * @see #setTargetGroups(Collection) */ public IEnumerable GetTargetGroups() { return new EnumerableProxy(targetGroups); } private ISet ExtractGeneralNames( IEnumerable names) { ISet result = new HashSet(); if (names != null) { foreach (object o in names) { if (o is GeneralName) { result.Add(o); } else { result.Add(GeneralName.GetInstance(Asn1Object.FromByteArray((byte[]) o))); } } } return result; } } }
using System; using System.Collections.Generic; using UnityEngine; using DarkMultiPlayerCommon; using MessageStream2; namespace DarkMultiPlayer { public class ChatWorker { private static ChatWorker singleton; public bool display = false; public bool workerEnabled = false; private bool isWindowLocked = false; private bool safeDisplay = false; private bool initialized = false; //State tracking private Queue<string> disconnectingPlayers = new Queue<string>(); private Queue<JoinLeaveMessage> newJoinMessages = new Queue<JoinLeaveMessage>(); private Queue<JoinLeaveMessage> newLeaveMessages = new Queue<JoinLeaveMessage>(); private Queue<ChannelEntry> newChannelMessages = new Queue<ChannelEntry>(); private Queue<PrivateEntry> newPrivateMessages = new Queue<PrivateEntry>(); private Queue<ConsoleEntry> newConsoleMessages = new Queue<ConsoleEntry>(); private Dictionary<string, List<string>> channelMessages = new Dictionary<string, List<string>>(); private Dictionary<string, List<string>> privateMessages = new Dictionary<string, List<string>>(); private List<string> consoleMessages = new List<string>(); private Dictionary<string, List<string>> playerChannels = new Dictionary<string, List<string>>(); private List<string> joinedChannels = new List<string>(); private List<string> joinedPMChannels = new List<string>(); private List<string> highlightChannel = new List<string>(); private List<string> highlightPM = new List<string>(); public bool chatButtonHighlighted = false; private string selectedChannel = null; private string selectedPMChannel = null; private bool chatLocked = false; private bool ignoreChatInput = false; private bool selectTextBox = false; private int previousTextID = 0; private string sendText = ""; public string consoleIdentifier = ""; //chat command register private Dictionary<string, ChatCommand> registeredChatCommands = new Dictionary<string, ChatCommand>(); //event handling private bool leaveEventHandled = true; private bool sendEventHandled = true; //GUILayout stuff private Rect windowRect; private Rect moveRect; private GUILayoutOption[] windowLayoutOptions; private GUILayoutOption[] smallSizeOption; private GUIStyle windowStyle; private GUIStyle labelStyle; private GUIStyle buttonStyle; private GUIStyle highlightStyle; private GUIStyle textAreaStyle; private GUIStyle scrollStyle; private Vector2 chatScrollPos; private Vector2 playerScrollPos; //window size private float WINDOW_HEIGHT = 300; private float WINDOW_WIDTH = 400; //const private const string DMP_CHAT_LOCK = "DMP_ChatLock"; private const string DMP_CHAT_WINDOW_LOCK = "DMP_Chat_Window_Lock"; public static ChatWorker fetch { get { return singleton; } } public ChatWorker() { RegisterChatCommand("help", DisplayHelp, "Displays this help"); RegisterChatCommand("join", JoinChannel, "Joins a new chat channel"); RegisterChatCommand("query", StartQuery, "Starts a query"); RegisterChatCommand("leave", LeaveChannel, "Leaves the current channel"); RegisterChatCommand("part", LeaveChannel, "Leaves the current channel"); RegisterChatCommand("ping", ServerPing, "Pings the server"); RegisterChatCommand("motd", ServerMOTD, "Gets the current Message of the Day"); RegisterChatCommand("resize", ResizeChat, "Resized the chat window"); RegisterChatCommand("version", DisplayVersion, "Displays the current version of DMP"); } private void PrintToSelectedChannel(string text) { if (selectedChannel == null && selectedPMChannel == null) { QueueChannelMessage(Settings.fetch.playerName, "", text); } if (selectedChannel != null && selectedChannel != consoleIdentifier) { QueueChannelMessage(Settings.fetch.playerName, selectedChannel, text); } if (selectedChannel == consoleIdentifier) { QueueSystemMessage(text); } if (selectedPMChannel != null) { QueuePrivateMessage(Settings.fetch.playerName, selectedPMChannel, text); } } private void DisplayHelp(string commandArgs) { List<ChatCommand> commands = new List<ChatCommand>(); int longestName = 0; foreach (ChatCommand cmd in registeredChatCommands.Values) { commands.Add(cmd); if (cmd.name.Length > longestName) { longestName = cmd.name.Length; } } commands.Sort(); foreach (ChatCommand cmd in commands) { string helpText = cmd.name.PadRight(longestName) + " - " + cmd.description; PrintToSelectedChannel(helpText); } } private void DisplayVersion(string commandArgs) { string versionMessage = (Common.PROGRAM_VERSION.Length == 40) ? "DarkMultiPlayer development build " + Common.PROGRAM_VERSION.Substring(0, 7) : "DarkMultiPlayer " + Common.PROGRAM_VERSION; PrintToSelectedChannel(versionMessage); } private void JoinChannel(string commandArgs) { if (commandArgs != "" && commandArgs != "Global" && commandArgs != consoleIdentifier && commandArgs != "#Global" && commandArgs != "#" + consoleIdentifier) { if (commandArgs.StartsWith("#")) { commandArgs = commandArgs.Substring(1); } if (!joinedChannels.Contains(commandArgs)) { DarkLog.Debug("Joining channel " + commandArgs); joinedChannels.Add(commandArgs); selectedChannel = commandArgs; selectedPMChannel = null; using (MessageWriter mw = new MessageWriter()) { mw.Write<int>((int)ChatMessageType.JOIN); mw.Write<string>(Settings.fetch.playerName); mw.Write<string>(commandArgs); NetworkWorker.fetch.SendChatMessage(mw.GetMessageBytes()); } } } else { ScreenMessages.PostScreenMessage("Couldn't join '" + commandArgs + "', channel name not valid!"); } } private void LeaveChannel(string commandArgs) { leaveEventHandled = false; } private void StartQuery(string commandArgs) { bool playerFound = false; if (commandArgs != consoleIdentifier) { foreach (PlayerStatus ps in PlayerStatusWorker.fetch.playerStatusList) { if (ps.playerName == commandArgs) { playerFound = true; } } } else { //Make sure we can always query the server. playerFound = true; } if (playerFound) { if (!joinedPMChannels.Contains(commandArgs)) { DarkLog.Debug("Starting query with " + commandArgs); joinedPMChannels.Add(commandArgs); selectedChannel = null; selectedPMChannel = commandArgs; } } else { ScreenMessages.PostScreenMessage("Couldn't start query with '" + commandArgs + "', player not found!"); } } private void ServerPing(string commandArgs) { NetworkWorker.fetch.SendPingRequest(); } private void ServerMOTD(string commandArgs) { NetworkWorker.fetch.SendMotdRequest(); } private void ResizeChat(string commandArgs) { string func = ""; float size = 0; func = commandArgs; if (commandArgs.Contains(" ")) { func = commandArgs.Substring(0, commandArgs.IndexOf(" ")); if (commandArgs.Substring(func.Length).Contains(" ")) { try { size = Convert.ToSingle(commandArgs.Substring(func.Length + 1)); } catch (FormatException) { PrintToSelectedChannel("Error: " + size + " is not a valid number"); size = 400f; } } } switch (func) { default: PrintToSelectedChannel("Undefined function. Usage: /resize [default|medium|large], /resize [x|y] size, or /resize show"); PrintToSelectedChannel("Chat window size is currently: " + WINDOW_WIDTH + "x" + WINDOW_HEIGHT); break; case "x": if (size <= 800 && size >= 300) { WINDOW_WIDTH = size; initialized = false; PrintToSelectedChannel("New window size is: " + WINDOW_WIDTH + "x" + WINDOW_HEIGHT); } else { PrintToSelectedChannel("Size is out of range."); } break; case "y": if (size <= 800 && size >= 300) { WINDOW_HEIGHT = size; initialized = false; PrintToSelectedChannel("New window size is: " + WINDOW_WIDTH + "x" + WINDOW_HEIGHT); } else { PrintToSelectedChannel("Size is out of range."); } break; case "default": WINDOW_HEIGHT = 300; WINDOW_WIDTH = 400; initialized = false; PrintToSelectedChannel("New window size is: " + WINDOW_WIDTH + "x" + WINDOW_HEIGHT); break; case "medium": WINDOW_HEIGHT = 600; WINDOW_WIDTH = 600; initialized = false; PrintToSelectedChannel("New window size is: " + WINDOW_WIDTH + "x" + WINDOW_HEIGHT); break; case "large": WINDOW_HEIGHT = 800; WINDOW_WIDTH = 800; initialized = false; PrintToSelectedChannel("New window size is: " + WINDOW_WIDTH + "x" + WINDOW_HEIGHT); break; case "show": PrintToSelectedChannel("Chat window size is currently: " + WINDOW_WIDTH + "x" + WINDOW_HEIGHT); break; } } private void InitGUI() { //Setup GUI stuff windowRect = new Rect(Screen.width / 10, Screen.height / 2f - WINDOW_HEIGHT / 2f, WINDOW_WIDTH, WINDOW_HEIGHT); moveRect = new Rect(0, 0, 10000, 20); windowLayoutOptions = new GUILayoutOption[4]; windowLayoutOptions[0] = GUILayout.MinWidth(WINDOW_WIDTH); windowLayoutOptions[1] = GUILayout.MaxWidth(WINDOW_WIDTH); windowLayoutOptions[2] = GUILayout.MinHeight(WINDOW_HEIGHT); windowLayoutOptions[3] = GUILayout.MaxHeight(WINDOW_HEIGHT); smallSizeOption = new GUILayoutOption[1]; smallSizeOption[0] = GUILayout.Width(WINDOW_WIDTH * .25f); windowStyle = new GUIStyle(GUI.skin.window); scrollStyle = new GUIStyle(GUI.skin.scrollView); chatScrollPos = new Vector2(0, 0); labelStyle = new GUIStyle(GUI.skin.label); buttonStyle = new GUIStyle(GUI.skin.button); highlightStyle = new GUIStyle(GUI.skin.button); highlightStyle.normal.textColor = Color.red; highlightStyle.active.textColor = Color.red; highlightStyle.hover.textColor = Color.red; textAreaStyle = new GUIStyle(GUI.skin.textArea); } public void QueueChatJoin(string playerName, string channelName) { JoinLeaveMessage jlm = new JoinLeaveMessage(); jlm.fromPlayer = playerName; jlm.channel = channelName; newJoinMessages.Enqueue(jlm); } public void QueueChatLeave(string playerName, string channelName) { JoinLeaveMessage jlm = new JoinLeaveMessage(); jlm.fromPlayer = playerName; jlm.channel = channelName; newLeaveMessages.Enqueue(jlm); } public void QueueChannelMessage(string fromPlayer, string channelName, string channelMessage) { // Check if any of these is null before doing anything else if (!string.IsNullOrEmpty(fromPlayer) && !string.IsNullOrEmpty(channelMessage)) { ChannelEntry ce = new ChannelEntry(); ce.fromPlayer = fromPlayer; ce.channel = channelName; ce.message = channelMessage; newChannelMessages.Enqueue(ce); } } public void QueuePrivateMessage(string fromPlayer, string toPlayer, string privateMessage) { PrivateEntry pe = new PrivateEntry(); pe.fromPlayer = fromPlayer; pe.toPlayer = toPlayer; pe.message = privateMessage; newPrivateMessages.Enqueue(pe); } public void QueueRemovePlayer(string playerName) { disconnectingPlayers.Enqueue(playerName); } public void PMMessageServer(string message) { using (MessageWriter mw = new MessageWriter()) { mw.Write<int>((int)ChatMessageType.PRIVATE_MESSAGE); mw.Write<string>(Settings.fetch.playerName); mw.Write<string>(consoleIdentifier); mw.Write<string>(message); NetworkWorker.fetch.SendChatMessage(mw.GetMessageBytes()); } } public void QueueSystemMessage(string message) { ConsoleEntry ce = new ConsoleEntry(); ce.message = message; newConsoleMessages.Enqueue(ce); } public void RegisterChatCommand(string command, Action<string> func, string description) { ChatCommand cmd = new ChatCommand(command, func, description); if (!registeredChatCommands.ContainsKey(command)) { registeredChatCommands.Add(command, cmd); } } public void HandleChatInput(string input) { if (!input.StartsWith("/") || input.StartsWith("//")) { //Handle chat messages if (input.StartsWith("//")) { input = input.Substring(1); } if (selectedChannel == null && selectedPMChannel == null) { //Sending a global chat message using (MessageWriter mw = new MessageWriter()) { mw.Write<int>((int)ChatMessageType.CHANNEL_MESSAGE); mw.Write<string>(Settings.fetch.playerName); //Global channel name is empty string. mw.Write<string>(""); mw.Write<string>(input); NetworkWorker.fetch.SendChatMessage(mw.GetMessageBytes()); } } if (selectedChannel != null && selectedChannel != consoleIdentifier) { using (MessageWriter mw = new MessageWriter()) { mw.Write<int>((int)ChatMessageType.CHANNEL_MESSAGE); mw.Write<string>(Settings.fetch.playerName); mw.Write<string>(selectedChannel); mw.Write<string>(input); NetworkWorker.fetch.SendChatMessage(mw.GetMessageBytes()); } } if (selectedChannel == consoleIdentifier) { using (MessageWriter mw = new MessageWriter()) { mw.Write<int>((int)ChatMessageType.CONSOLE_MESSAGE); mw.Write<string>(Settings.fetch.playerName); mw.Write<string>(input); NetworkWorker.fetch.SendChatMessage(mw.GetMessageBytes()); DarkLog.Debug("Server Command: " + input); } } if (selectedPMChannel != null) { using (MessageWriter mw = new MessageWriter()) { mw.Write<int>((int)ChatMessageType.PRIVATE_MESSAGE); mw.Write<string>(Settings.fetch.playerName); mw.Write<string>(selectedPMChannel); mw.Write<string>(input); NetworkWorker.fetch.SendChatMessage(mw.GetMessageBytes()); } } } else { string commandPart = input.Substring(1); string argumentPart = ""; if (commandPart.Contains(" ")) { if (commandPart.Length > commandPart.IndexOf(' ') + 1) { argumentPart = commandPart.Substring(commandPart.IndexOf(' ') + 1); } commandPart = commandPart.Substring(0, commandPart.IndexOf(' ')); } if (commandPart.Length > 0) { if (registeredChatCommands.ContainsKey(commandPart)) { try { DarkLog.Debug("Chat Command: " + input.Substring(1)); registeredChatCommands[commandPart].func(argumentPart); } catch (Exception e) { DarkLog.Debug("Error handling chat command " + commandPart + ", Exception " + e); PrintToSelectedChannel("Error handling chat command: " + commandPart); } } else { PrintToSelectedChannel("Unknown chat command: " + commandPart); } } } } private void HandleChatEvents() { //Handle leave event if (!leaveEventHandled) { if (!string.IsNullOrEmpty(selectedChannel) && selectedChannel != consoleIdentifier) { using (MessageWriter mw = new MessageWriter()) { mw.Write<int>((int)ChatMessageType.LEAVE); mw.Write<string>(Settings.fetch.playerName); mw.Write<string>(selectedChannel); NetworkWorker.fetch.SendChatMessage(mw.GetMessageBytes()); } if (joinedChannels.Contains(selectedChannel)) { joinedChannels.Remove(selectedChannel); } selectedChannel = null; selectedPMChannel = null; } if (!string.IsNullOrEmpty(selectedPMChannel)) { if (joinedPMChannels.Contains(selectedPMChannel)) { joinedPMChannels.Remove(selectedPMChannel); } selectedChannel = null; selectedPMChannel = null; } leaveEventHandled = true; } //Handle send event if (!sendEventHandled) { if (sendText != "") { HandleChatInput(sendText); } sendText = ""; sendEventHandled = true; } //Handle join messages while (newJoinMessages.Count > 0) { JoinLeaveMessage jlm = newJoinMessages.Dequeue(); if (!playerChannels.ContainsKey(jlm.fromPlayer)) { playerChannels.Add(jlm.fromPlayer, new List<string>()); } if (!playerChannels[jlm.fromPlayer].Contains(jlm.channel)) { playerChannels[jlm.fromPlayer].Add(jlm.channel); } } //Handle leave messages while (newLeaveMessages.Count > 0) { JoinLeaveMessage jlm = newLeaveMessages.Dequeue(); if (playerChannels.ContainsKey(jlm.fromPlayer)) { if (playerChannels[jlm.fromPlayer].Contains(jlm.channel)) { playerChannels[jlm.fromPlayer].Remove(jlm.channel); } if (playerChannels[jlm.fromPlayer].Count == 0) { playerChannels.Remove(jlm.fromPlayer); } } } //Handle channel messages while (newChannelMessages.Count > 0) { ChannelEntry ce = newChannelMessages.Dequeue(); if (!channelMessages.ContainsKey(ce.channel)) { channelMessages.Add(ce.channel, new List<string>()); } // Write message to screen if chat window is disabled if (!display) { chatButtonHighlighted = ce.fromPlayer != consoleIdentifier; if (!string.IsNullOrEmpty(ce.channel)) ScreenMessages.PostScreenMessage(ce.fromPlayer + " -> #" + ce.channel + ": " + ce.message, 5f, ScreenMessageStyle.UPPER_LEFT); else ScreenMessages.PostScreenMessage(ce.fromPlayer + " -> #Global : " + ce.message, 5f, ScreenMessageStyle.UPPER_LEFT); } //Highlight if the channel isn't selected. if (!string.IsNullOrEmpty(selectedChannel) && string.IsNullOrEmpty(ce.channel) && ce.fromPlayer != consoleIdentifier) { if (!highlightChannel.Contains(ce.channel)) highlightChannel.Add(ce.channel); } if (!string.IsNullOrEmpty(ce.channel) && ce.channel != selectedChannel) { if (!highlightChannel.Contains(ce.channel)) highlightChannel.Add(ce.channel); } //Move the bar to the bottom on a new message if (string.IsNullOrEmpty(selectedChannel) && string.IsNullOrEmpty(selectedPMChannel) && string.IsNullOrEmpty(ce.channel)) { chatScrollPos.y = float.PositiveInfinity; selectTextBox = chatLocked; } if (!string.IsNullOrEmpty(selectedChannel) && string.IsNullOrEmpty(selectedPMChannel) && ce.channel == selectedChannel) { chatScrollPos.y = float.PositiveInfinity; selectTextBox = chatLocked; } channelMessages[ce.channel].Add(ce.fromPlayer + ": " + ce.message); } //Handle private messages while (newPrivateMessages.Count > 0) { PrivateEntry pe = newPrivateMessages.Dequeue(); if (pe.fromPlayer != Settings.fetch.playerName) { if (!privateMessages.ContainsKey(pe.fromPlayer)) { privateMessages.Add(pe.fromPlayer, new List<string>()); } //Highlight if the player isn't selected if (!joinedPMChannels.Contains(pe.fromPlayer)) { joinedPMChannels.Add(pe.fromPlayer); } if (selectedPMChannel != pe.fromPlayer) { if (!highlightPM.Contains(pe.fromPlayer)) { highlightPM.Add(pe.fromPlayer); } } } if (!privateMessages.ContainsKey(pe.toPlayer)) { privateMessages.Add(pe.toPlayer, new List<string>()); } //Move the bar to the bottom on a new message if (!string.IsNullOrEmpty(selectedPMChannel) && string.IsNullOrEmpty(selectedChannel) && (pe.fromPlayer == selectedPMChannel || pe.fromPlayer == Settings.fetch.playerName)) { chatScrollPos.y = float.PositiveInfinity; selectTextBox = chatLocked; } if (pe.fromPlayer != Settings.fetch.playerName) { privateMessages[pe.fromPlayer].Add(pe.fromPlayer + ": " + pe.message); if (!display) { chatButtonHighlighted = true; ScreenMessages.PostScreenMessage(pe.fromPlayer + " -> @" + pe.toPlayer + ": " + pe.message, 5f, ScreenMessageStyle.UPPER_LEFT); } } else { privateMessages[pe.toPlayer].Add(pe.fromPlayer + ": " + pe.message); } } //Handle console messages while (newConsoleMessages.Count > 0) { ConsoleEntry ce = newConsoleMessages.Dequeue(); //Highlight if the channel isn't selected. if (selectedChannel != consoleIdentifier) { if (!highlightChannel.Contains(consoleIdentifier)) { highlightChannel.Add(consoleIdentifier); } } //Move the bar to the bottom on a new message if (!string.IsNullOrEmpty(selectedChannel) && string.IsNullOrEmpty(selectedPMChannel) && consoleIdentifier == selectedChannel) { chatScrollPos.y = float.PositiveInfinity; selectTextBox = chatLocked; } consoleMessages.Add(ce.message); } while (disconnectingPlayers.Count > 0) { string disconnectingPlayer = disconnectingPlayers.Dequeue(); if (playerChannels.ContainsKey(disconnectingPlayer)) { playerChannels.Remove(disconnectingPlayer); } if (joinedPMChannels.Contains(disconnectingPlayer)) { joinedPMChannels.Remove(disconnectingPlayer); } if (highlightPM.Contains(disconnectingPlayer)) { highlightPM.Remove(disconnectingPlayer); } if (privateMessages.ContainsKey(disconnectingPlayer)) { privateMessages.Remove(disconnectingPlayer); } } } private void Update() { safeDisplay = display; ignoreChatInput = false; if (chatButtonHighlighted && display) { chatButtonHighlighted = false; } if (chatLocked && !display) { chatLocked = false; InputLockManager.RemoveControlLock(DMP_CHAT_LOCK); } if (workerEnabled) { HandleChatEvents(); } } public void Draw() { if (!initialized) { InitGUI(); initialized = true; } if (safeDisplay) { bool pressedChatShortcutKey = (Event.current.type == EventType.KeyDown && Event.current.keyCode == Settings.fetch.chatKey); if (pressedChatShortcutKey) { ignoreChatInput = true; selectTextBox = true; } windowRect = DMPGuiUtil.PreventOffscreenWindow(GUILayout.Window(6704 + Client.WINDOW_OFFSET, windowRect, DrawContent, "DarkMultiPlayer Chat", windowStyle, windowLayoutOptions)); } CheckWindowLock(); } private void DrawContent(int windowID) { bool pressedEnter = (Event.current.type == EventType.KeyDown && !Event.current.shift && Event.current.character == '\n'); GUILayout.BeginVertical(); GUI.DragWindow(moveRect); GUILayout.BeginHorizontal(); DrawRooms(); GUILayout.FlexibleSpace(); if (selectedChannel != null && selectedChannel != consoleIdentifier || selectedPMChannel != null) { if (GUILayout.Button("Leave", buttonStyle)) { leaveEventHandled = false; } } DrawConsole(); GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); chatScrollPos = GUILayout.BeginScrollView(chatScrollPos, scrollStyle); if (selectedChannel == null && selectedPMChannel == null) { if (!channelMessages.ContainsKey("")) { channelMessages.Add("", new List<string>()); } foreach (string channelMessage in channelMessages[""]) { GUILayout.Label(channelMessage, labelStyle); } } if (selectedChannel != null && selectedChannel != consoleIdentifier) { if (!channelMessages.ContainsKey(selectedChannel)) { channelMessages.Add(selectedChannel, new List<string>()); } foreach (string channelMessage in channelMessages[selectedChannel]) { GUILayout.Label(channelMessage, labelStyle); } } if (selectedChannel == consoleIdentifier) { foreach (string consoleMessage in consoleMessages) { GUILayout.Label(consoleMessage, labelStyle); } } if (selectedPMChannel != null) { if (!privateMessages.ContainsKey(selectedPMChannel)) { privateMessages.Add(selectedPMChannel, new List<string>()); } foreach (string privateMessage in privateMessages[selectedPMChannel]) { GUILayout.Label(privateMessage, labelStyle); } } GUILayout.EndScrollView(); playerScrollPos = GUILayout.BeginScrollView(playerScrollPos, scrollStyle, smallSizeOption); GUILayout.BeginVertical(); GUILayout.Label(Settings.fetch.playerName, labelStyle); if (selectedPMChannel != null) { GUILayout.Label(selectedPMChannel, labelStyle); } else { if (selectedChannel == null) { //Global chat foreach (PlayerStatus player in PlayerStatusWorker.fetch.playerStatusList) { if (joinedPMChannels.Contains(player.playerName)) { GUI.enabled = false; } if (GUILayout.Button(player.playerName, labelStyle)) { if (!joinedPMChannels.Contains(player.playerName)) { joinedPMChannels.Add(player.playerName); } } GUI.enabled = true; } } else { foreach (KeyValuePair<string, List<string>> playerEntry in playerChannels) { if (playerEntry.Key != Settings.fetch.playerName) { if (playerEntry.Value.Contains(selectedChannel)) { if (joinedPMChannels.Contains(playerEntry.Key)) { GUI.enabled = false; } if (GUILayout.Button(playerEntry.Key, labelStyle)) { if (!joinedPMChannels.Contains(playerEntry.Key)) { joinedPMChannels.Add(playerEntry.Key); } } GUI.enabled = true; } } } } } GUILayout.EndVertical(); GUILayout.EndScrollView(); GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); GUI.SetNextControlName("SendTextArea"); string tempSendText = GUILayout.TextArea(sendText, textAreaStyle); //When a control is inserted or removed from the GUI, Unity's focusing starts tripping balls. This is a horrible workaround for unity that shouldn't exist... int newTextID = GUIUtility.GetControlID(FocusType.Keyboard); if (previousTextID != newTextID) { previousTextID = newTextID; if (chatLocked) { selectTextBox = true; } } //Don't add the newline to the messages, queue a send if (!ignoreChatInput) { if (pressedEnter) { sendEventHandled = false; } else { sendText = tempSendText; } } if (sendText == "") { GUI.enabled = false; } if (GUILayout.Button("Send", buttonStyle, smallSizeOption)) { sendEventHandled = false; } GUI.enabled = true; GUILayout.EndHorizontal(); GUILayout.EndVertical(); if (!selectTextBox) { if ((GUI.GetNameOfFocusedControl() == "SendTextArea") && !chatLocked) { chatLocked = true; InputLockManager.SetControlLock(DMPGuiUtil.BLOCK_ALL_CONTROLS, DMP_CHAT_LOCK); } if ((GUI.GetNameOfFocusedControl() != "SendTextArea") && chatLocked) { chatLocked = false; InputLockManager.RemoveControlLock(DMP_CHAT_LOCK); } } else { selectTextBox = false; GUI.FocusControl("SendTextArea"); } } private void DrawConsole() { GUIStyle possibleHighlightButtonStyle = buttonStyle; if (selectedChannel == consoleIdentifier) { GUI.enabled = false; } if (highlightChannel.Contains(consoleIdentifier)) { possibleHighlightButtonStyle = highlightStyle; } else { possibleHighlightButtonStyle = buttonStyle; } if (AdminSystem.fetch.IsAdmin(Settings.fetch.playerName)) { if (GUILayout.Button("#" + consoleIdentifier, possibleHighlightButtonStyle)) { if (highlightChannel.Contains(consoleIdentifier)) { highlightChannel.Remove(consoleIdentifier); } selectedChannel = consoleIdentifier; selectedPMChannel = null; chatScrollPos.y = float.PositiveInfinity; } } GUI.enabled = true; } private void DrawRooms() { GUIStyle possibleHighlightButtonStyle = buttonStyle; if (selectedChannel == null && selectedPMChannel == null) { GUI.enabled = false; } if (highlightChannel.Contains("")) { possibleHighlightButtonStyle = highlightStyle; } else { possibleHighlightButtonStyle = buttonStyle; } if (GUILayout.Button("#Global", possibleHighlightButtonStyle)) { if (highlightChannel.Contains("")) { highlightChannel.Remove(""); } selectedChannel = null; selectedPMChannel = null; chatScrollPos.y = float.PositiveInfinity; } GUI.enabled = true; foreach (string joinedChannel in joinedChannels) { if (highlightChannel.Contains(joinedChannel)) { possibleHighlightButtonStyle = highlightStyle; } else { possibleHighlightButtonStyle = buttonStyle; } if (selectedChannel == joinedChannel) { GUI.enabled = false; } if (GUILayout.Button("#" + joinedChannel, possibleHighlightButtonStyle)) { if (highlightChannel.Contains(joinedChannel)) { highlightChannel.Remove(joinedChannel); } selectedChannel = joinedChannel; selectedPMChannel = null; chatScrollPos.y = float.PositiveInfinity; } GUI.enabled = true; } foreach (string joinedPlayer in joinedPMChannels) { if (highlightPM.Contains(joinedPlayer)) { possibleHighlightButtonStyle = highlightStyle; } else { possibleHighlightButtonStyle = buttonStyle; } if (selectedPMChannel == joinedPlayer) { GUI.enabled = false; } if (GUILayout.Button("@" + joinedPlayer, possibleHighlightButtonStyle)) { if (highlightPM.Contains(joinedPlayer)) { highlightPM.Remove(joinedPlayer); } selectedChannel = null; selectedPMChannel = joinedPlayer; chatScrollPos.y = float.PositiveInfinity; } GUI.enabled = true; } } public static void Reset() { lock (Client.eventLock) { if (singleton != null) { singleton.workerEnabled = false; singleton.RemoveWindowLock(); Client.updateEvent.Remove(singleton.Update); Client.drawEvent.Remove(singleton.Draw); if (singleton.chatLocked) { singleton.chatLocked = false; InputLockManager.RemoveControlLock(DMP_CHAT_LOCK); } } singleton = new ChatWorker(); Client.updateEvent.Add(singleton.Update); Client.drawEvent.Add(singleton.Draw); } } private void CheckWindowLock() { if (!Client.fetch.gameRunning) { RemoveWindowLock(); return; } if (HighLogic.LoadedSceneIsFlight) { RemoveWindowLock(); return; } if (safeDisplay) { Vector2 mousePos = Input.mousePosition; mousePos.y = Screen.height - mousePos.y; bool shouldLock = windowRect.Contains(mousePos); if (shouldLock && !isWindowLocked) { InputLockManager.SetControlLock(ControlTypes.ALLBUTCAMERAS, DMP_CHAT_WINDOW_LOCK); isWindowLocked = true; } if (!shouldLock && isWindowLocked) { RemoveWindowLock(); } } if (!safeDisplay && isWindowLocked) { RemoveWindowLock(); } } private void RemoveWindowLock() { if (isWindowLocked) { isWindowLocked = false; InputLockManager.RemoveControlLock(DMP_CHAT_WINDOW_LOCK); } } private class ChatCommand : IComparable { public string name; public Action<string> func; public string description; public ChatCommand(string name, Action<string> func, string description) { this.name = name; this.func = func; this.description = description; } public int CompareTo(object obj) { var cmd = obj as ChatCommand; return this.name.CompareTo(cmd.name); } } } public class ChannelEntry { public string fromPlayer; public string channel; public string message; } public class PrivateEntry { public string fromPlayer; public string toPlayer; public string message; } public class JoinLeaveMessage { public string fromPlayer; public string channel; } public class ConsoleEntry { public string message; } }
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for Additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ namespace TestCases.SS.Format { using System; using System.Collections; using System.Collections.Generic; using System.Drawing; using System.Text.RegularExpressions; using System.Windows.Forms; using NUnit.Framework; using NPOI.HSSF.UserModel; using NPOI.SS.Format; using NPOI.SS.UserModel; using NPOI.Util; using TestCases.SS; using System.Diagnostics; /** * This class is a base class for spreadsheet-based tests, such as are used for * cell formatting. This Reads tests from the spreadsheet, as well as Reading * flags that can be used to paramterize these tests. * <p/> * Each test has four parts: The expected result (column A), the format string * (column B), the value to format (column C), and a comma-Separated list of * categores that this test falls in1. Normally all tests are Run, but if the * flag "Categories" is not empty, only tests that have at least one category * listed in "Categories" are Run. */ //[TestFixture] public class CellFormatTestBase { private static POILogger logger = POILogFactory.GetLogger(typeof(CellFormatTestBase)); private ITestDataProvider _testDataProvider; protected IWorkbook workbook; private String testFile; private Dictionary<String, String> testFlags; private bool tryAllColors; private Label label; private static String[] COLOR_NAMES = {"Black", "Red", "Green", "Blue", "Yellow", "Cyan", "Magenta", "White"}; private static Color[] COLORS = { Color.Black, Color.Red, Color.Green, Color.Blue, Color.Yellow, Color.Cyan, Color.Magenta, Color.Wheat }; public static Color TEST_COLOR = Color.Orange; //Darker(); protected CellFormatTestBase(ITestDataProvider testDataProvider) { _testDataProvider = testDataProvider; } public abstract class CellValue { public abstract Object GetValue(ICell cell); public Color GetColor(ICell cell) { return TEST_COLOR; } public virtual void Equivalent(String expected, String actual, CellFormatPart format) { Assert.AreEqual('"' + expected + '"', '"' + actual + '"', "format \"" + format.ToString() + "\""); } } protected void RunFormatTests(String workbookName, CellValue valueGetter) { OpenWorkbook(workbookName); ReadFlags(workbook); SortedList<string, object> runCategories = new SortedList<string, object>(StringComparer.InvariantCultureIgnoreCase); String RunCategoryList = flagString("Categories", ""); Regex regex = new Regex("\\s*,\\s*"); if (RunCategoryList != null) { foreach (string s in regex.Split(RunCategoryList)) if (!runCategories.ContainsKey(s)) runCategories.Add(s, null); runCategories.Remove(""); // this can be found and means nothing } ISheet sheet = workbook.GetSheet("Tests"); int end = sheet.LastRowNum; // Skip the header row, therefore "+ 1" for (int r = sheet.FirstRowNum + 1; r <= end; r++) { IRow row = sheet.GetRow(r); if (row == null) continue; int cellnum = 0; String expectedText = row.GetCell(cellnum).StringCellValue; String format = row.GetCell(1).StringCellValue; String testCategoryList = row.GetCell(3).StringCellValue; bool byCategory = RunByCategory(runCategories, testCategoryList); if ((expectedText.Length > 0 || format.Length > 0) && byCategory) { ICell cell = row.GetCell(2); Debug.WriteLine(string.Format("expectedText: {0}, format:{1}", expectedText, format)); tryFormat(r, expectedText, format, valueGetter, cell); } } } /** * Open a given workbook. * * @param workbookName The workbook name. This is presumed to live in the * "spreadsheets" directory under the directory named in * the Java property "POI.testdata.path". * * @throws IOException */ protected void OpenWorkbook(String workbookName) { workbook = _testDataProvider.OpenSampleWorkbook(workbookName); workbook.MissingCellPolicy = MissingCellPolicy.CREATE_NULL_AS_BLANK;//Row.CREATE_NULL_AS_BLANK); testFile = workbookName; } /** * Read the flags from the workbook. Flags are on the sheet named "Flags", * and consist of names in column A and values in column B. These are Put * into a map that can be queried later. * * @param wb The workbook to look in1. */ private void ReadFlags(IWorkbook wb) { ISheet flagSheet = wb.GetSheet("Flags"); testFlags = new Dictionary<String, String>(); if (flagSheet != null) { int end = flagSheet.LastRowNum; // Skip the header row, therefore "+ 1" for (int r = flagSheet.FirstRowNum + 1; r <= end; r++) { IRow row = flagSheet.GetRow(r); if (row == null) continue; String flagName = row.GetCell(0).StringCellValue; String flagValue = row.GetCell(1).StringCellValue; if (flagName.Length > 0) { testFlags.Add(flagName, flagValue); } } } tryAllColors = flagBoolean("AllColors", true); } /** * Returns <tt>true</tt> if any of the categories for this run are Contained * in the test's listed categories. * * @param categories The categories of tests to be Run. If this is * empty, then all tests will be Run. * @param testCategories The categories that this test is in1. This is a * comma-Separated list. If <em>any</em> tests in * this list are in <tt>categories</tt>, the test will * be Run. * * @return <tt>true</tt> if the test should be Run. */ private bool RunByCategory(SortedList<string, object> categories, String testCategories) { if (categories.Count == 0) return true; // If there are specified categories, find out if this has one of them Regex regex = new Regex("\\s*,\\s*"); foreach (String category in regex.Split(testCategories))//.Split("\\s*,\\s*")) { if (categories.ContainsKey(category)) { return true; } } return false; } private void tryFormat(int row, String expectedText, String desc, CellValue Getter, ICell cell) { Object value = Getter.GetValue(cell); Color testColor = Getter.GetColor(cell); if (testColor == null) testColor = TEST_COLOR; if (label == null) label = new Label(); label.ForeColor = (/*setter*/testColor); label.Text = (/*setter*/"xyzzy"); logger.Log(POILogger.INFO, String.Format("Row %d: \"%s\" -> \"%s\": expected \"%s\"", row + 1, value.ToString(), desc, expectedText)); String actualText = tryColor(desc, null, Getter, value, expectedText, testColor); logger.Log(POILogger.INFO, String.Format(", actual \"%s\")%n", actualText)); if (tryAllColors && testColor != TEST_COLOR) { for (int i = 0; i < COLOR_NAMES.Length; i++) { String cname = COLOR_NAMES[i]; tryColor(desc, cname, Getter, value, expectedText, COLORS[i]); } } } private String tryColor(String desc, String cname, CellValue Getter, Object value, String expectedText, Color expectedColor) { if (cname != null) desc = "[" + cname + "]" + desc; Color origColor = label.ForeColor; CellFormatPart format = new CellFormatPart(desc); if (!format.Apply(label, value).Applies) { // If this doesn't Apply, no color change is expected expectedColor = origColor; } String actualText = label.Text; Color actualColor = label.ForeColor; Getter.Equivalent(expectedText, actualText, format); Assert.AreEqual( expectedColor, actualColor,cname == null ? "no color" : "color " + cname); return actualText; } /** * Returns the value for the given flag. The flag has the value of * <tt>true</tt> if the text value is <tt>"true"</tt>, <tt>"yes"</tt>, or * <tt>"on"</tt> (ignoring case). * * @param flagName The name of the flag to fetch. * @param expected The value for the flag that is expected when the tests * are run for a full test. If the current value is not the * expected one, you will Get a warning in the test output. * This is so that you do not accidentally leave a flag Set * to a value that prevents Running some tests, thereby * letting you accidentally release code that is not fully * tested. * * @return The value for the flag. */ protected bool flagBoolean(String flagName, bool expected) { String value = testFlags[(flagName)]; bool isSet; if (value == null) isSet = false; else { isSet = value.Equals("true", StringComparison.InvariantCultureIgnoreCase) || value.Equals( "yes", StringComparison.InvariantCultureIgnoreCase) || value.Equals("on", StringComparison.InvariantCultureIgnoreCase); } warnIfUnexpected(flagName, expected, isSet); return isSet; } /** * Returns the value for the given flag. * * @param flagName The name of the flag to fetch. * @param expected The value for the flag that is expected when the tests * are run for a full test. If the current value is not the * expected one, you will Get a warning in the test output. * This is so that you do not accidentally leave a flag Set * to a value that prevents Running some tests, thereby * letting you accidentally release code that is not fully * tested. * * @return The value for the flag. */ protected String flagString(String flagName, String expected) { String value = testFlags[(flagName)]; if (value == null) value = ""; warnIfUnexpected(flagName, expected, value); return value; } private void warnIfUnexpected(String flagName, Object expected, Object actual) { if (!actual.Equals(expected)) { System.Console.WriteLine( "WARNING: " + testFile + ": " + "Flag " + flagName + " = \"" + actual + "\" [not \"" + expected + "\"]"); } } } }
// // 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.SiteRecovery; using Microsoft.Azure.Management.SiteRecovery.Models; namespace Microsoft.Azure.Management.SiteRecovery { public static partial class JobOperationsExtensions { /// <summary> /// Cancel the job . /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IJobOperations. /// </param> /// <param name='jobName'> /// Required. Job Name. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static LongRunningOperationResponse BeginCancelling(this IJobOperations operations, string jobName, CustomRequestHeaders customRequestHeaders) { return Task.Factory.StartNew((object s) => { return ((IJobOperations)s).BeginCancellingAsync(jobName, customRequestHeaders); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Cancel the job . /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IJobOperations. /// </param> /// <param name='jobName'> /// Required. Job Name. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static Task<LongRunningOperationResponse> BeginCancellingAsync(this IJobOperations operations, string jobName, CustomRequestHeaders customRequestHeaders) { return operations.BeginCancellingAsync(jobName, customRequestHeaders, CancellationToken.None); } /// <summary> /// Export jobs to blob. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IJobOperations. /// </param> /// <param name='parameters'> /// Required. Job Query Filters /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static LongRunningOperationResponse BeginExporting(this IJobOperations operations, JobQueryParameter parameters, CustomRequestHeaders customRequestHeaders) { return Task.Factory.StartNew((object s) => { return ((IJobOperations)s).BeginExportingAsync(parameters, customRequestHeaders); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Export jobs to blob. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IJobOperations. /// </param> /// <param name='parameters'> /// Required. Job Query Filters /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static Task<LongRunningOperationResponse> BeginExportingAsync(this IJobOperations operations, JobQueryParameter parameters, CustomRequestHeaders customRequestHeaders) { return operations.BeginExportingAsync(parameters, customRequestHeaders, CancellationToken.None); } /// <summary> /// Restart the job . /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IJobOperations. /// </param> /// <param name='jobName'> /// Required. Job Name. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static LongRunningOperationResponse BeginRestarting(this IJobOperations operations, string jobName, CustomRequestHeaders customRequestHeaders) { return Task.Factory.StartNew((object s) => { return ((IJobOperations)s).BeginRestartingAsync(jobName, customRequestHeaders); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Restart the job . /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IJobOperations. /// </param> /// <param name='jobName'> /// Required. Job Name. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static Task<LongRunningOperationResponse> BeginRestartingAsync(this IJobOperations operations, string jobName, CustomRequestHeaders customRequestHeaders) { return operations.BeginRestartingAsync(jobName, customRequestHeaders, CancellationToken.None); } /// <summary> /// Resume the job . /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IJobOperations. /// </param> /// <param name='jobId'> /// Required. Job ID. /// </param> /// <param name='resumeJobParameters'> /// Optional. Resume job parameters. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static LongRunningOperationResponse BeginResuming(this IJobOperations operations, string jobId, ResumeJobParams resumeJobParameters, CustomRequestHeaders customRequestHeaders) { return Task.Factory.StartNew((object s) => { return ((IJobOperations)s).BeginResumingAsync(jobId, resumeJobParameters, customRequestHeaders); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Resume the job . /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IJobOperations. /// </param> /// <param name='jobId'> /// Required. Job ID. /// </param> /// <param name='resumeJobParameters'> /// Optional. Resume job parameters. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static Task<LongRunningOperationResponse> BeginResumingAsync(this IJobOperations operations, string jobId, ResumeJobParams resumeJobParameters, CustomRequestHeaders customRequestHeaders) { return operations.BeginResumingAsync(jobId, resumeJobParameters, customRequestHeaders, CancellationToken.None); } /// <summary> /// Cancel the job . /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IJobOperations. /// </param> /// <param name='jobName'> /// Required. Job Name. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static LongRunningOperationResponse Cancel(this IJobOperations operations, string jobName, CustomRequestHeaders customRequestHeaders) { return Task.Factory.StartNew((object s) => { return ((IJobOperations)s).CancelAsync(jobName, customRequestHeaders); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Cancel the job . /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IJobOperations. /// </param> /// <param name='jobName'> /// Required. Job Name. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static Task<LongRunningOperationResponse> CancelAsync(this IJobOperations operations, string jobName, CustomRequestHeaders customRequestHeaders) { return operations.CancelAsync(jobName, customRequestHeaders, CancellationToken.None); } /// <summary> /// Export jobs to blob. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IJobOperations. /// </param> /// <param name='parameters'> /// Required. Job Query Filters /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static LongRunningOperationResponse Export(this IJobOperations operations, JobQueryParameter parameters, CustomRequestHeaders customRequestHeaders) { return Task.Factory.StartNew((object s) => { return ((IJobOperations)s).ExportAsync(parameters, customRequestHeaders); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Export jobs to blob. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IJobOperations. /// </param> /// <param name='parameters'> /// Required. Job Query Filters /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static Task<LongRunningOperationResponse> ExportAsync(this IJobOperations operations, JobQueryParameter parameters, CustomRequestHeaders customRequestHeaders) { return operations.ExportAsync(parameters, customRequestHeaders, CancellationToken.None); } /// <summary> /// Get the job details. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IJobOperations. /// </param> /// <param name='jobId'> /// Required. Job ID. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// The response model for the Job details object. /// </returns> public static JobResponse Get(this IJobOperations operations, string jobId, CustomRequestHeaders customRequestHeaders) { return Task.Factory.StartNew((object s) => { return ((IJobOperations)s).GetAsync(jobId, customRequestHeaders); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get the job details. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IJobOperations. /// </param> /// <param name='jobId'> /// Required. Job ID. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// The response model for the Job details object. /// </returns> public static Task<JobResponse> GetAsync(this IJobOperations operations, string jobId, CustomRequestHeaders customRequestHeaders) { return operations.GetAsync(jobId, customRequestHeaders, CancellationToken.None); } /// <summary> /// The Get Operation Status operation returns the status of the /// specified operation. After calling an asynchronous operation, you /// can call Get Operation Status to determine whether the operation /// has succeeded, failed, or is still in progress. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IJobOperations. /// </param> /// <param name='operationStatusLink'> /// Required. Location value returned by the Begin operation. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static JobOperationResponse GetCancelStatus(this IJobOperations operations, string operationStatusLink) { return Task.Factory.StartNew((object s) => { return ((IJobOperations)s).GetCancelStatusAsync(operationStatusLink); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The Get Operation Status operation returns the status of the /// specified operation. After calling an asynchronous operation, you /// can call Get Operation Status to determine whether the operation /// has succeeded, failed, or is still in progress. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IJobOperations. /// </param> /// <param name='operationStatusLink'> /// Required. Location value returned by the Begin operation. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static Task<JobOperationResponse> GetCancelStatusAsync(this IJobOperations operations, string operationStatusLink) { return operations.GetCancelStatusAsync(operationStatusLink, CancellationToken.None); } /// <summary> /// The Get Operation Status operation returns the status of the /// specified operation. After calling an asynchronous operation, you /// can call Get Operation Status to determine whether the operation /// has succeeded, failed, or is still in progress. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IJobOperations. /// </param> /// <param name='operationStatusLink'> /// Required. Location value returned by the Begin operation. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static JobOperationResponse GetExportStatus(this IJobOperations operations, string operationStatusLink) { return Task.Factory.StartNew((object s) => { return ((IJobOperations)s).GetExportStatusAsync(operationStatusLink); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The Get Operation Status operation returns the status of the /// specified operation. After calling an asynchronous operation, you /// can call Get Operation Status to determine whether the operation /// has succeeded, failed, or is still in progress. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IJobOperations. /// </param> /// <param name='operationStatusLink'> /// Required. Location value returned by the Begin operation. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static Task<JobOperationResponse> GetExportStatusAsync(this IJobOperations operations, string operationStatusLink) { return operations.GetExportStatusAsync(operationStatusLink, CancellationToken.None); } /// <summary> /// The Get Operation Status operation returns the status of the /// specified operation. After calling an asynchronous operation, you /// can call Get Operation Status to determine whether the operation /// has succeeded, failed, or is still in progress. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IJobOperations. /// </param> /// <param name='operationStatusLink'> /// Required. Location value returned by the Begin operation. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static JobOperationResponse GetRestartStatus(this IJobOperations operations, string operationStatusLink) { return Task.Factory.StartNew((object s) => { return ((IJobOperations)s).GetRestartStatusAsync(operationStatusLink); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The Get Operation Status operation returns the status of the /// specified operation. After calling an asynchronous operation, you /// can call Get Operation Status to determine whether the operation /// has succeeded, failed, or is still in progress. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IJobOperations. /// </param> /// <param name='operationStatusLink'> /// Required. Location value returned by the Begin operation. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static Task<JobOperationResponse> GetRestartStatusAsync(this IJobOperations operations, string operationStatusLink) { return operations.GetRestartStatusAsync(operationStatusLink, CancellationToken.None); } /// <summary> /// The Get Operation Status operation returns the status of the /// specified operation. After calling an asynchronous operation, you /// can call Get Operation Status to determine whether the operation /// has succeeded, failed, or is still in progress. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IJobOperations. /// </param> /// <param name='operationStatusLink'> /// Required. Location value returned by the Begin operation. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static JobOperationResponse GetResumeStatus(this IJobOperations operations, string operationStatusLink) { return Task.Factory.StartNew((object s) => { return ((IJobOperations)s).GetResumeStatusAsync(operationStatusLink); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// The Get Operation Status operation returns the status of the /// specified operation. After calling an asynchronous operation, you /// can call Get Operation Status to determine whether the operation /// has succeeded, failed, or is still in progress. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IJobOperations. /// </param> /// <param name='operationStatusLink'> /// Required. Location value returned by the Begin operation. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static Task<JobOperationResponse> GetResumeStatusAsync(this IJobOperations operations, string operationStatusLink) { return operations.GetResumeStatusAsync(operationStatusLink, CancellationToken.None); } /// <summary> /// Get the list of all jobs. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IJobOperations. /// </param> /// <param name='parameters'> /// Optional. Job query parameter. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// The response model for the list Jobs operation. /// </returns> public static JobListResponse List(this IJobOperations operations, JobQueryParameter parameters, CustomRequestHeaders customRequestHeaders) { return Task.Factory.StartNew((object s) => { return ((IJobOperations)s).ListAsync(parameters, customRequestHeaders); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get the list of all jobs. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IJobOperations. /// </param> /// <param name='parameters'> /// Optional. Job query parameter. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// The response model for the list Jobs operation. /// </returns> public static Task<JobListResponse> ListAsync(this IJobOperations operations, JobQueryParameter parameters, CustomRequestHeaders customRequestHeaders) { return operations.ListAsync(parameters, customRequestHeaders, CancellationToken.None); } /// <summary> /// Restart the job . /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IJobOperations. /// </param> /// <param name='jobName'> /// Required. Job Name. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static LongRunningOperationResponse Restart(this IJobOperations operations, string jobName, CustomRequestHeaders customRequestHeaders) { return Task.Factory.StartNew((object s) => { return ((IJobOperations)s).RestartAsync(jobName, customRequestHeaders); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Restart the job . /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IJobOperations. /// </param> /// <param name='jobName'> /// Required. Job Name. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static Task<LongRunningOperationResponse> RestartAsync(this IJobOperations operations, string jobName, CustomRequestHeaders customRequestHeaders) { return operations.RestartAsync(jobName, customRequestHeaders, CancellationToken.None); } /// <summary> /// Resume the job . /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IJobOperations. /// </param> /// <param name='jobId'> /// Required. Job ID. /// </param> /// <param name='resumeJobParameters'> /// Optional. Resume job parameters. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static LongRunningOperationResponse Resume(this IJobOperations operations, string jobId, ResumeJobParams resumeJobParameters, CustomRequestHeaders customRequestHeaders) { return Task.Factory.StartNew((object s) => { return ((IJobOperations)s).ResumeAsync(jobId, resumeJobParameters, customRequestHeaders); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Resume the job . /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.SiteRecovery.IJobOperations. /// </param> /// <param name='jobId'> /// Required. Job ID. /// </param> /// <param name='resumeJobParameters'> /// Optional. Resume job parameters. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static Task<LongRunningOperationResponse> ResumeAsync(this IJobOperations operations, string jobId, ResumeJobParams resumeJobParameters, CustomRequestHeaders customRequestHeaders) { return operations.ResumeAsync(jobId, resumeJobParameters, customRequestHeaders, CancellationToken.None); } } }
using System; using System.Collections.Generic; using System.Text; using ZombieSmashers.Particles; using Microsoft.Xna.Framework.Net; using Microsoft.Xna.Framework; namespace ZombieSmashers.net { public class NetGame { NetPlay netPlay; public const byte MSG_SERVER_DATA = 0; public const byte MSG_CLIENT_DATA = 1; public const byte MSG_CHARACTER = 2; public const byte MSG_PARTICLE = 3; public const byte MSG_END = 4; PacketWriter writer; PacketReader reader; float frame; public float FrameTime; public NetGame(NetPlay _netPlay) { netPlay = _netPlay; writer = new PacketWriter(); reader = new PacketReader(); } public void Update(Character[] c, ParticleManager pMan) { LocalNetworkGamer gamer = GetGamer(); if (gamer == null) return; frame -= FrameTime; if (frame < 0f) { frame = .05f; if (netPlay.Hosting) { if (c[0] != null) { writer.Write(MSG_SERVER_DATA); c[0].WriteToNet(writer); for (int i = 2; i < c.Length; i++) if (c[i] != null) c[i].WriteToNet(writer); pMan.NetWriteParticles(writer); writer.Write(MSG_END); gamer.SendData(writer, SendDataOptions.None); } } if (netPlay.Joined) { if (c[1] != null) { writer.Write(MSG_CLIENT_DATA); c[1].WriteToNet(writer); pMan.NetWriteParticles(writer); writer.Write(MSG_END); gamer.SendData(writer, SendDataOptions.None); } } } if (gamer.IsDataAvailable) { NetworkGamer sender; gamer.ReceiveData(reader, out sender); if (!sender.IsLocal) { byte type = reader.ReadByte(); if (netPlay.Joined) { for (int i = 0; i < c.Length; i++) if (i != 1) if (c[i] != null) c[i].ReceivedNetUpdate = false; } bool end = false; while (!end) { byte msg = reader.ReadByte(); switch (msg) { case MSG_END: end = true; break; case MSG_CHARACTER: int defID = NetPacker.SbyteToInt(reader.ReadSByte()); int team = NetPacker.SbyteToInt(reader.ReadSByte()); int ID = NetPacker.SbyteToInt(reader.ReadSByte()); if (c[ID] == null) { c[ID] = new Character(new Vector2(), Game1.charDef[defID], ID, team); } c[ID].ReadFromNet(reader); c[ID].ReceivedNetUpdate = true; break; case MSG_PARTICLE: byte pType = reader.ReadByte(); bool bg = reader.ReadBoolean(); switch (pType) { case Particle.PARTICLE_NONE: // break; case Particle.PARTICLE_BLOOD: pMan.AddParticle(new Blood(reader), bg, true); break; case Particle.PARTICLE_BLOOD_DUST: pMan.AddParticle(new BloodDust(reader), bg, true); break; case Particle.PARTICLE_BULLET: pMan.AddParticle(new Bullet(reader), bg, true); break; case Particle.PARTICLE_FIRE: pMan.AddParticle(new Fire(reader), bg, true); break; case Particle.PARTICLE_FOG: pMan.AddParticle(new Fog(reader), bg, true); break; case Particle.PARTICLE_HEAT: pMan.AddParticle(new Heat(reader), bg, true); break; case Particle.PARTICLE_HIT: pMan.AddParticle(new Hit(reader), bg, true); break; case Particle.PARTICLE_MUZZLEFLASH: pMan.AddParticle(new MuzzleFlash(reader), bg, true); break; case Particle.PARTICLE_ROCKET: pMan.AddParticle(new Rocket(reader), bg, true); break; case Particle.PARTICLE_SHOCKWAVE: pMan.AddParticle(new Shockwave(reader), bg, true); break; case Particle.PARTICLE_SMOKE: pMan.AddParticle(new Smoke(reader), bg, true); break; default: //Error! break; } break; } } if (netPlay.Joined) { for (int i = 0; i < c.Length; i++) if (i != 1) if (c[i] != null) if (c[i].ReceivedNetUpdate == false) { c[i] = null; } } } } } private LocalNetworkGamer GetGamer() { foreach (LocalNetworkGamer gamer in netPlay.NetSession.LocalGamers) if (gamer.SignedInGamer.PlayerIndex == PlayerIndex.One) return gamer; return null; } } }
//----------------------------------------------------------------------- // <copyright file="BindingSourceRefresh.cs" company="Marimer LLC"> // Copyright (c) Marimer LLC. All rights reserved. // Website: http://www.lhotka.net/cslanet/ // </copyright> // <summary>BindingSourceRefresh contains functionality for refreshing the data bound to controls on Host as well as a mechiaism for catching data</summary> //----------------------------------------------------------------------- using System; using System.Collections.Generic; using System.ComponentModel; using System.Windows.Forms; // code from Bill McCarthy // http://msmvps.com/bill/archive/2005/10/05/69012.aspx // used with permission namespace MvvmFx.Controls.WinForms { /// <summary> /// BindingSourceRefresh contains functionality for refreshing the data bound to controls on Host as well as a mechiaism for catching data /// binding errors that occur in Host. /// </summary> /// <remarks>Windows Forms extender control that resolves the /// data refresh issue with data bound detail controls /// as discussed in Chapter 5.</remarks> [DesignerCategory("")] [ProvideProperty("ReadValuesOnChange", typeof (BindingSource))] public class BindingSourceRefresh : Component, IExtenderProvider, ISupportInitialize { #region Fields private readonly Dictionary<BindingSource, bool> _sources = new Dictionary<BindingSource, bool>(); #endregion #region Events /// <summary> /// BindingError event is raised when a data binding error occurs due to a exception. /// </summary> public event BindingErrorEventHandler BindingError; #endregion #region Constructors /// <summary> /// Constructor creates a new BindingSourceRefresh component then initialises all the different sub components. /// </summary> public BindingSourceRefresh() { InitializeComponent(); } /// <summary> /// Constructor creates a new BindingSourceRefresh component, adds the component to the container supplied before initialising all the different sub components. /// </summary> /// <param name="container">The container the component is to be added to.</param> public BindingSourceRefresh(IContainer container) { container.Add(this); InitializeComponent(); } #endregion #region Designer Functionality /// <summary> /// Required designer variable. /// </summary> private IContainer components; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { components = new System.ComponentModel.Container(); } #endregion #endregion #region Public Methods /// <summary> /// CanExtend() returns true if extendee is a binding source. /// </summary> /// <param name="extendee">The control to be extended.</param> /// <returns>True if the control is a binding source, else false.</returns> public bool CanExtend(object extendee) { return (extendee is BindingSource); } /// <summary> /// GetReadValuesOnChange() gets the value of the custom ReadValuesOnChange extender property added to extended controls. /// property added to extended controls. /// </summary> /// <param name="source">Control being extended.</param> [Category("Behavior")] public bool GetReadValuesOnChange(BindingSource source) { bool result; if (_sources.TryGetValue(source, out result)) return result; else return false; } /// <summary> /// SetReadValuesOnChange() sets the value of the custom ReadValuesOnChange extender /// property added to extended controls. /// </summary> /// <param name="source">Control being extended.</param> /// <param name="value">New value of property.</param> /// <remarks></remarks> [Category("Behavior")] public void SetReadValuesOnChange( BindingSource source, bool value) { _sources[source] = value; if (!_isInitialising) { RegisterControlEvents(source, value); } } #endregion #region Properties /// <summary> /// Not in use - kept for backward compatibility /// </summary> [Browsable(false)] [DefaultValue(null)] public ContainerControl Host { get; set; } /// <summary> /// Forces the binding to re-read after an exception is thrown when changing the binding value /// </summary> [Browsable(true)] [DefaultValue(false)] public bool RefreshOnException { get; set; } #endregion #region Private Methods /// <summary> /// RegisterControlEvents() registers all the relevant events for the container control supplied and also to all child controls /// in the oontainer control. /// </summary> /// <param name="container">The control (including child controls) to have the refresh events registered.</param> /// <param name="register">True to register the events, false to unregister them.</param> private void RegisterControlEvents(ICurrencyManagerProvider container, bool register) { var currencyManager = container.CurrencyManager; // If we are to register the events the do so. if (register) { currencyManager.Bindings.CollectionChanged += Bindings_CollectionChanged; currencyManager.Bindings.CollectionChanging += Bindings_CollectionChanging; } // Else unregister them. else { currencyManager.Bindings.CollectionChanged -= Bindings_CollectionChanged; currencyManager.Bindings.CollectionChanging += Bindings_CollectionChanging; } // Reigster the binding complete events for the currencymanagers bindings. RegisterBindingEvents(currencyManager.Bindings, register); } /// <summary> /// Registers the control events. /// </summary> /// <param name="source">The source.</param> /// <param name="register">if set to <c>true</c> [register].</param> private void RegisterBindingEvents(BindingsCollection source, bool register) { foreach (Binding binding in source) { RegisterBindingEvent(binding, register); } } /// <summary> /// Registers the binding event. /// </summary> /// <param name="register">if set to <c>true</c> [register].</param> /// <param name="binding">The binding.</param> private void RegisterBindingEvent(Binding binding, bool register) { if (register) { binding.BindingComplete += Control_BindingComplete; } else { binding.BindingComplete -= Control_BindingComplete; } } #endregion #region Event Methods /// <summary> /// Handles the CollectionChanging event of the Bindings control. /// /// Remove event hooks for element or entire list depending on CollectionChangeAction. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.ComponentModel.CollectionChangeEventArgs"/> instance containing the event data.</param> private void Bindings_CollectionChanging(object sender, CollectionChangeEventArgs e) { switch (e.Action) { case CollectionChangeAction.Refresh: // remove events for entire list RegisterBindingEvents((BindingsCollection) sender, false); break; case CollectionChangeAction.Add: // adding new element - remove events for element RegisterBindingEvent((Binding) e.Element, false); break; case CollectionChangeAction.Remove: // removing element - remove events for element RegisterBindingEvent((Binding) e.Element, false); break; } } /// <summary> /// Handles the CollectionChanged event of the Bindings control. /// /// Add event hooks for element or entire list depending on CollectionChangeAction. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.ComponentModel.CollectionChangeEventArgs"/> instance containing the event data.</param> private void Bindings_CollectionChanged(object sender, CollectionChangeEventArgs e) { switch (e.Action) { case CollectionChangeAction.Refresh: // refresh entire list - add event to all items RegisterBindingEvents((BindingsCollection) sender, true); break; case CollectionChangeAction.Add: // new element added - add event to element RegisterBindingEvent((Binding) e.Element, true); break; case CollectionChangeAction.Remove: // element has been removed - do nothing break; } } /// <summary> /// Control_BindingComplete() is a event driven routine triggered when one of the control's bindings has been completed. /// Control_BindingComplete() simply validates the result where if the result was a exception then the BindingError /// event is raised, else if the binding was a successful data source update and we are to re-read the value on changed then /// the binding value is reread into the control. /// </summary> /// <param name="sender">The object that triggered the event.</param> /// <param name="e">The event arguments.</param> private void Control_BindingComplete(object sender, BindingCompleteEventArgs e) { switch (e.BindingCompleteState) { case BindingCompleteState.Exception: if ((RefreshOnException) && e.Binding.DataSource is BindingSource && GetReadValuesOnChange((BindingSource) e.Binding.DataSource)) { e.Binding.ReadValue(); } if (BindingError != null) { BindingError(this, new BindingErrorEventArgs(e.Binding, e.Exception)); } break; default: if ((e.BindingCompleteContext == BindingCompleteContext.DataSourceUpdate) && e.Binding.DataSource is BindingSource && GetReadValuesOnChange((BindingSource) e.Binding.DataSource)) { e.Binding.ReadValue(); } break; } } #endregion #region ISupportInitialize Interface private bool _isInitialising; /// <summary> /// BeginInit() is called when the component is starting to be initialised. BeginInit() simply sets the initialisation flag to true. /// </summary> void ISupportInitialize.BeginInit() { _isInitialising = true; } /// <summary> /// EndInit() is called when the component has finished being initialised. EndInt() sets the initialise flag to false then runs /// through registering all the different events that the component needs to hook into in Host. /// </summary> void ISupportInitialize.EndInit() { _isInitialising = false; foreach (var source in _sources) { if (source.Value) RegisterControlEvents(source.Key, true); } } #endregion } #region Delegates /// <summary> /// BindingErrorEventHandler delegates is the event handling definition for handling data binding errors that occurred due to exceptions. /// </summary> /// <param name="sender">The object that triggered the event.</param> /// <param name="e">The event arguments.</param> public delegate void BindingErrorEventHandler(object sender, BindingErrorEventArgs e); #endregion #region BindingErrorEventArgs Class /// <summary> /// BindingErrorEventArgs defines the event arguments for reporting a data binding error due to a exception. /// </summary> public class BindingErrorEventArgs : EventArgs { #region Property Fields private Exception _exception; private Binding _binding; #endregion #region Properties /// <summary> /// Exception gets the exception that caused the binding error. /// </summary> public Exception Exception { get { return (_exception); } } /// <summary> /// Binding gets the binding that caused the exception. /// </summary> public Binding Binding { get { return (_binding); } } #endregion #region Constructors /// <summary> /// Constructor creates a new BindingErrorEventArgs object instance using the information specified. /// </summary> /// <param name="binding">The binding that caused th exception.</param> /// <param name="exception">The exception that caused the error.</param> public BindingErrorEventArgs(Binding binding, Exception exception) { _binding = binding; _exception = exception; } #endregion } #endregion }
using System; #if FRB_MDX using Microsoft.DirectX; #else #endif using System.Collections.Generic; using FlatRedBall.Graphics; using FlatRedBall.ManagedSpriteGroups; namespace FlatRedBall.Gui { /// <summary> /// Summary description for ComboBox. /// </summary> public class ComboBox : Window { #region Fields Button mDropDownButton; TextBox mSelectionDisplay; ListBox mListBox; List<string> stringArray = new List<string>(); public object SelectedObject; object mPreviousSelectedObject; bool mExpandOnTextBoxClick; //bool mStretchListBoxToContentWidth; #endregion #region Properties public CollapseItem this[int i] { get { return mListBox.mItems[i]; } } public bool AllowTypingInTextBox { get { return mSelectionDisplay.TakingInput; } set { mSelectionDisplay.TakingInput = value; } } public int Count { get { return mListBox.mItems.Count; } } public override bool Enabled { get { return base.Enabled; } set { base.Enabled = value; // Vic says: I added this on September 1, 2009 // to make the UI change if disabled. Undo this if it // causes problems. if (mSelectionDisplay != null && mDropDownButton != null) { mSelectionDisplay.Enabled = value; mDropDownButton.Enabled = value; } } } public bool ExpandOnTextBoxClick { get { return mExpandOnTextBoxClick; } set { if (mExpandOnTextBoxClick == false && value == true) mSelectionDisplay.Click += new GuiMessage(OnDropDownButtonClick); else if (mExpandOnTextBoxClick == true && value == false) mSelectionDisplay.Click -= new GuiMessage(OnDropDownButtonClick); mExpandOnTextBoxClick = value; } } public bool HighlightOnRollOver { get { return mListBox.HighlightOnRollOver; } set { mListBox.HighlightOnRollOver = value; } } public override bool IsWindowOrChildrenReceivingInput { get { { return this.mListBox.Visible || base.IsWindowOrChildrenReceivingInput; } } } public object PreviousSelectedObject { get { return mPreviousSelectedObject; } } public override float ScaleX { get{ return mScaleX; } set { mScaleX = value; mDropDownButton.SetPositionTL(2*value - 1.3f, ScaleY); mSelectionDisplay.ScaleX = value - 1.4f; mSelectionDisplay.SetPositionTL(ScaleX -.9f, ScaleY); if (mListBox != null) { mListBox.ScaleX = value; } } } public ListBox.Sorting SortingStyle { get { return mListBox.SortingStyle; } set { mListBox.SortingStyle = value; } } public string Text { get{ return mSelectionDisplay.Text; } set { mSelectionDisplay.Text = value; } } #endregion #region Events public event GuiMessage ItemClick = null; public event GuiMessage TextChange = null; #endregion #region Delegate Methods /// <summary> /// Event clicked when the dropDownButton is clicked. If the ListBox is not visible /// it will appear. /// </summary> /// <param name="callingWindow"></param> void OnDropDownButtonClick(Window callingWindow) { if (mListBox.Visible) return; // The ListBox is not visible, so "expand" it. GuiManager.AddPerishableWindow(mListBox); mListBox.Visible = true; if (mListBox.SpriteFrame != null) { SpriteManager.AddSpriteFrame(mListBox.SpriteFrame); } // listBox.SetPositionTL(ScaleX, ScaleY + 4); mListBox.SetScaleToContents(ScaleX); mListBox.SetPositionTL(ScaleX, ScaleY + mListBox.ScaleY + 1); mListBox.HighlightOnRollOver = true; mListBox.UpdateDependencies(); float maximumScale = GuiManager.YEdge - (MenuStrip.MenuStripHeight / 2.0f); if (mListBox.ScaleY > maximumScale) { mListBox.ScrollBarVisible = true; mListBox.ScaleY = maximumScale; } if (mListBox.WorldUnitY - mListBox.ScaleY < -GuiManager.Camera.YEdge) mListBox.Y -= -GuiManager.Camera.YEdge - (mListBox.WorldUnitY - mListBox.ScaleY); if (mListBox.WorldUnitX + mListBox.ScaleX > GuiManager.Camera.XEdge) mListBox.X -= (mListBox.WorldUnitX + mListBox.ScaleX) - GuiManager.Camera.XEdge; if (mListBox.WorldUnitX - mListBox.ScaleX < -GuiManager.Camera.XEdge) mListBox.X += -GuiManager.Camera.XEdge - (mListBox.WorldUnitX - mListBox.ScaleX); mListBox.HighlightItem(mSelectionDisplay.Text); } void OnListBoxClicked(Window callingWindow) { mSelectionDisplay.Text = ""; List<string> a = ((ListBox)callingWindow).GetHighlighted(); if (a.Count != 0) { mPreviousSelectedObject = SelectedObject; mSelectionDisplay.Text = a[0]; this.SelectedObject = ((ListBox)callingWindow).GetHighlightedObject()[0]; } if (ItemClick != null) ItemClick(this); GuiManager.RemoveWindow(callingWindow, true); callingWindow.Visible = false; } void OnMouseWheelScroll(Window callingWindow) { if (mListBox.Items.Count == 0) return; int index = GetItemIndex(Text); if (mCursor.ZVelocity > 0) { index--; } else { index++; } index %= mListBox.Items.Count; if (index == -1) { index = mListBox.Items.Count - 1; } else if (index < -1) { index = 0; } mSelectionDisplay.Text = mListBox.Items[index].Text; mPreviousSelectedObject = SelectedObject; this.SelectedObject = mListBox.Items[index].ReferenceObject; if (ItemClick != null) ItemClick(this); } void RaiseTextChange(Window callingWindow) { if (TextChange != null) { TextChange(this); } } #endregion #region Methods #region Constructors public ComboBox(Cursor cursor) : base(cursor) { #region Create the TextBox (mSelectionDisplay) mSelectionDisplay = new TextBox(mCursor); AddWindow(mSelectionDisplay); mSelectionDisplay.TakingInput = false; mSelectionDisplay.fixedLength = false; //mStretchListBoxToContentWidth = true; #endregion #region Create drop-down button mDropDownButton = new Button(mCursor); AddWindow(mDropDownButton); // Not sure why this is here. Commented out July 31 2007 //dropDownButton.mSprite.RotationZ = (float)System.Math.PI; mDropDownButton.ScaleX = .9f; mDropDownButton.Click += new GuiMessage(OnDropDownButtonClick); #endregion this.ScaleY = 1.4f; SelectedObject = null; this.ScaleX = 4; mListBox = new ListBox(mCursor); AddWindow(mListBox); this.RemoveWindow(mListBox); // just a quick way to have a list box initialized for us, but not keep it on this window mListBox.SetPositionTL(ScaleX, ScaleY + 2); mListBox.Visible = false; mListBox.ScrollBarVisible = false; mListBox.Click += new GuiMessage(OnListBoxClicked); MouseWheelScroll += OnMouseWheelScroll; mSelectionDisplay.MouseWheelScroll += OnMouseWheelScroll; mDropDownButton.MouseWheelScroll += OnMouseWheelScroll; mSelectionDisplay.LosingFocus += RaiseTextChange; } // public ComboBox(SpriteFrame baseSF, SpriteFrame textBoxSF, // string buttonTexture, // Cursor cursor, Camera camera, string contentManagerName) // : base(baseSF, cursor) // { //// baseSF.colorOperation = Microsoft.DirectX.Direct3D.TextureOperation.Add; //// baseSF.tintBlue = 255; // mSelectionDisplay = base.AddTextBox(textBoxSF, "redball.bmp", camera, contentManagerName); // mSelectionDisplay.TakingInput = false; // mSelectionDisplay.fixedLength = false; // mSelectionDisplay.SpriteFrame.Z = baseSF.Z - .001f; // mSelectionDisplay.SpriteFrame.ScaleY = baseSF.ScaleY - .2f; // mStretchListBoxToContentWidth = false; // mDropDownButton = base.AddButton(buttonTexture, GuiManager.InternalGuiContentManagerName); // mDropDownButton.Click += new GuiMessage(OnDropDownButtonClick); // mDropDownButton.SpriteFrame.Z = baseSF.Z - .001f; // mDropDownButton.SpriteFrame.ScaleX = mDropDownButton.SpriteFrame.ScaleY = baseSF.ScaleY - .2f; // mName = baseSF.Name; // mListBox = this.AddListBox(baseSF.Clone(), null, null, null, null, null); // mListBox.SpriteFrame.Name = baseSF.Name + "ListBoxSpriteFrame"; // mListBox.SpriteFrame.UpdateInternalSpriteNames(); // SpriteManager.AddSpriteFrame(mListBox.SpriteFrame); // mListBox.SpriteFrame.Z = baseSF.Z - .1f; // this.RemoveWindow(mListBox); // just a quick way to have a list box initialized for us, but not keep it on this window // mListBox.SetPositionTL(ScaleX, ScaleY + 2); // mListBox.Visible = false; // mListBox.ScrollBarVisible = false; // mListBox.Click += new GuiMessage(OnListBoxClicked); // // I have no clue why this is in here. //// listBox.sf.xVelocity = 1; // SelectedObject = null; // this.ScaleX = SpriteFrame.ScaleX; // } // public ComboBox(SpriteFrame baseSF, SpriteFrame textBoxSF, SpriteFrame buttonSpriteFrame, // Cursor cursor, Camera camera) // : base(baseSF, cursor) // { // // baseSF.colorOperation = Microsoft.DirectX.Direct3D.TextureOperation.Add; // // baseSF.tintBlue = 255; // mSelectionDisplay = base.AddTextBox(textBoxSF, "redball.bmp", camera, GuiManager.InternalGuiContentManagerName); // mSelectionDisplay.TakingInput = false; // mSelectionDisplay.fixedLength = false; // mSelectionDisplay.SpriteFrame.Z = baseSF.Z - .001f; // mSelectionDisplay.SpriteFrame.ScaleY = baseSF.ScaleY - .2f; // mStretchListBoxToContentWidth = false; // mDropDownButton = base.AddButton(buttonSpriteFrame); // mDropDownButton.Click += new GuiMessage(OnDropDownButtonClick); // mDropDownButton.SpriteFrame.Z = baseSF.Z - .001f; //// dropDownButton.sf.ScaleX = dropDownButton.sf.ScaleY = baseSF.ScaleY - .2f; // mName = baseSF.Name; // mListBox = this.AddListBox(baseSF.Clone(), null, null, null, null, null); // mListBox.SpriteFrame.Name = baseSF.Name + "ListBoxSpriteFrame"; // mListBox.SpriteFrame.UpdateInternalSpriteNames(); // SpriteManager.AddSpriteFrame(mListBox.SpriteFrame); // mListBox.SpriteFrame.Z = baseSF.Z - .1f; // this.RemoveWindow(mListBox); // just a quick way to have a list box initialized for us, but not keep it on this window // mListBox.SetPositionTL(ScaleX, ScaleY + 2); // mListBox.Visible = false; // mListBox.ScrollBarVisible = false; // mListBox.Click += new GuiMessage(OnListBoxClicked); // // I have no clue why this was here //// listBox.sf.xVelocity = 1; // SelectedObject = null; // this.ScaleX = SpriteFrame.ScaleX; // } #endregion #region Public Methods public void AddItem(string stringToAdd) { mListBox.AddItem(stringToAdd); } public void AddItem(string stringToAdd, object referenceObject) { mListBox.AddItem(stringToAdd, referenceObject); } public void AddItemsFromEnum(Type enumType) { #if XBOX360 || WINDOWS_PHONE throw new NotImplementedException(); #else Clear(); string[] availableValues = Enum.GetNames(enumType); Array array = Enum.GetValues(enumType); for(int i = 0; i < array.Length; i++) { string s = availableValues[i]; AddItem(s, array.GetValue(i)); } #endif } public void CallOnItemClick() { if(this.ItemClick != null) ItemClick(this); } public void Clear() { mListBox.Clear(); } public bool ContainsText(string textToSearchFor) { foreach (CollapseItem ci in mListBox.mItems) { if (ci.Text == textToSearchFor) { return true; } } return false; } public bool ContainsObject(object objectToSearchFor) { foreach (CollapseItem ci in mListBox.mItems) { if (ci.ReferenceObject == objectToSearchFor) { return true; } } return false; } public bool ContainsObject(string objectToSearchFor) { foreach (CollapseItem ci in mListBox.mItems) { if (ci.ReferenceObject as string == objectToSearchFor) { return true; } } return false; } public CollapseItem FindItemByText(string textToSearchFor) { foreach (CollapseItem ci in mListBox.mItems) { if (ci.Text == textToSearchFor) { return ci; } } return null; } public int GetItemIndex(string text) { CollapseItem item = mListBox.GetItemByName(text); if (item != null) { return mListBox.Items.IndexOf(item); } else { return -1; } } public void InsertItem(int index, string stringToAdd) { mListBox.InsertItem(index, stringToAdd); } public void InsertItem(int index, string stringToAdd, object referenceObject) { mListBox.InsertItem(index, stringToAdd, referenceObject); } public void RemoveAt(int index) { mListBox.RemoveItemAt(index); } public void SelectItem(int index) { mSelectionDisplay.Text = mListBox.mItems[index].Text; mPreviousSelectedObject = SelectedObject; this.SelectedObject = mListBox.mItems[index].ReferenceObject; if (ItemClick != null) ItemClick(this); } public void SelectItemNoCall(int index) { mSelectionDisplay.Text = mListBox.mItems[index].Text; mPreviousSelectedObject = SelectedObject; this.SelectedObject = mListBox.mItems[index].ReferenceObject; } public void SelectItemByObject(object referenceObject) { foreach (CollapseItem ci in mListBox.mItems) { if (ci.ReferenceObject == referenceObject) { mSelectionDisplay.Text = ci.Text; mPreviousSelectedObject = SelectedObject; SelectedObject = ci.ReferenceObject; break; } } if (ItemClick != null) ItemClick(this); } public void SelectItemByObject(string referenceObject) { foreach (CollapseItem ci in mListBox.mItems) { if (ci.ReferenceObject as string == referenceObject) { mSelectionDisplay.Text = ci.Text; mPreviousSelectedObject = SelectedObject; SelectedObject = ci.ReferenceObject; break; } } if (ItemClick != null) ItemClick(this); } public void SelectItemByObjectNoCall(object referenceObject) { foreach (CollapseItem ci in mListBox.mItems) { if (ci.ReferenceObject == referenceObject) { mSelectionDisplay.Text = ci.Text; mPreviousSelectedObject = SelectedObject; SelectedObject = ci.ReferenceObject; break; } } } public void SelectItemByText(string itemText) { foreach (CollapseItem ci in mListBox.mItems) { if (ci.Text == itemText) { mSelectionDisplay.Text = ci.Text; mPreviousSelectedObject = SelectedObject; SelectedObject = ci.ReferenceObject; break; } } if (ItemClick != null) ItemClick(this); } public void SelectItemByTextNoCall(string itemText) { foreach (CollapseItem ci in mListBox.mItems) { if (ci.Text == itemText) { mSelectionDisplay.Text = ci.Text; mPreviousSelectedObject = SelectedObject; SelectedObject = ci.ReferenceObject; break; } } } #endregion #region Internal Methods internal override void Destroy() { base.Destroy(); this.mListBox.Destroy(); } internal protected override void Destroy(bool keepEvents) { base.Destroy(keepEvents); mListBox.Destroy(keepEvents); } #endregion #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.Net.Sockets; using Xunit; namespace System.Net.Primitives.Functional.Tests { public static class IPAddressTest { private const long MinAddress = 0; private const long MaxAddress = 0xFFFFFFFF; private const long MinScopeId = 0; private const long MaxScopeId = 0xFFFFFFFF; private static byte[] ipV6AddressBytes1 = new byte[] { 0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70, 0x80, 0x90, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16 }; private static byte[] ipV6AddressBytes2 = new byte[] { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16 }; private static IPAddress IPV4Address() { return IPAddress.Parse("192.168.0.9"); } private static IPAddress IPV6Address1() { return new IPAddress(ipV6AddressBytes1); } private static IPAddress IPV6Address2() { return new IPAddress(ipV6AddressBytes2); } [Theory] [InlineData(MinAddress, new byte[] { 0, 0, 0, 0 })] [InlineData(MaxAddress, new byte[] { 0xFF, 0xFF, 0xFF, 0xFF })] [InlineData(0x2414188f, new byte[] { 0x8f, 0x18, 0x14, 0x24 })] [InlineData(0xFF, new byte[] { 0xFF, 0, 0, 0 })] [InlineData(0xFF00FF, new byte[] { 0xFF, 0, 0xFF, 0 })] [InlineData(0xFF00FF00, new byte[] { 0, 0xFF, 0, 0xFF })] public static void Ctor_Long_Success(long address, byte[] expectedBytes) { IPAddress ip = new IPAddress(address); Assert.Equal(expectedBytes, ip.GetAddressBytes()); Assert.Equal(AddressFamily.InterNetwork, ip.AddressFamily); } [Theory] [InlineData(MinAddress - 1)] [InlineData(MaxAddress + 1)] public static void Ctor_Long_Invalid(long address) { Assert.Throws<ArgumentOutOfRangeException>("newAddress", () => new IPAddress(address)); } [Theory] [MemberData(nameof(AddressBytesAndFamilies))] public static void Ctor_Bytes_Success(byte[] address, AddressFamily expectedFamily) { IPAddress ip = new IPAddress(address); Assert.Equal(address, ip.GetAddressBytes()); Assert.Equal(expectedFamily, ip.AddressFamily); } public static object[][] AddressBytesAndFamilies = { new object[] { new byte[] { 0x8f, 0x18, 0x14, 0x24 }, AddressFamily.InterNetwork }, new object[] { ipV6AddressBytes1, AddressFamily.InterNetworkV6 }, new object[] { ipV6AddressBytes2, AddressFamily.InterNetworkV6 } }; [Fact] public static void Ctor_Bytes_Invalid() { Assert.Throws<ArgumentNullException>("address", () => new IPAddress(null)); Assert.Throws<ArgumentException>("address", () => new IPAddress(new byte[] { 0x01, 0x01, 0x02 })); } [Theory] [MemberData(nameof(IPv6AddressBytesAndScopeIds))] public static void Ctor_BytesScopeId_Success(byte[] address, long scopeId) { IPAddress ip = new IPAddress(address, scopeId); Assert.Equal(address, ip.GetAddressBytes()); Assert.Equal(scopeId, ip.ScopeId); Assert.Equal(AddressFamily.InterNetworkV6, ip.AddressFamily); } public static IEnumerable<object[]> IPv6AddressBytesAndScopeIds { get { foreach (long scopeId in new long[] { MinScopeId, MaxScopeId, 500 }) { yield return new object[] { ipV6AddressBytes1, scopeId }; yield return new object[] { ipV6AddressBytes2, scopeId }; } } } [Fact] public static void Ctor_BytesScopeId_Invalid() { Assert.Throws<ArgumentNullException>("address", () => new IPAddress(null, 500)); Assert.Throws<ArgumentException>("address", () => new IPAddress(new byte[] { 0x01, 0x01, 0x02 }, 500)); Assert.Throws<ArgumentOutOfRangeException>("scopeid", () => new IPAddress(ipV6AddressBytes1, MinScopeId - 1)); Assert.Throws<ArgumentOutOfRangeException>("scopeid", () => new IPAddress(ipV6AddressBytes1, MaxScopeId + 1)); } [Theory] [InlineData("192.168.0.1", "192.168.0.1")] //IpV4 [InlineData("Fe08::1", "fe08::1")] //IpV6... [InlineData("[Fe08::1]", "fe08::1")] [InlineData("[Fe08::1]:80", "fe08::1")] //Drop port [InlineData("[Fe08::1]:0xFA", "fe08::1")] //Drop hex port [InlineData("Fe08::1%13542", "fe08::1%13542")] //With scope id public static void Parse_String_Success(string ipString, string expected) { Assert.Equal(expected, IPAddress.Parse(ipString).ToString()); } [Theory] [InlineData("")] //Empty string [InlineData("192.168.0.0/16")] //IpV4: Invalid format [InlineData("192.168.0.0:80")] //IpV4: Port included [InlineData("Fe08::1]")] //IpV6: No leading bracket [InlineData("[Fe08::1")] //IpV6: No trailing bracket [InlineData("[Fe08::1]:80Z")] //IpV6: Invalid port [InlineData("Fe08::/64")] //IpV6: Subnet fail public static void Parse_String_Invalid(string ipString) { Assert.Throws<FormatException>(() => { IPAddress.Parse(ipString); }); IPAddress ip; Assert.False(IPAddress.TryParse(ipString, out ip)); } [Fact] public static void Parse_String_Invalid() { Assert.Throws<ArgumentNullException>("ipString", () => { IPAddress.Parse(null); }); IPAddress ip; Assert.False(IPAddress.TryParse(null, out ip)); } [Fact] public static void ScopeId_GetSet_Success() { IPAddress ip = IPV6Address1(); Assert.Equal(0, ip.ScopeId); ip.ScopeId = 700; Assert.Equal(ip.ScopeId, 700); ip.ScopeId = 700; } [Fact] public static void ScopeId_Set_Invalid() { IPAddress ip = IPV4Address(); //IpV4 Assert.ThrowsAny<Exception>(() => ip.ScopeId = 500); Assert.ThrowsAny<Exception>(() => ip.ScopeId); ip = IPV6Address1(); //IpV6 Assert.Throws<ArgumentOutOfRangeException>("value", () => ip.ScopeId = MinScopeId - 1); Assert.Throws<ArgumentOutOfRangeException>("value", () => ip.ScopeId = MaxScopeId + 1); } [Fact] public static void HostToNetworkOrder_Compare_Equal() { long l1 = (long)0x1350; long l2 = (long)0x5013000000000000; int i1 = (int)0x1350; int i2 = (int)0x50130000; short s1 = (short)0x1350; short s2 = (short) 0x5013; Assert.Equal(l2, IPAddress.HostToNetworkOrder(l1)); Assert.Equal(i2, IPAddress.HostToNetworkOrder(i1)); Assert.Equal(s2, IPAddress.HostToNetworkOrder(s1)); Assert.Equal(l1, IPAddress.NetworkToHostOrder(l2)); Assert.Equal(i1, IPAddress.NetworkToHostOrder(i2)); Assert.Equal(s1, IPAddress.NetworkToHostOrder(s2)); } [Fact] public static void IsLoopback_Get_Success() { IPAddress ip = IPV4Address(); //IpV4 Assert.False(IPAddress.IsLoopback(ip)); ip = new IPAddress(IPAddress.Loopback.GetAddressBytes()); //IpV4 loopback Assert.True(IPAddress.IsLoopback(ip)); ip = IPV6Address1(); //IpV6 Assert.False(IPAddress.IsLoopback(ip)); ip = new IPAddress(IPAddress.IPv6Loopback.GetAddressBytes()); //IpV6 loopback Assert.True(IPAddress.IsLoopback(ip)); } [Fact] public static void IsLooback_Get_Invalid() { Assert.Throws<ArgumentNullException>("address", () => IPAddress.IsLoopback(null)); } [Fact] public static void IsIPV6Multicast_Get_Success() { Assert.True(IPAddress.Parse("ff02::1").IsIPv6Multicast); Assert.False(IPAddress.Parse("Fe08::1").IsIPv6Multicast); Assert.False(IPV4Address().IsIPv6Multicast); } [Fact] public static void IsIPV6LinkLocal_Get_Success() { Assert.True(IPAddress.Parse("fe80::1").IsIPv6LinkLocal); Assert.False(IPAddress.Parse("Fe08::1").IsIPv6LinkLocal); Assert.False(IPV4Address().IsIPv6LinkLocal); } [Fact] public static void IsIPV6SiteLocal_Get_Success() { Assert.True(IPAddress.Parse("FEC0::1").IsIPv6SiteLocal); Assert.False(IPAddress.Parse("Fe08::1").IsIPv6SiteLocal); Assert.False(IPV4Address().IsIPv6SiteLocal); } [Fact] public static void IsIPV6Teredo_Get_Success() { Assert.True(IPAddress.Parse("2001::1").IsIPv6Teredo); Assert.False(IPAddress.Parse("Fe08::1").IsIPv6Teredo); Assert.False(IPV4Address().IsIPv6Teredo); } [Fact] public static void Equals_Compare_Success() { IPAddress ip1 = IPAddress.Parse("192.168.0.9"); //IpV4 IPAddress ip2 = IPAddress.Parse("192.168.0.9"); //IpV4 IPAddress ip3 = IPAddress.Parse("169.192.1.10"); //IpV4 IPAddress ip4 = new IPAddress(ipV6AddressBytes1); //IpV6 IPAddress ip5 = new IPAddress(ipV6AddressBytes1); //IpV6 IPAddress ip6 = new IPAddress(ipV6AddressBytes2); //IpV6 Assert.True(ip1.Equals(ip2)); Assert.True(ip2.Equals(ip1)); Assert.True(ip1.GetHashCode().Equals(ip2.GetHashCode())); Assert.False(ip1.GetHashCode().Equals(ip3.GetHashCode())); Assert.False(ip1.Equals(ip3)); Assert.False(ip1.Equals(ip4)); //IpV4 /= IpV6 Assert.False(ip1.Equals(null)); Assert.False(ip1.Equals("")); Assert.True(ip4.Equals(ip5)); Assert.False(ip4.Equals(ip6)); Assert.True(ip4.GetHashCode().Equals(ip5.GetHashCode())); Assert.False(ip4.GetHashCode().Equals(ip6.GetHashCode())); } } }
#region MIT License /* * Copyright (c) 2005-2008 Jonathan Mark Porter. http://physics2d.googlepages.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. */ #endregion #if UseDouble using Scalar = System.Double; #else using Scalar = System.Single; #endif using System; using System.Runtime.InteropServices; using AdvanceMath.Design; namespace AdvanceMath.Geometry2D { [StructLayout(LayoutKind.Sequential, Size = BoundingRectangle.Size)] [AdvBrowsableOrder("Min,Max"), Serializable] #if !CompactFramework && !WindowsCE && !PocketPC && !XBOX360 && !SILVERLIGHT [System.ComponentModel.TypeConverter(typeof(AdvTypeConverter<BoundingRectangle>))] #endif public struct BoundingRectangle : IEquatable<BoundingRectangle> { public const int Size = Vector2D.Size * 2; public static void Transform(ref Matrix2x3 matrix,ref BoundingRectangle rect, out BoundingRectangle result) { FromVectors(ref matrix, rect.Corners(), out result); } /// <summary> /// Creates a new BoundingRectangle Instance from 2 Vector2Ds. /// </summary> /// <param name="first">the first Vector2D.</param> /// <param name="second">the second Vector2D.</param> /// <returns>a new BoundingRectangle</returns> /// <remarks>The Max and Min values are automatically determined.</remarks> public static BoundingRectangle FromVectors(Vector2D first, Vector2D second) { BoundingRectangle result; if (first.X > second.X) { result.Max.X = first.X; result.Min.X = second.X; } else { result.Max.X = second.X; result.Min.X = first.X; } if (first.Y > second.Y) { result.Max.Y = first.Y; result.Min.Y = second.Y; } else { result.Max.Y = second.Y; result.Min.Y = first.Y; } return result; } public static void FromVectors(ref Vector2D first, ref Vector2D second, out BoundingRectangle result) { if (first.X > second.X) { result.Max.X = first.X; result.Min.X = second.X; } else { result.Max.X = second.X; result.Min.X = first.X; } if (first.Y > second.Y) { result.Max.Y = first.Y; result.Min.Y = second.Y; } else { result.Max.Y = second.Y; result.Min.Y = first.Y; } } /// <summary> /// Creates a new BoundingRectangle Instance from multiple Vector2Ds. /// </summary> /// <param name="vectors">the list of vectors</param> /// <returns>a new BoundingRectangle</returns> /// <remarks>The Max and Min values are automatically determined.</remarks> public static BoundingRectangle FromVectors(Vector2D[] vectors) { BoundingRectangle result; FromVectors(vectors, out result); return result; } public static void FromVectors(Vector2D[] vectors, out BoundingRectangle result) { if (vectors == null) { throw new ArgumentNullException("vectors"); } if (vectors.Length == 0) { throw new ArgumentOutOfRangeException("vectors"); } result.Max = vectors[0]; result.Min = vectors[0]; for (int index = 1; index < vectors.Length; ++index) { Vector2D current = vectors[index]; if (current.X > result.Max.X) { result.Max.X = current.X; } else if (current.X < result.Min.X) { result.Min.X = current.X; } if (current.Y > result.Max.Y) { result.Max.Y = current.Y; } else if (current.Y < result.Min.Y) { result.Min.Y = current.Y; } } } public static void FromVectors(ref Matrix3x3 matrix, Vector2D[] vectors, out BoundingRectangle result) { if (vectors == null) { throw new ArgumentNullException("vectors"); } if (vectors.Length == 0) { throw new ArgumentOutOfRangeException("vectors"); } Vector2D current; Vector2D.Transform(ref matrix, ref vectors[0], out current); result.Max = current; result.Min = current; for (int index = 1; index < vectors.Length; ++index) { Vector2D.Transform(ref matrix, ref vectors[index], out current); if (current.X > result.Max.X) { result.Max.X = current.X; } else if (current.X < result.Min.X) { result.Min.X = current.X; } if (current.Y > result.Max.Y) { result.Max.Y = current.Y; } else if (current.Y < result.Min.Y) { result.Min.Y = current.Y; } } } public static void FromVectors(ref Matrix2x3 matrix, Vector2D[] vectors, out BoundingRectangle result) { if (vectors == null) { throw new ArgumentNullException("vectors"); } if (vectors.Length == 0) { throw new ArgumentOutOfRangeException("vectors"); } Vector2D current; Vector2D.TransformNormal(ref matrix, ref vectors[0], out current); result.Max = current; result.Min = current; for (int index = 1; index < vectors.Length; ++index) { Vector2D.TransformNormal(ref matrix, ref vectors[index], out current); if (current.X > result.Max.X) { result.Max.X = current.X; } else if (current.X < result.Min.X) { result.Min.X = current.X; } if (current.Y > result.Max.Y) { result.Max.Y = current.Y; } else if (current.Y < result.Min.Y) { result.Min.Y = current.Y; } } result.Max.X += matrix.m02; result.Max.Y += matrix.m12; result.Min.X += matrix.m02; result.Min.Y += matrix.m12; } /// <summary> /// Makes a BoundingRectangle that can contain the 2 BoundingRectangles passed. /// </summary> /// <param name="first">The First BoundingRectangle.</param> /// <param name="second">The Second BoundingRectangle.</param> /// <returns>The BoundingRectangle that can contain the 2 BoundingRectangles passed.</returns> public static BoundingRectangle FromUnion(BoundingRectangle first, BoundingRectangle second) { BoundingRectangle result; Vector2D.Max(ref first.Max, ref second.Max, out result.Max); Vector2D.Min(ref first.Min, ref second.Min, out result.Min); return result; } public static void FromUnion(ref BoundingRectangle first, ref BoundingRectangle second, out BoundingRectangle result) { Vector2D.Max(ref first.Max, ref second.Max, out result.Max); Vector2D.Min(ref first.Min, ref second.Min, out result.Min); } /// <summary> /// Makes a BoundingRectangle that contains the area where the BoundingRectangles Intersect. /// </summary> /// <param name="first">The First BoundingRectangle.</param> /// <param name="second">The Second BoundingRectangle.</param> /// <returns>The BoundingRectangle that can contain the 2 BoundingRectangles passed.</returns> public static BoundingRectangle FromIntersection(BoundingRectangle first, BoundingRectangle second) { BoundingRectangle result; Vector2D.Min(ref first.Max, ref second.Max, out result.Max); Vector2D.Max(ref first.Min, ref second.Min, out result.Min); return result; } public static void FromIntersection(ref BoundingRectangle first, ref BoundingRectangle second, out BoundingRectangle result) { Vector2D.Min(ref first.Max, ref second.Max, out result.Max); Vector2D.Max(ref first.Min, ref second.Min, out result.Min); } public static BoundingRectangle FromCircle(BoundingCircle circle) { BoundingRectangle result; FromCircle(ref circle, out result); return result; } public static void FromCircle(ref BoundingCircle circle, out BoundingRectangle result) { result.Max.X = circle.Position.X + circle.Radius; result.Max.Y = circle.Position.Y + circle.Radius; result.Min.X = circle.Position.X - circle.Radius; result.Min.Y = circle.Position.Y - circle.Radius; } public static BoundingRectangle FromCircle( Matrix2x3 matrix, Scalar radius) { BoundingRectangle result; FromCircle(ref matrix, ref radius, out result); return result; } public static void FromCircle(ref Matrix2x3 matrix, ref Scalar radius, out BoundingRectangle result) { Scalar xRadius = matrix.m01 * matrix.m01 + matrix.m00 * matrix.m00; xRadius = ((xRadius == 1) ? (radius) : (radius * MathHelper.Sqrt(xRadius))); Scalar yRadius = matrix.m10 * matrix.m10 + matrix.m11 * matrix.m11; yRadius = ((yRadius == 1) ? (radius) : (radius * MathHelper.Sqrt(yRadius))); result.Max.X = matrix.m02 + xRadius; result.Min.X = matrix.m02 - xRadius; result.Max.Y = matrix.m12 + yRadius; result.Min.Y = matrix.m12 - yRadius; } [AdvBrowsable] public Vector2D Max; [AdvBrowsable] public Vector2D Min; /// <summary> /// Creates a new BoundingRectangle Instance. /// </summary> /// <param name="minX">The Lower Bound on the XAxis.</param> /// <param name="minY">The Lower Bound on the YAxis.</param> /// <param name="maxX">The Upper Bound on the XAxis.</param> /// <param name="maxY">The Upper Bound on the YAxis.</param> public BoundingRectangle(Scalar minX, Scalar minY, Scalar maxX, Scalar maxY) { this.Max.X = maxX; this.Max.Y = maxY; this.Min.X = minX; this.Min.Y = minY; } /// <summary> /// Creates a new BoundingRectangle Instance from 2 Vector2Ds. /// </summary> /// <param name="min">The Lower Vector2D.</param> /// <param name="max">The Upper Vector2D.</param> [InstanceConstructor("Min,Max")] public BoundingRectangle(Vector2D min, Vector2D max) { this.Max = max; this.Min = min; } public Scalar Area { get { return (Max.X - Min.X) * (Max.Y - Min.Y); } } public Scalar Perimeter { get { return ((Max.X - Min.X) + (Max.Y - Min.Y)) * 2; } } public Vector2D[] Corners() { return new Vector2D[4] { Max, new Vector2D(Min.X, Max.Y), Min, new Vector2D(Max.X, Min.Y), }; } public Scalar GetDistance(Vector2D point) { Scalar result; GetDistance(ref point, out result); return result; } public void GetDistance(ref Vector2D point, out Scalar result) { Scalar xDistance = Math.Abs(point.X - ((Max.X + Min.X) * .5f)) - (Max.X - Min.X) * .5f; Scalar yDistance = Math.Abs(point.Y - ((Max.Y + Min.Y) * .5f)) - (Max.Y - Min.Y) * .5f; if (xDistance > 0 && yDistance > 0) { result = MathHelper.Sqrt(xDistance * xDistance + yDistance * yDistance); } else { result = Math.Max(xDistance, yDistance); } } public ContainmentType Contains(Vector2D point) { if (point.X <= Max.X && point.X >= Min.X && point.Y <= Max.Y && point.Y >= Min.Y) { return ContainmentType.Contains; } else { return ContainmentType.Disjoint; } } public void Contains(ref Vector2D point, out ContainmentType result) { if (point.X <= Max.X && point.X >= Min.X && point.Y <= Max.Y && point.Y >= Min.Y) { result = ContainmentType.Contains; } else { result = ContainmentType.Disjoint; } } public ContainmentType Contains(BoundingRectangle rect) { if (this.Min.X > rect.Max.X || this.Min.Y > rect.Max.Y || this.Max.X < rect.Min.X || this.Max.Y < rect.Min.Y) { return ContainmentType.Disjoint; } else if ( this.Min.X <= rect.Min.X && this.Min.Y <= rect.Min.Y && this.Max.X >= rect.Max.X && this.Max.Y >= rect.Max.Y) { return ContainmentType.Contains; } else { return ContainmentType.Intersects; } } public void Contains(ref BoundingRectangle rect, out ContainmentType result) { if (this.Min.X > rect.Max.X || this.Min.Y > rect.Max.Y || this.Max.X < rect.Min.X || this.Max.Y < rect.Min.Y) { result = ContainmentType.Disjoint; } else if ( this.Min.X <= rect.Min.X && this.Min.Y <= rect.Min.Y && this.Max.X >= rect.Max.X && this.Max.Y >= rect.Max.Y) { result = ContainmentType.Contains; } else { result = ContainmentType.Intersects; } } public ContainmentType Contains(BoundingCircle circle) { if ((circle.Position.X + circle.Radius) <= Max.X && (circle.Position.X - circle.Radius) >= Min.X && (circle.Position.Y + circle.Radius) <= Max.Y && (circle.Position.Y - circle.Radius) >= Min.Y) { return ContainmentType.Contains; } else { bool intersects; circle.Intersects(ref this, out intersects); if (intersects) { return ContainmentType.Intersects; } else { return ContainmentType.Disjoint; } } } public void Contains(ref BoundingCircle circle, out ContainmentType result) { if ((circle.Position.X + circle.Radius) <= Max.X && (circle.Position.X - circle.Radius) >= Min.X && (circle.Position.Y + circle.Radius) <= Max.Y && (circle.Position.Y - circle.Radius) >= Min.Y) { result = ContainmentType.Contains; } else { bool intersects; circle.Intersects(ref this, out intersects); if (intersects) { result = ContainmentType.Intersects; } else { result = ContainmentType.Disjoint; } } } public ContainmentType Contains(BoundingPolygon polygon) { ContainmentType result; Contains(ref polygon, out result); return result; } public void Contains(ref BoundingPolygon polygon, out ContainmentType result) { if (polygon == null) { throw new ArgumentNullException("polygon"); } Vector2D[] vertexes = polygon.Vertexes; result = ContainmentType.Unknown; for (int index = 0; index < vertexes.Length && result != ContainmentType.Intersects; ++index) { ContainmentType con; Contains(ref vertexes[index], out con); result |= con; } if (result == ContainmentType.Disjoint) { bool test; polygon.Intersects(ref this, out test); if (test) { result = ContainmentType.Intersects; } } } public Scalar Intersects(Ray ray) { Scalar result; Intersects(ref ray, out result); return result; } public bool Intersects(BoundingRectangle rect) { return this.Min.X < rect.Max.X && this.Max.X > rect.Min.X && this.Max.Y > rect.Min.Y && this.Min.Y < rect.Max.Y; } public bool Intersects(BoundingCircle circle) { bool result; circle.Intersects(ref this, out result); return result; } public bool Intersects(Line line) { bool result; line.Intersects(ref this, out result); return result; } public bool Intersects(BoundingPolygon polygon) { if (polygon == null) { throw new ArgumentNullException("polygon"); } bool result; polygon.Intersects(ref this, out result); return result; } public void Intersects(ref Ray ray, out Scalar result) { if (Contains(ray.Origin)== ContainmentType.Contains) { result = 0; return; } Scalar distance; Scalar intersectValue; result = -1; if (ray.Origin.X < Min.X && ray.Direction.X > 0) { distance = (Min.X - ray.Origin.X) / ray.Direction.X; if (distance > 0) { intersectValue = ray.Origin.Y + ray.Direction.Y * distance; if (intersectValue >= Min.Y && intersectValue <= Max.Y && (result == -1 || distance < result)) { result = distance; } } } if (ray.Origin.X > Max.X && ray.Direction.X < 0) { distance = (Max.X - ray.Origin.X) / ray.Direction.X; if (distance > 0) { intersectValue = ray.Origin.Y + ray.Direction.Y * distance; if (intersectValue >= Min.Y && intersectValue <= Max.Y && (result == -1 || distance < result)) { result = distance; } } } if (ray.Origin.Y < Min.Y && ray.Direction.Y > 0) { distance = (Min.Y - ray.Origin.Y) / ray.Direction.Y; if (distance > 0) { intersectValue = ray.Origin.X + ray.Direction.X * distance; if (intersectValue >= Min.X && intersectValue <= Max.X && (result == -1 || distance < result)) { result = distance; } } } if (ray.Origin.Y > Max.Y && ray.Direction.Y < 0) { distance = (Max.Y - ray.Origin.Y) / ray.Direction.Y; if (distance > 0) { intersectValue = ray.Origin.X + ray.Direction.X * distance; if (intersectValue >= Min.X && intersectValue <= Max.X && (result == -1 || distance < result)) { result = distance; } } } } public void Intersects(ref BoundingRectangle rect, out bool result) { result = this.Min.X <= rect.Max.X && this.Max.X >= rect.Min.X && this.Max.Y >= rect.Min.Y && this.Min.Y <= rect.Max.Y; } public void Intersects(ref BoundingCircle circle, out bool result) { circle.Intersects(ref this, out result); } public void Intersects(ref BoundingPolygon polygon, out bool result) { if (polygon == null) { throw new ArgumentNullException("polygon"); } polygon.Intersects(ref this, out result); } public void Intersects(ref Line line, out bool result) { line.Intersects(ref this, out result); } public override string ToString() { return string.Format("{0} < {1}", Min, Max); } public override bool Equals(object obj) { return obj is BoundingRectangle && Equals((BoundingRectangle)obj); } public bool Equals(BoundingRectangle other) { return Equals(ref this, ref other); } public static bool Equals(BoundingRectangle rect1, BoundingRectangle rect2) { return Equals(ref rect1, ref rect2); } [CLSCompliant(false)] public static bool Equals(ref BoundingRectangle rect1, ref BoundingRectangle rect2) { return Vector2D.Equals(ref rect1.Min, ref rect2.Min) && Vector2D.Equals(ref rect1.Max, ref rect2.Max); } public override int GetHashCode() { return Min.GetHashCode() ^ Max.GetHashCode(); } public static bool operator ==(BoundingRectangle rect1, BoundingRectangle rect2) { return Equals(ref rect1, ref rect2); } public static bool operator !=(BoundingRectangle rect1, BoundingRectangle rect2) { return !Equals(ref rect1, ref rect2); } } }
// // Window.cs // // Author: // Lluis Sanchez <lluis@xamarin.com> // // Copyright (c) 2011 Xamarin Inc // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using Xwt.Backends; namespace Xwt { [BackendType(typeof(IWindowBackend))] public class Window : WindowFrame { Widget child; WidgetSpacing padding; Menu mainMenu; bool shown; protected new class WindowBackendHost : WindowFrame.WindowBackendHost { } protected override BackendHost CreateBackendHost() { return new WindowBackendHost(); } public Window() { Padding = 12; } IWindowBackend Backend { get { return (IWindowBackend)BackendHost.Backend; } } public WindowLocation InitialLocation { get { return initialLocation; } set { initialLocation = value; } } public WidgetSpacing Padding { get { return padding; } set { padding = value; UpdatePadding(); } } public double PaddingLeft { get { return padding.Left; } set { padding.Left = value; UpdatePadding(); } } public double PaddingRight { get { return padding.Right; } set { padding.Right = value; UpdatePadding(); } } public double PaddingTop { get { return padding.Top; } set { padding.Top = value; UpdatePadding(); } } public double PaddingBottom { get { return padding.Bottom; } set { padding.Bottom = value; UpdatePadding(); } } void UpdatePadding() { Backend.SetPadding(padding.Left, padding.Top, padding.Right, padding.Bottom); } public Menu MainMenu { get { return mainMenu; } set { mainMenu = value; Backend.SetMainMenu((IMenuBackend)BackendHost.ToolkitEngine.GetSafeBackend(mainMenu)); } } public Widget Content { get { return child; } set { if (child != null) child.SetParentWindow(null); this.child = value; child.SetParentWindow(this); Backend.SetChild((IWidgetBackend)BackendHost.ToolkitEngine.GetSafeBackend(child)); if (!BackendHost.EngineBackend.HandlesSizeNegotiation) Widget.QueueWindowSizeNegotiation(this); } } protected override void Dispose(bool disposing) { if (Content != null) Content.Dispose(); base.Dispose(disposing); } protected override void OnReallocate() { if (child != null && !BackendHost.EngineBackend.HandlesSizeNegotiation) { child.Surface.Reallocate(); } } bool widthSet; bool heightSet; bool locationSet; Rectangle initialBounds; WindowLocation initialLocation = WindowLocation.CenterParent; // internal public override void SetBackendSize(double width, double height) { if (shown) base.SetBackendSize(width, height); else { if (width != -1) { initialBounds.Width = width; widthSet = true; } if (height != -1) { heightSet = true; initialBounds.Height = height; } } } // internal public override void SetBackendLocation(double x, double y) { if (shown || BackendHost.EngineBackend.HandlesSizeNegotiation) base.SetBackendLocation(x, y); if (!shown) { locationSet = true; initialBounds.Location = new Point(x, y); } } // internal public override Rectangle BackendBounds { get { return shown || BackendHost.EngineBackend.HandlesSizeNegotiation ? base.BackendBounds : initialBounds; } set { if (shown || BackendHost.EngineBackend.HandlesSizeNegotiation) base.BackendBounds = value; if (!shown) { widthSet = heightSet = locationSet = true; initialBounds = value; } } } internal void OnChildPlacementChanged(Widget child) { Backend.UpdateChildPlacement(child.GetBackend()); if (!BackendHost.EngineBackend.HandlesSizeNegotiation) Widget.QueueWindowSizeNegotiation(this); } public override void AdjustSize() { Size mMinSize, mDecorationsSize; Backend.GetMetrics(out mMinSize, out mDecorationsSize); var size = shown ? Size : initialBounds.Size; var wc = (shown || widthSet) ? SizeConstraint.WithSize(Math.Max(size.Width - padding.HorizontalSpacing - mDecorationsSize.Width, mMinSize.Width)) : SizeConstraint.Unconstrained; var hc = (shown || heightSet) ? SizeConstraint.WithSize(Math.Max(size.Height - padding.VerticalSpacing - mDecorationsSize.Height, mMinSize.Height)) : SizeConstraint.Unconstrained; var ws = mDecorationsSize; if (child != null) { IWidgetSurface s = child.Surface; ws += s.GetPreferredSize(wc, hc, true); } ws.Width += padding.HorizontalSpacing; ws.Height += padding.VerticalSpacing; if (!shown) { if (!widthSet) size.Width = ws.Width; if (!heightSet) size.Height = ws.Height; } if (ws.Width < mMinSize.Width) ws.Width = mMinSize.Width; if (ws.Height < mMinSize.Height) ws.Height = mMinSize.Height; if (ws.Width > size.Width) size.Width = ws.Width; if (ws.Height > size.Height) size.Height = ws.Height; if (!shown) { shown = true; if (!locationSet && initialLocation != WindowLocation.Manual) { Point center; if (initialLocation == WindowLocation.CenterScreen || TransientFor == null) center = Desktop.PrimaryScreen.VisibleBounds.Center; else center = TransientFor.ScreenBounds.Center; initialBounds.X = Math.Round(center.X - size.Width / 2); initialBounds.Y = Math.Round(center.Y - size.Height / 2); locationSet = true; } if (size != Size) { if (locationSet) Backend.Bounds = new Rectangle(initialBounds.X, initialBounds.Y, size.Width, size.Height); else Backend.SetSize(size.Width, size.Height); } else if (locationSet && !shown) Backend.Move(initialBounds.X, initialBounds.Y); } else { if (size != Size) Backend.SetSize(size.Width, size.Height); } Backend.SetMinSize(new Size(ws.Width, ws.Height)); } } }
// 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.Linq; using System.Xml; using System.Xml.Linq; namespace System.Xml.XPath { internal class XNodeNavigator : XPathNavigator, IXmlLineInfo { internal static readonly string xmlPrefixNamespace = XNamespace.Xml.NamespaceName; internal static readonly string xmlnsPrefixNamespace = XNamespace.Xmlns.NamespaceName; const int DocumentContentMask = (1 << (int)XmlNodeType.Element) | (1 << (int)XmlNodeType.ProcessingInstruction) | (1 << (int)XmlNodeType.Comment); static readonly int[] ElementContentMasks = { 0, // Root (1 << (int)XmlNodeType.Element), // Element 0, // Attribute 0, // Namespace (1 << (int)XmlNodeType.CDATA) | (1 << (int)XmlNodeType.Text), // Text 0, // SignificantWhitespace 0, // Whitespace (1 << (int)XmlNodeType.ProcessingInstruction), // ProcessingInstruction (1 << (int)XmlNodeType.Comment), // Comment (1 << (int)XmlNodeType.Element) | (1 << (int)XmlNodeType.CDATA) | (1 << (int)XmlNodeType.Text) | (1 << (int)XmlNodeType.ProcessingInstruction) | (1 << (int)XmlNodeType.Comment) // All }; const int TextMask = (1 << (int)XmlNodeType.CDATA) | (1 << (int)XmlNodeType.Text); static XAttribute XmlNamespaceDeclaration; // The navigator position is encoded by the tuple (source, parent). // Lazy text uses (instance, parent element). Namespace declaration uses // (instance, parent element). Common XObjects uses (instance, null). object source; XElement parent; XmlNameTable nameTable; public XNodeNavigator(XNode node, XmlNameTable nameTable) { this.source = node; this.nameTable = nameTable != null ? nameTable : CreateNameTable(); } public XNodeNavigator(XNodeNavigator other) { source = other.source; parent = other.parent; nameTable = other.nameTable; } public override string BaseURI { get { XObject o = source as XObject; if (o != null) { return o.BaseUri; } if (parent != null) { return parent.BaseUri; } return string.Empty; } } public override bool HasAttributes { get { XElement e = source as XElement; if (e != null) { XAttribute a = e.LastAttribute; if (a != null) { do { a = a.NextAttribute; if (!a.IsNamespaceDeclaration) { return true; } } while (a != e.LastAttribute); } } return false; } } public override bool HasChildren { get { XContainer c = source as XContainer; if (c != null) { XNode content = c.LastNode; XNode n = content; if (n != null) { do { n = n.NextNode; if (IsContent(c, n)) { return true; } } while (n != content); return false; } } return false; } } public override bool IsEmptyElement { get { XElement e = source as XElement; return e != null && e.IsEmpty; } } public override string LocalName { get { return nameTable.Add(GetLocalName()); } } string GetLocalName() { XElement e = source as XElement; if (e != null) { return e.Name.LocalName; } XAttribute a = source as XAttribute; if (a != null) { if (parent != null && a.Name.NamespaceName.Length == 0) { return string.Empty; // backcompat } return a.Name.LocalName; } XProcessingInstruction p = source as XProcessingInstruction; if (p != null) { return p.Target; } return string.Empty; } public override string Name { get { string prefix = GetPrefix(); if (prefix.Length == 0) { return nameTable.Add(GetLocalName()); } return nameTable.Add(string.Concat(prefix, ":", GetLocalName())); } } public override string NamespaceURI { get { return nameTable.Add(GetNamespaceURI()); } } string GetNamespaceURI() { XElement e = source as XElement; if (e != null) { return e.Name.NamespaceName; } XAttribute a = source as XAttribute; if (a != null) { if (parent != null) { return string.Empty; // backcompat } return a.Name.NamespaceName; } return string.Empty; } public override XmlNameTable NameTable { get { return nameTable; } } public override XPathNodeType NodeType { get { XObject o = source as XObject; if (o != null) { switch (o.NodeType) { case XmlNodeType.Element: return XPathNodeType.Element; case XmlNodeType.Attribute: if (parent != null) { return XPathNodeType.Namespace; } return XPathNodeType.Attribute; case XmlNodeType.Document: return XPathNodeType.Root; case XmlNodeType.Comment: return XPathNodeType.Comment; case XmlNodeType.ProcessingInstruction: return XPathNodeType.ProcessingInstruction; default: return XPathNodeType.Text; } } return XPathNodeType.Text; } } public override string Prefix { get { return nameTable.Add(GetPrefix()); } } string GetPrefix() { XElement e = source as XElement; if (e != null) { string prefix = e.GetPrefixOfNamespace(e.Name.Namespace); if (prefix != null) { return prefix; } return string.Empty; } XAttribute a = source as XAttribute; if (a != null) { if (parent != null) { return string.Empty; // backcompat } string prefix = a.GetPrefixOfNamespace(a.Name.Namespace); if (prefix != null) { return prefix; } } return string.Empty; } public override object UnderlyingObject { get { if (source is string) { // convert lazy text to eager text source = parent.LastNode; parent = null; } return source; } } public override string Value { get { XObject o = source as XObject; if (o != null) { switch (o.NodeType) { case XmlNodeType.Element: return ((XElement)o).Value; case XmlNodeType.Attribute: return ((XAttribute)o).Value; case XmlNodeType.Document: XElement root = ((XDocument)o).Root; return root != null ? root.Value : string.Empty; case XmlNodeType.Text: case XmlNodeType.CDATA: return CollectText((XText)o); case XmlNodeType.Comment: return ((XComment)o).Value; case XmlNodeType.ProcessingInstruction: return ((XProcessingInstruction)o).Data; default: return string.Empty; } } return (string)source; } } public override XPathNavigator Clone() { return new XNodeNavigator(this); } public override bool IsSamePosition(XPathNavigator navigator) { XNodeNavigator other = navigator as XNodeNavigator; if (other == null) { return false; } return IsSamePosition(this, other); } public override bool MoveTo(XPathNavigator navigator) { XNodeNavigator other = navigator as XNodeNavigator; if (other != null) { source = other.source; parent = other.parent; return true; } return false; } public override bool MoveToAttribute(string localName, string namespaceName) { XElement e = source as XElement; if (e != null) { XAttribute a = e.LastAttribute; if (a != null) { do { a = a.NextAttribute; if (a.Name.LocalName == localName && a.Name.NamespaceName == namespaceName && !a.IsNamespaceDeclaration) { source = a; return true; } } while (a != e.LastAttribute); } } return false; } public override bool MoveToChild(string localName, string namespaceName) { XContainer c = source as XContainer; if (c != null) { XNode content = c.LastNode; XNode n = content; if (n != null) { do { n = n.NextNode; XElement e = n as XElement; if (e != null && e.Name.LocalName == localName && e.Name.NamespaceName == namespaceName) { source = e; return true; } } while (n != content); } } return false; } public override bool MoveToChild(XPathNodeType type) { XContainer c = source as XContainer; if (c != null) { XNode content = c.LastNode; XNode n = content; if (n != null) { int mask = GetElementContentMask(type); if ((TextMask & mask) != 0 && c.GetParent() == null && c is XDocument) { mask &= ~TextMask; } do { n = n.NextNode; if (((1 << (int)n.NodeType) & mask) != 0) { source = n; return true; } } while (n != content); return false; } } return false; } public override bool MoveToFirstAttribute() { XElement e = source as XElement; if (e != null) { XAttribute a = e.LastAttribute; if (a != null) { do { a = a.NextAttribute; if (!a.IsNamespaceDeclaration) { source = a; return true; } } while (a != e.LastAttribute); } } return false; } public override bool MoveToFirstChild() { XContainer c = source as XContainer; if (c != null) { XNode content = c.LastNode; XNode n = content; if (n != null) { do { n = n.NextNode; if (IsContent(c, n)) { source = n; return true; } } while (n != content); return false; } } return false; } public override bool MoveToFirstNamespace(XPathNamespaceScope scope) { XElement e = source as XElement; if (e != null) { XAttribute a = null; switch (scope) { case XPathNamespaceScope.Local: a = GetFirstNamespaceDeclarationLocal(e); break; case XPathNamespaceScope.ExcludeXml: a = GetFirstNamespaceDeclarationGlobal(e); while (a != null && a.Name.LocalName == "xml") { a = GetNextNamespaceDeclarationGlobal(a); } break; case XPathNamespaceScope.All: a = GetFirstNamespaceDeclarationGlobal(e); if (a == null) { a = GetXmlNamespaceDeclaration(); } break; } if (a != null) { source = a; parent = e; return true; } } return false; } public override bool MoveToId(string id) { throw new NotSupportedException(SR.NotSupported_MoveToId); } public override bool MoveToNamespace(string localName) { XElement e = source as XElement; if (e != null) { if (localName == "xmlns") { return false; // backcompat } if (localName != null && localName.Length == 0) { localName = "xmlns"; // backcompat } XAttribute a = GetFirstNamespaceDeclarationGlobal(e); while (a != null) { if (a.Name.LocalName == localName) { source = a; parent = e; return true; } a = GetNextNamespaceDeclarationGlobal(a); } if (localName == "xml") { source = GetXmlNamespaceDeclaration(); parent = e; return true; } } return false; } public override bool MoveToNext() { XNode n = source as XNode; if (n != null) { XContainer c = n.GetParent(); if (c != null) { XNode content = c.LastNode; while (n != content) { XNode next = n.NextNode; if (IsContent(c, next) && !(n is XText && next is XText)) { source = next; return true; } n = next; } } } return false; } public override bool MoveToNext(string localName, string namespaceName) { XNode n = source as XNode; if (n != null) { XContainer c = n.GetParent(); if (c != null) { XNode content = c.LastNode; while (n != content) { n = n.NextNode; XElement e = n as XElement; if (e != null && e.Name.LocalName == localName && e.Name.NamespaceName == namespaceName) { source = e; return true; } } } } return false; } public override bool MoveToNext(XPathNodeType type) { XNode n = source as XNode; if (n != null) { XContainer c = n.GetParent(); if (c != null) { XNode content = c.LastNode; int mask = GetElementContentMask(type); if ((TextMask & mask) != 0 && c.GetParent() == null && c is XDocument) { mask &= ~TextMask; } while (n != content) { XNode next = n.NextNode; if (((1 << (int)next.NodeType) & mask) != 0 && !(n is XText && next is XText)) { source = next; return true; } n = next; } } } return false; } public override bool MoveToNextAttribute() { XAttribute a = source as XAttribute; if (a != null && parent == null) { XElement e = (XElement)a.GetParent(); if (e != null) { while (a != e.LastAttribute) { a = a.NextAttribute; if (!a.IsNamespaceDeclaration) { source = a; return true; } } } } return false; } public override bool MoveToNextNamespace(XPathNamespaceScope scope) { XAttribute a = source as XAttribute; if (a != null && parent != null && !IsXmlNamespaceDeclaration(a)) { switch (scope) { case XPathNamespaceScope.Local: if (a.GetParent() != parent) { return false; } a = GetNextNamespaceDeclarationLocal(a); break; case XPathNamespaceScope.ExcludeXml: do { a = GetNextNamespaceDeclarationGlobal(a); } while (a != null && (a.Name.LocalName == "xml" || HasNamespaceDeclarationInScope(a, parent))); break; case XPathNamespaceScope.All: do { a = GetNextNamespaceDeclarationGlobal(a); } while (a != null && HasNamespaceDeclarationInScope(a, parent)); if (a == null && !HasNamespaceDeclarationInScope(GetXmlNamespaceDeclaration(), parent)) { a = GetXmlNamespaceDeclaration(); } break; } if (a != null) { source = a; return true; } } return false; } public override bool MoveToParent() { if (parent != null) { source = parent; parent = null; return true; } XObject o = (XObject)source; if (o.GetParent() != null) { source = o.GetParent(); return true; } return false; } public override bool MoveToPrevious() { XNode n = source as XNode; if (n != null) { XContainer c = n.GetParent(); if (c != null) { XNode q = c.LastNode; if (q.NextNode != n) { XNode p = null; do { q = q.NextNode; if (IsContent(c, q)) { p = p is XText && q is XText ? p : q; } } while (q.NextNode != n); if (p != null) { source = p; return true; } } } } return false; } public override XmlReader ReadSubtree() { XContainer c = source as XContainer; if (c == null) throw new InvalidOperationException(SR.Format(SR.InvalidOperation_BadNodeType, NodeType)); return c.CreateReader(); } bool IXmlLineInfo.HasLineInfo() { IXmlLineInfo li = source as IXmlLineInfo; if (li != null) { return li.HasLineInfo(); } return false; } int IXmlLineInfo.LineNumber { get { IXmlLineInfo li = source as IXmlLineInfo; if (li != null) { return li.LineNumber; } return 0; } } int IXmlLineInfo.LinePosition { get { IXmlLineInfo li = source as IXmlLineInfo; if (li != null) { return li.LinePosition; } return 0; } } static string CollectText(XText n) { string s = n.Value; if (n.GetParent() != null) { while (n != n.GetParent().LastNode) { n = n.NextNode as XText; if (n == null) break; s += n.Value; } } return s; } static XmlNameTable CreateNameTable() { XmlNameTable nameTable = new NameTable(); nameTable.Add(string.Empty); nameTable.Add(xmlnsPrefixNamespace); nameTable.Add(xmlPrefixNamespace); return nameTable; } static bool IsContent(XContainer c, XNode n) { if (c.GetParent() != null || c is XElement) { return true; } return ((1 << (int)n.NodeType) & DocumentContentMask) != 0; } static bool IsSamePosition(XNodeNavigator n1, XNodeNavigator n2) { if (n1.source == n2.source && n1.parent == n2.parent) { return true; } // compare lazy text with eager text if (n1.parent != null ^ n2.parent != null) { XText t1 = n1.source as XText; if (t1 != null) { return (object)t1.Value == (object)n2.source && t1.GetParent() == n2.parent; } XText t2 = n2.source as XText; if (t2 != null) { return (object)t2.Value == (object)n1.source && t2.GetParent() == n1.parent; } } return false; } static bool IsXmlNamespaceDeclaration(XAttribute a) { return (object)a == (object)GetXmlNamespaceDeclaration(); } static int GetElementContentMask(XPathNodeType type) { return ElementContentMasks[(int)type]; } static XAttribute GetFirstNamespaceDeclarationGlobal(XElement e) { do { XAttribute a = GetFirstNamespaceDeclarationLocal(e); if (a != null) { return a; } e = e.Parent; } while (e != null); return null; } static XAttribute GetFirstNamespaceDeclarationLocal(XElement e) { XAttribute a = e.LastAttribute; if (a != null) { do { a = a.NextAttribute; if (a.IsNamespaceDeclaration) { return a; } } while (a != e.LastAttribute); } return null; } static XAttribute GetNextNamespaceDeclarationGlobal(XAttribute a) { XElement e = (XElement)a.GetParent(); if (e == null) { return null; } XAttribute next = GetNextNamespaceDeclarationLocal(a); if (next != null) { return next; } e = e.Parent; if (e == null) { return null; } return GetFirstNamespaceDeclarationGlobal(e); } static XAttribute GetNextNamespaceDeclarationLocal(XAttribute a) { XElement e = (XElement)a.GetParent(); if (e == null) { return null; } while (a != e.LastAttribute) { a = a.NextAttribute; if (a.IsNamespaceDeclaration) { return a; } } return null; } static XAttribute GetXmlNamespaceDeclaration() { if (XmlNamespaceDeclaration == null) { System.Threading.Interlocked.CompareExchange(ref XmlNamespaceDeclaration, new XAttribute(XNamespace.Xmlns.GetName("xml"), xmlPrefixNamespace), null); } return XmlNamespaceDeclaration; } static bool HasNamespaceDeclarationInScope(XAttribute a, XElement e) { XName name = a.Name; while (e != null && e != a.GetParent()) { if (e.Attribute(name) != null) { return true; } e = e.Parent; } return false; } } struct XPathEvaluator { public object Evaluate<T>(XNode node, string expression, IXmlNamespaceResolver resolver) where T : class { XPathNavigator navigator = node.CreateNavigator(); object result = navigator.Evaluate(expression, resolver); if (result is XPathNodeIterator) { return EvaluateIterator<T>((XPathNodeIterator)result); } if (!(result is T)) throw new InvalidOperationException(SR.Format(SR.InvalidOperation_UnexpectedEvaluation, result.GetType())); return (T)result; } IEnumerable<T> EvaluateIterator<T>(XPathNodeIterator result) { foreach (XPathNavigator navigator in result) { object r = navigator.UnderlyingObject; if (!(r is T)) throw new InvalidOperationException(SR.Format(SR.InvalidOperation_UnexpectedEvaluation, r.GetType())); yield return (T)r; XText t = r as XText; if (t != null && t.GetParent() != null) { while (t != t.GetParent().LastNode) { t = t.NextNode as XText; if (t == null) break; yield return (T)(object)t; } } } } } /// <summary> /// Extension methods /// </summary> public static class Extensions { /// <summary> /// Creates an <see cref="XPathNavigator"/> for a given <see cref="XNode"/> /// </summary> /// <param name="node">Extension point <see cref="XNode"/></param> /// <returns>An <see cref="XPathNavigator"/></returns> public static XPathNavigator CreateNavigator(this XNode node) { return node.CreateNavigator(null); } /// <summary> /// Creates an <see cref="XPathNavigator"/> for a given <see cref="XNode"/> /// </summary> /// <param name="node">Extension point <see cref="XNode"/></param> /// <param name="nameTable">The <see cref="XmlNameTable"/> to be used by /// the <see cref="XPathNavigator"/></param> /// <returns>An <see cref="XPathNavigator"/></returns> public static XPathNavigator CreateNavigator(this XNode node, XmlNameTable nameTable) { if (node == null) throw new ArgumentNullException("node"); if (node is XDocumentType) throw new ArgumentException(SR.Format(SR.Argument_CreateNavigator, XmlNodeType.DocumentType)); XText text = node as XText; if (text != null) { if (text.GetParent() is XDocument) throw new ArgumentException(SR.Format(SR.Argument_CreateNavigator, XmlNodeType.Whitespace)); node = CalibrateText(text); } return new XNodeNavigator(node, nameTable); } /// <summary> /// Evaluates an XPath expression /// </summary> /// <param name="node">Extension point <see cref="XNode"/></param> /// <param name="expression">The XPath expression</param> /// <returns>The result of evaluating the expression which can be typed as bool, double, string or /// IEnumerable</returns> public static object XPathEvaluate(this XNode node, string expression) { return node.XPathEvaluate(expression, null); } /// <summary> /// Evaluates an XPath expression /// </summary> /// <param name="node">Extension point <see cref="XNode"/></param> /// <param name="expression">The XPath expression</param> /// <param name="resolver">A <see cref="IXmlNamespaceResolver"> for the namespace /// prefixes used in the XPath expression</see></param> /// <returns>The result of evaluating the expression which can be typed as bool, double, string or /// IEnumerable</returns> public static object XPathEvaluate(this XNode node, string expression, IXmlNamespaceResolver resolver) { if (node == null) throw new ArgumentNullException("node"); return new XPathEvaluator().Evaluate<object>(node, expression, resolver); } /// <summary> /// Select an <see cref="XElement"/> using a XPath expression /// </summary> /// <param name="node">Extension point <see cref="XNode"/></param> /// <param name="expression">The XPath expression</param> /// <returns>An <see cref="XElement"> or null</see></returns> public static XElement XPathSelectElement(this XNode node, string expression) { return node.XPathSelectElement(expression, null); } /// <summary> /// Select an <see cref="XElement"/> using a XPath expression /// </summary> /// <param name="node">Extension point <see cref="XNode"/></param> /// <param name="expression">The XPath expression</param> /// <param name="resolver">A <see cref="IXmlNamespaceResolver"/> for the namespace /// prefixes used in the XPath expression</param> /// <returns>An <see cref="XElement"> or null</see></returns> public static XElement XPathSelectElement(this XNode node, string expression, IXmlNamespaceResolver resolver) { return node.XPathSelectElements(expression, resolver).FirstOrDefault(); } /// <summary> /// Select a set of <see cref="XElement"/> using a XPath expression /// </summary> /// <param name="node">Extension point <see cref="XNode"/></param> /// <param name="expression">The XPath expression</param> /// <returns>An <see cref="IEnumerable&lt;XElement&gt;"/> corresponding to the resulting set of elements</returns> public static IEnumerable<XElement> XPathSelectElements(this XNode node, string expression) { return node.XPathSelectElements(expression, null); } /// <summary> /// Select a set of <see cref="XElement"/> using a XPath expression /// </summary> /// <param name="node">Extension point <see cref="XNode"/></param> /// <param name="expression">The XPath expression</param> /// <param name="resolver">A <see cref="IXmlNamespaceResolver"/> for the namespace /// prefixes used in the XPath expression</param> /// <returns>An <see cref="IEnumerable&lt;XElement&gt;"/> corresponding to the resulting set of elements</returns> public static IEnumerable<XElement> XPathSelectElements(this XNode node, string expression, IXmlNamespaceResolver resolver) { if (node == null) throw new ArgumentNullException("node"); return (IEnumerable<XElement>)new XPathEvaluator().Evaluate<XElement>(node, expression, resolver); } static XText CalibrateText(XText n) { if (n.GetParent() == null) { return n; } XNode p = n.GetParent().LastNode; while (true) { p = p.NextNode; XText t = p as XText; if (t != null) { do { if (p == n) { return t; } p = p.NextNode; } while (p is XText); } } } } }
using System; using System.Data; using System.Data.OleDb; using System.Collections; using System.Configuration; using PCSComUtils.Common; using PCSComUtils.PCSExc; using PCSComUtils.DataAccess; namespace PCSComMaterials.Inventory.DS { public class IV_BalanceLocationDS { public IV_BalanceLocationDS() { } private const string THIS = "PCSComMaterials.Inventory.DS.DS.IV_BalanceLocationDS"; //************************************************************************** /// <Description> /// This method uses to add data to IV_BalanceLocation /// </Description> /// <Inputs> /// IV_BalanceLocationVO /// </Inputs> /// <Outputs> /// newly inserted primarkey value /// </Outputs> /// <Returns> /// void /// </Returns> /// <Authors> /// Code generate /// </Authors> /// <History> /// Thursday, October 05, 2006 /// </History> /// <Notes> /// </Notes> //************************************************************************** public void Add(object pobjObjectVO) { const string METHOD_NAME = THIS + ".Add()"; OleDbConnection oconPCS =null; OleDbCommand ocmdPCS =null; try { IV_BalanceLocationVO objObject = (IV_BalanceLocationVO) pobjObjectVO; string strSql = String.Empty; oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand("", oconPCS); strSql= "INSERT INTO IV_BalanceLocation(" + IV_BalanceLocationTable.EFFECTDATE_FLD + "," + IV_BalanceLocationTable.OHQUANTITY_FLD + "," + IV_BalanceLocationTable.COMMITQUANTITY_FLD + "," + IV_BalanceLocationTable.PRODUCTID_FLD + "," + IV_BalanceLocationTable.LOCATIONID_FLD + "," + IV_BalanceLocationTable.MASTERLOCATIONID_FLD + "," + IV_BalanceLocationTable.STOCKUMID_FLD + ")" + "VALUES(?,?,?,?,?,?,?)"; ocmdPCS.Parameters.Add(new OleDbParameter(IV_BalanceLocationTable.EFFECTDATE_FLD, OleDbType.Date)); ocmdPCS.Parameters[IV_BalanceLocationTable.EFFECTDATE_FLD].Value = objObject.EffectDate; ocmdPCS.Parameters.Add(new OleDbParameter(IV_BalanceLocationTable.OHQUANTITY_FLD, OleDbType.Decimal)); ocmdPCS.Parameters[IV_BalanceLocationTable.OHQUANTITY_FLD].Value = objObject.OHQuantity; ocmdPCS.Parameters.Add(new OleDbParameter(IV_BalanceLocationTable.COMMITQUANTITY_FLD, OleDbType.Decimal)); ocmdPCS.Parameters[IV_BalanceLocationTable.COMMITQUANTITY_FLD].Value = objObject.CommitQuantity; ocmdPCS.Parameters.Add(new OleDbParameter(IV_BalanceLocationTable.PRODUCTID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[IV_BalanceLocationTable.PRODUCTID_FLD].Value = objObject.ProductID; ocmdPCS.Parameters.Add(new OleDbParameter(IV_BalanceLocationTable.LOCATIONID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[IV_BalanceLocationTable.LOCATIONID_FLD].Value = objObject.LocationID; ocmdPCS.Parameters.Add(new OleDbParameter(IV_BalanceLocationTable.MASTERLOCATIONID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[IV_BalanceLocationTable.MASTERLOCATIONID_FLD].Value = objObject.MasterLocationID; ocmdPCS.Parameters.Add(new OleDbParameter(IV_BalanceLocationTable.STOCKUMID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[IV_BalanceLocationTable.STOCKUMID_FLD].Value = objObject.StockUMID; ocmdPCS.CommandText = strSql; ocmdPCS.Connection.Open(); ocmdPCS.ExecuteNonQuery(); } catch(OleDbException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } catch(InvalidOperationException ex) { throw new PCSDBException(ErrorCode.DUPLICATE_KEY, 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> /// Add and return ID /// </summary> /// <param name="pobjObjectVO"></param> /// <returns></returns> /// <author>Trada</author> /// <date>Tuesday, October 10 2006</date> public int AddAndReturnID(object pobjObjectVO) { const string METHOD_NAME = THIS + ".AddAndReturnID()"; OleDbConnection oconPCS =null; OleDbCommand ocmdPCS =null; try { IV_BalanceLocationVO objObject = (IV_BalanceLocationVO) pobjObjectVO; string strSql = String.Empty; oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand("", oconPCS); strSql= "INSERT INTO IV_BalanceLocation(" + IV_BalanceLocationTable.EFFECTDATE_FLD + "," + IV_BalanceLocationTable.OHQUANTITY_FLD + "," + IV_BalanceLocationTable.COMMITQUANTITY_FLD + "," + IV_BalanceLocationTable.PRODUCTID_FLD + "," + IV_BalanceLocationTable.LOCATIONID_FLD + "," + IV_BalanceLocationTable.MASTERLOCATIONID_FLD + "," + IV_BalanceLocationTable.STOCKUMID_FLD + ")" + "VALUES(?,?,?,?,?,?,?)"; ocmdPCS.Parameters.Add(new OleDbParameter(IV_BalanceLocationTable.EFFECTDATE_FLD, OleDbType.Date)); ocmdPCS.Parameters[IV_BalanceLocationTable.EFFECTDATE_FLD].Value = objObject.EffectDate; ocmdPCS.Parameters.Add(new OleDbParameter(IV_BalanceLocationTable.OHQUANTITY_FLD, OleDbType.Decimal)); ocmdPCS.Parameters[IV_BalanceLocationTable.OHQUANTITY_FLD].Value = objObject.OHQuantity; ocmdPCS.Parameters.Add(new OleDbParameter(IV_BalanceLocationTable.COMMITQUANTITY_FLD, OleDbType.Decimal)); if (objObject.CommitQuantity != 0) { ocmdPCS.Parameters[IV_BalanceLocationTable.COMMITQUANTITY_FLD].Value = objObject.CommitQuantity; } else { ocmdPCS.Parameters[IV_BalanceLocationTable.COMMITQUANTITY_FLD].Value = DBNull.Value; } ocmdPCS.Parameters.Add(new OleDbParameter(IV_BalanceLocationTable.PRODUCTID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[IV_BalanceLocationTable.PRODUCTID_FLD].Value = objObject.ProductID; ocmdPCS.Parameters.Add(new OleDbParameter(IV_BalanceLocationTable.LOCATIONID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[IV_BalanceLocationTable.LOCATIONID_FLD].Value = objObject.LocationID; ocmdPCS.Parameters.Add(new OleDbParameter(IV_BalanceLocationTable.MASTERLOCATIONID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[IV_BalanceLocationTable.MASTERLOCATIONID_FLD].Value = objObject.MasterLocationID; ocmdPCS.Parameters.Add(new OleDbParameter(IV_BalanceLocationTable.STOCKUMID_FLD, OleDbType.Integer)); if (objObject.StockUMID != 0) { ocmdPCS.Parameters[IV_BalanceLocationTable.STOCKUMID_FLD].Value = objObject.StockUMID; } else { ocmdPCS.Parameters[IV_BalanceLocationTable.STOCKUMID_FLD].Value = DBNull.Value; } strSql += " ; SELECT @@IDENTITY AS NEWID"; ocmdPCS.CommandText = strSql; ocmdPCS.Connection.Open(); object objReturn = ocmdPCS.ExecuteScalar(); if (objReturn != null) { return int.Parse(objReturn.ToString()); } else { return 0; } } catch(OleDbException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } catch(InvalidOperationException ex) { throw new PCSDBException(ErrorCode.DUPLICATE_KEY, 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(); } } } } //************************************************************************** /// <Description> /// This method uses to delete data from IV_BalanceLocation /// </Description> /// <Inputs> /// ID /// </Inputs> /// <Outputs> /// void /// </Outputs> /// <Returns> /// /// </Returns> /// <Authors> /// Code generate /// </Authors> /// <History> /// 09-Dec-2004 /// </History> /// <Notes> /// </Notes> //************************************************************************** public void Delete(int pintID) { const string METHOD_NAME = THIS + ".Delete()"; string strSql = String.Empty; strSql= "DELETE " + IV_BalanceLocationTable.TABLE_NAME + " WHERE " + "BalanceLocationID" + "=" + 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) { 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(); } } } } //************************************************************************** /// <Description> /// This method uses to get data from IV_BalanceLocation /// </Description> /// <Inputs> /// ID /// </Inputs> /// <Outputs> /// IV_BalanceLocationVO /// </Outputs> /// <Returns> /// IV_BalanceLocationVO /// </Returns> /// <Authors> /// Code Generate /// </Authors> /// <History> /// Thursday, October 05, 2006 /// </History> /// <Notes> /// </Notes> //************************************************************************** public object 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 " + IV_BalanceLocationTable.BALANCELOCATIONID_FLD + "," + IV_BalanceLocationTable.EFFECTDATE_FLD + "," + IV_BalanceLocationTable.OHQUANTITY_FLD + "," + IV_BalanceLocationTable.COMMITQUANTITY_FLD + "," + IV_BalanceLocationTable.PRODUCTID_FLD + "," + IV_BalanceLocationTable.LOCATIONID_FLD + "," + IV_BalanceLocationTable.MASTERLOCATIONID_FLD + "," + IV_BalanceLocationTable.STOCKUMID_FLD + " FROM " + IV_BalanceLocationTable.TABLE_NAME +" WHERE " + IV_BalanceLocationTable.BALANCELOCATIONID_FLD + "=" + pintID; oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); odrPCS = ocmdPCS.ExecuteReader(); IV_BalanceLocationVO objObject = new IV_BalanceLocationVO(); while (odrPCS.Read()) { objObject.BalanceLocationID = int.Parse(odrPCS[IV_BalanceLocationTable.BALANCELOCATIONID_FLD].ToString()); objObject.EffectDate = DateTime.Parse(odrPCS[IV_BalanceLocationTable.EFFECTDATE_FLD].ToString()); objObject.OHQuantity = Decimal.Parse(odrPCS[IV_BalanceLocationTable.OHQUANTITY_FLD].ToString()); objObject.CommitQuantity = Decimal.Parse(odrPCS[IV_BalanceLocationTable.COMMITQUANTITY_FLD].ToString()); objObject.ProductID = int.Parse(odrPCS[IV_BalanceLocationTable.PRODUCTID_FLD].ToString()); objObject.LocationID = int.Parse(odrPCS[IV_BalanceLocationTable.LOCATIONID_FLD].ToString()); objObject.MasterLocationID = int.Parse(odrPCS[IV_BalanceLocationTable.MASTERLOCATIONID_FLD].ToString()); objObject.StockUMID = int.Parse(odrPCS[IV_BalanceLocationTable.STOCKUMID_FLD].ToString()); } 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(); } } } } //************************************************************************** /// <Description> /// This method uses to update data to IV_BalanceLocation /// </Description> /// <Inputs> /// IV_BalanceLocationVO /// </Inputs> /// <Outputs> /// /// </Outputs> /// <Returns> /// /// </Returns> /// <Authors> /// Code Generate /// </Authors> /// <History> /// 09-Dec-2004 /// </History> /// <Notes> /// </Notes> //************************************************************************** public void Update(object pobjObjecVO) { const string METHOD_NAME = THIS + ".Update()"; IV_BalanceLocationVO objObject = (IV_BalanceLocationVO) pobjObjecVO; //prepare value for parameters OleDbConnection oconPCS =null; OleDbCommand ocmdPCS = null; try { string strSql = String.Empty; oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); strSql= "UPDATE IV_BalanceLocation SET " + IV_BalanceLocationTable.EFFECTDATE_FLD + "= ?" + "," + IV_BalanceLocationTable.OHQUANTITY_FLD + "= ?" + "," + IV_BalanceLocationTable.COMMITQUANTITY_FLD + "= ?" + "," + IV_BalanceLocationTable.PRODUCTID_FLD + "= ?" + "," + IV_BalanceLocationTable.LOCATIONID_FLD + "= ?" + "," + IV_BalanceLocationTable.MASTERLOCATIONID_FLD + "= ?" + "," + IV_BalanceLocationTable.STOCKUMID_FLD + "= ?" +" WHERE " + IV_BalanceLocationTable.BALANCELOCATIONID_FLD + "= ?"; ocmdPCS.Parameters.Add(new OleDbParameter(IV_BalanceLocationTable.EFFECTDATE_FLD, OleDbType.Date)); ocmdPCS.Parameters[IV_BalanceLocationTable.EFFECTDATE_FLD].Value = objObject.EffectDate; ocmdPCS.Parameters.Add(new OleDbParameter(IV_BalanceLocationTable.OHQUANTITY_FLD, OleDbType.Decimal)); ocmdPCS.Parameters[IV_BalanceLocationTable.OHQUANTITY_FLD].Value = objObject.OHQuantity; ocmdPCS.Parameters.Add(new OleDbParameter(IV_BalanceLocationTable.COMMITQUANTITY_FLD, OleDbType.Decimal)); if (objObject.CommitQuantity != 0) { ocmdPCS.Parameters[IV_BalanceLocationTable.COMMITQUANTITY_FLD].Value = objObject.CommitQuantity; } else { ocmdPCS.Parameters[IV_BalanceLocationTable.COMMITQUANTITY_FLD].Value = DBNull.Value; } ocmdPCS.Parameters.Add(new OleDbParameter(IV_BalanceLocationTable.PRODUCTID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[IV_BalanceLocationTable.PRODUCTID_FLD].Value = objObject.ProductID; ocmdPCS.Parameters.Add(new OleDbParameter(IV_BalanceLocationTable.LOCATIONID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[IV_BalanceLocationTable.LOCATIONID_FLD].Value = objObject.LocationID; ocmdPCS.Parameters.Add(new OleDbParameter(IV_BalanceLocationTable.MASTERLOCATIONID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[IV_BalanceLocationTable.MASTERLOCATIONID_FLD].Value = objObject.MasterLocationID; ocmdPCS.Parameters.Add(new OleDbParameter(IV_BalanceLocationTable.STOCKUMID_FLD, OleDbType.Integer)); if (objObject.StockUMID != 0) { ocmdPCS.Parameters[IV_BalanceLocationTable.STOCKUMID_FLD].Value = objObject.StockUMID; } else { ocmdPCS.Parameters[IV_BalanceLocationTable.STOCKUMID_FLD].Value = DBNull.Value; } ocmdPCS.Parameters.Add(new OleDbParameter(IV_BalanceLocationTable.BALANCELOCATIONID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[IV_BalanceLocationTable.BALANCELOCATIONID_FLD].Value = objObject.BalanceLocationID; ocmdPCS.CommandText = strSql; ocmdPCS.Connection.Open(); ocmdPCS.ExecuteNonQuery(); } catch(OleDbException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } catch(InvalidOperationException ex) { throw new PCSDBException(ErrorCode.DUPLICATE_KEY, 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(); } } } } //************************************************************************** /// <Description> /// This method uses to get all data from IV_BalanceLocation /// </Description> /// <Inputs> /// /// </Inputs> /// <Outputs> /// DataSet /// </Outputs> /// <Returns> /// DataSet /// </Returns> /// <Authors> /// Code Generate /// </Authors> /// <History> /// Thursday, October 05, 2006 /// </History> /// <Notes> /// </Notes> //************************************************************************** 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 " + IV_BalanceLocationTable.BALANCELOCATIONID_FLD + "," + IV_BalanceLocationTable.EFFECTDATE_FLD + "," + IV_BalanceLocationTable.OHQUANTITY_FLD + "," + IV_BalanceLocationTable.COMMITQUANTITY_FLD + "," + IV_BalanceLocationTable.PRODUCTID_FLD + "," + IV_BalanceLocationTable.LOCATIONID_FLD + "," + IV_BalanceLocationTable.MASTERLOCATIONID_FLD + "," + IV_BalanceLocationTable.STOCKUMID_FLD + " FROM " + IV_BalanceLocationTable.TABLE_NAME; oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS); odadPCS.Fill(dstPCS,IV_BalanceLocationTable.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> /// Get all balance location in this period and previous period /// </summary> /// <param name="pdtmEffectDate"></param> /// <returns></returns> /// <author>Trada</author> /// <date>Wednesday, October 11 2006</date> public DataSet GetAllBalanceLocationInTwoPeriod(DateTime pdtmEffectDate) { const string METHOD_NAME = THIS + ".GetAllBalanceLocationInTwoPeriod()"; DataSet dstPCS = new DataSet(); OleDbConnection oconPCS =null; OleDbCommand ocmdPCS = null; try { string strSql = String.Empty; strSql= "SELECT " + IV_BalanceLocationTable.BALANCELOCATIONID_FLD + "," + IV_BalanceLocationTable.EFFECTDATE_FLD + "," + IV_BalanceLocationTable.OHQUANTITY_FLD + "," + IV_BalanceLocationTable.COMMITQUANTITY_FLD + "," + IV_BalanceLocationTable.PRODUCTID_FLD + "," + IV_BalanceLocationTable.LOCATIONID_FLD + "," + IV_BalanceLocationTable.MASTERLOCATIONID_FLD + "," + IV_BalanceLocationTable.STOCKUMID_FLD + " FROM " + IV_BalanceLocationTable.TABLE_NAME + " WHERE " + IV_BalanceLocationTable.EFFECTDATE_FLD + " = '" + pdtmEffectDate.ToShortDateString() + "' OR " + IV_BalanceLocationTable.EFFECTDATE_FLD + " = '" + pdtmEffectDate.AddMonths(-1).ToShortDateString() + "'"; oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS); odadPCS.Fill(dstPCS,IV_BalanceLocationTable.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(); } } } } //************************************************************************** /// <Description> /// This method uses to update a DataSet /// </Description> /// <Inputs> /// DataSet /// </Inputs> /// <Outputs> /// /// </Outputs> /// <Returns> /// /// </Returns> /// <Authors> /// Code Generate /// </Authors> /// <History> /// Thursday, October 05, 2006 /// </History> /// <Notes> /// </Notes> //************************************************************************** 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 " + IV_BalanceLocationTable.BALANCELOCATIONID_FLD + "," + IV_BalanceLocationTable.EFFECTDATE_FLD + "," + IV_BalanceLocationTable.OHQUANTITY_FLD + "," + IV_BalanceLocationTable.COMMITQUANTITY_FLD + "," + IV_BalanceLocationTable.PRODUCTID_FLD + "," + IV_BalanceLocationTable.LOCATIONID_FLD + "," + IV_BalanceLocationTable.MASTERLOCATIONID_FLD + "," + IV_BalanceLocationTable.STOCKUMID_FLD + " FROM " + IV_BalanceLocationTable.TABLE_NAME; oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); odadPCS.SelectCommand = new OleDbCommand(strSql, oconPCS); odcbPCS = new OleDbCommandBuilder(odadPCS); pData.EnforceConstraints = false; odadPCS.Update(pData,IV_BalanceLocationTable.TABLE_NAME); } catch(OleDbException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } catch(InvalidOperationException ex) { throw new PCSDBException(ErrorCode.DUPLICATE_KEY, 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(); } } } } } }
//------------------------------------------------------------------------------------------------------------------------------------------------------------------- // <copyright file="WindowsService.cs">(c) 2017 Mike Fourie and Contributors (https://github.com/mikefourie/MSBuildExtensionPack) under MIT License. See https://opensource.org/licenses/MIT </copyright> //------------------------------------------------------------------------------------------------------------------------------------------------------------------- namespace MSBuild.ExtensionPack.Computer { using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Management; using System.ServiceProcess; using Microsoft.Build.Framework; using Microsoft.Win32; /// <summary> /// Start mode of the Windows base service. /// </summary> internal enum ServiceStartMode { /// <summary> /// Service to be started automatically by the Service Control Manager during system startup. /// </summary> Automatic, /// <summary> /// Device driver started by the operating system loader. This value is valid only for driver services. /// </summary> Boot, /// <summary> /// Device driver started by the operating system initialization process. This value is valid only for driver services. /// </summary> System, /// <summary> /// Service to be started by the Service Control Manager when a process calls the StartService method. /// </summary> Manual, /// <summary> /// Service that can no longer be started. /// </summary> Disabled, /// <summary> /// Service to be started automatically by the Service Control Manager after all the service designated as Automatic have been started. /// </summary> AutomaticDelayedStart, } /// <summary> /// The return code from the WMI Class Win32_Service /// </summary> internal enum ServiceReturnCode { /// <summary> /// Success /// </summary> Success = 0, /// <summary> /// Not Supported /// </summary> NotSupported = 1, /// <summary> /// Access Denied /// </summary> AccessDenied = 2, /// <summary> /// Dependent Services Running /// </summary> DependentServicesRunning = 3, /// <summary> /// Invalid Service Control /// </summary> InvalidServiceControl = 4, /// <summary> /// Service Cannot Accept Control /// </summary> ServiceCannotAcceptControl = 5, /// <summary> /// Service Not Active /// </summary> ServiceNotActive = 6, /// <summary> /// Service Request Timeout /// </summary> ServiceRequestTimeout = 7, /// <summary> /// Unknown Failure /// </summary> UnknownFailure = 8, /// <summary> /// Path Not Found /// </summary> PathNotFound = 9, /// <summary> /// Service Already Running /// </summary> ServiceAlreadyRunning = 10, /// <summary> /// Service Database Locked /// </summary> ServiceDatabaseLocked = 11, /// <summary> /// Service Dependency Deleted /// </summary> ServiceDependencyDeleted = 12, /// <summary> /// Service Dependency Failure /// </summary> ServiceDependencyFailure = 13, /// <summary> /// Service Disabled /// </summary> ServiceDisabled = 14, /// <summary> /// Service Logon Failure /// </summary> ServiceLogOnFailure = 15, /// <summary> /// Service Marked For Deletion /// </summary> ServiceMarkedForDeletion = 16, /// <summary> /// Service No Thread /// </summary> ServiceNoThread = 17, /// <summary> /// Status Circular Dependency /// </summary> StatusCircularDependency = 18, /// <summary> /// Status Duplicate Name /// </summary> StatusDuplicateName = 19, /// <summary> /// Status Invalid Name /// </summary> StatusInvalidName = 20, /// <summary> /// Status Invalid Parameter /// </summary> StatusInvalidParameter = 21, /// <summary> /// Status Invalid Service Account /// </summary> StatusInvalidServiceAccount = 22, /// <summary> /// Status Service Exists /// </summary> StatusServiceExists = 23, /// <summary> /// Service Already Paused /// </summary> ServiceAlreadyPaused = 24 } /// <summary> /// Type of services provided to processes that call them. /// </summary> [Flags] internal enum ServiceTypes { /// <summary> /// Kernel Driverr /// </summary> KernalDriver = 1, /// <summary> /// File System Driver /// </summary> FileSystemDriver = 2, /// <summary> /// Adapter /// </summary> Adapter = 4, /// <summary> /// Recognizer Driver /// </summary> RecognizerDriver = 8, /// <summary> /// Own Process /// </summary> OwnProcess = 16, /// <summary> /// Share Process /// </summary> ShareProcess = 32, /// <summary> /// Interactive Process /// </summary> InteractiveProcess = 256 } /// <summary> /// Severity of the error if the Create method fails to start. The value indicates the action taken by the startup program if failure occurs. All errors are logged by the system. /// </summary> internal enum ServiceErrorControl { /// <summary> /// User is not notified. /// </summary> UserNotNotified = 0, /// <summary> /// User is notified. /// </summary> UserNotified = 1, /// <summary> /// System is restarted with the last-known-good configuration. /// </summary> SystemRestartedWithLastKnownGoodConfiguration = 2, /// <summary> /// System attempts to start with a good configuration. /// </summary> SystemAttemptsToStartWithAGoodConfiguration = 3 } /// <summary> /// Current state of the base service /// </summary> internal enum ServiceState { /// <summary> /// Running /// </summary> Running, /// <summary> /// Stopped /// </summary> Stopped, /// <summary> /// Paused /// </summary> Paused, /// <summary> /// Start Pending /// </summary> StartPending, /// <summary> /// Stop Pending /// </summary> StopPending, /// <summary> /// Pause Pending /// </summary> PausePending, /// <summary> /// Continue Pending /// </summary> ContinuePending } /// <summary> /// <b>Valid TaskActions are:</b> /// <para><i>CheckExists</i> (<b>Required: </b> ServiceName <b>Optional: </b>MachineName, RemoteUser, RemoteUserPassword <b>Output: </b>Exists)</para> /// <para><i>Delete</i> (<b>Required: </b> ServiceName <b>Optional: </b>MachineName)</para> /// <para><i>Disable</i> (<b>Required: </b> ServiceName <b>Optional: </b>MachineName)</para> /// <para><i>Install</i> (<b>Required: </b> ServiceName, ServicePath, User<b>Optional: </b>Force, StartupType, CommandLineArguments, Description, ServiceDependencies, ServiceDisplayName, MachineName, RemoteUser, RemoteUserPassword)</para> /// <para><i>Restart</i> (<b>Required: </b> ServiceName <b>Optional: </b>MachineName). Any running directly dependent services will be restarted too.</para> /// <para><i>SetAutomatic</i> (<b>Required: </b> ServiceName <b>Optional: </b>MachineName)</para> /// <para><i>SetManual</i> (<b>Required: </b> ServiceName <b>Optional: </b>MachineName)</para> /// <para><i>Start</i> (<b>Required: </b> ServiceName or Services <b>Optional: </b>MachineName, RetryAttempts)</para> /// <para><i>Stop</i> (<b>Required: </b> ServiceName or Services <b>Optional: </b>MachineName, RetryAttempts)</para> /// <para><i>Uninstall</i> (<b>Required: </b> ServicePath <b>Optional: </b>MachineName, RemoteUser, RemoteUserPassword)</para> /// <para><i>UpdateIdentity</i> (<b>Required: </b> ServiceName, User, Password <b>Optional: </b>MachineName)</para> /// <para><b>Remote Execution Support:</b> Yes</para> /// </summary> /// <example> /// <code lang="xml"><![CDATA[ /// <Project ToolsVersion="4.0" DefaultTargets="Default" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> /// <PropertyGroup> /// <TPath>$(MSBuildProjectDirectory)\..\MSBuild.ExtensionPack.tasks</TPath> /// <TPath Condition="Exists('$(MSBuildProjectDirectory)\..\..\Common\MSBuild.ExtensionPack.tasks')">$(MSBuildProjectDirectory)\..\..\Common\MSBuild.ExtensionPack.tasks</TPath> /// <User>serviceAcct</User> /// <Password>P2ssw0rd</Password> /// <RemoteMachine>VSTS2008</RemoteMachine> /// <RemoteUser>vsts2008\tfssetup</RemoteUser> /// <RemoteUserPassword>1Setuptfs</RemoteUserPassword> /// </PropertyGroup> /// <Import Project="$(TPath)"/> /// <Target Name="Default"> /// <!-- check whether a service exists (this should return true in most cases) --> /// <MSBuild.ExtensionPack.Computer.WindowsService TaskAction="CheckExists" ServiceName="Schedule"> /// <Output TaskParameter="Exists" PropertyName="DoesExist"/> /// </MSBuild.ExtensionPack.Computer.WindowsService> /// <Message Text="Schedule service exists: $(DoesExist)"/> /// <!-- check whether another service exists (this should return false)--> /// <MSBuild.ExtensionPack.Computer.WindowsService TaskAction="CheckExists" ServiceName="ThisServiceShouldNotExist"> /// <Output TaskParameter="Exists" PropertyName="DoesExist"/> /// </MSBuild.ExtensionPack.Computer.WindowsService> /// <Message Text="ThisServiceShouldNotExist service exists: $(DoesExist)"/> /// <!-- Check whether a service exists on a Remote Machine(this should return true in most cases) --> /// <MSBuild.ExtensionPack.Computer.WindowsService TaskAction="CheckExists" ServiceName="Schedule" RemoteUser="$(RemoteUser)" RemoteUserPassword="$(RemoteUserPassword)" MachineName="$(RemoteMachine)"> /// <Output TaskParameter="Exists" PropertyName="DoesExist"/> /// </MSBuild.ExtensionPack.Computer.WindowsService> /// <Message Text="Schedule service exists on '$(RemoteMachine)': $(DoesExist)"/> /// <!-- Start a service --> /// <MSBuild.ExtensionPack.Computer.WindowsService TaskAction="Start" ServiceName="MSSQLSERVER"/> /// <!-- Start a service on a Remote Machine --> /// <MSBuild.ExtensionPack.Computer.WindowsService TaskAction="Start" ServiceName="BITS" RemoteUser="$(RemoteUser)" RemoteUserPassword="$(RemoteUserPassword)" MachineName="$(RemoteMachine)" /> /// <!-- Stop a service --> /// <MSBuild.ExtensionPack.Computer.WindowsService TaskAction="Stop" ServiceName="MSSQLSERVER"/> /// <!-- Stop a service on a Remote Machine --> /// <MSBuild.ExtensionPack.Computer.WindowsService TaskAction="Stop" ServiceName="BITS" RemoteUser="$(RemoteUser)" RemoteUserPassword="$(RemoteUserPassword)" MachineName="$(RemoteMachine)"/> /// <!-- Uninstall a service on the Local Machine --> /// <MSBuild.ExtensionPack.Computer.WindowsService TaskAction="Uninstall" ServiceName="__TestService1" ServicePath="c:\WINDOWS\system32\taskmgr.exe" /> /// <!-- Uninstall a service on a Remote Machine --> /// <MSBuild.ExtensionPack.Computer.WindowsService TaskAction="Uninstall" ServiceName="__TestService1" ServicePath="c:\WINDOWS\system32\taskmgr.exe" RemoteUser="$(RemoteUser)" RemoteUserPassword="$(RemoteUserPassword)" MachineName="$(RemoteMachine)" /> /// <!-- Install a service on the Local machine --> /// <MSBuild.ExtensionPack.Computer.WindowsService TaskAction="Install" ServiceName="__TestService1" User="$(User)" Password="$(password)" ServicePath="c:\WINDOWS\system32\taskmgr.exe" /> /// <!-- Install a service on a Remote Machine --> /// <MSBuild.ExtensionPack.Computer.WindowsService TaskAction="Install" ServiceName="__TestService1" User="$(User)" Password="$(password)" ServicePath="c:\WINDOWS\system32\taskmgr.exe" RemoteUser="$(RemoteUser)" RemoteUserPassword="$(RemoteUserPassword)" MachineName="$(RemoteMachine)" /> /// <!-- Disable a service --> /// <MSBuild.ExtensionPack.Computer.WindowsService TaskAction="Disable" ServiceName="__TestService1"/> /// <!-- Disable a service on a Remote Machine --> /// <MSBuild.ExtensionPack.Computer.WindowsService TaskAction="Disable" ServiceName="__TestService1" RemoteUser="$(RemoteUser)" RemoteUserPassword="$(RemoteUserPassword)" MachineName="$(RemoteMachine)"/> /// <!-- Set a service to start automatically on system startup--> /// <MSBuild.ExtensionPack.Computer.WindowsService TaskAction="SetAutomatic" ServiceName="__TestService1"/> /// <!-- Set a service to start automatically on system startup on a Remote Machine --> /// <MSBuild.ExtensionPack.Computer.WindowsService TaskAction="SetAutomatic" ServiceName="__TestService1" RemoteUser="$(RemoteUser)" RemoteUserPassword="$(RemoteUserPassword)" MachineName="$(RemoteMachine)"/> /// <!-- Set a service to start manually --> /// <MSBuild.ExtensionPack.Computer.WindowsService TaskAction="SetManual" ServiceName="__TestService1"/> /// <!-- Set a service to start manually on a Remote Machine --> /// <MSBuild.ExtensionPack.Computer.WindowsService TaskAction="SetManual" ServiceName="__TestService1" RemoteUser="$(RemoteUser)" RemoteUserPassword="$(RemoteUserPassword)" MachineName="$(RemoteMachine)"/> /// <!-- Update the Identity that the service runs in --> /// <MSBuild.ExtensionPack.Computer.WindowsService TaskAction="UpdateIdentity" ServiceName="__TestService1" User="$(User)" Password="$(Password)"/> /// <!-- Update the Identity that the service on a Remote Machine runs in --> /// <MSBuild.ExtensionPack.Computer.WindowsService TaskAction="UpdateIdentity" ServiceName="__TestService1" User="$(User)" Password="$(Password)" RemoteUser="$(RemoteUser)" RemoteUserPassword="$(RemoteUserPassword)" MachineName="$(RemoteMachine)"/> /// </Target> /// </Project> /// ]]></code> /// </example> public class WindowsService : BaseTask { private const string CheckExistsTaskAction = "CheckExists"; private const string DeleteTaskAction = "Delete"; private const string DisableTaskAction = "Disable"; private const string InstallTaskAction = "Install"; private const string RestartTaskAction = "Restart"; private const string SetAutomaticTaskAction = "SetAutomatic"; private const string SetManualTaskAction = "SetManual"; private const string StartTaskAction = "Start"; private const string StopTaskAction = "Stop"; private const string UninstallTaskAction = "Uninstall"; private const string UpdateIdentityTaskAction = "UpdateIdentity"; private const string StartupTypeAutomatic = "Automatic"; private const string StartupTypeAutomaticDelayed = "AutomaticDelayedStart"; private const string StartupTypeDisabled = "Disabled"; private const string StartupTypeManual = "Manual"; private const bool RemoteExecutionAvailable = true; /// <summary> /// Sets the number of times to attempt Starting / Stopping a service. Default is 60. /// </summary> public int RetryAttempts { get; set; } = 60; /// <summary> /// Gets whether the service exists /// </summary> [Output] public bool Exists { get; set; } /// <summary> /// Sets the user. /// </summary> public string User { get; set; } /// <summary> /// The Name of the service. Note, this is the 'Service Name' as displayed in services.msc, NOT the 'Display Name' /// </summary> public string ServiceName { get; set; } /// <summary> /// The Display Name of the service. Defaults to ServiceName. /// </summary> public string ServiceDisplayName { get; set; } /// <summary> /// Sets the path of the service executable /// </summary> public ITaskItem ServicePath { get; set; } /// <summary> /// Sets user password /// </summary> public string Password { get; set; } /// <summary> /// Sets a value indicating whether to delete a service if it already exists when calling Install /// </summary> public bool Force { get; set; } /// <summary> /// Sets the service description /// </summary> public string Description { get; set; } /// <summary> /// Sets the user to impersonate on remote server. /// </summary> public string RemoteUser { get; set; } /// <summary> /// Sets the password for the user to impersonate on remote server. /// </summary> public string RemoteUserPassword { get; set; } /// <summary> /// Sets the services upon which the installed service depends. /// </summary> public ITaskItem[] ServiceDependencies { get; set; } /// <summary> /// Sets the command line arguments to be passed to the service. /// </summary> public string CommandLineArguments { get; set; } /// <summary> /// Sets the Startup Type of the service. /// </summary> public string StartupType { get; set; } /// <summary> /// Sets the collection of Services to target in parallel. See TaskAction parameters for which TaskActions support this. /// </summary> public ITaskItem[] Services { get; set; } /// <summary> /// Performs the action of this task. /// </summary> protected override void InternalExecute() { if (!this.TargetingLocalMachine(RemoteExecutionAvailable) && (string.IsNullOrEmpty(this.RemoteUser) || string.IsNullOrEmpty(this.RemoteUserPassword))) { this.LogTaskMessage(MessageImportance.Low, "No RemoteUser or RemoteUserPassword supplied. Attempting Integrated Security."); } if (this.Services == null) { if (string.IsNullOrEmpty(this.ServiceDisplayName)) { this.ServiceDisplayName = this.ServiceName; } if (this.ServiceDoesExist(this.ServiceName) == false && this.TaskAction != InstallTaskAction && this.TaskAction != CheckExistsTaskAction && this.TaskAction != UninstallTaskAction && this.TaskAction != DeleteTaskAction) { this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "Service does not exist: {0}", this.ServiceDisplayName)); return; } } switch (this.TaskAction) { case InstallTaskAction: this.Install(); break; case DeleteTaskAction: this.DeleteService(); break; case UninstallTaskAction: this.Uninstall(); break; case StopTaskAction: this.Stop(); break; case StartTaskAction: this.Start(); break; case RestartTaskAction: this.Restart(); break; case DisableTaskAction: this.SetStartupType(StartupTypeDisabled); break; case SetManualTaskAction: this.SetStartupType(StartupTypeManual); break; case SetAutomaticTaskAction: this.SetStartupType(StartupTypeAutomatic); break; case CheckExistsTaskAction: this.CheckExists(this.ServiceName, false); break; case UpdateIdentityTaskAction: this.UpdateIdentity(); break; default: this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "Invalid TaskAction passed: {0}", this.TaskAction)); return; } } private static string GetServiceStartupType(string startupType) { if (string.IsNullOrEmpty(startupType) || (string.Compare(startupType, StartupTypeAutomaticDelayed, StringComparison.CurrentCultureIgnoreCase) == 0)) { return StartupTypeAutomatic; } return startupType; } private void Restart() { this.LogTaskMessage(MessageImportance.High, string.Format(CultureInfo.CurrentCulture, "Restarting: {0} on {1}", this.ServiceName, this.MachineName)); using (ServiceController sc = new ServiceController(this.ServiceName, this.MachineName)) { List<ServiceController> runningDependencies = sc.DependentServices.Where(s => s.Status == ServiceControllerStatus.Running).ToList(); if (!sc.Status.Equals(ServiceControllerStatus.Stopped) && !sc.Status.Equals(ServiceControllerStatus.StopPending)) { this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "...Stopping: {0}", this.ServiceName)); sc.Stop(); sc.WaitForStatus(ServiceControllerStatus.Stopped); this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "...Starting: {0}", this.ServiceName)); sc.Start(); sc.WaitForStatus(ServiceControllerStatus.Running); foreach (ServiceController s in runningDependencies) { this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "...Starting dependent service: {0}", s.ServiceName)); s.Start(); sc.WaitForStatus(ServiceControllerStatus.Running); } } else { this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "Service is stopped: {0}", this.ServiceName)); } } } private void UpdateIdentity() { bool targetLocal = this.TargetingLocalMachine(RemoteExecutionAvailable); string userName = this.User; if (userName.IndexOf('\\') < 0) { userName = ".\\" + userName; } if (this.ServiceDoesExist(this.ServiceName)) { this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Updating Identity: {0} on '{1}' to '{2}'", this.ServiceDisplayName, this.MachineName, userName)); ManagementObject wmi = this.RetrieveManagementObject(this.ServiceName, targetLocal); object[] paramList = new object[] { null, null, null, null, null, null, userName, this.Password }; object result = wmi.InvokeMethod("Change", paramList); int returnCode = Convert.ToInt32(result, CultureInfo.InvariantCulture); if ((ServiceReturnCode)returnCode != ServiceReturnCode.Success) { this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "Error changing service identity of {0} on '{1}' to '{2}'", this.ServiceDisplayName, this.MachineName, userName)); } } else { this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "Service: {0} does not exist on: {1}.", this.ServiceDisplayName, this.MachineName)); } } private void CheckExists(string serviceName, bool overrideSDN) { string displayName = this.ServiceDisplayName; if (overrideSDN) { displayName = serviceName; } if (this.ServiceDoesExist(serviceName)) { this.Exists = true; this.LogTaskMessage(MessageImportance.Low, string.Format(CultureInfo.CurrentCulture, "Service: {0} exists on: {1}.", displayName, this.MachineName)); } else { this.Exists = false; this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Service: {0} does not exist on: {1}.", displayName, this.MachineName)); } } private void SetStartupType(string startup) { bool targetLocal = this.TargetingLocalMachine(RemoteExecutionAvailable); this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Setting StartUp Type to {0} for {1} on '{2}'.", startup, this.ServiceDisplayName, this.MachineName)); try { ManagementObject wmi = this.RetrieveManagementObject(this.ServiceName, targetLocal); object[] paramList = new object[] { startup }; object result = wmi.InvokeMethod("ChangeStartMode", paramList); int returnCode = Convert.ToInt32(result, CultureInfo.InvariantCulture); if ((ServiceReturnCode)returnCode != ServiceReturnCode.Success) { this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "SetStartupType [{2}] failed with return code '[{0}] {1}'", returnCode, (ServiceReturnCode)returnCode, startup)); } } catch (Exception ex) { this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "SetStartupType [{0}] failed with error '{1}'", startup, ex.Message)); throw; } } private ServiceStartMode GetServiceStartMode(string serviceName) { ServiceStartMode toReturn = ServiceStartMode.Manual; bool targetLocal = this.TargetingLocalMachine(RemoteExecutionAvailable); try { ManagementObject wmi = this.RetrieveManagementObject(serviceName, targetLocal); string startMode = wmi.Properties["StartMode"].Value.ToString().Trim(); switch (startMode) { case "Auto": toReturn = ServiceStartMode.Automatic; break; case "Boot": toReturn = ServiceStartMode.Boot; break; case "Disabled": toReturn = ServiceStartMode.Disabled; break; case "Manual": toReturn = ServiceStartMode.Manual; break; case "System": toReturn = ServiceStartMode.System; break; } } catch (Exception ex) { this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "An error occurred in GetServiceStartMode of {0} on '{1}'. Message: {2}", serviceName, this.MachineName, ex.Message)); throw; } return toReturn; } private void Start() { if (this.Services == null) { this.StartLogic(this.ServiceName, false); return; } System.Threading.Tasks.Parallel.ForEach(this.Services, service => this.StartLogic(service.ItemSpec, true)); } private void StartLogic(string serviceName, bool overrideSDN) { string displayName = this.ServiceDisplayName; if (overrideSDN) { displayName = serviceName; } // If the Service is disabled then we will just error out 60 times inside StartService() so we will // short-circuit the errors and let the user know. // Possible enhancement [SStJean]: Add ForceStart property to Task and change StartMode to Manual instead of throwing error. if (this.GetServiceStartMode(serviceName) == ServiceStartMode.Disabled) { this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "Cannot start service '{0}' on '{1}': Service is Disabled", displayName, this.MachineName)); return; } int i = 1; while (i <= this.RetryAttempts) { ServiceState state = this.GetServiceState(serviceName, overrideSDN); switch (state) { // We can't do anything when Service is in these states, so we log, count, pause and loop. case ServiceState.ContinuePending: case ServiceState.PausePending: case ServiceState.StartPending: case ServiceState.StopPending: this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Please wait, Service state: {0} on '{1}' - {2}...", displayName, this.MachineName, state)); ++i; break; case ServiceState.Paused: case ServiceState.Stopped: this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Starting: {0} on '{1}' - {2}...", displayName, this.MachineName, state)); this.StartService(serviceName, overrideSDN); ++i; break; case ServiceState.Running: this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Started: {0}", displayName)); return; } if (i == this.RetryAttempts) { this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "Could not start: {0}", displayName)); return; } System.Threading.Thread.Sleep(2000); } } private void StartService(string serviceName, bool overrideSDN) { string displayName = this.ServiceDisplayName; if (overrideSDN) { displayName = serviceName; } bool targetLocal = this.TargetingLocalMachine(RemoteExecutionAvailable); try { ManagementObject wmi = this.RetrieveManagementObject(serviceName, targetLocal); object[] paramList = new object[] { }; object result = wmi.InvokeMethod("StartService", paramList); int returnCode = Convert.ToInt32(result, CultureInfo.InvariantCulture); if ((ServiceReturnCode)returnCode != ServiceReturnCode.Success) { this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "Start Service failed with return code '[{0}] {1}'", returnCode, (ServiceReturnCode)returnCode)); } } catch (Exception ex) { this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "Start Service [{0} on {1}] failed with error '{2}'", displayName, this.MachineName, ex.Message)); throw; } } private bool Stop() { if (this.Services == null) { return this.StopLogic(this.ServiceName, false); } System.Threading.Tasks.Parallel.ForEach(this.Services, service => this.StopLogic(service.ItemSpec, true)); return true; } private bool StopLogic(string serviceName, bool overrideSDN) { if (!this.ServiceDoesExist(serviceName)) { this.LogTaskMessage(MessageImportance.Low, string.Format(CultureInfo.CurrentCulture, "Service not found: {0} on '{1}'", serviceName, this.MachineName)); return true; } string displayName = this.ServiceDisplayName; if (overrideSDN) { displayName = serviceName; } try { int i = 1; while (i <= this.RetryAttempts) { ServiceState state = this.GetServiceState(serviceName, overrideSDN); switch (state) { // We can't do anything when Service is in these states, so we log, count, pause and loop. case ServiceState.ContinuePending: case ServiceState.PausePending: case ServiceState.StartPending: case ServiceState.StopPending: this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Please wait, Service state: {0} on '{1}' - {2}...", displayName, this.MachineName, state)); ++i; break; case ServiceState.Paused: case ServiceState.Running: this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Stopping: {0} on '{1}' - {2}...", displayName, this.MachineName, state)); if (!this.StopService(serviceName, overrideSDN)) { return false; } ++i; break; case ServiceState.Stopped: this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Stopped: {0} on '{1}'", displayName, this.MachineName)); return true; } if (i == this.RetryAttempts) { this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "Could not stop: {0} on '{1}'", displayName, this.MachineName)); return false; } System.Threading.Thread.Sleep(2000); } } catch (Exception ex) { this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "{0}", ex.Message)); } return true; } private bool StopService(string serviceName, bool overrideSDN) { string displayName = this.ServiceDisplayName; if (overrideSDN) { displayName = serviceName; } bool targetLocal = this.TargetingLocalMachine(RemoteExecutionAvailable); bool noErrors = true; try { ManagementObject wmi = this.RetrieveManagementObject(serviceName, targetLocal); object[] paramList = new object[] { }; // Execute the method and obtain the return values. object result = wmi.InvokeMethod("StopService", paramList); int returnCode = Convert.ToInt32(result, CultureInfo.InvariantCulture); if ((ServiceReturnCode)returnCode != ServiceReturnCode.Success) { this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "Stop Service failed with return code '[{0}] {1}'", returnCode, (ServiceReturnCode)returnCode)); noErrors = false; } } catch (Exception ex) { this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "Stop Service [{0}on {1}] failed with error '{2}'", displayName, this.MachineName, ex.Message)); throw; } return noErrors; } private ManagementObject RetrieveManagementObject(string service, bool targetLocal) { string path = targetLocal ? "\\root\\CIMV2" : string.Format(CultureInfo.InvariantCulture, "\\\\{0}\\root\\CIMV2", this.MachineName); string servicePath = string.Format(CultureInfo.InvariantCulture, "Win32_Service.Name='{0}'", service); ManagementObject wmiReturnObject; using (ManagementObject wmi = new ManagementObject(path, servicePath, null)) { if (!targetLocal) { wmi.Scope.Options.Username = this.RemoteUser; wmi.Scope.Options.Password = this.RemoteUserPassword; } wmiReturnObject = wmi; } return wmiReturnObject; } private ServiceState GetServiceState(string serviceName, bool overrideSDN) { string displayName = this.ServiceDisplayName; if (overrideSDN) { displayName = serviceName; } ServiceState toReturn = ServiceState.Stopped; bool targetLocal = this.TargetingLocalMachine(RemoteExecutionAvailable); try { ManagementObject wmi = this.RetrieveManagementObject(serviceName, targetLocal); string state = wmi.Properties["State"].Value.ToString().Trim(); switch (state) { case "Running": toReturn = ServiceState.Running; break; case "Stopped": toReturn = ServiceState.Stopped; break; case "Paused": toReturn = ServiceState.Paused; break; case "Start Pending": toReturn = ServiceState.StartPending; break; case "Stop Pending": toReturn = ServiceState.StopPending; break; case "Continue Pending": toReturn = ServiceState.ContinuePending; break; case "Pause Pending": toReturn = ServiceState.PausePending; break; } } catch (Exception ex) { this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "An error occurred in GetState of {0} on '{1}'. Message: {2}", displayName, this.MachineName, ex.Message)); throw; } return toReturn; } private bool ServiceDoesExist(string serviceName) { bool targetLocal = this.TargetingLocalMachine(RemoteExecutionAvailable); ManagementObject wmi = this.RetrieveManagementObject(serviceName, targetLocal); try { wmi.InvokeMethod("InterrogateService", null); return true; } catch (ManagementException ex) { if (ex.ErrorCode == ManagementStatus.NotFound) { return false; } throw; } } private void Install() { bool targetLocal = this.TargetingLocalMachine(RemoteExecutionAvailable); // check to see if the exe path has been provided if (this.ServicePath == null) { this.Log.LogError("ServicePath was not provided."); return; } if (string.IsNullOrEmpty(this.User)) { this.Log.LogError("User was not provided."); return; } if (string.IsNullOrEmpty(this.ServiceName)) { this.Log.LogError("ServiceName was not provided."); return; } if (this.ServiceDoesExist(this.ServiceName) && !this.Force) { this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "Install Service failed with code: '{0}'", ServiceReturnCode.StatusServiceExists)); return; } if (this.ServiceDoesExist(this.ServiceName) && this.Force) { if (!this.DeleteService()) { return; } } // check to see if the correct path has been provided if (targetLocal && (System.IO.File.Exists(this.ServicePath.GetMetadata("FullPath")) == false)) { this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "ServicePath does not exist: {0}", this.ServicePath)); return; } var serviceDependencies = new List<string>(); if (this.ServiceDependencies != null) { serviceDependencies.AddRange(this.ServiceDependencies.Select(dep => dep.ItemSpec)); } string serviceStartupType = GetServiceStartupType(this.StartupType); ServiceReturnCode ret = this.Install(this.MachineName, this.ServiceName, this.ServiceDisplayName, this.ServicePath.ToString(), serviceStartupType, this.User, this.Password, serviceDependencies.ToArray(), false, this.RemoteUser, this.RemoteUserPassword); if (ret != ServiceReturnCode.Success) { this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "Install Service failed with code: '{0}'", ret)); } else { this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Install Service succeeded for '{0}' on '{1}'", this.ServiceDisplayName, this.MachineName)); if (!string.IsNullOrEmpty(this.Description)) { this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "...Setting Description for '{0}' on '{1}'", this.ServiceDisplayName, this.MachineName)); using (RegistryKey registryKey = RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine, this.MachineName, RegistryView.Registry32)) { RegistryKey subKey = registryKey.OpenSubKey(@"System\CurrentControlSet\Services\" + this.ServiceName, true); if (subKey != null) { subKey.SetValue("Description", this.Description); subKey.Close(); } } } if (!string.IsNullOrEmpty(this.CommandLineArguments)) { this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "...Setting command line arguments for '{0}' on '{1}'", this.ServiceDisplayName, this.MachineName)); using (RegistryKey registryKey = RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine, this.MachineName, RegistryView.Registry32)) { RegistryKey subKey = registryKey.OpenSubKey(@"System\CurrentControlSet\Services\" + this.ServiceName, true); if (subKey != null) { object imagePathValue = subKey.GetValue("ImagePath"); imagePathValue = imagePathValue + " " + this.CommandLineArguments; subKey.SetValue("ImagePath", imagePathValue, RegistryValueKind.ExpandString); } } } if (string.Compare(this.StartupType, StartupTypeAutomaticDelayed, StringComparison.CurrentCultureIgnoreCase) == 0) { this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "...Setting delayed start argument registry setting for '{0}' on '{1}'", this.ServiceDisplayName, this.MachineName)); using (RegistryKey registryKey = RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine, this.MachineName, RegistryView.Registry32)) { RegistryKey subKey = registryKey.OpenSubKey(@"System\CurrentControlSet\Services\" + this.ServiceName, true); if (subKey != null) { const uint DelayedAutoStart = 1; subKey.SetValue("DelayedAutostart", DelayedAutoStart, RegistryValueKind.DWord); } } } } } private bool DeleteService() { bool targetLocal = this.TargetingLocalMachine(RemoteExecutionAvailable); this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Attempting to Delete the '{0}' service on '{1}' machine", this.ServiceName, this.MachineName)); if (!this.ServiceDoesExist(this.ServiceName)) { this.LogTaskMessage(MessageImportance.Low, string.Format(CultureInfo.CurrentCulture, "Service does not exist: {0} on '{1}'", this.ServiceDisplayName, this.MachineName)); return true; } bool noErrors = true; try { ManagementObject wmi = this.RetrieveManagementObject(this.ServiceName, targetLocal); // Execute the method and obtain the return values. ManagementBaseObject result = wmi.InvokeMethod("delete", null, null); if (result != null) { int returnCode = Convert.ToInt32(result["ReturnValue"], CultureInfo.InvariantCulture); if ((ServiceReturnCode)returnCode != ServiceReturnCode.Success) { this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "Delete Service failed with return code '[{0}] {1}'", returnCode, (ServiceReturnCode)returnCode)); noErrors = false; } } } catch (Exception ex) { this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "Delete Service [{0}on {1}] failed with error '{2}'", this.ServiceDisplayName, this.MachineName, ex.Message)); throw; } return noErrors; } private ServiceReturnCode Install(string machineName, string name, string displayName, string physicalLocation, string startupType, string userName, string password, string[] dependencies, bool interactWithDesktop, string installingUser, string installingUserPassword) { bool targetLocal = this.TargetingLocalMachine(RemoteExecutionAvailable); this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Attempting to install the '{0}' service to the '{1}' machine", displayName, machineName)); if (userName.IndexOf('\\') < 0) { userName = ".\\" + userName; } try { string path = targetLocal ? "\\root\\CIMV2" : string.Format(CultureInfo.InvariantCulture, "\\\\{0}\\root\\CIMV2", machineName); using (ManagementClass wmi = new ManagementClass(path, "Win32_Service", null)) { if (!targetLocal) { wmi.Scope.Options.Username = installingUser; wmi.Scope.Options.Password = installingUserPassword; } object[] paramList = new object[] { name, displayName, physicalLocation, Convert.ToInt32(ServiceTypes.OwnProcess, CultureInfo.InvariantCulture), Convert.ToInt32(ServiceErrorControl.UserNotified, CultureInfo.InvariantCulture), startupType, interactWithDesktop, userName, password, null, null, dependencies }; // Execute the method and obtain the return values. object result = wmi.InvokeMethod("Create", paramList); int returnCode = Convert.ToInt32(result, CultureInfo.InvariantCulture); return (ServiceReturnCode)returnCode; } } catch (Exception ex) { this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "Install Service [{0} on {1}] failed with error '{2}'", this.ServiceDisplayName, this.MachineName, ex.Message)); return ServiceReturnCode.UnknownFailure; } } private void Uninstall() { bool targetLocal = this.TargetingLocalMachine(RemoteExecutionAvailable); if (!this.ServiceDoesExist(this.ServiceName)) { this.LogTaskMessage(MessageImportance.Low, string.Format(CultureInfo.CurrentCulture, "Service does not exist: {0} on '{1}'", this.ServiceDisplayName, this.MachineName)); return; } if (this.Stop()) { try { ManagementObject wmi = this.RetrieveManagementObject(this.ServiceName, targetLocal); object[] paramList = new object[] { }; object result = wmi.InvokeMethod("Delete", paramList); ServiceReturnCode returnCode = (ServiceReturnCode)Convert.ToInt32(result, CultureInfo.InvariantCulture); if (returnCode != ServiceReturnCode.Success) { this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "Uninstall Service failed with code: '{0}'", returnCode)); } else { this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Uninstall Service succeeded for '{0}' on '{1}'", this.ServiceDisplayName, this.MachineName)); } } catch (Exception ex) { this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "Uninstall Service [{0} on {1}] failed with error '{2}'", this.ServiceDisplayName, this.MachineName, ex.Message)); } } } } }
// 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.Abstractions; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Xml.Xsl; using XmlCoreTest.Common; using OLEDB.Test.ModuleCore; using System.Runtime.Loader; namespace System.Xml.Tests { public class XsltcTestCaseBase : CTestCase { // Generic data for all derived test cases public string szDefaultNS = "urn:my-object"; public string szEmpty = ""; public string szInvalid = "*?%(){}[]&!@#$"; public string szLongNS = "http://www.microsoft.com/this/is/a/very/long/namespace/uri/to/do/the/api/testing/for/xslt/0123456789/0123456789/0123456789/0123456789/0123456789/0123456789/0123456789/0123456789/0123456789/0123456789/0123456789/0123456789/0123456789/0123456789/0123456789/0123456789/0123456789/0123456789/"; public string szLongString = "ThisIsAVeryLongStringToBeStoredAsAVariableToDetermineHowLargeThisBufferForAVariableNameCanBeAndStillFunctionAsExpected"; public string szSimple = "myArg"; public string[] szWhiteSpace = { " ", "\n", "\t", "\r", "\t\n \r\t" }; public string szXslNS = "http://www.w3.org/1999/XSL/Transform"; // Other global variables protected bool _createFromInputFile = false; // This is intiialized from a parameter passed from LTM as a dimension, that dictates whether the variation is to be created using an input file. protected bool _isInProc; // Is the current test run in proc or /Host None? private static ITestOutputHelper s_output; public XsltcTestCaseBase(ITestOutputHelper output) { s_output = output; } public static bool xsltcExeFound() { try { // Verify xsltc.exe is available XmlCoreTest.Common.XsltVerificationLibrary.SearchPath("xsltc.exe"); } catch (FileNotFoundException) { return false; } return true; } public override int Init(object objParam) { // initialize whether this run is in proc or not string executionMode = "File"; _createFromInputFile = executionMode.Equals("File"); return 1; } protected static void CompareOutput(string expected, Stream actualStream) { using (var expectedStream = new MemoryStream(Encoding.UTF8.GetBytes(expected))) { CompareOutput(expectedStream, actualStream); } } private static string NormalizeLineEndings(string s) { return s.Replace("\r\n", "\n").Replace("\r", "\n"); } protected static void CompareOutput(Stream expectedStream, Stream actualStream, int count = 0) { actualStream.Seek(0, SeekOrigin.Begin); using (var expectedReader = new StreamReader(expectedStream)) using (var actualReader = new StreamReader(actualStream)) { for (int i = 0; i < count; i++) { actualReader.ReadLine(); expectedReader.ReadLine(); } string actual = NormalizeLineEndings(actualReader.ReadToEnd()); string expected = NormalizeLineEndings(expectedReader.ReadToEnd()); if (actual.Equals(expected)) { return; } throw new CTestFailedException("Output was not as expected.", actual, expected, null); } } protected bool LoadPersistedTransformAssembly(string asmName, string typeName, string baselineFile, bool pdb) { var other = (AssemblyLoader)Activator.CreateInstance(typeof(AssemblyLoader), typeof(AssemblyLoader).FullName); bool result = other.Verify(asmName, typeName, baselineFile, pdb); return result; } protected string ReplaceCurrentWorkingDirectory(string commandLine) { return commandLine.Replace(@"$(CurrentWorkingDirectory)", XsltcModule.TargetDirectory); } protected bool ShouldSkip(object[] varParams) { // some test only applicable in English environment, so skip them if current cultral is not english bool isCultralEnglish = CultureInfo.CurrentCulture.TwoLetterISOLanguageName.ToLower() == "en"; if (isCultralEnglish) { return false; } // look up key word "EnglishOnly", if hit return true, otherwise false return varParams != null && varParams.Any(o => o.ToString() == "EnglishOnly"); } protected void VerifyTest(string cmdLine, string baselineFile, bool loadFromFile) { VerifyTest(cmdLine, string.Empty, false, string.Empty, baselineFile, loadFromFile); } protected void VerifyTest(string cmdLine, string asmName, bool asmCreated, string typeName, string baselineFile, bool loadFromFile) { VerifyTest(cmdLine, asmName, asmCreated, typeName, string.Empty, false, baselineFile, loadFromFile); } protected void VerifyTest(string cmdLine, string asmName, bool asmCreated, string typeName, string pdbName, bool pdbCreated, string baselineFile, bool loadFromFile) { VerifyTest(cmdLine, asmName, asmCreated, typeName, pdbName, pdbCreated, baselineFile, true, loadFromFile); } protected void VerifyTest(string cmdLine, string asmName, bool asmCreated, string typeName, string pdbName, bool pdbCreated, string baselineFile, bool runAssemblyVerification, bool loadFromFile) { string targetDirectory = XsltcModule.TargetDirectory; string output = asmCreated ? TryCreatePersistedTransformAssembly(cmdLine, _createFromInputFile, true, targetDirectory) : TryCreatePersistedTransformAssembly(cmdLine, _createFromInputFile, false, targetDirectory); //verify assembly file existence if (asmName != null && string.CompareOrdinal(string.Empty, asmName) != 0) { if (File.Exists(GetPath(asmName)) != asmCreated) { throw new CTestFailedException("Assembly File Creation Check: FAILED"); } } //verify pdb existence if (pdbName != null && string.CompareOrdinal(string.Empty, pdbName) != 0) { if (File.Exists(GetPath(pdbName)) != pdbCreated) { throw new CTestFailedException("PDB File Creation Check: FAILED"); } } if (asmCreated && !string.IsNullOrEmpty(typeName)) { if (!LoadPersistedTransformAssembly(GetPath(asmName), typeName, baselineFile, pdbCreated)) { throw new CTestFailedException("Assembly loaded failed"); } } else { using (var ms = new MemoryStream()) using (var sw = new StreamWriter(ms) { AutoFlush = true }) using (var expected = new FileStream(GetPath(baselineFile), FileMode.Open, FileAccess.Read)) { sw.Write(output); CompareOutput(expected, ms, 4); } } SafeDeleteFile(GetPath(pdbName)); SafeDeleteFile(GetPath(asmName)); return; } private static void SafeDeleteFile(string fileName) { try { var fileInfo = new FileInfo(fileName); if (fileInfo.Directory != null && !fileInfo.Directory.Exists) { fileInfo.Directory.Create(); } if (fileInfo.Exists) { fileInfo.Delete(); } } catch (ArgumentException) { } catch (PathTooLongException) { } catch (Exception e) { s_output.WriteLine(e.Message); } } // Used to generate a unique name for an input file, and write that file, based on a specified command line. private string CreateInputFile(string commandLine) { string fileName = Path.Combine(XsltcModule.TargetDirectory, Guid.NewGuid() + ".ipf"); File.WriteAllText(fileName, commandLine); return fileName; } private string GetPath(string fileName) { return XsltcModule.TargetDirectory + Path.DirectorySeparatorChar + fileName; } /// <summary> /// Currently this method supports only 1 input file. For variations that require more than one input file to test /// @file /// functionality, custom-craft and write those input files in the body of the variation method, then pass an /// appropriate /// commandline such as @file1 @file2 @file3, along with createFromInputFile = false. /// </summary> /// <param name="commandLine"></param> /// <param name="createFromInputFile"></param> /// <param name="expectedToSucceed"></param> /// <param name="targetDirectory"></param> /// <returns></returns> private string TryCreatePersistedTransformAssembly(string commandLine, bool createFromInputFile, bool expectedToSucceed, string targetDirectory) { // If createFromInputFile is specified, create an input file now that the compiler can consume. string processArguments = createFromInputFile ? "@" + CreateInputFile(commandLine) : commandLine; var processStartInfo = new ProcessStartInfo { FileName = XsltVerificationLibrary.SearchPath("xsltc.exe"), Arguments = processArguments, //WindowStyle = ProcessWindowStyle.Hidden, CreateNoWindow = true, UseShellExecute = false, RedirectStandardOutput = true, WorkingDirectory = targetDirectory }; // Call xsltc to create persistant assembly. var compilerProcess = new Process { StartInfo = processStartInfo }; compilerProcess.Start(); string output = compilerProcess.StandardOutput.ReadToEnd(); compilerProcess.WaitForExit(); if (createFromInputFile) { SafeDeleteFile(processArguments.Substring(1)); } if (expectedToSucceed) { // The Assembly was created successfully if (compilerProcess.ExitCode == 0) { return output; } throw new CTestFailedException("Failed to create assembly: " + output); } return output; } public class AssemblyLoader //: MarshalByRefObject { public AssemblyLoader(string asmName) { } public bool Verify(string asmName, string typeName, string baselineFile, bool pdb) { try { var xslt = new XslCompiledTransform(); Assembly xsltasm = AssemblyLoadContext.Default.LoadFromAssemblyPath(Path.GetFullPath(asmName)); if (xsltasm == null) { //_output.WriteLine("Could not load file"); return false; } Type t = xsltasm.GetType(typeName); if (t == null) { //_output.WriteLine("No type loaded"); return false; } xslt.Load(t); var inputXml = new XmlDocument(); using (var stream = new MemoryStream()) using (var sw = new StreamWriter(stream) { AutoFlush = true }) { inputXml.LoadXml("<foo><bar>Hello, world!</bar></foo>"); xslt.Transform(inputXml, null, sw); if (!XsltVerificationLibrary.CompareXml(Path.Combine(XsltcModule.TargetDirectory, baselineFile), stream)) { //_output.WriteLine("Baseline file comparison failed"); return false; } } return true; } catch (Exception e) { s_output.WriteLine(e.Message); return false; } } private static byte[] loadFile(string filename) { using (var fs = new FileStream(filename, FileMode.Open)) { var buffer = new byte[(int)fs.Length]; fs.Read(buffer, 0, buffer.Length); return buffer; } } } } }
// Generated by UblXml2CSharp using System.Xml; using UblLarsen.Ubl2; using UblLarsen.Ubl2.Cac; using UblLarsen.Ubl2.Ext; using UblLarsen.Ubl2.Udt; namespace UblLarsen.Test.UblClass { internal class UBLInvoice20ExampleNS4 { public static InvoiceType Create() { var doc = new InvoiceType { UBLVersionID = "2.0", CustomizationID = "urn:oasis:names:specification:ubl:xpath:Invoice-2.0:sbs-1.0-draft", ProfileID = "bpid:urn:oasis:names:draft:bpss:ubl-2-sbs-invoice-notification-draft", ID = "A00095678", CopyIndicator = false, UUID = "849FBBCE-E081-40B4-906C-94C5FF9D1AC3", IssueDate = "2005-06-21", InvoiceTypeCode = "SalesInvoice", Note = new TextType[] { new TextType { Value = "sample" } }, TaxPointDate = "2005-06-21", OrderReference = new OrderReferenceType { ID = "AEG012345", SalesOrderID = "CON0095678", UUID = "6E09886B-DC6E-439F-82D1-7CCAC7F4E3B1", IssueDate = "2005-06-20" }, AccountingSupplierParty = new SupplierPartyType { CustomerAssignedAccountID = "CO001", Party = new PartyType { PartyName = new PartyNameType[] { new PartyNameType { Name = "Consortial" } }, PostalAddress = new AddressType { StreetName = "Busy Street", BuildingName = "Thereabouts", BuildingNumber = "56A", CityName = "Farthing", PostalZone = "AA99 1BB", CountrySubentity = "Heremouthshire", AddressLine = new AddressLineType[] { new AddressLineType { Line = "The Roundabout" } }, Country = new CountryType { IdentificationCode = "GB" } }, PartyTaxScheme = new PartyTaxSchemeType[] { new PartyTaxSchemeType { RegistrationName = "Farthing Purchasing Consortium", CompanyID = "175 269 2355", ExemptionReason = new TextType[] { new TextType { Value = "N/A" } }, TaxScheme = new TaxSchemeType { ID = "VAT", TaxTypeCode = "VAT" } } }, Contact = new ContactType { Name = "Mrs Bouquet", Telephone = "0158 1233714", Telefax = "0158 1233856", ElectronicMail = "bouquet@fpconsortial.co.uk" } } }, AccountingCustomerParty = new CustomerPartyType { CustomerAssignedAccountID = "XFB01", SupplierAssignedAccountID = "GT00978567", Party = new PartyType { PartyName = new PartyNameType[] { new PartyNameType { Name = "IYT Corporation" } }, PostalAddress = new AddressType { StreetName = "Avon Way", BuildingName = "Thereabouts", BuildingNumber = "56A", CityName = "Bridgtow", PostalZone = "ZZ99 1ZZ", CountrySubentity = "Avon", AddressLine = new AddressLineType[] { new AddressLineType { Line = "3rd Floor, Room 5" } }, Country = new CountryType { IdentificationCode = "GB" } }, PartyTaxScheme = new PartyTaxSchemeType[] { new PartyTaxSchemeType { RegistrationName = "Bridgtow District Council", CompanyID = "12356478", ExemptionReason = new TextType[] { new TextType { Value = "Local Authority" } }, TaxScheme = new TaxSchemeType { ID = "UK VAT", TaxTypeCode = "VAT" } } }, Contact = new ContactType { Name = "Mr Fred Churchill", Telephone = "0127 2653214", Telefax = "0127 2653215", ElectronicMail = "fred@iytcorporation.gov.uk" } } }, Delivery = new DeliveryType[] { new DeliveryType { ActualDeliveryDate = "2005-06-20", ActualDeliveryTime = "11:30:00.0Z", DeliveryAddress = new AddressType { StreetName = "Avon Way", BuildingName = "Thereabouts", BuildingNumber = "56A", CityName = "Bridgtow", PostalZone = "ZZ99 1ZZ", CountrySubentity = "Avon", AddressLine = new AddressLineType[] { new AddressLineType { Line = "3rd Floor, Room 5" } }, Country = new CountryType { IdentificationCode = "GB" } } } }, PaymentMeans = new PaymentMeansType[] { new PaymentMeansType { PaymentMeansCode = "20", PaymentDueDate = "2005-07-21", PayeeFinancialAccount = new FinancialAccountType { ID = "12345678", Name = "Farthing Purchasing Consortium", AccountTypeCode = "Current", CurrencyCode = "GBP", FinancialInstitutionBranch = new BranchType { ID = "10-26-58", Name = "Open Bank Ltd, Bridgstow Branch ", FinancialInstitution = new FinancialInstitutionType { ID = "10-26-58", Name = "Open Bank Ltd", Address = new AddressType { StreetName = "City Road", BuildingName = "Banking House", BuildingNumber = "12", CityName = "London", PostalZone = "AQ1 6TH", CountrySubentity = @"London ", AddressLine = new AddressLineType[] { new AddressLineType { Line = "5th Floor" } }, Country = new CountryType { IdentificationCode = "GB" } } }, Address = new AddressType { StreetName = "Busy Street", BuildingName = "The Mall", BuildingNumber = "152", CityName = "Farthing", PostalZone = "AA99 1BB", CountrySubentity = "Heremouthshire", AddressLine = new AddressLineType[] { new AddressLineType { Line = "West Wing" } }, Country = new CountryType { IdentificationCode = "GB" } } }, Country = new CountryType { IdentificationCode = "GB" } } } }, PaymentTerms = new PaymentTermsType[] { new PaymentTermsType { Note = new TextType[] { new TextType { Value = "Payable within 1 calendar month from the invoice date" } } } }, AllowanceCharge = new AllowanceChargeType[] { new AllowanceChargeType { ChargeIndicator = false, AllowanceChargeReasonCode = "17", MultiplierFactorNumeric = 0.10M, Amount = new AmountType { currencyID = "GBP", Value = 10.00M } } }, TaxTotal = new TaxTotalType[] { new TaxTotalType { TaxAmount = new AmountType { currencyID = "GBP", Value = 17.50M }, TaxEvidenceIndicator = true, TaxSubtotal = new TaxSubtotalType[] { new TaxSubtotalType { TaxableAmount = new AmountType { currencyID = "GBP", Value = 100.00M }, TaxAmount = new AmountType { currencyID = "GBP", Value = 17.50M }, TaxCategory = new TaxCategoryType { ID = "A", TaxScheme = new TaxSchemeType { ID = "UK VAT", TaxTypeCode = "VAT" } } } } } }, LegalMonetaryTotal = new MonetaryTotalType { LineExtensionAmount = new AmountType { currencyID = "GBP", Value = 100.00M }, TaxExclusiveAmount = new AmountType { currencyID = "GBP", Value = 90.00M }, AllowanceTotalAmount = new AmountType { currencyID = "GBP", Value = 10.00M }, PayableAmount = new AmountType { currencyID = "GBP", Value = 107.50M } }, InvoiceLine = new InvoiceLineType[] { new InvoiceLineType { ID = "A", InvoicedQuantity = new QuantityType { unitCode = "KGM", Value = 100M }, LineExtensionAmount = new AmountType { currencyID = "GBP", Value = 100.00M }, OrderLineReference = new OrderLineReferenceType[] { new OrderLineReferenceType { LineID = "1", SalesOrderLineID = "A", LineStatusCode = "NoStatus", OrderReference = new OrderReferenceType { ID = "AEG012345", SalesOrderID = "CON0095678", UUID = "6E09886B-DC6E-439F-82D1-7CCAC7F4E3B1", IssueDate = "2005-06-20" } } }, TaxTotal = new TaxTotalType[] { new TaxTotalType { TaxAmount = new AmountType { currencyID = "GBP", Value = 17.50M }, TaxEvidenceIndicator = true, TaxSubtotal = new TaxSubtotalType[] { new TaxSubtotalType { TaxableAmount = new AmountType { currencyID = "GBP", Value = 100.00M }, TaxAmount = new AmountType { currencyID = "GBP", Value = 17.50M }, TaxCategory = new TaxCategoryType { ID = "A", Percent = 17.5M, TaxScheme = new TaxSchemeType { ID = "UK VAT", TaxTypeCode = "VAT" } } } } } }, Item = new ItemType { Description = new TextType[] { new TextType { Value = "Acme beeswax" } }, Name = "beeswax", BuyersItemIdentification = new ItemIdentificationType { ID = "6578489" }, SellersItemIdentification = new ItemIdentificationType { ID = "17589683" }, ItemInstance = new ItemInstanceType[] { new ItemInstanceType { LotIdentification = new LotIdentificationType { LotNumberID = "546378239", ExpiryDate = "2010-01-01" } } } }, Price = new PriceType { PriceAmount = new AmountType { currencyID = "GBP", Value = 1.00M }, BaseQuantity = new QuantityType { unitCode = "KGM", Value = 1M } } } } }; doc.Xmlns = new System.Xml.Serialization.XmlSerializerNamespaces(new[] { new XmlQualifiedName("Harry","urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2"), new XmlQualifiedName("Sally","urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2"), new XmlQualifiedName("Bob","urn:oasis:names:specification:ubl:schema:xsd:Invoice-2"), }); return doc; } } }
//--------------------------------------------------------------------- // <copyright file="ResourceType.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // <summary> // Contains information about a particular resource. // </summary> // // @owner [....] //--------------------------------------------------------------------- namespace System.Data.Services.Providers { #region Namespaces. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Data.Services.Common; using System.Data.Services.Parsing; using System.Data.Services.Serializers; using System.Diagnostics; using System.Linq; using System.Linq.Expressions; using System.Reflection; #endregion Namespaces. /// <summary>Use this class to represent a DataService type (primitive, complex or entity).</summary> [DebuggerDisplay("{Name}: {InstanceType}, {ResourceTypeKind}")] public class ResourceType { #region Fields. /// <summary> empty list of properties </summary> internal static readonly ReadOnlyCollection<ResourceProperty> EmptyProperties = new ReadOnlyCollection<ResourceProperty>(new ResourceProperty[0]); /// <summary>Primitive string resource type.</summary> internal static readonly ResourceType PrimitiveStringResourceType = ResourceType.GetPrimitiveResourceType(typeof(string)); /// <summary>MethodInfo for object DataServiceProviderWrapper.GetPropertyValue(object target, ResourceProperty resourceProperty, ResourceType resourceType).</summary> private static readonly MethodInfo GetPropertyValueMethodInfo = typeof(DataServiceProviderWrapper).GetMethod( "GetPropertyValue", WebUtil.PublicInstanceBindingFlags); /// <summary>MethodInfo for object IProjectedResult.GetProjectedPropertyValue(this IProjectedResult value, string propertyName).</summary> private static readonly MethodInfo IProjectedResultGetProjectedPropertyValueMethodInfo = typeof(IProjectedResult).GetMethod( "GetProjectedPropertyValue", WebUtil.PublicInstanceBindingFlags); /// <summary> ResourceTypeKind for the type that this structure represents </summary> private readonly ResourceTypeKind resourceTypeKind; /// <summary> Reference to clr type that this resource represents </summary> private readonly Type type; /// <summary> Reference to base resource type </summary> private readonly ResourceType baseType; /// <summary> name of the resource.</summary> private readonly string name; /// <summary> full name of the resource.</summary> private readonly string fullName; /// <summary> Namespace for this type.</summary> private readonly string namespaceName; /// <summary>Whether this type is abstract.</summary> private readonly bool abstractType; /// <summary>Whether the resource type has open properties.</summary> private bool isOpenType; /// <summary>Whether the corresponding instance type actually represents this node's CLR type.</summary> private bool canReflectOnInstanceType; /// <summary>Cached delegate to create a new instance of this type.</summary> private Func<object> constructorDelegate; /// <summary>Cached delegate to serialize parts of this resource into a dictionary.</summary> private Action<object, System.Data.Services.Serializers.DictionaryContent> dictionarySerializerDelegate; /// <summary> List of properties declared in this type (includes properties only defined in this type, not in the base type) </summary> private IList<ResourceProperty> propertiesDeclaredOnThisType; /// <summary> List of all properties for this type (includes properties defined in the base type also) </summary> private ReadOnlyCollection<ResourceProperty> allProperties; /// <summary> list of key properties for this type</summary> private ReadOnlyCollection<ResourceProperty> keyProperties; /// <summary> list of etag properties for this type.</summary> private ReadOnlyCollection<ResourceProperty> etagProperties; /// <summary>If ResourceProperty.CanReflectOnInstanceTypeProperty is true, we cache the PropertyInfo object.</summary> private Dictionary<ResourceProperty, PropertyInfo> propertyInfosDeclaredOnThisType = new Dictionary<ResourceProperty, PropertyInfo>(ReferenceEqualityComparer<ResourceProperty>.Instance); /// <summary>EpmInfo for this <see cref="ResourceType"/></summary> private EpmInfoPerResourceType epmInfo; /// <summary>Indicates whether one of the base class of this resource type has EpmInfo.</summary> private bool? basesHaveEpmInfo; /// <summary>is true, if the type is set to readonly.</summary> private bool isReadOnly; /// <summary>True if the resource type includes a default stream </summary> private bool isMediaLinkEntry; /// <summary>True if the virtual load properties is already called, otherwise false.</summary> private bool isLoadPropertiesMethodCalled; #endregion Fields. #region Constructors. /// <summary> /// Constructs a new instance of Astoria type using the specified clr type /// </summary> /// <param name="instanceType">clr type that represents the flow format inside the Astoria runtime</param> /// <param name="resourceTypeKind"> kind of the resource type</param> /// <param name="baseType">base type of the resource type</param> /// <param name="namespaceName">Namespace name of the given resource type.</param> /// <param name="name">name of the given resource type.</param> /// <param name="isAbstract">whether the resource type is an abstract type or not.</param> public ResourceType( Type instanceType, ResourceTypeKind resourceTypeKind, ResourceType baseType, string namespaceName, string name, bool isAbstract) : this(instanceType, baseType, namespaceName, name, isAbstract) { WebUtil.CheckArgumentNull(instanceType, "instanceType"); WebUtil.CheckStringArgumentNull(name, "name"); WebUtil.CheckResourceTypeKind(resourceTypeKind, "resourceTypeKind"); if (resourceTypeKind == ResourceTypeKind.Primitive) { throw new ArgumentException(Strings.ResourceType_InvalidValueForResourceTypeKind, "resourceTypeKind"); } if (instanceType.IsValueType) { throw new ArgumentException(Strings.ResourceType_TypeCannotBeValueType, "instanceType"); } this.resourceTypeKind = resourceTypeKind; } /// <summary> /// Constructs a new instance of Resource type for the given clr primitive type. This constructor must be called only for primitive types. /// </summary> /// <param name="type">clr type representing the primitive type.</param> /// <param name="namespaceName">namespace of the primitive type.</param> /// <param name="name">name of the primitive type.</param> internal ResourceType(Type type, string namespaceName, string name) : this(type, null, namespaceName, name, false) { Debug.Assert(WebUtil.IsPrimitiveType(type), "This constructor should be called only for primitive types"); this.resourceTypeKind = ResourceTypeKind.Primitive; this.isReadOnly = true; } /// <summary> /// Constructs a new instance of Astoria type using the specified clr type /// </summary> /// <param name="type">clr type from which metadata needs to be pulled </param> /// <param name="baseType">base type of the resource type</param> /// <param name="namespaceName">Namespace name of the given resource type.</param> /// <param name="name">name of the given resource type.</param> /// <param name="isAbstract">whether the resource type is an abstract type or not.</param> private ResourceType( Type type, ResourceType baseType, string namespaceName, string name, bool isAbstract) { WebUtil.CheckArgumentNull(type, "type"); WebUtil.CheckArgumentNull(name, "name"); this.name = name; this.namespaceName = namespaceName ?? string.Empty; // This is to optimize the string property name in PlainXmlSerializer.WriteStartElementWithType function. // Checking here is a fixed overhead, and the gain is every time we serialize a string property. if (name == "String" && Object.ReferenceEquals(namespaceName, XmlConstants.EdmNamespace)) { this.fullName = XmlConstants.EdmStringTypeName; } else { this.fullName = string.IsNullOrEmpty(namespaceName) ? name : namespaceName + "." + name; } this.type = type; this.abstractType = isAbstract; this.canReflectOnInstanceType = true; if (baseType != null) { this.baseType = baseType; } } #endregion Constructors. #region Properties. /// <summary>True if the resource type includes a default stream</summary> public bool IsMediaLinkEntry { [DebuggerStepThrough] get { return this.isMediaLinkEntry; } set { this.ThrowIfSealed(); if (this.resourceTypeKind != ResourceTypeKind.EntityType && value == true) { throw new InvalidOperationException(Strings.ReflectionProvider_HasStreamAttributeOnlyAppliesToEntityType(this.name)); } this.isMediaLinkEntry = value; } } /// <summary> Reference to clr type that this resource represents </summary> public Type InstanceType { [DebuggerStepThrough] get { return this.type; } } /// <summary> Reference to base resource type, if any </summary> public ResourceType BaseType { [DebuggerStepThrough] get { return this.baseType; } } /// <summary> ResourceTypeKind of this type </summary> public ResourceTypeKind ResourceTypeKind { [DebuggerStepThrough] get { return this.resourceTypeKind; } } /// <summary> Returns the list of properties for this type </summary> public ReadOnlyCollection<ResourceProperty> Properties { get { return this.InitializeProperties(); } } /// <summary> list of properties declared on this type </summary> public ReadOnlyCollection<ResourceProperty> PropertiesDeclaredOnThisType { get { ReadOnlyCollection<ResourceProperty> readOnlyProperties = this.propertiesDeclaredOnThisType as ReadOnlyCollection<ResourceProperty>; if (readOnlyProperties == null) { // This method will call the virtual method, if that's not been called yet and add the list of properties // returned by the virtual method to the properties collection. this.GetPropertiesDeclaredOnThisType(); readOnlyProperties = new ReadOnlyCollection<ResourceProperty>(this.propertiesDeclaredOnThisType ?? ResourceType.EmptyProperties); if (!this.isReadOnly) { return readOnlyProperties; } // First try and validate the type. If that succeeds, then cache the results. otherwise we need to revert the results. IList<ResourceProperty> propertyCollection = this.propertiesDeclaredOnThisType; this.propertiesDeclaredOnThisType = readOnlyProperties; try { this.ValidateType(); } catch (Exception) { this.propertiesDeclaredOnThisType = propertyCollection; throw; } } Debug.Assert(this.isReadOnly, "PropetiesDeclaredInThisType - at this point, the resource type must be readonly"); return readOnlyProperties; } } /// <summary> Returns the list of key properties for this type, if this type is entity type.</summary> public ReadOnlyCollection<ResourceProperty> KeyProperties { get { if (this.keyProperties == null) { ResourceType rootType = this; while (rootType.BaseType != null) { rootType = rootType.BaseType; } ReadOnlyCollection<ResourceProperty> readOnlyKeyProperties; if (rootType.Properties == null) { readOnlyKeyProperties = ResourceType.EmptyProperties; } else { List<ResourceProperty> key = rootType.Properties.Where(p => p.IsOfKind(ResourcePropertyKind.Key)).ToList(); key.Sort(ResourceType.ResourcePropertyComparison); readOnlyKeyProperties = new ReadOnlyCollection<ResourceProperty>(key); } if (!this.isReadOnly) { return readOnlyKeyProperties; } this.keyProperties = readOnlyKeyProperties; } Debug.Assert(this.isReadOnly, "KeyProperties - at this point, the resource type must be readonly"); Debug.Assert( (this.ResourceTypeKind != ResourceTypeKind.EntityType && this.keyProperties.Count == 0) || (this.ResourceTypeKind == ResourceTypeKind.EntityType && this.keyProperties.Count > 0), "Entity type must have key properties and non-entity types cannot have key properties"); return this.keyProperties; } } /// <summary>Returns the list of etag properties for this type.</summary> public ReadOnlyCollection<ResourceProperty> ETagProperties { get { if (this.etagProperties == null) { ReadOnlyCollection<ResourceProperty> etag = new ReadOnlyCollection<ResourceProperty>(this.Properties.Where(p => p.IsOfKind(ResourcePropertyKind.ETag)).ToList()); if (!this.isReadOnly) { return etag; } this.etagProperties = etag; } Debug.Assert(this.isReadOnly, "ETagProperties - at this point, the resource type must be readonly"); return this.etagProperties; } } /// <summary> Gets the name of the resource.</summary> public string Name { get { return this.name; } } /// <summary> Gets the fullname of the resource.</summary> public string FullName { get { return this.fullName; } } /// <summary> Returns the namespace of this type.</summary> public string Namespace { get { return this.namespaceName; } } /// <summary>Indicates whether this is an abstract type.</summary> public bool IsAbstract { get { return this.abstractType; } } /// <summary>Indicates whether the resource type has open properties.</summary> public bool IsOpenType { [DebuggerStepThrough] get { return this.isOpenType; } set { this.ThrowIfSealed(); // Complex types can not be marked as open. if (this.resourceTypeKind == ResourceTypeKind.ComplexType && value == true) { throw new InvalidOperationException(Strings.ResourceType_ComplexTypeCannotBeOpen(this.FullName)); } this.isOpenType = value; } } /// <summary>Whether the corresponding instance type actually represents this node's CLR type.</summary> public bool CanReflectOnInstanceType { [DebuggerStepThrough] get { return this.canReflectOnInstanceType; } set { this.ThrowIfSealed(); this.canReflectOnInstanceType = value; } } /// <summary> /// PlaceHolder to hold custom state information about resource type. /// </summary> public object CustomState { get; set; } /// <summary> /// Returns true, if this resource type has been set to read only. Otherwise returns false. /// </summary> public bool IsReadOnly { get { return this.isReadOnly; } } /// <summary>Cached delegate to create a new instance of this type.</summary> internal Func<object> ConstructorDelegate { get { if (this.constructorDelegate == null) { this.constructorDelegate = (Func<object>) WebUtil.CreateNewInstanceConstructor(this.InstanceType, this.FullName, typeof(object)); } return this.constructorDelegate; } } /// <summary>Cached delegate to serialize parts of this resource into a dictionary.</summary> internal Action<object, System.Data.Services.Serializers.DictionaryContent> DictionarySerializerDelegate { get { return this.dictionarySerializerDelegate; } set { this.dictionarySerializerDelegate = value; } } /// <summary> /// Do we have entity property mappings for this <see cref="ResourceType"/> /// </summary> internal bool HasEntityPropertyMappings { get { Debug.Assert(this.IsReadOnly, "Type must be read-only."); if (this.epmInfo != null) { return true; } if (this.basesHaveEpmInfo == null) { this.basesHaveEpmInfo = this.BaseType != null ? this.BaseType.HasEntityPropertyMappings : false; } return this.basesHaveEpmInfo.Value; } } /// <summary> /// Property used to mark the fact that EpmInfo for the resource type has been initialized /// </summary> internal bool EpmInfoInitialized { get; set; } /// <summary>The mappings for friendly feeds are V1 compatible or not</summary> internal bool EpmIsV1Compatible { get { Debug.Assert(this.isReadOnly, "Resource type must already be read-only."); this.InitializeProperties(); return !this.HasEntityPropertyMappings || this.EpmTargetTree.IsV1Compatible; } } /// <summary> /// Tree of source paths for EntityPropertyMappingAttributes on this resource type /// </summary> internal EpmSourceTree EpmSourceTree { get { if (this.epmInfo == null) { this.epmInfo = new EpmInfoPerResourceType(); } return this.epmInfo.EpmSourceTree; } } /// <summary> /// Tree of target paths for EntityPropertyMappingAttributes on this resource type /// </summary> internal EpmTargetTree EpmTargetTree { get { Debug.Assert(this.epmInfo != null, "Must have valid EpmInfo"); return this.epmInfo.EpmTargetTree; } } /// <summary>Inherited EpmInfo</summary> internal IList<EntityPropertyMappingAttribute> InheritedEpmInfo { get { Debug.Assert(this.epmInfo != null, "Must have valid EpmInfo"); return this.epmInfo.InheritedEpmInfo; } } /// <summary>Own EpmInfo</summary> internal IList<EntityPropertyMappingAttribute> OwnEpmInfo { get { Debug.Assert(this.epmInfo != null, "Must have valid EpmInfo"); return this.epmInfo.OwnEpmInfo; } } /// <summary>All EpmInfo i.e. both own and inherited.</summary> internal IEnumerable<EntityPropertyMappingAttribute> AllEpmInfo { get { Debug.Assert(this.epmInfo != null, "Must have valid EpmInfo"); return this.epmInfo.OwnEpmInfo.Concat(this.epmInfo.InheritedEpmInfo); } } #endregion Properties. #region Methods. /// <summary> /// Get a ResourceType representing a primitive type given a .NET System.Type object /// </summary> /// <param name="type">.NET type to get the primitive type from</param> /// <returns>A ResourceType object representing the primitive type or null if not primitive</returns> public static ResourceType GetPrimitiveResourceType(Type type) { WebUtil.CheckArgumentNull(type, "type"); foreach (ResourceType resourceType in WebUtil.GetPrimitiveTypes()) { if (resourceType.InstanceType == type) { return resourceType; } } return null; } /// <summary> /// Adds the given property to this ResourceType instance /// </summary> /// <param name="property">resource property to be added</param> public void AddProperty(ResourceProperty property) { WebUtil.CheckArgumentNull(property, "property"); // only check whether the property with the same name exists in this type. // we will look in base types properties when the type is sealed. this.ThrowIfSealed(); // add the property to the list of properties declared on this type. this.AddPropertyInternal(property); } /// <summary> /// Adds an <see cref="EntityPropertyMappingAttribute"/> for the resource type. /// </summary> /// <param name="attribute">Given <see cref="EntityPropertyMappingAttribute"/></param> public void AddEntityPropertyMappingAttribute(EntityPropertyMappingAttribute attribute) { WebUtil.CheckArgumentNull(attribute, "attribute"); // EntityPropertyMapping attribute can not be added to readonly resource types. this.ThrowIfSealed(); if (this.ResourceTypeKind != ResourceTypeKind.EntityType) { throw new InvalidOperationException(Strings.EpmOnlyAllowedOnEntityTypes(this.Name)); } if (this.epmInfo == null) { this.epmInfo = new EpmInfoPerResourceType(); } this.OwnEpmInfo.Add(attribute); } /// <summary> /// Make the resource type readonly from now on. This means that no more changes can be made to the resource type anymore. /// </summary> public void SetReadOnly() { #if DEBUG IList<ResourceProperty> currentPropertyCollection = this.propertiesDeclaredOnThisType; #endif // if its already sealed, its a no-op if (this.isReadOnly) { return; } // We need to set readonly at the start to avoid any circular loops that may result due to navigation properties. // If there are any exceptions, we need to set readonly to false. this.isReadOnly = true; // There can be properties with the same name in the base class also (using the new construct) // if the base type is not null, then we need to make sure that there is no property with the same name. // Otherwise, we are only populating property declared for this type and clr gaurantees that they are unique if (this.BaseType != null) { this.BaseType.SetReadOnly(); // Mark current type as OpenType if base is an OpenType if (this.BaseType.IsOpenType && this.ResourceTypeKind != ResourceTypeKind.ComplexType) { this.isOpenType = true; } // Mark the current type as being a Media Link Entry if the base type is a Media Link Entry. if (this.BaseType.IsMediaLinkEntry) { this.isMediaLinkEntry = true; } // Make sure current type is not a CLR type if base is not a CLR type. if (!this.BaseType.CanReflectOnInstanceType) { this.canReflectOnInstanceType = false; } } // set all the properties to readonly if (this.propertiesDeclaredOnThisType != null) { foreach (ResourceProperty p in this.propertiesDeclaredOnThisType) { p.SetReadOnly(); } } #if DEBUG // We cannot change the properties collection method. Basically, we should not be calling Properties or PropertiesDeclaredOnThisType properties // since they call the virtual LoadPropertiesDeclaredOnThisType and we want to postpone that virtual call until we actually need to do something // more useful with the properties Debug.Assert(Object.ReferenceEquals(this.propertiesDeclaredOnThisType, currentPropertyCollection), "We should not have modified the properties collection instance"); #endif } /// <summary>By initializing the EpmInfo for the resource type, ensures that the information is available for de-serialization.</summary> internal void EnsureEpmInfoAvailability() { this.InitializeProperties(); } /// <summary>Given a resource type, builds the EntityPropertyMappingInfo for each EntityPropertyMappingAttribute on it</summary> /// <param name="currentResourceType">Resouce type for which EntityPropertyMappingAttribute discovery is happening</param> internal void BuildReflectionEpmInfo(ResourceType currentResourceType) { if (currentResourceType.BaseType != null) { this.BuildReflectionEpmInfo(currentResourceType.BaseType); } foreach (EntityPropertyMappingAttribute epmAttr in currentResourceType.InstanceType.GetCustomAttributes(typeof(EntityPropertyMappingAttribute), currentResourceType.BaseType != null ? false : true)) { this.BuildEpmInfo(epmAttr, currentResourceType, false); if (this == currentResourceType) { if (!this.PropertyExistsInCurrentType(epmAttr)) { this.InheritedEpmInfo.Add(epmAttr); } else { this.OwnEpmInfo.Add(epmAttr); } } } } /// <summary> /// Builds the EntityPropertyMappingInfo corresponding to an EntityPropertyMappingAttribute, also builds the delegate to /// be invoked in order to retrieve the property provided in the <paramref name="epmAttr"/> /// </summary> /// <param name="epmAttr">Source EntityPropertyMappingAttribute</param> /// <param name="definingType">Type that has the attribute applied to it</param> /// <param name="isEFProvider">Is EF provider being initialized, used for error message formatting</param> internal void BuildEpmInfo(EntityPropertyMappingAttribute epmAttr, ResourceType definingType, bool isEFProvider) { this.EpmSourceTree.Add(new EntityPropertyMappingInfo(epmAttr, definingType, this, isEFProvider)); } /// <summary> /// Sets the value <paramref name="propertyValue"/> on the <paramref name="currentValue"/> object /// </summary> /// <param name="currentSegment">Target path segment containing the corresponding attribute information</param> /// <param name="currentValue">Object on which to set property</param> /// <param name="propertyValue">Value to be set</param> /// <param name="deserializer">Current deserializer</param> internal void SetEpmValue(EpmTargetPathSegment currentSegment, Object currentValue, object propertyValue, EpmContentDeSerializerBase deserializer) { if (currentSegment.EpmInfo.Attribute.KeepInContent == false) { this.SetPropertyValueFromPath( currentSegment.EpmInfo.Attribute.SourcePath.Split('/'), this, currentValue, propertyValue, 0, deserializer); } } /// <summary> /// Given a collection of <paramref name="segments"/> corresponding to a property access path /// on the <paramref name="element"/> object, sets the <paramref name="propertyValue"/> on the property /// </summary> /// <param name="segments">Property access path where each element is a property name</param> /// <param name="resourceType">Resource type for which to set the property</param> /// <param name="element">Object on which to set property</param> /// <param name="propertyValue">Value of property</param> /// <param name="currentIndex">Index of the current segment being looked at</param> /// <param name="deserializer">Current deserializer</param> internal void SetPropertyValueFromPath( String[] segments, ResourceType resourceType, object element, object propertyValue, int currentIndex, EpmContentDeSerializerBase deserializer) { String currentSegment = segments[currentIndex]; ResourceProperty clientProp = resourceType.TryResolvePropertyName(currentSegment); ResourceType propertyType; if (clientProp == null && resourceType.IsOpenType == false) { throw DataServiceException.CreateBadRequestError(Strings.BadRequest_InvalidPropertyNameSpecified(currentSegment, resourceType.FullName)); } // If this is a open property OR we do not have to do type conversion for primitive types, // read the type from the payload. if (clientProp == null || (!deserializer.Service.Configuration.EnableTypeConversion && clientProp.ResourceType.ResourceTypeKind == ResourceTypeKind.Primitive)) { String foundTypeName = deserializer.PropertiesApplied.MapPropertyToType(String.Join("/", segments, 0, currentIndex + 1)); if (foundTypeName != null) { propertyType = WebUtil.TryResolveResourceType(deserializer.Service.Provider, foundTypeName); if (propertyType == null) { throw DataServiceException.CreateBadRequestError(Strings.BadRequest_InvalidTypeName(foundTypeName)); } if (propertyType.ResourceTypeKind == ResourceTypeKind.EntityType) { throw DataServiceException.CreateBadRequestError( Strings.PlainXml_EntityTypeNotSupported(propertyType.FullName)); } } else { propertyType = ResourceType.PrimitiveStringResourceType; } } else { propertyType = clientProp.ResourceType; } object currentValue; // Re-construct the source path to add the newly applied property string sourcePath = string.Join("/", segments, 0, currentIndex + 1); switch (propertyType.ResourceTypeKind) { case ResourceTypeKind.ComplexType: if (!deserializer.PropertiesApplied.Lookup(sourcePath)) { // Complex types are treated as atomic and we never allow merging of properties belonging to // a complex type. In other words, we either update the whole complex type or not at all, // never just a subset of its properties. If the complex property has not been applied yet // we create a new instance then apply its property mappings. currentValue = deserializer.Updatable.CreateResource(null, propertyType.FullName); ResourceType.SetEpmProperty(element, currentSegment, currentValue, sourcePath, deserializer); } else { // We've already created a new instance of the complex property by now, reuse the same instance. currentValue = deserializer.Updatable.GetValue(element, currentSegment); Debug.Assert(currentValue != null, "currentValue != null -- we should never be here if the complex property were null."); } this.SetPropertyValueFromPath(segments, propertyType, currentValue, propertyValue, ++currentIndex, deserializer); break; case ResourceTypeKind.EntityType: throw DataServiceException.CreateBadRequestError( Strings.PlainXml_NavigationPropertyNotSupported(clientProp.Name)); default: Debug.Assert( propertyType.ResourceTypeKind == ResourceTypeKind.Primitive, "property.TypeKind == ResourceTypeKind.Primitive -- metadata shouldn't return " + propertyType.ResourceTypeKind); currentValue = PlainXmlDeserializer.ConvertValuesForXml(propertyValue, currentSegment, propertyType.InstanceType); // Do not try to update the property if it is a key property if (!deserializer.IsUpdateOperation || clientProp == null || !clientProp.IsOfKind(ResourcePropertyKind.Key)) { ResourceType.SetEpmProperty(element, currentSegment, currentValue, sourcePath, deserializer); } break; } } /// <summary> /// Changes the key property to non key property and removes it from the key properties list /// </summary> internal void RemoveKeyProperties() { Debug.Assert(!this.isReadOnly, "The resource type cannot be sealed - RemoveKeyProperties"); ReadOnlyCollection<ResourceProperty> key = this.KeyProperties; Debug.Assert(key.Count == 1, "Key Properties count must be zero"); Debug.Assert(this.BaseType == null, "BaseType must be null"); Debug.Assert(key[0].IsOfKind(ResourcePropertyKind.Key), "must be key property"); ResourceProperty property = key[0]; property.Kind = property.Kind ^ ResourcePropertyKind.Key; } /// <summary>Tries to find the property for the specified name.</summary> /// <param name="propertyName">Name of property to resolve.</param> /// <returns>Resolved property; possibly null.</returns> internal ResourceProperty TryResolvePropertyName(string propertyName) { // In case of empty property name this will return null, which means propery is not found return this.Properties.FirstOrDefault(p => p.Name == propertyName); } /// <summary>Tries to find the property declared on this type for the specified name.</summary> /// <param name="propertyName">Name of property to resolve.</param> /// <returns>Resolved property; possibly null.</returns> internal ResourceProperty TryResolvePropertiesDeclaredOnThisTypeByName(string propertyName) { // In case of empty property name this will return null, which means propery is not found return this.PropertiesDeclaredOnThisType.FirstOrDefault(p => p.Name == propertyName); } /// <summary> /// Checks if the given type is assignable to this type. In other words, if this type /// is a subtype of the given type or not. /// </summary> /// <param name="superType">resource type to check.</param> /// <returns>true, if the given type is assignable to this type. Otherwise returns false.</returns> internal bool IsAssignableFrom(ResourceType superType) { while (superType != null) { if (superType == this) { return true; } superType = superType.BaseType; } return false; } /// <summary> /// Gets the property info for the resource property /// </summary> /// <param name="resourceProperty">Resource property instance to get the property info</param> /// <returns>Returns the propertyinfo object for the specified resource property.</returns> /// <remarks>The method searchies this type as well as all its base types for the property.</remarks> internal PropertyInfo GetPropertyInfo(ResourceProperty resourceProperty) { Debug.Assert(resourceProperty != null, "resourceProperty != null"); Debug.Assert(resourceProperty.CanReflectOnInstanceTypeProperty, "resourceProperty.CanReflectOnInstanceTypeProperty"); PropertyInfo propertyInfo = null; ResourceType resourceType = this; while (propertyInfo == null && resourceType != null) { propertyInfo = resourceType.GetPropertyInfoDecaredOnThisType(resourceProperty); resourceType = resourceType.BaseType; } Debug.Assert(propertyInfo != null, "propertyInfo != null"); return propertyInfo; } /// <summary>Sets the value of the property.</summary> /// <param name="instance">The object whose property needs to be set.</param> /// <param name="propertyValue">new value for the property.</param> /// <param name="resourceProperty">metadata for the property to be set.</param> internal void SetValue(object instance, object propertyValue, ResourceProperty resourceProperty) { Debug.Assert(instance != null, "instance != null"); Debug.Assert(resourceProperty != null, "resourceProperty != null"); MethodInfo setMethod = this.GetPropertyInfo(resourceProperty).GetSetMethod(); if (setMethod == null) { throw DataServiceException.CreateBadRequestError(Strings.BadRequest_PropertyValueCannotBeSet(resourceProperty.Name)); } try { setMethod.Invoke(instance, new object[] { propertyValue }); } catch (TargetInvocationException exception) { ErrorHandler.HandleTargetInvocationException(exception); throw; } catch (ArgumentException exception) { throw DataServiceException.CreateBadRequestError(Strings.BadRequest_ErrorInSettingPropertyValue(resourceProperty.Name), exception); } } /// <summary> /// Return the list of properties declared by this resource type. This method gives a chance to lazy load the properties /// of a resource type, instead of loading them upfront. This property will be called once and only once, whenever /// ResourceType.Properties or ResourceType.PropertiesDeclaredOnThisType property is accessed. /// </summary> /// <returns>the list of properties declared on this type.</returns> protected virtual IEnumerable<ResourceProperty> LoadPropertiesDeclaredOnThisType() { return new ResourceProperty[0]; } /// <summary> /// Compares two resource property instances, sorting them so keys are first, /// and are alphabetically ordered in case-insensitive ordinal order. /// </summary> /// <param name="a">First property to compare.</param> /// <param name="b">Second property to compare.</param> /// <returns> /// Less than zero if a sorts before b; zero if equal; greater than zero if a sorts /// after b. /// </returns> private static int ResourcePropertyComparison(ResourceProperty a, ResourceProperty b) { return StringComparer.OrdinalIgnoreCase.Compare(a.Name, b.Name); } /// <summary> /// Sets a mapped property value and mark its source path as applied /// </summary> /// <param name="element">Object on which to set the property</param> /// <param name="propertyName">Name of the property</param> /// <param name="propertyValue">Value of the property</param> /// <param name="sourcePath">Source mapping path for the property to be set</param> /// <param name="deserializer">Current deserializer</param> private static void SetEpmProperty(object element, string propertyName, object propertyValue, string sourcePath, EpmContentDeSerializerBase deserializer) { deserializer.Updatable.SetValue(element, propertyName, propertyValue); deserializer.PropertiesApplied.AddAppliedProperty(sourcePath, false); } /// <summary> /// Initializes all properties for the resource type, to be used by Properties getter. /// </summary> /// <returns>Collection of properties exposed by this resource type.</returns> private ReadOnlyCollection<ResourceProperty> InitializeProperties() { if (this.allProperties == null) { ReadOnlyCollection<ResourceProperty> readOnlyAllProps; List<ResourceProperty> allProps = new List<ResourceProperty>(); if (this.BaseType != null) { allProps.AddRange(this.BaseType.Properties); } allProps.AddRange(this.PropertiesDeclaredOnThisType); readOnlyAllProps = new ReadOnlyCollection<ResourceProperty>(allProps); if (!this.isReadOnly) { return readOnlyAllProps; } this.allProperties = readOnlyAllProps; } Debug.Assert(this.isReadOnly, "Propeties - at this point, the resource type must be readonly"); return this.allProperties; } /// <summary> /// Validate the given <paramref name="property"/> and adds it to the list of properties for this type /// </summary> /// <param name="property">property which needs to be added.</param> private void AddPropertyInternal(ResourceProperty property) { if (this.propertiesDeclaredOnThisType == null) { this.propertiesDeclaredOnThisType = new List<ResourceProperty>(); } foreach (ResourceProperty resourceProperty in this.propertiesDeclaredOnThisType) { if (resourceProperty.Name == property.Name) { throw new InvalidOperationException(Strings.ResourceType_PropertyWithSameNameAlreadyExists(resourceProperty.Name, this.FullName)); } } if (property.IsOfKind(ResourcePropertyKind.Key)) { if (this.baseType != null) { throw new InvalidOperationException(Strings.ResourceType_NoKeysInDerivedTypes); } if (this.ResourceTypeKind != ResourceTypeKind.EntityType) { throw new InvalidOperationException(Strings.ResourceType_KeyPropertiesOnlyOnEntityTypes); } Debug.Assert(property.TypeKind == ResourceTypeKind.Primitive, "This check must have been done in ResourceProperty.ValidatePropertyParameters method"); Debug.Assert(!property.IsOfKind(ResourcePropertyKind.ETag), "This check must have been done in ResourceProperty.ValidatePropertyParameters method"); Debug.Assert(property.IsOfKind(ResourcePropertyKind.Primitive), "This check must have been done in ResourceProperty.ValidatePropertyParameters method"); } if (property.IsOfKind(ResourcePropertyKind.ETag)) { if (this.ResourceTypeKind != ResourceTypeKind.EntityType) { throw new InvalidOperationException(Strings.ResourceType_ETagPropertiesOnlyOnEntityTypes); } #if DEBUG Debug.Assert(property.TypeKind == ResourceTypeKind.Primitive, "This check must have been done in ResourceProperty.ValidatePropertyParameters method"); Debug.Assert(property.IsOfKind(ResourcePropertyKind.Primitive), "This check must have been done in ResourceProperty.ValidatePropertyParameters method"); Debug.Assert(!property.IsOfKind(ResourcePropertyKind.Key), "This check must have been done in ResourceProperty.ValidatePropertyParameters method"); #endif } this.propertiesDeclaredOnThisType.Add(property); } /// <summary> /// Gets the property info for the resource property declared on this type /// </summary> /// <param name="resourceProperty">Resource property instance to get the property info</param> /// <returns>Returns the propertyinfo object for the specified resource property.</returns> private PropertyInfo GetPropertyInfoDecaredOnThisType(ResourceProperty resourceProperty) { Debug.Assert(resourceProperty != null, "resourceProperty != null"); Debug.Assert(resourceProperty.CanReflectOnInstanceTypeProperty, "resourceProperty.CanReflectOnInstanceTypeProperty"); if (this.propertyInfosDeclaredOnThisType == null) { this.propertyInfosDeclaredOnThisType = new Dictionary<ResourceProperty, PropertyInfo>(ReferenceEqualityComparer<ResourceProperty>.Instance); } PropertyInfo propertyInfo; if (!this.propertyInfosDeclaredOnThisType.TryGetValue(resourceProperty, out propertyInfo)) { BindingFlags bindingFlags = WebUtil.PublicInstanceBindingFlags; propertyInfo = this.InstanceType.GetProperty(resourceProperty.Name, bindingFlags); if (propertyInfo == null) { throw new DataServiceException(500, Strings.BadProvider_UnableToGetPropertyInfo(this.FullName, resourceProperty.Name)); } this.propertyInfosDeclaredOnThisType.Add(resourceProperty, propertyInfo); } Debug.Assert(propertyInfo != null, "propertyInfo != null"); return propertyInfo; } /// <summary>Given a resource type, builds the EntityPropertyMappingInfo for each of the dynamic entity property mapping attribute</summary> /// <param name="currentResourceType">Resouce type for which EntityPropertyMappingAttribute discovery is happening</param> private void BuildDynamicEpmInfo(ResourceType currentResourceType) { if (currentResourceType.BaseType != null) { this.BuildDynamicEpmInfo(currentResourceType.BaseType); } if (currentResourceType.HasEntityPropertyMappings) { foreach (EntityPropertyMappingAttribute epmAttr in currentResourceType.AllEpmInfo.ToList()) { this.BuildEpmInfo(epmAttr, currentResourceType, false); if (this == currentResourceType) { if (!this.PropertyExistsInCurrentType(epmAttr)) { this.InheritedEpmInfo.Add(epmAttr); this.OwnEpmInfo.Remove(epmAttr); } else { Debug.Assert(this.OwnEpmInfo.SingleOrDefault(attr => Object.ReferenceEquals(epmAttr, attr)) != null, "Own epmInfo should already have the given instance"); } } } } } /// <summary> /// Does given property in the attribute exist in this type or one of it's base types /// </summary> /// <param name="epmAttr">Attribute which has PropertyName</param> /// <returns>true if property exists in current type, false otherwise</returns> private bool PropertyExistsInCurrentType(EntityPropertyMappingAttribute epmAttr) { int indexOfSeparator = epmAttr.SourcePath.IndexOf('/'); String propertyToLookFor = indexOfSeparator == -1 ? epmAttr.SourcePath : epmAttr.SourcePath.Substring(0, indexOfSeparator); return this.PropertiesDeclaredOnThisType.Any(p => p.Name == propertyToLookFor); } /// <summary> /// Checks if the resource type is sealed. If not, it throws an InvalidOperationException. /// </summary> private void ThrowIfSealed() { if (this.isReadOnly) { throw new InvalidOperationException(Strings.ResourceType_Sealed(this.FullName)); } } /// <summary> /// Calls the virtual LoadPropertiesDeclaredOnThisType method, if its not already called and then /// adds the properties returned by the method to the list of properties for this type. /// </summary> private void GetPropertiesDeclaredOnThisType() { // We just call the virtual LoadPropertiesDeclaredOnThisType method only once. If it hasn't been called yet, // then call the method and update the state to reflect that. if (!this.isLoadPropertiesMethodCalled) { foreach (ResourceProperty p in this.LoadPropertiesDeclaredOnThisType()) { this.AddPropertyInternal(p); // if this type is already set to readonly, make sure that new properties returned by the virtual method // are also set to readonly if (this.IsReadOnly) { p.SetReadOnly(); } } this.isLoadPropertiesMethodCalled = true; } } /// <summary> /// This method is called only when the Properties property is called and the type is already set to read-only. /// This method validates all the properties w.r.t to the base type and calls SetReadOnly on all the properties. /// </summary> private void ValidateType() { Debug.Assert(this.isLoadPropertiesMethodCalled && this.IsReadOnly, "This method must be invoked only if LoadPropertiesDeclaredOnThisType has been called and the type is set to ReadOnly"); if (this.BaseType != null) { // make sure that there are no properties with the same name. Properties with duplicate name within the type // is already checked in AddProperty method foreach (ResourceProperty rp in this.BaseType.Properties) { if (this.propertiesDeclaredOnThisType.Where(p => p.Name == rp.Name).FirstOrDefault() != null) { throw new InvalidOperationException(Strings.ResourceType_PropertyWithSameNameAlreadyExists(rp.Name, this.FullName)); } } } else if (this.ResourceTypeKind == ResourceTypeKind.EntityType) { if (this.propertiesDeclaredOnThisType.Where(p => p.IsOfKind(ResourcePropertyKind.Key)).FirstOrDefault() == null) { throw new InvalidOperationException(Strings.ResourceType_MissingKeyPropertiesForEntity(this.FullName)); } } // set all the properties to readonly foreach (ResourceProperty p in this.propertiesDeclaredOnThisType) { p.SetReadOnly(); // Note that we cache the propertyinfo objects for each CLR properties in the ResourceType class // rather than the ResourceProperty class because the same ResourceProperty instance can be added // to multiple ResourceType instances. if (p.CanReflectOnInstanceTypeProperty) { this.GetPropertyInfoDecaredOnThisType(p); } } // Resolve EpmInfos now that everything in the type hierarchy is readonly try { if (this.EpmInfoInitialized == false) { this.BuildDynamicEpmInfo(this); this.EpmInfoInitialized = true; } } catch { // If an exception was thrown from this.BuildDynamicEpmInfo(this) method // EpmSourceTree and EpmTargetTree may be only half constructed and need to be reset. if (this.HasEntityPropertyMappings && !this.EpmInfoInitialized) { this.epmInfo.Reset(); } throw; } } #endregion Methods. #region EpmInfoPerResourceType /// <summary>Holder of Epm related data structure per resource type</summary> private sealed class EpmInfoPerResourceType { /// <summary>EpmSourceTree per <see cref="ResourceType"/></summary> private EpmSourceTree epmSourceTree; /// <summary>EpmTargetTree per <see cref="ResourceType"/></summary> private EpmTargetTree epmTargetTree; /// <summary>Inherited EpmInfo</summary> private List<EntityPropertyMappingAttribute> inheritedEpmInfo; /// <summary>Own EpmInfo</summary> private List<EntityPropertyMappingAttribute> ownEpmInfo; /// <summary>Property for obtaining EpmSourceTree for a type</summary> internal EpmSourceTree EpmSourceTree { get { if (this.epmSourceTree == null) { this.epmSourceTree = new EpmSourceTree(this.EpmTargetTree); } return this.epmSourceTree; } } /// <summary>Property for obtaining EpmTargetTree for a type</summary> internal EpmTargetTree EpmTargetTree { get { if (this.epmTargetTree == null) { this.epmTargetTree = new EpmTargetTree(); } return this.epmTargetTree; } } /// <summary>Inherited EpmInfo</summary> internal List<EntityPropertyMappingAttribute> InheritedEpmInfo { get { if (this.inheritedEpmInfo == null) { this.inheritedEpmInfo = new List<EntityPropertyMappingAttribute>(); } return this.inheritedEpmInfo; } } /// <summary>Own EpmInfo</summary> internal List<EntityPropertyMappingAttribute> OwnEpmInfo { get { if (this.ownEpmInfo == null) { this.ownEpmInfo = new List<EntityPropertyMappingAttribute>(); } return this.ownEpmInfo; } } /// <summary> /// Removes all data created internally by ResourceType. This is needed when building epm /// info fails since the trees may be left in undefined state (i.e. half constructed) and /// if inherited EPM attributes exist duplicates will be added. /// </summary> internal void Reset() { this.epmTargetTree = null; this.epmSourceTree = null; this.inheritedEpmInfo = null; } } #endregion } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel; using System.Linq; using Avalonia.Data.Core; namespace Avalonia.Collections { /// <summary> /// A notifying dictionary. /// </summary> /// <typeparam name="TKey">The type of the dictionary key.</typeparam> /// <typeparam name="TValue">The type of the dictionary value.</typeparam> public class AvaloniaDictionary<TKey, TValue> : IDictionary<TKey, TValue>, IDictionary, INotifyCollectionChanged, INotifyPropertyChanged { private Dictionary<TKey, TValue> _inner; /// <summary> /// Initializes a new instance of the <see cref="AvaloniaDictionary{TKey, TValue}"/> class. /// </summary> public AvaloniaDictionary() { _inner = new Dictionary<TKey, TValue>(); } /// <summary> /// Occurs when the collection changes. /// </summary> public event NotifyCollectionChangedEventHandler CollectionChanged; /// <summary> /// Raised when a property on the collection changes. /// </summary> public event PropertyChangedEventHandler PropertyChanged; /// <inheritdoc/> public int Count => _inner.Count; /// <inheritdoc/> public bool IsReadOnly => false; /// <inheritdoc/> public ICollection<TKey> Keys => _inner.Keys; /// <inheritdoc/> public ICollection<TValue> Values => _inner.Values; bool IDictionary.IsFixedSize => ((IDictionary)_inner).IsFixedSize; ICollection IDictionary.Keys => ((IDictionary)_inner).Keys; ICollection IDictionary.Values => ((IDictionary)_inner).Values; bool ICollection.IsSynchronized => ((IDictionary)_inner).IsSynchronized; object ICollection.SyncRoot => ((IDictionary)_inner).SyncRoot; /// <summary> /// Gets or sets the named resource. /// </summary> /// <param name="key">The resource key.</param> /// <returns>The resource, or null if not found.</returns> public TValue this[TKey key] { get { return _inner[key]; } set { TValue old; bool replace = _inner.TryGetValue(key, out old); _inner[key] = value; if (replace) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs($"Item[{key}]")); if (CollectionChanged != null) { var e = new NotifyCollectionChangedEventArgs( NotifyCollectionChangedAction.Replace, new KeyValuePair<TKey, TValue>(key, value), new KeyValuePair<TKey, TValue>(key, old)); CollectionChanged(this, e); } } else { NotifyAdd(key, value); } } } object IDictionary.this[object key] { get => ((IDictionary)_inner)[key]; set => ((IDictionary)_inner)[key] = value; } /// <inheritdoc/> public void Add(TKey key, TValue value) { _inner.Add(key, value); NotifyAdd(key, value); } /// <inheritdoc/> public void Clear() { var old = _inner; _inner = new Dictionary<TKey, TValue>(); PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Count))); PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(CommonPropertyNames.IndexerName)); if (CollectionChanged != null) { var e = new NotifyCollectionChangedEventArgs( NotifyCollectionChangedAction.Remove, old.ToList(), -1); CollectionChanged(this, e); } } /// <inheritdoc/> public bool ContainsKey(TKey key) => _inner.ContainsKey(key); /// <inheritdoc/> public void CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex) { ((IDictionary<TKey, TValue>)_inner).CopyTo(array, arrayIndex); } /// <inheritdoc/> public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator() => _inner.GetEnumerator(); /// <inheritdoc/> public bool Remove(TKey key) { if (_inner.TryGetValue(key, out TValue value)) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Count))); PropertyChanged?.Invoke(this, new PropertyChangedEventArgs($"Item[{key}]")); if (CollectionChanged != null) { var e = new NotifyCollectionChangedEventArgs( NotifyCollectionChangedAction.Remove, new[] { new KeyValuePair<TKey, TValue>(key, value) }, -1); CollectionChanged(this, e); } return true; } else { return false; } } /// <inheritdoc/> public bool TryGetValue(TKey key, out TValue value) => _inner.TryGetValue(key, out value); /// <inheritdoc/> IEnumerator IEnumerable.GetEnumerator() => _inner.GetEnumerator(); /// <inheritdoc/> void ICollection.CopyTo(Array array, int index) => ((ICollection)_inner).CopyTo(array, index); /// <inheritdoc/> void ICollection<KeyValuePair<TKey, TValue>>.Add(KeyValuePair<TKey, TValue> item) { Add(item.Key, item.Value); } /// <inheritdoc/> bool ICollection<KeyValuePair<TKey, TValue>>.Contains(KeyValuePair<TKey, TValue> item) { return _inner.Contains(item); } /// <inheritdoc/> bool ICollection<KeyValuePair<TKey, TValue>>.Remove(KeyValuePair<TKey, TValue> item) { return Remove(item.Key); } /// <inheritdoc/> void IDictionary.Add(object key, object value) => Add((TKey)key, (TValue)value); /// <inheritdoc/> bool IDictionary.Contains(object key) => ((IDictionary) _inner).Contains(key); /// <inheritdoc/> IDictionaryEnumerator IDictionary.GetEnumerator() => ((IDictionary)_inner).GetEnumerator(); /// <inheritdoc/> void IDictionary.Remove(object key) => Remove((TKey)key); private void NotifyAdd(TKey key, TValue value) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Count))); PropertyChanged?.Invoke(this, new PropertyChangedEventArgs($"Item[{key}]")); if (CollectionChanged != null) { var e = new NotifyCollectionChangedEventArgs( NotifyCollectionChangedAction.Add, new[] { new KeyValuePair<TKey, TValue>(key, value) }, -1); CollectionChanged(this, e); } } } }
//------------------------------------------------------------------------------ // <copyright file="uribuilder.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System { using System.Text; using System.Globalization; using System.Threading; /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public class UriBuilder { // fields private bool m_changed = true; private string m_fragment = String.Empty; private string m_host = "localhost"; private string m_password = String.Empty; private string m_path = "/"; private int m_port = -1; private string m_query = String.Empty; private string m_scheme = "http"; private string m_schemeDelimiter = Uri.SchemeDelimiter; private Uri m_uri; private string m_username = String.Empty; // constructors /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public UriBuilder() { } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public UriBuilder(string uri) { // setting allowRelative=true for a string like www.acme.org Uri tryUri = new Uri(uri, UriKind.RelativeOrAbsolute); if (tryUri.IsAbsoluteUri) { Init(tryUri); } else { uri = Uri.UriSchemeHttp + Uri.SchemeDelimiter + uri; Init(new Uri(uri)); } } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public UriBuilder(Uri uri) { if ((object)uri == null) throw new ArgumentNullException("uri"); Init(uri); } private void Init(Uri uri) { m_fragment = uri.Fragment; m_query = uri.Query; m_host = uri.Host; m_path = uri.AbsolutePath; m_port = uri.Port; m_scheme = uri.Scheme; m_schemeDelimiter = uri.HasAuthority? Uri.SchemeDelimiter: ":"; string userInfo = uri.UserInfo; if (!string.IsNullOrEmpty(userInfo)) { int index = userInfo.IndexOf(':'); if (index != -1) { m_password = userInfo.Substring(index + 1); m_username = userInfo.Substring(0, index); } else { m_username = userInfo; } } SetFieldsFromUri(uri); } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public UriBuilder(string schemeName, string hostName) { Scheme = schemeName; Host = hostName; } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public UriBuilder(string scheme, string host, int portNumber) : this(scheme, host) { Port = portNumber; } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public UriBuilder(string scheme, string host, int port, string pathValue ) : this(scheme, host, port) { Path = pathValue; } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public UriBuilder(string scheme, string host, int port, string path, string extraValue ) : this(scheme, host, port, path) { try { Extra = extraValue; } catch (Exception exception) { if (exception is ThreadAbortException || exception is StackOverflowException || exception is OutOfMemoryException) { throw; } throw new ArgumentException("extraValue"); } } // properties private string Extra { set { if (value == null) { value = String.Empty; } if (value.Length > 0) { if (value[0] == '#') { Fragment = value.Substring(1); } else if (value[0] == '?') { int end = value.IndexOf('#'); if (end == -1) { end = value.Length; } else { Fragment = value.Substring(end+1); } Query = value.Substring(1, end-1); } else { throw new ArgumentException("value"); } } else { Fragment = String.Empty; Query = String.Empty; } } } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public string Fragment { get { return m_fragment; } set { if (value == null) { value = String.Empty; } if (value.Length > 0) { value = '#' + value; } m_fragment = value; m_changed = true; } } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public string Host { get { return m_host; } set { if (value == null) { value = String.Empty; } m_host = value; //probable ipv6 address - if (m_host.IndexOf(':') >= 0) { //set brackets if (m_host[0] != '[') m_host = "[" + m_host + "]"; } m_changed = true; } } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public string Password { get { return m_password; } set { if (value == null) { value = String.Empty; } m_password = value; m_changed = true; } } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public string Path { get { return m_path; } set { if ((value == null) || (value.Length == 0)) { value = "/"; } //if ((value[0] != '/') && (value[0] != '\\')) { // value = '/' + value; //} m_path = Uri.InternalEscapeString(ConvertSlashes(value)); m_changed = true; } } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public int Port { get { return m_port; } set { if (value < -1 || value > 0xFFFF) { throw new ArgumentOutOfRangeException("value"); } m_port = value; m_changed = true; } } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public string Query { get { return m_query; } set { if (value == null) { value = String.Empty; } if (value.Length > 0) { value = '?' + value; } m_query = value; m_changed = true; } } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public string Scheme { get { return m_scheme; } set { if (value == null) { value = String.Empty; } int index = value.IndexOf(':'); if (index != -1) { value = value.Substring(0, index); } if (value.Length != 0) { if (!Uri.CheckSchemeName(value)) { throw new ArgumentException("value"); } value = value.ToLower(CultureInfo.InvariantCulture); } m_scheme = value; m_changed = true; } } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public Uri Uri { get { if (m_changed) { m_uri = new Uri(ToString()); SetFieldsFromUri(m_uri); m_changed = false; } return m_uri; } } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public string UserName { get { return m_username; } set { if (value == null) { value = String.Empty; } m_username = value; m_changed = true; } } // methods private string ConvertSlashes(string path) { StringBuilder sb = new StringBuilder(path.Length); char ch; for (int i = 0; i < path.Length; ++i) { ch = path[i]; if (ch == '\\') { ch = '/'; } sb.Append(ch); } return sb.ToString(); } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public override bool Equals(object rparam) { if (rparam == null) { return false; } return Uri.Equals(rparam.ToString()); } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public override int GetHashCode() { return Uri.GetHashCode(); } private void SetFieldsFromUri(Uri uri) { m_fragment = uri.Fragment; m_query = uri.Query; m_host = uri.Host; m_path = uri.AbsolutePath; m_port = uri.Port; m_scheme = uri.Scheme; m_schemeDelimiter = uri.HasAuthority? Uri.SchemeDelimiter: ":"; string userInfo = uri.UserInfo; if (userInfo.Length > 0) { int index = userInfo.IndexOf(':'); if (index != -1) { m_password = userInfo.Substring(index + 1); m_username = userInfo.Substring(0, index); } else { m_username = userInfo; } } } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public override string ToString() { if (m_username.Length == 0 && m_password.Length > 0) { throw new UriFormatException(SR.GetString(SR.net_uri_BadUserPassword)); } if (m_scheme.Length != 0) { UriParser syntax = UriParser.GetSyntax(m_scheme); if (syntax != null) m_schemeDelimiter = syntax.InFact(UriSyntaxFlags.MustHaveAuthority) || (m_host.Length != 0 && syntax.NotAny(UriSyntaxFlags.MailToLikeUri) && syntax.InFact(UriSyntaxFlags.OptionalAuthority )) ? Uri.SchemeDelimiter : ":"; else m_schemeDelimiter = m_host.Length != 0? Uri.SchemeDelimiter: ":"; } string result = m_scheme.Length != 0? (m_scheme + m_schemeDelimiter): string.Empty; return result + m_username + ((m_password.Length > 0) ? (":" + m_password) : String.Empty) + ((m_username.Length > 0) ? "@" : String.Empty) + m_host + (((m_port != -1) && (m_host.Length > 0)) ? (":" + m_port) : String.Empty) + (((m_host.Length > 0) && (m_path.Length != 0) && (m_path[0] != '/')) ? "/" : String.Empty) + m_path + m_query + m_fragment; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace Microsoft.Tools.ServiceModel.SvcUtil.XmlSerializer { using System; using System.ServiceModel.Channels; using System.Configuration; using System.Collections.Generic; using System.IO; using System.Reflection; using System.ServiceModel; internal partial class Options { private ToolMode? _defaultMode; private ToolMode _validModes = ToolMode.Any; private string _modeSettingOption; private string _modeSettingValue; private string _targetValue; private string _outputFileArg; private string _directoryArg; private string _configFileArg; private bool _noLogo; private List<string> _inputParameters; private List<Type> _referencedTypes; private List<Assembly> _referencedAssemblies; private Dictionary<string, Type> _excludedTypes; private bool _nostdlib; private Dictionary<string, string> _namespaceMappings; internal string OutputFileArg { get { return _outputFileArg; } } internal string DirectoryArg { get { return _directoryArg; } } internal bool NoLogo { get { return _noLogo; } } internal List<string> InputParameters { get { return _inputParameters; } } internal List<Type> ReferencedTypes { get { return _referencedTypes; } } internal List<Assembly> ReferencedAssemblies { get { return _referencedAssemblies; } } internal bool Nostdlib { get { return _nostdlib; } } internal Dictionary<string, string> NamespaceMappings { get { return _namespaceMappings; } } private TypeResolver _typeResolver; internal string ModeSettingOption { get { return _modeSettingOption; } } internal string ModeSettingValue { get { return _modeSettingValue; } } private Options(ArgumentDictionary arguments) { OptionProcessingHelper optionProcessor = new OptionProcessingHelper(this, arguments); optionProcessor.ProcessArguments(); } internal static Options ParseArguments(string[] args) { ArgumentDictionary arguments; try { arguments = CommandParser.ParseCommand(args, Options.Switches.All); } catch (ArgumentException ae) { throw new ToolOptionException(ae.Message); } return new Options(arguments); } internal void SetAllowedModes(ToolMode newDefaultMode, ToolMode validModes, string option, string value) { Tool.Assert(validModes != ToolMode.None, "validModes should never be set to None!"); Tool.Assert(newDefaultMode != ToolMode.None, "newDefaultMode should never be set to None!"); Tool.Assert((validModes & newDefaultMode) != ToolMode.None, "newDefaultMode must be a validMode!"); Tool.Assert(IsSingleBit(newDefaultMode), "newDefaultMode must Always represent a single mode!"); //update/filter list of valid modes _validModes &= validModes; if (_validModes == ToolMode.None) throw new InvalidToolModeException(); bool currentDefaultIsValid = (_defaultMode.HasValue && (_defaultMode & _validModes) != ToolMode.None); bool newDefaultIsValid = (newDefaultMode & _validModes) != ToolMode.None; if (!currentDefaultIsValid) { if (newDefaultIsValid) _defaultMode = newDefaultMode; else _defaultMode = null; } //If this is true, then this is an explicit mode setting if (IsSingleBit(validModes)) { _modeSettingOption = option; _modeSettingValue = value; } } internal ToolMode? GetToolMode() { if (IsSingleBit(_validModes)) return _validModes; return _defaultMode; } internal string GetCommandLineString(string option, string value) { return (value == null) ? option : option + ":" + value; } private static bool IsSingleBit(ToolMode mode) { //figures out if the mode has a single bit set ( is a power of 2) int x = (int)mode; return (x != 0) && ((x & (x + ~0)) == 0); } internal bool IsTypeExcluded(Type type) { return OptionProcessingHelper.IsTypeSpecified(type, _excludedTypes, Options.Cmd.ExcludeType); } private class OptionProcessingHelper { private Options _parent; private ArgumentDictionary _arguments; private static Type s_typeOfDateTimeOffset = typeof(DateTimeOffset); internal OptionProcessingHelper(Options options, ArgumentDictionary arguments) { _parent = options; _arguments = arguments; } internal void ProcessArguments() { CheckForBasicOptions(); if (CheckForHelpOption()) return; ProcessDirectoryOption(); ProcessOutputOption(); ReadInputArguments(); ParseNamespaceMappings(); ParseReferenceAssemblies(); } private bool CheckForHelpOption() { if (_arguments.ContainsArgument(Options.Cmd.Help) || _arguments.Count == 0) { _parent.SetAllowedModes(ToolMode.DisplayHelp, ToolMode.DisplayHelp, Options.Cmd.Help, null); return true; } return false; } private void CheckForBasicOptions() { _parent._noLogo = _arguments.ContainsArgument(Options.Cmd.NoLogo); #if DEBUG ToolConsole.SetOptions(_arguments.ContainsArgument(Options.Cmd.Debug)); #endif } private void ProcessDirectoryOption() { // Directory //--------------------------------------------------------------------------------------------------------- if (_arguments.ContainsArgument(Options.Cmd.Directory)) { string directoryArgValue = _arguments.GetArgument(Options.Cmd.Directory); try { ValidateIsDirectoryPathOnly(Options.Cmd.Directory, directoryArgValue); if (!directoryArgValue.EndsWith(Path.DirectorySeparatorChar.ToString(), StringComparison.Ordinal)) directoryArgValue += Path.DirectorySeparatorChar; _parent._directoryArg = Path.GetFullPath(directoryArgValue); } catch (ToolOptionException) { throw; } #pragma warning suppress 56500 // covered by FxCOP catch (Exception e) { if (Tool.IsFatal(e)) throw; throw new ToolArgumentException(SR.Format(SR.ErrInvalidPath, directoryArgValue, Options.Cmd.Directory), e); } } else { _parent._directoryArg = null; } } private static void ValidateIsDirectoryPathOnly(string arg, string value) { ValidatePath(arg, value); FileInfo fileInfo = new FileInfo(value); if (fileInfo.Exists) throw new ToolOptionException(SR.Format(SR.ErrDirectoryPointsToAFile, arg, value)); } private static void ValidatePath(string arg, string value) { int invalidCharacterIndex = value.IndexOfAny(Path.GetInvalidPathChars()); if (invalidCharacterIndex != -1) { string invalidCharacter = value[invalidCharacterIndex].ToString(); throw new ToolOptionException(SR.Format(SR.ErrDirectoryContainsInvalidCharacters, arg, value, invalidCharacter)); } } private void ProcessOutputOption() { if (_arguments.ContainsArgument(Options.Cmd.Out)) { _parent._outputFileArg = _arguments.GetArgument(Options.Cmd.Out); if (_parent._outputFileArg != string.Empty) { SetAllowedModesFromOption(ToolMode.XmlSerializerGeneration, ToolMode.XmlSerializerGeneration, Options.Cmd.Out, ""); ValidatePath(Options.Cmd.Out, _parent._outputFileArg); } } else { _parent._outputFileArg = null; } } private void ReadInputArguments() { _parent._inputParameters = new List<string>(_arguments.GetArguments(String.Empty)); } private void ParseNamespaceMappings() { IList<string> namespaceMappingsArgs = _arguments.GetArguments(Options.Cmd.Namespace); _parent._namespaceMappings = new Dictionary<string, string>(namespaceMappingsArgs.Count); foreach (string namespaceMapping in namespaceMappingsArgs) { string[] parts = namespaceMapping.Split(','); if (parts == null || parts.Length != 2) throw new ToolOptionException(SR.Format(SR.ErrInvalidNamespaceArgument, Options.Cmd.Namespace, namespaceMapping)); string targetNamespace = parts[0].Trim(); string clrNamespace = parts[1].Trim(); if (_parent._namespaceMappings.ContainsKey(targetNamespace)) { string prevClrNamespace = _parent._namespaceMappings[targetNamespace]; if (prevClrNamespace != clrNamespace) throw new ToolOptionException(SR.Format(SR.ErrCannotSpecifyMultipleMappingsForNamespace, Options.Cmd.Namespace, targetNamespace, prevClrNamespace, clrNamespace)); } else { _parent._namespaceMappings.Add(targetNamespace, clrNamespace); } } } private void ParseReferenceAssemblies() { IList<string> referencedAssembliesArgs = _arguments.GetArguments(Options.Cmd.Reference); IList<string> excludeTypesArgs = _arguments.GetArguments(Options.Cmd.ExcludeType); IList<string> referencedCollectionTypesArgs = _arguments.GetArguments(Options.Cmd.CollectionType); bool nostdlib = _arguments.ContainsArgument(Options.Cmd.Nostdlib); if (excludeTypesArgs != null && excludeTypesArgs.Count > 0) SetAllowedModesFromOption(ToolMode.XmlSerializerGeneration, ToolMode.XmlSerializerGeneration, Options.Cmd.ExcludeType, null); AddReferencedTypes(referencedAssembliesArgs, excludeTypesArgs, referencedCollectionTypesArgs, nostdlib); _parent._typeResolver = CreateTypeResolver(_parent); } private void SetAllowedModesFromOption(ToolMode newDefaultMode, ToolMode allowedModes, string option, string value) { try { _parent.SetAllowedModes(newDefaultMode, allowedModes, option, value); } catch (InvalidToolModeException) { string optionStr = _parent.GetCommandLineString(option, value); if (_parent._modeSettingOption != null) { if (_parent._modeSettingOption == Options.Cmd.Target) { throw new ToolOptionException(SR.Format(SR.ErrOptionConflictsWithTarget, Options.Cmd.Target, _parent.ModeSettingValue, optionStr)); } else { string modeSettingStr = _parent.GetCommandLineString(_parent._modeSettingOption, _parent._modeSettingValue); throw new ToolOptionException(SR.Format(SR.ErrOptionModeConflict, optionStr, modeSettingStr)); } } else { throw new ToolOptionException(SR.Format(SR.ErrAmbiguousOptionModeConflict, optionStr)); } } } private void AddReferencedTypes(IList<string> referenceArgs, IList<string> excludedTypeArgs, IList<string> collectionTypesArgs, bool nostdlib) { _parent._referencedTypes = new List<Type>(); _parent._referencedAssemblies = new List<Assembly>(referenceArgs.Count); _parent._nostdlib = nostdlib; _parent._excludedTypes = AddSpecifiedTypesToDictionary(excludedTypeArgs, Options.Cmd.ExcludeType); Dictionary<string, Type> foundCollectionTypes = AddSpecifiedTypesToDictionary(collectionTypesArgs, Options.Cmd.CollectionType); LoadReferencedAssemblies(referenceArgs); foreach (Assembly assembly in _parent._referencedAssemblies) { AddReferencedTypesFromAssembly(assembly, foundCollectionTypes); } if (!nostdlib) { AddMscorlib(foundCollectionTypes); AddServiceModelLib(foundCollectionTypes); } } private void LoadReferencedAssemblies(IList<string> referenceArgs) { foreach (string path in referenceArgs) { Assembly assembly; try { assembly = InputModule.LoadAssembly(path); if (!_parent._referencedAssemblies.Contains(assembly)) { _parent._referencedAssemblies.Add(assembly); } else { throw new ToolOptionException(SR.Format(SR.ErrDuplicateReferenceValues, Options.Cmd.Reference, assembly.Location)); } } #pragma warning suppress 56500 // covered by FxCOP catch (Exception e) { if (Tool.IsFatal(e)) throw; throw new ToolOptionException(SR.Format(SR.ErrCouldNotLoadReferenceAssemblyAt, path), e); } } } private Dictionary<string, Type> AddSpecifiedTypesToDictionary(IList<string> typeArgs, string cmd) { Dictionary<string, Type> specifiedTypes = new Dictionary<string, Type>(typeArgs.Count); foreach (string typeArg in typeArgs) { if (specifiedTypes.ContainsKey(typeArg)) throw new ToolOptionException(SR.Format(SR.ErrDuplicateValuePassedToTypeArg, cmd, typeArg)); specifiedTypes.Add(typeArg, null); } return specifiedTypes; } private void AddReferencedTypesFromAssembly(Assembly assembly, Dictionary<string, Type> foundCollectionTypes) { foreach (Type type in InputModule.LoadTypes(assembly)) { if (type.IsPublic || type.IsNestedPublic) { if (!_parent.IsTypeExcluded(type)) _parent._referencedTypes.Add(type); } } } private void AddMscorlib(Dictionary<string, Type> foundCollectionTypes) { Assembly mscorlib = typeof(int).Assembly; if (!_parent._referencedAssemblies.Contains(mscorlib)) { AddReferencedTypesFromAssembly(mscorlib, foundCollectionTypes); } } private void AddServiceModelLib(Dictionary<string, Type> foundCollectionTypes) { Assembly serviceModelLib = typeof(ChannelFactory).Assembly; if (!_parent._referencedAssemblies.Contains(serviceModelLib)) { AddReferencedTypesFromAssembly(serviceModelLib, foundCollectionTypes); } } internal static bool IsTypeSpecified(Type type, Dictionary<string, Type> specifiedTypes, string cmd) { Type foundType = null; string foundTypeName = null; // Search the Dictionary for the type // -------------------------------------------------------------------------------------------------------- if (specifiedTypes.TryGetValue(type.FullName, out foundType)) foundTypeName = type.FullName; if (specifiedTypes.TryGetValue(type.AssemblyQualifiedName, out foundType)) foundTypeName = type.AssemblyQualifiedName; // Throw appropriate error message if we found something and the entry value wasn't null // -------------------------------------------------------------------------------------------------------- if (foundTypeName != null) { if (foundType != null && foundType != type) { throw new ToolOptionException(SR.Format(SR.ErrCannotDisambiguateSpecifiedTypes, cmd, type.AssemblyQualifiedName, foundType.AssemblyQualifiedName)); } else { specifiedTypes[foundTypeName] = type; } return true; } return false; } static TypeResolver CreateTypeResolver(Options options) { TypeResolver typeResolver = new TypeResolver(options); AppDomain.CurrentDomain.TypeResolve += new ResolveEventHandler(typeResolver.ResolveType); AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(typeResolver.ResolveAssembly); return typeResolver; } } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System.Management.Automation.Language; using System.Security; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Management.Automation.Internal; using System.Management.Automation.Runspaces; using Dbg = System.Management.Automation; using System.Diagnostics.CodeAnalysis; namespace System.Management.Automation { /// <summary> /// Holds the state of a Monad Shell session. /// </summary> [SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling", Justification = "This is a bridge class between internal classes and a public interface. It requires this much coupling.")] internal sealed partial class SessionStateInternal { #region tracer /// <summary> /// An instance of the PSTraceSource class used for trace output /// using "SessionState" as the category. /// </summary> [Dbg.TraceSourceAttribute( "SessionState", "SessionState Class")] private static Dbg.PSTraceSource s_tracer = Dbg.PSTraceSource.GetTracer("SessionState", "SessionState Class"); #endregion tracer #region Constructor /// <summary> /// Constructor for session state object. /// </summary> /// <param name="context"> /// The context for the runspace to which this session state object belongs. /// </param> /// <exception cref="ArgumentNullException"> /// if <paramref name="context"/> is null. /// </exception> internal SessionStateInternal(ExecutionContext context) : this(null, false, context) { } internal SessionStateInternal(SessionStateInternal parent, bool linkToGlobal, ExecutionContext context) { if (context == null) { throw PSTraceSource.NewArgumentNullException("context"); } ExecutionContext = context; // Create the working directory stack. This // is used for the pushd and popd commands _workingLocationStack = new Dictionary<string, Stack<PathInfo>>(StringComparer.OrdinalIgnoreCase); // Conservative choice to limit the Set-Location history in order to limit memory impact in case of a regression. const uint locationHistoryLimit = 20; _setLocationHistory = new HistoryStack<PathInfo>(locationHistoryLimit); GlobalScope = new SessionStateScope(null); ModuleScope = GlobalScope; _currentScope = GlobalScope; InitializeSessionStateInternalSpecialVariables(false); // Create the push the global scope on as // the starting script scope. That way, if you dot-source a script // that uses variables qualified by script: it works. GlobalScope.ScriptScope = GlobalScope; if (parent != null) { GlobalScope.Parent = parent.GlobalScope; // Copy the drives and providers from the parent... CopyProviders(parent); // During loading of core modules, providers are not populated. // We set the drive information later if (Providers != null && Providers.Count > 0) { CurrentDrive = parent.CurrentDrive; } // Link it to the global scope... if (linkToGlobal) { GlobalScope = parent.GlobalScope; } } else { _currentScope.LocalsTuple = MutableTuple.MakeTuple(Compiler.DottedLocalsTupleType, Compiler.DottedLocalsNameIndexMap); } } /// <summary> /// Add any special variables to the session state variable table. This routine /// must be called at construction time or if the variable table is reset. /// </summary> internal void InitializeSessionStateInternalSpecialVariables(bool clearVariablesTable) { if (clearVariablesTable) { // Clear the variable table GlobalScope.Variables.Clear(); // Add in the per-scope default variables. GlobalScope.AddSessionStateScopeDefaultVariables(); } // Set variable $Error PSVariable errorvariable = new PSVariable("Error", new ArrayList(), ScopedItemOptions.Constant); GlobalScope.SetVariable(errorvariable.Name, errorvariable, false, false, this, fastPath: true); // Set variable $PSDefaultParameterValues Collection<Attribute> attributes = new Collection<Attribute>(); attributes.Add(new ArgumentTypeConverterAttribute(typeof(System.Management.Automation.DefaultParameterDictionary))); PSVariable psDefaultParameterValuesVariable = new PSVariable(SpecialVariables.PSDefaultParameterValues, new DefaultParameterDictionary(), ScopedItemOptions.None, attributes, RunspaceInit.PSDefaultParameterValuesDescription); GlobalScope.SetVariable(psDefaultParameterValuesVariable.Name, psDefaultParameterValuesVariable, false, false, this, fastPath: true); } #endregion Constructor #region Private data /// <summary> /// Provides all the path manipulation and globbing for Monad paths. /// </summary> internal LocationGlobber Globber { get { return _globberPrivate ?? (_globberPrivate = ExecutionContext.LocationGlobber); } } private LocationGlobber _globberPrivate; /// <summary> /// The context of the runspace to which this session state object belongs. /// </summary> internal ExecutionContext ExecutionContext { get; } /// <summary> /// Returns the public session state facade object for this session state instance. /// </summary> internal SessionState PublicSessionState { get { return _publicSessionState ?? (_publicSessionState = new SessionState(this)); } set { _publicSessionState = value; } } private SessionState _publicSessionState; /// <summary> /// Gets the engine APIs to access providers. /// </summary> internal ProviderIntrinsics InvokeProvider { get { return _invokeProvider ?? (_invokeProvider = new ProviderIntrinsics(this)); } } private ProviderIntrinsics _invokeProvider; /// <summary> /// The module info object associated with this session state. /// </summary> internal PSModuleInfo Module { get; set; } = null; // This is used to maintain the order in which modules were imported. // This is used by Get-Command -All to order by last imported internal List<string> ModuleTableKeys = new List<string>(); /// <summary> /// The private module table for this session state object... /// </summary> internal Dictionary<string, PSModuleInfo> ModuleTable { get; } = new Dictionary<string, PSModuleInfo>(StringComparer.OrdinalIgnoreCase); /// <summary> /// Get/set constraints for this execution environment. /// </summary> internal PSLanguageMode LanguageMode { get { return ExecutionContext.LanguageMode; } set { ExecutionContext.LanguageMode = value; } } /// <summary> /// If true the PowerShell debugger will use FullLanguage mode, otherwise it will use the current language mode. /// </summary> internal bool UseFullLanguageModeInDebugger { get { return ExecutionContext.UseFullLanguageModeInDebugger; } } /// <summary> /// The list of scripts that are allowed to be run. If the name "*" /// is in the list, then all scripts can be run. (This is the default.) /// </summary> public List<string> Scripts { get; } = new List<string>(new string[] { "*" }); /// <summary> /// See if a script is allowed to be run. /// </summary> /// <param name="scriptPath">Path to check.</param> /// <returns>True if script is allowed.</returns> internal SessionStateEntryVisibility CheckScriptVisibility(string scriptPath) { return checkPathVisibility(Scripts, scriptPath); } /// <summary> /// The list of applications that are allowed to be run. If the name "*" /// is in the list, then all applications can be run. (This is the default.) /// </summary> public List<string> Applications { get; } = new List<string>(new string[] { "*" }); /// <summary> /// List of functions/filters to export from this session state object... /// </summary> internal List<CmdletInfo> ExportedCmdlets { get; } = new List<CmdletInfo>(); /// <summary> /// Defines the default command visibility for this session state. Binding an InitialSessionState instance /// with private members will set this to Private. /// </summary> internal SessionStateEntryVisibility DefaultCommandVisibility = SessionStateEntryVisibility.Public; /// <summary> /// Add an new SessionState cmdlet entry to this session state object... /// </summary> /// <param name="entry">The entry to add.</param> internal void AddSessionStateEntry(SessionStateCmdletEntry entry) { AddSessionStateEntry(entry, /*local*/false); } /// <summary> /// Add an new SessionState cmdlet entry to this session state object... /// </summary> /// <param name="entry">The entry to add.</param> /// <param name="local">If local, add cmdlet to current scope. Else, add to module scope.</param> internal void AddSessionStateEntry(SessionStateCmdletEntry entry, bool local) { ExecutionContext.CommandDiscovery.AddSessionStateCmdletEntryToCache(entry, local); } /// <summary> /// Add an new SessionState cmdlet entry to this session state object... /// </summary> /// <param name="entry">The entry to add.</param> internal void AddSessionStateEntry(SessionStateApplicationEntry entry) { this.Applications.Add(entry.Path); } /// <summary> /// Add an new SessionState cmdlet entry to this session state object... /// </summary> /// <param name="entry">The entry to add.</param> internal void AddSessionStateEntry(SessionStateScriptEntry entry) { this.Scripts.Add(entry.Path); } /// <summary> /// Add the variables that must always be present in a SessionState instance... /// </summary> internal void InitializeFixedVariables() { // // BUGBUG // // String resources for aliases are currently associated with Runspace init // // $Host PSVariable v = new PSVariable( SpecialVariables.Host, ExecutionContext.EngineHostInterface, ScopedItemOptions.Constant | ScopedItemOptions.AllScope, RunspaceInit.PSHostDescription); this.GlobalScope.SetVariable(v.Name, v, asValue: false, force: true, this, CommandOrigin.Internal, fastPath: true); // $HOME - indicate where a user's home directory is located in the file system. // -- %USERPROFILE% on windows // -- %HOME% on unix string home = Environment.GetEnvironmentVariable(Platform.CommonEnvVariableNames.Home) ?? string.Empty; v = new PSVariable(SpecialVariables.Home, home, ScopedItemOptions.ReadOnly | ScopedItemOptions.AllScope, RunspaceInit.HOMEDescription); this.GlobalScope.SetVariable(v.Name, v, asValue: false, force: true, this, CommandOrigin.Internal, fastPath: true); // $ExecutionContext v = new PSVariable(SpecialVariables.ExecutionContext, ExecutionContext.EngineIntrinsics, ScopedItemOptions.Constant | ScopedItemOptions.AllScope, RunspaceInit.ExecutionContextDescription); this.GlobalScope.SetVariable(v.Name, v, asValue: false, force: true, this, CommandOrigin.Internal, fastPath: true); // $PSVersionTable v = new PSVariable(SpecialVariables.PSVersionTable, PSVersionInfo.GetPSVersionTable(), ScopedItemOptions.Constant | ScopedItemOptions.AllScope, RunspaceInit.PSVersionTableDescription); this.GlobalScope.SetVariable(v.Name, v, asValue: false, force: true, this, CommandOrigin.Internal, fastPath: true); // $PSEdition v = new PSVariable(SpecialVariables.PSEdition, PSVersionInfo.PSEditionValue, ScopedItemOptions.Constant | ScopedItemOptions.AllScope, RunspaceInit.PSEditionDescription); this.GlobalScope.SetVariable(v.Name, v, asValue: false, force: true, this, CommandOrigin.Internal, fastPath: true); // $PID Process currentProcess = Process.GetCurrentProcess(); v = new PSVariable( SpecialVariables.PID, currentProcess.Id, ScopedItemOptions.Constant | ScopedItemOptions.AllScope, RunspaceInit.PIDDescription); this.GlobalScope.SetVariable(v.Name, v, asValue: false, force: true, this, CommandOrigin.Internal, fastPath: true); // $PSCulture v = new PSCultureVariable(); this.GlobalScope.SetVariable(v.Name, v, asValue: false, force: true, this, CommandOrigin.Internal, fastPath: true); // $PSUICulture v = new PSUICultureVariable(); this.GlobalScope.SetVariable(v.Name, v, asValue: false, force: true, this, CommandOrigin.Internal, fastPath: true); // $? v = new QuestionMarkVariable(this.ExecutionContext); this.GlobalScope.SetVariableForce(v, this); // $ShellId - if there is no runspace config, use the default string string shellId = ExecutionContext.ShellID; v = new PSVariable(SpecialVariables.ShellId, shellId, ScopedItemOptions.Constant | ScopedItemOptions.AllScope, RunspaceInit.MshShellIdDescription); this.GlobalScope.SetVariable(v.Name, v, asValue: false, force: true, this, CommandOrigin.Internal, fastPath: true); // $PSHOME string applicationBase = Utils.DefaultPowerShellAppBase; v = new PSVariable(SpecialVariables.PSHome, applicationBase, ScopedItemOptions.Constant | ScopedItemOptions.AllScope, RunspaceInit.PSHOMEDescription); this.GlobalScope.SetVariable(v.Name, v, asValue: false, force: true, this, CommandOrigin.Internal, fastPath: true); // $EnabledExperimentalFeatures v = new PSVariable(SpecialVariables.EnabledExperimentalFeatures, ExperimentalFeature.EnabledExperimentalFeatureNames, ScopedItemOptions.Constant | ScopedItemOptions.AllScope, RunspaceInit.EnabledExperimentalFeatures); this.GlobalScope.SetVariable(v.Name, v, asValue: false, force: true, this, CommandOrigin.Internal, fastPath: true); } /// <summary> /// Check to see if an application is allowed to be run. /// </summary> /// <param name="applicationPath">The path to the application to check.</param> /// <returns>True if application is permitted.</returns> internal SessionStateEntryVisibility CheckApplicationVisibility(string applicationPath) { return checkPathVisibility(Applications, applicationPath); } private SessionStateEntryVisibility checkPathVisibility(List<string> list, string path) { if (list == null || list.Count == 0) return SessionStateEntryVisibility.Private; if (string.IsNullOrEmpty(path)) return SessionStateEntryVisibility.Private; if (list.Contains("*")) return SessionStateEntryVisibility.Public; foreach (string p in list) { if (string.Equals(p, path, StringComparison.OrdinalIgnoreCase)) return SessionStateEntryVisibility.Public; if (WildcardPattern.ContainsWildcardCharacters(p)) { WildcardPattern pattern = WildcardPattern.Get(p, WildcardOptions.IgnoreCase); if (pattern.IsMatch(path)) { return SessionStateEntryVisibility.Public; } } } return SessionStateEntryVisibility.Private; } #endregion Private data /// <summary> /// Notification for SessionState to do cleanup /// before runspace is closed. /// </summary> internal void RunspaceClosingNotification() { if (this != ExecutionContext.TopLevelSessionState && Providers.Count > 0) { // Remove all providers at the top level... CmdletProviderContext context = new CmdletProviderContext(this.ExecutionContext); foreach (string providerName in Providers.Keys) { // All errors are ignored. RemoveProvider(providerName, true, context); } } } #region Errors /// <summary> /// Constructs a new instance of a ProviderInvocationException /// using the specified data. /// </summary> /// <param name="resourceId"> /// The resource ID to use as the format message for the error. /// </param> /// <param name="resourceStr"> /// This is the message template string. /// </param> /// <param name="provider"> /// The provider information used when formatting the error message. /// </param> /// <param name="path"> /// The path used when formatting the error message. /// </param> /// <param name="e"> /// The exception that was thrown by the provider. This will be set as /// the ProviderInvocationException's InnerException and the message will /// be used when formatting the error message. /// </param> /// <returns> /// A new instance of a ProviderInvocationException. /// </returns> /// <exception cref="ProviderInvocationException"> /// Wraps <paramref name="e"/> in a ProviderInvocationException /// and then throws it. /// </exception> internal ProviderInvocationException NewProviderInvocationException( string resourceId, string resourceStr, ProviderInfo provider, string path, Exception e) { return NewProviderInvocationException(resourceId, resourceStr, provider, path, e, true); } /// <summary> /// Constructs a new instance of a ProviderInvocationException /// using the specified data. /// </summary> /// <param name="resourceId"> /// The resource ID to use as the format message for the error. /// </param> /// <param name="resourceStr"> /// This is the message template string. /// </param> /// <param name="provider"> /// The provider information used when formatting the error message. /// </param> /// <param name="path"> /// The path used when formatting the error message. /// </param> /// <param name="e"> /// The exception that was thrown by the provider. This will be set as /// the ProviderInvocationException's InnerException and the message will /// be used when formatting the error message. /// </param> /// <param name="useInnerExceptionErrorMessage"> /// If true, the error record from the inner exception will be used if it contains one. /// If false, the error message specified by the resourceId will be used. /// </param> /// <returns> /// A new instance of a ProviderInvocationException. /// </returns> /// <exception cref="ProviderInvocationException"> /// Wraps <paramref name="e"/> in a ProviderInvocationException /// and then throws it. /// </exception> internal ProviderInvocationException NewProviderInvocationException( string resourceId, string resourceStr, ProviderInfo provider, string path, Exception e, bool useInnerExceptionErrorMessage) { // If the innerException was itself thrown by // ProviderBase.ThrowTerminatingError, it is already a // ProviderInvocationException, and we don't want to // re-wrap it. ProviderInvocationException pie = e as ProviderInvocationException; if (pie != null) { pie._providerInfo = provider; return pie; } pie = new ProviderInvocationException(resourceId, resourceStr, provider, path, e, useInnerExceptionErrorMessage); // Log a provider health event MshLog.LogProviderHealthEvent( ExecutionContext, provider.Name, pie, Severity.Warning); return pie; } #endregion Errors } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Microsoft.Win32.SafeHandles; using System.Diagnostics; using System.Runtime.InteropServices; using System.Security.Authentication; using System.Security.Authentication.ExtendedProtection; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; namespace System.Net.Security { #if DEBUG internal sealed class SafeFreeCertContext : DebugSafeHandle { #else internal sealed class SafeFreeCertContext : SafeHandle { #endif private readonly SafeX509Handle _certificate; public SafeFreeCertContext(SafeX509Handle certificate) : base(IntPtr.Zero, true) { // In certain scenarios (eg. server querying for a client cert), the // input certificate may be invalid and this is OK if ((null != certificate) && !certificate.IsInvalid) { bool gotRef = false; certificate.DangerousAddRef(ref gotRef); Debug.Assert(gotRef, "Unexpected failure in AddRef of certificate"); _certificate = certificate; handle = _certificate.DangerousGetHandle(); } } public override bool IsInvalid { get { return handle == IntPtr.Zero; } } protected override bool ReleaseHandle() { _certificate.DangerousRelease(); _certificate.Dispose(); return true; } } // // Implementation of handles dependable on FreeCredentialsHandle // #if DEBUG internal sealed class SafeFreeCredentials : DebugSafeHandle { #else internal sealed class SafeFreeCredentials : SafeHandle { #endif private SafeX509Handle _certHandle; private SafeEvpPKeyHandle _certKeyHandle; private SslProtocols _protocols = SslProtocols.None; private EncryptionPolicy _policy; internal SafeX509Handle CertHandle { get { return _certHandle; } } internal SafeEvpPKeyHandle CertKeyHandle { get { return _certKeyHandle; } } internal SslProtocols Protocols { get { return _protocols; } } public SafeFreeCredentials(X509Certificate certificate, SslProtocols protocols, EncryptionPolicy policy) : base(IntPtr.Zero, true) { Debug.Assert( certificate == null || certificate is X509Certificate2, "Only X509Certificate2 certificates are supported at this time"); X509Certificate2 cert = (X509Certificate2)certificate; if (cert != null) { Debug.Assert(cert.HasPrivateKey, "cert.HasPrivateKey"); using (RSAOpenSsl rsa = (RSAOpenSsl)cert.GetRSAPrivateKey()) { if (rsa != null) { _certKeyHandle = rsa.DuplicateKeyHandle(); Interop.Crypto.CheckValidOpenSslHandle(_certKeyHandle); } } // TODO (3390): Add support for ECDSA. Debug.Assert(_certKeyHandle != null, "Failed to extract a private key handle"); _certHandle = Interop.libcrypto.X509_dup(cert.Handle); Interop.Crypto.CheckValidOpenSslHandle(_certHandle); } _protocols = protocols; _policy = policy; } public override bool IsInvalid { get { return SslProtocols.None == _protocols; } } protected override bool ReleaseHandle() { if (_certHandle != null) { _certHandle.Dispose(); } if (_certKeyHandle != null) { _certKeyHandle.Dispose(); } _protocols = SslProtocols.None; return true; } } // // This is a class holding a Credential handle reference, used for static handles cache // #if DEBUG internal sealed class SafeCredentialReference : DebugCriticalHandleMinusOneIsInvalid { #else internal sealed class SafeCredentialReference : CriticalHandleMinusOneIsInvalid { #endif // // Static cache will return the target handle if found the reference in the table. // internal SafeFreeCredentials Target; internal static SafeCredentialReference CreateReference(SafeFreeCredentials target) { SafeCredentialReference result = new SafeCredentialReference(target); if (result.IsInvalid) { return null; } return result; } private SafeCredentialReference(SafeFreeCredentials target) : base() { // Bumps up the refcount on Target to signify that target handle is statically cached so // its dispose should be postponed bool ignore = false; target.DangerousAddRef(ref ignore); Target = target; SetHandle(new IntPtr(0)); // make this handle valid } protected override bool ReleaseHandle() { SafeFreeCredentials target = Target; if (target != null) { target.DangerousRelease(); } Target = null; return true; } } #if DEBUG internal sealed class SafeDeleteContext : DebugSafeHandle { #else internal sealed class SafeDeleteContext : SafeHandle { #endif private readonly SafeFreeCredentials _credential; private readonly Interop.libssl.SafeSslHandle _sslContext; public Interop.libssl.SafeSslHandle SslContext { get { return _sslContext; } } public SafeDeleteContext(SafeFreeCredentials credential, long options, bool isServer, bool remoteCertRequired) : base(IntPtr.Zero, true) { Debug.Assert((null != credential) && !credential.IsInvalid, "Invalid credential used in SafeDeleteContext"); // When a credential handle is first associated with the context we keep credential // ref count bumped up to ensure ordered finalization. The certificate handle and // key handle are used in the SSL data structures and should survive the lifetime of // the SSL context bool ignore = false; _credential = credential; _credential.DangerousAddRef(ref ignore); try { _sslContext = Interop.OpenSsl.AllocateSslContext( options, credential.CertHandle, credential.CertKeyHandle, isServer, remoteCertRequired); } finally { if (IsInvalid) { _credential.DangerousRelease(); } } } public override bool IsInvalid { get { return (null == _sslContext) || _sslContext.IsInvalid; } } protected override bool ReleaseHandle() { Interop.OpenSsl.FreeSslContext(_sslContext); Debug.Assert((null != _credential) && !_credential.IsInvalid, "Invalid credential saved in SafeDeleteContext"); _credential.DangerousRelease(); return true; } public override string ToString() { return IsInvalid ? String.Empty : handle.ToString(); } } internal abstract class SafeFreeContextBufferChannelBinding : ChannelBinding { // TODO (Issue #3362) To be implemented } }
// file: Model\DateTimeProperty.cs // // summary: Implements the date time property class using System; using System.Collections.Generic; using System.Xml; using System.Xml.Serialization; namespace numl.Model { /// <summary>Features available for the DateTime property.</summary> [Flags] public enum DateTimeFeature { /// <summary> /// Year /// </summary> Year = 0x0001, /// <summary> /// Day of the year (1, 366) /// </summary> DayOfYear = 0x0002, /// <summary> /// Month /// </summary> Month = 0x0008, /// <summary> /// Day /// </summary> Day = 0x0010, /// <summary> /// Day of the week (0, 6) /// </summary> DayOfWeek = 0x0020, /// <summary> /// Hour /// </summary> Hour = 0x0040, /// <summary> /// Minute /// </summary> Minute = 0x0080, /// <summary> /// Second /// </summary> Second = 0x0100, /// <summary> /// Millisecond /// </summary> Millisecond = 0x0200 } /// <summary>Date portions available for the DateTime property.</summary> [Flags] public enum DatePortion { /// <summary> /// Date (Jan. 1, 2000) -> [1, 1, 2000] /// </summary> Date = 0x0001, /// <summary> /// Extended Date (Jan. 1, 2000) -> [1, 6] (DayOfYear, DayOfWeek) /// </summary> DateExtended = 0x0002, /// <summary> /// Time 4:45pm -> [16, 45] (Hour, Minute) /// </summary> Time = 0x0008, /// <summary> /// Extended Time 4:45pm -> [0, 0] (Second, Millisecond) /// </summary> TimeExtended = 0x0010 } /// <summary>DateTime Property. Used as a feature expansion mechanism.</summary> [XmlRoot("DateTimeProperty"), Serializable] public class DateTimeProperty : Property { /// <summary>Gets or sets the features.</summary> /// <value>The features.</value> public DateTimeFeature Features { get; private set; } /// <summary>Default constructor.</summary> public DateTimeProperty() : base() { this.Initialize(DatePortion.Date | DatePortion.DateExtended); } /// <summary>Constructor.</summary> /// <param name="portion">The portion.</param> public DateTimeProperty(DatePortion portion) : base() { this.Initialize(portion); } /// <summary>Constructor.</summary> /// <param name="features">The features.</param> public DateTimeProperty(DateTimeFeature features) : base() { this.Type = typeof(DateTime); this.Features = features; } /// <summary>The length.</summary> private int _length = -1; /// <summary>Length of property.</summary> /// <value>The length.</value> public override int Length { get { if (this._length == -1) { this._length = 0; if (this.Features.HasFlag(DateTimeFeature.Year)) this._length++; if (this.Features.HasFlag(DateTimeFeature.DayOfYear)) this._length++; if (this.Features.HasFlag(DateTimeFeature.Month)) this._length++; if (this.Features.HasFlag(DateTimeFeature.Day)) this._length++; if (this.Features.HasFlag(DateTimeFeature.DayOfWeek)) this._length++; if (this.Features.HasFlag(DateTimeFeature.Hour)) this._length++; if (this.Features.HasFlag(DateTimeFeature.Minute)) this._length++; if (this.Features.HasFlag(DateTimeFeature.Second)) this._length++; if (this.Features.HasFlag(DateTimeFeature.Millisecond)) this._length++; } return this._length; } } /// <summary>Convert the numeric representation back to the original type.</summary> /// <param name="val">.</param> /// <returns>An object.</returns> public override object Convert(double val) { return val; } /// <summary>Initializes this object.</summary> /// <param name="portion">The portion.</param> private void Initialize(DatePortion portion) { this.Type = typeof(DateTime); this.Features = 0; if (portion.HasFlag(DatePortion.Date)) this.Features |= DateTimeFeature.Year | DateTimeFeature.Month | DateTimeFeature.Day; if (portion.HasFlag(DatePortion.DateExtended)) this.Features |= DateTimeFeature.DayOfYear | DateTimeFeature.DayOfWeek; if (portion.HasFlag(DatePortion.Time)) this.Features |= DateTimeFeature.Hour | DateTimeFeature.Minute; if (portion.HasFlag(DatePortion.TimeExtended)) this.Features |= DateTimeFeature.Second | DateTimeFeature.Millisecond; } /// <summary> /// Retrieve the list of expanded columns. If there is a one-to-one correspondence between the /// type and its expansion it will return a single value/. /// </summary> /// <returns> /// An enumerator that allows foreach to be used to process the columns in this collection. /// </returns> public override IEnumerable<string> GetColumns() { if (this.Features.HasFlag(DateTimeFeature.Year)) yield return "Year"; if (this.Features.HasFlag(DateTimeFeature.DayOfYear)) yield return "DayOfYear"; if (this.Features.HasFlag(DateTimeFeature.Month)) yield return "Month"; if (this.Features.HasFlag(DateTimeFeature.Day)) yield return "Day"; if (this.Features.HasFlag(DateTimeFeature.DayOfWeek)) yield return "DayOfWeek"; if (this.Features.HasFlag(DateTimeFeature.Hour)) yield return "Hour"; if (this.Features.HasFlag(DateTimeFeature.Minute)) yield return "Minute"; if (this.Features.HasFlag(DateTimeFeature.Second)) yield return "Second"; if (this.Features.HasFlag(DateTimeFeature.Millisecond)) yield return "Millisecond"; } /// <summary>Convert an object to a list of numbers.</summary> /// <exception cref="InvalidCastException">Thrown when an object cannot be cast to a required /// type.</exception> /// <param name="o">Object.</param> /// <returns>Lazy list of doubles.</returns> public override IEnumerable<double> Convert(object o) { if (o.GetType() == typeof(DateTime)) { // tedious I know... // be thankful I wrote it for you... var d = (DateTime)o; if (this.Features.HasFlag(DateTimeFeature.Year)) yield return d.Year; if (this.Features.HasFlag(DateTimeFeature.DayOfYear)) yield return d.DayOfYear; if (this.Features.HasFlag(DateTimeFeature.Month)) yield return d.Month; if (this.Features.HasFlag(DateTimeFeature.Day)) yield return d.Day; if (this.Features.HasFlag(DateTimeFeature.DayOfWeek)) yield return (int)d.DayOfWeek; if (this.Features.HasFlag(DateTimeFeature.Hour)) yield return d.Hour; if (this.Features.HasFlag(DateTimeFeature.Minute)) yield return d.Minute; if (this.Features.HasFlag(DateTimeFeature.Second)) yield return d.Second; if (this.Features.HasFlag(DateTimeFeature.Millisecond)) yield return d.Millisecond; } else throw new InvalidCastException("Object is not a date"); } /// <summary>Converts an object into its XML representation.</summary> /// <param name="writer">The <see cref="T:System.Xml.XmlWriter" /> stream to which the object is /// serialized.</param> public override void WriteXml(XmlWriter writer) { base.WriteXml(writer); writer.WriteAttributeString("Features", ((int) this.Features).ToString()); } /// <summary>Generates an object from its XML representation.</summary> /// <param name="reader">The <see cref="T:System.Xml.XmlReader" /> stream from which the object is /// deserialized.</param> public override void ReadXml(XmlReader reader) { base.ReadXml(reader); this.Features = (DateTimeFeature)int.Parse(reader.GetAttribute("Features")); } } }
//--------------------------------------------------------------------------- // // <copyright file="DoubleKeyFrameCollection.cs" company="Microsoft"> // Copyright (C) Microsoft Corporation. All rights reserved. // </copyright> // // This file was generated, please do not edit it directly. // // Please see http://wiki/default.aspx/Microsoft.Projects.Avalon/MilCodeGen.html for more information. // //--------------------------------------------------------------------------- using MS.Internal; using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.Windows.Media.Animation; using System.Windows.Media.Media3D; namespace System.Windows.Media.Animation { /// <summary> /// This collection is used in conjunction with a KeyFrameDoubleAnimation /// to animate a Double property value along a set of key frames. /// </summary> public class DoubleKeyFrameCollection : Freezable, IList { #region Data private List<DoubleKeyFrame> _keyFrames; private static DoubleKeyFrameCollection s_emptyCollection; #endregion #region Constructors /// <Summary> /// Creates a new DoubleKeyFrameCollection. /// </Summary> public DoubleKeyFrameCollection() : base() { _keyFrames = new List< DoubleKeyFrame>(2); } #endregion #region Static Methods /// <summary> /// An empty DoubleKeyFrameCollection. /// </summary> public static DoubleKeyFrameCollection Empty { get { if (s_emptyCollection == null) { DoubleKeyFrameCollection emptyCollection = new DoubleKeyFrameCollection(); emptyCollection._keyFrames = new List< DoubleKeyFrame>(0); emptyCollection.Freeze(); s_emptyCollection = emptyCollection; } return s_emptyCollection; } } #endregion #region Freezable /// <summary> /// Creates a freezable copy of this DoubleKeyFrameCollection. /// </summary> /// <returns>The copy</returns> public new DoubleKeyFrameCollection Clone() { return (DoubleKeyFrameCollection)base.Clone(); } /// <summary> /// Implementation of <see cref="System.Windows.Freezable.CreateInstanceCore">Freezable.CreateInstanceCore</see>. /// </summary> /// <returns>The new Freezable.</returns> protected override Freezable CreateInstanceCore() { return new DoubleKeyFrameCollection(); } /// <summary> /// Implementation of <see cref="System.Windows.Freezable.CloneCore(System.Windows.Freezable)">Freezable.CloneCore</see>. /// </summary> protected override void CloneCore(Freezable sourceFreezable) { DoubleKeyFrameCollection sourceCollection = (DoubleKeyFrameCollection) sourceFreezable; base.CloneCore(sourceFreezable); int count = sourceCollection._keyFrames.Count; _keyFrames = new List< DoubleKeyFrame>(count); for (int i = 0; i < count; i++) { DoubleKeyFrame keyFrame = (DoubleKeyFrame)sourceCollection._keyFrames[i].Clone(); _keyFrames.Add(keyFrame); OnFreezablePropertyChanged(null, keyFrame); } } /// <summary> /// Implementation of <see cref="System.Windows.Freezable.CloneCurrentValueCore(System.Windows.Freezable)">Freezable.CloneCurrentValueCore</see>. /// </summary> protected override void CloneCurrentValueCore(Freezable sourceFreezable) { DoubleKeyFrameCollection sourceCollection = (DoubleKeyFrameCollection) sourceFreezable; base.CloneCurrentValueCore(sourceFreezable); int count = sourceCollection._keyFrames.Count; _keyFrames = new List< DoubleKeyFrame>(count); for (int i = 0; i < count; i++) { DoubleKeyFrame keyFrame = (DoubleKeyFrame)sourceCollection._keyFrames[i].CloneCurrentValue(); _keyFrames.Add(keyFrame); OnFreezablePropertyChanged(null, keyFrame); } } /// <summary> /// Implementation of <see cref="System.Windows.Freezable.GetAsFrozenCore(System.Windows.Freezable)">Freezable.GetAsFrozenCore</see>. /// </summary> protected override void GetAsFrozenCore(Freezable sourceFreezable) { DoubleKeyFrameCollection sourceCollection = (DoubleKeyFrameCollection) sourceFreezable; base.GetAsFrozenCore(sourceFreezable); int count = sourceCollection._keyFrames.Count; _keyFrames = new List< DoubleKeyFrame>(count); for (int i = 0; i < count; i++) { DoubleKeyFrame keyFrame = (DoubleKeyFrame)sourceCollection._keyFrames[i].GetAsFrozen(); _keyFrames.Add(keyFrame); OnFreezablePropertyChanged(null, keyFrame); } } /// <summary> /// Implementation of <see cref="System.Windows.Freezable.GetCurrentValueAsFrozenCore(System.Windows.Freezable)">Freezable.GetCurrentValueAsFrozenCore</see>. /// </summary> protected override void GetCurrentValueAsFrozenCore(Freezable sourceFreezable) { DoubleKeyFrameCollection sourceCollection = (DoubleKeyFrameCollection) sourceFreezable; base.GetCurrentValueAsFrozenCore(sourceFreezable); int count = sourceCollection._keyFrames.Count; _keyFrames = new List< DoubleKeyFrame>(count); for (int i = 0; i < count; i++) { DoubleKeyFrame keyFrame = (DoubleKeyFrame)sourceCollection._keyFrames[i].GetCurrentValueAsFrozen(); _keyFrames.Add(keyFrame); OnFreezablePropertyChanged(null, keyFrame); } } /// <summary> /// /// </summary> protected override bool FreezeCore(bool isChecking) { bool canFreeze = base.FreezeCore(isChecking); for (int i = 0; i < _keyFrames.Count && canFreeze; i++) { canFreeze &= Freezable.Freeze(_keyFrames[i], isChecking); } return canFreeze; } #endregion #region IEnumerable /// <summary> /// Returns an enumerator of the DoubleKeyFrames in the collection. /// </summary> public IEnumerator GetEnumerator() { ReadPreamble(); return _keyFrames.GetEnumerator(); } #endregion #region ICollection /// <summary> /// Returns the number of DoubleKeyFrames in the collection. /// </summary> public int Count { get { ReadPreamble(); return _keyFrames.Count; } } /// <summary> /// See <see cref="System.Collections.ICollection.IsSynchronized">ICollection.IsSynchronized</see>. /// </summary> public bool IsSynchronized { get { ReadPreamble(); return (IsFrozen || Dispatcher != null); } } /// <summary> /// See <see cref="System.Collections.ICollection.SyncRoot">ICollection.SyncRoot</see>. /// </summary> public object SyncRoot { get { ReadPreamble(); return ((ICollection)_keyFrames).SyncRoot; } } /// <summary> /// Copies all of the DoubleKeyFrames in the collection to an /// array. /// </summary> void ICollection.CopyTo(Array array, int index) { ReadPreamble(); ((ICollection)_keyFrames).CopyTo(array, index); } /// <summary> /// Copies all of the DoubleKeyFrames in the collection to an /// array of DoubleKeyFrames. /// </summary> public void CopyTo(DoubleKeyFrame[] array, int index) { ReadPreamble(); _keyFrames.CopyTo(array, index); } #endregion #region IList /// <summary> /// Adds a DoubleKeyFrame to the collection. /// </summary> int IList.Add(object keyFrame) { return Add((DoubleKeyFrame)keyFrame); } /// <summary> /// Adds a DoubleKeyFrame to the collection. /// </summary> public int Add(DoubleKeyFrame keyFrame) { if (keyFrame == null) { throw new ArgumentNullException("keyFrame"); } WritePreamble(); OnFreezablePropertyChanged(null, keyFrame); _keyFrames.Add(keyFrame); WritePostscript(); return _keyFrames.Count - 1; } /// <summary> /// Removes all DoubleKeyFrames from the collection. /// </summary> public void Clear() { WritePreamble(); if (_keyFrames.Count > 0) { for (int i = 0; i < _keyFrames.Count; i++) { OnFreezablePropertyChanged(_keyFrames[i], null); } _keyFrames.Clear(); WritePostscript(); } } /// <summary> /// Returns true of the collection contains the given DoubleKeyFrame. /// </summary> bool IList.Contains(object keyFrame) { return Contains((DoubleKeyFrame)keyFrame); } /// <summary> /// Returns true of the collection contains the given DoubleKeyFrame. /// </summary> public bool Contains(DoubleKeyFrame keyFrame) { ReadPreamble(); return _keyFrames.Contains(keyFrame); } /// <summary> /// Returns the index of a given DoubleKeyFrame in the collection. /// </summary> int IList.IndexOf(object keyFrame) { return IndexOf((DoubleKeyFrame)keyFrame); } /// <summary> /// Returns the index of a given DoubleKeyFrame in the collection. /// </summary> public int IndexOf(DoubleKeyFrame keyFrame) { ReadPreamble(); return _keyFrames.IndexOf(keyFrame); } /// <summary> /// Inserts a DoubleKeyFrame into a specific location in the collection. /// </summary> void IList.Insert(int index, object keyFrame) { Insert(index, (DoubleKeyFrame)keyFrame); } /// <summary> /// Inserts a DoubleKeyFrame into a specific location in the collection. /// </summary> public void Insert(int index, DoubleKeyFrame keyFrame) { if (keyFrame == null) { throw new ArgumentNullException("keyFrame"); } WritePreamble(); OnFreezablePropertyChanged(null, keyFrame); _keyFrames.Insert(index, keyFrame); WritePostscript(); } /// <summary> /// Returns true if the collection is frozen. /// </summary> public bool IsFixedSize { get { ReadPreamble(); return IsFrozen; } } /// <summary> /// Returns true if the collection is frozen. /// </summary> public bool IsReadOnly { get { ReadPreamble(); return IsFrozen; } } /// <summary> /// Removes a DoubleKeyFrame from the collection. /// </summary> void IList.Remove(object keyFrame) { Remove((DoubleKeyFrame)keyFrame); } /// <summary> /// Removes a DoubleKeyFrame from the collection. /// </summary> public void Remove(DoubleKeyFrame keyFrame) { WritePreamble(); if (_keyFrames.Contains(keyFrame)) { OnFreezablePropertyChanged(keyFrame, null); _keyFrames.Remove(keyFrame); WritePostscript(); } } /// <summary> /// Removes the DoubleKeyFrame at the specified index from the collection. /// </summary> public void RemoveAt(int index) { WritePreamble(); OnFreezablePropertyChanged(_keyFrames[index], null); _keyFrames.RemoveAt(index); WritePostscript(); } /// <summary> /// Gets or sets the DoubleKeyFrame at a given index. /// </summary> object IList.this[int index] { get { return this[index]; } set { this[index] = (DoubleKeyFrame)value; } } /// <summary> /// Gets or sets the DoubleKeyFrame at a given index. /// </summary> public DoubleKeyFrame this[int index] { get { ReadPreamble(); return _keyFrames[index]; } set { if (value == null) { throw new ArgumentNullException(String.Format(CultureInfo.InvariantCulture, "DoubleKeyFrameCollection[{0}]", index)); } WritePreamble(); if (value != _keyFrames[index]) { OnFreezablePropertyChanged(_keyFrames[index], value); _keyFrames[index] = value; Debug.Assert(_keyFrames[index] != null); WritePostscript(); } } } #endregion } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Diagnostics; using System.IO; using System.Runtime.Remoting; using System.Runtime.Remoting.Channels; using System.Runtime.Remoting.Channels.Ipc; using System.Runtime.Serialization.Formatters; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.ErrorReporting; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Interactive { /// <summary> /// Represents a process that hosts an interactive session. /// </summary> /// <remarks> /// Handles spawning of the host process and communication between the local callers and the remote session. /// </remarks> internal sealed partial class InteractiveHost : MarshalByRefObject { private readonly Type _replType; private readonly string _hostPath; private readonly string _initialWorkingDirectory; // adjustable for testing purposes private readonly int _millisecondsTimeout; private const int MaxAttemptsToCreateProcess = 2; private LazyRemoteService _lazyRemoteService; private int _remoteServiceInstanceId; // Remoting channel to communicate with the remote service. private IpcServerChannel _serverChannel; private TextWriter _output; private TextWriter _errorOutput; internal event Action<InteractiveHostOptions> ProcessStarting; public InteractiveHost( Type replType, string hostPath, string workingDirectory, int millisecondsTimeout = 5000) { _millisecondsTimeout = millisecondsTimeout; _output = TextWriter.Null; _errorOutput = TextWriter.Null; _replType = replType; _hostPath = hostPath; _initialWorkingDirectory = workingDirectory; var serverProvider = new BinaryServerFormatterSinkProvider { TypeFilterLevel = TypeFilterLevel.Full }; _serverChannel = new IpcServerChannel(GenerateUniqueChannelLocalName(), "ReplChannel-" + Guid.NewGuid(), serverProvider); ChannelServices.RegisterChannel(_serverChannel, ensureSecurity: false); } #region Test hooks internal event Action<char[], int> OutputReceived; internal event Action<char[], int> ErrorOutputReceived; internal Process TryGetProcess() { InitializedRemoteService initializedService; return (_lazyRemoteService?.InitializedService != null && _lazyRemoteService.InitializedService.TryGetValue(out initializedService)) ? initializedService.ServiceOpt.Process : null; } internal Service TryGetService() { var initializedService = TryGetOrCreateRemoteServiceAsync().Result; return initializedService.ServiceOpt?.Service; } // Triggered whenever we create a fresh process. // The ProcessExited event is not hooked yet. internal event Action<Process> InteractiveHostProcessCreated; internal IpcServerChannel _ServerChannel { get { return _serverChannel; } } internal void Dispose(bool joinThreads) { Dispose(joinThreads, disposing: true); } #endregion private static string GenerateUniqueChannelLocalName() { return typeof(InteractiveHost).FullName + Guid.NewGuid(); } public override object InitializeLifetimeService() { return null; } private RemoteService TryStartProcess(CancellationToken cancellationToken) { Process newProcess = null; int newProcessId = -1; Semaphore semaphore = null; try { int currentProcessId = Process.GetCurrentProcess().Id; bool semaphoreCreated; string semaphoreName; while (true) { semaphoreName = "InteractiveHostSemaphore-" + Guid.NewGuid(); semaphore = new Semaphore(0, 1, semaphoreName, out semaphoreCreated); if (semaphoreCreated) { break; } semaphore.Close(); cancellationToken.ThrowIfCancellationRequested(); } var remoteServerPort = "InteractiveHostChannel-" + Guid.NewGuid(); var processInfo = new ProcessStartInfo(_hostPath); processInfo.Arguments = remoteServerPort + " " + semaphoreName + " " + currentProcessId; processInfo.WorkingDirectory = _initialWorkingDirectory; processInfo.CreateNoWindow = true; processInfo.UseShellExecute = false; processInfo.RedirectStandardOutput = true; processInfo.RedirectStandardError = true; processInfo.StandardErrorEncoding = Encoding.UTF8; processInfo.StandardOutputEncoding = Encoding.UTF8; newProcess = new Process(); newProcess.StartInfo = processInfo; // enables Process.Exited event to be raised: newProcess.EnableRaisingEvents = true; newProcess.Start(); // test hook: var processCreated = InteractiveHostProcessCreated; if (processCreated != null) { processCreated(newProcess); } cancellationToken.ThrowIfCancellationRequested(); try { newProcessId = newProcess.Id; } catch { newProcessId = 0; } // sync: while (!semaphore.WaitOne(_millisecondsTimeout)) { if (!CheckAlive(newProcess)) { return null; } _output.WriteLine(FeaturesResources.AttemptToConnectToProcess, newProcessId); cancellationToken.ThrowIfCancellationRequested(); } // instantiate remote service: Service newService; try { newService = (Service)Activator.GetObject( typeof(Service), "ipc://" + remoteServerPort + "/" + Service.ServiceName); cancellationToken.ThrowIfCancellationRequested(); newService.Initialize(_replType); } catch (RemotingException) when(!CheckAlive(newProcess)) { return null; } return new RemoteService(this, newProcess, newProcessId, newService); } catch (OperationCanceledException) { if (newProcess != null) { RemoteService.InitiateTermination(newProcess, newProcessId); } return null; } finally { if (semaphore != null) { semaphore.Close(); } } } private bool CheckAlive(Process process) { bool alive = process.IsAlive(); if (!alive) { _errorOutput.WriteLine(FeaturesResources.FailedToLaunchProcess, _hostPath, process.ExitCode); _errorOutput.WriteLine(process.StandardError.ReadToEnd()); } return alive; } ~InteractiveHost() { Dispose(joinThreads: false, disposing: false); } public void Dispose() { Dispose(joinThreads: false, disposing: true); } private void Dispose(bool joinThreads, bool disposing) { if (disposing) { GC.SuppressFinalize(this); DisposeChannel(); } if (_lazyRemoteService != null) { _lazyRemoteService.Dispose(joinThreads); _lazyRemoteService = null; } } private void DisposeChannel() { if (_serverChannel != null) { ChannelServices.UnregisterChannel(_serverChannel); _serverChannel = null; } } public TextWriter Output { get { return _output; } set { if (value == null) { throw new ArgumentNullException("value"); } var oldOutput = Interlocked.Exchange(ref _output, value); oldOutput.Flush(); } } public TextWriter ErrorOutput { get { return _errorOutput; } set { if (value == null) { throw new ArgumentNullException("value"); } var oldOutput = Interlocked.Exchange(ref _errorOutput, value); oldOutput.Flush(); } } internal void OnOutputReceived(bool error, char[] buffer, int count) { var notification = error ? ErrorOutputReceived : OutputReceived; if (notification != null) { notification(buffer, count); } var writer = error ? ErrorOutput : Output; writer.Write(buffer, 0, count); } private LazyRemoteService CreateRemoteService(InteractiveHostOptions options, bool skipInitialization) { return new LazyRemoteService(this, options, Interlocked.Increment(ref _remoteServiceInstanceId), skipInitialization); } private Task OnProcessExited(Process process) { ReportProcessExited(process); return TryGetOrCreateRemoteServiceAsync(); } private void ReportProcessExited(Process process) { int? exitCode; try { exitCode = process.HasExited ? process.ExitCode : (int?)null; } catch { exitCode = null; } if (exitCode.HasValue) { _errorOutput.WriteLine(FeaturesResources.HostingProcessExitedWithExitCode, exitCode.Value); } } private async Task<InitializedRemoteService> TryGetOrCreateRemoteServiceAsync() { try { LazyRemoteService currentRemoteService = _lazyRemoteService; // disposed or not reset: Debug.Assert(currentRemoteService != null); for (int attempt = 0; attempt < MaxAttemptsToCreateProcess; attempt++) { var initializedService = await currentRemoteService.InitializedService.GetValueAsync(currentRemoteService.CancellationSource.Token).ConfigureAwait(false); if (initializedService.ServiceOpt != null && initializedService.ServiceOpt.Process.IsAlive()) { return initializedService; } // Service failed to start or initialize or the process died. var newService = CreateRemoteService(currentRemoteService.Options, skipInitialization: !initializedService.InitializationResult.Success); var previousService = Interlocked.CompareExchange(ref _lazyRemoteService, newService, currentRemoteService); if (previousService == currentRemoteService) { // we replaced the service whose process we know is dead: currentRemoteService.Dispose(joinThreads: false); currentRemoteService = newService; } else { // the process was reset in between our checks, try to use the new service: newService.Dispose(joinThreads: false); currentRemoteService = previousService; } } _errorOutput.WriteLine(FeaturesResources.UnableToCreateHostingProcess); } catch (OperationCanceledException) { // The user reset the process during initialization. // The reset operation will recreate the process. } catch (Exception e) when(FatalError.Report(e)) { throw ExceptionUtilities.Unreachable; } return default(InitializedRemoteService); } private async Task<TResult> Async<TResult>(Action<Service, RemoteAsyncOperation<TResult>> action) { try { var initializedService = await TryGetOrCreateRemoteServiceAsync().ConfigureAwait(false); if (initializedService.ServiceOpt == null) { return default(TResult); } return await new RemoteAsyncOperation<TResult>(initializedService.ServiceOpt).AsyncExecute(action).ConfigureAwait(false); } catch (Exception e) when(FatalError.Report(e)) { throw ExceptionUtilities.Unreachable; } } private static async Task<TResult> Async<TResult>(RemoteService remoteService, Action<Service, RemoteAsyncOperation<TResult>> action) { try { return await new RemoteAsyncOperation<TResult>(remoteService).AsyncExecute(action).ConfigureAwait(false); } catch (Exception e) when(FatalError.Report(e)) { throw ExceptionUtilities.Unreachable; } } #region Operations /// <summary> /// Restarts and reinitializes the host process (or starts a new one if it is not running yet). /// </summary> /// <param name="optionsOpt">The options to initialize the new process with, or null to use the current options (or default options if the process isn't running yet).</param> public async Task<RemoteExecutionResult> ResetAsync(InteractiveHostOptions optionsOpt) { try { // replace the existing service with a new one: var newService = CreateRemoteService(optionsOpt ?? _lazyRemoteService?.Options ?? InteractiveHostOptions.Default, skipInitialization: false); LazyRemoteService oldService = Interlocked.Exchange(ref _lazyRemoteService, newService); if (oldService != null) { oldService.Dispose(joinThreads: false); } var initializedService = await TryGetOrCreateRemoteServiceAsync().ConfigureAwait(false); if (initializedService.ServiceOpt == null) { return default(RemoteExecutionResult); } return initializedService.InitializationResult; } catch (Exception e) when(FatalError.Report(e)) { throw ExceptionUtilities.Unreachable; } } /// <summary> /// Asynchronously executes given code in the remote interactive session. /// </summary> /// <param name="code">The code to execute.</param> /// <remarks> /// This method is thread safe. References can be added and source code executed in parallel. /// The operations are serialized to UI thread in the remote process in first come first served order. /// </remarks> public Task<RemoteExecutionResult> ExecuteAsync(string code) { Debug.Assert(code != null); return Async<RemoteExecutionResult>((service, operation) => service.ExecuteAsync(operation, code)); } /// <summary> /// Asynchronously executes given code in the remote interactive session. /// </summary> /// <param name="path">The file to execute.</param> /// <exception cref="ArgumentNullException"><paramref name="path"/> is null.</exception> /// <remarks> /// This method is thread safe. All session operations are serialized to UI thread in the remote process in first come first served order. /// </remarks> public Task<RemoteExecutionResult> ExecuteFileAsync(string path) { if (path == null) { throw new ArgumentNullException("path"); } return Async<RemoteExecutionResult>((service, operation) => service.ExecuteFileAsync(operation, path)); } /// <summary> /// Asynchronously adds a reference to the set of available references for next submission. /// </summary> /// <param name="reference">The reference to add.</param> /// <remarks> /// This method is thread safe. All session operations are serialized to UI thread in the remote process in first come first served order. /// </remarks> public Task<bool> AddReferenceAsync(string reference) { Debug.Assert(reference != null); return Async<bool>((service, operation) => service.AddReferenceAsync(operation, reference)); } /// <summary> /// Sets the current session's search paths and base directory. /// </summary> public Task SetPathsAsync(string[] referenceSearchPaths, string[] sourceSearchPaths, string baseDirectory) { Debug.Assert(referenceSearchPaths != null); Debug.Assert(sourceSearchPaths != null); Debug.Assert(baseDirectory != null); return Async<object>((service, operation) => service.SetPathsAsync(operation, referenceSearchPaths, sourceSearchPaths, baseDirectory)); } #endregion } }
// -------------------------------------------------------------------------------------------- // <copyright from='2011' to='2011' company='SIL International'> // Copyright (c) 2011, SIL International. All Rights Reserved. // // Distributable under the terms of either the Common Public License or the // GNU Lesser General Public License, as specified in the LICENSING.txt file. // </copyright> // -------------------------------------------------------------------------------------------- #if __MonoCS__ using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Runtime.InteropServices; using NUnit.Framework; using Palaso.UI.WindowsForms.Keyboarding; using Palaso.UI.WindowsForms.Keyboarding.Linux; using Palaso.UI.WindowsForms.Keyboarding.Types; using Palaso.WritingSystems; using X11.XKlavier; namespace PalasoUIWindowsForms.Tests.Keyboarding { [TestFixture] [Platform(Include="Linux", Reason="Linux specific tests")] [SetUICulture("en-US")] public class XkbKeyboardAdapterTests { /// <summary> /// Fakes the installed keyboards /// </summary> private class XklEngineResponder: XklEngine { public static string[] SetGroupNames { set; private get; } public override string[] GroupNames { get { return SetGroupNames; } } } #region Helper class/method to set the LANGUAGE environment variable /// <summary>Helper class/method to set the LANGUAGE environment variable. This is /// necessary to get localized texts</summary> /// <remarks>A different, probably cleaner approach, would be to derive a class from /// NUnit's ActionAttribute. However, this currently doesn't work when running the tests /// in MonoDevelop (at least up to version 4.3).</remarks> class LanguageHelper: IDisposable { private string OldLanguage { get; set; } public LanguageHelper(string language) { // To get XklConfigRegistry to return values in the expected language we have to // set the LANGUAGE environment variable. OldLanguage = Environment.GetEnvironmentVariable("LANGUAGE"); Environment.SetEnvironmentVariable("LANGUAGE", string.Format("{0}:{1}", language.Replace('-', '_'), OldLanguage)); } #region Disposable stuff #if DEBUG /// <summary/> ~LanguageHelper() { Dispose(false); } #endif /// <summary/> public bool IsDisposed { get; private set; } /// <summary/> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// <summary/> protected virtual void Dispose(bool fDisposing) { System.Diagnostics.Debug.WriteLineIf(!fDisposing, "****** Missing Dispose() call for " + GetType() + ". *******"); if (fDisposing && !IsDisposed) { // dispose managed and unmanaged objects Environment.SetEnvironmentVariable("LANGUAGE", OldLanguage); } IsDisposed = true; } #endregion /// <summary> /// Checks the list of installed languages and ignores the test if the desired language /// is not installed. /// </summary> /// <param name="desiredLanguage">Desired language.</param> public static void CheckInstalledLanguages(string desiredLanguage) { var language = desiredLanguage.Replace('-', '_'); if (Environment.GetEnvironmentVariable("LANGUAGE").Contains(language)) return; using (var process = new Process()) { process.StartInfo.FileName = "locale"; process.StartInfo.Arguments = "-a"; process.StartInfo.UseShellExecute = false; process.StartInfo.CreateNoWindow = true; process.StartInfo.RedirectStandardOutput = true; process.Start(); process.WaitForExit(); for (var line = process.StandardOutput.ReadLine(); line != null; line = process.StandardOutput.ReadLine()) { if (line.StartsWith(language, StringComparison.InvariantCultureIgnoreCase)) return; } Assert.Ignore("Can't run test because language pack for {0} is not installed.", desiredLanguage); } } } private LanguageHelper SetLanguage(string language) { LanguageHelper.CheckInstalledLanguages(language); return new LanguageHelper(language); } #endregion [DllImportAttribute("libgtk-x11-2.0")] [return: MarshalAs(UnmanagedType.I4)] private static extern bool gtk_init_check(ref int argc, ref IntPtr argv) ; private string KeyboardUSA { get { return KeyboardNames[0]; } } private string KeyboardGermany { get { return KeyboardNames[1]; } } private string KeyboardFranceEliminateDeadKeys { get { return KeyboardNames[2]; } } private string KeyboardUK { get { return KeyboardNames[3]; } } private string KeyboardBelgium { get { return KeyboardNames[4]; } } private string KeyboardFinlandNorthernSaami { get { return KeyboardNames[5]; } } private string[] KeyboardNames; private string[] OldKeyboardNames = new string[] { "USA", "Germany", "France - Eliminate dead keys", "United Kingdom", "Belgium", "Finland - Northern Saami" }; private string[] NewKeyboardNames = new string[] { "English (US)", "German", "French (eliminate dead keys)", "English (UK)", "Belgian", "Northern Saami (Finland)" }; private string ExpectedKeyboardUSA { get { return ExpectedKeyboardNames[0]; } } private string ExpectedKeyboardGermany { get { return ExpectedKeyboardNames[1]; } } private string ExpectedKeyboardFranceEliminateDeadKeys { get { return ExpectedKeyboardNames[2]; } } private string ExpectedKeyboardUK { get { return ExpectedKeyboardNames[3]; } } //private string ExpectedKeyboardBelgium { get { return ExpectedKeyboardNames[4]; } } private string ExpectedKeyboardFinlandNorthernSaami { get { return ExpectedKeyboardNames[5]; } } private string[] ExpectedKeyboardNames; private string[] OldExpectedKeyboardNames = new string[] { "English (US) - English (United States)", "German - German (Germany)", "Eliminate dead keys - French (France)", "English (UK) - English (United Kingdom)", "", "Northern Saami - Northern Sami (Finland)" }; private string[] NewExpectedKeyboardNames = new string[] { "English (US) - English (United States)", "German - German (Germany)", "French (eliminate dead keys) - French (France)", "English (UK) - English (United Kingdom)", "", "Northern Saami (Finland) - Northern Sami (Finland)" }; private static bool IsNewEvdevNames { get { // Debian/Ubuntu version 2.2.1 of xkeyboard-config changed the way keyboard names // are stored in evdev.xml: previously the country name was used ("Belgium"), now // they use the adjective ("Belgian"). We detect this by greping evdev.xml and then // use the appropriate names using (var process = new Process()) { process.StartInfo.FileName = "/bin/grep"; process.StartInfo.Arguments = "Belgian /usr/share/X11/xkb/rules/evdev.xml"; process.Start(); process.WaitForExit(); return process.ExitCode == 0; } } } [TestFixtureSetUp] public void FixtureSetup() { // We're using GTK functions, so we need to intialize when we run in // nunit-console. I'm doing it through p/invoke rather than gtk-sharp (Application.Init()) // so that we don't need to reference gtk-sharp (which might cause // problems on Windows) int argc = 0; IntPtr argv = IntPtr.Zero; Assert.IsTrue(gtk_init_check(ref argc, ref argv)); if (IsNewEvdevNames) { KeyboardNames = NewKeyboardNames; ExpectedKeyboardNames = NewExpectedKeyboardNames; } else { KeyboardNames = OldKeyboardNames; ExpectedKeyboardNames = OldExpectedKeyboardNames; } KeyboardController.Initialize(); } [TestFixtureTearDown] public void FixtureTearDown() { KeyboardController.Shutdown(); } /// <summary> /// Tests converting the keyboard layouts that XKB reports to LCIDs with the help of ICU /// and list of available layouts. /// </summary> [Test] public void InstalledKeyboards_USA() { XklEngineResponder.SetGroupNames = new string[] { KeyboardUSA }; KeyboardController.Manager.SetKeyboardAdaptors(new [] { new XkbKeyboardAdaptor(new XklEngineResponder()) }); var keyboards = Keyboard.Controller.AllAvailableKeyboards; Assert.AreEqual(1, keyboards.Count()); Assert.AreEqual("en-US_us", keyboards.First().Id); Assert.AreEqual(ExpectedKeyboardUSA, keyboards.First().Name); } [Test] public void InstalledKeyboards_Germany() { XklEngineResponder.SetGroupNames = new string[] { KeyboardGermany }; KeyboardController.Manager.SetKeyboardAdaptors(new [] { new XkbKeyboardAdaptor(new XklEngineResponder()) }); var keyboards = Keyboard.Controller.AllAvailableKeyboards; Assert.AreEqual(1, keyboards.Count()); Assert.AreEqual("de-DE_de", keyboards.First().Id); Assert.AreEqual(ExpectedKeyboardGermany, keyboards.First().Name); } [Test] public void InstalledKeyboards_FrenchWithVariant() { XklEngineResponder.SetGroupNames = new string[] { KeyboardFranceEliminateDeadKeys }; KeyboardController.Manager.SetKeyboardAdaptors(new [] { new XkbKeyboardAdaptor(new XklEngineResponder()) }); var keyboards = Keyboard.Controller.AllAvailableKeyboards; Assert.AreEqual(1, keyboards.Count()); Assert.AreEqual(ExpectedKeyboardFranceEliminateDeadKeys, keyboards.First().Name); } [Test] public void InstalledKeyboards_GB() { XklEngineResponder.SetGroupNames = new string[] { KeyboardUK }; KeyboardController.Manager.SetKeyboardAdaptors(new [] { new XkbKeyboardAdaptor(new XklEngineResponder()) }); var keyboards = Keyboard.Controller.AllAvailableKeyboards; Assert.AreEqual(1, keyboards.Count()); Assert.AreEqual("en-GB_gb", keyboards.First().Id); Assert.AreEqual(ExpectedKeyboardUK, keyboards.First().Name); } private IKeyboardDefinition CreateKeyboard(string layoutName, string layout, string locale) { CultureInfo culture = null; try { culture = new CultureInfo(locale); } catch (ArgumentException) { // this can happen if locale is not supported. } return new KeyboardDescription(layoutName, layout, locale, new InputLanguageWrapper(culture, IntPtr.Zero, layoutName), null); } [Test] public void InstalledKeyboards_Belgium() { XklEngineResponder.SetGroupNames = new string[] { KeyboardBelgium }; KeyboardController.Manager.SetKeyboardAdaptors(new [] { new XkbKeyboardAdaptor(new XklEngineResponder()) }); var keyboards = Keyboard.Controller.AllAvailableKeyboards.OrderBy(kbd => kbd.Id).ToArray(); // It seems that Dutch (Belgium) got added recently, so some machines are missing // this. Assert.That(keyboards.Length == 3 || keyboards.Length == 2); var expectedKeyboards = new List<IKeyboardDefinition>() { CreateKeyboard("German", "be", "de-BE") }; expectedKeyboards.Add(CreateKeyboard("French", "be", "fr-BE")); if (keyboards.Length > 2) expectedKeyboards.Add(CreateKeyboard("Dutch", "be", "nl-BE")); Assert.That(keyboards, Is.EquivalentTo(expectedKeyboards)); } [Test] public void InstalledKeyboards_Multiple() { XklEngineResponder.SetGroupNames = new string[] { KeyboardUSA, KeyboardGermany }; KeyboardController.Manager.SetKeyboardAdaptors(new [] { new XkbKeyboardAdaptor(new XklEngineResponder()) }); var keyboards = Keyboard.Controller.AllAvailableKeyboards.ToArray(); Assert.AreEqual(2, keyboards.Length); Assert.AreEqual("en-US_us", keyboards[0].Id); Assert.AreEqual(ExpectedKeyboardUSA, keyboards[0].Name); Assert.AreEqual("de-DE_de", keyboards[1].Id); Assert.AreEqual(ExpectedKeyboardGermany, keyboards[1].Name); } /// <summary> /// Tests the values returned by InstalledKeyboards if the UICulture is set to German /// </summary> [Test] [SetUICulture("de-DE")] public void InstalledKeyboards_Germany_GermanCulture() { XklEngineResponder.SetGroupNames = new string[] { KeyboardGermany }; KeyboardController.Manager.SetKeyboardAdaptors(new [] { new XkbKeyboardAdaptor(new XklEngineResponder()) }); var keyboards = Keyboard.Controller.AllAvailableKeyboards; Assert.AreEqual(1, keyboards.Count()); Assert.AreEqual("de-DE_de", keyboards.First().Id); Assert.AreEqual("German - Deutsch (Deutschland)", keyboards.First().Name); } /// <summary> /// Tests the values returned by InstalledKeyboards if the UICulture is set to German /// and we're getting localized keyboard layouts /// </summary> [Test] [SetUICulture("de-DE")] public void InstalledKeyboards_Germany_AllGerman() // FWNX-1388 { XklEngineResponder.SetGroupNames = new string[] { KeyboardGermany }; using (SetLanguage("de-DE")) { KeyboardController.Manager.SetKeyboardAdaptors(new [] { new XkbKeyboardAdaptor(new XklEngineResponder()) }); var keyboards = Keyboard.Controller.AllAvailableKeyboards; Assert.AreEqual(1, keyboards.Count()); Assert.AreEqual("de-DE_de", keyboards.First().Id); Assert.AreEqual("Deutsch - Deutsch (Deutschland)", keyboards.First().Name); } } /// <summary> /// Tests InstalledKeyboards property. "Finland - Northern Saami" gives us two /// layouts (smi_FIN and sme_FIN), but ICU returns a LCID only for one of them. /// </summary> [Test] public void InstalledKeyboards_NorthernSami() { XklEngineResponder.SetGroupNames = new string[] { KeyboardFinlandNorthernSaami }; KeyboardController.Manager.SetKeyboardAdaptors(new [] { new XkbKeyboardAdaptor(new XklEngineResponder()) }); var keyboards = Keyboard.Controller.AllAvailableKeyboards; Assert.AreEqual(1, keyboards.Count()); Assert.AreEqual(ExpectedKeyboardFinlandNorthernSaami, keyboards.First().Name); } [Test] public void ErrorKeyboards() { XklEngineResponder.SetGroupNames = new string[] { "Fake" }; KeyboardController.Manager.SetKeyboardAdaptors(new [] { new XkbKeyboardAdaptor(new XklEngineResponder()) }); var keyboards = Keyboard.Controller.AllAvailableKeyboards; Assert.AreEqual(0, keyboards.Count()); //Assert.AreEqual(1, KeyboardController.ErrorKeyboards.Count); //Assert.AreEqual("Fake", KeyboardController.Errorkeyboards.First().Details); } /// <summary/> [Test] public void ActivateKeyboard_FirstTime_NotCrash() { XklEngineResponder.SetGroupNames = new string[] { KeyboardUSA }; var adaptor = new XkbKeyboardAdaptor(new XklEngineResponder()); KeyboardController.Manager.SetKeyboardAdaptors(new [] { adaptor }); var keyboards = Keyboard.Controller.AllAvailableKeyboards; adaptor.ActivateKeyboard(keyboards.First()); } /// <summary> /// FWNX-895 /// </summary> [Test] public void ActivateKeyboard_SecondTime_NotCrash() { XklEngineResponder.SetGroupNames = new string[] { KeyboardUSA }; var adaptor = new XkbKeyboardAdaptor(new XklEngineResponder()); KeyboardController.Manager.SetKeyboardAdaptors(new [] { adaptor }); var keyboards = Keyboard.Controller.AllAvailableKeyboards; adaptor.ActivateKeyboard(keyboards.First()); adaptor = new XkbKeyboardAdaptor(new XklEngineResponder()); KeyboardController.Manager.SetKeyboardAdaptors(new [] { adaptor }); keyboards = Keyboard.Controller.AllAvailableKeyboards; adaptor.ActivateKeyboard(keyboards.First()); } } } #endif
// Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information. using Microsoft.VisualStudio.OLE.Interop; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.Designer.Interfaces; using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Globalization; using System.IO; using System.Runtime.InteropServices; using System.Windows.Forms; using System.Xml; using System.Diagnostics; using System.Collections.ObjectModel; // NOTE: // When converting, System.TypeConverter.Convert* passes us CultureInfo.CurrentCulture - this is wrong! // We really want CultureInfo.CurrentUICulture. So we will adjust. namespace Microsoft.VisualStudio.FSharp.ProjectSystem { internal class OutputTypeConverter : EnumConverter { public OutputTypeConverter() : base(typeof(OutputType)) { } public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) { if (sourceType == typeof(string)) return true; return base.CanConvertFrom(context, sourceType); } public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo c, object value) { string str = value as string; CultureInfo culture = CultureInfo.CurrentUICulture; if (str != null) { if (str == SR.GetString(SR.Exe, culture)) return OutputType.Exe; if (str == SR.GetString(SR.Library, culture)) return OutputType.Library; if (str == SR.GetString(SR.WinExe, culture)) return OutputType.WinExe; } return base.ConvertFrom(context, culture, value); } public override object ConvertTo(ITypeDescriptorContext context, CultureInfo c, object value, Type destinationType) { CultureInfo culture = CultureInfo.CurrentUICulture; if (destinationType == typeof(string)) { string result = null; // In some cases if multiple nodes are selected the windows form engine // calls us with a null value if the selected node's property values are not equal if (value != null) { result = SR.GetString(((OutputType)value).ToString(), culture); } else { result = SR.GetString(OutputType.Library.ToString(), culture); } if (result != null) return result; } return base.ConvertTo(context, culture, value, destinationType); } public override bool GetStandardValuesSupported(System.ComponentModel.ITypeDescriptorContext context) { return true; } public override System.ComponentModel.TypeConverter.StandardValuesCollection GetStandardValues(System.ComponentModel.ITypeDescriptorContext context) { return new StandardValuesCollection(new OutputType[] { OutputType.Exe, OutputType.Library, OutputType.WinExe }); } } internal class DebugModeConverter : EnumConverter { public DebugModeConverter() : base(typeof(DebugMode)) { } public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) { if (sourceType == typeof(string)) return true; return base.CanConvertFrom(context, sourceType); } public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo c, object value) { string str = value as string; CultureInfo culture = CultureInfo.CurrentUICulture; if (str != null) { if (str == SR.GetString(SR.Program, culture)) return DebugMode.Program; if (str == SR.GetString(SR.Project, culture)) return DebugMode.Project; if (str == SR.GetString(SR.URL, culture)) return DebugMode.URL; } return base.ConvertFrom(context, culture, value); } public override object ConvertTo(ITypeDescriptorContext context, CultureInfo c, object value, Type destinationType) { CultureInfo culture = CultureInfo.CurrentUICulture; if (destinationType == typeof(string)) { string result = null; // In some cases if multiple nodes are selected the windows form engine // calls us with a null value if the selected node's property values are not equal if (value != null) { result = SR.GetString(((DebugMode)value).ToString(), culture); } else { result = SR.GetString(DebugMode.Program.ToString(), culture); } if (result != null) return result; } return base.ConvertTo(context, culture, value, destinationType); } public override bool GetStandardValuesSupported(System.ComponentModel.ITypeDescriptorContext context) { return true; } public override System.ComponentModel.TypeConverter.StandardValuesCollection GetStandardValues(System.ComponentModel.ITypeDescriptorContext context) { return new StandardValuesCollection(new DebugMode[] { DebugMode.Program, DebugMode.Project, DebugMode.URL }); } } internal class BuildActionConverter : TypeConverter { List<BuildAction> buildActions = new List<BuildAction>(); public ReadOnlyCollection<BuildAction> RegisteredBuildActions { get { return buildActions.AsReadOnly(); } } public BuildActionConverter() { ResetBuildActionsToDefaults(); } public void ResetBuildActionsToDefaults() { this.buildActions.Clear(); this.buildActions.Add(BuildAction.None); this.buildActions.Add(BuildAction.Compile); this.buildActions.Add(BuildAction.Content); this.buildActions.Add(BuildAction.EmbeddedResource); } public void RegisterBuildAction(BuildAction buildAction) { if (!this.buildActions.Contains(buildAction)) { this.buildActions.Add(buildAction); } } public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) { if (sourceType == typeof(string)) return true; return false; } public override bool CanConvertTo(ITypeDescriptorContext context, Type sourceType) { return sourceType == typeof(string); } public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo c, object value) { string s = value as string; if (s != null) return new BuildAction(s); return null; } public override object ConvertTo(ITypeDescriptorContext context, CultureInfo c, object value, Type destinationType) { if (destinationType == typeof(string)) { return ((BuildAction)value).Name; } return null; } public override bool GetStandardValuesSupported(System.ComponentModel.ITypeDescriptorContext context) { return true; } public override System.ComponentModel.TypeConverter.StandardValuesCollection GetStandardValues(System.ComponentModel.ITypeDescriptorContext context) { return new StandardValuesCollection(buildActions); } } internal class CopyToOutputDirectoryConverter : EnumConverter { public CopyToOutputDirectoryConverter() : base(typeof(CopyToOutputDirectory)) { } public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) { if (sourceType == typeof(string)) return true; return base.CanConvertFrom(context, sourceType); } public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo c, object value) { CultureInfo culture = CultureInfo.CurrentUICulture; string str = value as string; if (str != null) { if (str == SR.GetString(SR.CopyAlways, culture)) return CopyToOutputDirectory.Always; if (str == SR.GetString(SR.CopyIfNewer, culture)) return CopyToOutputDirectory.PreserveNewest; if (str == SR.GetString(SR.DoNotCopy, culture)) return CopyToOutputDirectory.DoNotCopy; } return base.ConvertFrom(context, culture, value); } public override object ConvertTo(ITypeDescriptorContext context, CultureInfo c, object value, Type destinationType) { CultureInfo culture = CultureInfo.CurrentUICulture; if (destinationType == typeof(string)) { string result = null; // In some cases if multiple nodes are selected the windows form engine // calls us with a null value if the selected node's property values are not equal if (value != null) { if (((CopyToOutputDirectory)value) == CopyToOutputDirectory.DoNotCopy) result = SR.GetString(SR.DoNotCopy, culture); if (((CopyToOutputDirectory)value) == CopyToOutputDirectory.Always) result = SR.GetString(SR.CopyAlways, culture); if (((CopyToOutputDirectory)value) == CopyToOutputDirectory.PreserveNewest) result = SR.GetString(SR.CopyIfNewer, culture); } else { result = ""; } if (result != null) return result; } return base.ConvertTo(context, culture, value, destinationType); } public override bool GetStandardValuesSupported(System.ComponentModel.ITypeDescriptorContext context) { return true; } public override System.ComponentModel.TypeConverter.StandardValuesCollection GetStandardValues(System.ComponentModel.ITypeDescriptorContext context) { return new StandardValuesCollection(new CopyToOutputDirectory[] { CopyToOutputDirectory.Always, CopyToOutputDirectory.DoNotCopy, CopyToOutputDirectory.PreserveNewest }); } } internal class PlatformTypeConverter : EnumConverter { public PlatformTypeConverter() : base(typeof(PlatformType)) { } public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) { if (sourceType == typeof(string)) return true; return base.CanConvertFrom(context, sourceType); } public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo c, object value) { CultureInfo culture = CultureInfo.CurrentUICulture; string str = value as string; if (str != null) { if (str == SR.GetString(SR.v1, culture)) return PlatformType.v1; if (str == SR.GetString(SR.v11, culture)) return PlatformType.v11; if (str == SR.GetString(SR.v2, culture)) return PlatformType.v2; if (str == SR.GetString(SR.cli1, culture)) return PlatformType.cli1; } return base.ConvertFrom(context, culture, value); } public override object ConvertTo(ITypeDescriptorContext context, CultureInfo c, object value, Type destinationType) { CultureInfo culture = CultureInfo.CurrentUICulture; if (destinationType == typeof(string)) { string result = null; // In some cases if multiple nodes are selected the windows form engine // calls us with a null value if the selected node's property values are not equal if (value != null) { result = SR.GetString(((PlatformType)value).ToString(), culture); } else { result = SR.GetString(PlatformType.notSpecified.ToString(), culture); } if (result != null) return result; } return base.ConvertTo(context, culture, value, destinationType); } public override bool GetStandardValuesSupported(System.ComponentModel.ITypeDescriptorContext context) { return true; } public override System.ComponentModel.TypeConverter.StandardValuesCollection GetStandardValues(System.ComponentModel.ITypeDescriptorContext context) { return new StandardValuesCollection(new PlatformType[] { PlatformType.v1, PlatformType.v11, PlatformType.v2, PlatformType.cli1 }); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Sockets; using System.Reflection; using System.Text; using System.Threading; using System.Threading.Tasks; using GodotTools.IdeMessaging.Requests; using GodotTools.IdeMessaging.Utils; namespace GodotTools.IdeMessaging { public sealed class Peer : IDisposable { /// <summary> /// Major version. /// There is no forward nor backward compatibility between different major versions. /// Connection is refused if client and server have different major versions. /// </summary> public static readonly int ProtocolVersionMajor = Assembly.GetAssembly(typeof(Peer)).GetName().Version.Major; /// <summary> /// Minor version, which clients must be backward compatible with. /// Connection is refused if the client's minor version is lower than the server's. /// </summary> public static readonly int ProtocolVersionMinor = Assembly.GetAssembly(typeof(Peer)).GetName().Version.Minor; /// <summary> /// Revision, which doesn't affect compatibility. /// </summary> public static readonly int ProtocolVersionRevision = Assembly.GetAssembly(typeof(Peer)).GetName().Version.Revision; public const string ClientHandshakeName = "GodotIdeClient"; public const string ServerHandshakeName = "GodotIdeServer"; private const int ClientWriteTimeout = 8000; public delegate Task<Response> RequestHandler(Peer peer, MessageContent content); private readonly TcpClient tcpClient; private readonly TextReader clientReader; private readonly TextWriter clientWriter; private readonly SemaphoreSlim writeSem = new SemaphoreSlim(1); private string remoteIdentity = string.Empty; public string RemoteIdentity => remoteIdentity; public event Action Connected; public event Action Disconnected; private ILogger Logger { get; } public bool IsDisposed { get; private set; } public bool IsTcpClientConnected => tcpClient.Client != null && tcpClient.Client.Connected; private bool IsConnected { get; set; } private readonly IHandshake handshake; private readonly IMessageHandler messageHandler; private readonly Dictionary<string, Queue<ResponseAwaiter>> requestAwaiterQueues = new Dictionary<string, Queue<ResponseAwaiter>>(); private readonly SemaphoreSlim requestsSem = new SemaphoreSlim(1); public Peer(TcpClient tcpClient, IHandshake handshake, IMessageHandler messageHandler, ILogger logger) { this.tcpClient = tcpClient; this.handshake = handshake; this.messageHandler = messageHandler; Logger = logger; NetworkStream clientStream = tcpClient.GetStream(); clientStream.WriteTimeout = ClientWriteTimeout; clientReader = new StreamReader(clientStream, Encoding.UTF8); clientWriter = new StreamWriter(clientStream, Encoding.UTF8) {NewLine = "\n"}; } public async Task Process() { try { var decoder = new MessageDecoder(); string messageLine; while ((messageLine = await ReadLine()) != null) { var state = decoder.Decode(messageLine, out var msg); if (state == MessageDecoder.State.Decoding) continue; // Not finished decoding yet if (state == MessageDecoder.State.Errored) { Logger.LogError($"Received message line with invalid format: {messageLine}"); continue; } Logger.LogDebug($"Received message: {msg}"); try { if (msg.Kind == MessageKind.Request) { var responseContent = await messageHandler.HandleRequest(this, msg.Id, msg.Content, Logger); await WriteMessage(new Message(MessageKind.Response, msg.Id, responseContent)); } else if (msg.Kind == MessageKind.Response) { ResponseAwaiter responseAwaiter; using (await requestsSem.UseAsync()) { if (!requestAwaiterQueues.TryGetValue(msg.Id, out var queue) || queue.Count <= 0) { Logger.LogError($"Received unexpected response: {msg.Id}"); return; } responseAwaiter = queue.Dequeue(); } responseAwaiter.SetResult(msg.Content); } else { throw new IndexOutOfRangeException($"Invalid message kind {msg.Kind}"); } } catch (Exception e) { Logger.LogError($"Message handler for '{msg}' failed with exception", e); } } } catch (Exception e) { if (!IsDisposed || !(e is SocketException || e.InnerException is SocketException)) { Logger.LogError("Unhandled exception in the peer loop", e); } } } public async Task<bool> DoHandshake(string identity) { if (!await WriteLine(handshake.GetHandshakeLine(identity))) { Logger.LogError("Could not write handshake"); return false; } var readHandshakeTask = ReadLine(); if (await Task.WhenAny(readHandshakeTask, Task.Delay(8000)) != readHandshakeTask) { Logger.LogError("Timeout waiting for the client handshake"); return false; } string peerHandshake = await readHandshakeTask; if (handshake == null || !handshake.IsValidPeerHandshake(peerHandshake, out remoteIdentity, Logger)) { Logger.LogError("Received invalid handshake: " + peerHandshake); return false; } IsConnected = true; Connected?.Invoke(); Logger.LogInfo("Peer connection started"); return true; } private async Task<string> ReadLine() { try { return await clientReader.ReadLineAsync(); } catch (Exception e) { if (IsDisposed) { var se = e as SocketException ?? e.InnerException as SocketException; if (se != null && se.SocketErrorCode == SocketError.Interrupted) return null; } throw; } } private Task<bool> WriteMessage(Message message) { Logger.LogDebug($"Sending message: {message}"); int bodyLineCount = message.Content.Body.Count(c => c == '\n'); bodyLineCount += 1; // Extra line break at the end var builder = new StringBuilder(); builder.AppendLine(message.Kind.ToString()); builder.AppendLine(message.Id); builder.AppendLine(message.Content.Status.ToString()); builder.AppendLine(bodyLineCount.ToString()); builder.AppendLine(message.Content.Body); return WriteLine(builder.ToString()); } public async Task<TResponse> SendRequest<TResponse>(string id, string body) where TResponse : Response, new() { ResponseAwaiter responseAwaiter; using (await requestsSem.UseAsync()) { bool written = await WriteMessage(new Message(MessageKind.Request, id, new MessageContent(body))); if (!written) return null; if (!requestAwaiterQueues.TryGetValue(id, out var queue)) { queue = new Queue<ResponseAwaiter>(); requestAwaiterQueues.Add(id, queue); } responseAwaiter = new ResponseAwaiter<TResponse>(); queue.Enqueue(responseAwaiter); } return (TResponse)await responseAwaiter; } private async Task<bool> WriteLine(string text) { if (clientWriter == null || IsDisposed || !IsTcpClientConnected) return false; using (await writeSem.UseAsync()) { try { await clientWriter.WriteLineAsync(text); await clientWriter.FlushAsync(); } catch (Exception e) { if (!IsDisposed) { var se = e as SocketException ?? e.InnerException as SocketException; if (se != null && se.SocketErrorCode == SocketError.Shutdown) Logger.LogInfo("Client disconnected ungracefully"); else Logger.LogError("Exception thrown when trying to write to client", e); Dispose(); } } } return true; } // ReSharper disable once UnusedMember.Global public void ShutdownSocketSend() { tcpClient.Client.Shutdown(SocketShutdown.Send); } public void Dispose() { if (IsDisposed) return; IsDisposed = true; if (IsTcpClientConnected) { if (IsConnected) Disconnected?.Invoke(); } clientReader?.Dispose(); clientWriter?.Dispose(); ((IDisposable)tcpClient)?.Dispose(); } } }
// 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 gagve = Google.Ads.GoogleAds.V9.Enums; using gagvr = Google.Ads.GoogleAds.V9.Resources; using gaxgrpc = Google.Api.Gax.Grpc; using gr = Google.Rpc; using grpccore = Grpc.Core; using moq = Moq; using st = System.Threading; using stt = System.Threading.Tasks; using NUnit.Framework; using Google.Ads.GoogleAds.V9.Services; namespace Google.Ads.GoogleAds.Tests.V9.Services { /// <summary>Generated unit tests.</summary> public sealed class GeneratedConversionValueRuleSetServiceClientTest { [Category("Autogenerated")][Test] public void GetConversionValueRuleSetRequestObject() { moq::Mock<ConversionValueRuleSetService.ConversionValueRuleSetServiceClient> mockGrpcClient = new moq::Mock<ConversionValueRuleSetService.ConversionValueRuleSetServiceClient>(moq::MockBehavior.Strict); GetConversionValueRuleSetRequest request = new GetConversionValueRuleSetRequest { ResourceNameAsConversionValueRuleSetName = gagvr::ConversionValueRuleSetName.FromCustomerConversionValueRuleSet("[CUSTOMER_ID]", "[CONVERSION_VALUE_RULE_SET_ID]"), }; gagvr::ConversionValueRuleSet expectedResponse = new gagvr::ConversionValueRuleSet { ResourceNameAsConversionValueRuleSetName = gagvr::ConversionValueRuleSetName.FromCustomerConversionValueRuleSet("[CUSTOMER_ID]", "[CONVERSION_VALUE_RULE_SET_ID]"), Id = -6774108720365892680L, ConversionValueRulesAsConversionValueRuleNames = { gagvr::ConversionValueRuleName.FromCustomerConversionValueRule("[CUSTOMER_ID]", "[CONVERSION_VALUE_RULE_ID]"), }, Dimensions = { gagve::ValueRuleSetDimensionEnum.Types.ValueRuleSetDimension.Unspecified, }, OwnerCustomerAsCustomerName = gagvr::CustomerName.FromCustomer("[CUSTOMER_ID]"), AttachmentType = gagve::ValueRuleSetAttachmentTypeEnum.Types.ValueRuleSetAttachmentType.Unspecified, CampaignAsCampaignName = gagvr::CampaignName.FromCustomerCampaign("[CUSTOMER_ID]", "[CAMPAIGN_ID]"), Status = gagve::ConversionValueRuleSetStatusEnum.Types.ConversionValueRuleSetStatus.Paused, }; mockGrpcClient.Setup(x => x.GetConversionValueRuleSet(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); ConversionValueRuleSetServiceClient client = new ConversionValueRuleSetServiceClientImpl(mockGrpcClient.Object, null); gagvr::ConversionValueRuleSet response = client.GetConversionValueRuleSet(request); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task GetConversionValueRuleSetRequestObjectAsync() { moq::Mock<ConversionValueRuleSetService.ConversionValueRuleSetServiceClient> mockGrpcClient = new moq::Mock<ConversionValueRuleSetService.ConversionValueRuleSetServiceClient>(moq::MockBehavior.Strict); GetConversionValueRuleSetRequest request = new GetConversionValueRuleSetRequest { ResourceNameAsConversionValueRuleSetName = gagvr::ConversionValueRuleSetName.FromCustomerConversionValueRuleSet("[CUSTOMER_ID]", "[CONVERSION_VALUE_RULE_SET_ID]"), }; gagvr::ConversionValueRuleSet expectedResponse = new gagvr::ConversionValueRuleSet { ResourceNameAsConversionValueRuleSetName = gagvr::ConversionValueRuleSetName.FromCustomerConversionValueRuleSet("[CUSTOMER_ID]", "[CONVERSION_VALUE_RULE_SET_ID]"), Id = -6774108720365892680L, ConversionValueRulesAsConversionValueRuleNames = { gagvr::ConversionValueRuleName.FromCustomerConversionValueRule("[CUSTOMER_ID]", "[CONVERSION_VALUE_RULE_ID]"), }, Dimensions = { gagve::ValueRuleSetDimensionEnum.Types.ValueRuleSetDimension.Unspecified, }, OwnerCustomerAsCustomerName = gagvr::CustomerName.FromCustomer("[CUSTOMER_ID]"), AttachmentType = gagve::ValueRuleSetAttachmentTypeEnum.Types.ValueRuleSetAttachmentType.Unspecified, CampaignAsCampaignName = gagvr::CampaignName.FromCustomerCampaign("[CUSTOMER_ID]", "[CAMPAIGN_ID]"), Status = gagve::ConversionValueRuleSetStatusEnum.Types.ConversionValueRuleSetStatus.Paused, }; mockGrpcClient.Setup(x => x.GetConversionValueRuleSetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::ConversionValueRuleSet>(stt::Task.FromResult(expectedResponse), null, null, null, null)); ConversionValueRuleSetServiceClient client = new ConversionValueRuleSetServiceClientImpl(mockGrpcClient.Object, null); gagvr::ConversionValueRuleSet responseCallSettings = await client.GetConversionValueRuleSetAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); gagvr::ConversionValueRuleSet responseCancellationToken = await client.GetConversionValueRuleSetAsync(request, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void GetConversionValueRuleSet() { moq::Mock<ConversionValueRuleSetService.ConversionValueRuleSetServiceClient> mockGrpcClient = new moq::Mock<ConversionValueRuleSetService.ConversionValueRuleSetServiceClient>(moq::MockBehavior.Strict); GetConversionValueRuleSetRequest request = new GetConversionValueRuleSetRequest { ResourceNameAsConversionValueRuleSetName = gagvr::ConversionValueRuleSetName.FromCustomerConversionValueRuleSet("[CUSTOMER_ID]", "[CONVERSION_VALUE_RULE_SET_ID]"), }; gagvr::ConversionValueRuleSet expectedResponse = new gagvr::ConversionValueRuleSet { ResourceNameAsConversionValueRuleSetName = gagvr::ConversionValueRuleSetName.FromCustomerConversionValueRuleSet("[CUSTOMER_ID]", "[CONVERSION_VALUE_RULE_SET_ID]"), Id = -6774108720365892680L, ConversionValueRulesAsConversionValueRuleNames = { gagvr::ConversionValueRuleName.FromCustomerConversionValueRule("[CUSTOMER_ID]", "[CONVERSION_VALUE_RULE_ID]"), }, Dimensions = { gagve::ValueRuleSetDimensionEnum.Types.ValueRuleSetDimension.Unspecified, }, OwnerCustomerAsCustomerName = gagvr::CustomerName.FromCustomer("[CUSTOMER_ID]"), AttachmentType = gagve::ValueRuleSetAttachmentTypeEnum.Types.ValueRuleSetAttachmentType.Unspecified, CampaignAsCampaignName = gagvr::CampaignName.FromCustomerCampaign("[CUSTOMER_ID]", "[CAMPAIGN_ID]"), Status = gagve::ConversionValueRuleSetStatusEnum.Types.ConversionValueRuleSetStatus.Paused, }; mockGrpcClient.Setup(x => x.GetConversionValueRuleSet(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); ConversionValueRuleSetServiceClient client = new ConversionValueRuleSetServiceClientImpl(mockGrpcClient.Object, null); gagvr::ConversionValueRuleSet response = client.GetConversionValueRuleSet(request.ResourceName); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task GetConversionValueRuleSetAsync() { moq::Mock<ConversionValueRuleSetService.ConversionValueRuleSetServiceClient> mockGrpcClient = new moq::Mock<ConversionValueRuleSetService.ConversionValueRuleSetServiceClient>(moq::MockBehavior.Strict); GetConversionValueRuleSetRequest request = new GetConversionValueRuleSetRequest { ResourceNameAsConversionValueRuleSetName = gagvr::ConversionValueRuleSetName.FromCustomerConversionValueRuleSet("[CUSTOMER_ID]", "[CONVERSION_VALUE_RULE_SET_ID]"), }; gagvr::ConversionValueRuleSet expectedResponse = new gagvr::ConversionValueRuleSet { ResourceNameAsConversionValueRuleSetName = gagvr::ConversionValueRuleSetName.FromCustomerConversionValueRuleSet("[CUSTOMER_ID]", "[CONVERSION_VALUE_RULE_SET_ID]"), Id = -6774108720365892680L, ConversionValueRulesAsConversionValueRuleNames = { gagvr::ConversionValueRuleName.FromCustomerConversionValueRule("[CUSTOMER_ID]", "[CONVERSION_VALUE_RULE_ID]"), }, Dimensions = { gagve::ValueRuleSetDimensionEnum.Types.ValueRuleSetDimension.Unspecified, }, OwnerCustomerAsCustomerName = gagvr::CustomerName.FromCustomer("[CUSTOMER_ID]"), AttachmentType = gagve::ValueRuleSetAttachmentTypeEnum.Types.ValueRuleSetAttachmentType.Unspecified, CampaignAsCampaignName = gagvr::CampaignName.FromCustomerCampaign("[CUSTOMER_ID]", "[CAMPAIGN_ID]"), Status = gagve::ConversionValueRuleSetStatusEnum.Types.ConversionValueRuleSetStatus.Paused, }; mockGrpcClient.Setup(x => x.GetConversionValueRuleSetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::ConversionValueRuleSet>(stt::Task.FromResult(expectedResponse), null, null, null, null)); ConversionValueRuleSetServiceClient client = new ConversionValueRuleSetServiceClientImpl(mockGrpcClient.Object, null); gagvr::ConversionValueRuleSet responseCallSettings = await client.GetConversionValueRuleSetAsync(request.ResourceName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); gagvr::ConversionValueRuleSet responseCancellationToken = await client.GetConversionValueRuleSetAsync(request.ResourceName, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void GetConversionValueRuleSetResourceNames() { moq::Mock<ConversionValueRuleSetService.ConversionValueRuleSetServiceClient> mockGrpcClient = new moq::Mock<ConversionValueRuleSetService.ConversionValueRuleSetServiceClient>(moq::MockBehavior.Strict); GetConversionValueRuleSetRequest request = new GetConversionValueRuleSetRequest { ResourceNameAsConversionValueRuleSetName = gagvr::ConversionValueRuleSetName.FromCustomerConversionValueRuleSet("[CUSTOMER_ID]", "[CONVERSION_VALUE_RULE_SET_ID]"), }; gagvr::ConversionValueRuleSet expectedResponse = new gagvr::ConversionValueRuleSet { ResourceNameAsConversionValueRuleSetName = gagvr::ConversionValueRuleSetName.FromCustomerConversionValueRuleSet("[CUSTOMER_ID]", "[CONVERSION_VALUE_RULE_SET_ID]"), Id = -6774108720365892680L, ConversionValueRulesAsConversionValueRuleNames = { gagvr::ConversionValueRuleName.FromCustomerConversionValueRule("[CUSTOMER_ID]", "[CONVERSION_VALUE_RULE_ID]"), }, Dimensions = { gagve::ValueRuleSetDimensionEnum.Types.ValueRuleSetDimension.Unspecified, }, OwnerCustomerAsCustomerName = gagvr::CustomerName.FromCustomer("[CUSTOMER_ID]"), AttachmentType = gagve::ValueRuleSetAttachmentTypeEnum.Types.ValueRuleSetAttachmentType.Unspecified, CampaignAsCampaignName = gagvr::CampaignName.FromCustomerCampaign("[CUSTOMER_ID]", "[CAMPAIGN_ID]"), Status = gagve::ConversionValueRuleSetStatusEnum.Types.ConversionValueRuleSetStatus.Paused, }; mockGrpcClient.Setup(x => x.GetConversionValueRuleSet(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); ConversionValueRuleSetServiceClient client = new ConversionValueRuleSetServiceClientImpl(mockGrpcClient.Object, null); gagvr::ConversionValueRuleSet response = client.GetConversionValueRuleSet(request.ResourceNameAsConversionValueRuleSetName); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task GetConversionValueRuleSetResourceNamesAsync() { moq::Mock<ConversionValueRuleSetService.ConversionValueRuleSetServiceClient> mockGrpcClient = new moq::Mock<ConversionValueRuleSetService.ConversionValueRuleSetServiceClient>(moq::MockBehavior.Strict); GetConversionValueRuleSetRequest request = new GetConversionValueRuleSetRequest { ResourceNameAsConversionValueRuleSetName = gagvr::ConversionValueRuleSetName.FromCustomerConversionValueRuleSet("[CUSTOMER_ID]", "[CONVERSION_VALUE_RULE_SET_ID]"), }; gagvr::ConversionValueRuleSet expectedResponse = new gagvr::ConversionValueRuleSet { ResourceNameAsConversionValueRuleSetName = gagvr::ConversionValueRuleSetName.FromCustomerConversionValueRuleSet("[CUSTOMER_ID]", "[CONVERSION_VALUE_RULE_SET_ID]"), Id = -6774108720365892680L, ConversionValueRulesAsConversionValueRuleNames = { gagvr::ConversionValueRuleName.FromCustomerConversionValueRule("[CUSTOMER_ID]", "[CONVERSION_VALUE_RULE_ID]"), }, Dimensions = { gagve::ValueRuleSetDimensionEnum.Types.ValueRuleSetDimension.Unspecified, }, OwnerCustomerAsCustomerName = gagvr::CustomerName.FromCustomer("[CUSTOMER_ID]"), AttachmentType = gagve::ValueRuleSetAttachmentTypeEnum.Types.ValueRuleSetAttachmentType.Unspecified, CampaignAsCampaignName = gagvr::CampaignName.FromCustomerCampaign("[CUSTOMER_ID]", "[CAMPAIGN_ID]"), Status = gagve::ConversionValueRuleSetStatusEnum.Types.ConversionValueRuleSetStatus.Paused, }; mockGrpcClient.Setup(x => x.GetConversionValueRuleSetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::ConversionValueRuleSet>(stt::Task.FromResult(expectedResponse), null, null, null, null)); ConversionValueRuleSetServiceClient client = new ConversionValueRuleSetServiceClientImpl(mockGrpcClient.Object, null); gagvr::ConversionValueRuleSet responseCallSettings = await client.GetConversionValueRuleSetAsync(request.ResourceNameAsConversionValueRuleSetName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); gagvr::ConversionValueRuleSet responseCancellationToken = await client.GetConversionValueRuleSetAsync(request.ResourceNameAsConversionValueRuleSetName, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void MutateConversionValueRuleSetsRequestObject() { moq::Mock<ConversionValueRuleSetService.ConversionValueRuleSetServiceClient> mockGrpcClient = new moq::Mock<ConversionValueRuleSetService.ConversionValueRuleSetServiceClient>(moq::MockBehavior.Strict); MutateConversionValueRuleSetsRequest request = new MutateConversionValueRuleSetsRequest { CustomerId = "customer_id3b3724cb", Operations = { new ConversionValueRuleSetOperation(), }, ValidateOnly = true, ResponseContentType = gagve::ResponseContentTypeEnum.Types.ResponseContentType.ResourceNameOnly, PartialFailure = false, }; MutateConversionValueRuleSetsResponse expectedResponse = new MutateConversionValueRuleSetsResponse { Results = { new MutateConversionValueRuleSetResult(), }, PartialFailureError = new gr::Status(), }; mockGrpcClient.Setup(x => x.MutateConversionValueRuleSets(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); ConversionValueRuleSetServiceClient client = new ConversionValueRuleSetServiceClientImpl(mockGrpcClient.Object, null); MutateConversionValueRuleSetsResponse response = client.MutateConversionValueRuleSets(request); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task MutateConversionValueRuleSetsRequestObjectAsync() { moq::Mock<ConversionValueRuleSetService.ConversionValueRuleSetServiceClient> mockGrpcClient = new moq::Mock<ConversionValueRuleSetService.ConversionValueRuleSetServiceClient>(moq::MockBehavior.Strict); MutateConversionValueRuleSetsRequest request = new MutateConversionValueRuleSetsRequest { CustomerId = "customer_id3b3724cb", Operations = { new ConversionValueRuleSetOperation(), }, ValidateOnly = true, ResponseContentType = gagve::ResponseContentTypeEnum.Types.ResponseContentType.ResourceNameOnly, PartialFailure = false, }; MutateConversionValueRuleSetsResponse expectedResponse = new MutateConversionValueRuleSetsResponse { Results = { new MutateConversionValueRuleSetResult(), }, PartialFailureError = new gr::Status(), }; mockGrpcClient.Setup(x => x.MutateConversionValueRuleSetsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<MutateConversionValueRuleSetsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); ConversionValueRuleSetServiceClient client = new ConversionValueRuleSetServiceClientImpl(mockGrpcClient.Object, null); MutateConversionValueRuleSetsResponse responseCallSettings = await client.MutateConversionValueRuleSetsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); MutateConversionValueRuleSetsResponse responseCancellationToken = await client.MutateConversionValueRuleSetsAsync(request, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void MutateConversionValueRuleSets() { moq::Mock<ConversionValueRuleSetService.ConversionValueRuleSetServiceClient> mockGrpcClient = new moq::Mock<ConversionValueRuleSetService.ConversionValueRuleSetServiceClient>(moq::MockBehavior.Strict); MutateConversionValueRuleSetsRequest request = new MutateConversionValueRuleSetsRequest { CustomerId = "customer_id3b3724cb", Operations = { new ConversionValueRuleSetOperation(), }, }; MutateConversionValueRuleSetsResponse expectedResponse = new MutateConversionValueRuleSetsResponse { Results = { new MutateConversionValueRuleSetResult(), }, PartialFailureError = new gr::Status(), }; mockGrpcClient.Setup(x => x.MutateConversionValueRuleSets(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); ConversionValueRuleSetServiceClient client = new ConversionValueRuleSetServiceClientImpl(mockGrpcClient.Object, null); MutateConversionValueRuleSetsResponse response = client.MutateConversionValueRuleSets(request.CustomerId, request.Operations); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task MutateConversionValueRuleSetsAsync() { moq::Mock<ConversionValueRuleSetService.ConversionValueRuleSetServiceClient> mockGrpcClient = new moq::Mock<ConversionValueRuleSetService.ConversionValueRuleSetServiceClient>(moq::MockBehavior.Strict); MutateConversionValueRuleSetsRequest request = new MutateConversionValueRuleSetsRequest { CustomerId = "customer_id3b3724cb", Operations = { new ConversionValueRuleSetOperation(), }, }; MutateConversionValueRuleSetsResponse expectedResponse = new MutateConversionValueRuleSetsResponse { Results = { new MutateConversionValueRuleSetResult(), }, PartialFailureError = new gr::Status(), }; mockGrpcClient.Setup(x => x.MutateConversionValueRuleSetsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<MutateConversionValueRuleSetsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); ConversionValueRuleSetServiceClient client = new ConversionValueRuleSetServiceClientImpl(mockGrpcClient.Object, null); MutateConversionValueRuleSetsResponse responseCallSettings = await client.MutateConversionValueRuleSetsAsync(request.CustomerId, request.Operations, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); MutateConversionValueRuleSetsResponse responseCancellationToken = await client.MutateConversionValueRuleSetsAsync(request.CustomerId, request.Operations, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } } }
using System; using System.Collections; using System.ComponentModel; using System.Drawing; using System.Windows.Forms; namespace VRS.UI.Controls { /// <summary> /// /// </summary> public delegate void SelectionChangedHandler(object sender,WComboSelChanged_EventArgs e); #region public class WComboSelChanged_EventArgs public class WComboSelChanged_EventArgs { private object m_SelectedValue; public WComboSelChanged_EventArgs(object selectedValue) { m_SelectedValue = selectedValue; } #region Properties Implementation public string Text { get{ return m_SelectedValue.ToString(); } } public WComboItem Item { get{ if(m_SelectedValue != null){ return (WComboItem)m_SelectedValue; } else{ return null; } } } #endregion } #endregion public class WComboPopUp : VRS.UI.Controls.WPopUpFormBase { private WComboListBox m_pListBox; private System.ComponentModel.IContainer components = null; public event SelectionChangedHandler SelectionChanged = null; private ViewStyle m_pViewStyle = null; /// <summary> /// /// </summary> /// <param name="parent"></param> /// <param name="viewStyle"></param> /// <param name="listBoxItems"></param> /// <param name="visibleItems"></param> public WComboPopUp(Control parent,ViewStyle viewStyle,object[] listBoxItems,int visibleItems,string selectedText,int dropDownWidth) : base(parent) { // This call is required by the Windows Form Designer. InitializeComponent(); // TODO: Add any initialization after the InitializeComponent call // Store view style m_pViewStyle = viewStyle; if(visibleItems > listBoxItems.Length){ visibleItems = listBoxItems.Length; } this.Width = dropDownWidth; this.Height = (m_pListBox.ItemHeight * visibleItems)+2; m_pListBox.BackColor = viewStyle.EditColor; // Add items to listbox m_pListBox.Items.AddRange(listBoxItems); int index = m_pListBox.FindStringExact(selectedText); if(index > -1){ m_pListBox.SelectedIndex = index; } } #region function Dispose /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if (components != null) { components.Dispose(); } } base.Dispose( disposing ); } #endregion #region 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.m_pListBox = new VRS.UI.Controls.WComboListBox(); this.SuspendLayout(); // // m_pListBox // this.m_pListBox.Anchor = (((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right); this.m_pListBox.BorderStyle = System.Windows.Forms.BorderStyle.None; this.m_pListBox.IntegralHeight = false; this.m_pListBox.Location = new System.Drawing.Point(1, 1); this.m_pListBox.Name = "m_pListBox"; this.m_pListBox.Size = new System.Drawing.Size(118, 70); this.m_pListBox.TabIndex = 0; this.m_pListBox.KeyUp += new System.Windows.Forms.KeyEventHandler(this.m_pListBox_KeyUp); this.m_pListBox.MouseMove += new System.Windows.Forms.MouseEventHandler(this.listBox_MouseMove); // // WComboPopUp // this.ClientSize = new System.Drawing.Size(120, 72); this.Controls.AddRange(new System.Windows.Forms.Control[] { this.m_pListBox}); this.Name = "WComboPopUp"; this.ResumeLayout(false); } #endregion #region Events handling #region function m_pListBox_MouseMove private void listBox_MouseMove(object sender, System.Windows.Forms.MouseEventArgs e) { int index = m_pListBox.IndexFromPoint(e.X,e.Y); if(m_pListBox.SelectedIndex != index){ m_pListBox.SelectedIndex = index; } } #endregion #region function m_pListBox_KeyUp private void m_pListBox_KeyUp(object sender, System.Windows.Forms.KeyEventArgs e) { if(e.KeyData == Keys.Escape){ this.Close(); } if(e.KeyData == Keys.Enter){ OnSelectionChanged(); this.Close(); } } #endregion #endregion #region function OnPaint protected override void OnPaint(System.Windows.Forms.PaintEventArgs e) { base.OnPaint(e); Rectangle rect = new Rectangle(this.ClientRectangle.Location,new Size(this.ClientRectangle.Width - 1,this.ClientRectangle.Height - 1)); Pen pen = new Pen(m_pViewStyle.BorderHotColor); e.Graphics.DrawRectangle(pen,rect); } #endregion #region function PostMessage public override void PostMessage(ref Message m) { Message msg = new Message(); msg.HWnd = m_pListBox.Handle; msg.LParam = m.LParam; msg.Msg = m.Msg; msg.Result = m.Result; msg.WParam = m.WParam; // Forward message to ListBox m_pListBox.PostMessage(ref msg); } #endregion #region Public Functions public void RaiseSelectionChanged() { OnSelectionChanged(); } #endregion #region Events Implementation private void OnSelectionChanged() { if(m_pListBox.SelectedItem != null){ WComboSelChanged_EventArgs oArgs = new WComboSelChanged_EventArgs(m_pListBox.SelectedItem); if(this.SelectionChanged != null){ this.SelectionChanged(this,oArgs); } } } #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.Data; using System.Linq; using System.Reflection; using log4net; using MySql.Data.MySqlClient; using OpenMetaverse; using OpenSim.Framework; namespace OpenSim.Data.MySQL { /// <summary> /// A MySQL Interface for the Asset Server /// </summary> public class MySQLXInventoryData : IXInventoryData { private MySqlFolderHandler m_Folders; private MySqlItemHandler m_Items; public MySQLXInventoryData(string conn, string realm) { m_Folders = new MySqlFolderHandler( conn, "inventoryfolders", "InventoryStore"); m_Items = new MySqlItemHandler( conn, "inventoryitems", String.Empty); } public XInventoryFolder[] GetFolders(string[] fields, string[] vals) { return m_Folders.Get(fields, vals); } public XInventoryItem[] GetItems(string[] fields, string[] vals) { return m_Items.Get(fields, vals); } public bool StoreFolder(XInventoryFolder folder) { if (folder.folderName.Length > 64) folder.folderName = folder.folderName.Substring(0, 64); return m_Folders.Store(folder); } public bool StoreItem(XInventoryItem item) { if (item.inventoryName.Length > 64) item.inventoryName = item.inventoryName.Substring(0, 64); if (item.inventoryDescription.Length > 128) item.inventoryDescription = item.inventoryDescription.Substring(0, 128); return m_Items.Store(item); } public bool DeleteFolders(string field, string val) { return m_Folders.Delete(field, val); } public bool DeleteFolders(string[] fields, string[] vals) { return m_Folders.Delete(fields, vals); } public bool DeleteItems(string field, string val) { return m_Items.Delete(field, val); } public bool DeleteItems(string[] fields, string[] vals) { return m_Items.Delete(fields, vals); } public bool MoveItem(string id, string newParent) { return m_Items.MoveItem(id, newParent); } public bool MoveFolder(string id, string newParent) { return m_Folders.MoveFolder(id, newParent); } public XInventoryItem[] GetActiveGestures(UUID principalID) { return m_Items.GetActiveGestures(principalID); } public int GetAssetPermissions(UUID principalID, UUID assetID) { return m_Items.GetAssetPermissions(principalID, assetID); } } public class MySqlItemHandler : MySqlInventoryHandler<XInventoryItem> { // private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); public MySqlItemHandler(string c, string t, string m) : base(c, t, m) { } public override bool Delete(string field, string val) { XInventoryItem[] retrievedItems = Get(new string[] { field }, new string[] { val }); if (retrievedItems.Length == 0) return false; if (!base.Delete(field, val)) return false; // Don't increment folder version here since Delete(string, string) calls Delete(string[], string[]) // IncrementFolderVersion(retrievedItems[0].parentFolderID); return true; } public override bool Delete(string[] fields, string[] vals) { XInventoryItem[] retrievedItems = Get(fields, vals); if (retrievedItems.Length == 0) return false; if (!base.Delete(fields, vals)) return false; HashSet<UUID> deletedItemFolderUUIDs = new HashSet<UUID>(); Array.ForEach<XInventoryItem>(retrievedItems, i => deletedItemFolderUUIDs.Add(i.parentFolderID)); foreach (UUID deletedItemFolderUUID in deletedItemFolderUUIDs) IncrementFolderVersion(deletedItemFolderUUID); return true; } public bool MoveItem(string id, string newParent) { XInventoryItem[] retrievedItems = Get(new string[] { "inventoryID" }, new string[] { id }); if (retrievedItems.Length == 0) return false; UUID oldParent = retrievedItems[0].parentFolderID; using (MySqlCommand cmd = new MySqlCommand()) { cmd.CommandText = String.Format("update {0} set parentFolderID = ?ParentFolderID where inventoryID = ?InventoryID", m_Realm); cmd.Parameters.AddWithValue("?ParentFolderID", newParent); cmd.Parameters.AddWithValue("?InventoryID", id); if (ExecuteNonQuery(cmd) == 0) return false; } IncrementFolderVersion(oldParent); IncrementFolderVersion(newParent); return true; } public XInventoryItem[] GetActiveGestures(UUID principalID) { using (MySqlCommand cmd = new MySqlCommand()) { // cmd.CommandText = String.Format("select * from inventoryitems where avatarId = ?uuid and assetType = ?type and flags & 1", m_Realm); cmd.CommandText = String.Format("select * from inventoryitems where avatarId = ?uuid and assetType = ?type and flags & 1"); cmd.Parameters.AddWithValue("?uuid", principalID.ToString()); cmd.Parameters.AddWithValue("?type", (int)AssetType.Gesture); return DoQuery(cmd); } } public int GetAssetPermissions(UUID principalID, UUID assetID) { using (MySqlConnection dbcon = new MySqlConnection(m_connectionString)) { dbcon.Open(); using (MySqlCommand cmd = new MySqlCommand()) { cmd.Connection = dbcon; // cmd.CommandText = String.Format("select bit_or(inventoryCurrentPermissions) as inventoryCurrentPermissions from inventoryitems where avatarID = ?PrincipalID and assetID = ?AssetID group by assetID", m_Realm); cmd.CommandText = String.Format("select bit_or(inventoryCurrentPermissions) as inventoryCurrentPermissions from inventoryitems where avatarID = ?PrincipalID and assetID = ?AssetID group by assetID"); cmd.Parameters.AddWithValue("?PrincipalID", principalID.ToString()); cmd.Parameters.AddWithValue("?AssetID", assetID.ToString()); using (IDataReader reader = cmd.ExecuteReader()) { int perms = 0; if (reader.Read()) { perms = Convert.ToInt32(reader["inventoryCurrentPermissions"]); } return perms; } } } } public override bool Store(XInventoryItem item) { if (!base.Store(item)) return false; IncrementFolderVersion(item.parentFolderID); return true; } } public class MySqlFolderHandler : MySqlInventoryHandler<XInventoryFolder> { // private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); public MySqlFolderHandler(string c, string t, string m) : base(c, t, m) { } public bool MoveFolder(string id, string newParentFolderID) { XInventoryFolder[] folders = Get(new string[] { "folderID" }, new string[] { id }); if (folders.Length == 0) return false; UUID oldParentFolderUUID = folders[0].parentFolderID; using (MySqlCommand cmd = new MySqlCommand()) { cmd.CommandText = String.Format( "update {0} set parentFolderID = ?ParentFolderID where folderID = ?folderID", m_Realm); cmd.Parameters.AddWithValue("?ParentFolderID", newParentFolderID); cmd.Parameters.AddWithValue("?folderID", id); if (ExecuteNonQuery(cmd) == 0) return false; } IncrementFolderVersion(oldParentFolderUUID); IncrementFolderVersion(newParentFolderID); return true; } public override bool Store(XInventoryFolder folder) { if (!base.Store(folder)) return false; IncrementFolderVersion(folder.parentFolderID); return true; } } public class MySqlInventoryHandler<T> : MySQLGenericTableHandler<T> where T: class, new() { public MySqlInventoryHandler(string c, string t, string m) : base(c, t, m) {} protected bool IncrementFolderVersion(UUID folderID) { return IncrementFolderVersion(folderID.ToString()); } protected bool IncrementFolderVersion(string folderID) { // m_log.DebugFormat("[MYSQL FOLDER HANDLER]: Incrementing version on folder {0}", folderID); // Util.PrintCallStack(); using (MySqlConnection dbcon = new MySqlConnection(m_connectionString)) { dbcon.Open(); using (MySqlCommand cmd = new MySqlCommand()) { cmd.Connection = dbcon; cmd.CommandText = String.Format("update inventoryfolders set version=version+1 where folderID = ?folderID"); cmd.Parameters.AddWithValue("?folderID", folderID); try { cmd.ExecuteNonQuery(); } catch (Exception) { return false; } cmd.Dispose(); } dbcon.Close(); } return true; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using Xunit; namespace System.Tests { public abstract class RealParserTestsBase { // The following methods need to be implemented for the tests to run: protected abstract string InvariantToStringDouble(double d); protected abstract string InvariantToStringSingle(float f); protected abstract bool InvariantTryParseDouble(string s, out double result); protected abstract bool InvariantTryParseSingle(string s, out float result); /// <summary> /// Test some specific floating-point literals that have been shown to be problematic /// in some implementation. /// </summary> [Theory] // https://msdn.microsoft.com/en-us/library/kfsatb94(v=vs.110).aspx [InlineData("0.6822871999174", 0x3FE5D54BF743FD1Bul)] // Common problem numbers [InlineData("2.2250738585072011e-308", 0x000FFFFFFFFFFFFFul)] [InlineData("2.2250738585072012e-308", 0x0010000000000000ul)] // http://www.exploringbinary.com/bigcomp-deciding-truncated-near-halfway-conversions/ [InlineData("1.3694713649464322631e-11", 0x3DAE1D703BB5749Dul)] [InlineData("9.3170532238714134438e+16", 0x4374B021AFD9F651ul)] // https://connect.microsoft.com/VisualStudio/feedback/details/914964/double-round-trip-conversion-via-a-string-is-not-safe [InlineData("0.84551240822557006", 0x3FEB0E7009B61CE0ul)] // This value has a non-terminating binary fraction. It has a 0 at bit 54 // followed by 120 ones. // http://www.exploringbinary.com/a-bug-in-the-bigcomp-function-of-david-gays-strtod/ [InlineData("1.8254370818746402660437411213933955878019332885742187", 0x3FFD34FD8378EA83ul)] // http://www.exploringbinary.com/decimal-to-floating-point-needs-arbitrary-precision [InlineData("7.8459735791271921e+65", 0x4D9DCD0089C1314Eul)] [InlineData("3.08984926168550152811e-32", 0x39640DE48676653Bul)] // other values from https://github.com/dotnet/roslyn/issues/4221 [InlineData("0.6822871999174000000", 0x3FE5D54BF743FD1Bul)] [InlineData("0.6822871999174000001", 0x3FE5D54BF743FD1Bul)] // A handful of selected values for which double.Parse has been observed to produce an incorrect result [InlineData("88.7448699245e+188", 0x675fde6aee647ed2ul)] [InlineData("02.0500496671303857e-88", 0x2dba19a3cf32cd7ful)] [InlineData("1.15362842193e193", 0x68043a6fcda86331ul)] [InlineData("65.9925719e-190", 0x18dd672e04e96a79ul)] [InlineData("0.4619024460e-158", 0x1f103c1e5abd7c87ul)] [InlineData("61.8391820096448e147", 0x5ed35849885ad12bul)] [InlineData("0.2e+127", 0x5a27a2ecc414a03ful)] [InlineData("0.8e+127", 0x5a47a2ecc414a03ful)] [InlineData("35.27614496323756e-307", 0x0083d141335ce6c7ul)] [InlineData("3.400034617466e190", 0x677e863a216ab367ul)] [InlineData("0.78393577148319e-254", 0x0b2d6d5379bc932dul)] [InlineData("0.947231e+100", 0x54b152a10483a38ful)] [InlineData("4.e126", 0x5a37a2ecc414a03ful)] [InlineData("6.235271922748e-165", 0x1dd6faeba4fc9f91ul)] [InlineData("3.497444198362024e-82", 0x2f053b8036dd4203ul)] [InlineData("8.e+126", 0x5a47a2ecc414a03ful)] [InlineData("10.027247729e+91", 0x53089cc2d930ed3ful)] [InlineData("4.6544819e-192", 0x18353c5d35ceaaadul)] [InlineData("5.e+125", 0x5a07a2ecc414a03ful)] [InlineData("6.96768e68", 0x4e39d8352ee997f9ul)] [InlineData("0.73433e-145", 0x21cd57b723dc17bful)] [InlineData("31.076044256878e259", 0x76043627aa7248dful)] [InlineData("0.8089124675e-201", 0x162fb3bf98f037f7ul)] [InlineData("88.7453407049700914e-144", 0x227150a674c218e3ul)] [InlineData("32.401089401e-65", 0x32c10fa88084d643ul)] [InlineData("0.734277884753e-209", 0x14834fdfb6248755ul)] [InlineData("8.3435e+153", 0x5fe3e9c5b617dc39ul)] [InlineData("30.379e-129", 0x25750ec799af9efful)] [InlineData("78.638509299e141", 0x5d99cb8c0a72cd05ul)] [InlineData("30.096884930e-42", 0x3784f976b4d47d63ul)] // values from http://www.icir.org/vern/papers/testbase-report.pdf table 1 (less than half ULP - round down) [InlineData("69e+267", 0x77C0B7CB60C994DAul)] [InlineData("999e-026", 0x3B282782AFE1869Eul)] [InlineData("7861e-034", 0x39AFE3544145E9D8ul)] [InlineData("75569e-254", 0x0C35A462D91C6AB3ul)] [InlineData("928609e-261", 0x0AFBE2DD66200BEFul)] [InlineData("9210917e+080", 0x51FDA232347E6032ul)] [InlineData("84863171e+114", 0x59406E98F5EC8F37ul)] [InlineData("653777767e+273", 0x7A720223F2B3A881ul)] [InlineData("5232604057e-298", 0x041465B896C24520ul)] [InlineData("27235667517e-109", 0x2B77D41824D64FB2ul)] [InlineData("653532977297e-123", 0x28D925A0AABCDC68ul)] [InlineData("3142213164987e-294", 0x057D3409DFBCA26Ful)] [InlineData("46202199371337e-072", 0x33D28F9EDFBD341Ful)] [InlineData("231010996856685e-073", 0x33C28F9EDFBD341Ful)] [InlineData("9324754620109615e+212", 0x6F43AE60753AF6CAul)] [InlineData("78459735791271921e+049", 0x4D9DCD0089C1314Eul)] [InlineData("272104041512242479e+200", 0x6D13BBB4BF05F087ul)] [InlineData("6802601037806061975e+198", 0x6CF3BBB4BF05F087ul)] [InlineData("20505426358836677347e-221", 0x161012954B6AABBAul)] [InlineData("836168422905420598437e-234", 0x13B20403A628A9CAul)] [InlineData("4891559871276714924261e+222", 0x7286ECAF7694A3C7ul)] // values from http://www.icir.org/vern/papers/testbase-report.pdf table 2 (greater than half ULP - round up) [InlineData("85e-037", 0x38A698CCDC60015Aul)] [InlineData("623e+100", 0x554640A62F3A83DFul)] [InlineData("3571e+263", 0x77462644C61D41AAul)] [InlineData("81661e+153", 0x60B7CA8E3D68578Eul)] [InlineData("920657e-023", 0x3C653A9985DBDE6Cul)] [InlineData("4603285e-024", 0x3C553A9985DBDE6Cul)] [InlineData("87575437e-309", 0x016E07320602056Cul)] [InlineData("245540327e+122", 0x5B01B6231E18C5CBul)] [InlineData("6138508175e+120", 0x5AE1B6231E18C5CBul)] [InlineData("83356057653e+193", 0x6A4544E6DAEE2A18ul)] [InlineData("619534293513e+124", 0x5C210C20303FE0F1ul)] [InlineData("2335141086879e+218", 0x6FC340A1C932C1EEul)] [InlineData("36167929443327e-159", 0x21BCE77C2B3328FCul)] [InlineData("609610927149051e-255", 0x0E104273B18918B1ul)] [InlineData("3743626360493413e-165", 0x20E8823A57ADBEF9ul)] [InlineData("94080055902682397e-242", 0x11364981E39E66CAul)] [InlineData("899810892172646163e+283", 0x7E6ADF51FA055E03ul)] [InlineData("7120190517612959703e+120", 0x5CC3220DCD5899FDul)] [InlineData("25188282901709339043e-252", 0x0FA4059AF3DB2A84ul)] [InlineData("308984926168550152811e-052", 0x39640DE48676653Bul)] [InlineData("6372891218502368041059e+064", 0x51C067047DBB38FEul)] // http://www.exploringbinary.com/incorrect-decimal-to-floating-point-conversion-in-sqlite/ [InlineData("1e-23", 0x3B282DB34012B251ul)] [InlineData("8.533e+68", 0x4E3FA69165A8EEA2ul)] [InlineData("4.1006e-184", 0x19DBE0D1C7EA60C9ul)] [InlineData("9.998e+307", 0x7FE1CC0A350CA87Bul)] [InlineData("9.9538452227e-280", 0x0602117AE45CDE43ul)] [InlineData("6.47660115e-260", 0x0A1FDD9E333BADADul)] [InlineData("7.4e+47", 0x49E033D7ECA0ADEFul)] [InlineData("5.92e+48", 0x4A1033D7ECA0ADEFul)] [InlineData("7.35e+66", 0x4DD172B70EABABA9ul)] [InlineData("8.32116e+55", 0x4B8B2628393E02CDul)] public void TestParserDouble_Troublesome(string s, ulong expectedBits) { CheckOneDouble(s, expectedBits); } /// <summary> /// Test round tripping for some specific floating-point values constructed to test the edge cases of conversion implementations. /// </summary> [Theory] [InlineData("0.0", 0x0000000000000000ul)] [InlineData("1.0e-99999999999999999999", 0x0000000000000000ul)] [InlineData("0e-99999999999999999999", 0x0000000000000000ul)] [InlineData("0e99999999999999999999", 0x0000000000000000ul)] // Verify small and large exactly representable integers: [InlineData("1", 0x3ff0000000000000)] [InlineData("2", 0x4000000000000000)] [InlineData("3", 0x4008000000000000)] [InlineData("4", 0x4010000000000000)] [InlineData("5", 0x4014000000000000)] [InlineData("6", 0x4018000000000000)] [InlineData("7", 0x401C000000000000)] [InlineData("8", 0x4020000000000000)] [InlineData("9007199254740984", 0x433ffffffffffff8)] [InlineData("9007199254740985", 0x433ffffffffffff9)] [InlineData("9007199254740986", 0x433ffffffffffffa)] [InlineData("9007199254740987", 0x433ffffffffffffb)] [InlineData("9007199254740988", 0x433ffffffffffffc)] [InlineData("9007199254740989", 0x433ffffffffffffd)] [InlineData("9007199254740990", 0x433ffffffffffffe)] [InlineData("9007199254740991", 0x433fffffffffffff)] // 2^53 - 1 // Verify the smallest and largest denormal values: [InlineData("5.0e-324", 0x0000000000000001)] [InlineData("1.0e-323", 0x0000000000000002)] [InlineData("1.5e-323", 0x0000000000000003)] [InlineData("2.0e-323", 0x0000000000000004)] [InlineData("2.5e-323", 0x0000000000000005)] [InlineData("3.0e-323", 0x0000000000000006)] [InlineData("3.5e-323", 0x0000000000000007)] [InlineData("4.0e-323", 0x0000000000000008)] [InlineData("4.5e-323", 0x0000000000000009)] [InlineData("5.0e-323", 0x000000000000000a)] [InlineData("5.5e-323", 0x000000000000000b)] [InlineData("6.0e-323", 0x000000000000000c)] [InlineData("6.5e-323", 0x000000000000000d)] [InlineData("7.0e-323", 0x000000000000000e)] [InlineData("7.5e-323", 0x000000000000000f)] [InlineData("2.2250738585071935e-308", 0x000ffffffffffff0)] [InlineData("2.2250738585071940e-308", 0x000ffffffffffff1)] [InlineData("2.2250738585071945e-308", 0x000ffffffffffff2)] [InlineData("2.2250738585071950e-308", 0x000ffffffffffff3)] [InlineData("2.2250738585071955e-308", 0x000ffffffffffff4)] [InlineData("2.2250738585071960e-308", 0x000ffffffffffff5)] [InlineData("2.2250738585071964e-308", 0x000ffffffffffff6)] [InlineData("2.2250738585071970e-308", 0x000ffffffffffff7)] [InlineData("2.2250738585071974e-308", 0x000ffffffffffff8)] [InlineData("2.2250738585071980e-308", 0x000ffffffffffff9)] [InlineData("2.2250738585071984e-308", 0x000ffffffffffffa)] [InlineData("2.2250738585071990e-308", 0x000ffffffffffffb)] [InlineData("2.2250738585071994e-308", 0x000ffffffffffffc)] [InlineData("2.2250738585072000e-308", 0x000ffffffffffffd)] [InlineData("2.2250738585072004e-308", 0x000ffffffffffffe)] [InlineData("2.2250738585072010e-308", 0x000fffffffffffff)] // Test cases from Rick Regan's article, "Incorrectly Rounded Conversions in Visual C++": // // http://www.exploringbinary.com/incorrectly-rounded-conversions-in-visual-c-plus-plus/ // // Example 1: [InlineData("9214843084008499", 0x43405e6cec57761a)] // Example 2: [InlineData("0.500000000000000166533453693773481063544750213623046875", 0x3fe0000000000002)] // Example 3 (2^-1 + 2^-53 + 2^-54): [InlineData("30078505129381147446200", 0x44997a3c7271b021)] // Example 4: [InlineData("1777820000000000000001", 0x4458180d5bad2e3e)] // Example 5 (2^-1 + 2^-53 + 2^-54 + 2^-66): [InlineData("0.500000000000000166547006220929549868969843373633921146392822265625", 0x3fe0000000000002)] // Example 6 (2^-1 + 2^-53 + 2^-54 + 2^-65): [InlineData("0.50000000000000016656055874808561867439493653364479541778564453125", 0x3fe0000000000002)] // Example 7: [InlineData("0.3932922657273", 0x3fd92bb352c4623a)] // The following test cases are taken from other articles on Rick Regan's // Exploring Binary blog. These are conversions that other implementations // were found to perform incorrectly. // http://www.exploringbinary.com/nondeterministic-floating-point-conversions-in-java/ // http://www.exploringbinary.com/incorrectly-rounded-subnormal-conversions-in-java/ // Example 1 (2^-1047 + 2^-1075, half-ulp above a power of two): [InlineData("6.6312368714697582767853966302759672433990999473553031442499717587" + "362866301392654396180682007880487441059604205526018528897150063763" + "256665955396033303618005191075917832333584923372080578494993608994" + "251286407188566165030934449228547591599881603044399098682919739314" + "266256986631577498362522745234853124423586512070512924530832781161" + "439325697279187097860044978723221938561502254152119972830784963194" + "121246401117772161481107528151017752957198119743384519360959074196" + "224175384736794951486324803914359317679811223967034438033355297560" + "033532098300718322306892013830155987921841729099279241763393155074" + "022348361207309147831684007154624400538175927027662135590421159867" + "638194826541287705957668068727833491469671712939495988506756821156" + "96218943412532098591327667236328125E-316", 0x0000000008000000)] // Example 2 (2^-1058 - 2^-1075, half-ulp below a power of two): [InlineData("3.2378839133029012895883524125015321748630376694231080599012970495" + "523019706706765657868357425877995578606157765598382834355143910841" + "531692526891905643964595773946180389283653051434639551003566966656" + "292020173313440317300443693602052583458034314716600326995807313009" + "548483639755486900107515300188817581841745696521731104736960227499" + "346384253806233697747365600089974040609674980283891918789639685754" + "392222064169814626901133425240027243859416510512935526014211553334" + "302252372915238433223313261384314778235911424088000307751706259156" + "707286570031519536642607698224949379518458015308952384398197084033" + "899378732414634842056080000272705311068273879077914449185347715987" + "501628125488627684932015189916680282517302999531439241685457086639" + "13273994694463908672332763671875E-319", 0x0000000000010000)] // Example 3 (2^-1027 + 2^-1066 + 2^-1075, half-ulp above a non-power of two): [InlineData("6.9533558078476771059728052155218916902221198171459507544162056079" + "800301315496366888061157263994418800653863998640286912755395394146" + "528315847956685600829998895513577849614468960421131982842131079351" + "102171626549398024160346762138294097205837595404767869364138165416" + "212878432484332023692099166122496760055730227032447997146221165421" + "888377703760223711720795591258533828013962195524188394697705149041" + "926576270603193728475623010741404426602378441141744972109554498963" + "891803958271916028866544881824524095839813894427833770015054620157" + "450178487545746683421617594966617660200287528887833870748507731929" + "971029979366198762266880963149896457660004790090837317365857503352" + "620998601508967187744019647968271662832256419920407478943826987518" + "09812609536720628966577351093292236328125E-310", 0x0000800000000100)] // Example 4 (2^-1058 + 2^-1063 + 2^-1075, half-ulp below a non-power of two): [InlineData("3.3390685575711885818357137012809439119234019169985217716556569973" + "284403145596153181688491490746626090999981130094655664268081703784" + "340657229916596426194677060348844249897410807907667784563321682004" + "646515939958173717821250106683466529959122339932545844611258684816" + "333436749050742710644097630907080178565840197768788124253120088123" + "262603630354748115322368533599053346255754042160606228586332807443" + "018924703005556787346899784768703698535494132771566221702458461669" + "916553215355296238706468887866375289955928004361779017462862722733" + "744717014529914330472578638646014242520247915673681950560773208853" + "293843223323915646452641434007986196650406080775491621739636492640" + "497383622906068758834568265867109610417379088720358034812416003767" + "05491726170293986797332763671875E-319", 0x0000000000010800)] // http://www.exploringbinary.com/gays-strtod-returns-zero-for-inputs-just-above-2-1075/ // A number between 2^-2074 and 2^-1075, just slightly larger than 2^-1075. // It has bit 1075 set (the denormal rounding bit), followed by 2506 zeroes, // followed by one bits. It should round up to 2^-1074. [InlineData("2.470328229206232720882843964341106861825299013071623822127928412503" + "37753635104375932649918180817996189898282347722858865463328355177969" + "89819938739800539093906315035659515570226392290858392449105184435931" + "80284993653615250031937045767824921936562366986365848075700158576926" + "99037063119282795585513329278343384093519780155312465972635795746227" + "66465272827220056374006485499977096599470454020828166226237857393450" + "73633900796776193057750674017632467360096895134053553745851666113422" + "37666786041621596804619144672918403005300575308490487653917113865916" + "46239524912623653881879636239373280423891018672348497668235089863388" + "58792562830275599565752445550725518931369083625477918694866799496832" + "40497058210285131854513962138377228261454376934125320985913276672363" + "28125001e-324", 0x0000000000000001)] // This is the exact string for the largest denormal value and contains // the most significant digits of any double-precision floating-point value [InlineData("2.225073858507200889024586876085859887650423112240959465493524802562" + "44000922823569517877588880375915526423097809504343120858773871583572" + "91821993020294379224223559819827501242041788969571311791082261043971" + "97960400045489739193807919893608152561311337614984204327175103362739" + "15497827315941438281362751138386040942494649422863166954291050802018" + "15926642134996606517803095075913058719846423906068637102005108723282" + "78467884363194451586613504122347901479236958520832159762106637540161" + "37365830441936037147783553066828345356340050740730401356029680463759" + "18583163124224521599262546494300836851861719422417646455137135420132" + "21703137049658321015465406803539741790602258950302350193751977303094" + "57631732108525072993050897615825191597207572324554347709124613174935" + "80281734466552734375e-308", 0x000FFFFFFFFFFFFF)] // This is the exact string for the largest denormal value plus an additional rounding digit. // The rounding digit is such that the resulting value should still be the largest denormal. [InlineData("2.225073858507200889024586876085859887650423112240959465493524802562" + "44000922823569517877588880375915526423097809504343120858773871583572" + "91821993020294379224223559819827501242041788969571311791082261043971" + "97960400045489739193807919893608152561311337614984204327175103362739" + "15497827315941438281362751138386040942494649422863166954291050802018" + "15926642134996606517803095075913058719846423906068637102005108723282" + "78467884363194451586613504122347901479236958520832159762106637540161" + "37365830441936037147783553066828345356340050740730401356029680463759" + "18583163124224521599262546494300836851861719422417646455137135420132" + "21703137049658321015465406803539741790602258950302350193751977303094" + "57631732108525072993050897615825191597207572324554347709124613174935" + "802817344665527343754e-308", 0x000FFFFFFFFFFFFF)] [InlineData("0.000000000000000000000000000000000000000000000000000000000000000000" + "00000000000000000000000000000000000000000000000000000000000000000000" + "00000000000000000000000000000000000000000000000000000000000000000000" + "00000000000000000000000000000000000000000000000000000000000000000000" + "00000000000000000000000000000000000000000000000000000000000000000000" + "00000000000000000000000020000000000000000000000000000000000000002000" + "00000000000000000000000000000000000000000000000000000000000000000000" + "00000000000000000000000000000000000000000000000000000000000000000000" + "00000000000000000000000000000000000000000000000000000000000000000000" + "00000000000000000000000000000000000000000000000000000000000000000000" + "00000000000000000000000000000000000000000000000000000000000000000000" + "00000000000000000000000000000000000000000000000000000000000000000000" + "00000000000000000000000000000000000000000000000000000000000000000000" + "00000000000000000000000000000000000000000000000000000000000000000000" + "00000000000000000000000000000000000000000000000000000000000000000000" + "00000000000000000000000000000000000000000000000000000000000000000000" + "00000000000000000000000020000000000000000000000000000000000000000000" + "00000000000000000000000000000000000000000000000000000000000000000000" + "00000000000000000000000000000000000000000000000000000000000000000000" + "00000000000000000000000000000000000000000000000000000000000000000000" + "00000000000000000000000040000", 0x0000000000000000)] [InlineData("00000000000000000000000000000000000000000000000000000000000000000000" + "00000000000000000000000000000000000000000000000000000000000000000000" + "00000000000000000000000000000000000000000000000000000000000000000000" + "00000000000000000000000000000000000000000000000000000000000000000000" + "00000000000000000000000000000000000000000000000000000000000000000000" + "00000000000000000000000020000000000000000000000000000000000000002000" + "00000000000000000000000000000000000000000000000000000000000000000000" + "00000000000000000000000000000000000000000000000000000000000000000000" + "00000000000000000000000000000000000000000000000000000000000000000000" + "00000000000000000000000000000000000000000000000000000000000000000000" + "00000000000000000000000000000000000000000000000000000000000000000000" + "00000000000000000000000000000000000000000000000000000000000000000000" + "00000000000000000000000000000000000000000000000000000000000000000000" + "00000000000000000000000000000000000000000000000000000000000000000000" + "00000000000000000000000000000000000000000000000000000000000000000000" + "00000000000000000000000000000000000000000000000000000000000000000000" + "00000000000000000000000020000000000000000000000000000000000000000000" + "00000000000000000000000000000000000000000000000000000000000000000000" + "00000000000000000000000000000000000000000000000000000000000000000000" + "00000000000000000000000000000000000000000000000000000000000000000000" + "00000000000000000000000040000", 0x7FF0000000000000)] public void TestParserDouble_SpecificValues(string s, ulong expectedBits) { CheckOneDouble(s, expectedBits); } [Theory] [InlineData("-0", 0x8000000000000000ul)] [InlineData("-0.0", 0x8000000000000000ul)] [InlineData("-infinity", 0xFFF0000000000000ul)] [InlineData("-iNfInItY", 0xFFF0000000000000ul)] [InlineData("-INFINITY", 0xFFF0000000000000ul)] [InlineData("infinity", 0x7FF0000000000000)] [InlineData("InFiNiTy", 0x7FF0000000000000)] [InlineData("INFINITY", 0x7FF0000000000000)] [InlineData("+infinity", 0x7FF0000000000000)] [InlineData("+InFiNiTy", 0x7FF0000000000000)] [InlineData("+INFINITY", 0x7FF0000000000000)] [InlineData("-nan", 0xFFF8000000000000ul)] [InlineData("-nAn", 0xFFF8000000000000ul)] [InlineData("-NAN", 0xFFF8000000000000ul)] [InlineData("nan", 0xFFF8000000000000ul)] [InlineData("Nan", 0xFFF8000000000000ul)] [InlineData("NAN", 0xFFF8000000000000ul)] [InlineData("+nan", 0xFFF8000000000000ul)] [InlineData("+NaN", 0xFFF8000000000000ul)] [InlineData("+NAN", 0xFFF8000000000000ul)] public void TestParserDouble_SpecialValues(string s, ulong expectedBits) { CheckOneDouble(s, expectedBits); } /// <summary> /// Test round tripping for some specific floating-point values constructed to test the edge cases of conversion implementations. /// </summary> [Theory] // Verify the smallest denormals: [InlineData(0x0000000000000001ul, 0x0000000000000100ul)] // Verify the largest denormals and the smallest normals: [InlineData(0x000fffffffffff00ul, 0x0010000000000100ul)] // Verify the largest normals: [InlineData(0x7fefffffffffff00ul, 0x7ff0000000000000ul)] public void TestParserDouble_SpecificRanges(ulong start, ulong end) { for (ulong i = start; i != end; i++) { TestRoundTripDouble(i); } } [Theory] // Verify all representable powers of two and nearby values: [InlineData(2, -1022, 1024)] // Verify all representable powers of ten and nearby values: [InlineData(10, -323, 309)] public void TestParserDouble_SpecificPowers(int b, int start, int end) { for (int i = start; i != end; i++) { double d = Math.Pow(b, i); ulong bits = (ulong)BitConverter.DoubleToInt64Bits(d); TestRoundTripDouble(bits - 1); TestRoundTripDouble(bits); TestRoundTripDouble(bits + 1); } } [Theory] [InlineData("0.0", 0x00000000)] // Verify small and large exactly representable integers: [InlineData("1", 0x3f800000)] [InlineData("2", 0x40000000)] [InlineData("3", 0x40400000)] [InlineData("4", 0x40800000)] [InlineData("5", 0x40A00000)] [InlineData("6", 0x40C00000)] [InlineData("7", 0x40E00000)] [InlineData("8", 0x41000000)] [InlineData("16777208", 0x4b7ffff8)] [InlineData("16777209", 0x4b7ffff9)] [InlineData("16777210", 0x4b7ffffa)] [InlineData("16777211", 0x4b7ffffb)] [InlineData("16777212", 0x4b7ffffc)] [InlineData("16777213", 0x4b7ffffd)] [InlineData("16777214", 0x4b7ffffe)] [InlineData("16777215", 0x4b7fffff)] // 2^24 - 1 // Verify the smallest and largest denormal values: [InlineData("1.4012984643248170e-45", 0x00000001)] [InlineData("2.8025969286496340e-45", 0x00000002)] [InlineData("4.2038953929744510e-45", 0x00000003)] [InlineData("5.6051938572992680e-45", 0x00000004)] [InlineData("7.0064923216240850e-45", 0x00000005)] [InlineData("8.4077907859489020e-45", 0x00000006)] [InlineData("9.8090892502737200e-45", 0x00000007)] [InlineData("1.1210387714598537e-44", 0x00000008)] [InlineData("1.2611686178923354e-44", 0x00000009)] [InlineData("1.4012984643248170e-44", 0x0000000a)] [InlineData("1.5414283107572988e-44", 0x0000000b)] [InlineData("1.6815581571897805e-44", 0x0000000c)] [InlineData("1.8216880036222622e-44", 0x0000000d)] [InlineData("1.9618178500547440e-44", 0x0000000e)] [InlineData("2.1019476964872256e-44", 0x0000000f)] [InlineData("1.1754921087447446e-38", 0x007ffff0)] [InlineData("1.1754922488745910e-38", 0x007ffff1)] [InlineData("1.1754923890044375e-38", 0x007ffff2)] [InlineData("1.1754925291342839e-38", 0x007ffff3)] [InlineData("1.1754926692641303e-38", 0x007ffff4)] [InlineData("1.1754928093939768e-38", 0x007ffff5)] [InlineData("1.1754929495238232e-38", 0x007ffff6)] [InlineData("1.1754930896536696e-38", 0x007ffff7)] [InlineData("1.1754932297835160e-38", 0x007ffff8)] [InlineData("1.1754933699133625e-38", 0x007ffff9)] [InlineData("1.1754935100432089e-38", 0x007ffffa)] [InlineData("1.1754936501730553e-38", 0x007ffffb)] [InlineData("1.1754937903029018e-38", 0x007ffffc)] [InlineData("1.1754939304327482e-38", 0x007ffffd)] [InlineData("1.1754940705625946e-38", 0x007ffffe)] [InlineData("1.1754942106924411e-38", 0x007fffff)] // This number is exactly representable and should not be rounded in any // mode: // 0.1111111111111111111111100 // ^ [InlineData("0.99999988079071044921875", 0x3f7ffffe)] // This number is below the halfway point between two representable values // so it should round down in nearest mode: // 0.11111111111111111111111001 // ^ [InlineData("0.99999989569187164306640625", 0x3f7ffffe)] // This number is exactly halfway between two representable values, so it // should round to even in nearest mode: // 0.1111111111111111111111101 // ^ [InlineData("0.9999999105930328369140625", 0x3f7ffffe)] // This number is above the halfway point between two representable values // so it should round up in nearest mode: // 0.11111111111111111111111011 // ^ [InlineData("0.99999992549419403076171875", 0x3f7fffff)] // This is the exact string for the largest denormal value and contains // the most significant digits of any single-precision floating-point value [InlineData("1.175494210692441075487029444849287348827052428745893333857174530571" + "588870475618904265502351336181163787841796875e-38", 0x007FFFFF)] [InlineData("0.000000000000000000000000000000000000000000000000000000000000000000" + "00000000000000000000000000000000000000000000000000000000000000000000" + "00000000000000000000000000000000000000000000000000000000000000000000" + "00000000000000000000000000000000000000000000000000000000000000000000" + "00000000000000000000000000000000000000000000000000000000000000000000" + "00000000000000000000000020000000000000000000000000000000000000002000" + "00000000000000000000000000000000000000000000000000000000000000000000" + "00000000000000000000000000000000000000000000000000000000000000000000" + "00000000000000000000000000000000000000000000000000000000000000000000" + "00000000000000000000000000000000000000000000000000000000000000000000" + "00000000000000000000000000000000000000000000000000000000000000000000" + "00000000000000000000000000000000000000000000000000000000000000000000" + "00000000000000000000000000000000000000000000000000000000000000000000" + "00000000000000000000000000000000000000000000000000000000000000000000" + "00000000000000000000000000000000000000000000000000000000000000000000" + "00000000000000000000000000000000000000000000000000000000000000000000" + "00000000000000000000000020000000000000000000000000000000000000000000" + "00000000000000000000000000000000000000000000000000000000000000000000" + "00000000000000000000000000000000000000000000000000000000000000000000" + "00000000000000000000000000000000000000000000000000000000000000000000" + "00000000000000000000000040000", 0x00000000)] [InlineData("00000000000000000000000000000000000000000000000000000000000000000000" + "00000000000000000000000000000000000000000000000000000000000000000000" + "00000000000000000000000000000000000000000000000000000000000000000000" + "00000000000000000000000000000000000000000000000000000000000000000000" + "00000000000000000000000000000000000000000000000000000000000000000000" + "00000000000000000000000020000000000000000000000000000000000000002000" + "00000000000000000000000000000000000000000000000000000000000000000000" + "00000000000000000000000000000000000000000000000000000000000000000000" + "00000000000000000000000000000000000000000000000000000000000000000000" + "00000000000000000000000000000000000000000000000000000000000000000000" + "00000000000000000000000000000000000000000000000000000000000000000000" + "00000000000000000000000000000000000000000000000000000000000000000000" + "00000000000000000000000000000000000000000000000000000000000000000000" + "00000000000000000000000000000000000000000000000000000000000000000000" + "00000000000000000000000000000000000000000000000000000000000000000000" + "00000000000000000000000000000000000000000000000000000000000000000000" + "00000000000000000000000020000000000000000000000000000000000000000000" + "00000000000000000000000000000000000000000000000000000000000000000000" + "00000000000000000000000000000000000000000000000000000000000000000000" + "00000000000000000000000000000000000000000000000000000000000000000000" + "00000000000000000000000040000", 0x7F800000)] public void TestParserSingle_SpecificValues(string s, uint expectedBits) { CheckOneSingle(s, expectedBits); } [Theory] [InlineData("-0", 0x80000000u)] [InlineData("-0.0", 0x80000000u)] [InlineData("-infinity", 0xFF800000u)] [InlineData("-iNfInItY", 0xFF800000u)] [InlineData("-INFINITY", 0xFF800000u)] [InlineData("infinity", 0x7F800000)] [InlineData("InFiNiTy", 0x7F800000)] [InlineData("INFINITY", 0x7F800000)] [InlineData("+infinity", 0x7F800000)] [InlineData("+InFiNiTy", 0x7F800000)] [InlineData("+INFINITY", 0x7F800000)] [InlineData("-nan", 0xFFC00000u)] [InlineData("-nAn", 0xFFC00000u)] [InlineData("-NAN", 0xFFC00000u)] [InlineData("nan", 0xFFC00000u)] [InlineData("Nan", 0xFFC00000u)] [InlineData("NAN", 0xFFC00000u)] [InlineData("+nan", 0xFFC00000u)] [InlineData("+NaN", 0xFFC00000u)] [InlineData("+NAN", 0xFFC00000u)] public void TestParserSingle_SpecialValues(string s, uint expectedBits) { CheckOneSingle(s, expectedBits); } [Theory] // Verify the smallest denormals: [InlineData(0x00000001, 0x00000100)] // Verify the largest denormals and the smallest normals: [InlineData(0x007fff00, 0x00800100)] // Verify the largest normals: [InlineData(0x7f7fff00, 0x7f800000)] public void TestParserSingle_SpecificRanges(uint start, uint end) { for (uint i = start; i != end; i++) { TestRoundTripSingle(i); } TestRoundTripSingle((float)int.MaxValue); TestRoundTripSingle((float)uint.MaxValue); } [Theory] // Verify all representable powers of two and nearby values: [InlineData(2, -1022, 1024)] // Verify all representable powers of ten and nearby values: [InlineData(10, -50, 41)] public void TestParserSingle_SpecificPowers(int b, int start, int end) { for (int i = start; i != end; ++i) { float f = MathF.Pow(b, i); uint bits = (uint)BitConverter.SingleToInt32Bits(f); TestRoundTripSingle(bits - 1); TestRoundTripSingle(bits); TestRoundTripSingle(bits + 1); } } private void CheckOneDouble(string s, ulong expectedBits) { CheckOneDouble(s, BitConverter.Int64BitsToDouble((long)(expectedBits))); } private void CheckOneDouble(string s, double expected) { if (!InvariantTryParseDouble(s, out double actual)) { // If we fail to parse, set actual to NaN to ensure the comparison below will fail actual = double.NaN; } Assert.True(actual.Equals(expected), $"Expected {InvariantToStringDouble(expected)}, Actual {InvariantToStringDouble(actual)}"); } private void CheckOneSingle(string s, uint expectedBits) { CheckOneSingle(s, BitConverter.Int32BitsToSingle((int)(expectedBits))); } private void CheckOneSingle(string s, float expected) { if (!InvariantTryParseSingle(s, out float actual)) { // If we fail to parse, set actual to NaN to ensure the comparison below will fail actual = float.NaN; } Assert.True(actual.Equals(expected), $"Expected {InvariantToStringSingle(expected)}, Actual {InvariantToStringSingle(actual)}"); } private void TestRoundTripDouble(double d) { string s = InvariantToStringDouble(d); CheckOneDouble(s, d); } private void TestRoundTripDouble(ulong bits) { double d = BitConverter.Int64BitsToDouble((long)(bits)); if (double.IsFinite(d)) { string s = InvariantToStringDouble(d); CheckOneDouble(s, bits); } } private void TestRoundTripSingle(float d) { string s = InvariantToStringSingle(d); CheckOneSingle(s, d); } private void TestRoundTripSingle(uint bits) { float d = BitConverter.Int32BitsToSingle((int)(bits)); if (float.IsFinite(d)) { string s = InvariantToStringSingle(d); CheckOneSingle(s, bits); } } } }
using System; using System.Collections.Generic; using System.IO; using System.Threading; using Mono.Unix; using Hyena.Data.Sqlite; using Banshee.Base; using Banshee.Configuration; using Banshee.ServiceStack; using Banshee.Database; using Banshee.Sources; using Banshee.Playlists.Formats; using Banshee.Collection; using Banshee.Collection.Database; namespace Banshee.Playlist { public class PlaylistImportCanceledException : ApplicationException { public PlaylistImportCanceledException (string message) : base (message) { } public PlaylistImportCanceledException () : base () { } } public static class PlaylistFileUtil { public static readonly SchemaEntry<string> DefaultExportFormat = new SchemaEntry<string> ( "player_window", "default_export_format", String.Empty, "Export Format", "The default playlist export format" ); private static PlaylistFormatDescription [] export_formats = new PlaylistFormatDescription [] { M3uPlaylistFormat.FormatDescription, PlsPlaylistFormat.FormatDescription, XspfPlaylistFormat.FormatDescription }; public static readonly string [] PlaylistExtensions = new string [] { M3uPlaylistFormat.FormatDescription.FileExtension, PlsPlaylistFormat.FormatDescription.FileExtension, XspfPlaylistFormat.FormatDescription.FileExtension }; public static PlaylistFormatDescription [] ExportFormats { get { return export_formats; } } public static bool IsSourceExportSupported (Source source) { bool supported = true; if (source == null || !(source is AbstractPlaylistSource)) { supported = false; } return supported; } public static PlaylistFormatDescription GetDefaultExportFormat () { PlaylistFormatDescription default_format = null; try { string exportFormat = DefaultExportFormat.Get (); PlaylistFormatDescription [] formats = PlaylistFileUtil.ExportFormats; foreach (PlaylistFormatDescription format in formats) { if (format.FileExtension.Equals (exportFormat)) { default_format = format; break; } } } catch { // Ignore errors, return our default if we encounter an error. } finally { if (default_format == null) { default_format = M3uPlaylistFormat.FormatDescription; } } return default_format; } public static void SetDefaultExportFormat (PlaylistFormatDescription format) { try { DefaultExportFormat.Set (format.FileExtension); } catch (Exception) { } } public static int GetFormatIndex (PlaylistFormatDescription [] formats, PlaylistFormatDescription playlist) { int default_export_index = -1; foreach (PlaylistFormatDescription format in formats) { default_export_index++; if (format.FileExtension.Equals (playlist.FileExtension)) { break; } } return default_export_index; } public static string [] ImportPlaylist (string playlistUri) { return ImportPlaylist (playlistUri, null); } public static string [] ImportPlaylist (string playlistUri, Uri baseUri) { IPlaylistFormat playlist = Load (playlistUri, baseUri); List<string> uris = new List<string> (); if (playlist != null) { foreach (Dictionary<string, object> element in playlist.Elements) { uris.Add (((Uri)element["uri"]).AbsoluteUri); } } return uris.ToArray (); } public static bool PathHasPlaylistExtension (string playlistUri) { if (System.IO.Path.HasExtension (playlistUri)) { string extension = System.IO.Path.GetExtension (playlistUri).ToLower (); foreach (PlaylistFormatDescription format in PlaylistFileUtil.ExportFormats) { if (extension.Equals ("." + format.FileExtension)) { return true; } } } return false; } public static IPlaylistFormat Load (string playlistUri, Uri baseUri) { PlaylistFormatDescription [] formats = PlaylistFileUtil.ExportFormats; // If the file has an extenstion, rearrange the format array so that the // appropriate format is tried first. if (System.IO.Path.HasExtension (playlistUri)) { string extension = System.IO.Path.GetExtension (playlistUri); extension = extension.ToLower (); int index = -1; foreach (PlaylistFormatDescription format in formats) { index++; if (extension.Equals ("." + format.FileExtension)) { break; } } if (index != -1 && index != 0 && index < formats.Length) { // Move to first position in array. PlaylistFormatDescription preferredFormat = formats[index]; formats[index] = formats[0]; formats[0] = preferredFormat; } } foreach (PlaylistFormatDescription format in formats) { try { IPlaylistFormat playlist = (IPlaylistFormat)Activator.CreateInstance (format.Type); playlist.BaseUri = baseUri; playlist.Load (Banshee.IO.File.OpenRead (new SafeUri (playlistUri)), true); return playlist; } catch (InvalidPlaylistException) { } } return null; } public static void ImportPlaylistToLibrary (string path) { ImportPlaylistToLibrary (path, ServiceManager.SourceManager.MusicLibrary, null); } public static void ImportPlaylistToLibrary (string path, PrimarySource source, DatabaseImportManager importer) { try { SafeUri uri = new SafeUri (path); PlaylistParser parser = new PlaylistParser (); string relative_dir = System.IO.Path.GetDirectoryName (uri.LocalPath); if (relative_dir[relative_dir.Length - 1] != System.IO.Path.DirectorySeparatorChar) { relative_dir = relative_dir + System.IO.Path.DirectorySeparatorChar; } parser.BaseUri = new Uri (relative_dir); if (parser.Parse (uri)) { List<string> uris = new List<string> (); foreach (Dictionary<string, object> element in parser.Elements) { uris.Add (((Uri)element["uri"]).LocalPath); } ImportPlaylistWorker worker = new ImportPlaylistWorker ( parser.Title, uris.ToArray (), source, importer); worker.Import (); } } catch (Exception e) { Hyena.Log.Exception (e); } } } public class ImportPlaylistWorker { private string [] uris; private string name; private PrimarySource source; private DatabaseImportManager importer; private bool finished; public ImportPlaylistWorker (string name, string [] uris, PrimarySource source, DatabaseImportManager importer) { this.name = name; this.uris = uris; this.source = source; this.importer = importer; } public void Import () { try { if (importer == null) { importer = new Banshee.Library.LibraryImportManager (); } finished = false; importer.Finished += CreatePlaylist; importer.Enqueue (uris); } catch (PlaylistImportCanceledException e) { Hyena.Log.Exception (e); } } private void CreatePlaylist (object o, EventArgs args) { if (finished) { return; } finished = true; try { PlaylistSource playlist = new PlaylistSource (name, source); playlist.Save (); source.AddChildSource (playlist); HyenaSqliteCommand insert_command = new HyenaSqliteCommand (String.Format ( @"INSERT INTO CorePlaylistEntries (PlaylistID, TrackID) VALUES ({0}, ?)", playlist.DbId)); //ServiceManager.DbConnection.BeginTransaction (); foreach (string uri in uris) { // FIXME: Does the following call work if the source is just a PrimarySource (not LibrarySource)? int track_id = source.GetTrackIdForUri (uri); if (track_id > 0) { ServiceManager.DbConnection.Execute (insert_command, track_id); } } playlist.Reload (); playlist.NotifyUser (); } catch (Exception e) { Hyena.Log.Exception (e); } } } }
using Moq; using Ocelot.Configuration; using Ocelot.Configuration.Creator; using Ocelot.Configuration.File; using Ocelot.Infrastructure; using Ocelot.Logging; using Ocelot.Responses; using Ocelot.UnitTests.Responder; using Shouldly; using System.Collections.Generic; using TestStack.BDDfy; using Xunit; namespace Ocelot.UnitTests.Configuration { public class HeaderFindAndReplaceCreatorTests { private HeaderFindAndReplaceCreator _creator; private FileReRoute _reRoute; private HeaderTransformations _result; private Mock<IPlaceholders> _placeholders; private Mock<IOcelotLoggerFactory> _factory; private Mock<IOcelotLogger> _logger; public HeaderFindAndReplaceCreatorTests() { _logger = new Mock<IOcelotLogger>(); _factory = new Mock<IOcelotLoggerFactory>(); _factory.Setup(x => x.CreateLogger<HeaderFindAndReplaceCreator>()).Returns(_logger.Object); _placeholders = new Mock<IPlaceholders>(); _creator = new HeaderFindAndReplaceCreator(_placeholders.Object, _factory.Object); } [Fact] public void should_create() { var reRoute = new FileReRoute { UpstreamHeaderTransform = new Dictionary<string, string> { {"Test", "Test, Chicken"}, {"Moop", "o, a"} }, DownstreamHeaderTransform = new Dictionary<string, string> { {"Pop", "West, East"}, {"Bop", "e, r"} } }; var upstream = new List<HeaderFindAndReplace> { new HeaderFindAndReplace("Test", "Test", "Chicken", 0), new HeaderFindAndReplace("Moop", "o", "a", 0) }; var downstream = new List<HeaderFindAndReplace> { new HeaderFindAndReplace("Pop", "West", "East", 0), new HeaderFindAndReplace("Bop", "e", "r", 0) }; this.Given(x => GivenTheReRoute(reRoute)) .When(x => WhenICreate()) .Then(x => ThenTheFollowingUpstreamIsReturned(upstream)) .Then(x => ThenTheFollowingDownstreamIsReturned(downstream)) .BDDfy(); } [Fact] public void should_create_with_add_headers_to_request() { const string key = "X-Forwarded-For"; const string value = "{RemoteIpAddress}"; var reRoute = new FileReRoute { UpstreamHeaderTransform = new Dictionary<string, string> { {key, value}, } }; var expected = new AddHeader(key, value); this.Given(x => GivenTheReRoute(reRoute)) .When(x => WhenICreate()) .Then(x => ThenTheFollowingAddHeaderToUpstreamIsReturned(expected)) .BDDfy(); } [Fact] public void should_use_base_url_placeholder() { var reRoute = new FileReRoute { DownstreamHeaderTransform = new Dictionary<string, string> { {"Location", "http://www.bbc.co.uk/, {BaseUrl}"}, } }; var downstream = new List<HeaderFindAndReplace> { new HeaderFindAndReplace("Location", "http://www.bbc.co.uk/", "http://ocelot.com/", 0), }; this.Given(x => GivenTheReRoute(reRoute)) .And(x => GivenTheBaseUrlIs("http://ocelot.com/")) .When(x => WhenICreate()) .Then(x => ThenTheFollowingDownstreamIsReturned(downstream)) .BDDfy(); } [Fact] public void should_log_errors_and_not_add_headers() { var reRoute = new FileReRoute { DownstreamHeaderTransform = new Dictionary<string, string> { {"Location", "http://www.bbc.co.uk/, {BaseUrl}"}, }, UpstreamHeaderTransform = new Dictionary<string, string> { {"Location", "http://www.bbc.co.uk/, {BaseUrl}"}, } }; var expected = new List<HeaderFindAndReplace> { }; this.Given(x => GivenTheReRoute(reRoute)) .And(x => GivenTheBaseUrlErrors()) .When(x => WhenICreate()) .Then(x => ThenTheFollowingDownstreamIsReturned(expected)) .And(x => ThenTheFollowingUpstreamIsReturned(expected)) .And(x => ThenTheLoggerIsCalledCorrectly("Unable to add DownstreamHeaderTransform Location: http://www.bbc.co.uk/, {BaseUrl}")) .And(x => ThenTheLoggerIsCalledCorrectly("Unable to add UpstreamHeaderTransform Location: http://www.bbc.co.uk/, {BaseUrl}")) .BDDfy(); } private void ThenTheLoggerIsCalledCorrectly(string message) { _logger.Verify(x => x.LogWarning(message), Times.Once); } [Fact] public void should_use_base_url_partial_placeholder() { var reRoute = new FileReRoute { DownstreamHeaderTransform = new Dictionary<string, string> { {"Location", "http://www.bbc.co.uk/pay, {BaseUrl}pay"}, } }; var downstream = new List<HeaderFindAndReplace> { new HeaderFindAndReplace("Location", "http://www.bbc.co.uk/pay", "http://ocelot.com/pay", 0), }; this.Given(x => GivenTheReRoute(reRoute)) .And(x => GivenTheBaseUrlIs("http://ocelot.com/")) .When(x => WhenICreate()) .Then(x => ThenTheFollowingDownstreamIsReturned(downstream)) .BDDfy(); } [Fact] public void should_add_trace_id_header() { var reRoute = new FileReRoute { DownstreamHeaderTransform = new Dictionary<string, string> { {"Trace-Id", "{TraceId}"}, } }; var expected = new AddHeader("Trace-Id", "{TraceId}"); this.Given(x => GivenTheReRoute(reRoute)) .And(x => GivenTheBaseUrlIs("http://ocelot.com/")) .When(x => WhenICreate()) .Then(x => ThenTheFollowingAddHeaderToDownstreamIsReturned(expected)) .BDDfy(); } [Fact] public void should_add_downstream_header_as_is_when_no_replacement_is_given() { var reRoute = new FileReRoute { DownstreamHeaderTransform = new Dictionary<string, string> { {"X-Custom-Header", "Value"}, } }; var expected = new AddHeader("X-Custom-Header", "Value"); this.Given(x => GivenTheReRoute(reRoute)) .And(x => WhenICreate()) .Then(x => x.ThenTheFollowingAddHeaderToDownstreamIsReturned(expected)) .BDDfy(); } [Fact] public void should_add_upstream_header_as_is_when_no_replacement_is_given() { var reRoute = new FileReRoute { UpstreamHeaderTransform = new Dictionary<string, string> { {"X-Custom-Header", "Value"}, } }; var expected = new AddHeader("X-Custom-Header", "Value"); this.Given(x => GivenTheReRoute(reRoute)) .And(x => WhenICreate()) .Then(x => x.ThenTheFollowingAddHeaderToUpstreamIsReturned(expected)) .BDDfy(); } private void GivenTheBaseUrlIs(string baseUrl) { _placeholders.Setup(x => x.Get(It.IsAny<string>())).Returns(new OkResponse<string>(baseUrl)); } private void GivenTheBaseUrlErrors() { _placeholders.Setup(x => x.Get(It.IsAny<string>())).Returns(new ErrorResponse<string>(new AnyError())); } private void ThenTheFollowingAddHeaderToDownstreamIsReturned(AddHeader addHeader) { _result.AddHeadersToDownstream[0].Key.ShouldBe(addHeader.Key); _result.AddHeadersToDownstream[0].Value.ShouldBe(addHeader.Value); } private void ThenTheFollowingAddHeaderToUpstreamIsReturned(AddHeader addHeader) { _result.AddHeadersToUpstream[0].Key.ShouldBe(addHeader.Key); _result.AddHeadersToUpstream[0].Value.ShouldBe(addHeader.Value); } private void ThenTheFollowingDownstreamIsReturned(List<HeaderFindAndReplace> downstream) { _result.Downstream.Count.ShouldBe(downstream.Count); for (int i = 0; i < _result.Downstream.Count; i++) { var result = _result.Downstream[i]; var expected = downstream[i]; result.Find.ShouldBe(expected.Find); result.Index.ShouldBe(expected.Index); result.Key.ShouldBe(expected.Key); result.Replace.ShouldBe(expected.Replace); } } private void GivenTheReRoute(FileReRoute reRoute) { _reRoute = reRoute; } private void WhenICreate() { _result = _creator.Create(_reRoute); } private void ThenTheFollowingUpstreamIsReturned(List<HeaderFindAndReplace> expecteds) { _result.Upstream.Count.ShouldBe(expecteds.Count); for (int i = 0; i < _result.Upstream.Count; i++) { var result = _result.Upstream[i]; var expected = expecteds[i]; result.Find.ShouldBe(expected.Find); result.Index.ShouldBe(expected.Index); result.Key.ShouldBe(expected.Key); result.Replace.ShouldBe(expected.Replace); } } } }
using Orleans.Serialization; namespace Orleans.CodeGenerator { using System; using System.CodeDom.Compiler; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using Microsoft.CodeAnalysis.CSharp.Syntax; using Orleans.Async; using Orleans.CodeGeneration; using Orleans.Runtime; using GrainInterfaceUtils = Orleans.CodeGeneration.GrainInterfaceUtils; using SF = Microsoft.CodeAnalysis.CSharp.SyntaxFactory; /// <summary> /// Implements a code generator using the Roslyn C# compiler. /// </summary> public class RoslynCodeGenerator : IRuntimeCodeGenerator, ISourceCodeGenerator, ICodeGeneratorCache { /// <summary> /// The compiled assemblies. /// </summary> private readonly ConcurrentDictionary<string, CachedAssembly> CompiledAssemblies = new ConcurrentDictionary<string, CachedAssembly>(); /// <summary> /// The logger. /// </summary> private static readonly Logger Logger = LogManager.GetLogger("CodeGenerator"); /// <summary> /// The serializer generation manager. /// </summary> private readonly SerializerGenerationManager serializerGenerationManager; /// <summary> /// Initializes a new instance of the <see cref="RoslynCodeGenerator"/> class. /// </summary> /// <param name="serializationManager">The serialization manager.</param> public RoslynCodeGenerator(SerializationManager serializationManager) { this.serializerGenerationManager = new SerializerGenerationManager(serializationManager); } /// <summary> /// Adds a pre-generated assembly. /// </summary> /// <param name="targetAssemblyName"> /// The name of the assembly the provided <paramref name="generatedAssembly"/> targets. /// </param> /// <param name="generatedAssembly"> /// The generated assembly. /// </param> public void AddGeneratedAssembly(string targetAssemblyName, GeneratedAssembly generatedAssembly) { CompiledAssemblies.TryAdd(targetAssemblyName, new CachedAssembly(generatedAssembly)); } /// <summary> /// Generates code for all loaded assemblies and loads the output. /// </summary> public IReadOnlyList<GeneratedAssembly> GenerateAndLoadForAllAssemblies() { return this.GenerateAndLoadForAssemblies(AppDomain.CurrentDomain.GetAssemblies()); } /// <summary> /// Generates and loads code for the specified inputs. /// </summary> /// <param name="inputs">The assemblies to generate code for.</param> public IReadOnlyList<GeneratedAssembly> GenerateAndLoadForAssemblies(params Assembly[] inputs) { if (inputs == null) { throw new ArgumentNullException(nameof(inputs)); } var results = new List<GeneratedAssembly>(); var timer = Stopwatch.StartNew(); var emitDebugSymbols = false; foreach (var input in inputs) { if (!emitDebugSymbols) { emitDebugSymbols |= RuntimeVersion.IsAssemblyDebugBuild(input); } RegisterGeneratedCodeTargets(input); var cached = TryLoadGeneratedAssemblyFromCache(input); if (cached != null) { results.Add(cached); } } var grainAssemblies = inputs.Where(ShouldGenerateCodeForAssembly).ToList(); if (grainAssemblies.Count == 0) { // Already up to date. return results; } try { // Generate code for newly loaded assemblies. var generatedSyntax = GenerateForAssemblies(grainAssemblies, true); CachedAssembly generatedAssembly; if (generatedSyntax.Syntax != null) { generatedAssembly = CompileAndLoad(generatedSyntax, emitDebugSymbols); if (generatedAssembly != null) { results.Add(generatedAssembly); } } else { generatedAssembly = new CachedAssembly { Loaded = true }; } foreach (var assembly in generatedSyntax.SourceAssemblies) { CompiledAssemblies.AddOrUpdate( assembly.GetName().FullName, generatedAssembly, (_, __) => generatedAssembly); } if (Logger.IsVerbose2) { Logger.Verbose2( ErrorCode.CodeGenCompilationSucceeded, "Generated code for {0} assemblies in {1}ms", generatedSyntax.SourceAssemblies.Count, timer.ElapsedMilliseconds); } return results; } catch (Exception exception) { var assemblyNames = string.Join("\n", grainAssemblies.Select(_ => _.GetName().FullName)); var message = $"Exception generating code for input assemblies:\n{assemblyNames}\nException: {LogFormatter.PrintException(exception)}"; Logger.Warn(ErrorCode.CodeGenCompilationFailed, message, exception); throw; } } /// <summary> /// Ensures that code generation has been run for the provided assembly. /// </summary> /// <param name="input"> /// The assembly to generate code for. /// </param> public GeneratedAssembly GenerateAndLoadForAssembly(Assembly input) { try { RegisterGeneratedCodeTargets(input); if (!ShouldGenerateCodeForAssembly(input)) { return TryLoadGeneratedAssemblyFromCache(input); } var timer = Stopwatch.StartNew(); var generated = GenerateForAssemblies(new List<Assembly> { input }, true); CachedAssembly generatedAssembly; if (generated.Syntax != null) { var emitDebugSymbols = RuntimeVersion.IsAssemblyDebugBuild(input); generatedAssembly = CompileAndLoad(generated, emitDebugSymbols); } else { generatedAssembly = new CachedAssembly { Loaded = true }; } foreach (var assembly in generated.SourceAssemblies) { CompiledAssemblies.AddOrUpdate( assembly.GetName().FullName, generatedAssembly, (_, __) => generatedAssembly); } if (Logger.IsVerbose2) { Logger.Verbose2( ErrorCode.CodeGenCompilationSucceeded, "Generated code for 1 assembly in {0}ms", timer.ElapsedMilliseconds); } return generatedAssembly; } catch (Exception exception) { var message = $"Exception generating code for input assembly {input.GetName().FullName}\nException: {LogFormatter.PrintException(exception)}"; Logger.Warn(ErrorCode.CodeGenCompilationFailed, message, exception); throw; } } /// <summary> /// Generates source code for the provided assembly. /// </summary> /// <param name="input"> /// The assembly to generate source for. /// </param> /// <returns> /// The generated source. /// </returns> public string GenerateSourceForAssembly(Assembly input) { RegisterGeneratedCodeTargets(input); if (!ShouldGenerateCodeForAssembly(input)) { return string.Empty; } var generated = GenerateForAssemblies(new List<Assembly> { input }, false); if (generated.Syntax == null) { return string.Empty; } return CodeGeneratorCommon.GenerateSourceCode(CodeGeneratorCommon.AddGeneratedCodeAttribute(generated)); } /// <summary> /// Returns the collection of generated assemblies as pairs of target assembly name to raw assembly bytes. /// </summary> /// <returns>The collection of generated assemblies.</returns> public IDictionary<string, GeneratedAssembly> GetGeneratedAssemblies() { return CompiledAssemblies.ToDictionary(_ => _.Key, _ => (GeneratedAssembly)_.Value); } /// <summary> /// Attempts to load a generated assembly from the cache. /// </summary> /// <param name="targetAssembly"> /// The target assembly which the cached counterpart is generated for. /// </param> private CachedAssembly TryLoadGeneratedAssemblyFromCache(Assembly targetAssembly) { CachedAssembly cached; if (!CompiledAssemblies.TryGetValue(targetAssembly.GetName().FullName, out cached) || cached.RawBytes == null || cached.Loaded) { return cached; } // Load the assembly and mark it as being loaded. cached.Assembly = LoadAssembly(cached); cached.Loaded = true; return cached; } /// <summary> /// Compiles the provided syntax tree, and loads and returns the result. /// </summary> /// <param name="generatedSyntax">The syntax tree.</param> /// <param name="emitDebugSymbols"> /// Whether or not to emit debug symbols for the generated assembly. /// </param> /// <returns>The compilation output.</returns> private static CachedAssembly CompileAndLoad(GeneratedSyntax generatedSyntax, bool emitDebugSymbols) { var generated = CodeGeneratorCommon.CompileAssembly(generatedSyntax, "OrleansCodeGen", emitDebugSymbols: emitDebugSymbols); var loadedAssembly = LoadAssembly(generated); return new CachedAssembly(generated) { Loaded = true, Assembly = loadedAssembly, }; } /// <summary> /// Loads the specified assembly. /// </summary> /// <param name="asm">The assembly to load.</param> private static Assembly LoadAssembly(GeneratedAssembly asm) { #if ORLEANS_BOOTSTRAP throw new NotImplementedException(); #elif NETSTANDARD Assembly result; result = Orleans.PlatformServices.PlatformAssemblyLoader.LoadFromBytes(asm.RawBytes); Orleans.AppDomain.CurrentDomain.AddAssembly(result); return result; #else return Assembly.Load(asm.RawBytes); #endif } /// <summary> /// Generates a syntax tree for the provided assemblies. /// </summary> /// <param name="assemblies">The assemblies to generate code for.</param> /// <param name="runtime">Whether or not runtime code generation is being performed.</param> /// <returns>The generated syntax tree.</returns> private GeneratedSyntax GenerateForAssemblies(List<Assembly> assemblies, bool runtime) { if (Logger.IsVerbose) { Logger.Verbose( "Generating code for assemblies: {0}", string.Join(", ", assemblies.Select(_ => _.FullName))); } Assembly targetAssembly; HashSet<Type> ignoredTypes; if (runtime) { // Ignore types which have already been accounted for. ignoredTypes = GetTypesWithGeneratedSupportClasses(); targetAssembly = null; } else { ignoredTypes = new HashSet<Type>(); targetAssembly = assemblies.FirstOrDefault(); } var members = new List<MemberDeclarationSyntax>(); // Include assemblies which are marked as included. var knownAssemblyAttributes = new Dictionary<Assembly, KnownAssemblyAttribute>(); var knownAssemblies = new HashSet<Assembly>(); foreach (var attribute in assemblies.SelectMany(asm => asm.GetCustomAttributes<KnownAssemblyAttribute>())) { knownAssemblyAttributes[attribute.Assembly] = attribute; knownAssemblies.Add(attribute.Assembly); } if (knownAssemblies.Count > 0) { knownAssemblies.UnionWith(assemblies); assemblies = knownAssemblies.ToList(); } // Get types from assemblies which reference Orleans and are not generated assemblies. var includedTypes = new HashSet<Type>(); for (var i = 0; i < assemblies.Count; i++) { var assembly = assemblies[i]; foreach (var attribute in assembly.GetCustomAttributes<ConsiderForCodeGenerationAttribute>()) { ConsiderType(attribute.Type, runtime, targetAssembly, includedTypes, considerForSerialization: true); if (attribute.ThrowOnFailure && !serializerGenerationManager.IsTypeRecorded(attribute.Type)) { throw new CodeGenerationException( $"Found {attribute.GetType().Name} for type {attribute.Type.GetParseableName()}, but code" + " could not be generated. Ensure that the type is accessible."); } } KnownAssemblyAttribute knownAssemblyAttribute; var considerAllTypesForSerialization = knownAssemblyAttributes.TryGetValue(assembly, out knownAssemblyAttribute) && knownAssemblyAttribute.TreatTypesAsSerializable; foreach (var type in TypeUtils.GetDefinedTypes(assembly, Logger)) { var considerForSerialization = considerAllTypesForSerialization || type.IsSerializable; ConsiderType(type.AsType(), runtime, targetAssembly, includedTypes, considerForSerialization); } } includedTypes.RemoveWhere(_ => ignoredTypes.Contains(_)); // Group the types by namespace and generate the required code in each namespace. foreach (var group in includedTypes.GroupBy(_ => CodeGeneratorCommon.GetGeneratedNamespace(_))) { var namespaceMembers = new List<MemberDeclarationSyntax>(); foreach (var type in group) { // The module containing the serializer. var module = runtime ? null : type.GetTypeInfo().Module; // Every type which is encountered must be considered for serialization. Action<Type> onEncounteredType = encounteredType => { // If a type was encountered which can be accessed, process it for serialization. serializerGenerationManager.RecordTypeToGenerate(encounteredType, module, targetAssembly); }; if (Logger.IsVerbose2) { Logger.Verbose2("Generating code for: {0}", type.GetParseableName()); } if (GrainInterfaceUtils.IsGrainInterface(type)) { if (Logger.IsVerbose2) { Logger.Verbose2( "Generating GrainReference and MethodInvoker for {0}", type.GetParseableName()); } GrainInterfaceUtils.ValidateInterfaceRules(type); namespaceMembers.Add(GrainReferenceGenerator.GenerateClass(type, onEncounteredType)); namespaceMembers.Add(GrainMethodInvokerGenerator.GenerateClass(type)); } // Generate serializers. var first = true; Type toGen; while (serializerGenerationManager.GetNextTypeToProcess(out toGen)) { if (!runtime) { if (first) { ConsoleText.WriteStatus("ClientGenerator - Generating serializer classes for types:"); first = false; } ConsoleText.WriteStatus( "\ttype " + toGen.FullName + " in namespace " + toGen.Namespace + " defined in Assembly " + toGen.GetTypeInfo().Assembly.GetName()); } if (Logger.IsVerbose2) { Logger.Verbose2( "Generating & Registering Serializer for Type {0}", toGen.GetParseableName()); } namespaceMembers.Add(SerializerGenerator.GenerateClass(toGen, onEncounteredType)); } } if (namespaceMembers.Count == 0) { if (Logger.IsVerbose) { Logger.Verbose2("Skipping namespace: {0}", group.Key); } continue; } members.Add( SF.NamespaceDeclaration(SF.ParseName(group.Key)) .AddUsings( TypeUtils.GetNamespaces(typeof(TaskUtility), typeof(GrainExtensions), typeof(IntrospectionExtensions)) .Select(_ => SF.UsingDirective(SF.ParseName(_))) .ToArray()) .AddMembers(namespaceMembers.ToArray())); } return new GeneratedSyntax { SourceAssemblies = assemblies, Syntax = members.Count > 0 ? SF.CompilationUnit().AddMembers(members.ToArray()) : null }; } private void ConsiderType( Type type, bool runtime, Assembly targetAssembly, ISet<Type> includedTypes, bool considerForSerialization = false) { // The module containing the serializer. var typeInfo = type.GetTypeInfo(); var module = runtime || !Equals(typeInfo.Assembly, targetAssembly) ? null : typeInfo.Module; // If a type was encountered which can be accessed and is marked as [Serializable], process it for serialization. if (considerForSerialization) { RecordType(type, module, targetAssembly, includedTypes); } // Consider generic arguments to base types and implemented interfaces for code generation. ConsiderGenericBaseTypeArguments(typeInfo, module, targetAssembly, includedTypes); ConsiderGenericInterfacesArguments(typeInfo, module, targetAssembly, includedTypes); // Include grain interface types. if (GrainInterfaceUtils.IsGrainInterface(type)) { // If code generation is being performed at runtime, the interface must be accessible to the generated code. if (!runtime || TypeUtilities.IsAccessibleFromAssembly(type, targetAssembly)) { if (Logger.IsVerbose2) Logger.Verbose2("Will generate code for: {0}", type.GetParseableName()); includedTypes.Add(type); } } } private void RecordType(Type type, Module module, Assembly targetAssembly, ISet<Type> includedTypes) { if (serializerGenerationManager.RecordTypeToGenerate(type, module, targetAssembly)) { includedTypes.Add(type); } } private void ConsiderGenericBaseTypeArguments( TypeInfo typeInfo, Module module, Assembly targetAssembly, ISet<Type> includedTypes) { if (typeInfo.BaseType == null) return; if (!typeInfo.BaseType.IsConstructedGenericType) return; foreach (var type in typeInfo.BaseType.GetGenericArguments()) { RecordType(type, module, targetAssembly, includedTypes); } } private void ConsiderGenericInterfacesArguments( TypeInfo typeInfo, Module module, Assembly targetAssembly, ISet<Type> includedTypes) { var interfaces = typeInfo.GetInterfaces().Where(x => x.IsConstructedGenericType); foreach (var type in interfaces.SelectMany(v => v.GetTypeInfo().GetGenericArguments())) { RecordType(type, module, targetAssembly, includedTypes); } } /// <summary> /// Get types which have corresponding generated classes. /// </summary> /// <returns>Types which have corresponding generated classes marked.</returns> private static HashSet<Type> GetTypesWithGeneratedSupportClasses() { // Get assemblies which contain generated code. var all = AppDomain.CurrentDomain.GetAssemblies() .Where(assemblies => assemblies.GetCustomAttribute<GeneratedCodeAttribute>() != null) .SelectMany(assembly => TypeUtils.GetDefinedTypes(assembly, Logger)); // Get all generated types in each assembly. var attributes = all.SelectMany(_ => _.GetCustomAttributes<GeneratedAttribute>()); var results = new HashSet<Type>(); foreach (var attribute in attributes) { if (attribute.TargetType != null) { results.Add(attribute.TargetType); } } return results; } /// <summary> /// Returns a value indicating whether or not code should be generated for the provided assembly. /// </summary> /// <param name="assembly">The assembly.</param> /// <returns>A value indicating whether or not code should be generated for the provided assembly.</returns> private bool ShouldGenerateCodeForAssembly(Assembly assembly) { return !assembly.IsDynamic && !CompiledAssemblies.ContainsKey(assembly.GetName().FullName) && TypeUtils.IsOrleansOrReferencesOrleans(assembly) && assembly.GetCustomAttribute<GeneratedCodeAttribute>() == null && assembly.GetCustomAttribute<SkipCodeGenerationAttribute>() == null; } /// <summary> /// Registers the input assembly with this class. /// </summary> /// <param name="input">The assembly to register.</param> private void RegisterGeneratedCodeTargets(Assembly input) { var targets = input.GetCustomAttributes<OrleansCodeGenerationTargetAttribute>(); foreach (var target in targets) { CompiledAssemblies.TryAdd(target.AssemblyName, new CachedAssembly { Loaded = true }); } } [Serializable] private class CachedAssembly : GeneratedAssembly { public CachedAssembly() { } public CachedAssembly(GeneratedAssembly generated) : base(generated) { } /// <summary> /// Gets or sets a value indicating whether or not the assembly has been loaded. /// </summary> public bool Loaded { get; set; } } } }
namespace java.net { [global::MonoJavaBridge.JavaClass()] public partial class ServerSocket : java.lang.Object { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; protected ServerSocket(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } private static global::MonoJavaBridge.MethodId _m0; public override global::java.lang.String toString() { return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.String>(this, global::java.net.ServerSocket.staticClass, "toString", "()Ljava/lang/String;", ref global::java.net.ServerSocket._m0) as java.lang.String; } private static global::MonoJavaBridge.MethodId _m1; public virtual void close() { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.net.ServerSocket.staticClass, "close", "()V", ref global::java.net.ServerSocket._m1); } private static global::MonoJavaBridge.MethodId _m2; public virtual global::java.net.Socket accept() { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.net.ServerSocket.staticClass, "accept", "()Ljava/net/Socket;", ref global::java.net.ServerSocket._m2) as java.net.Socket; } public new global::java.nio.channels.ServerSocketChannel Channel { get { return getChannel(); } } private static global::MonoJavaBridge.MethodId _m3; public virtual global::java.nio.channels.ServerSocketChannel getChannel() { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.net.ServerSocket.staticClass, "getChannel", "()Ljava/nio/channels/ServerSocketChannel;", ref global::java.net.ServerSocket._m3) as java.nio.channels.ServerSocketChannel; } private static global::MonoJavaBridge.MethodId _m4; public virtual bool isClosed() { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::java.net.ServerSocket.staticClass, "isClosed", "()Z", ref global::java.net.ServerSocket._m4); } private static global::MonoJavaBridge.MethodId _m5; public virtual void bind(java.net.SocketAddress arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.net.ServerSocket.staticClass, "bind", "(Ljava/net/SocketAddress;)V", ref global::java.net.ServerSocket._m5, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m6; public virtual void bind(java.net.SocketAddress arg0, int arg1) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.net.ServerSocket.staticClass, "bind", "(Ljava/net/SocketAddress;I)V", ref global::java.net.ServerSocket._m6, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } public new global::java.net.SocketAddress LocalSocketAddress { get { return getLocalSocketAddress(); } } private static global::MonoJavaBridge.MethodId _m7; public virtual global::java.net.SocketAddress getLocalSocketAddress() { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.net.ServerSocket.staticClass, "getLocalSocketAddress", "()Ljava/net/SocketAddress;", ref global::java.net.ServerSocket._m7) as java.net.SocketAddress; } private static global::MonoJavaBridge.MethodId _m8; public virtual void setReceiveBufferSize(int arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.net.ServerSocket.staticClass, "setReceiveBufferSize", "(I)V", ref global::java.net.ServerSocket._m8, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } public new int ReceiveBufferSize { get { return getReceiveBufferSize(); } set { setReceiveBufferSize(value); } } private static global::MonoJavaBridge.MethodId _m9; public virtual int getReceiveBufferSize() { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::java.net.ServerSocket.staticClass, "getReceiveBufferSize", "()I", ref global::java.net.ServerSocket._m9); } private static global::MonoJavaBridge.MethodId _m10; public virtual void setSoTimeout(int arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.net.ServerSocket.staticClass, "setSoTimeout", "(I)V", ref global::java.net.ServerSocket._m10, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } public new int SoTimeout { get { return getSoTimeout(); } set { setSoTimeout(value); } } private static global::MonoJavaBridge.MethodId _m11; public virtual int getSoTimeout() { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::java.net.ServerSocket.staticClass, "getSoTimeout", "()I", ref global::java.net.ServerSocket._m11); } private static global::MonoJavaBridge.MethodId _m12; public virtual bool isBound() { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::java.net.ServerSocket.staticClass, "isBound", "()Z", ref global::java.net.ServerSocket._m12); } public new global::java.net.InetAddress InetAddress { get { return getInetAddress(); } } private static global::MonoJavaBridge.MethodId _m13; public virtual global::java.net.InetAddress getInetAddress() { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.net.ServerSocket.staticClass, "getInetAddress", "()Ljava/net/InetAddress;", ref global::java.net.ServerSocket._m13) as java.net.InetAddress; } public new int LocalPort { get { return getLocalPort(); } } private static global::MonoJavaBridge.MethodId _m14; public virtual int getLocalPort() { return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::java.net.ServerSocket.staticClass, "getLocalPort", "()I", ref global::java.net.ServerSocket._m14); } private static global::MonoJavaBridge.MethodId _m15; public virtual void setReuseAddress(bool arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.net.ServerSocket.staticClass, "setReuseAddress", "(Z)V", ref global::java.net.ServerSocket._m15, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } public new bool ReuseAddress { get { return getReuseAddress(); } set { setReuseAddress(value); } } private static global::MonoJavaBridge.MethodId _m16; public virtual bool getReuseAddress() { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::java.net.ServerSocket.staticClass, "getReuseAddress", "()Z", ref global::java.net.ServerSocket._m16); } private static global::MonoJavaBridge.MethodId _m17; public virtual void setPerformancePreferences(int arg0, int arg1, int arg2) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.net.ServerSocket.staticClass, "setPerformancePreferences", "(III)V", ref global::java.net.ServerSocket._m17, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } private static global::MonoJavaBridge.MethodId _m18; protected virtual void implAccept(java.net.Socket arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.net.ServerSocket.staticClass, "implAccept", "(Ljava/net/Socket;)V", ref global::java.net.ServerSocket._m18, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } public static global::java.net.SocketImplFactory SocketFactory { set { setSocketFactory(value); } } private static global::MonoJavaBridge.MethodId _m19; public static void setSocketFactory(java.net.SocketImplFactory arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.net.ServerSocket._m19.native == global::System.IntPtr.Zero) global::java.net.ServerSocket._m19 = @__env.GetStaticMethodIDNoThrow(global::java.net.ServerSocket.staticClass, "setSocketFactory", "(Ljava/net/SocketImplFactory;)V"); @__env.CallStaticVoidMethod(java.net.ServerSocket.staticClass, global::java.net.ServerSocket._m19, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m20; public ServerSocket() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.net.ServerSocket._m20.native == global::System.IntPtr.Zero) global::java.net.ServerSocket._m20 = @__env.GetMethodIDNoThrow(global::java.net.ServerSocket.staticClass, "<init>", "()V"); global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(java.net.ServerSocket.staticClass, global::java.net.ServerSocket._m20); Init(@__env, handle); } private static global::MonoJavaBridge.MethodId _m21; public ServerSocket(int arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.net.ServerSocket._m21.native == global::System.IntPtr.Zero) global::java.net.ServerSocket._m21 = @__env.GetMethodIDNoThrow(global::java.net.ServerSocket.staticClass, "<init>", "(I)V"); global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(java.net.ServerSocket.staticClass, global::java.net.ServerSocket._m21, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); Init(@__env, handle); } private static global::MonoJavaBridge.MethodId _m22; public ServerSocket(int arg0, int arg1) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.net.ServerSocket._m22.native == global::System.IntPtr.Zero) global::java.net.ServerSocket._m22 = @__env.GetMethodIDNoThrow(global::java.net.ServerSocket.staticClass, "<init>", "(II)V"); global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(java.net.ServerSocket.staticClass, global::java.net.ServerSocket._m22, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); Init(@__env, handle); } private static global::MonoJavaBridge.MethodId _m23; public ServerSocket(int arg0, int arg1, java.net.InetAddress arg2) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.net.ServerSocket._m23.native == global::System.IntPtr.Zero) global::java.net.ServerSocket._m23 = @__env.GetMethodIDNoThrow(global::java.net.ServerSocket.staticClass, "<init>", "(IILjava/net/InetAddress;)V"); global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(java.net.ServerSocket.staticClass, global::java.net.ServerSocket._m23, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); Init(@__env, handle); } static ServerSocket() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::java.net.ServerSocket.staticClass = @__env.NewGlobalRef(@__env.FindClass("java/net/ServerSocket")); } } }